{"id": 45749, "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", "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": 45750, "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++": "#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": 45751, "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++": "#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": 45752, "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++": "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": 45753, "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++": "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": 45754, "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++": "#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": 45755, "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++": "#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": 45756, "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++": "#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": 45757, "name": "Euler's constant 0.5772...", "C": "\n#include <math.h>\n#include <stdio.h>\n\n#define eps 1e-6\n\nint main(void) {\ndouble a, b, h, n2, r, u, v;\nint k, k2, m, n;\n\nprintf(\"From the definition, err. 3e-10\\n\");\n\nn = 400;\n\nh = 1;\nfor (k = 2; k <= n; k++) {\n   h += 1.0 / k;\n}\n\na = log(n +.5 + 1.0 / (24*n));\n\nprintf(\"Hn    %.16f\\n\", h);\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", h - a, n);\n\n\nprintf(\"Sweeney, 1963, err. idem\\n\");\n\nn = 21;\n\ndouble s[] = {0, n};\nr = n;\nk = 1;\ndo {\n   k += 1;\n   r *= (double) n / k;\n   s[k & 1] += r / k;\n} while (r > eps);\n\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", s[1] - s[0] - log(n), k);\n\n\nprintf(\"Bailey, 1988\\n\");\n\nn = 5;\n\na = 1;\nh = 1;\nn2 = pow(2,n);\nr = 1;\nk = 1;\ndo {\n   k += 1;\n   r *= n2 / k;\n   h += 1.0 / k;\n   b = a; a += r * h;\n} while (fabs(b - a) > eps);\na *= n2 / exp(n2);\n\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", a - n * log(2), k);\n\n\nprintf(\"Brent-McMillan, 1980\\n\");\n\nn = 13;\n\na = -log(n);\nb = 1;\nu = a;\nv = b;\nn2 = n * n;\nk2 = 0;\nk = 0;\ndo {\n   k2 += 2*k + 1;\n   k += 1;\n   a *= n2 / k;\n   b *= n2 / k2;\n   a = (a + b) / k;\n   u += a;\n   v += b;\n} while (fabs(a) > eps);\n\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", u / v, k);\n\n\nprintf(\"How Euler did it in 1735\\n\");\n\ndouble B2[] = {1.0,1.0/6,-1.0/30,1.0/42,-1.0/30,\\\n 5.0/66,-691.0/2730,7.0/6,-3617.0/510,43867.0/798};\nm = 7;\nif (m > 9) return(0);\n\nn = 10;\n\n\nh = 1;\nfor (k = 2; k <= n; k++) {\n   h += 1.0 / k;\n}\nprintf(\"Hn    %.16f\\n\", h);\n\nh -= log(n);\nprintf(\"  -ln %.16f\\n\", h);\n\n\na = -1.0 / (2*n);\nn2 = n * n;\nr = 1;\nfor (k = 1; k <= m; k++) {\n   r *= n2;\n   a += B2[k] / (2*k * r);\n}\n\nprintf(\"err  %.16f\\ngamma %.16f\\nk = %d\", a, h + a, n + m);\n\nprintf(\"\\n\\nC  =  0.57721566490153286...\\n\");\n}\n", "C++": "#include <array>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\ndouble ByVaccaSeries(int numTerms)\n{\n    \n    \n    \n    \n    \n    \n    \n    double gamma = 0;\n    size_t next = 4;\n    \n    for(double numerator = 1; numerator < numTerms; ++numerator)\n    {\n        double delta = 0;\n        for(size_t denominator = next/2; denominator < next; denominator+=2)\n        {\n            \n            delta += 1.0/denominator - 1.0/(denominator + 1);\n        }\n\n        gamma += numerator * delta;\n        next *= 2;\n    }\n    return gamma;\n}\n\n\ndouble ByEulersMethod()\n{\n    \n    const std::array<double, 8> B2 {1.0, 1.0/6, -1.0/30, 1.0/42, -1.0/30,\n        5.0/66, -691.0/2730, 7.0/6};\n    \n    const int n = 10;\n\n    \n    const double h = [] \n    {\n        double sum = 1;\n        for (int k = 2; k <= n; k++) { sum += 1.0 / k; }\n        return sum - log(n);\n    }();\n\n    \n    double a = -1.0 / (2*n);\n    double r = 1;\n    for (int k = 1; k < ssize(B2); k++)\n    {\n        r *= n * n;\n        a += B2[k] / (2*k * r);\n    }\n\n    return h + a;\n}\n\n\nint main()\n{\n    std::cout << std::setprecision(16) << \"Vacca series:  \" << ByVaccaSeries(32);\n    std::cout << std::setprecision(16) << \"\\nEulers method: \" << ByEulersMethod();\n}\n"}
{"id": 45758, "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++": "#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": 45759, "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", "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": 45760, "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", "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": 45761, "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", "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": 45762, "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", "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": 45763, "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", "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": 45764, "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", "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": 45765, "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++": "#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": 45766, "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++": "#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": 45767, "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++": "#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": 45768, "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", "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": 45769, "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", "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": 45770, "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", "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": 45771, "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", "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": 45772, "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", "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": 45773, "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", "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": 45774, "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", "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": 45775, "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", "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": 45776, "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", "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": 45777, "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", "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": 45778, "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", "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": 45779, "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", "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": 45780, "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", "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": 45781, "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", "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": 45782, "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", "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": 45783, "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", "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": 45784, "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", "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": 45785, "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", "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": 45786, "name": "String comparison", "C": "\nif (strcmp(a,b)) action_on_equality();\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": 45787, "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", "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": 45788, "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", "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": 45789, "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", "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": 45790, "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", "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": 45791, "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", "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": 45792, "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", "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": 45793, "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", "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": 45794, "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", "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": 45795, "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", "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": 45796, "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", "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": 45797, "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", "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": 45798, "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", "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": 45799, "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", "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": 45800, "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", "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": 45801, "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", "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": 45802, "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", "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": 45803, "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", "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": 45804, "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", "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": 45805, "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", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 45806, "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", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\n}\n"}
{"id": 45807, "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", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n"}
{"id": 45808, "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", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 1);\n    return 0;\n}\n"}
{"id": 45809, "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", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 45810, "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", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 45811, "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", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\n\n"}
{"id": 45812, "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", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n"}
{"id": 45813, "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", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 45814, "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", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 45815, "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", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\n}\n"}
{"id": 45816, "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", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 45817, "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", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 45818, "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", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 45819, "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", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 45820, "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", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n"}
{"id": 45821, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 45822, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 45823, "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", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 45824, "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", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 45825, "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", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 45826, "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", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 45827, "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", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 45828, "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", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 45829, "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", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\n}\n"}
{"id": 45830, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 45831, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 45832, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 45833, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 45834, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 45835, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 45836, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 45837, "name": "Checkpoint synchronization", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n"}
{"id": 45838, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n"}
{"id": 45839, "name": "Record sound", "C": "#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <fcntl.h>\n\nvoid * record(size_t bytes)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_RDONLY))) return 0;\n\tvoid *a = malloc(bytes);\n\tread(fd, a, bytes);\n\tclose(fd);\n\treturn a;\n}\n\nint play(void *buf, size_t len)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_WRONLY))) return 0;\n\twrite(fd, buf, len);\n\tclose(fd);\n\treturn 1;\n}\n\nint main()\n{\n\tvoid *p = record(65536);\n\tplay(p, 65536);\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\nusing namespace std;\n\nclass recorder\n{\npublic:\n    void start()\n    {\n\tpaused = rec = false; action = \"IDLE\";\n\twhile( true )\n\t{\n\t    cout << endl << \"==\" << action << \"==\" << endl << endl;\n\t    cout << \"1) Record\" << endl << \"2) Play\" << endl << \"3) Pause\" << endl << \"4) Stop\" << endl << \"5) Quit\" << endl;\n\t    char c; cin >> c;\n\t    if( c > '0' && c < '6' )\n\t    {\n\t\tswitch( c )\n\t\t{\n\t\t    case '1': record(); break;\n\t\t    case '2': play();   break;\n\t\t    case '3': pause();  break;\n\t\t    case '4': stop();   break;\n\t\t    case '5': stop();   return;\n\t\t}\n\t    }\n\t}\n    }\nprivate:\n    void record()\n    {\n\tif( mciExecute( \"open new type waveaudio alias my_sound\") )\n\t{ \n\t    mciExecute( \"record my_sound\" ); \n\t    action = \"RECORDING\"; rec = true; \n\t}\n    }\n    void play()\n    {\n\tif( paused )\n\t    mciExecute( \"play my_sound\" );\n\telse\n\t    if( mciExecute( \"open tmp.wav alias my_sound\" ) )\n\t\tmciExecute( \"play my_sound\" );\n\n\taction = \"PLAYING\";\n\tpaused = false;\n    }\n    void pause()\n    {\n\tif( rec ) return;\n\tmciExecute( \"pause my_sound\" );\n\tpaused = true; action = \"PAUSED\";\n    }\n    void stop()\n    {\n\tif( rec )\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"save my_sound tmp.wav\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\"; rec = false;\n\t}\n\telse\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\";\n\t}\n    }\n    bool mciExecute( string cmd )\n    {\n\tif( mciSendString( cmd.c_str(), NULL, 0, NULL ) )\n\t{\n\t    cout << \"Can't do this: \" << cmd << endl;\n\t    return false;\n\t}\n\treturn true;\n    }\n\n    bool paused, rec;\n    string action;\n};\n\nint main( int argc, char* argv[] )\n{\n    recorder r; r.start();\n    return 0;\n}\n"}
{"id": 45840, "name": "SHA-256 Merkle tree", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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": 45841, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 45842, "name": "User input_Graphical", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n"}
{"id": 45843, "name": "Sierpinski arrowhead curve", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45844, "name": "Text processing_1", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n"}
{"id": 45845, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 45846, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 45847, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 45848, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 45849, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 45850, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 45851, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 45852, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 45853, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 45854, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 45855, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "C++": "#include <stack>\n"}
{"id": 45856, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 45857, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 45858, "name": "Random number generator (included)", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <random>\n \nint main()\n{\n    std::random_device rd;\n    std::uniform_int_distribution<int> dist(1, 10);\n    std::mt19937 mt(rd());\n    \n    std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n    std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}\n"}
{"id": 45859, "name": "Random number generator (included)", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <random>\n \nint main()\n{\n    std::random_device rd;\n    std::uniform_int_distribution<int> dist(1, 10);\n    std::mt19937 mt(rd());\n    \n    std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n    std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}\n"}
{"id": 45860, "name": "Random number generator (included)", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <random>\n \nint main()\n{\n    std::random_device rd;\n    std::uniform_int_distribution<int> dist(1, 10);\n    std::mt19937 mt(rd());\n    \n    std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n    std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}\n"}
{"id": 45861, "name": "Fractran", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n"}
{"id": 45862, "name": "Sorting algorithms_Stooge sort", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n"}
{"id": 45863, "name": "Galton box animation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\n", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n"}
{"id": 45864, "name": "Sorting Algorithms_Circle Sort", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\n"}
{"id": 45865, "name": "Kronecker product based fractals", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\n"}
{"id": 45866, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 45867, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 45868, "name": "Circular primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 45869, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n"}
{"id": 45870, "name": "Sorting algorithms_Radix sort", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n"}
{"id": 45871, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n"}
{"id": 45872, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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 <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 45873, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 45874, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 45875, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 45876, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 45877, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 45878, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 45879, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 45880, "name": "Singleton", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 45881, "name": "Safe addition", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n"}
{"id": 45882, "name": "Case-sensitivity of identifiers", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n"}
{"id": 45883, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 45884, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 45885, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 45886, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 45887, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 45888, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 45889, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 45890, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 45891, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 45892, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 45893, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 45894, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 45895, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 45896, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 45897, "name": "Non-continuous subsequences", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 45898, "name": "Fibonacci word_fractal", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\n"}
{"id": 45899, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n"}
{"id": 45900, "name": "15 puzzle solver", "C": " \n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\ntypedef unsigned char u8t;\ntypedef unsigned short u16t;\nenum { NR=4, NC=4, NCELLS = NR*NC };\nenum { UP, DOWN, LEFT, RIGHT, NDIRS };\nenum { OK = 1<<8, XX = 1<<9, FOUND = 1<<10, zz=0x80 };\nenum { MAX_INT=0x7E, MAX_NODES=(16*65536)*90};\nenum { BIT_HDR=1<<0, BIT_GRID=1<<1, BIT_OTHER=1<<2 };\nenum { PHASE1,PHASE2 };  \n\ntypedef struct { u16t dn; u16t hn; }HSORT_T;\n\ntypedef struct {\n   u8t data[NCELLS]; unsigned id; unsigned src;\n   u8t h; u8t g; u8t udlr;\n}NODE_T;  \n\nNODE_T goal44={\n   {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,0},0,0,0,0,0};\nNODE_T work; \n\nNODE_T G34={ \n {13,9,5,4, 15,6,1,8, 0,10,2,11, 14,3,7,12},0,0,0,0,0};\n\nNODE_T G52={ \n   {15,13,9,5, 14,6,1,4,  10,12,0,8, 3,7,11,2},0,0,0,0,0};\n\nNODE_T G99={ \n   {15,14,1,6, 9,11,4,12, 0,10,7,3, 13,8,5,2},0,0,0,0,0};\n\nstruct {\n   unsigned nodes;\n   unsigned gfound;\n   unsigned root_visits;\n   unsigned verbose;\n   unsigned locks;\n   unsigned phase;\n}my;\n\nu16t  HybridIDA_star(NODE_T *pNode);\nu16t  make_node(NODE_T *pNode, NODE_T *pNew, u8t udlr );\nu16t  search(NODE_T *pNode, u16t bound);\nu16t  taxi_dist( NODE_T *pNode);\nu16t  tile_home( NODE_T *p44);\nvoid  print_node( NODE_T *pN, const char *pMsg, short force );\nu16t  goal_found(NODE_T *pNode);\nchar  udlr_to_char( char udlr );\nvoid  idx_to_rc( u16t idx, u16t *row, u16t *col );\nvoid  sort_nodes(HSORT_T *p);\n\nint main( )\n{\n   my.verbose = 0;\t\t\n   \n   \n   \n   memcpy(&work,  &G99, sizeof(NODE_T));  \n   if(1){   \n      printf(\"Phase1: IDA* search for 1234 permutation..\\n\");\n      my.phase = PHASE1;\n      (void) HybridIDA_star(&work);\n   }\n   printf(\"Phase2: IDA* search phase1 seed..\\n\");\n   my.phase = PHASE2;\n   (void)HybridIDA_star(&work);\n   return 0;\n}\n\n\nu16t HybridIDA_star(NODE_T *pN){\n   my.nodes = 1;\n   my.gfound = 0;\n   my.root_visits = 0;\n   pN->udlr = NDIRS;\n   pN->g = 0;\n   pN->h = taxi_dist(pN);\n   pN->id = my.nodes;\n   pN->src = 0;\n   const char *pr = {\"Start\"}; \n   print_node( pN,pr,1 );\n   u16t depth = pN->h;\n   while(1){\n      depth = search(pN,depth);\n      if( depth & FOUND){\n         return FOUND;  \n      }\n      if( depth & 0xFF00 ){\n\t printf(\"..error %x\\n\",depth);\n\t return XX;\n      }\n      my.root_visits++;\n      printf(\"[root visits: %u, depth %u]\\n\",my.root_visits,depth);\n   }\n   return 0;\n}\n\n\nu16t search(NODE_T *pN, u16t bound){ \n   if(bound & 0xff00){ return bound; }\n   u16t f = pN->g + pN->h;\n   if( f > bound){ return f; }\n   if(goal_found(pN)){\n      my.gfound = pN->g;\n      memcpy(&work,pN,sizeof(NODE_T));\n      printf(\"total nodes=%d, g=%u \\n\", my.nodes, my.gfound);\n      const char *pr = {\"Found..\"}; \n      print_node( &work,pr,1 );\n      return FOUND;\n   }\n   NODE_T news;\n   \n   \n   \n   HSORT_T hlist[NDIRS];\n   for( short i=0; i<NDIRS; i++ ){\n      u16t rv = make_node(pN,&news, i );\n      hlist[i].dn = i;\n      if( rv & OK ){\n\t hlist[i].hn = news.h;\n\t continue;\n      }\n      hlist[i].hn = XX;\n   }\n   sort_nodes(&hlist[0]);\n   \n   u16t temp, min = MAX_INT; \n   for( short i=0; i<NDIRS; i++ ){\n      if( hlist[i].hn > 0xff ) continue;\n      temp = make_node(pN,&news, hlist[i].dn );\n      if( temp & XX ) return XX;\n      if( temp & OK ){\n\t news.id = my.nodes++;\n\t print_node(&news,\" succ\",0 );\n\t temp = search(&news, bound);\n\t if(temp & 0xff00){  return temp;}\n\t if(temp < min){ min = temp; }\n      }\n   }\n   return min;\n}\n\n\nvoid sort_nodes(HSORT_T *p){\n   for( short s=0; s<NDIRS-1; s++ ){\n      HSORT_T tmp = p[0];\n      if( p[1].hn < p[0].hn ){tmp=p[0]; p[0]=p[1]; p[1]=tmp; }\n      if( p[2].hn < p[1].hn ){tmp=p[1]; p[1]=p[2]; p[2]=tmp; }\n      if( p[3].hn < p[2].hn ){tmp=p[2]; p[2]=p[3]; p[3]=tmp; }\n   }\n}\n\n\nu16t tile_home(NODE_T *pN ){\n   for( short i=0; i<NCELLS; i++ ){\n      if( pN->data[i] == 0 ) return i;\n   }\n   return XX;\n}\n\n\nvoid print_node( NODE_T *pN, const char *pMsg, short force ){\n   const int tp1 = 0;\n   if( my.verbose & BIT_HDR || force || tp1){\n      char ch = udlr_to_char(pN->udlr);\n      printf(\"id:%u src:%u; h=%d, g=%u, udlr=%c, %s\\n\",\n\t     pN->id, pN->src, pN->h, pN->g, ch, pMsg);\n   }\n   if(my.verbose & BIT_GRID || force || tp1){\n      for(u16t i=0; i<NR; i++ ){\n\t for( u16t j=0; j<NC; j++ ){\n\t    printf(\"%3d\",pN->data[i*NR+j]);\n\t }\n\t printf(\"\\n\");\n      }\n      printf(\"\\n\");\n   }\n   \n}\n\n\nu16t goal_found(NODE_T *pN) {\n   if(my.phase==PHASE1){\n      short tags = 0;\n      for( short i=0; i<(NC); i++ ){\n\t if( pN->data[i] == i+1 ) tags++;\n      }\n      if( tags==4 ) return 1;  \n   }\n   \n   for( short i=0; i<(NR*NC); i++ ){\n      if( pN->data[i] != goal44.data[i] ) return 0;\n   }\n   return 1;\n}\n\n\nchar udlr_to_char( char udlr ){\n   char ch = '?';\n   switch(udlr){\n   case UP:    ch = 'U'; break;\n   case DOWN:  ch = 'D'; break;\n   case LEFT:  ch = 'L'; break;\n   case RIGHT: ch = 'R'; break;\n   default: break;\n   }\n   return ch;\n}\n\n\nvoid idx_to_rc( u16t idx, u16t *row, u16t *col ){\n   *row = idx/NR; *col = abs( idx - (*row * NR));\n}\n\n\n\nu16t make_node(NODE_T *pSrc, NODE_T *pNew, u8t udlr ){\n   u16t row,col,home_idx,idx2;\n   if(udlr>=NDIRS||udlr<0 ){ printf(\"invalid udlr %u\\n\",udlr); return XX; }\n   if(my.nodes > MAX_NODES ){ printf(\"excessive nodes %u\\n\",my.nodes);\n      return XX; }\n   memcpy(pNew,pSrc,sizeof(NODE_T));\n   home_idx = tile_home(pNew);\n   idx_to_rc(home_idx, &row, &col );\n\n   if( udlr == LEFT)  { if( col < 1 ) return 0; col--; }\n   if( udlr == RIGHT ){ if( col >= (NC-1) ) return 0; col++; }\n   if( udlr == DOWN ) { if(row >= (NR-1)) return 0; row++; }\n   if( udlr == UP ){\t if(row < 1) return 0; row--; }\n   idx2 = row * NR + col;\n   if( idx2 < NCELLS ){\n      u8t *p = &pNew->data[0];\n      p[home_idx] = p[idx2];\n      p[idx2]     = 0; \n      pNew->src   = pSrc->id;\n      pNew->g     = pSrc->g + 1;\n      pNew->h     = taxi_dist(pNew);\n      pNew->udlr  = udlr; \n      return OK;\n   }\n   return 0;\n}\n\n\nu16t taxi_dist( NODE_T *pN){\n   u16t tile,sum = 0, r1,c1,r2,c2;\n   u8t *p44 = &pN->data[0];\n   for( short i=0; i<(NR*NC); i++ ){\n      tile = p44[i];\n      if( tile==0 ) continue;\n      idx_to_rc(i, &r2, &c2 );\n      idx_to_rc(tile-1, &r1, &c1 );\n      sum += abs(r1-r2) + abs(c1-c2);\n   }\n   }\n   return sum;\n}\n", "C++": "\nclass fifteenSolver{\n  const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};\n  int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};\n  unsigned long N2[100]{};\n  const bool fY(){\n    if (N4[n]<_n) return fN();\n    if (N2[n]==0x123456789abcdef0) {std::cout<<\"Solution found in \"<<n<<\" moves :\"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};\n    if (N4[n]==_n) return fN(); else return false;\n  }\n  const bool                     fN(){\n    if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}\n    return false;\n  }\n  void fI(){\n    const int           g = (11-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);\n  } \n  void fG(){\n    const int           g = (19-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);\n  } \n  void fE(){\n    const int           g = (14-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);\n  } \n  void fL(){\n    const int           g = (16-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);\n  }\npublic:\n  fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}\n  void Solve(){for(;not fY();++_n);}\n};\n"}
{"id": 45901, "name": "Roots of unity", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 45902, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 45903, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 45904, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 45905, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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 <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 45906, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 45907, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 45908, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 45909, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 45910, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 45911, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n"}
{"id": 45912, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n"}
{"id": 45913, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 45914, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 45915, "name": "Carmichael 3 strong pseudoprimes", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n"}
{"id": 45916, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n"}
{"id": 45917, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n"}
{"id": 45918, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 45919, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 45920, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 45921, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 45922, "name": "Conjugate transpose", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n"}
{"id": 45923, "name": "Conjugate transpose", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n"}
{"id": 45924, "name": "Jacobsthal numbers", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 45925, "name": "Jacobsthal numbers", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 45926, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n"}
{"id": 45927, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 45928, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 45929, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 45930, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 45931, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 45932, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n"}
{"id": 45933, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 45934, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 45935, "name": "Fermat numbers", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <gmp.h>\n\nvoid mpz_factors(mpz_t n) {\n  int factors = 0;\n  mpz_t s, m, p;\n  mpz_init(s), mpz_init(m), mpz_init(p);\n\n  mpz_set_ui(m, 3);\n  mpz_set(p, n);\n  mpz_sqrt(s, p);\n\n  while (mpz_cmp(m, s) < 0) {\n    if (mpz_divisible_p(p, m)) {\n      gmp_printf(\"%Zd \", m);\n      mpz_fdiv_q(p, p, m);\n      mpz_sqrt(s, p);\n      factors ++;\n    }\n    mpz_add_ui(m, m, 2);\n  }\n\n  if (factors == 0) printf(\"PRIME\\n\");\n  else gmp_printf(\"%Zd\\n\", p);\n}\n\nint main(int argc, char const *argv[]) {\n  mpz_t fermat;\n  mpz_init_set_ui(fermat, 3);\n  printf(\"F(0) = 3 -> PRIME\\n\");\n  for (unsigned i = 1; i < 10; i ++) {\n    mpz_sub_ui(fermat, fermat, 1);\n    mpz_mul(fermat, fermat, fermat);\n    mpz_add_ui(fermat, fermat, 1);\n    gmp_printf(\"F(%d) = %Zd -> \", i, fermat);\n    mpz_factors(fermat);\n  }\n\n  return 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntypedef boost::multiprecision::cpp_int integer;\n\ninteger fermat(unsigned int n) {\n    unsigned int p = 1;\n    for (unsigned int i = 0; i < n; ++i)\n        p *= 2;\n    return 1 + pow(integer(2), p);\n}\n\ninline void g(integer& x, const integer& n) {\n    x *= x;\n    x += 1;\n    x %= n;\n}\n\ninteger pollard_rho(const integer& n) {\n    integer x = 2, y = 2, d = 1, z = 1;\n    int count = 0;\n    for (;;) {\n        g(x, n);\n        g(y, n);\n        g(y, n);\n        d = abs(x - y);\n        z = (z * d) % n;\n        ++count;\n        if (count == 100) {\n            d = gcd(z, n);\n            if (d != 1)\n                break;\n            z = 1;\n            count = 0;\n        }\n    }\n    if (d == n)\n        return 0;\n    return d;\n}\n\nstd::vector<integer> get_prime_factors(integer n) {\n    std::vector<integer> factors;\n    for (;;) {\n        if (miller_rabin_test(n, 25)) {\n            factors.push_back(n);\n            break;\n        }\n        integer f = pollard_rho(n);\n        if (f == 0) {\n            factors.push_back(n);\n            break;\n        }\n        factors.push_back(f);\n        n /= f;\n    }\n    return factors;\n}\n\nvoid print_vector(const std::vector<integer>& factors) {\n    if (factors.empty())\n        return;\n    auto i = factors.begin();\n    std::cout << *i++;\n    for (; i != factors.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout << \"First 10 Fermat numbers:\\n\";\n    for (unsigned int i = 0; i < 10; ++i)\n        std::cout << \"F(\" << i << \") = \" << fermat(i) << '\\n';\n    std::cout << \"\\nPrime factors:\\n\";\n    for (unsigned int i = 0; i < 9; ++i) {\n        std::cout << \"F(\" << i << \"): \";\n        print_vector(get_prime_factors(fermat(i)));\n    }\n    return 0;\n}\n"}
{"id": 45936, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 45937, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 45938, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 45939, "name": "Water collected between towers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 45940, "name": "Descending primes", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 45941, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n"}
{"id": 45942, "name": "Jaro similarity", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n"}
{"id": 45943, "name": "Sum and product puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n"}
{"id": 45944, "name": "Fairshare between two and more", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 45945, "name": "Two bullet roulette", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstatic int nextInt(int size) {\n    return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n    bool t = cylinder[5];\n    int i;\n    for (i = 4; i >= 0; i--) {\n        cylinder[i + 1] = cylinder[i];\n    }\n    cylinder[0] = t;\n}\n\nstatic void unload() {\n    int i;\n    for (i = 0; i < 6; i++) {\n        cylinder[i] = false;\n    }\n}\n\nstatic void load() {\n    while (cylinder[0]) {\n        rshift();\n    }\n    cylinder[0] = true;\n    rshift();\n}\n\nstatic void spin() {\n    int lim = nextInt(6) + 1;\n    int i;\n    for (i = 1; i < lim; i++) {\n        rshift();\n    }\n}\n\nstatic bool fire() {\n    bool shot = cylinder[0];\n    rshift();\n    return shot;\n}\n\nstatic int method(const char *s) {\n    unload();\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            load();\n            break;\n        case 'S':\n            spin();\n            break;\n        case 'F':\n            if (fire()) {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n    if (*out != '\\0') {\n        strcat(out, \", \");\n    }\n    strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            append(out, \"load\");\n            break;\n        case 'S':\n            append(out, \"spin\");\n            break;\n        case 'F':\n            append(out, \"fire\");\n            break;\n        }\n    }\n}\n\nstatic void test(char *src) {\n    char buffer[41] = \"\";\n    const int tests = 100000;\n    int sum = 0;\n    int t;\n    double pc;\n\n    for (t = 0; t < tests; t++) {\n        sum += method(src);\n    }\n\n    mstring(src, buffer);\n    pc = 100.0 * sum / tests;\n\n    printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n    srand(time(0));\n\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <sstream>\n\nclass Roulette {\nprivate:\n    std::array<bool, 6> cylinder;\n\n    std::mt19937 gen;\n    std::uniform_int_distribution<> distrib;\n\n    int next_int() {\n        return distrib(gen);\n    }\n\n    void rshift() {\n        std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n    }\n\n    void unload() {\n        std::fill(cylinder.begin(), cylinder.end(), false);\n    }\n\n    void load() {\n        while (cylinder[0]) {\n            rshift();\n        }\n        cylinder[0] = true;\n        rshift();\n    }\n\n    void spin() {\n        int lim = next_int();\n        for (int i = 1; i < lim; i++) {\n            rshift();\n        }\n    }\n\n    bool fire() {\n        auto shot = cylinder[0];\n        rshift();\n        return shot;\n    }\n\npublic:\n    Roulette() {\n        std::random_device rd;\n        gen = std::mt19937(rd());\n        distrib = std::uniform_int_distribution<>(1, 6);\n\n        unload();\n    }\n\n    int method(const std::string &s) {\n        unload();\n        for (auto c : s) {\n            switch (c) {\n            case 'L':\n                load();\n                break;\n            case 'S':\n                spin();\n                break;\n            case 'F':\n                if (fire()) {\n                    return 1;\n                }\n                break;\n            }\n        }\n        return 0;\n    }\n};\n\nstd::string mstring(const std::string &s) {\n    std::stringstream ss;\n    bool first = true;\n\n    auto append = [&ss, &first](const std::string s) {\n        if (first) {\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << s;\n    };\n\n    for (auto c : s) {\n        switch (c) {\n        case 'L':\n            append(\"load\");\n            break;\n        case 'S':\n            append(\"spin\");\n            break;\n        case 'F':\n            append(\"fire\");\n            break;\n        }\n    }\n\n    return ss.str();\n}\n\nvoid test(const std::string &src) {\n    const int tests = 100000;\n    int sum = 0;\n\n    Roulette r;\n    for (int t = 0; t < tests; t++) {\n        sum += r.method(src);\n    }\n\n    double pc = 100.0 * sum / tests;\n\n    std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n"}
{"id": 45946, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n"}
{"id": 45947, "name": "Prime triangle", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 45948, "name": "Trabb Pardo–Knuth algorithm", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 45949, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 45950, "name": "Sequence_ nth number with exactly n divisors", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 45951, "name": "Sequence_ smallest number with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n"}
{"id": 45952, "name": "Pancake numbers", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 45953, "name": "Generate random chess position", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n"}
{"id": 45954, "name": "Esthetic numbers", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n"}
{"id": 45955, "name": "Topswops", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n"}
{"id": 45956, "name": "Old Russian measure of length", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n"}
{"id": 45957, "name": "Rate counter", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n"}
{"id": 45958, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n"}
{"id": 45959, "name": "Padovan sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <cmath>\n\n\n\nint pRec(int n) {\n    static std::map<int,int> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n\n    if (n <= 2) memo[n] = 1;\n    else memo[n] = pRec(n-2) + pRec(n-3);\n    return memo[n];\n}\n\n\n\nint pFloor(int n) {\n    long const double p = 1.324717957244746025960908854;\n    long const double s = 1.0453567932525329623;\n    return std::pow(p, n-1)/s + 0.5;\n}\n\n\nstd::string& lSystem(int n) {\n    static std::map<int,std::string> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n    \n    if (n == 0) memo[n] = \"A\";\n    else {\n        memo[n] = \"\";\n        for (char ch : memo[n-1]) {\n            switch(ch) {\n                case 'A': memo[n].push_back('B'); break;\n                case 'B': memo[n].push_back('C'); break;\n                case 'C': memo[n].append(\"AB\"); break;\n            }\n        }\n    }\n    return memo[n];\n}\n\n\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n    std::cout << \"The \" << descr << \" functions \";\n    int i;\n    for (i=0; i<stop; i++) {\n        int n1 = f1(i);\n        int n2 = f2(i);\n        if (n1 != n2) {\n            std::cout << \"do not match at \" << i\n                      << \": \" << n1 << \" != \" << n2 << \".\\n\";\n            break;\n        }\n    }\n    if (i == stop) {\n        std::cout << \"match from P_0 to P_\" << stop << \".\\n\";\n    }\n}\n\nint main() {\n    \n    std::cout << \"P_0 .. P_19: \";\n    for (int i=0; i<20; i++) std::cout << pRec(i) << \" \";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, pRec, \"floor- and recurrence-based\", 64);\n    \n    \n    std::cout << \"\\nThe first 10 L-system strings are:\\n\";\n    for (int i=0; i<10; i++) std::cout << lSystem(i) << \"\\n\";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, [](int n){return (int)lSystem(n).length();}, \n                            \"floor- and L-system-based\", 32);\n    return 0;\n}\n"}
{"id": 45960, "name": "Pythagoras tree", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n"}
{"id": 45961, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 45962, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 45963, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 45964, "name": "Numeric error propagation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n"}
{"id": 45965, "name": "Numeric error propagation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n"}
{"id": 45966, "name": "List rooted trees", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n"}
{"id": 45967, "name": "List rooted trees", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n"}
{"id": 45968, "name": "Longest common suffix", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n"}
{"id": 45969, "name": "Sum of elements below main diagonal of matrix", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n"}
{"id": 45970, "name": "FASTA format", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 45971, "name": "Elementary cellular automaton_Random number generator", "C": "#include <stdio.h>\n#include <limits.h>\n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}\n", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n"}
{"id": 45972, "name": "Pseudo-random numbers_PCG32", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 45973, "name": "Sierpinski pentagon", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 45974, "name": "Rep-string", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 45975, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45976, "name": "Monads_List monad", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n    return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n    char buf[100];\n    char*str= malloc(1+sprintf(buf, \"%d\", *x));\n    sprintf(str, \"%d\", *x);\n    return (MONAD)(str);\n}\n\nvoid task(int y) {\n    char *z= INTBIND(boundInt2str, boundInt, &y);\n    printf(\"%s\\n\", z);\n    free(z);\n}\n\nint main() {\n    task(13);\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate <typename T>\nauto operator>>(const vector<T>& monad, auto f)\n{\n    \n    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;\n    for(auto& item : monad)\n    {\n        \n        \n        const auto r = f(item);\n        \n        result.insert(result.end(), begin(r), end(r));\n    }\n    \n    return result;\n}\n\n\nauto Pure(auto t)\n{\n    return vector{t};\n}\n\n\nauto Double(int i)\n{\n    return Pure(2 * i);\n}\n\n\nauto Increment(int i)\n{\n    return Pure(i + 1);\n}\n\n\nauto NiceNumber(int i)\n{\n    return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n\n\nauto UpperSequence = [](auto startingVal)\n{\n    const int MaxValue = 500;\n    vector<decltype(startingVal)> sequence;\n    while(startingVal <= MaxValue) \n        sequence.push_back(startingVal++);\n    return sequence;\n};\n\n\nvoid PrintVector(const auto& vec)\n{\n    cout << \" \";\n    for(auto value : vec)\n    {\n        cout << value << \" \";\n    }\n    cout << \"\\n\";\n}\n\n\nvoid PrintTriples(const auto& vec)\n{\n    cout << \"Pythagorean triples:\\n\";\n    for(auto it = vec.begin(); it != vec.end();)\n    {\n        auto x = *it++;\n        auto y = *it++;\n        auto z = *it++;\n        \n        cout << x << \", \" << y << \", \" << z << \"\\n\";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    \n    auto listMonad = \n        vector<int> {2, 3, 4} >> \n        Increment >> \n        Double >>\n        NiceNumber;\n        \n    PrintVector(listMonad);\n    \n    \n    \n    \n    \n    auto pythagoreanTriples = UpperSequence(1) >> \n        [](int x){return UpperSequence(x) >>\n        [x](int y){return UpperSequence(y) >>\n        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};\n    \n    PrintTriples(pythagoreanTriples);\n}\n"}
{"id": 45977, "name": "Special factorials", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 45978, "name": "Four is magic", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 45979, "name": "Getting the number of decimals", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 45980, "name": "Parse an IP Address", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n"}
{"id": 45981, "name": "Parse an IP Address", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n"}
{"id": 45982, "name": "Textonyms", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n"}
{"id": 45983, "name": "Textonyms", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n"}
{"id": 45984, "name": "Teacup rim text", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45985, "name": "Teacup rim text", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45986, "name": "Increasing gaps between consecutive Niven numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 45987, "name": "Increasing gaps between consecutive Niven numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 45988, "name": "Print debugging statement", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n"}
{"id": 45989, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 45990, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 45991, "name": "Type detection", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 45992, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 45993, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 45994, "name": "Variable declaration reset", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n"}
{"id": 45995, "name": "Variable declaration reset", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n"}
{"id": 45996, "name": "Numbers with equal rises and falls", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n"}
{"id": 45997, "name": "Koch curve", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45998, "name": "Words from neighbour ones", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45999, "name": "Magic squares of singly even order", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n"}
{"id": 46000, "name": "Generate Chess960 starting position", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n"}
{"id": 46001, "name": "File size distribution", "C": "#include<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 46002, "name": "File size distribution", "C": "#include<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 46003, "name": "Unix_ls", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 46004, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 46005, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 46006, "name": "Pseudo-random numbers_Xorshift star", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 46007, "name": "ASCII art diagram converter", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n"}
{"id": 46008, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n"}
{"id": 46009, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n"}
{"id": 46010, "name": "Peaceful chess queen armies", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 46011, "name": "Numbers with same digit set in base 10 and base 16", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n"}
{"id": 46012, "name": "Largest proper divisor of n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n"}
{"id": 46013, "name": "Largest proper divisor of n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n"}
{"id": 46014, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 46015, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 46016, "name": "Sum of first n cubes", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 46017, "name": "Test integerness", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n"}
{"id": 46018, "name": "Longest increasing subsequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 46019, "name": "Longest increasing subsequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 46020, "name": "Superpermutation minimisation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 46021, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 46022, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 46023, "name": "Summarize and say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 46024, "name": "Summarize and say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 46025, "name": "Spelling of ordinal numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 46026, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 46027, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 46028, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 46029, "name": "Numeric separator syntax", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n", "C++": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n"}
{"id": 46030, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n"}
{"id": 46031, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n"}
{"id": 46032, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 46033, "name": "Sunflower fractal", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 46034, "name": "Vogel's approximation method", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n"}
{"id": 46035, "name": "Vogel's approximation method", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n"}
{"id": 46036, "name": "Permutations by swapping", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n"}
{"id": 46037, "name": "Minimum multiple of m where digital sum equals m", "C": "#include <stdio.h>\n\nunsigned digit_sum(unsigned n) {\n    unsigned sum = 0;\n    do { sum += n % 10; }\n    while(n /= 10);\n    return sum;\n}\n\nunsigned a131382(unsigned n) {\n    unsigned m;\n    for (m = 1; n != digit_sum(m*n); m++);\n    return m;\n}\n\nint main() {\n    unsigned n;\n    for (n = 1; n <= 70; n++) {\n        printf(\"%9u\", a131382(n));\n        if (n % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n"}
{"id": 46038, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n"}
{"id": 46039, "name": "Steady squares", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n", "C++": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n"}
{"id": 46040, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 46041, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 46042, "name": "Dice game probabilities", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n"}
{"id": 46043, "name": "Dice game probabilities", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n"}
{"id": 46044, "name": "Halt and catch fire", "C": "int main(){int a=0, b=0, c=a/b;}\n", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n"}
{"id": 46045, "name": "Plasma effect", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n"}
{"id": 46046, "name": "Plasma effect", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n"}
{"id": 46047, "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 <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": 46048, "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": "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": 46049, "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": "#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": 46050, "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": "#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": 46051, "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": "#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": 46052, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/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": 46053, "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", "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": 46054, "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", "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": 46055, "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", "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": 46056, "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", "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": 46057, "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", "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": 46058, "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", "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": 46059, "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", "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": 46060, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 46061, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46062, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46063, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 46064, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $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 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": 46065, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $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 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": 46066, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 46067, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 46068, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\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": 46069, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($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": 46070, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download 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": 46071, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 46072, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 46073, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 46074, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 46075, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 46076, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 46077, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 46078, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 46079, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 46080, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 46081, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 46082, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 46083, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 46084, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 46085, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 46086, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 46087, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 46088, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 46089, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 46090, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 46091, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 46092, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n"}
{"id": 46093, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 46094, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 46095, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 46096, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 46097, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n"}
{"id": 46098, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n"}
{"id": 46099, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 46100, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 46101, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 46102, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 46103, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 46104, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 46105, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 46106, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 46107, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 46108, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 46109, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 46110, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 46111, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 46112, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 46113, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 46114, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 46115, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 46116, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 46117, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 46118, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 46119, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 46120, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n"}
{"id": 46121, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 46122, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 46123, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 46124, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 46125, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n"}
{"id": 46126, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "C": "char ch = 'z';\n"}
{"id": 46127, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 46128, "name": "SOAP", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n"}
{"id": 46129, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 46130, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 46131, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "C": "int meaning_of_life();\n"}
{"id": 46132, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "C": "int meaning_of_life();\n"}
{"id": 46133, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n"}
{"id": 46134, "name": "Calendar - for _REAL_ programmers", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n", "C": "\n\n\n\n\n\nINT PUTCHAR(INT);\n\nINT WIDTH = 80, YEAR = 1969;\nINT COLS, LEAD, GAP;\n \nCONST CHAR *WDAYS[] = { \"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\" };\nSTRUCT MONTHS {\n    CONST CHAR *NAME;\n    INT DAYS, START_WDAY, AT;\n} MONTHS[12] = {\n    { \"JANUARY\",    31, 0, 0 },\n    { \"FEBRUARY\",    28, 0, 0 },\n    { \"MARCH\",    31, 0, 0 },\n    { \"APRIL\",    30, 0, 0 },\n    { \"MAY\",    31, 0, 0 },\n    { \"JUNE\",    30, 0, 0 },\n    { \"JULY\",    31, 0, 0 },\n    { \"AUGUST\",    31, 0, 0 },\n    { \"SEPTEMBER\",    30, 0, 0 },\n    { \"OCTOBER\",    31, 0, 0 },\n    { \"NOVEMBER\",    30, 0, 0 },\n    { \"DECEMBER\",    31, 0, 0 }\n};\n \nVOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }\nVOID PRINT(CONST CHAR * S){ WHILE (*S != '\\0') { PUTCHAR(*S++); } }\nINT  STRLEN(CONST CHAR * S)\n{\n   INT L = 0;\n   WHILE (*S++ != '\\0') { L ++; };\nRETURN L;\n}\nINT ATOI(CONST CHAR * S)\n{\n    INT I = 0;\n    INT SIGN = 1;\n    CHAR C;\n    WHILE ((C = *S++) != '\\0') {\n        IF (C == '-')\n            SIGN *= -1;\n        ELSE {\n            I *= 10;\n            I += (C - '0');\n        }\n    }\nRETURN I * SIGN;\n}\n\nVOID INIT_MONTHS(VOID)\n{\n    INT I;\n \n    IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))\n        MONTHS[1].DAYS = 29;\n \n    YEAR--;\n    MONTHS[0].START_WDAY\n        = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;\n \n    FOR (I = 1; I < 12; I++)\n        MONTHS[I].START_WDAY =\n            (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;\n \n    COLS = (WIDTH + 2) / 22;\n    WHILE (12 % COLS) COLS--;\n    GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;\n    IF (GAP > 4) GAP = 4;\n    LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;\n        YEAR++;\n}\n \nVOID PRINT_ROW(INT ROW)\n{\n    INT C, I, FROM = ROW * COLS, TO = FROM + COLS;\n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        I = STRLEN(MONTHS[C].NAME);\n        SPACE((20 - I)/2);\n        PRINT(MONTHS[C].NAME);\n        SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));\n    }\n    PUTCHAR('\\012');\n \n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        FOR (I = 0; I < 7; I++) {\n            PRINT(WDAYS[I]);\n            PRINT(I == 6 ? \"\" : \" \");\n        }\n        IF (C < TO - 1) SPACE(GAP);\n        ELSE PUTCHAR('\\012');\n    }\n \n    WHILE (1) {\n        FOR (C = FROM; C < TO; C++)\n            IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;\n        IF (C == TO) BREAK;\n \n        SPACE(LEAD);\n        FOR (C = FROM; C < TO; C++) {\n            FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);\n            WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {\n                INT MM = ++MONTHS[C].AT;\n                PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));\n                PUTCHAR('0' + (MM %10));\n                IF (I < 7 || C < TO - 1) PUTCHAR(' ');\n            }\n            WHILE (I++ <= 7 && C < TO - 1) SPACE(3);\n            IF (C < TO - 1) SPACE(GAP - 1);\n            MONTHS[C].START_WDAY = 0;\n        }\n        PUTCHAR('\\012');\n    }\n    PUTCHAR('\\012');\n}\n \nVOID PRINT_YEAR(VOID)\n{\n    INT Y = YEAR;\n    INT ROW;\n    CHAR BUF[32];\n    CHAR * B = &(BUF[31]);\n    *B-- = '\\0';\n    DO {\n        *B-- = '0' + (Y % 10);\n        Y /= 10;\n    } WHILE (Y > 0);\n    B++;\n    SPACE((WIDTH - STRLEN(B)) / 2);\n    PRINT(B);PUTCHAR('\\012');PUTCHAR('\\012');\n    FOR (ROW = 0; ROW * COLS < 12; ROW++)\n        PRINT_ROW(ROW);\n}\n \nINT MAIN(INT C, CHAR **V)\n{\n    INT I, YEAR_SET = 0, RESULT = 0;\n    FOR (I = 1; I < C && RESULT == 0; I++) {\n        IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\\0') {\n            IF (++I == C || (WIDTH = ATOI(V[I])) < 20)\n                RESULT = 1;\n        } ELSE IF (!YEAR_SET) {\n            YEAR = ATOI(V[I]);\n            IF (YEAR <= 0)\n                YEAR = 1969;\n            YEAR_SET = 1;\n        } ELSE\n            RESULT = 1;\n    }\n \n    IF (RESULT == 0) {\n        INIT_MONTHS();\n        PRINT_YEAR();\n    } ELSE {\n        PRINT(\"BAD ARGS\\012USAGE: \");\n        PRINT(V[0]);\n        PRINT(\" YEAR [-W WIDTH (>= 20)]\\012\");\n    }\nRETURN RESULT;\n}\n"}
{"id": 46135, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 46136, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n"}
{"id": 46137, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n"}
{"id": 46138, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n"}
{"id": 46139, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n"}
{"id": 46140, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n"}
{"id": 46141, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 46142, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 46143, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 46144, "name": "Bitmap_Bézier curves_Cubic", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n", "C": "void cubic_bezier(\n       \timage img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        unsigned int x4, unsigned int y4,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 46145, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n"}
{"id": 46146, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 46147, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "C": "int j;\n"}
{"id": 46148, "name": "Periodic table", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n", "C": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\n\nGD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );\nint select_box_chemical_elem( RDS(MT_CELL, Elements) );\nvoid put_information(RDS( MT_CELL, elem), int i);\n\nMain\n   \n   GD_VIDEO table;\n   \n   Resize_terminal(42,135);\n   Init_video( &table );\n   \n   Gpm_Connect conn;\n\n   if ( ! Init_mouse(&conn)){\n        Msg_red(\"No se puede conectar al servidor del ratón\\n\");\n        Stop(1);\n   }  \n   Enable_raw_mode();\n   Hide_cursor;\n\n   \n   New multitype Elements;\n   Elements = load_chem_elements( pSDS(Elements) );\n   Throw( load_fail );\n   \n  \n   New objects Btn_exit;\n   Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, \"  Terminar  \", 6,44, 15, 0);\n\n  \n   table = put_chemical_cell( table, SDS(Elements) );\n\n  \n   Refresh(table);\n   Put object Btn_exit;\n  \n  \n   int c;\n   Waiting_some_clic(c)\n   {\n       if( select_box_chemical_elem(SDS(Elements)) ){\n           Waiting_some_clic(c) break;\n       }\n       if (Object_mouse( Btn_exit)) break;\n       \n       Refresh(table);\n       Put object Btn_exit;\n   }\n\n   Free object Btn_exit;\n   Free multitype Elements;\n   \n   Exception( load_fail ){\n      Msg_red(\"No es un archivo matriciable\");\n   }\n\n   Free video table;\n   Disable_raw_mode();\n   Close_mouse();\n   Show_cursor;\n   \n   At SIZE_TERM_ROWS,0;\n   Prnl;\nEnd\n\nvoid put_information(RDS(MT_CELL, elem), int i)\n{\n    At 2,19;\n    Box_solid(11,64,67,17);\n    Color(15,17);\n    At 4,22; Print \"Elemento (%s) = %s\", (char*)$s-elem[i,5],(char*)$s-elem[i,6];\n    if (Cell_type(elem,i,7) == double_TYPE ){\n        At 5,22; Print \"Peso atómico  = %f\", $d-elem[i,7];\n    }else{\n        At 5,22; Print \"Peso atómico  = (%ld)\", $l-elem[i,7];\n    }\n    At 6,22; Print \"Posición      = (%ld, %ld)\",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;\n    At 8,22; Print \"1ª energía de\";\n    if (Cell_type(elem,i,12) == double_TYPE ){\n        At 9,22; Print \"ionización (kJ/mol) = %.*f\",2,$d-elem[i,12];\n    }else{\n        At 9,22; Print \"ionización (kJ/mol) = ---\";\n    }\n    if (Cell_type(elem,i,13) == double_TYPE ){\n        At 10,22; Print \"Electronegatividad  = %.*f\",2,$d-elem[i,13];\n    }else{\n        At 10,22; Print \"Electronegatividad  = ---\";\n    }\n    At 4,56; Print \"Conf. electrónica:\";\n    At 5,56; Print \"       %s\", (char*)$s-elem[i,14];\n    At 7,56; Print \"Estados de oxidación:\";\n    if ( Cell_type(elem,i,15) == string_TYPE ){\n        At 8,56; Print \"       %s\", (char*)$s-elem[i,15];\n    }else{\n       \n        At 8,56; Print \"       %ld\", $l-elem[i,15];\n    }\n    At 10,56; Print \"Número Atómico: %ld\",$l-elem[i,4];\n    Reset_color;\n}\n\nint select_box_chemical_elem( RDS(MT_CELL, elem) )\n{\n   int i;\n   Iterator up i [0:1:Rows(elem)]{\n       if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){\n           Gotoxy( $l-elem[i,8], $l-elem[i,9] );\n           Color_fore( 15 ); Color_back( 0 );\n           Box( 4,5, DOUB_ALL );\n\n           Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print \"%ld\",$l-elem[i,4];\n           Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print \"%s\",(char*)$s-elem[i,5];\n           Flush_out;\n           Reset_color;\n           put_information(SDS(elem),i);\n           return 1;\n       }\n   }\n   return 0;\n}\n\nGD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)\n{\n   int i;\n   \n   \n   Iterator up i [0:1:Rows(elem)]{\n       long rx = 2+($l-elem[i,0]*4);\n       long cx = 3+($l-elem[i,1]*7);\n       long offr = rx+3;\n       long offc = cx+6;\n\n       Gotoxy(table, rx, cx);\n\n       Color_fore(table, $l-elem[i,2]);\n       Color_back(table,$l-elem[i,3]);\n\n       Box(table, 4,5, SING_ALL );\n\n       char Atnum[50], Elem[50];\n       sprintf(Atnum,\"\\x1b[3m%ld\\x1b[23m\",$l-elem[i,4]);\n       sprintf(Elem, \"\\x1b[1m%s\\x1b[22m\",(char*)$s-elem[i,5]);\n\n       Outvid(table,rx+1, cx+2, Atnum);\n       Outvid(table,rx+2, cx+2, Elem);\n\n       Reset_text(table);\n       \n       $l-elem[i,8] = rx;\n       $l-elem[i,9] = cx;\n       $l-elem[i,10] = offr;\n       $l-elem[i,11] = offc;\n       \n   }\n   \n   Iterator up i [ 1: 1: 19 ]{\n       Gotoxy(table, 31, 5+(i-1)*7);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Iterator up i [ 1: 1: 8 ]{\n       Gotoxy(table, 3+(i-1)*4, 130);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Outvid( table, 35,116, \"8\");\n   Outvid( table, 39,116, \"9\");\n   \n   \n   Color_fore(table, 15);\n   Color_back(table, 0);\n   Outvid(table,35,2,\"Lantánidos ->\");\n   Outvid(table,39,2,\"Actínidos  ->\");\n   Reset_text(table);\n   return table;\n}\n\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )\n{\n   F_STAT dataFile = Stat_file(\"chem_table.txt\");\n   if( dataFile.is_matrix ){\n       \n       Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n       E = Load_matrix_mt( SDS(E), \"chem_table.txt\", dataFile, DET_LONG);\n   }else{\n       Is_ok=0;\n   }\n   return E;\n}\n"}
{"id": 46149, "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++": "#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": 46150, "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++": "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": 46151, "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++": "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": 46152, "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++": "#include <fstream>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    std::ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\\n\" << dimx << ' ' << dimy << \"\\n255\\n\";\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << static_cast<char>(i % 256) \n                << static_cast<char>(j % 256)\n                << static_cast<char>((i * j) % 256);\n}\n"}
{"id": 46153, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/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": 46154, "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", "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": 46155, "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", "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": 46156, "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", "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": 46157, "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", "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": 46158, "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", "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": 46159, "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", "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": 46160, "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", "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": 46161, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 46162, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46163, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46164, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 46165, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 46166, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 46167, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 46168, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\n\n"}
{"id": 46169, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 46170, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n"}
{"id": 46171, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 46172, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 46173, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 46174, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 46175, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 46176, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 46177, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 46178, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 46179, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 46180, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 46181, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 46182, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 46183, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 46184, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 46185, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 46186, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 46187, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 46188, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 46189, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 46190, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 46191, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "C++": "#include <stack>\n"}
{"id": 46192, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 46193, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n"}
{"id": 46194, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 46195, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 46196, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 46197, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 46198, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 46199, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n"}
{"id": 46200, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 46201, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 46202, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 46203, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 46204, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 46205, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 46206, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 46207, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 46208, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 46209, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n"}
{"id": 46210, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 46211, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 46212, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 46213, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n"}
{"id": 46214, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 46215, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n"}
{"id": 46216, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 46217, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 46218, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 46219, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 46220, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 46221, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 46222, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 46223, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 46224, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n"}
{"id": 46225, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 46226, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "C++": "int meaning_of_life();\n"}
{"id": 46227, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "C++": "int meaning_of_life();\n"}
{"id": 46228, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 46229, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 46230, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 46231, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 46232, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 46233, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 46234, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n"}
{"id": 46235, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 46236, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 46237, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 46238, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 46239, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n"}
{"id": 46240, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n"}
{"id": 46241, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 46242, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 46243, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n"}
{"id": 46244, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n"}
{"id": 46245, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n"}
{"id": 46246, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 46247, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 46248, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 46249, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n"}
{"id": 46250, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 46251, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "C++": "#include <map>\n"}
{"id": 46252, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 46253, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "C++": "int a;\n"}
{"id": 46254, "name": "Monads_Writer monad", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n", "C++": "#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct LoggingMonad\n{\n    double Value;\n    string Log;\n};\n\n\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n    auto result = f(monad.Value);\n    return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n\nauto MakeWriter = [](auto f, string message)\n{\n    return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n    \n    auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n    cout << result.Log << \"\\nResult: \" << result.Value;\n}\n"}
{"id": 46255, "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", "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": 46256, "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", "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": 46257, "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", "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": 46258, "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", "Python": "for i in range(1, 11):\n    if i % 5 == 0:\n        print(i)\n        continue\n    print(i, end=', ')\n"}
{"id": 46259, "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", "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": 46260, "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", "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": 46261, "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", "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": 46262, "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", "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": 46263, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\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": 46264, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\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": 46265, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 46266, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 46267, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\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": 46268, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\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": 46269, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\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": 46270, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\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": 46271, "name": "SHA-256 Merkle tree", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\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": 46272, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \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": 46273, "name": "User input_Graphical", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\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": 46274, "name": "Sierpinski arrowhead curve", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\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": 46275, "name": "Text processing_1", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\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": 46276, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\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": 46277, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\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": 46278, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\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": 46279, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\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": 46280, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\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": 46281, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\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": 46282, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\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": 46283, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\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": 46284, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 46285, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 46286, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\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": 46287, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 46288, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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\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": 46289, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\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": 46290, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\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": 46291, "name": "Fractran", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\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": 46292, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\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": 46293, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\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": 46294, "name": "Galton box animation", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\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": 46295, "name": "Sorting Algorithms_Circle Sort", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\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": 46296, "name": "Kronecker product based fractals", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\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": 46297, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\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": 46298, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\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": 46299, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\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": 46300, "name": "Circular primes", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\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": 46301, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\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": 46302, "name": "Sorting algorithms_Radix sort", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\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": 46303, "name": "List comprehensions", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\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": 46304, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\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": 46305, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\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": 46306, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\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": 46307, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\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": 46308, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\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": 46309, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\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": 46310, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \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": 46311, "name": "Safe addition", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\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": 46312, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\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": 46313, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 46314, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n"}
{"id": 46315, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 46316, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\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": 46317, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\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": 46318, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\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": 46319, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\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": 46320, "name": "Non-continuous subsequences", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\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": 46321, "name": "Fibonacci word_fractal", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\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": 46322, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\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": 46323, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\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": 46324, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 46325, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\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": 46326, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\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": 46327, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\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": 46328, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\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": 46329, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\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": 46330, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\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": 46331, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 46332, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \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": 46333, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\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": 46334, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\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": 46335, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\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": 46336, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\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": 46337, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 46338, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 46339, "name": "Carmichael 3 strong pseudoprimes", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n"}
{"id": 46340, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n"}
{"id": 46341, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 46342, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 46343, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 46344, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 46345, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 46346, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 46347, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 46348, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 46349, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 46350, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 46351, "name": "Fermat numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class FermatNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 Fermat numbers:\");\n        for ( int i = 0 ; i < 10 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, fermat(i));\n        }\n        System.out.printf(\"%nFirst 12 Fermat numbers factored:%n\");\n        for ( int i = 0 ; i < 13 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, getString(getFactors(i, fermat(i))));\n        }\n    }\n    \n    private static String getString(List<BigInteger> factors) {\n        if ( factors.size() == 1 ) {\n            return factors.get(0) + \" (PRIME)\";\n        }\n        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith(\"-\") ? \"(C\" + v.replace(\"-\", \"\") + \")\" : v).collect(Collectors.joining(\" * \"));\n    }\n\n    private static Map<Integer, String> COMPOSITE = new HashMap<>();\n    static {\n        COMPOSITE.put(9, \"5529\");\n        COMPOSITE.put(10, \"6078\");\n        COMPOSITE.put(11, \"1037\");\n        COMPOSITE.put(12, \"5488\");\n        COMPOSITE.put(13, \"2884\");\n    }\n\n    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {\n        List<BigInteger> factors = new ArrayList<>();\n        BigInteger factor = BigInteger.ONE;\n        while ( true ) {\n            if ( n.isProbablePrime(100) ) {\n                factors.add(n);\n                break;\n            }\n            else {\n                if ( COMPOSITE.containsKey(fermatIndex) ) {\n                    String stop = COMPOSITE.get(fermatIndex);\n                    if ( n.toString().startsWith(stop) ) {\n                        factors.add(new BigInteger(\"-\" + n.toString().length()));\n                        break;\n                    }\n                }\n                factor = pollardRhoFast(n);\n                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {\n                    factors.add(n);\n                    break;\n                }\n                else {\n                    factors.add(factor);\n                    n = n.divide(factor);\n                }\n            }\n        }\n        return factors;\n    }\n    \n    private static final BigInteger TWO = BigInteger.valueOf(2);\n    \n    private static BigInteger fermat(int n) {\n        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);\n    }\n        \n    \n    @SuppressWarnings(\"unused\")\n    private static BigInteger pollardRho(BigInteger n) {\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        while ( d.compareTo(BigInteger.ONE) == 0 ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs().gcd(n);\n        }\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n    \n    \n    \n    \n    \n    \n    private static BigInteger pollardRhoFast(BigInteger n) {\n        long start = System.currentTimeMillis();\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        int count = 0;\n        BigInteger z = BigInteger.ONE;\n        while ( true ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs();\n            z = z.multiply(d).mod(n);\n            count++;\n            if ( count == 100 ) {\n                d = z.gcd(n);\n                if ( d.compareTo(BigInteger.ONE) != 0 ) {\n                    break;\n                }\n                z = BigInteger.ONE;\n                count = 0;\n            }\n        }\n        long end = System.currentTimeMillis();\n        System.out.printf(\"    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n\", n, (end-start), d);\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n\n    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {\n        return x.multiply(x).add(BigInteger.ONE).mod(n);\n    }\n\n}\n", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n"}
{"id": 46352, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 46353, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 46354, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 46355, "name": "Water collected between towers", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n"}
{"id": 46356, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"}
{"id": 46357, "name": "Jaro similarity", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46358, "name": "Sum and product puzzle", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n"}
{"id": 46359, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n"}
{"id": 46360, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 46361, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 46362, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 46363, "name": "Sequence_ nth number with exactly n divisors", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 46364, "name": "Sequence_ smallest number with exactly n divisors", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 46365, "name": "Pancake numbers", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n"}
{"id": 46366, "name": "Generate random chess position", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n"}
{"id": 46367, "name": "Esthetic numbers", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n"}
{"id": 46368, "name": "Topswops", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n"}
{"id": 46369, "name": "Old Russian measure of length", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n"}
{"id": 46370, "name": "Rate counter", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n"}
{"id": 46371, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 46372, "name": "Pythagoras tree", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n"}
{"id": 46373, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 46374, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 46375, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 46376, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 46377, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 46378, "name": "Sine wave", "Java": "import processing.sound.*;\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\nsine.freq(500);\nsine.play();\n\ndelay(5000);\n", "Python": "\n\nimport os\nfrom math import pi, sin\n\n\nau_header = bytearray(\n            [46, 115, 110, 100,   \n              0,   0,   0,  24,   \n            255, 255, 255, 255,   \n              0,   0,   0,   3,   \n              0,   0, 172,  68,   \n              0,   0,   0,   1])  \n\ndef f(x, freq):\n    \"Compute sine wave as 16-bit integer\"\n    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536\n\ndef play_sine(freq=440, duration=5, oname=\"pysine.au\"):\n    \"Play a sine wave for `duration` seconds\"\n    out = open(oname, 'wb')\n    out.write(au_header)\n    v = [f(x, freq) for x in range(duration * 44100 + 1)]\n    s = []\n    for i in v:\n        s.append(i >> 8)\n        s.append(i % 256)\n    out.write(bytearray(s))\n    out.close()\n    os.system(\"vlc \" + oname)   \n\nplay_sine()\n"}
{"id": 46379, "name": "Compiler_code generator", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 46380, "name": "Compiler_code generator", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 46381, "name": "Compiler_code generator", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 46382, "name": "Stern-Brocot sequence", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 46383, "name": "Numeric error propagation", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n"}
{"id": 46384, "name": "Soundex", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 46385, "name": "List rooted trees", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n"}
{"id": 46386, "name": "Documentation", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n"}
{"id": 46387, "name": "Problem of Apollonius", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n"}
{"id": 46388, "name": "Longest common suffix", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46389, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n"}
{"id": 46390, "name": "Idiomatically determine all the lowercase and uppercase letters", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n"}
{"id": 46391, "name": "Idiomatically determine all the lowercase and uppercase letters", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n"}
{"id": 46392, "name": "Sum of elements below main diagonal of matrix", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n"}
{"id": 46393, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 46394, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 46395, "name": "Numerical integration_Adaptive Simpson's method", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 46396, "name": "Numerical integration_Adaptive Simpson's method", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 46397, "name": "FASTA format", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n"}
{"id": 46398, "name": "FASTA format", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n"}
{"id": 46399, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 46400, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 46401, "name": "Window creation_X11", "Java": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n  public static void main(String[] args) {\n    Runnable runnable = new Runnable() {\n      public void run() {\n\tcreateAndShow();\n      }\n    };\n    SwingUtilities.invokeLater(runnable);\n  }\n\t\n  static void createAndShow() {\n    JFrame frame = new JFrame(\"Hello World\");\n    frame.setSize(640,480);\n    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n}\n", "Python": "from Xlib import X, display\n\nclass Window:\n    def __init__(self, display, msg):\n        self.display = display\n        self.msg = msg\n        \n        self.screen = self.display.screen()\n        self.window = self.screen.root.create_window(\n            10, 10, 100, 100, 1,\n            self.screen.root_depth,\n            background_pixel=self.screen.white_pixel,\n            event_mask=X.ExposureMask | X.KeyPressMask,\n            )\n        self.gc = self.window.create_gc(\n            foreground = self.screen.black_pixel,\n            background = self.screen.white_pixel,\n            )\n\n        self.window.map()\n\n    def loop(self):\n        while True:\n            e = self.display.next_event()\n                \n            if e.type == X.Expose:\n                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n                self.window.draw_text(self.gc, 10, 50, self.msg)\n            elif e.type == X.KeyPress:\n                raise SystemExit\n\n                \nif __name__ == \"__main__\":\n    Window(display.Display(), \"Hello, World!\").loop()\n"}
{"id": 46402, "name": "Finite state machine", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n"}
{"id": 46403, "name": "Vibrating rectangles", "Java": "\n\nint counter = 100;\n\nvoid setup(){\n  size(1000,1000);\n}\n\nvoid draw(){\n  \n  for(int i=0;i<20;i++){\n    fill(counter - 5*i);\n    rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);\n  }\n  counter++;\n  \n  if(counter > 255)\n    counter = 100;\n  \n  delay(100);\n}\n", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n"}
{"id": 46404, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 46405, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 46406, "name": "Pseudo-random numbers_PCG32", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 46407, "name": "Deconvolution_1D", "Java": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n    public static int[] deconv(int[] g, int[] f) {\n        int[] h = new int[g.length - f.length + 1];\n        for (int n = 0; n < h.length; n++) {\n            h[n] = g[n];\n            int lower = Math.max(n - f.length + 1, 0);\n            for (int i = lower; i < n; i++)\n                h[n] -= h[i] * f[n - i];\n            h[n] /= f[0];\n        }\n        return h;\n    }\n\n    public static void main(String[] args) {\n        int[] h = { -8, -9, -3, -1, -6, 7 };\n        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n                96, 31, 55, 36, 29, -43, -7 };\n\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n        sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n        sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n        sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n        System.out.println(sb.toString());\n    }\n}\n", "Python": "def ToReducedRowEchelonForm( M ):\n    if not M: return\n    lead = 0\n    rowCount = len(M)\n    columnCount = len(M[0])\n    for r in range(rowCount):\n        if lead >= columnCount:\n            return\n        i = r\n        while M[i][lead] == 0:\n            i += 1\n            if i == rowCount:\n                i = r\n                lead += 1\n                if columnCount == lead:\n                    return\n        M[i],M[r] = M[r],M[i]\n        lv = M[r][lead]\n        M[r] = [ mrx / lv for mrx in M[r]]\n        for i in range(rowCount):\n            if i != r:\n                lv = M[i][lead]\n                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n        lead += 1\n    return M\n \ndef pmtx(mtx):\n    print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n \ndef convolve(f, h):\n    g = [0] * (len(f) + len(h) - 1)\n    for hindex, hval in enumerate(h):\n        for findex, fval in enumerate(f):\n            g[hindex + findex] += fval * hval\n    return g\n\ndef deconvolve(g, f):\n    lenh = len(g) - len(f) + 1\n    mtx = [[0 for x in range(lenh+1)] for y in g]\n    for hindex in range(lenh):\n        for findex, fval in enumerate(f):\n            gindex = hindex + findex\n            mtx[gindex][hindex] = fval\n    for gindex, gval in enumerate(g):        \n        mtx[gindex][lenh] = gval\n    ToReducedRowEchelonForm( mtx )\n    return [mtx[i][lenh] for i in range(lenh)]  \n\nif __name__ == '__main__':\n    h = [-8,-9,-3,-1,-6,7]\n    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n    assert convolve(f,h) == g\n    assert deconvolve(g, f) == h\n"}
{"id": 46408, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 46409, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 46410, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 46411, "name": "Disarium numbers", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n"}
{"id": 46412, "name": "Disarium numbers", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n"}
{"id": 46413, "name": "Sierpinski pentagon", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n"}
{"id": 46414, "name": "Bitmap_Histogram", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 46415, "name": "Mutex", "Java": "import java.util.concurrent.Semaphore;\n\npublic class VolatileClass{\n   public Semaphore mutex = new Semaphore(1); \n                                              \n   public void needsToBeSynched(){\n      \n   }\n   \n}\n", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n"}
{"id": 46416, "name": "Metronome", "Java": "class Metronome{\n\tdouble bpm;\n\tint measure, counter;\n\tpublic Metronome(double bpm, int measure){\n\t\tthis.bpm = bpm;\n\t\tthis.measure = measure;\t\n\t}\n\tpublic void start(){\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tThread.sleep((long)(1000*(60.0/bpm)));\n\t\t\t}catch(InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tcounter++;\n\t\t\tif (counter%measure==0){\n\t\t\t\t System.out.println(\"TICK\");\n\t\t\t}else{\n\t\t\t\t System.out.println(\"TOCK\");\n\t\t\t}\n\t\t}\n\t}\n}\npublic class test {\n\tpublic static void main(String[] args) {\n\t\tMetronome metronome1 = new Metronome(120,4);\n\t\tmetronome1.start();\n\t}\n}\n", "Python": "\nimport time\n\ndef main(bpm = 72, bpb = 4):\n    sleep = 60.0 / bpm\n    counter = 0\n    while True:\n        counter += 1\n        if counter % bpb:\n            print 'tick'\n        else:\n            print 'TICK'\n        time.sleep(sleep)\n        \n\n\nmain()\n"}
{"id": 46417, "name": "EKG sequence convergence", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n    public static void main(String[] args) {\n        System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n        for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n            System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n        }\n        System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n        List<Integer> ekg5 = ekg(5, 100);\n        List<Integer> ekg7 = ekg(7, 100);\n        for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n            if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n                System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n                break;\n            }\n        }\n    }\n    \n    \n    private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {\n        List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));\n        Collections.sort(list1);\n        List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));\n        Collections.sort(list2);\n        for ( int i = 0 ; i < n ; i++ ) {\n            if ( list1.get(i) != list2.get(i) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    \n    \n    private static List<Integer> ekg(int two, int maxN) {\n        List<Integer> result = new ArrayList<>();\n        result.add(1);\n        result.add(two);\n        Map<Integer,Integer> seen = new HashMap<>();\n        seen.put(1, 1);\n        seen.put(two, 1);\n        int minUnseen = two == 2 ? 3 : 2;\n        int prev = two;\n        for ( int n = 3 ; n <= maxN ; n++ ) {\n            int test = minUnseen - 1;\n            while ( true ) {\n                test++;\n                if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n                    \n                    result.add(test);\n                    seen.put(test, n);\n                    prev = test;\n                    if ( minUnseen == test ) {\n                        do {\n                            minUnseen++;\n                        } while ( seen.containsKey(minUnseen) );\n                    }\n                    break;\n                }\n            }\n        }\n        return result;\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": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n    \n    c = count(start + 1)\n    last, so_far = start, list(range(2, start))\n    yield 1, []\n    yield last, []\n    while True:\n        for index, sf in enumerate(so_far):\n            if gcd(last, sf) > 1:\n                last = so_far.pop(index)\n                yield last, so_far[::]\n                break\n        else:\n            so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n    \"Returns the convergence point or zero if not found within the limit\"\n    ekg = [EKG_gen(n) for n in ekgs]\n    for e in ekg:\n        next(e)    \n    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),\n                                  zip(*ekg))))\n\nif __name__ == '__main__':\n    for start in 2, 5, 7, 9, 10:\n        print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n    print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")\n"}
{"id": 46418, "name": "Rep-string", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n"}
{"id": 46419, "name": "Terminal control_Preserve screen", "Java": "public class PreserveScreen\n{\n    public static void main(String[] args) throws InterruptedException {\n        System.out.print(\"\\033[?1049h\\033[H\");\n        System.out.println(\"Alternate screen buffer\\n\");\n        for (int i = 5; i > 0; i--) {\n            String s = (i > 1) ? \"s\" : \"\";\n            System.out.printf(\"\\rgoing back in %d second%s...\", i, s);\n            Thread.sleep(1000);\n        }\n        System.out.print(\"\\033[?1049l\");\n    }\n}\n", "Python": "\n\nimport time\n\nprint \"\\033[?1049h\\033[H\"\nprint \"Alternate buffer!\"\n\nfor i in xrange(5, 0, -1):\n    print \"Going back in:\", i\n    time.sleep(1)\n\nprint \"\\033[?1049l\"\n"}
{"id": 46420, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 46421, "name": "Changeable words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n"}
{"id": 46422, "name": "Window management", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n"}
{"id": 46423, "name": "Window management", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n"}
{"id": 46424, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n"}
{"id": 46425, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n"}
{"id": 46426, "name": "Mayan numerals", "Java": "import java.math.BigInteger;\n\npublic class MayanNumerals {\n\n    public static void main(String[] args) {\n        for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {\n            displayMyan(BigInteger.valueOf(base10));\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static char[] digits = \"0123456789ABCDEFGHJK\".toCharArray();\n    private static BigInteger TWENTY = BigInteger.valueOf(20);\n    \n    private static void displayMyan(BigInteger numBase10) {\n        System.out.printf(\"As base 10:  %s%n\", numBase10);\n        String numBase20 = \"\";\n        while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {\n            numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;\n            numBase10 = numBase10.divide(TWENTY);\n        }\n        System.out.printf(\"As base 20:  %s%nAs Mayan:%n\", numBase20);\n        displayMyanLine1(numBase20);\n        displayMyanLine2(numBase20);\n        displayMyanLine3(numBase20);\n        displayMyanLine4(numBase20);\n        displayMyanLine5(numBase20);\n        displayMyanLine6(numBase20);\n    }\n \n    private static char boxUL = Character.toChars(9556)[0];\n    private static char boxTeeUp = Character.toChars(9574)[0];\n    private static char boxUR = Character.toChars(9559)[0];\n    private static char boxHorz = Character.toChars(9552)[0];\n    private static char boxVert = Character.toChars(9553)[0];\n    private static char theta = Character.toChars(952)[0];\n    private static char boxLL = Character.toChars(9562)[0];\n    private static char boxLR = Character.toChars(9565)[0];\n    private static char boxTeeLow = Character.toChars(9577)[0];\n    private static char bullet = Character.toChars(8729)[0];\n    private static char dash = Character.toChars(9472)[0];\n    \n    private static void displayMyanLine1(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxUL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeUp : boxUR);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String getBullet(int count) {\n        StringBuilder sb = new StringBuilder();\n        switch ( count ) {\n        case 1:  sb.append(\" \" + bullet + \"  \"); break;\n        case 2:  sb.append(\" \" + bullet + bullet + \" \"); break;\n        case 3:  sb.append(\"\" + bullet + bullet + bullet + \" \"); break;\n        case 4:  sb.append(\"\" + bullet + bullet + bullet + bullet); break;\n        default:  throw new IllegalArgumentException(\"Must be 1-4:  \" + count);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine2(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'G':  sb.append(getBullet(1)); break;\n            case 'H':  sb.append(getBullet(2)); break;\n            case 'J':  sb.append(getBullet(3)); break;\n            case 'K':  sb.append(getBullet(4)); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String DASH = getDash();\n    \n    private static String getDash() {\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < 4 ; i++ ) {\n            sb.append(dash);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine3(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'B':  sb.append(getBullet(1)); break;\n            case 'C':  sb.append(getBullet(2)); break;\n            case 'D':  sb.append(getBullet(3)); break;\n            case 'E':  sb.append(getBullet(4)); break;\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine4(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '6':  sb.append(getBullet(1)); break;\n            case '7':  sb.append(getBullet(2)); break;\n            case '8':  sb.append(getBullet(3)); break;\n            case '9':  sb.append(getBullet(4)); break;\n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine5(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '0':  sb.append(\" \" + theta + \"  \"); break;\n            case '1':  sb.append(getBullet(1)); break;\n            case '2':  sb.append(getBullet(2)); break;\n            case '3':  sb.append(getBullet(3)); break;\n            case '4':  sb.append(getBullet(4)); break;\n            case '5': case '6': case '7': case '8': case '9': \n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine6(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxLL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeLow : boxLR);\n        }\n        System.out.println(sb.toString());\n    }\n\n}\n", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46427, "name": "Ramsey's theorem", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n", "Python": "range17 = range(17)\na = [['0'] * 17 for i in range17]\nidx = [0] * 4\n\n\ndef find_group(mark, min_n, max_n, depth=1):\n    if (depth == 4):\n        prefix = \"\" if (mark == '1') else \"un\"\n        print(\"Fail, found totally {}connected group:\".format(prefix))\n        for i in range(4):\n            print(idx[i])\n        return True\n\n    for i in range(min_n, max_n):\n        n = 0\n        while (n < depth):\n            if (a[idx[n]][i] != mark):\n                break\n            n += 1\n\n        if (n == depth):\n            idx[n] = i\n            if (find_group(mark, 1, max_n, depth + 1)):\n                return True\n\n    return False\n\n\nif __name__ == '__main__':\n    for i in range17:\n        a[i][i] = '-'\n    for k in range(4):\n        for i in range17:\n            j = (i + pow(2, k)) % 17\n            a[i][j] = a[j][i] = '1'\n\n    \n    \n\n    for row in a:\n        print(' '.join(row))\n\n    for i in range17:\n        idx[0] = i\n        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):\n            print(\"no good\")\n            exit()\n\n    print(\"all good\")\n"}
{"id": 46428, "name": "GUI_Maximum window dimensions", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n"}
{"id": 46429, "name": "Four is magic", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n"}
{"id": 46430, "name": "Getting the number of decimals", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n"}
{"id": 46431, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 46432, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 46433, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 46434, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 46435, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 46436, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 46437, "name": "Parse an IP Address", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n"}
{"id": 46438, "name": "Textonyms", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n"}
{"id": 46439, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 46440, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 46441, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 46442, "name": "Teacup rim text", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46443, "name": "Increasing gaps between consecutive Niven numbers", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n"}
{"id": 46444, "name": "Print debugging statement", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n"}
{"id": 46445, "name": "Superellipse", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n"}
{"id": 46446, "name": "Permutations_Rank of a permutation", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n"}
{"id": 46447, "name": "Permutations_Rank of a permutation", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n"}
{"id": 46448, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n"}
{"id": 46449, "name": "Maximum triangle path sum", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 46450, "name": "Zhang-Suen thinning algorithm", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n"}
{"id": 46451, "name": "Variable declaration reset", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n"}
{"id": 46452, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 46453, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 46454, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 46455, "name": "Numbers with equal rises and falls", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n"}
{"id": 46456, "name": "Koch curve", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n"}
{"id": 46457, "name": "Draw pixel 2", "Java": "\n\nsize(640,480);\n\nstroke(#ffff00);\n\nellipse(random(640),random(480),1,1);\n", "Python": "import Tkinter,random\ndef draw_pixel_2 ( sizex=640,sizey=480 ):\n    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )\n    root = Tkinter.Tk()\n    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )\n    can.create_rectangle( pos*2,outline='yellow' )\n    can.pack()\n    root.title('press ESCAPE to quit')\n    root.bind('<Escape>',lambda e : root.quit())\n    root.mainloop()\n\ndraw_pixel_2()\n"}
{"id": 46458, "name": "Draw a pixel", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n"}
{"id": 46459, "name": "Words from neighbour ones", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n"}
{"id": 46460, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 46461, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 46462, "name": "Magic squares of singly even order", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n"}
{"id": 46463, "name": "Generate Chess960 starting position", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n"}
{"id": 46464, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 46465, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 46466, "name": "Perlin noise", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n", "Python": "import math\n\ndef perlin_noise(x, y, z):\n    X = math.floor(x) & 255                  \n    Y = math.floor(y) & 255                  \n    Z = math.floor(z) & 255\n    x -= math.floor(x)                                \n    y -= math.floor(y)                                \n    z -= math.floor(z)\n    u = fade(x)                                \n    v = fade(y)                                \n    w = fade(z)\n    A = p[X  ]+Y; AA = p[A]+Z; AB = p[A+1]+Z      \n    B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z      \n \n    return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                   grad(p[BA  ], x-1, y  , z   )), \n                           lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                   grad(p[BB  ], x-1, y-1, z   ))),\n                   lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                   grad(p[BA+1], x-1, y  , z-1 )), \n                           lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                   grad(p[BB+1], x-1, y-1, z-1 ))))\n                                   \ndef fade(t): \n    return t ** 3 * (t * (t * 6 - 15) + 10)\n    \ndef lerp(t, a, b):\n    return a + t * (b - a)\n    \ndef grad(hash, x, y, z):\n    h = hash & 15                      \n    u = x if h<8 else y                \n    v = y if h<4 else (x if h in (12, 14) else z)\n    return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n    p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n    print(\"%1.17f\" % perlin_noise(3.14, 42, 7))\n"}
{"id": 46467, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 46468, "name": "UTF-8 encode and decode", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n"}
{"id": 46469, "name": "Xiaolin Wu's line algorithm", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n    return x - int(x)\n\ndef _rfpart(x):\n    return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n    \n    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n    c = compose_color(img.getpixel(xy), color)\n    img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n    \n    x1, y1 = p1\n    x2, y2 = p2\n    dx, dy = x2-x1, y2-y1\n    steep = abs(dx) < abs(dy)\n    p = lambda px, py: ((px,py), (py,px))[steep]\n\n    if steep:\n        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n    if x2 < x1:\n        x1, x2, y1, y2 = x2, x1, y2, y1\n\n    grad = dy/dx\n    intery = y1 + _rfpart(x1) * grad\n    def draw_endpoint(pt):\n        x, y = pt\n        xend = round(x)\n        yend = y + grad * (xend - x)\n        xgap = _rfpart(x + 0.5)\n        px, py = int(xend), int(yend)\n        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n        return px\n\n    xstart = draw_endpoint(p(*p1)) + 1\n    xend = draw_endpoint(p(*p2))\n\n    for x in range(xstart, xend):\n        y = int(intery)\n        putpixel(img, p(x, y), color, _rfpart(intery))\n        putpixel(img, p(x, y+1), color, _fpart(intery))\n        intery += grad\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print 'usage: python xiaolinwu.py [output-file]'\n        sys.exit(-1)\n\n    blue = (0, 0, 255)\n    yellow = (255, 255, 0)\n    img = Image.new(\"RGB\", (500,500), blue)\n    for a in range(10, 431, 60):\n        draw_line(img, (10, 10), (490, a), yellow)\n        draw_line(img, (10, 10), (a, 490), yellow)\n    draw_line(img, (10, 10), (490, 490), yellow)\n    filename = sys.argv[1]\n    img.save(filename)\n    print 'image saved to', filename\n"}
{"id": 46470, "name": "Keyboard macros", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n"}
{"id": 46471, "name": "Keyboard macros", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n"}
{"id": 46472, "name": "McNuggets problem", "Java": "public class McNuggets {\n\n    public static void main(String... args) {\n        int[] SIZES = new int[] { 6, 9, 20 };\n        int MAX_TOTAL = 100;\n        \n        int numSizes = SIZES.length;\n        int[] counts = new int[numSizes];\n        int maxFound = MAX_TOTAL + 1;\n        boolean[] found = new boolean[maxFound];\n        int numFound = 0;\n        int total = 0;\n        boolean advancedState = false;\n        do {\n            if (!found[total]) {\n                found[total] = true;\n                numFound++;\n            }\n            \n            \n            advancedState = false;\n            for (int i = 0; i < numSizes; i++) {\n                int curSize = SIZES[i];\n                if ((total + curSize) > MAX_TOTAL) {\n                    \n                    total -= counts[i] * curSize;\n                    counts[i] = 0;\n                }\n                else {\n                    \n                    counts[i]++;\n                    total += curSize;\n                    advancedState = true;\n                    break;\n                }\n            }\n            \n        } while ((numFound < maxFound) && advancedState);\n        \n        if (numFound < maxFound) {\n            \n            for (int i = MAX_TOTAL; i >= 0; i--) {\n                if (!found[i]) {\n                    System.out.println(\"Largest non-McNugget number in the search space is \" + i);\n                    break;\n                }\n            }\n        }\n        else {\n            System.out.println(\"All numbers in the search space are McNugget numbers\");\n        }\n        \n        return;\n    }\n}\n", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n"}
{"id": 46473, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 46474, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 46475, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 46476, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 46477, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 46478, "name": "Pseudo-random numbers_Xorshift star", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 46479, "name": "Four is the number of letters in the ...", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class FourIsTheNumberOfLetters {\n\n    public static void main(String[] args) {\n        String [] words = neverEndingSentence(201);\n        System.out.printf(\"Display the first 201 numbers in the sequence:%n%3d: \", 1);\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            System.out.printf(\"%2d \", numberOfLetters(words[i]));\n            if ( (i+1) % 25 == 0 ) {\n                System.out.printf(\"%n%3d: \", i+2);\n            }\n        }\n        System.out.printf(\"%nTotal number of characters in the sentence is %d%n\", characterCount(words));\n        for ( int i = 3 ; i <= 7 ; i++ ) {\n            int index = (int) Math.pow(10, i);\n            words = neverEndingSentence(index);\n            String last = words[words.length-1].replace(\",\", \"\");\n            System.out.printf(\"Number of letters of the %s word is %d. The word is \\\"%s\\\".  The sentence length is %,d characters.%n\", toOrdinal(index), numberOfLetters(last), last, characterCount(words));\n        }\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static void displaySentence(String[] words, int lineLength) {\n        int currentLength = 0;\n        for ( String word : words ) {\n            if ( word.length() + currentLength > lineLength ) {\n                String first = word.substring(0, lineLength-currentLength);\n                String second = word.substring(lineLength-currentLength);\n                System.out.println(first);\n                System.out.print(second);\n                currentLength = second.length();\n            }\n            else {\n                System.out.print(word);\n                currentLength += word.length();\n            }\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n            System.out.print(\" \");\n            currentLength++;\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n        }\n        System.out.println();\n    }\n    \n    private static int numberOfLetters(String word) {\n        return word.replace(\",\",\"\").replace(\"-\",\"\").length();\n    }\n    \n    private static long characterCount(String[] words) {\n        int characterCount = 0;\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            characterCount += words[i].length() + 1;\n        }        \n        \n        characterCount--;\n        return characterCount;\n    }\n    \n    private static String[] startSentence = new String[] {\"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\", \"first\", \"word\", \"of\", \"this\", \"sentence,\"};\n    \n    private static String[] neverEndingSentence(int wordCount) {\n        String[] words = new String[wordCount];\n        int index;\n        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {\n            words[index] = startSentence[index];\n        }\n        int sentencePosition = 1;\n        while ( index < wordCount ) {\n            \n            \n            sentencePosition++;\n            String word = words[sentencePosition-1];\n            for ( String wordLoop : numToString(numberOfLetters(word)).split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n            \n            words[index] = \"in\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            words[index] = \"the\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            for ( String wordLoop : (toOrdinal(sentencePosition) + \",\").split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n        }\n        return words;\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n    \n}\n", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n"}
{"id": 46480, "name": "ASCII art diagram converter", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n"}
{"id": 46481, "name": "Levenshtein distance_Alignment", "Java": "public class LevenshteinAlignment {\n\n    public static String[] alignment(String a, String b) {\n        a = a.toLowerCase();\n        b = b.toLowerCase();\n        \n        int[][] costs = new int[a.length()+1][b.length()+1];\n        for (int j = 0; j <= b.length(); j++)\n            costs[0][j] = j;\n        for (int i = 1; i <= a.length(); i++) {\n            costs[i][0] = i;\n            for (int j = 1; j <= b.length(); j++) {\n                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);\n            }\n        }\n\n\t\n\tStringBuilder aPathRev = new StringBuilder();\n\tStringBuilder bPathRev = new StringBuilder();\n\tfor (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {\n\t    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append(b.charAt(--j));\n\t    } else if (costs[i][j] == 1 + costs[i-1][j]) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append('-');\n\t    } else if (costs[i][j] == 1 + costs[i][j-1]) {\n\t\taPathRev.append('-');\n\t\tbPathRev.append(b.charAt(--j));\n\t    }\n\t}\n        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};\n    }\n\n    public static void main(String[] args) {\n\tString[] result = alignment(\"rosettacode\", \"raisethysword\");\n\tSystem.out.println(result[0]);\n\tSystem.out.println(result[1]);\n    }\n}\n", "Python": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n    result = \"\"\n    pos, removed = 0, 0\n    for x in ndiff(str1, str2):\n        if pos<len(str1) and str1[pos] == x[2]:\n          pos += 1\n          result += x[2]\n          if x[0] == \"-\":\n              removed += 1\n          continue\n        else:\n          if removed > 0:\n            removed -=1\n          else:\n            result += \"-\"\n    print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")\n"}
{"id": 46482, "name": "Same fringe", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 46483, "name": "Same fringe", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 46484, "name": "Simulate input_Keyboard", "Java": "import java.awt.Robot\npublic static void type(String str){\n   Robot robot = new Robot();\n   for(char ch:str.toCharArray()){\n      if(Character.isUpperCase(ch)){\n         robot.keyPress(KeyEvent.VK_SHIFT);\n         robot.keyPress((int)ch);\n         robot.keyRelease((int)ch);\n         robot.keyRelease(KeyEvent.VK_SHIFT);\n      }else{\n         char upCh = Character.toUpperCase(ch);\n         robot.keyPress((int)upCh);\n         robot.keyRelease((int)upCh);\n      }\n   }\n}\n", "Python": "import autopy\nautopy.key.type_string(\"Hello, world!\") \nautopy.key.type_string(\"Hello, world!\", wpm=60) \nautopy.key.tap(autopy.key.Code.RETURN)\nautopy.key.tap(autopy.key.Code.F1)\nautopy.key.tap(autopy.key.Code.LEFT_ARROW)\n"}
{"id": 46485, "name": "Peaceful chess queen armies", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n"}
{"id": 46486, "name": "Peaceful chess queen armies", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n"}
{"id": 46487, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 46488, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 46489, "name": "Active Directory_Search for a user", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n"}
{"id": 46490, "name": "Singular value decomposition", "Java": "import Jama.Matrix;\npublic class SingularValueDecomposition {\n    public static void main(String[] args) {\n        double[][] matrixArray = {{3, 0}, {4, 5}};\n        var matrix = new Matrix(matrixArray);\n        var svd = matrix.svd();\n        svd.getU().print(0, 10); \n        svd.getS().print(0, 10);\n        svd.getV().print(0, 10);\n    }\n}\n", "Python": "from numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n"}
{"id": 46491, "name": "Test integerness", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n"}
{"id": 46492, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 46493, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 46494, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 46495, "name": "Death Star", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n"}
{"id": 46496, "name": "Lucky and even lucky numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n"}
{"id": 46497, "name": "Scope modifiers", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n"}
{"id": 46498, "name": "Scope modifiers", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n"}
{"id": 46499, "name": "Simple database", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n"}
{"id": 46500, "name": "Simple database", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n"}
{"id": 46501, "name": "Total circles area", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 46502, "name": "Total circles area", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 46503, "name": "Total circles area", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 46504, "name": "Hough transform", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\n  }\n}\n", "Python": "from math import hypot, pi, cos, sin\nfrom PIL import Image\n\n\ndef hough(im, ntx=460, mry=360):\n    \"Calculate Hough transform.\"\n    pim = im.load()\n    nimx, mimy = im.size\n    mry = int(mry/2)*2          \n    him = Image.new(\"L\", (ntx, mry), 255)\n    phim = him.load()\n\n    rmax = hypot(nimx, mimy)\n    dr = rmax / (mry/2)\n    dth = pi / ntx\n\n    for jx in xrange(nimx):\n        for iy in xrange(mimy):\n            col = pim[jx, iy]\n            if col == 255: continue\n            for jtx in xrange(ntx):\n                th = dth * jtx\n                r = jx*cos(th) + iy*sin(th)\n                iry = mry/2 + int(r/dr+0.5)\n                phim[jtx, iry] -= 1\n    return him\n\n\ndef test():\n    \"Test Hough transform with pentagon.\"\n    im = Image.open(\"pentagon.png\").convert(\"L\")\n    him = hough(im)\n    him.save(\"ho5.bmp\")\n\n\nif __name__ == \"__main__\": test()\n"}
{"id": 46505, "name": "Verify distribution uniformity_Chi-squared test", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n"}
{"id": 46506, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 46507, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 46508, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 46509, "name": "Topological sort_Extracted top item", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n"}
{"id": 46510, "name": "Topological sort_Extracted top item", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n"}
{"id": 46511, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 46512, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 46513, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 46514, "name": "Superpermutation minimisation", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n"}
{"id": 46515, "name": "GUI component interaction", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n"}
{"id": 46516, "name": "One of n lines in a file", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 46517, "name": "Summarize and say sequence", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n"}
{"id": 46518, "name": "Spelling of ordinal numbers", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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"}
{"id": 46519, "name": "Spelling of ordinal numbers", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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"}
{"id": 46520, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 46521, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 46522, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n"}
{"id": 46523, "name": "Repeat", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 46524, "name": "Sparkline in unicode", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n"}
{"id": 46525, "name": "Compiler_AST interpreter", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 46526, "name": "Compiler_AST interpreter", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 46527, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 46528, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 46529, "name": "Simulate input_Mouse", "Java": "Point p = component.getLocation();\nRobot robot = new Robot();\nrobot.mouseMove(p.getX(), p.getY()); \nrobot.mousePress(InputEvent.BUTTON1_MASK); \n                                       \nrobot.mouseRelease(InputEvent.BUTTON1_MASK);\n", "Python": "import ctypes\n\ndef click():\n    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    \n    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    \n\nclick()\n"}
{"id": 46530, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 46531, "name": "Terminal control_Clear the screen", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n", "Python": "import os\nos.system(\"clear\")\n"}
{"id": 46532, "name": "Sunflower fractal", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n"}
{"id": 46533, "name": "Vogel's approximation method", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n"}
{"id": 46534, "name": "Air mass", "Java": "public class AirMass {\n    public static void main(String[] args) {\n        System.out.println(\"Angle     0 m              13700 m\");\n        System.out.println(\"------------------------------------\");\n        for (double z = 0; z <= 90; z+= 5) {\n            System.out.printf(\"%2.0f      %11.8f      %11.8f\\n\",\n                            z, airmass(0.0, z), airmass(13700.0, z));\n        }\n    }\n\n    private static double rho(double a) {\n        \n        return Math.exp(-a / 8500.0);\n    }\n\n    private static double height(double a, double z, double d) {\n        \n        \n        \n        double aa = RE + a;\n        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));\n        return hh - RE;\n    }\n\n    private static double columnDensity(double a, double z) {\n        \n        double sum = 0.0, d = 0.0;\n        while (d < FIN) {\n            \n            double delta = Math.max(DD * d, DD);\n            sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n            d += delta;\n        }\n        return sum;\n    }\n     \n    private static double airmass(double a, double z) {\n        return columnDensity(a, z) / columnDensity(a, 0.0);\n    }\n\n    private static final double RE = 6371000.0; \n    private static final double DD = 0.001; \n    private static final double FIN = 10000000.0; \n}\n", "Python": "\n\nfrom math import sqrt, cos, exp\n\nDEG = 0.017453292519943295769236907684886127134  \nRE = 6371000                                     \ndd = 0.001      \nFIN = 10000000  \n \ndef rho(a):\n    \n    return exp(-a / 8500.0)\n \ndef height(a, z, d):\n     \n    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE\n \ndef column_density(a, z):\n    \n    dsum, d = 0.0, 0.0\n    while d < FIN:\n        delta = max(dd, (dd)*d)  \n        dsum += rho(height(a, z, d + 0.5 * delta)) * delta\n        d += delta\n    return dsum\n\ndef airmass(a, z):\n    return column_density(a, z) / column_density(a, 0)\n\nprint('Angle           0 m          13700 m\\n', '-' * 36)\nfor z in range(0, 91, 5):\n    print(f\"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}\")\n"}
{"id": 46535, "name": "Sorting algorithms_Pancake sort", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n"}
{"id": 46536, "name": "Sorting algorithms_Pancake sort", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n"}
{"id": 46537, "name": "Chemical calculator", "Java": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\npublic class ChemicalCalculator {\n    private static final Map<String, Double> atomicMass = new HashMap<>();\n\n    static {\n        atomicMass.put(\"H\", 1.008);\n        atomicMass.put(\"He\", 4.002602);\n        atomicMass.put(\"Li\", 6.94);\n        atomicMass.put(\"Be\", 9.0121831);\n        atomicMass.put(\"B\", 10.81);\n        atomicMass.put(\"C\", 12.011);\n        atomicMass.put(\"N\", 14.007);\n        atomicMass.put(\"O\", 15.999);\n        atomicMass.put(\"F\", 18.998403163);\n        atomicMass.put(\"Ne\", 20.1797);\n        atomicMass.put(\"Na\", 22.98976928);\n        atomicMass.put(\"Mg\", 24.305);\n        atomicMass.put(\"Al\", 26.9815385);\n        atomicMass.put(\"Si\", 28.085);\n        atomicMass.put(\"P\", 30.973761998);\n        atomicMass.put(\"S\", 32.06);\n        atomicMass.put(\"Cl\", 35.45);\n        atomicMass.put(\"Ar\", 39.948);\n        atomicMass.put(\"K\", 39.0983);\n        atomicMass.put(\"Ca\", 40.078);\n        atomicMass.put(\"Sc\", 44.955908);\n        atomicMass.put(\"Ti\", 47.867);\n        atomicMass.put(\"V\", 50.9415);\n        atomicMass.put(\"Cr\", 51.9961);\n        atomicMass.put(\"Mn\", 54.938044);\n        atomicMass.put(\"Fe\", 55.845);\n        atomicMass.put(\"Co\", 58.933194);\n        atomicMass.put(\"Ni\", 58.6934);\n        atomicMass.put(\"Cu\", 63.546);\n        atomicMass.put(\"Zn\", 65.38);\n        atomicMass.put(\"Ga\", 69.723);\n        atomicMass.put(\"Ge\", 72.630);\n        atomicMass.put(\"As\", 74.921595);\n        atomicMass.put(\"Se\", 78.971);\n        atomicMass.put(\"Br\", 79.904);\n        atomicMass.put(\"Kr\", 83.798);\n        atomicMass.put(\"Rb\", 85.4678);\n        atomicMass.put(\"Sr\", 87.62);\n        atomicMass.put(\"Y\", 88.90584);\n        atomicMass.put(\"Zr\", 91.224);\n        atomicMass.put(\"Nb\", 92.90637);\n        atomicMass.put(\"Mo\", 95.95);\n        atomicMass.put(\"Ru\", 101.07);\n        atomicMass.put(\"Rh\", 102.90550);\n        atomicMass.put(\"Pd\", 106.42);\n        atomicMass.put(\"Ag\", 107.8682);\n        atomicMass.put(\"Cd\", 112.414);\n        atomicMass.put(\"In\", 114.818);\n        atomicMass.put(\"Sn\", 118.710);\n        atomicMass.put(\"Sb\", 121.760);\n        atomicMass.put(\"Te\", 127.60);\n        atomicMass.put(\"I\", 126.90447);\n        atomicMass.put(\"Xe\", 131.293);\n        atomicMass.put(\"Cs\", 132.90545196);\n        atomicMass.put(\"Ba\", 137.327);\n        atomicMass.put(\"La\", 138.90547);\n        atomicMass.put(\"Ce\", 140.116);\n        atomicMass.put(\"Pr\", 140.90766);\n        atomicMass.put(\"Nd\", 144.242);\n        atomicMass.put(\"Pm\", 145.0);\n        atomicMass.put(\"Sm\", 150.36);\n        atomicMass.put(\"Eu\", 151.964);\n        atomicMass.put(\"Gd\", 157.25);\n        atomicMass.put(\"Tb\", 158.92535);\n        atomicMass.put(\"Dy\", 162.500);\n        atomicMass.put(\"Ho\", 164.93033);\n        atomicMass.put(\"Er\", 167.259);\n        atomicMass.put(\"Tm\", 168.93422);\n        atomicMass.put(\"Yb\", 173.054);\n        atomicMass.put(\"Lu\", 174.9668);\n        atomicMass.put(\"Hf\", 178.49);\n        atomicMass.put(\"Ta\", 180.94788);\n        atomicMass.put(\"W\", 183.84);\n        atomicMass.put(\"Re\", 186.207);\n        atomicMass.put(\"Os\", 190.23);\n        atomicMass.put(\"Ir\", 192.217);\n        atomicMass.put(\"Pt\", 195.084);\n        atomicMass.put(\"Au\", 196.966569);\n        atomicMass.put(\"Hg\", 200.592);\n        atomicMass.put(\"Tl\", 204.38);\n        atomicMass.put(\"Pb\", 207.2);\n        atomicMass.put(\"Bi\", 208.98040);\n        atomicMass.put(\"Po\", 209.0);\n        atomicMass.put(\"At\", 210.0);\n        atomicMass.put(\"Rn\", 222.0);\n        atomicMass.put(\"Fr\", 223.0);\n        atomicMass.put(\"Ra\", 226.0);\n        atomicMass.put(\"Ac\", 227.0);\n        atomicMass.put(\"Th\", 232.0377);\n        atomicMass.put(\"Pa\", 231.03588);\n        atomicMass.put(\"U\", 238.02891);\n        atomicMass.put(\"Np\", 237.0);\n        atomicMass.put(\"Pu\", 244.0);\n        atomicMass.put(\"Am\", 243.0);\n        atomicMass.put(\"Cm\", 247.0);\n        atomicMass.put(\"Bk\", 247.0);\n        atomicMass.put(\"Cf\", 251.0);\n        atomicMass.put(\"Es\", 252.0);\n        atomicMass.put(\"Fm\", 257.0);\n        atomicMass.put(\"Uue\", 315.0);\n        atomicMass.put(\"Ubn\", 299.0);\n    }\n\n    private static double evaluate(String s) {\n        String sym = s + \"[\";\n        double sum = 0.0;\n        StringBuilder symbol = new StringBuilder();\n        String number = \"\";\n        for (int i = 0; i < sym.length(); ++i) {\n            char c = sym.charAt(i);\n            if ('@' <= c && c <= '[') {\n                \n                int n = 1;\n                if (!number.isEmpty()) {\n                    n = Integer.parseInt(number);\n                }\n                if (symbol.length() > 0) {\n                    sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;\n                }\n                if (c == '[') {\n                    break;\n                }\n                symbol = new StringBuilder(String.valueOf(c));\n                number = \"\";\n            } else if ('a' <= c && c <= 'z') {\n                symbol.append(c);\n            } else if ('0' <= c && c <= '9') {\n                number += c;\n            } else {\n                throw new RuntimeException(\"Unexpected symbol \" + c + \" in molecule\");\n            }\n        }\n        return sum;\n    }\n\n    private static String replaceParens(String s) {\n        char letter = 'a';\n        String si = s;\n        while (true) {\n            int start = si.indexOf('(');\n            if (start == -1) {\n                break;\n            }\n\n            for (int i = start + 1; i < si.length(); ++i) {\n                if (si.charAt(i) == ')') {\n                    String expr = si.substring(start + 1, i);\n                    String symbol = \"@\" + letter;\n                    String pattern = Pattern.quote(si.substring(start, i + 1));\n                    si = si.replaceFirst(pattern, symbol);\n                    atomicMass.put(symbol, evaluate(expr));\n                    letter++;\n                    break;\n                }\n                if (si.charAt(i) == '(') {\n                    start = i;\n                }\n            }\n        }\n        return si;\n    }\n\n    public static void main(String[] args) {\n        List<String> molecules = List.of(\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        );\n        for (String molecule : molecules) {\n            double mass = evaluate(replaceParens(molecule));\n            System.out.printf(\"%17s -> %7.3f\\n\", molecule, mass);\n        }\n    }\n}\n", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n"}
{"id": 46538, "name": "Active Directory_Connect", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 46539, "name": "Permutations by swapping", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n"}
{"id": 46540, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 46541, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 46542, "name": "Image convolution", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class ImageConvolution\n{\n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n  }\n  \n  private static int bound(int value, int endIndex)\n  {\n    if (value < 0)\n      return 0;\n    if (value < endIndex)\n      return value;\n    return endIndex - 1;\n  }\n  \n  public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)\n  {\n    int inputWidth = inputData.width;\n    int inputHeight = inputData.height;\n    int kernelWidth = kernel.width;\n    int kernelHeight = kernel.height;\n    if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd width\");\n    if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd height\");\n    int kernelWidthRadius = kernelWidth >>> 1;\n    int kernelHeightRadius = kernelHeight >>> 1;\n    \n    ArrayData outputData = new ArrayData(inputWidth, inputHeight);\n    for (int i = inputWidth - 1; i >= 0; i--)\n    {\n      for (int j = inputHeight - 1; j >= 0; j--)\n      {\n        double newValue = 0.0;\n        for (int kw = kernelWidth - 1; kw >= 0; kw--)\n          for (int kh = kernelHeight - 1; kh >= 0; kh--)\n            newValue += kernel.get(kw, kh) * inputData.get(\n                          bound(i + kw - kernelWidthRadius, inputWidth),\n                          bound(j + kh - kernelHeightRadius, inputHeight));\n        outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));\n      }\n    }\n    return outputData;\n  }\n  \n  public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData reds = new ArrayData(width, height);\n    ArrayData greens = new ArrayData(width, height);\n    ArrayData blues = new ArrayData(width, height);\n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        reds.set(x, y, (rgbValue >>> 16) & 0xFF);\n        greens.set(x, y, (rgbValue >>> 8) & 0xFF);\n        blues.set(x, y, rgbValue & 0xFF);\n      }\n    }\n    return new ArrayData[] { reds, greens, blues };\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException\n  {\n    ArrayData reds = redGreenBlue[0];\n    ArrayData greens = redGreenBlue[1];\n    ArrayData blues = redGreenBlue[2];\n    BufferedImage outputImage = new BufferedImage(reds.width, reds.height,\n                                                  BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < reds.height; y++)\n    {\n      for (int x = 0; x < reds.width; x++)\n      {\n        int red = bound(reds.get(x, y), 256);\n        int green = bound(greens.get(x, y), 256);\n        int blue = bound(blues.get(x, y), 256);\n        outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    int kernelWidth = Integer.parseInt(args[2]);\n    int kernelHeight = Integer.parseInt(args[3]);\n    int kernelDivisor = Integer.parseInt(args[4]);\n    System.out.println(\"Kernel size: \" + kernelWidth + \"x\" + kernelHeight +\n                       \", divisor=\" + kernelDivisor);\n    int y = 5;\n    ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);\n    for (int i = 0; i < kernelHeight; i++)\n    {\n      System.out.print(\"[\");\n      for (int j = 0; j < kernelWidth; j++)\n      {\n        kernel.set(j, i, Integer.parseInt(args[y++]));\n        System.out.print(\" \" + kernel.get(j, i) + \" \");\n      }\n      System.out.println(\"]\");\n    }\n    \n    ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);\n    for (int i = 0; i < dataArrays.length; i++)\n      dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);\n    writeOutputImage(args[1], dataArrays);\n    return;\n  }\n}\n", "Python": "\nfrom PIL import Image, ImageFilter\n\nif __name__==\"__main__\":\n\tim = Image.open(\"test.jpg\")\n\n\tkernelValues = [-2,-1,0,-1,1,1,0,1,2] \n\tkernel = ImageFilter.Kernel((3,3), kernelValues)\n\n\tim2 = im.filter(kernel)\n\n\tim2.show()\n"}
{"id": 46543, "name": "Dice game probabilities", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n"}
{"id": 46544, "name": "Sokoban", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n"}
{"id": 46545, "name": "Practical numbers", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n"}
{"id": 46546, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 46547, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 46548, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 46549, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 46550, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46551, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46552, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 46553, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 46554, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 46555, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 46556, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 46557, "name": "Word search", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n"}
{"id": 46558, "name": "Word search", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n"}
{"id": 46559, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 46560, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 46561, "name": "Object serialization", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 46562, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 46563, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 46564, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46565, "name": "Zumkeller numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n"}
{"id": 46566, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 46567, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 46568, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 46569, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 46570, "name": "Markov chain text generator", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 46571, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 46572, "name": "Geometric algebra", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n"}
{"id": 46573, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 46574, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 46575, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 46576, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n"}
{"id": 46577, "name": "Penrose tiling", "Java": "import java.awt.*;\nimport java.util.List;\nimport java.awt.geom.Path2D;\nimport java.util.*;\nimport javax.swing.*;\nimport static java.lang.Math.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class PenroseTiling extends JPanel {\n    \n    class Tile {\n        double x, y, angle, size;\n        Type type;\n\n        Tile(Type t, double x, double y, double a, double s) {\n            type = t;\n            this.x = x;\n            this.y = y;\n            angle = a;\n            size = s;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Tile) {\n                Tile t = (Tile) o;\n                return type == t.type && x == t.x && y == t.y && angle == t.angle;\n            }\n            return false;\n        }\n    }\n\n    enum Type {\n        Kite, Dart\n    }\n\n    static final double G = (1 + sqrt(5)) / 2; \n    static final double T = toRadians(36); \n\n    List<Tile> tiles = new ArrayList<>();\n\n    public PenroseTiling() {\n        int w = 700, h = 450;\n        setPreferredSize(new Dimension(w, h));\n        setBackground(Color.white);\n\n        tiles = deflateTiles(setupPrototiles(w, h), 5);\n    }\n\n    List<Tile> setupPrototiles(int w, int h) {\n        List<Tile> proto = new ArrayList<>();\n\n        \n        for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)\n            proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));\n\n        return proto;\n    }\n\n    List<Tile> deflateTiles(List<Tile> tls, int generation) {\n        if (generation <= 0)\n            return tls;\n\n        List<Tile> next = new ArrayList<>();\n\n        for (Tile tile : tls) {\n            double x = tile.x, y = tile.y, a = tile.angle, nx, ny;\n            double size = tile.size / G;\n\n            if (tile.type == Type.Dart) {\n                next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    nx = x + cos(a - 4 * T * sign) * G * tile.size;\n                    ny = y - sin(a - 4 * T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));\n                }\n\n            } else {\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));\n\n                    nx = x + cos(a - T * sign) * G * tile.size;\n                    ny = y - sin(a - T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));\n                }\n            }\n        }\n        \n        tls = next.stream().distinct().collect(toList());\n\n        return deflateTiles(tls, generation - 1);\n    }\n\n    void drawTiles(Graphics2D g) {\n        double[][] dist = {{G, G, G}, {-G, -1, -G}};\n        for (Tile tile : tiles) {\n            double angle = tile.angle - T;\n            Path2D path = new Path2D.Double();\n            path.moveTo(tile.x, tile.y);\n\n            int ord = tile.type.ordinal();\n            for (int i = 0; i < 3; i++) {\n                double x = tile.x + dist[ord][i] * tile.size * cos(angle);\n                double y = tile.y - dist[ord][i] * tile.size * sin(angle);\n                path.lineTo(x, y);\n                angle += T;\n            }\n            path.closePath();\n            g.setColor(ord == 0 ? Color.orange : Color.yellow);\n            g.fill(path);\n            g.setColor(Color.darkGray);\n            g.draw(path);\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics og) {\n        super.paintComponent(og);\n        Graphics2D g = (Graphics2D) og;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        drawTiles(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(\"Penrose Tiling\");\n            f.setResizable(false);\n            f.add(new PenroseTiling(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "def penrose(depth):\n    print(\t<g id=\"A{d+1}\" transform=\"translate(100, 0) scale(0.6180339887498949)\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n\t<g id=\"B{d+1}\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\t<g id=\"G\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n  </defs>\n  <g transform=\"scale(2, 2)\">\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n  </g>\n</svg>''')\n\npenrose(6)\n"}
{"id": 46578, "name": "Sphenic numbers", "Java": "import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SphenicNumbers {\n    public static void main(String[] args) {\n        final int limit = 1000000;\n        final int imax = limit / 6;\n        boolean[] sieve = primeSieve(imax + 1);\n        boolean[] sphenic = new boolean[limit + 1];\n        for (int i = 0; i <= imax; ++i) {\n            if (!sieve[i])\n                continue;\n            int jmax = Math.min(imax, limit / (i * i));\n            if (jmax <= i)\n                break;\n            for (int j = i + 1; j <= jmax; ++j) {\n                if (!sieve[j])\n                    continue;\n                int p = i * j;\n                int kmax = Math.min(imax, limit / p);\n                if (kmax <= j)\n                    break;\n                for (int k = j + 1; k <= kmax; ++k) {\n                    if (!sieve[k])\n                        continue;\n                    assert(p * k <= limit);\n                    sphenic[p * k] = true;\n                }\n            }\n        }\n    \n        System.out.println(\"Sphenic numbers < 1000:\");\n        for (int i = 0, n = 0; i < 1000; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++n;\n            System.out.printf(\"%3d%c\", i, n % 15 == 0 ? '\\n' : ' ');\n        }\n    \n        System.out.println(\"\\nSphenic triplets < 10,000:\");\n        for (int i = 0, n = 0; i < 10000; ++i) {\n            if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n                ++n;\n                System.out.printf(\"(%d, %d, %d)%c\",\n                                  i - 2, i - 1, i, n % 3 == 0 ? '\\n' : ' ');\n            }\n        }\n    \n        int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n        for (int i = 0; i < limit; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++count;\n            if (count == 200000)\n                s200000 = i;\n            if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n                ++triplets;\n                if (triplets == 5000)\n                    t5000 = i;\n            }\n        }\n    \n        System.out.printf(\"\\nNumber of sphenic numbers < 1,000,000: %d\\n\", count);\n        System.out.printf(\"Number of sphenic triplets < 1,000,000: %d\\n\", triplets);\n    \n        List<Integer> factors = primeFactors(s200000);\n        assert(factors.size() == 3);\n        System.out.printf(\"The 200,000th sphenic number: %d = %d * %d * %d\\n\",\n                          s200000, factors.get(0), factors.get(1),\n                          factors.get(2));\n        System.out.printf(\"The 5,000th sphenic triplet: (%d, %d, %d)\\n\",\n                          t5000 - 2, t5000 - 1, t5000);\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3, sq = 9; sq < limit; p += 2) {\n            if (sieve[p]) {\n                for (int q = sq; q < limit; q += p << 1)\n                    sieve[q] = false;\n            }\n            sq += (p + 1) << 2;\n        }\n        return sieve;\n    }\n    \n    private static List<Integer> primeFactors(int n) {\n        List<Integer> factors = new ArrayList<>();\n        if (n > 1 && (n & 1) == 0) {\n            factors.add(2);\n            while ((n & 1) == 0)\n                n >>= 1;\n        }\n        for (int p = 3; p * p <= n; p += 2) {\n            if (n % p == 0) {\n                factors.add(p);\n                while (n % p == 0)\n                    n /= p;\n            }\n        }\n        if (n > 1)\n            factors.add(n);\n        return factors;\n    }\n}\n", "Python": "\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n    d = factorint(i)\n    if len(d) == 3 and sum(d.values()) == 3:\n        sphenics1m.append(i)\n        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n            sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n    if n < 1000:\n        print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n    else:\n        break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n    if n < 10_000:\n        print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else '  ')\n    else:\n        break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n      'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n"}
{"id": 46579, "name": "Find duplicate files", "Java": "import java.io.*;\nimport java.nio.*;\nimport java.nio.file.*;\nimport java.nio.file.attribute.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class DuplicateFiles {\n    public static void main(String[] args) {\n        if (args.length != 2) {\n            System.err.println(\"Directory name and minimum file size are required.\");\n            System.exit(1);\n        }\n        try {\n            findDuplicateFiles(args[0], Long.parseLong(args[1]));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void findDuplicateFiles(String directory, long minimumSize)\n        throws IOException, NoSuchAlgorithmException {\n        System.out.println(\"Directory: '\" + directory + \"', minimum size: \" + minimumSize + \" bytes.\");\n        Path path = FileSystems.getDefault().getPath(directory);\n        FileVisitor visitor = new FileVisitor(path, minimumSize);\n        Files.walkFileTree(path, visitor);\n        System.out.println(\"The following sets of files have the same size and checksum:\");\n        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {\n            Map<Object, List<String>> map = e.getValue();\n            if (!containsDuplicates(map))\n                continue;\n            List<List<String>> fileSets = new ArrayList<>(map.values());\n            for (List<String> files : fileSets)\n                Collections.sort(files);\n            Collections.sort(fileSets, new StringListComparator());\n            FileKey key = e.getKey();\n            System.out.println();\n            System.out.println(\"Size: \" + key.size_ + \" bytes\");\n            for (List<String> files : fileSets) {\n                for (int i = 0, n = files.size(); i < n; ++i) {\n                    if (i > 0)\n                        System.out.print(\" = \");\n                    System.out.print(files.get(i));\n                }\n                System.out.println();\n            }\n        }\n    }\n\n    private static class StringListComparator implements Comparator<List<String>> {\n        public int compare(List<String> a, List<String> b) {\n            int len1 = a.size(), len2 = b.size();\n            for (int i = 0; i < len1 && i < len2; ++i) {\n                int c = a.get(i).compareTo(b.get(i));\n                if (c != 0)\n                    return c;\n            }\n            return Integer.compare(len1, len2);\n        }\n    }\n\n    private static boolean containsDuplicates(Map<Object, List<String>> map) {\n        if (map.size() > 1)\n            return true;\n        for (List<String> files : map.values()) {\n            if (files.size() > 1)\n                return true;\n        }\n        return false;\n    }\n\n    private static class FileVisitor extends SimpleFileVisitor<Path> {\n        private MessageDigest digest_;\n        private Path directory_;\n        private long minimumSize_;\n        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();\n\n        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {\n            directory_ = directory;\n            minimumSize_ = minimumSize;\n            digest_ = MessageDigest.getInstance(\"MD5\");\n        }\n\n        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n            if (attrs.size() >= minimumSize_) {\n                FileKey key = new FileKey(file, attrs, getMD5Sum(file));\n                Map<Object, List<String>> map = fileMap_.get(key);\n                if (map == null)\n                    fileMap_.put(key, map = new HashMap<>());\n                List<String> files = map.get(attrs.fileKey());\n                if (files == null)\n                    map.put(attrs.fileKey(), files = new ArrayList<>());\n                Path relative = directory_.relativize(file);\n                files.add(relative.toString());\n            }\n            return FileVisitResult.CONTINUE;\n        }\n\n        private byte[] getMD5Sum(Path file) throws IOException {\n            digest_.reset();\n            try (InputStream in = new FileInputStream(file.toString())) {\n                byte[] buffer = new byte[8192];\n                int bytes;\n                while ((bytes = in.read(buffer)) != -1) {\n                    digest_.update(buffer, 0, bytes);\n                }\n            }\n            return digest_.digest();\n        }\n    }\n\n    private static class FileKey implements Comparable<FileKey> {\n        private byte[] hash_;\n        private long size_;\n\n        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {\n            size_ = attrs.size();\n            hash_ = hash;\n        }\n\n        public int compareTo(FileKey other) {\n            int c = Long.compare(other.size_, size_);\n            if (c == 0)\n                c = hashCompare(hash_, other.hash_);\n            return c;\n        }\n    }\n\n    private static int hashCompare(byte[] a, byte[] b) {\n        int len1 = a.length, len2 = b.length;\n        for (int i = 0; i < len1 && i < len2; ++i) {\n            int c = Byte.compare(a[i], b[i]);\n            if (c != 0)\n                return c;\n        }\n        return Integer.compare(len1, len2);\n    }\n}\n", "Python": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n    knownFiles = {}\n\n    \n    for root, dirs, files in os.walk(pth):\n        for fina in files:\n            fullFina = os.path.join(root, fina)\n            isSymLink = os.path.islink(fullFina)\n            if isSymLink:\n                continue \n            si = os.path.getsize(fullFina)\n            if si < minSize:\n                continue\n            if si not in knownFiles:\n                knownFiles[si] = {}\n            h = hashlib.new(hashName)\n            h.update(open(fullFina, \"rb\").read())\n            hashed = h.digest()\n            if hashed in knownFiles[si]:\n                fileRec = knownFiles[si][hashed]\n                fileRec.append(fullFina)\n            else:\n                knownFiles[si][hashed] = [fullFina]\n\n    \n    sizeList = list(knownFiles.keys())\n    sizeList.sort(reverse=True)\n    for si in sizeList:\n        filesAtThisSize = knownFiles[si]\n        for hashVal in filesAtThisSize:\n            if len(filesAtThisSize[hashVal]) < 2:\n                continue\n            fullFinaLi = filesAtThisSize[hashVal]\n            print (\"=======Duplicate=======\")\n            for fullFina in fullFinaLi:\n                st = os.stat(fullFina)\n                isHardLink = st.st_nlink > 1 \n                infoStr = []\n                if isHardLink:\n                    infoStr.append(\"(Hard linked)\")\n                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n                print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n"}
{"id": 46580, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 46581, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 46582, "name": "Order disjoint list items", "Java": "import java.util.Arrays;\nimport java.util.BitSet;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class OrderDisjointItems {\n\n    public static void main(String[] args) {\n        final String[][] MNs = {{\"the cat sat on the mat\", \"mat cat\"},\n        {\"the cat sat on the mat\", \"cat mat\"},\n        {\"A B C A B C A B C\", \"C A C A\"}, {\"A B C A B D A B E\", \"E A D A\"},\n        {\"A B\", \"B\"}, {\"A B\", \"B A\"}, {\"A B B A\", \"B A\"}, {\"X X Y\", \"X\"}};\n\n        for (String[] a : MNs) {\n            String[] r = orderDisjointItems(a[0].split(\" \"), a[1].split(\" \"));\n            System.out.printf(\"%s | %s -> %s%n\", a[0], a[1], Arrays.toString(r));\n        }\n    }\n\n    \n    static String[] orderDisjointItems(String[] m, String[] n) {\n        for (String e : n) {\n            int idx = ArrayUtils.indexOf(m, e);\n            if (idx != -1)\n                m[idx] = null;\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (m[i] == null)\n                m[i] = n[j++];\n        }\n        return m;\n    }\n\n    \n    static String[] orderDisjointItems2(String[] m, String[] n) {\n        BitSet bitSet = new BitSet(m.length);\n        for (String e : n) {\n            int idx = -1;\n            do {\n                idx = ArrayUtils.indexOf(m, e, idx + 1);\n            } while (idx != -1 && bitSet.get(idx));\n            if (idx != -1)\n                bitSet.set(idx);\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (bitSet.get(i))\n                m[i] = n[j++];\n        }\n        return m;\n    }\n}\n", "Python": "from __future__ import print_function\n\ndef order_disjoint_list_items(data, items):\n    \n    itemindices = []\n    for item in set(items):\n        itemcount = items.count(item)\n        \n        lastindex = [-1]\n        for i in range(itemcount):\n            lastindex.append(data.index(item, lastindex[-1] + 1))\n        itemindices += lastindex[1:]\n    itemindices.sort()\n    for index, item in zip(itemindices, items):\n        data[index] = item\n\nif __name__ == '__main__':\n    tostring = ' '.join\n    for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),\n                         (str.split('the cat sat on the mat'), str.split('cat mat')),\n                         (list('ABCABCABC'), list('CACA')),\n                         (list('ABCABDABE'), list('EADA')),\n                         (list('AB'), list('B')),\n                         (list('AB'), list('BA')),\n                         (list('ABBA'), list('BA')),\n                         (list(''), list('')),\n                         (list('A'), list('A')),\n                         (list('AB'), list('')),\n                         (list('ABBA'), list('AB')),\n                         (list('ABAB'), list('AB')),\n                         (list('ABAB'), list('BABA')),\n                         (list('ABCCBA'), list('ACAC')),\n                         (list('ABCCBA'), list('CACA')),\n                       ]:\n        print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')\n        order_disjoint_list_items(data, items)\n        print(\"-> M' %r\" % tostring(data))\n"}
{"id": 46583, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "Python": "print()\n"}
{"id": 46584, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "Python": "print()\n"}
{"id": 46585, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 46586, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n"}
{"id": 46587, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n"}
{"id": 46588, "name": "Most frequent k chars distance", "Java": "import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class SDF {\n\n    \n    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {\n\n        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();\n\n        for (char element : array) {\n            Integer count = countMap.get(element);\n            count = (count == null) ? 1 : count + 1;\n            countMap.put(element, count);\n        }\n\n        return countMap;\n    }\n    \n    \n    private static <K, V extends Comparable<? super V>>\n            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { \n\tList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());\n\t\n\tCollections.sort(list, new Comparator<Map.Entry<K, V>>() {\n\t\tpublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n\t\t    return o2.getValue().compareTo(o1.getValue());\n\t\t}\n\t    });\n\n\t\n\t\n\tHashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();\n\tfor (Map.Entry<K, V> entry : list) {\n\t    sortedHashMap.put(entry.getKey(), entry.getValue());\n\t} \n\treturn sortedHashMap;\n    }\n    \n    public static String mostOcurrencesElement(char[] array, int k) {\n        HashMap<Character, Integer> countMap = countElementOcurrences(array);\n        System.out.println(countMap);\n        Map<Character, Integer> map = descendingSortByValues(countMap); \n        System.out.println(map);\n        int i = 0;\n        String output = \"\";\n        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {\n\t    if (i++ >= k)\n\t\tbreak;\n            output += \"\" + pairs.getKey() + pairs.getValue();\n        }\n        return output;\n    }\n    \n    public static int getDiff(String str1, String str2, int limit) {\n        int similarity = 0;\n\tint k = 0;\n\tfor (int i = 0; i < str1.length() ; i = k) {\n\t    k ++;\n\t    if (Character.isLetter(str1.charAt(i))) {\n\t\tint pos = str2.indexOf(str1.charAt(i));\n\t\t\t\t\n\t\tif (pos >= 0) {\t\n\t\t    String digitStr1 = \"\";\n\t\t    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {\n\t\t\tdigitStr1 += str1.charAt(k);\n\t\t\tk++;\n\t\t    }\n\t\t\t\t\t\n\t\t    int k2 = pos+1;\n\t\t    String digitStr2 = \"\";\n\t\t    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {\n\t\t\tdigitStr2 += str2.charAt(k2);\n\t\t\tk2++;\n\t\t    }\n\t\t\t\t\t\n\t\t    similarity += Integer.parseInt(digitStr2)\n\t\t\t+ Integer.parseInt(digitStr1);\n\t\t\t\t\t\n\t\t} \n\t    }\n\t}\n\treturn Math.abs(limit - similarity);\n    }\n    \n    public static int SDFfunc(String str1, String str2, int limit) {\n        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);\n    }\n\n    public static void main(String[] args) {\n        String input1 = \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\";\n        String input2 = \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\";\n        System.out.println(SDF.SDFfunc(input1,input2,100));\n\n    }\n\n}\n", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n"}
{"id": 46589, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n"}
{"id": 46590, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n"}
{"id": 46591, "name": "Lychrel numbers", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 46592, "name": "Lychrel numbers", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 46593, "name": "Sierpinski square curve", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n"}
{"id": 46594, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 46595, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 46596, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 46597, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 46598, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 46599, "name": "Odd words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class OddWords {\n    public static void main(String[] args) {\n        try {\n            Set<String> dictionary = new TreeSet<>();\n            final int minLength = 5;\n            String fileName = \"unixdict.txt\";\n            if (args.length != 0)\n                fileName = args[0];\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        dictionary.add(line);\n                }\n            }\n            StringBuilder word1 = new StringBuilder();\n            StringBuilder word2 = new StringBuilder();\n            List<StringPair> evenWords = new ArrayList<>();\n            List<StringPair> oddWords = new ArrayList<>();\n            for (String word : dictionary) {\n                int length = word.length();\n                if (length < minLength + 2 * (minLength/2))\n                    continue;\n                word1.setLength(0);\n                word2.setLength(0);\n                for (int i = 0; i < length; ++i) {\n                    if ((i & 1) == 0)\n                        word1.append(word.charAt(i));\n                    else\n                        word2.append(word.charAt(i));\n                }\n                String oddWord = word1.toString();\n                String evenWord = word2.toString();\n                if (dictionary.contains(oddWord))\n                    oddWords.add(new StringPair(word, oddWord));\n                if (dictionary.contains(evenWord))\n                    evenWords.add(new StringPair(word, evenWord));\n            }\n            System.out.println(\"Odd words:\");\n            printWords(oddWords);\n            System.out.println(\"\\nEven words:\");\n            printWords(evenWords);\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n\n    private static void printWords(List<StringPair> strings) {\n        int n = 1;\n        for (StringPair pair : strings) {\n            System.out.printf(\"%2d: %-14s%s\\n\", n++,\n                                    pair.string1, pair.string2);\n        }\n    }\n\n    private static class StringPair {\n        private String string1;\n        private String string2;\n        private StringPair(String s1, String s2) {\n            string1 = s1;\n            string2 = s2;\n        }\n    }\n}\n", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n"}
{"id": 46600, "name": "Ramanujan's constant", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 46601, "name": "Ramanujan's constant", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 46602, "name": "Word break problem", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46603, "name": "Word break problem", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46604, "name": "Brilliant numbers", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n"}
{"id": 46605, "name": "Brilliant numbers", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n"}
{"id": 46606, "name": "Word ladder", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n"}
{"id": 46607, "name": "Word ladder", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n"}
{"id": 46608, "name": "Earliest difference between prime gaps", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n", "Python": "\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n    if pri[i] - pri[i - 1] not in gapstarts:\n        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n    while GAP1 not in gapstarts:\n        GAP1 += 2\n    start1 = gapstarts[GAP1]\n    GAP2 = GAP1 + 2\n    if GAP2 not in gapstarts:\n        GAP1 = GAP2 + 2\n        continue\n    start2 = gapstarts[GAP2]\n    diff = abs(start2 - start1)\n    if diff > PM:\n        print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n        print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n        if PM == LIMIT:\n            break\n        PM *= 10\n    else:\n        GAP1 = GAP2\n"}
{"id": 46609, "name": "Latin Squares in reduced form", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n"}
{"id": 46610, "name": "UPC", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 46611, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 46612, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 46613, "name": "Closest-pair problem", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 46614, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 46615, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 46616, "name": "Color wheel", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n"}
{"id": 46617, "name": "Plasma effect", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n"}
{"id": 46618, "name": "Plasma effect", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n"}
{"id": 46619, "name": "Hello world_Newbie", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n", "Python": "print \"Goodbye, World!\"\n"}
{"id": 46620, "name": "Hello world_Newbie", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n", "Python": "print \"Goodbye, World!\"\n"}
{"id": 46621, "name": "Polymorphism", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 46622, "name": "Wagstaff primes", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n"}
{"id": 46623, "name": "Wagstaff primes", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n"}
{"id": 46624, "name": "Wagstaff primes", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n"}
{"id": 46625, "name": "Create an object_Native demonstration", "Java": "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\npublic class ImmutableMap {\n\n    public static void main(String[] args) {\n        Map<String,Integer> hashMap = getImmutableMap();\n        try {\n            hashMap.put(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put new value.\");\n        }\n        try {\n            hashMap.clear();\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to clear map.\");\n        }\n        try {\n            hashMap.putIfAbsent(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put if absent.\");\n        }\n        \n        for ( String key : hashMap.keySet() ) {\n            System.out.printf(\"key = %s, value = %s%n\", key, hashMap.get(key));\n        }\n    }\n    \n    private static Map<String,Integer> getImmutableMap() {\n        Map<String,Integer> hashMap = new HashMap<>();\n        hashMap.put(\"Key 1\", 34);\n        hashMap.put(\"Key 2\", 105);\n        hashMap.put(\"Key 3\", 144);\n\n        return Collections.unmodifiableMap(hashMap);\n    }\n    \n}\n", "Python": "from collections import UserDict\nimport copy\n\nclass Dict(UserDict):\n    \n    def __init__(self, dict=None, **kwargs):\n        self.__init = True\n        super().__init__(dict, **kwargs)\n        self.default = copy.deepcopy(self.data)\n        self.__init = False\n    \n    def __delitem__(self, key):\n        if key in self.default:\n            self.data[key] = self.default[key]\n        else:\n            raise NotImplementedError\n\n    def __setitem__(self, key, item):\n        if self.__init:\n            super().__setitem__(key, item)\n        elif key in self.data:\n            self.data[key] = item\n        else:\n            raise KeyError\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, super().__repr__())\n    \n    def fromkeys(cls, iterable, value=None):\n        if self.__init:\n            super().fromkeys(cls, iterable, value)\n        else:\n            for key in iterable:\n                if key in self.data:\n                    self.data[key] = value\n                else:\n                    raise KeyError\n\n    def clear(self):\n        self.data.update(copy.deepcopy(self.default))\n\n    def pop(self, key, default=None):\n        raise NotImplementedError\n\n    def popitem(self):\n        raise NotImplementedError\n\n    def update(self, E, **F):\n        if self.__init:\n            super().update(E, **F)\n        else:\n            haskeys = False\n            try:\n                keys = E.keys()\n                haskeys = Ture\n            except AttributeError:\n                pass\n            if haskeys:\n                for key in keys:\n                    self[key] = E[key]\n            else:\n                for key, val in E:\n                    self[key] = val\n            for key in F:\n                self[key] = F[key]\n\n    def setdefault(self, key, default=None):\n        if key not in self.data:\n            raise KeyError\n        else:\n            return super().setdefault(key, default)\n"}
{"id": 46626, "name": "Rare numbers", "Java": "import java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\n\npublic class RareNumbers {\n    public interface Consumer5<A, B, C, D, E> {\n        void apply(A a, B b, C c, D d, E e);\n    }\n\n    public interface Consumer7<A, B, C, D, E, F, G> {\n        void apply(A a, B b, C c, D d, E e, F f, G g);\n    }\n\n    public interface Recursable5<A, B, C, D, E> {\n        void apply(A a, B b, C c, D d, E e, Recursable5<A, B, C, D, E> r);\n    }\n\n    public interface Recursable7<A, B, C, D, E, F, G> {\n        void apply(A a, B b, C c, D d, E e, F f, G g, Recursable7<A, B, C, D, E, F, G> r);\n    }\n\n    public static <A, B, C, D, E> Consumer5<A, B, C, D, E> recurse(Recursable5<A, B, C, D, E> r) {\n        return (a, b, c, d, e) -> r.apply(a, b, c, d, e, r);\n    }\n\n    public static <A, B, C, D, E, F, G> Consumer7<A, B, C, D, E, F, G> recurse(Recursable7<A, B, C, D, E, F, G> r) {\n        return (a, b, c, d, e, f, g) -> r.apply(a, b, c, d, e, f, g, r);\n    }\n\n    private static class Term {\n        long coeff;\n        byte ix1, ix2;\n\n        public Term(long coeff, byte ix1, byte ix2) {\n            this.coeff = coeff;\n            this.ix1 = ix1;\n            this.ix2 = ix2;\n        }\n    }\n\n    private static final int MAX_DIGITS = 16;\n\n    private static long toLong(List<Byte> digits, boolean reverse) {\n        long sum = 0;\n        if (reverse) {\n            for (int i = digits.size() - 1; i >= 0; --i) {\n                sum = sum * 10 + digits.get(i);\n            }\n        } else {\n            for (Byte digit : digits) {\n                sum = sum * 10 + digit;\n            }\n        }\n        return sum;\n    }\n\n    private static boolean isNotSquare(long n) {\n        long root = (long) Math.sqrt(n);\n        return root * root != n;\n    }\n\n    private static List<Byte> seq(byte from, byte to, byte step) {\n        List<Byte> res = new ArrayList<>();\n        for (byte i = from; i <= to; i += step) {\n            res.add(i);\n        }\n        return res;\n    }\n\n    private static String commatize(long n) {\n        String s = String.valueOf(n);\n        int le = s.length();\n        int i = le - 3;\n        while (i >= 1) {\n            s = s.substring(0, i) + \",\" + s.substring(i);\n            i -= 3;\n        }\n        return s;\n    }\n\n    public static void main(String[] args) {\n        final LocalDateTime startTime = LocalDateTime.now();\n        long pow = 1L;\n        System.out.println(\"Aggregate timings to process all numbers up to:\");\n        \n        List<List<Term>> allTerms = new ArrayList<>();\n        for (int i = 0; i < MAX_DIGITS - 1; ++i) {\n            allTerms.add(new ArrayList<>());\n        }\n        for (int r = 2; r <= MAX_DIGITS; ++r) {\n            List<Term> terms = new ArrayList<>();\n            pow *= 10;\n            long pow1 = pow;\n            long pow2 = 1;\n            byte i1 = 0;\n            byte i2 = (byte) (r - 1);\n            while (i1 < i2) {\n                terms.add(new Term(pow1 - pow2, i1, i2));\n\n                pow1 /= 10;\n                pow2 *= 10;\n\n                i1++;\n                i2--;\n            }\n            allTerms.set(r - 2, terms);\n        }\n        \n        Map<Byte, List<List<Byte>>> fml = Map.of(\n            (byte) 0, List.of(List.of((byte) 2, (byte) 2), List.of((byte) 8, (byte) 8)),\n            (byte) 1, List.of(List.of((byte) 6, (byte) 5), List.of((byte) 8, (byte) 7)),\n            (byte) 4, List.of(List.of((byte) 4, (byte) 0)),\n            (byte) 6, List.of(List.of((byte) 6, (byte) 0), List.of((byte) 8, (byte) 2))\n        );\n        \n        Map<Byte, List<List<Byte>>> dmd = new HashMap<>();\n        for (int i = 0; i < 100; ++i) {\n            List<Byte> a = List.of((byte) (i / 10), (byte) (i % 10));\n\n            int d = a.get(0) - a.get(1);\n            dmd.computeIfAbsent((byte) d, k -> new ArrayList<>()).add(a);\n        }\n        List<Byte> fl = List.of((byte) 0, (byte) 1, (byte) 4, (byte) 6);\n        List<Byte> dl = seq((byte) -9, (byte) 9, (byte) 1); \n        List<Byte> zl = List.of((byte) 0);                  \n        List<Byte> el = seq((byte) -8, (byte) 8, (byte) 2); \n        List<Byte> ol = seq((byte) -9, (byte) 9, (byte) 2); \n        List<Byte> il = seq((byte) 0, (byte) 9, (byte) 1);\n        List<Long> rares = new ArrayList<>();\n        List<List<List<Byte>>> lists = new ArrayList<>();\n        for (int i = 0; i < 4; ++i) {\n            lists.add(new ArrayList<>());\n        }\n        for (int i = 0; i < fl.size(); ++i) {\n            List<List<Byte>> temp1 = new ArrayList<>();\n            List<Byte> temp2 = new ArrayList<>();\n            temp2.add(fl.get(i));\n            temp1.add(temp2);\n            lists.set(i, temp1);\n        }\n        final AtomicReference<List<Byte>> digits = new AtomicReference<>(new ArrayList<>());\n        AtomicInteger count = new AtomicInteger();\n\n        \n        \n        Consumer7<List<Byte>, List<Byte>, List<List<Byte>>, List<List<Byte>>, Long, Integer, Integer> fnpr = recurse((cand, di, dis, indicies, nmr, nd, level, func) -> {\n            if (level == dis.size()) {\n                digits.get().set(indicies.get(0).get(0), fml.get(cand.get(0)).get(di.get(0)).get(0));\n                digits.get().set(indicies.get(0).get(1), fml.get(cand.get(0)).get(di.get(0)).get(1));\n                int le = di.size();\n                if (nd % 2 == 1) {\n                    le--;\n                    digits.get().set(nd / 2, di.get(le));\n                }\n                for (int i = 1; i < le; ++i) {\n                    digits.get().set(indicies.get(i).get(0), dmd.get(cand.get(i)).get(di.get(i)).get(0));\n                    digits.get().set(indicies.get(i).get(1), dmd.get(cand.get(i)).get(di.get(i)).get(1));\n                }\n                long r = toLong(digits.get(), true);\n                long npr = nmr + 2 * r;\n                if (isNotSquare(npr)) {\n                    return;\n                }\n                count.getAndIncrement();\n                System.out.printf(\"     R/N %2d:\", count.get());\n                LocalDateTime checkPoint = LocalDateTime.now();\n                long elapsed = Duration.between(startTime, checkPoint).toMillis();\n                System.out.printf(\"  %9sms\", elapsed);\n                long n = toLong(digits.get(), false);\n                System.out.printf(\"  (%s)\\n\", commatize(n));\n                rares.add(n);\n            } else {\n                for (Byte num : dis.get(level)) {\n                    di.set(level, num);\n                    func.apply(cand, di, dis, indicies, nmr, nd, level + 1, func);\n                }\n            }\n        });\n\n        \n        Consumer5<List<Byte>, List<List<Byte>>, List<List<Byte>>, Integer, Integer> fnmr = recurse((cand, list, indicies, nd, level, func) -> {\n            if (level == list.size()) {\n                long nmr = 0;\n                long nmr2 = 0;\n                List<Term> terms = allTerms.get(nd - 2);\n                for (int i = 0; i < terms.size(); ++i) {\n                    Term t = terms.get(i);\n                    if (cand.get(i) >= 0) {\n                        nmr += t.coeff * cand.get(i);\n                    } else {\n                        nmr2 += t.coeff * -cand.get(i);\n                        if (nmr >= nmr2) {\n                            nmr -= nmr2;\n                            nmr2 = 0;\n                        } else {\n                            nmr2 -= nmr;\n                            nmr = 0;\n                        }\n                    }\n                }\n                if (nmr2 >= nmr) {\n                    return;\n                }\n                nmr -= nmr2;\n                if (isNotSquare(nmr)) {\n                    return;\n                }\n                List<List<Byte>> dis = new ArrayList<>();\n                dis.add(seq((byte) 0, (byte) (fml.get(cand.get(0)).size() - 1), (byte) 1));\n                for (int i = 1; i < cand.size(); ++i) {\n                    dis.add(seq((byte) 0, (byte) (dmd.get(cand.get(i)).size() - 1), (byte) 1));\n                }\n                if (nd % 2 == 1) {\n                    dis.add(il);\n                }\n                List<Byte> di = new ArrayList<>();\n                for (int i = 0; i < dis.size(); ++i) {\n                    di.add((byte) 0);\n                }\n                fnpr.apply(cand, di, dis, indicies, nmr, nd, 0);\n            } else {\n                for (Byte num : list.get(level)) {\n                    cand.set(level, num);\n                    func.apply(cand, list, indicies, nd, level + 1, func);\n                }\n            }\n        });\n\n        for (int nd = 2; nd <= MAX_DIGITS; ++nd) {\n            digits.set(new ArrayList<>());\n            for (int i = 0; i < nd; ++i) {\n                digits.get().add((byte) 0);\n            }\n            if (nd == 4) {\n                lists.get(0).add(zl);\n                lists.get(1).add(ol);\n                lists.get(2).add(el);\n                lists.get(3).add(ol);\n            } else if (allTerms.get(nd - 2).size() > lists.get(0).size()) {\n                for (int i = 0; i < 4; ++i) {\n                    lists.get(i).add(dl);\n                }\n            }\n            List<List<Byte>> indicies = new ArrayList<>();\n            for (Term t : allTerms.get(nd - 2)) {\n                indicies.add(List.of(t.ix1, t.ix2));\n            }\n            for (List<List<Byte>> list : lists) {\n                List<Byte> cand = new ArrayList<>();\n                for (int i = 0; i < list.size(); ++i) {\n                    cand.add((byte) 0);\n                }\n                fnmr.apply(cand, list, indicies, nd, 0);\n            }\n            LocalDateTime checkPoint = LocalDateTime.now();\n            long elapsed = Duration.between(startTime, checkPoint).toMillis();\n            System.out.printf(\"  %2d digits:  %9sms\\n\", nd, elapsed);\n        }\n\n        Collections.sort(rares);\n        System.out.printf(\"\\nThe rare numbers with up to %d digits are:\\n\", MAX_DIGITS);\n        for (int i = 0; i < rares.size(); ++i) {\n            System.out.printf(\"  %2d:  %25s\\n\", i + 1, commatize(rares.get(i)));\n        }\n    }\n}\n", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n"}
{"id": 46627, "name": "Arithmetic evaluation", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n"}
{"id": 46628, "name": "Arithmetic evaluation", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n"}
{"id": 46629, "name": "Special variables", "Java": "import java.util.Arrays;\n\npublic class SpecialVariables {\n\n    public static void main(String[] args) {\n\n        \n        \n        System.out.println(Arrays.toString(args));\n\n        \n        \n        System.out.println(SpecialVariables.class);\n\n\n        \n\n        \n        System.out.println(System.getenv());\n\n        \n        \n        System.out.println(System.getProperties());\n\n        \n        \n        System.out.println(Runtime.getRuntime().availableProcessors());\n\n    }\n}\n", "Python": "names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))\nprint( '\\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )\n"}
{"id": 46630, "name": "Execute CopyPasta Language", "Java": "import java.io.File;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class Copypasta\n{\n\t\n\tpublic static void fatal_error(String errtext)\n\t{\n\t\tStackTraceElement[] stack = Thread.currentThread().getStackTrace();\n\t\tStackTraceElement main = stack[stack.length - 1];\n\t\tString mainClass = main.getClassName();\n\t\tSystem.out.println(\"%\" + errtext);\n\t\tSystem.out.println(\"usage: \" + mainClass + \" [filename.cp]\");\n\t\tSystem.exit(1);\n\t}\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tString fname = null;\n\t\tString source = null;\n\t\ttry\n\t\t{\n\t\t\tfname = args[0];\n\t\t\tsource = new String(Files.readAllBytes(new File(fname).toPath()));\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tfatal_error(\"error while trying to read from specified file\");\n\t\t}\n\n\t\t\n\t\tArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split(\"\\n\")));\n\t\t\n\t\t\n\t\tString clipboard = \"\";\n\t\t\n\t\t\n\t\tint loc = 0;\n\t\twhile(loc < lines.size())\n\t\t{\n\t\t\t\n\t\t\tString command = lines.get(loc).trim();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(command.equals(\"Copy\"))\n\t\t\t\t\tclipboard += lines.get(loc + 1);\n\t\t\t\telse if(command.equals(\"CopyFile\"))\n\t\t\t\t{\n\t\t\t\t\tif(lines.get(loc + 1).equals(\"TheF*ckingCode\"))\n\t\t\t\t\t\tclipboard += source;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tString filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));\n\t\t\t\t\t\tclipboard += filetext;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Duplicate\"))\n\t\t\t\t{\n\t\t\t\t\tString origClipboard = clipboard;\n\n\t\t\t\t\tint amount = Integer.parseInt(lines.get(loc + 1)) - 1;\n\t\t\t\t\tfor(int i = 0; i < amount; i++)\n\t\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Pasta!\"))\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(clipboard);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\n\t\t\t\n\t\t\tloc += 2;\n\t\t}\n\t}\n}\n", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n"}
{"id": 46631, "name": "Reflection_List properties", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 46632, "name": "Minimal steps down to 1", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MinimalStepsDownToOne {\n\n    public static void main(String[] args) {\n        runTasks(getFunctions1());\n        runTasks(getFunctions2());\n        runTasks(getFunctions3());\n    }\n    \n    private static void runTasks(List<Function> functions) {\n        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);\n\n        \n        int max = 10;\n        populateMap(minPath, functions, max);\n        System.out.printf(\"%nWith functions:  %s%n\", functions);\n        System.out.printf(\"  Minimum steps to 1:%n\");\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int steps = minPath.get(n).size();\n            System.out.printf(\"    %2d: %d step%1s: %s%n\", n, steps, steps == 1 ? \"\" : \"s\", minPath.get(n));\n        }\n        \n        \n        displayMaxMin(minPath, functions, 2000);\n\n        \n        displayMaxMin(minPath, functions, 20000);\n\n        \n        displayMaxMin(minPath, functions, 100000);\n    }\n    \n    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        populateMap(minPath, functions, max);\n        List<Integer> maxIntegers = getMaxMin(minPath, max);\n        int maxSteps = maxIntegers.remove(0);\n        int numCount = maxIntegers.size();\n        System.out.printf(\"  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n\", numCount == 1 ? \"is\" : \"are\", numCount, numCount == 1 ? \"\" : \"s\", max, maxSteps, maxIntegers);\n        \n    }\n    \n    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {\n        int maxSteps = Integer.MIN_VALUE;\n        List<Integer> maxIntegers = new ArrayList<Integer>();\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int len = minPath.get(n).size();\n            if ( len > maxSteps ) {\n                maxSteps = len;\n                maxIntegers.clear();\n                maxIntegers.add(n);\n            }\n            else if ( len == maxSteps ) {\n                maxIntegers.add(n);\n            }\n        }\n        maxIntegers.add(0, maxSteps);\n        return maxIntegers;\n    }\n\n    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        for ( int n = 2 ; n <= max ; n++ ) {\n            if ( minPath.containsKey(n) ) {\n                continue;\n            }\n            Function minFunction = null;\n            int minSteps = Integer.MAX_VALUE;\n            for ( Function f : functions ) {\n                if ( f.actionOk(n) ) {\n                    int result = f.action(n);\n                    int steps = 1 + minPath.get(result).size();\n                    if ( steps < minSteps ) {\n                        minFunction = f;\n                        minSteps = steps;\n                    }\n                }\n            }\n            int result = minFunction.action(n);\n            List<String> path = new ArrayList<String>();\n            path.add(minFunction.toString(n));\n            path.addAll(minPath.get(result));\n            minPath.put(n, path);\n        }\n        \n    }\n\n    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {\n        Map<Integer,List<String>> minPath = new HashMap<>();\n        for ( int i = 2 ; i <= max ; i++ ) {\n            for ( Function f : functions ) {\n                if ( f.actionOk(i) ) {\n                    int result = f.action(i);\n                    if ( result == 1 ) {\n                        List<String> path = new ArrayList<String>();\n                        path.add(f.toString(i));\n                        minPath.put(i, path);\n                    }\n                }\n            }\n        }\n        return minPath;\n    }\n\n    private static List<Function> getFunctions3() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide2Function());\n        functions.add(new Divide3Function());\n        functions.add(new Subtract2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions2() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract2Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions1() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n    \n    public abstract static class Function {\n        abstract public int action(int n);\n        abstract public boolean actionOk(int n);\n        abstract public String toString(int n);\n    }\n    \n    public static class Divide2Function extends Function {\n        @Override public int action(int n) {\n            return n/2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 2 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/2 -> \" + n/2;\n        }\n        \n        @Override public String toString() {\n            return \"Divisor 2\";\n        }\n        \n    }\n\n    public static class Divide3Function extends Function {\n        @Override public int action(int n) {\n            return n/3;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 3 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/3 -> \" + n/3;\n        }\n\n        @Override public String toString() {\n            return \"Divisor 3\";\n        }\n\n    }\n\n    public static class Subtract1Function extends Function {\n        @Override public int action(int n) {\n            return n-1;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return true;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-1 -> \" + (n-1);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 1\";\n        }\n\n    }\n\n    public static class Subtract2Function extends Function {\n        @Override public int action(int n) {\n            return n-2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n > 2;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-2 -> \" + (n-2);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 2\";\n        }\n\n    }\n\n}\n", "Python": "from functools import lru_cache\n\n\n\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n    \"Recursive, memoised minimised steps to 1\"\n\n    def __init__(self, divs=DIVS, subs=SUBS):\n        self.divs, self.subs = divs, subs\n\n    @lru_cache(maxsize=None)\n    def _minrec(self, n):\n        \"Recursive, memoised\"\n        if n == 1:\n            return 0, ['=1']\n        possibles = {}\n        for d in self.divs:\n            if n % d == 0:\n                possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n        for s in self.subs:\n            if n > s:\n                possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n        thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n        ret = 1 + count, [thiskind] + otherkinds\n        return ret\n\n    def __call__(self, n):\n        \"Recursive, memoised\"\n        ans = self._minrec(n)[1][:-1]\n        return len(ans), ans\n\n\nif __name__ == '__main__':\n    for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n        minrec = Minrec(DIVS, SUBS)\n        print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n        print('  Possible divisors:  ', DIVS)\n        print('  Possible decrements:', SUBS)\n        for n in range(1, 11):\n            steps, how = minrec(n)\n            print(f'    minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n        upto = 2000\n        print(f'\\n    Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n        stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n        mx = stepn[-1][0]\n        ans = [x[1] for x in stepn if x[0] == mx]\n        print('      Taking', mx, f'steps is/are the {len(ans)} numbers:',\n              ', '.join(str(n) for n in sorted(ans)))\n        \n        print()\n"}
{"id": 46633, "name": "Align columns", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 46634, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 46635, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 46636, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 46637, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 46638, "name": "Dynamic variable names", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n"}
{"id": 46639, "name": "Data Encryption Standard", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n", "Python": "\n\n\n\nIP = (\n    58, 50, 42, 34, 26, 18, 10, 2,\n    60, 52, 44, 36, 28, 20, 12, 4,\n    62, 54, 46, 38, 30, 22, 14, 6,\n    64, 56, 48, 40, 32, 24, 16, 8,\n    57, 49, 41, 33, 25, 17, 9,  1,\n    59, 51, 43, 35, 27, 19, 11, 3,\n    61, 53, 45, 37, 29, 21, 13, 5,\n    63, 55, 47, 39, 31, 23, 15, 7\n)\nIP_INV = (\n    40,  8, 48, 16, 56, 24, 64, 32,\n    39,  7, 47, 15, 55, 23, 63, 31,\n    38,  6, 46, 14, 54, 22, 62, 30,\n    37,  5, 45, 13, 53, 21, 61, 29,\n    36,  4, 44, 12, 52, 20, 60, 28,\n    35,  3, 43, 11, 51, 19, 59, 27,\n    34,  2, 42, 10, 50, 18, 58, 26,\n    33,  1, 41,  9, 49, 17, 57, 25\n)\nPC1 = (\n    57, 49, 41, 33, 25, 17, 9,\n    1,  58, 50, 42, 34, 26, 18,\n    10, 2,  59, 51, 43, 35, 27,\n    19, 11, 3,  60, 52, 44, 36,\n    63, 55, 47, 39, 31, 23, 15,\n    7,  62, 54, 46, 38, 30, 22,\n    14, 6,  61, 53, 45, 37, 29,\n    21, 13, 5,  28, 20, 12, 4\n)\nPC2 = (\n    14, 17, 11, 24, 1,  5,\n    3,  28, 15, 6,  21, 10,\n    23, 19, 12, 4,  26, 8,\n    16, 7,  27, 20, 13, 2,\n    41, 52, 31, 37, 47, 55,\n    30, 40, 51, 45, 33, 48,\n    44, 49, 39, 56, 34, 53,\n    46, 42, 50, 36, 29, 32\n)\n\nE  = (\n    32, 1,  2,  3,  4,  5,\n    4,  5,  6,  7,  8,  9,\n    8,  9,  10, 11, 12, 13,\n    12, 13, 14, 15, 16, 17,\n    16, 17, 18, 19, 20, 21,\n    20, 21, 22, 23, 24, 25,\n    24, 25, 26, 27, 28, 29,\n    28, 29, 30, 31, 32, 1\n)\n\nSboxes = {\n    0: (\n        14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7,\n        0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8,\n        4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0,\n        15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13\n    ),\n    1: (\n        15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10,\n        3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5,\n        0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15,\n        13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9 \n    ),\n    2: (\n        10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8,\n        13,  7,  0,  9,  3,  4,  6, 10,  2,  8,  5, 14, 12, 11, 15,  1,\n        13,  6,  4,  9,  8, 15,  3,  0, 11,  1,  2, 12,  5, 10, 14,  7,\n        1, 10, 13,  0,  6,  9,  8,  7,  4, 15, 14,  3, 11,  5,  2, 12 \n    ),\n    3: (\n        7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15,\n        13,  8, 11,  5,  6, 15,  0,  3,  4,  7,  2, 12,  1, 10, 14,  9,\n        10,  6,  9,  0, 12, 11,  7, 13, 15,  1,  3, 14,  5,  2,  8,  4,\n        3, 15,  0,  6, 10,  1, 13,  8,  9,  4,  5, 11, 12,  7,  2, 14\n    ),\n    4: (\n        2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9,\n        14, 11,  2, 12,  4,  7, 13,  1,  5,  0, 15, 10,  3,  9,  8,  6,\n        4,  2,  1, 11, 10, 13,  7,  8, 15,  9, 12,  5,  6,  3,  0, 14,\n        11,  8, 12,  7,  1, 14,  2, 13,  6, 15,  0,  9, 10,  4,  5,  3\n    ),\n    5: (\n        12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11,\n        10, 15,  4,  2,  7, 12,  9,  5,  6,  1, 13, 14,  0, 11,  3,  8,\n        9, 14, 15,  5,  2,  8, 12,  3,  7,  0,  4, 10,  1, 13, 11,  6,\n        4,  3,  2, 12,  9,  5, 15, 10, 11, 14,  1,  7,  6,  0,  8, 13\n    ),\n    6: (\n        4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1,\n        13,  0, 11,  7,  4,  9,  1, 10, 14,  3,  5, 12,  2, 15,  8,  6,\n        1,  4, 11, 13, 12,  3,  7, 14, 10, 15,  6,  8,  0,  5,  9,  2,\n        6, 11, 13,  8,  1,  4, 10,  7,  9,  5,  0, 15, 14,  2,  3, 12\n    ),\n    7: (\n        13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7,\n        1, 15, 13,  8, 10,  3,  7,  4, 12,  5,  6, 11,  0, 14,  9,  2,\n        7, 11,  4,  1,  9, 12, 14,  2,  0,  6, 10, 13, 15,  3,  5,  8,\n        2,  1, 14,  7,  4, 10,  8, 13, 15, 12,  9,  0,  3,  5,  6, 11\n    )\n}\n\nP = (\n    16,  7, 20, 21,\n    29, 12, 28, 17,\n    1, 15, 23, 26,\n    5, 18, 31, 10,\n    2,  8, 24, 14,\n    32, 27,  3,  9,\n    19, 13, 30,  6,\n    22, 11, 4,  25\n)\n    \ndef encrypt(msg, key, decrypt=False):\n    \n    assert isinstance(msg, int) and isinstance(key, int)\n    assert not msg.bit_length() > 64\n    assert not key.bit_length() > 64\n\n    \n    key = permutation_by_table(key, 64, PC1) \n\n    \n    \n    C0 = key >> 28\n    D0 = key & (2**28-1)\n    round_keys = generate_round_keys(C0, D0) \n\n    msg_block = permutation_by_table(msg, 64, IP)\n    L0 = msg_block >> 32\n    R0 = msg_block & (2**32-1)\n\n    \n    L_last = L0\n    R_last = R0\n    for i in range(1,17):\n        if decrypt: \n            i = 17-i\n        L_round = R_last\n        R_round = L_last ^ round_function(R_last, round_keys[i])\n        L_last = L_round\n        R_last = R_round\n\n    \n    cipher_block = (R_round<<32) + L_round\n\n    \n    cipher_block = permutation_by_table(cipher_block, 64, IP_INV)\n\n    return cipher_block\n\ndef round_function(Ri, Ki):\n    \n    Ri = permutation_by_table(Ri, 32, E)\n\n    \n    Ri ^= Ki\n\n    \n    Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)]\n\n    \n    for i, block in enumerate(Ri_blocks):\n        \n        row = ((0b100000 & block) >> 4) + (0b1 & block)\n        col = (0b011110 & block) >> 1\n        \n        Ri_blocks[i] = Sboxes[i][16*row+col]\n\n    \n    Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0))\n    Ri = 0\n    for block, lshift_val in Ri_blocks:\n        Ri += (block << lshift_val)\n\n    \n    Ri = permutation_by_table(Ri, 32, P)\n\n    return Ri\n\ndef permutation_by_table(block, block_len, table):\n    \n    block_str = bin(block)[2:].zfill(block_len)\n    perm = []\n    for pos in range(len(table)):\n        perm.append(block_str[table[pos]-1])\n    return int(''.join(perm), 2)\n\ndef generate_round_keys(C0, D0):\n    \n\n    round_keys = dict.fromkeys(range(0,17))\n    lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1)\n\n    \n    lrot = lambda val, r_bits, max_bits: \\\n    (val << r_bits%max_bits) & (2**max_bits-1) | \\\n    ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))\n\n    \n    C0 = lrot(C0, 0, 28)\n    D0 = lrot(D0, 0, 28)\n    round_keys[0] = (C0, D0)\n\n    \n    for i, rot_val in enumerate(lrot_values):\n        i+=1\n        Ci = lrot(round_keys[i-1][0], rot_val, 28)\n        Di = lrot(round_keys[i-1][1], rot_val, 28)\n        round_keys[i] = (Ci, Di)\n\n    \n    \n    \n    del round_keys[0]\n\n    \n    for i, (Ci, Di) in round_keys.items():\n        Ki = (Ci << 28) + Di\n        round_keys[i] = permutation_by_table(Ki, 56, PC2) \n\n    return round_keys\n\nk = 0x0e329232ea6d0d73 \nk2 = 0x133457799BBCDFF1\nm = 0x8787878787878787\nm2 = 0x0123456789ABCDEF\n\ndef prove(key, msg):\n    print('key:       {:x}'.format(key))\n    print('message:   {:x}'.format(msg))\n    cipher_text = encrypt(msg, key)\n    print('encrypted: {:x}'.format(cipher_text))\n    plain_text = encrypt(cipher_text, key, decrypt=True)\n    print('decrypted: {:x}'.format(plain_text))\n\nprove(k, m)\nprint('----------')\nprove(k2, m2)\n"}
{"id": 46640, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n"}
{"id": 46641, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n"}
{"id": 46642, "name": "Commatizing numbers", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n"}
{"id": 46643, "name": "Arithmetic coding_As a generalized change of radix", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n"}
{"id": 46644, "name": "Kosaraju", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n"}
{"id": 46645, "name": "Reflection_List methods", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n"}
{"id": 46646, "name": "Comments", "Java": "\nInt i = 0;     \n", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n"}
{"id": 46647, "name": "Pentomino tiling", "Java": "package pentominotiling;\n\nimport java.util.*;\n\npublic class PentominoTiling {\n\n    static final char[] symbols = \"FILNPTUVWXYZ-\".toCharArray();\n    static final Random rand = new Random();\n\n    static final int nRows = 8;\n    static final int nCols = 8;\n    static final int blank = 12;\n\n    static int[][] grid = new int[nRows][nCols];\n    static boolean[] placed = new boolean[symbols.length - 1];\n\n    public static void main(String[] args) {\n        shuffleShapes();\n\n        for (int r = 0; r < nRows; r++)\n            Arrays.fill(grid[r], -1);\n\n        for (int i = 0; i < 4; i++) {\n            int randRow, randCol;\n            do {\n                randRow = rand.nextInt(nRows);\n                randCol = rand.nextInt(nCols);\n            } while (grid[randRow][randCol] == blank);\n            grid[randRow][randCol] = blank;\n        }\n\n        if (solve(0, 0)) {\n            printResult();\n        } else {\n            System.out.println(\"no solution\");\n        }\n    }\n\n    static void shuffleShapes() {\n        int n = shapes.length;\n        while (n > 1) {\n            int r = rand.nextInt(n--);\n\n            int[][] tmp = shapes[r];\n            shapes[r] = shapes[n];\n            shapes[n] = tmp;\n\n            char tmpSymbol = symbols[r];\n            symbols[r] = symbols[n];\n            symbols[n] = tmpSymbol;\n        }\n    }\n\n    static void printResult() {\n        for (int[] r : grid) {\n            for (int i : r)\n                System.out.printf(\"%c \", symbols[i]);\n            System.out.println();\n        }\n    }\n\n    static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {\n\n        for (int i = 0; i < o.length; i += 2) {\n            int x = c + o[i + 1];\n            int y = r + o[i];\n            if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                return false;\n        }\n\n        grid[r][c] = shapeIndex;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = shapeIndex;\n\n        return true;\n    }\n\n    static void removeOrientation(int[] o, int r, int c) {\n        grid[r][c] = -1;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = -1;\n    }\n\n    static boolean solve(int pos, int numPlaced) {\n        if (numPlaced == shapes.length)\n            return true;\n\n        int row = pos / nCols;\n        int col = pos % nCols;\n\n        if (grid[row][col] != -1)\n            return solve(pos + 1, numPlaced);\n\n        for (int i = 0; i < shapes.length; i++) {\n            if (!placed[i]) {\n                for (int[] orientation : shapes[i]) {\n\n                    if (!tryPlaceOrientation(orientation, row, col, i))\n                        continue;\n\n                    placed[i] = true;\n\n                    if (solve(pos + 1, numPlaced + 1))\n                        return true;\n\n                    removeOrientation(orientation, row, col);\n                    placed[i] = false;\n                }\n            }\n        }\n        return false;\n    }\n\n    static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};\n\n    static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};\n\n    static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};\n\n    static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};\n\n    static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};\n\n    static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};\n\n    static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};\n\n    static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};\n\n    static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};\n}\n", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n"}
{"id": 46648, "name": "Pentomino tiling", "Java": "package pentominotiling;\n\nimport java.util.*;\n\npublic class PentominoTiling {\n\n    static final char[] symbols = \"FILNPTUVWXYZ-\".toCharArray();\n    static final Random rand = new Random();\n\n    static final int nRows = 8;\n    static final int nCols = 8;\n    static final int blank = 12;\n\n    static int[][] grid = new int[nRows][nCols];\n    static boolean[] placed = new boolean[symbols.length - 1];\n\n    public static void main(String[] args) {\n        shuffleShapes();\n\n        for (int r = 0; r < nRows; r++)\n            Arrays.fill(grid[r], -1);\n\n        for (int i = 0; i < 4; i++) {\n            int randRow, randCol;\n            do {\n                randRow = rand.nextInt(nRows);\n                randCol = rand.nextInt(nCols);\n            } while (grid[randRow][randCol] == blank);\n            grid[randRow][randCol] = blank;\n        }\n\n        if (solve(0, 0)) {\n            printResult();\n        } else {\n            System.out.println(\"no solution\");\n        }\n    }\n\n    static void shuffleShapes() {\n        int n = shapes.length;\n        while (n > 1) {\n            int r = rand.nextInt(n--);\n\n            int[][] tmp = shapes[r];\n            shapes[r] = shapes[n];\n            shapes[n] = tmp;\n\n            char tmpSymbol = symbols[r];\n            symbols[r] = symbols[n];\n            symbols[n] = tmpSymbol;\n        }\n    }\n\n    static void printResult() {\n        for (int[] r : grid) {\n            for (int i : r)\n                System.out.printf(\"%c \", symbols[i]);\n            System.out.println();\n        }\n    }\n\n    static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {\n\n        for (int i = 0; i < o.length; i += 2) {\n            int x = c + o[i + 1];\n            int y = r + o[i];\n            if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                return false;\n        }\n\n        grid[r][c] = shapeIndex;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = shapeIndex;\n\n        return true;\n    }\n\n    static void removeOrientation(int[] o, int r, int c) {\n        grid[r][c] = -1;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = -1;\n    }\n\n    static boolean solve(int pos, int numPlaced) {\n        if (numPlaced == shapes.length)\n            return true;\n\n        int row = pos / nCols;\n        int col = pos % nCols;\n\n        if (grid[row][col] != -1)\n            return solve(pos + 1, numPlaced);\n\n        for (int i = 0; i < shapes.length; i++) {\n            if (!placed[i]) {\n                for (int[] orientation : shapes[i]) {\n\n                    if (!tryPlaceOrientation(orientation, row, col, i))\n                        continue;\n\n                    placed[i] = true;\n\n                    if (solve(pos + 1, numPlaced + 1))\n                        return true;\n\n                    removeOrientation(orientation, row, col);\n                    placed[i] = false;\n                }\n            }\n        }\n        return false;\n    }\n\n    static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};\n\n    static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};\n\n    static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};\n\n    static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};\n\n    static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};\n\n    static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};\n\n    static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};\n\n    static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};\n\n    static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};\n}\n", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n"}
{"id": 46649, "name": "Send an unknown method call", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n"}
{"id": 46650, "name": "Variables", "Java": "int a;\ndouble b;\nAClassNameHere c;\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 46651, "name": "Particle swarm optimization", "Java": "import java.util.Arrays;\nimport java.util.Objects;\nimport java.util.Random;\nimport java.util.function.Function;\n\npublic class App {\n    static class Parameters {\n        double omega;\n        double phip;\n        double phig;\n\n        Parameters(double omega, double phip, double phig) {\n            this.omega = omega;\n            this.phip = phip;\n            this.phig = phig;\n        }\n    }\n\n    static class State {\n        int iter;\n        double[] gbpos;\n        double gbval;\n        double[] min;\n        double[] max;\n        Parameters parameters;\n        double[][] pos;\n        double[][] vel;\n        double[][] bpos;\n        double[] bval;\n        int nParticles;\n        int nDims;\n\n        State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) {\n            this.iter = iter;\n            this.gbpos = gbpos;\n            this.gbval = gbval;\n            this.min = min;\n            this.max = max;\n            this.parameters = parameters;\n            this.pos = pos;\n            this.vel = vel;\n            this.bpos = bpos;\n            this.bval = bval;\n            this.nParticles = nParticles;\n            this.nDims = nDims;\n        }\n\n        void report(String testfunc) {\n            System.out.printf(\"Test Function        : %s\\n\", testfunc);\n            System.out.printf(\"Iterations           : %d\\n\", iter);\n            System.out.printf(\"Global Best Position : %s\\n\", Arrays.toString(gbpos));\n            System.out.printf(\"Global Best value    : %.15f\\n\", gbval);\n        }\n    }\n\n    private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) {\n        int nDims = min.length;\n        double[][] pos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            pos[i] = min.clone();\n        }\n        double[][] vel = new double[nParticles][nDims];\n        double[][] bpos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            bpos[i] = min.clone();\n        }\n        double[] bval = new double[nParticles];\n        for (int i = 0; i < bval.length; ++i) {\n            bval[i] = Double.POSITIVE_INFINITY;\n        }\n        int iter = 0;\n        double[] gbpos = new double[nDims];\n        for (int i = 0; i < gbpos.length; ++i) {\n            gbpos[i] = Double.POSITIVE_INFINITY;\n        }\n        double gbval = Double.POSITIVE_INFINITY;\n        return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n    }\n\n    private static Random r = new Random();\n\n    private static State pso(Function<double[], Double> fn, State y) {\n        Parameters p = y.parameters;\n        double[] v = new double[y.nParticles];\n        double[][] bpos = new double[y.nParticles][];\n        for (int i = 0; i < y.nParticles; ++i) {\n            bpos[i] = y.min.clone();\n        }\n        double[] bval = new double[y.nParticles];\n        double[] gbpos = new double[y.nDims];\n        double gbval = Double.POSITIVE_INFINITY;\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            v[j] = fn.apply(y.pos[j]);\n            \n            if (v[j] < y.bval[j]) {\n                bpos[j] = y.pos[j];\n                bval[j] = v[j];\n            } else {\n                bpos[j] = y.bpos[j];\n                bval[j] = y.bval[j];\n            }\n            if (bval[j] < gbval) {\n                gbval = bval[j];\n                gbpos = bpos[j];\n            }\n        }\n        double rg = r.nextDouble();\n        double[][] pos = new double[y.nParticles][y.nDims];\n        double[][] vel = new double[y.nParticles][y.nDims];\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            double rp = r.nextDouble();\n            boolean ok = true;\n            Arrays.fill(vel[j], 0.0);\n            Arrays.fill(pos[j], 0.0);\n            for (int k = 0; k < y.nDims; ++k) {\n                vel[j][k] = p.omega * y.vel[j][k] +\n                    p.phip * rp * (bpos[j][k] - y.pos[j][k]) +\n                    p.phig * rg * (gbpos[k] - y.pos[j][k]);\n                pos[j][k] = y.pos[j][k] + vel[j][k];\n                ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];\n            }\n            if (!ok) {\n                for (int k = 0; k < y.nDims; ++k) {\n                    pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble();\n                }\n            }\n        }\n        int iter = 1 + y.iter;\n        return new State(\n            iter, gbpos, gbval, y.min, y.max, y.parameters,\n            pos, vel, bpos, bval, y.nParticles, y.nDims\n        );\n    }\n\n    private static State iterate(Function<double[], Double> fn, int n, State y) {\n        State r = y;\n        if (n == Integer.MAX_VALUE) {\n            State old = y;\n            while (true) {\n                r = pso(fn, r);\n                if (Objects.equals(r, old)) break;\n                old = r;\n            }\n        } else {\n            for (int i = 0; i < n; ++i) {\n                r = pso(fn, r);\n            }\n        }\n        return r;\n    }\n\n    private static double mccormick(double[] x) {\n        double a = x[0];\n        double b = x[1];\n        return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;\n    }\n\n    private static double michalewicz(double[] x) {\n        int m = 10;\n        int d = x.length;\n        double sum = 0.0;\n        for (int i = 1; i < d; ++i) {\n            double j = x[i - 1];\n            double k = Math.sin(i * j * j / Math.PI);\n            sum += Math.sin(j) * Math.pow(k, 2.0 * m);\n        }\n        return -sum;\n    }\n\n    public static void main(String[] args) {\n        State state = psoInit(\n            new double[]{-1.5, -3.0},\n            new double[]{4.0, 4.0},\n            new Parameters(0.0, 0.6, 0.3),\n            100\n        );\n        state = iterate(App::mccormick, 40, state);\n        state.report(\"McCormick\");\n        System.out.printf(\"f(-.54719, -1.54719) : %.15f\\n\", mccormick(new double[]{-.54719, -1.54719}));\n        System.out.println();\n\n        state = psoInit(\n            new double[]{0.0, 0.0},\n            new double[]{Math.PI, Math.PI},\n            new Parameters(0.3, 3.0, 0.3),\n            1000\n        );\n        state = iterate(App::michalewicz, 30, state);\n        state.report(\"Michalewicz (2D)\");\n        System.out.printf(\"f(2.20, 1.57)        : %.15f\\n\", michalewicz(new double[]{2.20, 1.57}));\n    }\n}\n", "Python": "import math\nimport random\n\nINFINITY = 1 << 127\nMAX_INT = 1 << 31\n\nclass Parameters:\n    def __init__(self, omega, phip, phig):\n        self.omega = omega\n        self.phip = phip\n        self.phig = phig\n\nclass State:\n    def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):\n        self.iter = iter\n        self.gbpos = gbpos\n        self.gbval = gbval\n        self.min = min\n        self.max = max\n        self.parameters = parameters\n        self.pos = pos\n        self.vel = vel\n        self.bpos = bpos\n        self.bval = bval\n        self.nParticles = nParticles\n        self.nDims = nDims\n\n    def report(self, testfunc):\n        print \"Test Function :\", testfunc\n        print \"Iterations    :\", self.iter\n        print \"Global Best Position :\", self.gbpos\n        print \"Global Best Value    : %.16f\" % self.gbval\n\ndef uniform01():\n    v = random.random()\n    assert 0.0 <= v and v < 1.0\n    return v\n\ndef psoInit(min, max, parameters, nParticles):\n    nDims = len(min)\n    pos = [min[:]] * nParticles\n    vel = [[0.0] * nDims] * nParticles\n    bpos = [min[:]] * nParticles\n    bval = [INFINITY] * nParticles\n    iter = 0\n    gbpos = [INFINITY] * nDims\n    gbval = INFINITY\n    return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n\ndef pso(fn, y):\n    p = y.parameters\n    v = [0.0] * (y.nParticles)\n    bpos = [y.min[:]] * (y.nParticles)\n    bval = [0.0] * (y.nParticles)\n    gbpos = [0.0] * (y.nDims)\n    gbval = INFINITY\n    for j in xrange(0, y.nParticles):\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j]:\n            bpos[j] = y.pos[j][:]\n            bval[j] = v[j]\n        else:\n            bpos[j] = y.bpos[j][:]\n            bval[j] = y.bval[j]\n        if bval[j] < gbval:\n            gbval = bval[j]\n            gbpos = bpos[j][:]\n    rg = uniform01()\n    pos = [[None] * (y.nDims)] * (y.nParticles)\n    vel = [[None] * (y.nDims)] * (y.nParticles)\n    for j in xrange(0, y.nParticles):\n        \n        rp = uniform01()\n        ok = True\n        vel[j] = [0.0] * (len(vel[j]))\n        pos[j] = [0.0] * (len(pos[j]))\n        for k in xrange(0, y.nDims):\n            vel[j][k] = p.omega * y.vel[j][k] \\\n                      + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \\\n                      + p.phig * rg * (gbpos[k] - y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]\n        if not ok:\n            for k in xrange(0, y.nDims):\n                pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()\n    iter = 1 + y.iter\n    return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n\ndef iterate(fn, n, y):\n    r = y\n    old = y\n    if n == MAX_INT:\n        while True:\n            r = pso(fn, r)\n            if r == old:\n                break\n            old = r\n    else:\n        for _ in xrange(0, n):\n            r = pso(fn, r)\n    return r\n\ndef mccormick(x):\n    (a, b) = x\n    return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a\n\ndef michalewicz(x):\n    m = 10\n    d = len(x)\n    sum = 0.0\n    for i in xrange(1, d):\n        j = x[i - 1]\n        k = math.sin(i * j * j / math.pi)\n        sum += math.sin(j) * k ** (2.0 * m)\n    return -sum\n\ndef main():\n    state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)\n    state = iterate(mccormick, 40, state)\n    state.report(\"McCormick\")\n    print \"f(-.54719, -1.54719) : %.16f\" % (mccormick([-.54719, -1.54719]))\n\n    print\n\n    state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)\n    state = iterate(michalewicz, 30, state)\n    state.report(\"Michalewicz (2D)\")\n    print \"f(2.20, 1.57)        : %.16f\" % (michalewicz([2.2, 1.57]))\n\nmain()\n"}
{"id": 46652, "name": "Interactive programming (repl)", "Java": "public static void main(String[] args) {\n    System.out.println(concat(\"Rosetta\", \"Code\", \":\"));\n}\n\npublic static String concat(String a, String b, String c) {\n   return a + c + c + b;\n}\n\nRosetta::Code\n", "Python": "python\nPython 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(string1, string2, separator):\n\treturn separator.join([string1, '', string2])\n\n>>> f('Rosetta', 'Code', ':')\n'Rosetta::Code'\n>>>\n"}
{"id": 46653, "name": "Index finite lists of positive integers", "Java": "import java.math.BigInteger;\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.Collectors.*;\n\npublic class Test3 {\n    static BigInteger rank(int[] x) {\n        String s = stream(x).mapToObj(String::valueOf).collect(joining(\"F\"));\n        return new BigInteger(s, 16);\n    }\n\n    static List<BigInteger> unrank(BigInteger n) {\n        BigInteger sixteen = BigInteger.valueOf(16);\n        String s = \"\";\n        while (!n.equals(BigInteger.ZERO)) {\n            s = \"0123456789ABCDEF\".charAt(n.mod(sixteen).intValue()) + s;\n            n = n.divide(sixteen);\n        }\n        return stream(s.split(\"F\")).map(x -> new BigInteger(x)).collect(toList());\n    }\n\n    public static void main(String[] args) {\n        int[] s = {1, 2, 3, 10, 100, 987654321};\n        System.out.println(Arrays.toString(s));\n        System.out.println(rank(s));\n        System.out.println(unrank(rank(s)));\n    }\n}\n", "Python": "def rank(x): return int('a'.join(map(str, [1] + x)), 11)\n\ndef unrank(n):\n\ts = ''\n\twhile n: s,n = \"0123456789a\"[n%11] + s, n//11\n\treturn map(int, s.split('a'))[1:]\n\nl = [1, 2, 3, 10, 100, 987654321]\nprint l\nn = rank(l)\nprint n\nl = unrank(n)\nprint l\n"}
{"id": 46654, "name": "Make a backup file", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 46655, "name": "Make a backup file", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 46656, "name": "Reverse the gender of a string", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n"}
{"id": 46657, "name": "Reverse the gender of a string", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n"}
{"id": 46658, "name": "Audio alarm", "Java": "import com.sun.javafx.application.PlatformImpl;\nimport java.io.File;\nimport java.util.Scanner;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport javafx.scene.media.Media;\nimport javafx.scene.media.MediaPlayer;\n\npublic class AudioAlarm {\n\n    public static void main(String[] args) throws InterruptedException {\n        Scanner input = new Scanner(System.in);\n\n        System.out.print(\"Enter a number of seconds: \");\n        int seconds = Integer.parseInt(input.nextLine());\n\n        System.out.print(\"Enter a filename (must end with .mp3 or .wav): \");\n        String audio = input.nextLine();\n\n        TimeUnit.SECONDS.sleep(seconds);\n\n        Media media = new Media(new File(audio).toURI().toString());\n        AtomicBoolean stop = new AtomicBoolean();\n        Runnable onEnd = () -> stop.set(true);\n\n        PlatformImpl.startup(() -> {}); \n\n        MediaPlayer player = new MediaPlayer(media);\n        player.setOnEndOfMedia(onEnd);\n        player.setOnError(onEnd);\n        player.setOnHalted(onEnd);\n        player.play();\n\n        while (!stop.get()) {\n            Thread.sleep(100);\n        }\n        System.exit(0); \n    }\n}\n", "Python": "import time\nimport os\n\nseconds = input(\"Enter a number of seconds: \")\nsound = input(\"Enter an mp3 filename: \")\n\ntime.sleep(float(seconds))\nos.startfile(sound + \".mp3\")\n"}
{"id": 46659, "name": "Decimal floating point number to binary", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n"}
{"id": 46660, "name": "Decimal floating point number to binary", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n"}
{"id": 46661, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 46662, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 46663, "name": "Check Machin-like formulas", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n"}
{"id": 46664, "name": "Check Machin-like formulas", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n"}
{"id": 46665, "name": "MD5_Implementation", "Java": "class MD5\n{\n\n  private static final int INIT_A = 0x67452301;\n  private static final int INIT_B = (int)0xEFCDAB89L;\n  private static final int INIT_C = (int)0x98BADCFEL;\n  private static final int INIT_D = 0x10325476;\n  \n  private static final int[] SHIFT_AMTS = {\n    7, 12, 17, 22,\n    5,  9, 14, 20,\n    4, 11, 16, 23,\n    6, 10, 15, 21\n  };\n  \n  private static final int[] TABLE_T = new int[64];\n  static\n  {\n    for (int i = 0; i < 64; i++)\n      TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));\n  }\n  \n  public static byte[] computeMD5(byte[] message)\n  {\n    int messageLenBytes = message.length;\n    int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;\n    int totalLen = numBlocks << 6;\n    byte[] paddingBytes = new byte[totalLen - messageLenBytes];\n    paddingBytes[0] = (byte)0x80;\n    \n    long messageLenBits = (long)messageLenBytes << 3;\n    for (int i = 0; i < 8; i++)\n    {\n      paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;\n      messageLenBits >>>= 8;\n    }\n    \n    int a = INIT_A;\n    int b = INIT_B;\n    int c = INIT_C;\n    int d = INIT_D;\n    int[] buffer = new int[16];\n    for (int i = 0; i < numBlocks; i ++)\n    {\n      int index = i << 6;\n      for (int j = 0; j < 64; j++, index++)\n        buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);\n      int originalA = a;\n      int originalB = b;\n      int originalC = c;\n      int originalD = d;\n      for (int j = 0; j < 64; j++)\n      {\n        int div16 = j >>> 4;\n        int f = 0;\n        int bufferIndex = j;\n        switch (div16)\n        {\n          case 0:\n            f = (b & c) | (~b & d);\n            break;\n            \n          case 1:\n            f = (b & d) | (c & ~d);\n            bufferIndex = (bufferIndex * 5 + 1) & 0x0F;\n            break;\n            \n          case 2:\n            f = b ^ c ^ d;\n            bufferIndex = (bufferIndex * 3 + 5) & 0x0F;\n            break;\n            \n          case 3:\n            f = c ^ (b | ~d);\n            bufferIndex = (bufferIndex * 7) & 0x0F;\n            break;\n        }\n        int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);\n        a = d;\n        d = c;\n        c = b;\n        b = temp;\n      }\n      \n      a += originalA;\n      b += originalB;\n      c += originalC;\n      d += originalD;\n    }\n    \n    byte[] md5 = new byte[16];\n    int count = 0;\n    for (int i = 0; i < 4; i++)\n    {\n      int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));\n      for (int j = 0; j < 4; j++)\n      {\n        md5[count++] = (byte)n;\n        n >>>= 8;\n      }\n    }\n    return md5;\n  }\n  \n  public static String toHexString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      sb.append(String.format(\"%02X\", b[i] & 0xFF));\n    }\n    return sb.toString();\n  }\n\n  public static void main(String[] args)\n  {\n    String[] testStrings = { \"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" };\n    for (String s : testStrings)\n      System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\");\n    return;\n  }\n  \n}\n", "Python": "import math\n\nrotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\nconstants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]\n\ninit_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]\n\nfunctions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \\\n            16*[lambda b, c, d: (d & b) | (~d & c)] + \\\n            16*[lambda b, c, d: b ^ c ^ d] + \\\n            16*[lambda b, c, d: c ^ (b | ~d)]\n\nindex_functions = 16*[lambda i: i] + \\\n                  16*[lambda i: (5*i + 1)%16] + \\\n                  16*[lambda i: (3*i + 5)%16] + \\\n                  16*[lambda i: (7*i)%16]\n\ndef left_rotate(x, amount):\n    x &= 0xFFFFFFFF\n    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF\n\ndef md5(message):\n\n    message = bytearray(message) \n    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff\n    message.append(0x80)\n    while len(message)%64 != 56:\n        message.append(0)\n    message += orig_len_in_bits.to_bytes(8, byteorder='little')\n\n    hash_pieces = init_values[:]\n\n    for chunk_ofst in range(0, len(message), 64):\n        a, b, c, d = hash_pieces\n        chunk = message[chunk_ofst:chunk_ofst+64]\n        for i in range(64):\n            f = functions[i](b, c, d)\n            g = index_functions[i](i)\n            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')\n            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF\n            a, b, c, d = d, new_b, b, c\n        for i, val in enumerate([a, b, c, d]):\n            hash_pieces[i] += val\n            hash_pieces[i] &= 0xFFFFFFFF\n    \n    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))\n        \ndef md5_to_hex(digest):\n    raw = digest.to_bytes(16, byteorder='little')\n    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))\n\nif __name__=='__main__':\n    demo = [b\"\", b\"a\", b\"abc\", b\"message digest\", b\"abcdefghijklmnopqrstuvwxyz\",\n            b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n            b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"]\n    for message in demo:\n        print(md5_to_hex(md5(message)),' <= \"',message.decode('ascii'),'\"', sep='')\n"}
{"id": 46666, "name": "K-means++ clustering", "Java": "import java.util.Random;\n\npublic class KMeansWithKpp{\n\t\t\n\t\tpublic Point[] points;\n\t\tpublic Point[] centroids;\n\t\tRandom rand;\n\t\tpublic int n;\n\t\tpublic int k;\n\n\t\t\n\t\tprivate KMeansWithKpp(){\n\t\t}\n\n\t\tKMeansWithKpp(Point[] p, int clusters){\n\t\t\t\tpoints = p;\n\t\t\t\tn = p.length;\n\t\t\t\tk = Math.max(1, clusters);\n\t\t\t\tcentroids = new Point[k];\n\t\t\t\trand = new Random();\n\t\t}\n\n\n\t\tprivate static double distance(Point a, Point b){\n\t\t\t\treturn (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n\t\t}\n\n\t\tprivate static int nearest(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tint index = pt.group;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn index;\n\t\t}\n\n\t\tprivate static double nearestDistance(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn minD;\n\t\t}\n\n\t\tprivate void kpp(){\n\t\t\t\tcentroids[0] = points[rand.nextInt(n)];\n\t\t\t\tdouble[] dist = new double[n];\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor (int i = 1; i < k; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tdist[j] = nearestDistance(points[j], centroids, i);\n\t\t\t\t\t\t\t\tsum += dist[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tif ((sum -= dist[j]) > 0)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tcentroids[i].x = points[j].x;\n\t\t\t\t\t\t\t\tcentroids[i].y = points[j].y;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tpoints[i].group = nearest(points[i], centroids, k);\n\t\t\t\t}\n\t\t}\n\n\t\tpublic void kMeans(int maxTimes){\n\t\t\t\tif (k == 1 || n <= 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(k >= n){\n\t\t\t\t\t\tfor(int i =0; i < n; i++){\n\t\t\t\t\t\t\t\tpoints[i].group = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxTimes = Math.max(1, maxTimes);\n\t\t\t\tint changed;\n\t\t\t\tint bestPercent = n/1000;\n\t\t\t\tint minIndex;\n\t\t\t\tkpp();\n\t\t\t\tdo {\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x = 0.0;\n\t\t\t\t\t\t\t\tc.y = 0.0;\n\t\t\t\t\t\t\t\tc.group = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tif(pt.group < 0 || pt.group > centroids.length){\n\t\t\t\t\t\t\t\t\t\tpt.group = rand.nextInt(centroids.length);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcentroids[pt.group].x += pt.x;\n\t\t\t\t\t\t\t\tcentroids[pt.group].y = pt.y;\n\t\t\t\t\t\t\t\tcentroids[pt.group].group++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x /= c.group;\n\t\t\t\t\t\t\t\tc.y /= c.group;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tminIndex = nearest(pt, centroids, k);\n\t\t\t\t\t\t\t\tif (k != pt.group) {\n\t\t\t\t\t\t\t\t\t\tchanged++;\n\t\t\t\t\t\t\t\t\t\tpt.group = minIndex;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxTimes--;\n\t\t\t\t} while (changed > bestPercent && maxTimes > 0);\n\t\t}\n}\n\n\n\n\nclass Point{\n\t\tpublic double x;\n\t\tpublic double y;\n\t\tpublic int group;\n\n\t\tPoint(){\n\t\t\t\tx = y = 0.0;\n\t\t\t\tgroup = 0;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){\n\t\t\t\tif (size <= 0)\n\t\t\t\t\t\treturn null;\n\t\t\t\tdouble xdiff, ydiff;\n\t\t\t\txdiff = maxX - minX;\n\t\t\t\tydiff = maxY - minY;\n\t\t\t\tif (minX > maxX) {\n\t\t\t\t\t\txdiff = minX - maxX;\n\t\t\t\t\t\tminX = maxX;\n\t\t\t\t}\n\t\t\t\tif (maxY < minY) {\n\t\t\t\t\t\tydiff = minY - maxY;\n\t\t\t\t\t\tminY = maxY;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tdata[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPolarData(double radius, int size){\n\t\t\t\tif (size <= 0) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tdouble radi, arg;\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tradi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\targ = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].x = radi * Math.cos(arg);\n\t\t\t\t\t\tdata[i].y = radi * Math.sin(arg);\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\t\t\n}\n", "Python": "from math import pi, sin, cos\nfrom collections import namedtuple\nfrom random import random, choice\nfrom copy import copy\n\ntry:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\n\nFLOAT_MAX = 1e100\n\n\nclass Point:\n    __slots__ = [\"x\", \"y\", \"group\"]\n    def __init__(self, x=0.0, y=0.0, group=0):\n        self.x, self.y, self.group = x, y, group\n\n\ndef generate_points(npoints, radius):\n    points = [Point() for _ in xrange(npoints)]\n\n    \n    for p in points:\n        r = random() * radius\n        ang = random() * 2 * pi\n        p.x = r * cos(ang)\n        p.y = r * sin(ang)\n\n    return points\n\n\ndef nearest_cluster_center(point, cluster_centers):\n    \n    def sqr_distance_2D(a, b):\n        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2\n\n    min_index = point.group\n    min_dist = FLOAT_MAX\n\n    for i, cc in enumerate(cluster_centers):\n        d = sqr_distance_2D(cc, point)\n        if min_dist > d:\n            min_dist = d\n            min_index = i\n\n    return (min_index, min_dist)\n\n\ndef kpp(points, cluster_centers):\n    cluster_centers[0] = copy(choice(points))\n    d = [0.0 for _ in xrange(len(points))]\n\n    for i in xrange(1, len(cluster_centers)):\n        sum = 0\n        for j, p in enumerate(points):\n            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]\n            sum += d[j]\n\n        sum *= random()\n\n        for j, di in enumerate(d):\n            sum -= di\n            if sum > 0:\n                continue\n            cluster_centers[i] = copy(points[j])\n            break\n\n    for p in points:\n        p.group = nearest_cluster_center(p, cluster_centers)[0]\n\n\ndef lloyd(points, nclusters):\n    cluster_centers = [Point() for _ in xrange(nclusters)]\n\n    \n    kpp(points, cluster_centers)\n\n    lenpts10 = len(points) >> 10\n\n    changed = 0\n    while True:\n        \n        for cc in cluster_centers:\n            cc.x = 0\n            cc.y = 0\n            cc.group = 0\n\n        for p in points:\n            cluster_centers[p.group].group += 1\n            cluster_centers[p.group].x += p.x\n            cluster_centers[p.group].y += p.y\n\n        for cc in cluster_centers:\n            cc.x /= cc.group\n            cc.y /= cc.group\n\n        \n        changed = 0\n        for p in points:\n            min_i = nearest_cluster_center(p, cluster_centers)[0]\n            if min_i != p.group:\n                changed += 1\n                p.group = min_i\n\n        \n        if changed <= lenpts10:\n            break\n\n    for i, cc in enumerate(cluster_centers):\n        cc.group = i\n\n    return cluster_centers\n\n\ndef print_eps(points, cluster_centers, W=400, H=400):\n    Color = namedtuple(\"Color\", \"r g b\");\n\n    colors = []\n    for i in xrange(len(cluster_centers)):\n        colors.append(Color((3 * (i + 1) % 11) / 11.0,\n                            (7 * i % 11) / 11.0,\n                            (9 * i % 11) / 11.0))\n\n    max_x = max_y = -FLOAT_MAX\n    min_x = min_y = FLOAT_MAX\n\n    for p in points:\n        if max_x < p.x: max_x = p.x\n        if min_x > p.x: min_x = p.x\n        if max_y < p.y: max_y = p.y\n        if min_y > p.y: min_y = p.y\n\n    scale = min(W / (max_x - min_x),\n                H / (max_y - min_y))\n    cx = (max_x + min_x) / 2\n    cy = (max_y + min_y) / 2\n\n    print \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: -5 -5 %d %d\" % (W + 10, H + 10)\n\n    print (\"/l {rlineto} def /m {rmoveto} def\\n\" +\n           \"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\\n\" +\n           \"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath \" +\n           \"   gsave 1 setgray fill grestore gsave 3 setlinewidth\" +\n           \" 1 setgray stroke grestore 0 setgray stroke }def\")\n\n    for i, cc in enumerate(cluster_centers):\n        print (\"%g %g %g setrgbcolor\" %\n               (colors[i].r, colors[i].g, colors[i].b))\n\n        for p in points:\n            if p.group != i:\n                continue\n            print (\"%.3f %.3f c\" % ((p.x - cx) * scale + W / 2,\n                                    (p.y - cy) * scale + H / 2))\n\n        print (\"\\n0 setgray %g %g s\" % ((cc.x - cx) * scale + W / 2,\n                                        (cc.y - cy) * scale + H / 2))\n\n    print \"\\n%%%%EOF\"\n\n\ndef main():\n    npoints = 30000\n    k = 7 \n\n    points = generate_points(npoints, 10)\n    cluster_centers = lloyd(points, k)\n    print_eps(points, cluster_centers)\n\n\nmain()\n"}
{"id": 46667, "name": "K-means++ clustering", "Java": "import java.util.Random;\n\npublic class KMeansWithKpp{\n\t\t\n\t\tpublic Point[] points;\n\t\tpublic Point[] centroids;\n\t\tRandom rand;\n\t\tpublic int n;\n\t\tpublic int k;\n\n\t\t\n\t\tprivate KMeansWithKpp(){\n\t\t}\n\n\t\tKMeansWithKpp(Point[] p, int clusters){\n\t\t\t\tpoints = p;\n\t\t\t\tn = p.length;\n\t\t\t\tk = Math.max(1, clusters);\n\t\t\t\tcentroids = new Point[k];\n\t\t\t\trand = new Random();\n\t\t}\n\n\n\t\tprivate static double distance(Point a, Point b){\n\t\t\t\treturn (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n\t\t}\n\n\t\tprivate static int nearest(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tint index = pt.group;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn index;\n\t\t}\n\n\t\tprivate static double nearestDistance(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn minD;\n\t\t}\n\n\t\tprivate void kpp(){\n\t\t\t\tcentroids[0] = points[rand.nextInt(n)];\n\t\t\t\tdouble[] dist = new double[n];\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor (int i = 1; i < k; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tdist[j] = nearestDistance(points[j], centroids, i);\n\t\t\t\t\t\t\t\tsum += dist[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tif ((sum -= dist[j]) > 0)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tcentroids[i].x = points[j].x;\n\t\t\t\t\t\t\t\tcentroids[i].y = points[j].y;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tpoints[i].group = nearest(points[i], centroids, k);\n\t\t\t\t}\n\t\t}\n\n\t\tpublic void kMeans(int maxTimes){\n\t\t\t\tif (k == 1 || n <= 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(k >= n){\n\t\t\t\t\t\tfor(int i =0; i < n; i++){\n\t\t\t\t\t\t\t\tpoints[i].group = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxTimes = Math.max(1, maxTimes);\n\t\t\t\tint changed;\n\t\t\t\tint bestPercent = n/1000;\n\t\t\t\tint minIndex;\n\t\t\t\tkpp();\n\t\t\t\tdo {\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x = 0.0;\n\t\t\t\t\t\t\t\tc.y = 0.0;\n\t\t\t\t\t\t\t\tc.group = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tif(pt.group < 0 || pt.group > centroids.length){\n\t\t\t\t\t\t\t\t\t\tpt.group = rand.nextInt(centroids.length);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcentroids[pt.group].x += pt.x;\n\t\t\t\t\t\t\t\tcentroids[pt.group].y = pt.y;\n\t\t\t\t\t\t\t\tcentroids[pt.group].group++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x /= c.group;\n\t\t\t\t\t\t\t\tc.y /= c.group;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tminIndex = nearest(pt, centroids, k);\n\t\t\t\t\t\t\t\tif (k != pt.group) {\n\t\t\t\t\t\t\t\t\t\tchanged++;\n\t\t\t\t\t\t\t\t\t\tpt.group = minIndex;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxTimes--;\n\t\t\t\t} while (changed > bestPercent && maxTimes > 0);\n\t\t}\n}\n\n\n\n\nclass Point{\n\t\tpublic double x;\n\t\tpublic double y;\n\t\tpublic int group;\n\n\t\tPoint(){\n\t\t\t\tx = y = 0.0;\n\t\t\t\tgroup = 0;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){\n\t\t\t\tif (size <= 0)\n\t\t\t\t\t\treturn null;\n\t\t\t\tdouble xdiff, ydiff;\n\t\t\t\txdiff = maxX - minX;\n\t\t\t\tydiff = maxY - minY;\n\t\t\t\tif (minX > maxX) {\n\t\t\t\t\t\txdiff = minX - maxX;\n\t\t\t\t\t\tminX = maxX;\n\t\t\t\t}\n\t\t\t\tif (maxY < minY) {\n\t\t\t\t\t\tydiff = minY - maxY;\n\t\t\t\t\t\tminY = maxY;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tdata[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPolarData(double radius, int size){\n\t\t\t\tif (size <= 0) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tdouble radi, arg;\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tradi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\targ = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].x = radi * Math.cos(arg);\n\t\t\t\t\t\tdata[i].y = radi * Math.sin(arg);\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\t\t\n}\n", "Python": "from math import pi, sin, cos\nfrom collections import namedtuple\nfrom random import random, choice\nfrom copy import copy\n\ntry:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\n\nFLOAT_MAX = 1e100\n\n\nclass Point:\n    __slots__ = [\"x\", \"y\", \"group\"]\n    def __init__(self, x=0.0, y=0.0, group=0):\n        self.x, self.y, self.group = x, y, group\n\n\ndef generate_points(npoints, radius):\n    points = [Point() for _ in xrange(npoints)]\n\n    \n    for p in points:\n        r = random() * radius\n        ang = random() * 2 * pi\n        p.x = r * cos(ang)\n        p.y = r * sin(ang)\n\n    return points\n\n\ndef nearest_cluster_center(point, cluster_centers):\n    \n    def sqr_distance_2D(a, b):\n        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2\n\n    min_index = point.group\n    min_dist = FLOAT_MAX\n\n    for i, cc in enumerate(cluster_centers):\n        d = sqr_distance_2D(cc, point)\n        if min_dist > d:\n            min_dist = d\n            min_index = i\n\n    return (min_index, min_dist)\n\n\ndef kpp(points, cluster_centers):\n    cluster_centers[0] = copy(choice(points))\n    d = [0.0 for _ in xrange(len(points))]\n\n    for i in xrange(1, len(cluster_centers)):\n        sum = 0\n        for j, p in enumerate(points):\n            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]\n            sum += d[j]\n\n        sum *= random()\n\n        for j, di in enumerate(d):\n            sum -= di\n            if sum > 0:\n                continue\n            cluster_centers[i] = copy(points[j])\n            break\n\n    for p in points:\n        p.group = nearest_cluster_center(p, cluster_centers)[0]\n\n\ndef lloyd(points, nclusters):\n    cluster_centers = [Point() for _ in xrange(nclusters)]\n\n    \n    kpp(points, cluster_centers)\n\n    lenpts10 = len(points) >> 10\n\n    changed = 0\n    while True:\n        \n        for cc in cluster_centers:\n            cc.x = 0\n            cc.y = 0\n            cc.group = 0\n\n        for p in points:\n            cluster_centers[p.group].group += 1\n            cluster_centers[p.group].x += p.x\n            cluster_centers[p.group].y += p.y\n\n        for cc in cluster_centers:\n            cc.x /= cc.group\n            cc.y /= cc.group\n\n        \n        changed = 0\n        for p in points:\n            min_i = nearest_cluster_center(p, cluster_centers)[0]\n            if min_i != p.group:\n                changed += 1\n                p.group = min_i\n\n        \n        if changed <= lenpts10:\n            break\n\n    for i, cc in enumerate(cluster_centers):\n        cc.group = i\n\n    return cluster_centers\n\n\ndef print_eps(points, cluster_centers, W=400, H=400):\n    Color = namedtuple(\"Color\", \"r g b\");\n\n    colors = []\n    for i in xrange(len(cluster_centers)):\n        colors.append(Color((3 * (i + 1) % 11) / 11.0,\n                            (7 * i % 11) / 11.0,\n                            (9 * i % 11) / 11.0))\n\n    max_x = max_y = -FLOAT_MAX\n    min_x = min_y = FLOAT_MAX\n\n    for p in points:\n        if max_x < p.x: max_x = p.x\n        if min_x > p.x: min_x = p.x\n        if max_y < p.y: max_y = p.y\n        if min_y > p.y: min_y = p.y\n\n    scale = min(W / (max_x - min_x),\n                H / (max_y - min_y))\n    cx = (max_x + min_x) / 2\n    cy = (max_y + min_y) / 2\n\n    print \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: -5 -5 %d %d\" % (W + 10, H + 10)\n\n    print (\"/l {rlineto} def /m {rmoveto} def\\n\" +\n           \"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\\n\" +\n           \"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath \" +\n           \"   gsave 1 setgray fill grestore gsave 3 setlinewidth\" +\n           \" 1 setgray stroke grestore 0 setgray stroke }def\")\n\n    for i, cc in enumerate(cluster_centers):\n        print (\"%g %g %g setrgbcolor\" %\n               (colors[i].r, colors[i].g, colors[i].b))\n\n        for p in points:\n            if p.group != i:\n                continue\n            print (\"%.3f %.3f c\" % ((p.x - cx) * scale + W / 2,\n                                    (p.y - cy) * scale + H / 2))\n\n        print (\"\\n0 setgray %g %g s\" % ((cc.x - cx) * scale + W / 2,\n                                        (cc.y - cy) * scale + H / 2))\n\n    print \"\\n%%%%EOF\"\n\n\ndef main():\n    npoints = 30000\n    k = 7 \n\n    points = generate_points(npoints, 10)\n    cluster_centers = lloyd(points, k)\n    print_eps(points, cluster_centers)\n\n\nmain()\n"}
{"id": 46668, "name": "Maze solving", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class MazeSolver\n{\n    \n    private static String[] readLines (InputStream f) throws IOException\n    {\n        BufferedReader r =\n            new BufferedReader (new InputStreamReader (f, \"US-ASCII\"));\n        ArrayList<String> lines = new ArrayList<String>();\n        String line;\n        while ((line = r.readLine()) != null)\n            lines.add (line);\n        return lines.toArray(new String[0]);\n    }\n\n    \n    private static char[][] decimateHorizontally (String[] lines)\n    {\n        final int width = (lines[0].length() + 1) / 2;\n        char[][] c = new char[lines.length][width];\n        for (int i = 0  ;  i < lines.length  ;  i++)\n            for (int j = 0  ;  j < width  ;  j++)\n                c[i][j] = lines[i].charAt (j * 2);\n        return c;\n    }\n\n    \n    private static boolean solveMazeRecursively (char[][] maze,\n                                                 int x, int y, int d)\n    {\n        boolean ok = false;\n        for (int i = 0  ;  i < 4  &&  !ok  ;  i++)\n            if (i != d)\n                switch (i)\n                    {\n                        \n                    case 0:\n                        if (maze[y-1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y - 2, 2);\n                        break;\n                    case 1:\n                        if (maze[y][x+1] == ' ')\n                            ok = solveMazeRecursively (maze, x + 2, y, 3);\n                        break;\n                    case 2:\n                        if (maze[y+1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y + 2, 0);\n                        break;\n                    case 3:\n                        if (maze[y][x-1] == ' ')\n                            ok = solveMazeRecursively (maze, x - 2, y, 1);\n                        break;\n                    }\n        \n        if (x == 1  &&  y == 1)\n            ok = true;\n        \n        if (ok)\n            {\n                maze[y][x] = '*';\n                switch (d)\n                    {\n                    case 0:\n                        maze[y-1][x] = '*';\n                        break;\n                    case 1:\n                        maze[y][x+1] = '*';\n                        break;\n                    case 2:\n                        maze[y+1][x] = '*';\n                        break;\n                    case 3:\n                        maze[y][x-1] = '*';\n                        break;\n                    }\n            }\n        return ok;\n    }\n\n    \n    private static void solveMaze (char[][] maze)\n    {\n        solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1);\n    }\n\n    \n    private static String[] expandHorizontally (char[][] maze)\n    {\n        char[] tmp = new char[3];\n        String[] lines = new String[maze.length];\n        for (int i = 0  ;  i < maze.length  ;  i++)\n            {\n                StringBuilder sb = new StringBuilder(maze[i].length * 2);\n                for (int j = 0  ;  j < maze[i].length  ;  j++)\n                    if (j % 2 == 0)\n                        sb.append (maze[i][j]);\n                    else\n                        {\n                            tmp[0] = tmp[1] = tmp[2] = maze[i][j];\n                            if (tmp[1] == '*')\n                                tmp[0] = tmp[2] = ' ';\n                            sb.append (tmp);\n                        }\n                lines[i] = sb.toString();\n            }\n        return lines;\n    }\n\n    \n    public static void main (String[] args) throws IOException\n    {\n        InputStream f = (args.length > 0\n                         ?  new FileInputStream (args[0])\n                         :  System.in);\n        String[] lines = readLines (f);\n        char[][] maze = decimateHorizontally (lines);\n        solveMaze (maze);\n        String[] solvedLines = expandHorizontally (maze);\n        for (int i = 0  ;  i < solvedLines.length  ;  i++)\n            System.out.println (solvedLines[i]);\n    }\n}\n", "Python": "\n\ndef Dijkstra(Graph, source):\n    \n    \n    infinity = float('infinity')\n    n = len(graph)\n    dist = [infinity]*n   \n    previous = [infinity]*n \n    dist[source] = 0        \n    Q = list(range(n)) \n    while Q:           \n        u = min(Q, key=lambda n:dist[n])                 \n        Q.remove(u)\n        if dist[u] == infinity:\n            break \n        for v in range(n):               \n            if Graph[u][v] and (v in Q): \n                alt = dist[u] + Graph[u][v]\n                if alt < dist[v]:       \n                    dist[v] = alt\n                    previous[v] = u\n    return dist,previous\n\ndef display_solution(predecessor):\n    cell = len(predecessor)-1\n    while cell:\n        print(cell,end='<')\n        cell = predecessor[cell]\n    print(0)\n"}
{"id": 46669, "name": "Generate random numbers without repeating a value", "Java": "import java.util.*;\n\npublic class RandomShuffle {\n    public static void main(String[] args) {\n        Random rand = new Random();\n        List<Integer> list = new ArrayList<>();\n        for (int j = 1; j <= 20; ++j)\n            list.add(j);\n        Collections.shuffle(list, rand);\n        System.out.println(list);\n    }\n}\n", "Python": "import random\n\nprint(random.sample(range(1, 21), 20))\n"}
{"id": 46670, "name": "Solve triangle solitare puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\n\npublic class IQPuzzle {\n\n    public static void main(String[] args) {\n        System.out.printf(\"  \");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"  %,6d\", start);\n        }\n        System.out.printf(\"%n\");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"%2d\", start);\n            Map<Integer,Integer> solutions = solve(start);    \n            for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {\n                System.out.printf(\"  %,6d\", solutions.containsKey(end) ? solutions.get(end) : 0);\n            }\n            System.out.printf(\"%n\");\n        }\n        int moveNum = 0;\n        System.out.printf(\"%nOne Solution:%n\");\n        for ( Move m : oneSolution ) {\n            moveNum++;\n            System.out.printf(\"Move %d = %s%n\", moveNum, m);\n        }\n    }\n    \n    private static List<Move> oneSolution = null;\n    \n    private static Map<Integer, Integer> solve(int emptyPeg) {\n        Puzzle puzzle = new Puzzle(emptyPeg);\n        Map<Integer,Integer> solutions = new HashMap<>();\n        Stack<Puzzle> stack = new Stack<Puzzle>();\n        stack.push(puzzle);\n        while ( ! stack.isEmpty() ) {\n            Puzzle p = stack.pop();\n            if ( p.solved() ) {\n                solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);\n                if ( oneSolution == null ) {\n                    oneSolution = p.moves;\n                }\n                continue;\n            }\n            for ( Move move : p.getValidMoves() ) {\n                Puzzle pMove = p.move(move);\n                stack.add(pMove);\n            }\n        }\n        \n        return solutions;\n    }\n    \n    private static class Puzzle {\n        \n        public static int MAX_PEGS = 16;\n        private boolean[] pegs = new boolean[MAX_PEGS];  \n        \n        private List<Move> moves;\n\n        public Puzzle(int emptyPeg) {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            pegs[emptyPeg] = false;\n            moves = new ArrayList<>();\n        }\n\n        public Puzzle() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            moves = new ArrayList<>();\n        }\n\n        private static Map<Integer,List<Move>> validMoves = new HashMap<>(); \n        static {\n            validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));\n            validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));\n            validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));\n            validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));\n            validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));\n            validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));\n            validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));\n            validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));\n            validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));\n            validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));\n            validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));\n            validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));\n            validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));\n            validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));\n            validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));\n        }\n        \n        public List<Move> getValidMoves() {\n            List<Move> moves = new ArrayList<Move>();\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    for ( Move testMove : validMoves.get(i) ) {\n                        if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {\n                            moves.add(testMove);\n                        }\n                    }\n                }\n            }\n            return moves;\n        }\n\n        public boolean solved() {\n            boolean foundFirstPeg = false;\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    if ( foundFirstPeg ) {\n                        return false;\n                    }\n                    foundFirstPeg = true;\n                }\n            }\n            return true;\n        }\n        \n        public Puzzle move(Move move) {\n            Puzzle p = new Puzzle();\n            if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {\n                throw new RuntimeException(\"Invalid move.\");\n            }\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                p.pegs[i] = pegs[i];\n            }\n            p.pegs[move.start] = false;\n            p.pegs[move.jump] = false;\n            p.pegs[move.end] = true;\n            for ( Move m : moves ) {\n                p.moves.add(new Move(m.start, m.jump, m.end));\n            }\n            p.moves.add(new Move(move.start, move.jump, move.end));\n            return p;\n        }\n        \n        public int getLastPeg() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    return i;\n                }\n            }\n            throw new RuntimeException(\"ERROR:  Illegal position.\");\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"[\");\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                sb.append(pegs[i] ? 1 : 0);\n                sb.append(\",\");\n            }\n            sb.setLength(sb.length()-1);            \n            sb.append(\"]\");\n            return sb.toString();\n        }\n    }\n    \n    private static class Move {\n        int start;\n        int jump;\n        int end;\n        \n        public Move(int s, int j, int e) {\n            start = s; jump = j; end = e;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"{\");\n            sb.append(\"s=\" + start);\n            sb.append(\", j=\" + jump);\n            sb.append(\", e=\" + end);\n            sb.append(\"}\");\n            return sb.toString();\n        }\n    }\n\n}\n", "Python": "\n\n\ndef DrawBoard(board):\n  peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n  for n in xrange(1,16):\n    peg[n] = '.'\n    if n in board:\n      peg[n] = \"%X\" % n\n  print \"     %s\" % peg[1]\n  print \"    %s %s\" % (peg[2],peg[3])\n  print \"   %s %s %s\" % (peg[4],peg[5],peg[6])\n  print \"  %s %s %s %s\" % (peg[7],peg[8],peg[9],peg[10])\n  print \" %s %s %s %s %s\" % (peg[11],peg[12],peg[13],peg[14],peg[15])\n\n\n\ndef RemovePeg(board,n):\n  board.remove(n)\n\n\ndef AddPeg(board,n):\n  board.append(n)\n\n\ndef IsPeg(board,n):\n  return n in board\n\n\n\nJumpMoves = { 1: [ (2,4),(3,6) ],  \n              2: [ (4,7),(5,9)  ],\n              3: [ (5,8),(6,10) ],\n              4: [ (2,1),(5,6),(7,11),(8,13) ],\n              5: [ (8,12),(9,14) ],\n              6: [ (3,1),(5,4),(9,13),(10,15) ],\n              7: [ (4,2),(8,9)  ],\n              8: [ (5,3),(9,10) ],\n              9: [ (5,2),(8,7)  ],\n             10: [ (9,8) ],\n             11: [ (12,13) ],\n             12: [ (8,5),(13,14) ],\n             13: [ (8,4),(9,6),(12,11),(14,15) ],\n             14: [ (9,5),(13,12)  ],\n             15: [ (10,6),(14,13) ]\n            }\n\nSolution = []\n\n\n\ndef Solve(board):\n  \n  if len(board) == 1:\n    return board \n  \n  for peg in xrange(1,16): \n    if IsPeg(board,peg):\n      movelist = JumpMoves[peg]\n      for over,land in movelist:\n        if IsPeg(board,over) and not IsPeg(board,land):\n          saveboard = board[:] \n          RemovePeg(board,peg)\n          RemovePeg(board,over)\n          AddPeg(board,land) \n\n          Solution.append((peg,over,land))\n\n          board = Solve(board)\n          if len(board) == 1:\n            return board\n        \n          board = saveboard[:] \n          del Solution[-1] \n  return board\n\n\n\n\ndef InitSolve(empty):\n  board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n  RemovePeg(board,empty_start)\n  Solve(board)\n\n\nempty_start = 1\nInitSolve(empty_start)\n\nboard = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nRemovePeg(board,empty_start)\nfor peg,over,land in Solution:\n  RemovePeg(board,peg)\n  RemovePeg(board,over)\n  AddPeg(board,land) \n  DrawBoard(board)\n  print \"Peg %X jumped over %X to land on %X\\n\" % (peg,over,land)\n"}
{"id": 46671, "name": "Non-transitive dice", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n    private static List<List<Integer>> fourFaceCombos() {\n        List<List<Integer>> res = new ArrayList<>();\n        Set<Integer> found = new HashSet<>();\n\n        for (int i = 1; i <= 4; i++) {\n            for (int j = 1; j <= 4; j++) {\n                for (int k = 1; k <= 4; k++) {\n                    for (int l = 1; l <= 4; l++) {\n                        List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());\n\n                        int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);\n                        if (found.add(key)) {\n                            res.add(c);\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static int cmp(List<Integer> x, List<Integer> y) {\n        int xw = 0;\n        int yw = 0;\n        for (int i = 0; i < 4; i++) {\n            for (int j = 0; j < 4; j++) {\n                if (x.get(i) > y.get(j)) {\n                    xw++;\n                } else if (x.get(i) < y.get(j)) {\n                    yw++;\n                }\n            }\n        }\n        return Integer.compare(xw, yw);\n    }\n\n    private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (List<Integer> kl : cs) {\n                        if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {\n                            res.add(List.of(cs.get(i), cs.get(j), kl));\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (int k = 0; k < cs.size(); k++) {\n                        if (cmp(cs.get(j), cs.get(k)) == -1) {\n                            for (List<Integer> ll : cs) {\n                                if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {\n                                    res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> combos = fourFaceCombos();\n        System.out.printf(\"Number of eligible 4-faced dice: %d%n\", combos.size());\n        System.out.println();\n\n        List<List<List<Integer>>> it3 = findIntransitive3(combos);\n        System.out.printf(\"%d ordered lists of 3 non-transitive dice found, namely:%n\", it3.size());\n        for (List<List<Integer>> a : it3) {\n            System.out.println(a);\n        }\n        System.out.println();\n\n        List<List<List<Integer>>> it4 = findIntransitive4(combos);\n        System.out.printf(\"%d ordered lists of 4 non-transitive dice found, namely:%n\", it4.size());\n        for (List<List<Integer>> a : it4) {\n            System.out.println(a);\n        }\n    }\n}\n", "Python": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n    dice = list(cmbr(faces, n))\n \n    succ = [set(j for j, b in enumerate(dice)\n                    if sum((x>y) - (x<y) for x in a for y in b) > 0)\n                for a in dice]\n \n    def loops(seq):\n        s = succ[seq[-1]]\n\n        if len(seq) == m:\n            if seq[0] in s: yield seq\n            return\n\n        for d in (x for x in s if x > seq[0] and not x in seq):\n            yield from loops(seq + (d,))\n \n    yield from (tuple(''.join(dice[s]) for s in x)\n                    for i, v in enumerate(succ)\n                    for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n    print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n    t, t0 = time(), t\n    print(f'\\ttime: {t - t0:.4f} seconds\\n')\n"}
{"id": 46672, "name": "History variables", "Java": "public class HistoryVariable\n{\n    private Object value;\n\n    public HistoryVariable(Object v)\n    {\n        value = v;\n    }\n\n    public void update(Object v)\n    {\n        value = v;\n    }\n\n    public Object undo()\n    {\n        return value;\n    }\n\n    @Override\n    public String toString()\n    {\n        return value.toString();\n    }\n\n    public void dispose()\n    {\n    }\n}\n", "Python": "import sys\n\nHIST = {}\n\ndef trace(frame, event, arg):\n    for name,val in frame.f_locals.items():\n        if name not in HIST:\n            HIST[name] = []\n        else:\n            if HIST[name][-1] is val:\n                continue\n        HIST[name].append(val)\n    return trace\n\ndef undo(name):\n    HIST[name].pop(-1)\n    return HIST[name][-1]\n\ndef main():\n    a = 10\n    a = 20\n\n    for i in range(5):\n        c = i\n\n    print \"c:\", c, \"-> undo x3 ->\",\n    c = undo('c')\n    c = undo('c')\n    c = undo('c')\n    print c\n    print 'HIST:', HIST\n\nsys.settrace(trace)\nmain()\n"}
{"id": 46673, "name": "Perceptron", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.util.*;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class Perceptron extends JPanel {\n\n    class Trainer {\n        double[] inputs;\n        int answer;\n\n        Trainer(double x, double y, int a) {\n            inputs = new double[]{x, y, 1};\n            answer = a;\n        }\n    }\n\n    Trainer[] training = new Trainer[2000];\n    double[] weights;\n    double c = 0.00001;\n    int count;\n\n    public Perceptron(int n) {\n        Random r = new Random();\n        Dimension dim = new Dimension(640, 360);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        weights = new double[n];\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] = r.nextDouble() * 2 - 1;\n        }\n\n        for (int i = 0; i < training.length; i++) {\n            double x = r.nextDouble() * dim.width;\n            double y = r.nextDouble() * dim.height;\n\n            int answer = y < f(x) ? -1 : 1;\n\n            training[i] = new Trainer(x, y, answer);\n        }\n\n        new Timer(10, (ActionEvent e) -> {\n            repaint();\n        }).start();\n    }\n\n    private double f(double x) {\n        return x * 0.7 + 40;\n    }\n\n    int feedForward(double[] inputs) {\n        assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n        double sum = 0;\n        for (int i = 0; i < weights.length; i++) {\n            sum += inputs[i] * weights[i];\n        }\n        return activate(sum);\n    }\n\n    int activate(double s) {\n        return s > 0 ? 1 : -1;\n    }\n\n    void train(double[] inputs, int desired) {\n        int guess = feedForward(inputs);\n        double error = desired - guess;\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] += c * error * inputs[i];\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        \n        int x = getWidth();\n        int y = (int) f(x);\n        g.setStroke(new BasicStroke(2));\n        g.setColor(Color.orange);\n        g.drawLine(0, (int) f(0), x, y);\n\n        train(training[count].inputs, training[count].answer);\n        count = (count + 1) % training.length;\n\n        g.setStroke(new BasicStroke(1));\n        g.setColor(Color.black);\n        for (int i = 0; i < count; i++) {\n            int guess = feedForward(training[i].inputs);\n\n            x = (int) training[i].inputs[0] - 4;\n            y = (int) training[i].inputs[1] - 4;\n\n            if (guess > 0)\n                g.drawOval(x, y, 8, 8);\n            else\n                g.fillOval(x, y, 8, 8);\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(\"Perceptron\");\n            f.setResizable(false);\n            f.add(new Perceptron(3), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "import random\n\nTRAINING_LENGTH = 2000\n\nclass Perceptron:\n    \n    def __init__(self,n):\n        self.c = .01\n        self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)]\n\n    def feed_forward(self, inputs):\n        vars = []\n        for i in range(len(inputs)):\n            vars.append(inputs[i] * self.weights[i])\n        return self.activate(sum(vars))\n\n    def activate(self, value):\n        return 1 if value > 0 else -1\n\n    def train(self, inputs, desired):\n        guess = self.feed_forward(inputs)\n        error = desired - guess\n        for i in range(len(inputs)):\n            self.weights[i] += self.c * error * inputs[i]\n        \nclass Trainer():\n    \n    def __init__(self, x, y, a):\n        self.inputs = [x, y, 1]\n        self.answer = a\n\ndef F(x):\n    return 2 * x + 1\n\nif __name__ == \"__main__\":\n    ptron = Perceptron(3)\n    training = []\n    for i in range(TRAINING_LENGTH):\n        x = random.uniform(-10,10)\n        y = random.uniform(-10,10)\n        answer = 1\n        if y < F(x): answer = -1\n        training.append(Trainer(x,y,answer))\n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Untrained')\n    for row in result:\n        print(''.join(v for v in row))\n\n    for t in training:\n        ptron.train(t.inputs, t.answer)\n    \n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Trained')\n    for row in result:\n        print(''.join(v for v in row))\n"}
{"id": 46674, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "Python": ">>> exec \n10\n"}
{"id": 46675, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "Python": ">>> exec \n10\n"}
{"id": 46676, "name": "Pisano period", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class PisanoPeriod {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Print pisano(p^2) for every prime p lower than 15%n\");\n        for ( long i = 2 ; i < 15 ; i++ ) { \n            if ( isPrime(i) ) {\n                long n = i*i; \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(p) for every prime p lower than 180%n\");\n        for ( long n = 2 ; n < 180 ; n++ ) { \n            if ( isPrime(n) ) { \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(n) for every integer from 1 to 180%n\");\n        for ( long n = 1 ; n <= 180 ; n++ ) { \n            System.out.printf(\"%3d  \", pisano(n));\n            if ( n % 10 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n\n        \n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\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    \n    private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();\n    static {\n        PERIOD_MEMO.put(2L, 3L);\n        PERIOD_MEMO.put(3L, 8L);\n        PERIOD_MEMO.put(5L, 20L);        \n    }\n    \n    \n    private static long pisano(long n) {\n        if ( PERIOD_MEMO.containsKey(n) ) {\n            return PERIOD_MEMO.get(n);\n        }\n        if ( n == 1 ) {\n            return 1;\n        }\n        Map<Long,Long> factors = getFactors(n);\n        \n        \n        \n        if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {\n            long result = 3 * n / 2;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 4*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 6*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        List<Long> primes = new ArrayList<>(factors.keySet());\n        long prime = primes.get(0);\n        if ( factors.size() == 1 && factors.get(prime) == 1 ) {\n            List<Long> divisors = new ArrayList<>();\n            if ( n % 10 == 1 || n % 10 == 9 ) {\n                for ( long divisor : getDivisors(prime-1) ) {\n                    if ( divisor % 2 == 0 ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            else {\n                List<Long> pPlus1Divisors = getDivisors(prime+1);\n                for ( long divisor : getDivisors(2*prime+2) ) {\n                    if ( !  pPlus1Divisors.contains(divisor) ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            Collections.sort(divisors);\n            for ( long divisor : divisors ) {\n                if ( fibModIdentity(divisor, prime) ) {\n                    PERIOD_MEMO.put(prime, divisor);\n                    return divisor;\n                }\n            }\n            throw new RuntimeException(\"ERROR 144: Divisor not found.\");\n        }\n        long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);\n        for ( int i = 1 ; i < primes.size() ; i++ ) {\n            prime = primes.get(i);\n            period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));\n        }\n        PERIOD_MEMO.put(n, period);\n        return period;\n    }\n    \n    \n    private static boolean fibModIdentity(long n, long mod) {\n        long aRes = 0;\n        long bRes = 1;\n        long cRes = 1;\n        long aBase = 0;\n        long bBase = 1;\n        long cBase = 1;\n        while ( n > 0 ) {\n            if ( n % 2 == 1 ) {\n                long temp1 = 0, temp2 = 0, temp3 = 0;\n                if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {\n                    temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;\n                    temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;\n                    temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;\n                }\n                else {\n                    temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;\n                    temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;\n                    temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;\n                }\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            n >>= 1L;\n            long temp1 = 0, temp2 = 0, temp3 = 0; \n            if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {\n                temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;\n                temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;\n                temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;\n            }\n            else {\n                temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;\n                temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;\n                temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;\n            }\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;\n    }\n\n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        \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        \n        return x % modulus;\n    }\n\n    private static final List<Long> getDivisors(long number) {\n        List<Long> divisors = new ArrayList<>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                long div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n    public static long lcm(long a, long b) {\n        return a*b/gcd(a,b);\n    }\n\n    public 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 final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();\n    static {\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        factors.put(2L, 1L);\n        allFactors.put(2L, factors);\n    }\n\n    public static Long MAX_ALL_FACTORS = 100000L;\n\n    public static final Map<Long,Long> getFactors(Long number) {\n        if ( allFactors.containsKey(number) ) {\n            return allFactors.get(number);\n        }\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        if ( number % 2 == 0 ) {\n            Map<Long,Long> factorsdDivTwo = getFactors(number/2);\n            factors.putAll(factorsdDivTwo);\n            factors.merge(2L, 1L, (v1, v2) -> v1 + v2);\n            if ( number < MAX_ALL_FACTORS ) {\n                allFactors.put(number, factors);\n            }\n            return factors;\n        }\n        boolean prime = true;\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 3 ; i <= sqrt ; i += 2 ) {\n            if ( number % i == 0 ) {\n                prime = false;\n                factors.putAll(getFactors(number/i));\n                factors.merge(i, 1L, (v1, v2) -> v1 + v2);\n                if ( number < MAX_ALL_FACTORS ) {\n                    allFactors.put(number, factors);\n                }\n                return factors;\n            }\n        }\n        if ( prime ) {\n            factors.put(number, 1L);\n            if ( number < MAX_ALL_FACTORS ) { \n                allFactors.put(number, factors);\n            }\n        }\n        return factors;\n    }\n\n}\n", "Python": "from sympy import isprime, lcm, factorint, primerange\nfrom functools import reduce\n\n\ndef pisano1(m):\n    \"Simple definition\"\n    if m < 2:\n        return 1\n    lastn, n = 0, 1\n    for i in range(m ** 2):\n        lastn, n = n, (lastn + n) % m\n        if lastn == 0 and n == 1:\n            return i + 1\n    return 1\n\ndef pisanoprime(p, k):\n    \"Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1\"\n    assert isprime(p) and k > 0\n    return p ** (k - 1) * pisano1(p)\n\ndef pisano_mult(m, n):\n    \"pisano(m*n) where m and n assumed coprime integers\"\n    return lcm(pisano1(m), pisano1(n))\n\ndef pisano2(m):\n    \"Uses prime factorization of m\"\n    return reduce(lcm, (pisanoprime(prime, mult)\n                        for prime, mult in factorint(m).items()), 1)\n\n\nif __name__ == '__main__':\n    for n in range(1, 181):\n        assert pisano1(n) == pisano2(n), \"Wall-Sun-Sun prime exists??!!\"\n    print(\"\\nPisano period (p, 2) for primes less than 50\\n \",\n          [pisanoprime(prime, 2) for prime in primerange(1, 50)])\n    print(\"\\nPisano period (p, 1) for primes less than 180\\n \",\n          [pisanoprime(prime, 1) for prime in primerange(1, 180)])\n    print(\"\\nPisano period (p) for integers 1 to 180\")\n    for i in range(1, 181):\n        print(\" %3d\" % pisano2(i), end=\"\" if i % 10 else \"\\n\")\n"}
{"id": 46677, "name": "Railway circuit", "Java": "package railwaycircuit;\n\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.IntStream.range;\n\npublic class RailwayCircuit {\n    final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0;\n\n    static String normalize(int[] tracks) {\n        char[] a = new char[tracks.length];\n        for (int i = 0; i < a.length; i++)\n            a[i] = \"abc\".charAt(tracks[i] + 1);\n\n        \n        String norm = new String(a);\n        for (int i = 0, len = a.length; i < len; i++) {\n\n            String s = new String(a);\n            if (s.compareTo(norm) < 0)\n                norm = s;\n\n            char tmp = a[0];\n            for (int j = 1; j < a.length; j++)\n                a[j - 1] = a[j];\n            a[len - 1] = tmp;\n        }\n        return norm;\n    }\n\n    static boolean fullCircleStraight(int[] tracks, int nStraight) {\n        if (nStraight == 0)\n            return true;\n\n        \n        if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight)\n            return false;\n\n        \n        int[] straight = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == STRAIGHT)\n                straight[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6])\n                && range(0, 8).anyMatch(i -> straight[i] != straight[i + 4]));\n    }\n\n    static boolean fullCircleRight(int[] tracks) {\n\n        \n        if (stream(tracks).map(i -> i * 30).sum() % 360 != 0)\n            return false;\n\n        \n        int[] rTurns = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == RIGHT)\n                rTurns[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6])\n                && range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4]));\n    }\n\n    static void circuits(int nCurved, int nStraight) {\n        Map<String, int[]> solutions = new HashMap<>();\n\n        PermutationsGen gen = getPermutationsGen(nCurved, nStraight);\n        while (gen.hasNext()) {\n\n            int[] tracks = gen.next();\n\n            if (!fullCircleStraight(tracks, nStraight))\n                continue;\n\n            if (!fullCircleRight(tracks))\n                continue;\n\n            solutions.put(normalize(tracks), tracks.clone());\n        }\n        report(solutions, nCurved, nStraight);\n    }\n\n    static PermutationsGen getPermutationsGen(int nCurved, int nStraight) {\n        assert (nCurved + nStraight - 12) % 4 == 0 : \"input must be 12 + k * 4\";\n\n        int[] trackTypes = new int[]{RIGHT, LEFT};\n\n        if (nStraight != 0) {\n            if (nCurved == 12)\n                trackTypes = new int[]{RIGHT, STRAIGHT};\n            else\n                trackTypes = new int[]{RIGHT, LEFT, STRAIGHT};\n        }\n\n        return new PermutationsGen(nCurved + nStraight, trackTypes);\n    }\n\n    static void report(Map<String, int[]> sol, int numC, int numS) {\n\n        int size = sol.size();\n        System.out.printf(\"%n%d solution(s) for C%d,%d %n\", size, numC, numS);\n\n        if (size < 10)\n            sol.values().stream().forEach(tracks -> {\n                stream(tracks).forEach(i -> System.out.printf(\"%2d \", i));\n                System.out.println();\n            });\n    }\n\n    public static void main(String[] args) {\n        circuits(12, 0);\n        circuits(16, 0);\n        circuits(20, 0);\n        circuits(24, 0);\n        circuits(12, 4);\n    }\n}\n\nclass PermutationsGen {\n    \n    private int[] indices;\n    private int[] choices;\n    private int[] sequence;\n    private int carry;\n\n    PermutationsGen(int numPositions, int[] choices) {\n        indices = new int[numPositions];\n        sequence = new int[numPositions];\n        this.choices = choices;\n    }\n\n    int[] next() {\n        carry = 1;\n        \n        for (int i = 1; i < indices.length && carry > 0; i++) {\n            indices[i] += carry;\n            carry = 0;\n\n            if (indices[i] == choices.length) {\n                carry = 1;\n                indices[i] = 0;\n            }\n        }\n\n        for (int i = 0; i < indices.length; i++)\n            sequence[i] = choices[indices[i]];\n\n        return sequence;\n    }\n\n    boolean hasNext() {\n        return carry != 1;\n    }\n}\n", "Python": "from itertools import count, islice\nimport numpy as np\nfrom numpy import sin, cos, pi\n\n\nANGDIV = 12\nANG = 2*pi/ANGDIV\n\ndef draw_all(sols):\n    import matplotlib.pyplot as plt\n\n    def draw_track(ax, s):\n        turn, xend, yend = 0, [0], [0]\n\n        for d in s:\n            x0, y0 = xend[-1], yend[-1]\n            a = turn*ANG\n            cs, sn = cos(a), sin(a)\n            ang = a + d*pi/2\n            cx, cy = x0 + cos(ang), y0 + sin(ang)\n\n            da = np.linspace(ang, ang + d*ANG, 10)\n            xs = cx - cos(da)\n            ys = cy - sin(da)\n            ax.plot(xs, ys, 'green' if d == -1 else 'orange')\n\n            xend.append(xs[-1])\n            yend.append(ys[-1])\n            turn += d\n\n        ax.plot(xend, yend, 'k.', markersize=1)\n        ax.set_aspect(1)\n\n    ls = len(sols)\n    if ls == 0: return\n\n    w, h = min((abs(w*2 - h*3) + w*h - ls, w, h)\n        for w, h in ((w, (ls + w - 1)//w)\n            for w in range(1, ls + 1)))[1:]\n\n    fig, ax = plt.subplots(h, w, squeeze=False)\n    for a in ax.ravel(): a.set_axis_off()\n\n    for i, s in enumerate(sols):\n        draw_track(ax[i//w, i%w], s)\n\n    plt.show()\n\n\ndef match_up(this, that, equal_lr, seen):\n    if not this or not that: return\n\n    n = len(this[0][-1])\n    n2 = n*2\n\n    l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0\n\n    def record(m):\n        for _ in range(n2):\n            seen[m] = True\n            m = (m&1) << (n2 - 1) | (m >> 1)\n\n        if equal_lr:\n            m ^= (1<<n2) - 1\n            for _ in range(n2):\n                seen[m] = True\n                m = (m&1) << (n2 - 1) | (m >> 1)\n\n    l_n, r_n = len(this), len(that)\n    tol = 1e-3\n\n    while l_lo < l_n:\n        while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol:\n            l_hi += 1\n\n        while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol:\n            r_lo += 1\n\n        r_hi = r_lo\n        while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol:\n            r_hi += 1\n\n        for a in this[l_lo:l_hi]:\n            m_left = a[-2]<<n\n            for b in that[r_lo:r_hi]:\n                if (m := m_left | b[-2]) not in seen:\n                    if np.abs(a[1] + b[2]) < tol:\n                        record(m)\n                        record(int(f'{m:b}'[::-1], base=2))\n                        yield(a[-1] + b[-1])\n\n        l_lo, r_lo = l_hi, r_hi\n\ndef track_combo(left, right):\n    n = (left + right)//2\n    n1 = left + right - n\n\n    alphas = np.exp(1j*ANG*np.arange(ANGDIV))\n    def half_track(m, n):\n        turns = tuple(1 - 2*(m>>i & 1) for i in range(n))\n        rcnt = np.cumsum(turns)%ANGDIV\n        asum = np.sum(alphas[rcnt])\n        want = asum/alphas[rcnt[-1]]\n        return np.abs(asum), asum, want, m, turns\n\n    res = [[] for _ in range(right + 1)]\n    for i in range(1<<n):\n        b = i.bit_count()\n        if b <= right:\n            res[b].append(half_track(i, n))\n\n    for v in res: v.sort()\n    if n1 == n:\n        return res, res\n\n    res1 = [[] for _ in range(right + 1)]\n    for i in range(1<<n1):\n        b = i.bit_count()\n        if b <= right:\n            res1[b].append(half_track(i, n1))\n\n    for v in res: v.sort()\n    return res, res1\n\ndef railway(n):\n    seen = {}\n\n    for l in range(n//2, n + 1):\n        r = n - l\n        if not l >= r: continue\n\n        if (l - r)%ANGDIV == 0:\n            res_l, res_r = track_combo(l, r)\n\n            for i, this in enumerate(res_l):\n                if 2*i < r: continue\n                that = res_r[r - i]\n                for s in match_up(this, that, l == r, seen):\n                    yield s\n\nsols = []\nfor i, s in enumerate(railway(30)):\n    \n    print(i + 1, s)\n    sols.append(s)\n\ndraw_all(sols[:40])\n"}
{"id": 46678, "name": "Distance and Bearing", "Java": "\npackage distanceAndBearing;\npublic class Airport {\n\tprivate String airport;\n\tprivate String country;\n\tprivate String icao;\n\tprivate double lat;\n\tprivate double lon;\n\tpublic String getAirportName() {\treturn this.airport;\t}\n\tpublic void setAirportName(String airport) {\tthis.airport = airport; }\n\tpublic String getCountry() {\treturn this.country;\t}\n\tpublic void setCountry(String country) {\tthis.country = country;\t}\n\tpublic String getIcao() { return this.icao; }\n\tpublic void setIcao(String icao) { this.icao = icao;\t}\n\tpublic double getLat() {\treturn this.lat; }\n\tpublic void setLat(double lat) {\tthis.lat = lat;\t}\n\tpublic double getLon() {\treturn this.lon; }\n\tpublic void setLon(double lon) {\tthis.lon = lon;\t}\n\t@Override\n\tpublic String toString() {return \"Airport: \" + getAirportName() + \": ICAO: \" + getIcao();}\n}\n\n\npackage distanceAndBearing;\nimport java.io.File;\nimport java.text.DecimalFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.stream.Collectors;\npublic class DistanceAndBearing {\n\tprivate final double earthRadius = 6371;\n\tprivate File datFile;\n\tprivate List<Airport> airports;\n\tpublic DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }\n\tpublic boolean readFile(String filename) {\n\t\tthis.datFile = new File(filename);\n\t\ttry {\n\t\t\tScanner fileScanner = new Scanner(datFile);\n\t\t\tString line;\n\t\t\twhile (fileScanner.hasNextLine()) {\n\t\t\t\tline = fileScanner.nextLine();\n\t\t\t\tline = line.replace(\", \", \"; \"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tline = line.replace(\",\\\",\\\"\", \"\\\",\\\"\"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tString[] parts = line.split(\",\");\n\t\t\t\tAirport airport = new Airport();\n\t\t\t\tairport.setAirportName(parts[1].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setCountry(parts[3].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setIcao(parts[5].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setLat(Double.valueOf(parts[6]));\n\t\t\t\tairport.setLon(Double.valueOf(parts[7]));\n\t\t\t\tthis.airports.add(airport);\n\t\t\t}\n\t\t\tfileScanner.close();\n\t\t\treturn true; \n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false; \n\t\t}}\n\tpublic double[] calculate(double lat1, double lon1, double lat2, double lon2) {\n\t\tdouble[] results = new double[2];\n\t\tdouble dLat = Math.toRadians(lat2 - lat1);\n\t\tdouble dLon = Math.toRadians(lon2 - lon1);\n\t\tdouble rlat1 = Math.toRadians(lat1);\n\t\tdouble rlat2 = Math.toRadians(lat2);\n\t\tdouble a = Math.pow(Math.sin(dLat / 2), 2)\n\t\t\t\t+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);\n\t\tdouble c = 2 * Math.asin(Math.sqrt(a));\n\t\tdouble distance = earthRadius * c;\n\t\tDecimalFormat df = new DecimalFormat(\"#0.00\");\n\t\tdistance = Double.valueOf(df.format(distance));\n\t\tresults[0] = distance;\n\t\tdouble X = Math.cos(rlat2) * Math.sin(dLon);\n\t\tdouble Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);\n\t\tdouble heading = Math.atan2(X, Y);\n\t\theading = Math.toDegrees(heading);\n\t\tresults[1] = heading;\n\t\treturn results;\n\t}\n\tpublic Airport searchByName(final String name) {\n\t\tAirport airport = new Airport();\n\t\tList<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))\n\t\t\t\t.collect(Collectors.toList());\n\t\tairport = results.get(0);\n\t\treturn airport;\n\t}\n\tpublic List<Airport> findClosestAirports(double lat, double lon) {\n\t\t\n\t\tMap<Double, Airport> airportDistances = new HashMap<>();\n\t\tMap<Double, Airport> airportHeading = new HashMap<>();\n\t\tList<Airport> closestAirports = new ArrayList<Airport>();\n\t\t\n\t\t\n\t\tfor (Airport ap : this.airports) {\n\t\t\tdouble[] result = calculate(lat, lon, ap.getLat(), ap.getLon());\n\t\t\tairportDistances.put(result[0], ap);\n\t\t\tairportHeading.put(result[1], ap);\n\t\t}\n\t\t\n\t\tArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());\n\t\tCollections.sort(distances);\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tfor (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}\n\t\t\n\t\tMap<String, Double> distanceMap = new HashMap<>();\n\t\tfor (Double d : airportDistances.keySet()) {\tdistanceMap.put(airportDistances.get(d).getAirportName(), d);}\n\t\tMap<String, Double> headingMap = new HashMap<>();\n\t\tfor (Double d : airportHeading.keySet()) { \n            double d2 = d;\n            if(d2<0){d2+=360'}\n            headingMap.put(airportHeading.get(d).getAirportName(), d2); }\n\n\t\t\n\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12s %15s\\n\", \"Num\", \"Airport\", \"Country\", \"ICAO\", \"Distance\", \"Bearing\");\n\t\tSystem.out.println(\"-----------------------------------------------------------------------------------------------------------\");\n\t\tint i = 0;\n\t\tfor (Airport a : closestAirports) {\n\t\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12.1f %15.0f\\n\", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));\n\t\t}\n\t\treturn closestAirports;\n\t}\n}\n", "Python": "\n\nfrom math import radians, degrees, sin, cos, asin, atan2, sqrt\nfrom pandas import read_csv\n\n\nEARTH_RADIUS_KM = 6372.8\nTASK_CONVERT_NM =  0.0094174\nAIRPORT_DATA_FILE = 'airports.dat.txt'\n\nQUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n    \n    rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]\n    dlat = rlat2 - rlat1\n    dlon = rlon2 - rlon1\n    arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2\n    clen = 2.0 * degrees(asin(sqrt(arc)))\n    theta = atan2(sin(dlon) * cos(rlat2),\n                  cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))\n    theta = (degrees(theta) + 360) % 360\n    return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta\n\n\ndef find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):\n    \n    airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[\n                        'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])\n    airports['Distance'] = 0.0\n    airports['Bearing'] = 0\n    for (idx, row) in enumerate(airports.itertuples()):\n        distance, bearing = haversine(\n            latitude, longitude, row.Latitude, row.Longitude)\n        airports.at[idx, 'Distance'] = round(distance, ndigits=1)\n        airports.at[idx, 'Bearing'] = int(round(bearing))\n\n    airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)\n    return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]\n\n\nprint(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))\n"}
{"id": 46679, "name": "Distance and Bearing", "Java": "\npackage distanceAndBearing;\npublic class Airport {\n\tprivate String airport;\n\tprivate String country;\n\tprivate String icao;\n\tprivate double lat;\n\tprivate double lon;\n\tpublic String getAirportName() {\treturn this.airport;\t}\n\tpublic void setAirportName(String airport) {\tthis.airport = airport; }\n\tpublic String getCountry() {\treturn this.country;\t}\n\tpublic void setCountry(String country) {\tthis.country = country;\t}\n\tpublic String getIcao() { return this.icao; }\n\tpublic void setIcao(String icao) { this.icao = icao;\t}\n\tpublic double getLat() {\treturn this.lat; }\n\tpublic void setLat(double lat) {\tthis.lat = lat;\t}\n\tpublic double getLon() {\treturn this.lon; }\n\tpublic void setLon(double lon) {\tthis.lon = lon;\t}\n\t@Override\n\tpublic String toString() {return \"Airport: \" + getAirportName() + \": ICAO: \" + getIcao();}\n}\n\n\npackage distanceAndBearing;\nimport java.io.File;\nimport java.text.DecimalFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.stream.Collectors;\npublic class DistanceAndBearing {\n\tprivate final double earthRadius = 6371;\n\tprivate File datFile;\n\tprivate List<Airport> airports;\n\tpublic DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }\n\tpublic boolean readFile(String filename) {\n\t\tthis.datFile = new File(filename);\n\t\ttry {\n\t\t\tScanner fileScanner = new Scanner(datFile);\n\t\t\tString line;\n\t\t\twhile (fileScanner.hasNextLine()) {\n\t\t\t\tline = fileScanner.nextLine();\n\t\t\t\tline = line.replace(\", \", \"; \"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tline = line.replace(\",\\\",\\\"\", \"\\\",\\\"\"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tString[] parts = line.split(\",\");\n\t\t\t\tAirport airport = new Airport();\n\t\t\t\tairport.setAirportName(parts[1].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setCountry(parts[3].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setIcao(parts[5].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setLat(Double.valueOf(parts[6]));\n\t\t\t\tairport.setLon(Double.valueOf(parts[7]));\n\t\t\t\tthis.airports.add(airport);\n\t\t\t}\n\t\t\tfileScanner.close();\n\t\t\treturn true; \n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false; \n\t\t}}\n\tpublic double[] calculate(double lat1, double lon1, double lat2, double lon2) {\n\t\tdouble[] results = new double[2];\n\t\tdouble dLat = Math.toRadians(lat2 - lat1);\n\t\tdouble dLon = Math.toRadians(lon2 - lon1);\n\t\tdouble rlat1 = Math.toRadians(lat1);\n\t\tdouble rlat2 = Math.toRadians(lat2);\n\t\tdouble a = Math.pow(Math.sin(dLat / 2), 2)\n\t\t\t\t+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);\n\t\tdouble c = 2 * Math.asin(Math.sqrt(a));\n\t\tdouble distance = earthRadius * c;\n\t\tDecimalFormat df = new DecimalFormat(\"#0.00\");\n\t\tdistance = Double.valueOf(df.format(distance));\n\t\tresults[0] = distance;\n\t\tdouble X = Math.cos(rlat2) * Math.sin(dLon);\n\t\tdouble Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);\n\t\tdouble heading = Math.atan2(X, Y);\n\t\theading = Math.toDegrees(heading);\n\t\tresults[1] = heading;\n\t\treturn results;\n\t}\n\tpublic Airport searchByName(final String name) {\n\t\tAirport airport = new Airport();\n\t\tList<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))\n\t\t\t\t.collect(Collectors.toList());\n\t\tairport = results.get(0);\n\t\treturn airport;\n\t}\n\tpublic List<Airport> findClosestAirports(double lat, double lon) {\n\t\t\n\t\tMap<Double, Airport> airportDistances = new HashMap<>();\n\t\tMap<Double, Airport> airportHeading = new HashMap<>();\n\t\tList<Airport> closestAirports = new ArrayList<Airport>();\n\t\t\n\t\t\n\t\tfor (Airport ap : this.airports) {\n\t\t\tdouble[] result = calculate(lat, lon, ap.getLat(), ap.getLon());\n\t\t\tairportDistances.put(result[0], ap);\n\t\t\tairportHeading.put(result[1], ap);\n\t\t}\n\t\t\n\t\tArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());\n\t\tCollections.sort(distances);\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tfor (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}\n\t\t\n\t\tMap<String, Double> distanceMap = new HashMap<>();\n\t\tfor (Double d : airportDistances.keySet()) {\tdistanceMap.put(airportDistances.get(d).getAirportName(), d);}\n\t\tMap<String, Double> headingMap = new HashMap<>();\n\t\tfor (Double d : airportHeading.keySet()) { \n            double d2 = d;\n            if(d2<0){d2+=360'}\n            headingMap.put(airportHeading.get(d).getAirportName(), d2); }\n\n\t\t\n\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12s %15s\\n\", \"Num\", \"Airport\", \"Country\", \"ICAO\", \"Distance\", \"Bearing\");\n\t\tSystem.out.println(\"-----------------------------------------------------------------------------------------------------------\");\n\t\tint i = 0;\n\t\tfor (Airport a : closestAirports) {\n\t\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12.1f %15.0f\\n\", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));\n\t\t}\n\t\treturn closestAirports;\n\t}\n}\n", "Python": "\n\nfrom math import radians, degrees, sin, cos, asin, atan2, sqrt\nfrom pandas import read_csv\n\n\nEARTH_RADIUS_KM = 6372.8\nTASK_CONVERT_NM =  0.0094174\nAIRPORT_DATA_FILE = 'airports.dat.txt'\n\nQUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n    \n    rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]\n    dlat = rlat2 - rlat1\n    dlon = rlon2 - rlon1\n    arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2\n    clen = 2.0 * degrees(asin(sqrt(arc)))\n    theta = atan2(sin(dlon) * cos(rlat2),\n                  cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))\n    theta = (degrees(theta) + 360) % 360\n    return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta\n\n\ndef find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):\n    \n    airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[\n                        'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])\n    airports['Distance'] = 0.0\n    airports['Bearing'] = 0\n    for (idx, row) in enumerate(airports.itertuples()):\n        distance, bearing = haversine(\n            latitude, longitude, row.Latitude, row.Longitude)\n        airports.at[idx, 'Distance'] = round(distance, ndigits=1)\n        airports.at[idx, 'Bearing'] = int(round(bearing))\n\n    airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)\n    return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]\n\n\nprint(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))\n"}
{"id": 46680, "name": "Free polyominoes enumeration", "Java": "import java.awt.Point;\nimport java.util.*;\nimport static java.util.Arrays.asList;\nimport java.util.function.Function;\nimport static java.util.Comparator.comparing;\nimport static java.util.stream.Collectors.toList;\n\npublic class FreePolyominoesEnum {\n    static final List<Function<Point, Point>> transforms = new ArrayList<>();\n\n    static {\n        transforms.add(p -> new Point(p.y, -p.x));\n        transforms.add(p -> new Point(-p.x, -p.y));\n        transforms.add(p -> new Point(-p.y, p.x));\n        transforms.add(p -> new Point(-p.x, p.y));\n        transforms.add(p -> new Point(-p.y, -p.x));\n        transforms.add(p -> new Point(p.x, -p.y));\n        transforms.add(p -> new Point(p.y, p.x));\n    }\n\n    static Point findMinima(List<Point> poly) {\n        return new Point(\n                poly.stream().mapToInt(a -> a.x).min().getAsInt(),\n                poly.stream().mapToInt(a -> a.y).min().getAsInt());\n    }\n\n    static List<Point> translateToOrigin(List<Point> poly) {\n        final Point min = findMinima(poly);\n        poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));\n        return poly;\n    }\n\n    static List<List<Point>> rotationsAndReflections(List<Point> poly) {\n        List<List<Point>> lst = new ArrayList<>();\n        lst.add(poly);\n        for (Function<Point, Point> t : transforms)\n            lst.add(poly.stream().map(t).collect(toList()));\n        return lst;\n    }\n\n    static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)\n            .thenComparingInt(p -> p.y);\n\n    static List<Point> normalize(List<Point> poly) {\n        return rotationsAndReflections(poly).stream()\n                .map(lst -> translateToOrigin(lst))\n                .map(lst -> lst.stream().sorted(byCoords).collect(toList()))\n                .min(comparing(Object::toString)) \n                .get();\n    }\n\n    static List<Point> neighborhoods(Point p) {\n        return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),\n                new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));\n    }\n\n    static List<Point> concat(List<Point> lst, Point pt) {\n        List<Point> r = new ArrayList<>();\n        r.addAll(lst);\n        r.add(pt);\n        return r;\n    }\n\n    static List<Point> newPoints(List<Point> poly) {\n        return poly.stream()\n                .flatMap(p -> neighborhoods(p).stream())\n                .filter(p -> !poly.contains(p))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> constructNextRank(List<Point> poly) {\n        return newPoints(poly).stream()\n                .map(p -> normalize(concat(poly, p)))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> rank(int n) {\n        if (n < 0)\n            throw new IllegalArgumentException(\"n cannot be negative\");\n\n        if (n < 2) {\n            List<List<Point>> r = new ArrayList<>();\n            if (n == 1)\n                r.add(asList(new Point(0, 0)));\n            return r;\n        }\n\n        return rank(n - 1).stream()\n                .parallel()\n                .flatMap(lst -> constructNextRank(lst).stream())\n                .distinct()\n                .collect(toList());\n    }\n\n    public static void main(String[] args) {\n        for (List<Point> poly : rank(5)) {\n            for (Point p : poly)\n                System.out.printf(\"(%d,%d) \", p.x, p.y);\n            System.out.println();\n        }\n    }\n}\n", "Python": "from itertools import imap, imap, groupby, chain, imap\nfrom operator import itemgetter\nfrom sys import argv\nfrom array import array\n\ndef concat_map(func, it):\n    return list(chain.from_iterable(imap(func, it)))\n\ndef minima(poly):\n    \n    return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))\n\ndef translate_to_origin(poly):\n    (minx, miny) = minima(poly)\n    return [(x - minx, y - miny) for (x, y) in poly]\n\nrotate90   = lambda (x, y): ( y, -x)\nrotate180  = lambda (x, y): (-x, -y)\nrotate270  = lambda (x, y): (-y,  x)\nreflect    = lambda (x, y): (-x,  y)\n\ndef rotations_and_reflections(poly):\n    \n    return (poly,\n            map(rotate90, poly),\n            map(rotate180, poly),\n            map(rotate270, poly),\n            map(reflect, poly),\n            [reflect(rotate90(pt)) for pt in poly],\n            [reflect(rotate180(pt)) for pt in poly],\n            [reflect(rotate270(pt)) for pt in poly])\n\ndef canonical(poly):\n    return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly))\n\ndef unique(lst):\n    lst.sort()\n    return map(next, imap(itemgetter(1), groupby(lst)))\n\n\ncontiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]\n\ndef new_points(poly):\n    \n    return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly])\n\ndef new_polys(poly):\n    return unique([canonical(poly + [pt]) for pt in new_points(poly)])\n\nmonomino = [(0, 0)]\nmonominoes = [monomino]\n\ndef rank(n):\n    \n    assert n >= 0\n    if n == 0: return []\n    if n == 1: return monominoes\n    return unique(concat_map(new_polys, rank(n - 1)))\n\ndef text_representation(poly):\n    \n    min_pt = minima(poly)\n    max_pt = (max(p[0] for p in poly), max(p[1] for p in poly))\n    table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1)\n             for _ in xrange(max_pt[0] - min_pt[0] + 1)]\n    for pt in poly:\n        table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = '\n    return \"\\n\".join(row.tostring() for row in table)\n\ndef main():\n    print [len(rank(n)) for n in xrange(1, 11)]\n\n    n = int(argv[1]) if (len(argv) == 2) else 5\n    print \"\\nAll free polyominoes of rank %d:\" % n\n\n    for poly in rank(n):\n        print text_representation(poly), \"\\n\"\n\nmain()\n"}
{"id": 46681, "name": "Use a REST API", "Java": "package src;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.net.URI;\n\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\n\n\n\npublic class EventGetter {\n\t\n\n\tString city = \"\";\n\tString topic = \"\";\n\t\n\tpublic String getEvent(String path_code,String key) throws Exception{\n\t\tString responseString = \"\";\n\t\t\n\t\tURI request = new URIBuilder()\t\t\t\n\t\t\t.setScheme(\"http\")\n\t\t\t.setHost(\"api.meetup.com\")\n\t\t\t.setPath(path_code)\n\t\t\t\n\t\t\t.setParameter(\"topic\", topic)\n\t\t\t.setParameter(\"city\", city)\n\t\t\t\n\t\t\t.setParameter(\"key\", key)\n\t\t\t.build();\n\t\t\n\t\tHttpGet get = new HttpGet(request);\t\t\t\n\t\tSystem.out.println(\"Get request : \"+get.toString());\n\t\t\n\t\tCloseableHttpClient client = HttpClients.createDefault();\n\t\tCloseableHttpResponse response = client.execute(get);\n\t\tresponseString = EntityUtils.toString(response.getEntity());\n\t\t\n\t\treturn responseString;\n\t}\n\t\n\tpublic String getApiKey(String key_path){\n\t\tString key = \"\";\n\t\t\n\t\ttry{\n\t\t\tBufferedReader reader = new BufferedReader(new FileReader(key_path));\t\n\t\t\tkey = reader.readLine().toString();\t\t\t\t\t\t\t\t\t\n\t\t\treader.close();\n\t\t}\n\t\tcatch(Exception e){System.out.println(e.toString());}\n\t\t\n\t\treturn key;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t}\n\t\n}\n", "Python": "\nimport requests\nimport json\n\ncity = None\ntopic = None\n\ndef getEvent(url_path, key) :\n    responseString = \"\"\n    \n    params = {'city':city, 'key':key,'topic':topic}\n    r = requests.get(url_path, params = params)    \n    print(r.url)    \n    responseString = r.text\n    return responseString\n\n\ndef getApiKey(key_path):\n    key = \"\"\n    f = open(key_path, 'r')\n    key = f.read()\n    return key\n\n\ndef submitEvent(url_path,params):\n    r = requests.post(url_path, data=json.dumps(params))        \n    print(r.text+\" : Event Submitted\")\n"}
{"id": 46682, "name": "Twelve statements", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n"}
{"id": 46683, "name": "Deming's funnel", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n"}
{"id": 46684, "name": "Deming's funnel", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n"}
{"id": 46685, "name": "Rosetta Code_Fix code tags", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\n\npublic class FixCodeTags \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tString sourcefile=args[0];\n\t\tString convertedfile=args[1];\n\t\tconvert(sourcefile,convertedfile);\n\t}\n\t\tstatic String[] languages = {\"abap\", \"actionscript\", \"actionscript3\",\n\t\t\t\"ada\", \"apache\", \"applescript\", \"apt_sources\", \"asm\", \"asp\",\n\t\t\t\"autoit\", \"avisynth\", \"bar\", \"bash\", \"basic4gl\", \"bf\",\n\t\t\t\"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\",\n\t\t\t\"cfm\", \"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\",\n\t\t\t\"d\", \"delphi\", \"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\",\n\t\t\t\"foo\", \"fortran\", \"freebasic\", \"genero\", \"gettext\", \"glsl\", \"gml\",\n\t\t\t\"gnuplot\", \"go\", \"groovy\", \"haskell\", \"hq9plus\", \"html4strict\",\n\t\t\t\"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\", \"java5\",\n\t\t\t\"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\",\n\t\t\t\"m68k\", \"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\",\n\t\t\t\"mysql\", \"nsis\", \"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\",\n\t\t\t\"oracle11\", \"oracle8\", \"pascal\", \"per\", \"perl\", \"php\", \"php-brief\",\n\t\t\t\"pic16\", \"pixelbender\", \"plsql\", \"povray\", \"powershell\",\n\t\t\t\"progress\", \"prolog\", \"providex\", \"python\", \"qbasic\", \"rails\",\n\t\t\t\"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\", \"scilab\",\n\t\t\t\"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\",\n\t\t\t\"verilog\", \"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\",\n\t\t\t\"whitespace\", \"winbatch\", \"xml\", \"xorg_conf\", \"xpp\", \"z80\"};\n\tstatic void convert(String sourcefile,String convertedfile)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedReader br=new BufferedReader(new FileReader(sourcefile));\n\t\t\t\n\t\t\tStringBuffer sb=new StringBuffer(\"\");\n\t\t\tString line;\n\t\t\twhile((line=br.readLine())!=null)\n\t\t\t{\n\t\t\t\tfor(int i=0;i<languages.length;i++)\n\t\t\t\t{\n\t\t\t\t\tString lang=languages[i];\n\t\t\t\t\tline=line.replaceAll(\"<\"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</\"+lang+\">\", \"</\"+\"lang>\");\n\t\t\t\t\tline=line.replaceAll(\"<code \"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</code>\", \"</\"+\"lang>\");\n\t\t\t\t}\n\t\t\t\tsb.append(line);\n\t\t\t}\n\t\t\tbr.close();\n\t\t\t\n\t\t\tFileWriter fw=new FileWriter(new File(convertedfile));\n\t\t\t\n\t\t\tfw.write(sb.toString());\n\t\t\tfw.close();\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tSystem.out.println(\"Something went horribly wrong: \"+e.getMessage());\n\t\t}\n\t}\n}\n", "Python": "\n\nfrom re import sub\n\ntesttexts = [\n,\n    ,\n    ]\n\nfor txt in testtexts:\n    text2 = sub(r'<lang\\s+\\\"?([\\w\\d\\s]+)\\\"?\\s?>', r'<syntaxhighlight lang=\\1>', txt)\n    text2 = sub(r'<lang\\s*>', r'<syntaxhighlight lang=text>', text2)\n    text2 = sub(r'</lang\\s*>', r'\n"}
{"id": 46686, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46687, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46688, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 46689, "name": "One-time pad", "Java": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class OneTimePad {\n\n    public static void main(String[] args) {\n        String controlName = \"AtomicBlonde\";\n        generatePad(controlName, 5, 60, 65, 90);\n        String text = \"IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES\";\n        String encrypted = parse(true, controlName, text.replaceAll(\" \", \"\"));\n        String decrypted = parse(false, controlName, encrypted);\n        System.out.println(\"Input  text    = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n\n        controlName = \"AtomicBlondeCaseSensitive\";\n        generatePad(controlName, 5, 60, 32, 126);\n        text = \"It was the best of times, it was the worst of times.\";\n        encrypted = parse(true, controlName, text);\n        decrypted = parse(false, controlName, encrypted);\n        System.out.println();\n        System.out.println(\"Input text     = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n    }\n    \n    private static String parse(boolean encryptText, String controlName, String text) {\n        StringBuilder sb = new StringBuilder();\n        int minCh = 0;\n        int maxCh = 0;\n        Pattern minChPattern = Pattern.compile(\"^#  MIN_CH = ([\\\\d]+)$\");\n        Pattern maxChPattern = Pattern.compile(\"^#  MAX_CH = ([\\\\d]+)$\");\n        boolean validated = false;\n        try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {\n            String inLine = null;\n            while ( (inLine = in.readLine()) != null ) {\n                Matcher minMatcher = minChPattern.matcher(inLine);\n                if ( minMatcher.matches() ) {\n                    minCh = Integer.parseInt(minMatcher.group(1));\n                    continue;\n                }\n                Matcher maxMatcher = maxChPattern.matcher(inLine);\n                if ( maxMatcher.matches() ) {\n                    maxCh = Integer.parseInt(maxMatcher.group(1));\n                    continue;\n                }\n                if ( ! validated && minCh > 0 && maxCh > 0 ) {\n                    validateText(text, minCh, maxCh);\n                    validated = true;\n                }\n                \n                if ( inLine.startsWith(\"#\") || inLine.startsWith(\"-\") ) {\n                    continue;\n                }\n                \n                String key = inLine;\n                if ( encryptText ) {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));\n                    }\n                }\n                else {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        int decrypt = text.charAt(i) - key.charAt(i);\n                        if ( decrypt < 0 ) {\n                            decrypt += maxCh - minCh + 1;\n                        }\n                        decrypt += minCh;\n                        sb.append((char) decrypt);\n                    }\n                }\n                break;\n            }\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n        return sb.toString();\n    }\n\n    private static void validateText(String text, int minCh, int maxCh) {\n        \n        for ( char ch : text.toCharArray() ) {\n            if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {\n                throw new IllegalArgumentException(\"ERROR 103:  Invalid text.\");\n            }\n        }\n        \n    }\n    \n    private static String getFileName(String controlName) {\n        return controlName + \".1tp\";\n    }\n    \n    private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {\n        Random random = new Random();\n        try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {\n            writer.write(\"#  Lines starting with '#' are ignored.\");\n            writer.newLine();\n            writer.write(\"#  Lines starting with '-' are previously used.\");\n            writer.newLine();\n            writer.write(\"#  MIN_CH = \" + minCh);\n            writer.newLine();\n            writer.write(\"#  MAX_CH = \" + maxCh);\n            writer.newLine();\n            for ( int line = 0 ; line < keys ; line++ ) {\n                StringBuilder sb = new StringBuilder();\n                for ( int ch = 0 ; ch < keyLength ; ch++ ) {\n                    sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));\n                }\n                writer.write(sb.toString());\n                writer.newLine();\n            }\n            writer.write(\"#  EOF\");\n            writer.newLine();\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n}\n", "Python": "\n\nimport argparse\nimport itertools\nimport pathlib\nimport re\nimport secrets\nimport sys\n\n\n\nMAGIC = \"\n\n\ndef make_keys(n, size):\n    \n    \n    \n    \n    return (secrets.token_hex(size) for _ in range(n))\n\n\ndef make_pad(name, pad_size, key_size):\n    \n    pad = [\n        MAGIC,\n        f\"\n        f\"\n        *make_keys(pad_size, key_size),\n    ]\n\n    return \"\\n\".join(pad)\n\n\ndef xor(message, key):\n    \n    return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))\n\n\ndef use_key(pad):\n    \n    match = re.search(r\"^[a-f0-9]+$\", pad, re.MULTILINE)\n    if not match:\n        error(\"pad is all used up\")\n\n    key = match.group()\n    pos = match.start()\n\n    return (f\"{pad[:pos]}-{pad[pos:]}\", key)\n\n\ndef log(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n\n\ndef error(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n    sys.exit(1)\n\n\ndef write_pad(path, pad_size, key_size):\n    \n    if path.exists():\n        error(f\"pad '{path}' already exists\")\n\n    with path.open(\"w\") as fd:\n        fd.write(make_pad(path.name, pad_size, key_size))\n\n    log(f\"New one-time pad written to {path}\")\n\n\ndef main(pad, message, outfile):\n    \n    if not pad.exists():\n        error(f\"no such pad '{pad}'\")\n\n    with pad.open(\"r\") as fd:\n        if fd.readline().strip() != MAGIC:\n            error(f\"file '{pad}' does not look like a one-time pad\")\n\n    \n    with pad.open(\"r+\") as fd:\n        updated, key = use_key(fd.read())\n\n        fd.seek(0)\n        fd.write(updated)\n\n    outfile.write(xor(message, bytes.fromhex(key)))\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description=\"One-time pad.\")\n\n    parser.add_argument(\n        \"pad\",\n        help=(\n            \"Path to one-time pad. If neither --encrypt or --decrypt \"\n            \"are given, will create a new pad.\"\n        ),\n    )\n\n    parser.add_argument(\n        \"--length\",\n        type=int,\n        default=10,\n        help=\"Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.\",\n    )\n\n    parser.add_argument(\n        \"--key-size\",\n        type=int,\n        default=64,\n        help=\"Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.\",\n    )\n\n    parser.add_argument(\n        \"-o\",\n        \"--outfile\",\n        type=argparse.FileType(\"wb\"),\n        default=sys.stdout.buffer,\n        help=(\n            \"Write encoded/decoded message to a file. Ignored if --encrypt or \"\n            \"--decrypt is not given. Defaults to stdout.\"\n        ),\n    )\n\n    group = parser.add_mutually_exclusive_group()\n\n    group.add_argument(\n        \"--encrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Encrypt FILE using the next available key from pad.\",\n    )\n    group.add_argument(\n        \"--decrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Decrypt FILE using the next available key from pad.\",\n    )\n\n    args = parser.parse_args()\n\n    if args.encrypt:\n        message = args.encrypt.read()\n    elif args.decrypt:\n        message = args.decrypt.read()\n    else:\n        message = None\n\n    \n    if isinstance(message, str):\n        message = message.encode()\n\n    pad = pathlib.Path(args.pad).with_suffix(\".1tp\")\n\n    if message:\n        main(pad, message, args.outfile)\n    else:\n        write_pad(pad, args.length, args.key_size)\n"}
{"id": 46690, "name": "One-time pad", "Java": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class OneTimePad {\n\n    public static void main(String[] args) {\n        String controlName = \"AtomicBlonde\";\n        generatePad(controlName, 5, 60, 65, 90);\n        String text = \"IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES\";\n        String encrypted = parse(true, controlName, text.replaceAll(\" \", \"\"));\n        String decrypted = parse(false, controlName, encrypted);\n        System.out.println(\"Input  text    = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n\n        controlName = \"AtomicBlondeCaseSensitive\";\n        generatePad(controlName, 5, 60, 32, 126);\n        text = \"It was the best of times, it was the worst of times.\";\n        encrypted = parse(true, controlName, text);\n        decrypted = parse(false, controlName, encrypted);\n        System.out.println();\n        System.out.println(\"Input text     = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n    }\n    \n    private static String parse(boolean encryptText, String controlName, String text) {\n        StringBuilder sb = new StringBuilder();\n        int minCh = 0;\n        int maxCh = 0;\n        Pattern minChPattern = Pattern.compile(\"^#  MIN_CH = ([\\\\d]+)$\");\n        Pattern maxChPattern = Pattern.compile(\"^#  MAX_CH = ([\\\\d]+)$\");\n        boolean validated = false;\n        try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {\n            String inLine = null;\n            while ( (inLine = in.readLine()) != null ) {\n                Matcher minMatcher = minChPattern.matcher(inLine);\n                if ( minMatcher.matches() ) {\n                    minCh = Integer.parseInt(minMatcher.group(1));\n                    continue;\n                }\n                Matcher maxMatcher = maxChPattern.matcher(inLine);\n                if ( maxMatcher.matches() ) {\n                    maxCh = Integer.parseInt(maxMatcher.group(1));\n                    continue;\n                }\n                if ( ! validated && minCh > 0 && maxCh > 0 ) {\n                    validateText(text, minCh, maxCh);\n                    validated = true;\n                }\n                \n                if ( inLine.startsWith(\"#\") || inLine.startsWith(\"-\") ) {\n                    continue;\n                }\n                \n                String key = inLine;\n                if ( encryptText ) {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));\n                    }\n                }\n                else {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        int decrypt = text.charAt(i) - key.charAt(i);\n                        if ( decrypt < 0 ) {\n                            decrypt += maxCh - minCh + 1;\n                        }\n                        decrypt += minCh;\n                        sb.append((char) decrypt);\n                    }\n                }\n                break;\n            }\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n        return sb.toString();\n    }\n\n    private static void validateText(String text, int minCh, int maxCh) {\n        \n        for ( char ch : text.toCharArray() ) {\n            if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {\n                throw new IllegalArgumentException(\"ERROR 103:  Invalid text.\");\n            }\n        }\n        \n    }\n    \n    private static String getFileName(String controlName) {\n        return controlName + \".1tp\";\n    }\n    \n    private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {\n        Random random = new Random();\n        try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {\n            writer.write(\"#  Lines starting with '#' are ignored.\");\n            writer.newLine();\n            writer.write(\"#  Lines starting with '-' are previously used.\");\n            writer.newLine();\n            writer.write(\"#  MIN_CH = \" + minCh);\n            writer.newLine();\n            writer.write(\"#  MAX_CH = \" + maxCh);\n            writer.newLine();\n            for ( int line = 0 ; line < keys ; line++ ) {\n                StringBuilder sb = new StringBuilder();\n                for ( int ch = 0 ; ch < keyLength ; ch++ ) {\n                    sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));\n                }\n                writer.write(sb.toString());\n                writer.newLine();\n            }\n            writer.write(\"#  EOF\");\n            writer.newLine();\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n}\n", "Python": "\n\nimport argparse\nimport itertools\nimport pathlib\nimport re\nimport secrets\nimport sys\n\n\n\nMAGIC = \"\n\n\ndef make_keys(n, size):\n    \n    \n    \n    \n    return (secrets.token_hex(size) for _ in range(n))\n\n\ndef make_pad(name, pad_size, key_size):\n    \n    pad = [\n        MAGIC,\n        f\"\n        f\"\n        *make_keys(pad_size, key_size),\n    ]\n\n    return \"\\n\".join(pad)\n\n\ndef xor(message, key):\n    \n    return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))\n\n\ndef use_key(pad):\n    \n    match = re.search(r\"^[a-f0-9]+$\", pad, re.MULTILINE)\n    if not match:\n        error(\"pad is all used up\")\n\n    key = match.group()\n    pos = match.start()\n\n    return (f\"{pad[:pos]}-{pad[pos:]}\", key)\n\n\ndef log(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n\n\ndef error(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n    sys.exit(1)\n\n\ndef write_pad(path, pad_size, key_size):\n    \n    if path.exists():\n        error(f\"pad '{path}' already exists\")\n\n    with path.open(\"w\") as fd:\n        fd.write(make_pad(path.name, pad_size, key_size))\n\n    log(f\"New one-time pad written to {path}\")\n\n\ndef main(pad, message, outfile):\n    \n    if not pad.exists():\n        error(f\"no such pad '{pad}'\")\n\n    with pad.open(\"r\") as fd:\n        if fd.readline().strip() != MAGIC:\n            error(f\"file '{pad}' does not look like a one-time pad\")\n\n    \n    with pad.open(\"r+\") as fd:\n        updated, key = use_key(fd.read())\n\n        fd.seek(0)\n        fd.write(updated)\n\n    outfile.write(xor(message, bytes.fromhex(key)))\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description=\"One-time pad.\")\n\n    parser.add_argument(\n        \"pad\",\n        help=(\n            \"Path to one-time pad. If neither --encrypt or --decrypt \"\n            \"are given, will create a new pad.\"\n        ),\n    )\n\n    parser.add_argument(\n        \"--length\",\n        type=int,\n        default=10,\n        help=\"Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.\",\n    )\n\n    parser.add_argument(\n        \"--key-size\",\n        type=int,\n        default=64,\n        help=\"Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.\",\n    )\n\n    parser.add_argument(\n        \"-o\",\n        \"--outfile\",\n        type=argparse.FileType(\"wb\"),\n        default=sys.stdout.buffer,\n        help=(\n            \"Write encoded/decoded message to a file. Ignored if --encrypt or \"\n            \"--decrypt is not given. Defaults to stdout.\"\n        ),\n    )\n\n    group = parser.add_mutually_exclusive_group()\n\n    group.add_argument(\n        \"--encrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Encrypt FILE using the next available key from pad.\",\n    )\n    group.add_argument(\n        \"--decrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Decrypt FILE using the next available key from pad.\",\n    )\n\n    args = parser.parse_args()\n\n    if args.encrypt:\n        message = args.encrypt.read()\n    elif args.decrypt:\n        message = args.decrypt.read()\n    else:\n        message = None\n\n    \n    if isinstance(message, str):\n        message = message.encode()\n\n    pad = pathlib.Path(args.pad).with_suffix(\".1tp\")\n\n    if message:\n        main(pad, message, args.outfile)\n    else:\n        write_pad(pad, args.length, args.key_size)\n"}
{"id": 46691, "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": 46692, "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", "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": 46693, "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", "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": 46694, "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", "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": 46695, "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", "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": 46696, "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", "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": 46697, "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", "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": 46698, "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", "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": 46699, "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", "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": 46700, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 46701, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 46702, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46703, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46704, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46705, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 46706, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 46707, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 46708, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 46709, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 46710, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 46711, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 46712, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 46713, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 46714, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 46715, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 46716, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\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": 46717, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\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": 46718, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($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": 46719, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($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": 46720, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download 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": 46721, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download 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": 46722, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 46723, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 46724, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 46725, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 46726, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 46727, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 46728, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 46729, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 46730, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 46731, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 46732, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\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": 46733, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\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": 46734, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 46735, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 46736, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 46737, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 46738, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 46739, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 46740, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 46741, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 46742, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 46743, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 46744, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 46745, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 46746, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 46747, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 46748, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 46749, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 46750, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 46751, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 46752, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 46753, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 46754, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 46755, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 46756, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 46757, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 46758, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 46759, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 46760, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 46761, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 46762, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 46763, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 46764, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 46765, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 46766, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 46767, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 46768, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 46769, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 46770, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 46771, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 46772, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 46773, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 46774, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 46775, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 46776, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 46777, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 46778, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 46779, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 46780, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 46781, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 46782, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 46783, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 46784, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 46785, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 46786, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 46787, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 46788, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 46789, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 46790, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 46791, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 46792, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 46793, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 46794, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 46795, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 46796, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 46797, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 46798, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 46799, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 46800, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 46801, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 46802, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 46803, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 46804, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 46805, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 46806, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 46807, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 46808, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 46809, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 46810, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 46811, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 46812, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 46813, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 46814, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 46815, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 46816, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 46817, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 46818, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 46819, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 46820, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 46821, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 46822, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 46823, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 46824, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 46825, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 46826, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n"}
{"id": 46827, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n"}
{"id": 46828, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n"}
{"id": 46829, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n"}
{"id": 46830, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 46831, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 46832, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 46833, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 46834, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 46835, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 46836, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 46837, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 46838, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 46839, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 46840, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 46841, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 46842, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 46843, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 46844, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 46845, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 46846, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n"}
{"id": 46847, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n"}
{"id": 46848, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 46849, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 46850, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 46851, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 46852, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 46853, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 46854, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 46855, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 46856, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 46857, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 46858, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 46859, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 46860, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 46861, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 46862, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n"}
{"id": 46863, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n"}
{"id": 46864, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 46865, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 46866, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 46867, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 46868, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 46869, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 46870, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 46871, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 46872, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 46873, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 46874, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 46875, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 46876, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 46877, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 46878, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 46879, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 46880, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 46881, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 46882, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 46883, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 46884, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n"}
{"id": 46885, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n"}
{"id": 46886, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 46887, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 46888, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 46889, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 46890, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 46891, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 46892, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 46893, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 46894, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 46895, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 46896, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 46897, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 46898, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 46899, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 46900, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n"}
{"id": 46901, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n"}
{"id": 46902, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n"}
{"id": 46903, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n"}
{"id": 46904, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n"}
{"id": 46905, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n"}
{"id": 46906, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 46907, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 46908, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 46909, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 46910, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n"}
{"id": 46911, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n"}
{"id": 46912, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n"}
{"id": 46913, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n"}
{"id": 46914, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n"}
{"id": 46915, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n"}
{"id": 46916, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Java": "int a;\ndouble b;\nAClassNameHere c;\n"}
{"id": 46917, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Java": "int a;\ndouble b;\nAClassNameHere c;\n"}
{"id": 46918, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 46919, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 46920, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 46921, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 46922, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 46923, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 46924, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 46925, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 46926, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 46927, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 46928, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 46929, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 46930, "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", "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": 46931, "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", "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": 46932, "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", "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": 46933, "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", "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": 46934, "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", "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": 46935, "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", "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": 46936, "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", "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": 46937, "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", "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": 46938, "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", "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": 46939, "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", "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": 46940, "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", "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": 46941, "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", "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": 46942, "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", "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": 46943, "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", "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": 46944, "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", "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": 46945, "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", "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": 46946, "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", "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": 46947, "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", "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": 46948, "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", "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": 46949, "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", "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": 46950, "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", "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": 46951, "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", "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": 46952, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 46953, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 46954, "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", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 46955, "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", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\n"}
{"id": 46956, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 46957, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 46958, "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", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\n"}
{"id": 46959, "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", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n"}
{"id": 46960, "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", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n"}
{"id": 46961, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 46962, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 46963, "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", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n"}
{"id": 46964, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 46965, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 46966, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 46967, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 46968, "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", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n"}
{"id": 46969, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 46970, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 46971, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 46972, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 46973, "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", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 46974, "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", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 46975, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 46976, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 46977, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 46978, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 46979, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 46980, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 46981, "name": "Text processing_1", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n"}
{"id": 46982, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 46983, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 46984, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 46985, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 46986, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 46987, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 46988, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 46989, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 46990, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 46991, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 46992, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 46993, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 46994, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 46995, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 46996, "name": "Fractran", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n"}
{"id": 46997, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n"}
{"id": 46998, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 46999, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 47000, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 47001, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 47002, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 47003, "name": "Case-sensitivity of identifiers", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n"}
{"id": 47004, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n"}
{"id": 47005, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 47006, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 47007, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 47008, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 47009, "name": "Non-continuous subsequences", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 47010, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 47011, "name": "Roots of unity", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 47012, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 47013, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 47014, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 47015, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 47016, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 47017, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 47018, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 47019, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 47020, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 47021, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 47022, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 47023, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 47024, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 47025, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 47026, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 47027, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 47028, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 47029, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 47030, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 47031, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 47032, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 47033, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 47034, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 47035, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 47036, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 47037, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 47038, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 47039, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 47040, "name": "Water collected between towers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 47041, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 47042, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 47043, "name": "Jaro similarity", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n"}
{"id": 47044, "name": "Jaro similarity", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n"}
{"id": 47045, "name": "Fairshare between two and more", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 47046, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 47047, "name": "Prime triangle", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n"}
{"id": 47048, "name": "Prime triangle", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n"}
{"id": 47049, "name": "Trabb Pardo–Knuth algorithm", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n"}
{"id": 47050, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 47051, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 47052, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 47053, "name": "Biorhythms", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n"}
{"id": 47054, "name": "Biorhythms", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n"}
{"id": 47055, "name": "Table creation_Postal addresses", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n"}
{"id": 47056, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n"}
{"id": 47057, "name": "Soundex", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n"}
{"id": 47058, "name": "Chat server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 47059, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 47060, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 47061, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 47062, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 47063, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 47064, "name": "Terminal control_Dimensions", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n"}
{"id": 47065, "name": "Finite state machine", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n"}
{"id": 47066, "name": "Finite state machine", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n"}
{"id": 47067, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 47068, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 47069, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 47070, "name": "Sierpinski pentagon", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n"}
{"id": 47071, "name": "Rep-string", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n"}
{"id": 47072, "name": "Rep-string", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n"}
{"id": 47073, "name": "GUI_Maximum window dimensions", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n"}
{"id": 47074, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 47075, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 47076, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 47077, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 47078, "name": "Parse an IP Address", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n"}
{"id": 47079, "name": "Knapsack problem_Unbounded", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n"}
{"id": 47080, "name": "Textonyms", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n"}
{"id": 47081, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n"}
{"id": 47082, "name": "Type detection", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n"}
{"id": 47083, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n"}
{"id": 47084, "name": "Zhang-Suen thinning algorithm", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n"}
{"id": 47085, "name": "Variable declaration reset", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n"}
{"id": 47086, "name": "Start from a main routine", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n", "VB": "SUB Main()\n  \nEND\n"}
{"id": 47087, "name": "Start from a main routine", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n", "VB": "SUB Main()\n  \nEND\n"}
{"id": 47088, "name": "Koch curve", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n"}
{"id": 47089, "name": "Draw a pixel", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n"}
{"id": 47090, "name": "Words from neighbour ones", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n"}
{"id": 47091, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 47092, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 47093, "name": "UTF-8 encode and decode", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n"}
{"id": 47094, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n"}
{"id": 47095, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 47096, "name": "Execute a system command", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n"}
{"id": 47097, "name": "XML validation", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n"}
{"id": 47098, "name": "Death Star", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n"}
{"id": 47099, "name": "Verify distribution uniformity_Chi-squared test", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 47100, "name": "Brace expansion", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 47101, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 47102, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 47103, "name": "GUI component interaction", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 47104, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n"}
{"id": 47105, "name": "Spelling of ordinal numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n"}
{"id": 47106, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 47107, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 47108, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n"}
{"id": 47109, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 47110, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 47111, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 47112, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n"}
{"id": 47113, "name": "Own digits power sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define MAX_DIGITS 9\n\nint digits[MAX_DIGITS];\n\nvoid getDigits(int i) {\n    int ix = 0;\n    while (i > 0) {\n        digits[ix++] = i % 10;\n        i /= 10;\n    }\n}\n\nint main() {\n    int n, d, i, max, lastDigit, sum, dp;\n    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};\n    printf(\"Own digits power sums for N = 3 to 9 inclusive:\\n\");\n    for (n = 3; n < 10; ++n) {\n        for (d = 2; d < 10; ++d) powers[d] *= d;\n        i = (int)pow(10, n-1);\n        max = i * 10;\n        lastDigit = 0;\n        while (i < max) {\n            if (!lastDigit) {\n                getDigits(i);\n                sum = 0;\n                for (d = 0; d < n; ++d) {\n                    dp = digits[d];\n                    sum += powers[dp];\n                }\n            } else if (lastDigit == 1) {\n                sum++;\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1];\n            }\n            if (sum == i) {\n                printf(\"%d\\n\", i);\n                if (lastDigit == 0) printf(\"%d\\n\", i + 1);\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (sum > i) {\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (lastDigit < 9) {\n                i++;\n                lastDigit++;\n            } else {\n                i++;\n                lastDigit = 0;\n            }\n        }\n    }\n    return 0;\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\n\n\n\nModule OwnDigitsPowerSum\n\n    Public Sub Main\n\n        \n        Dim used(9) As Integer\n        Dim check(9) As Integer\n        Dim power(9, 9) As Long\n        For i As Integer = 0 To 9\n            check(i) = 0\n        Next i\n        For i As Integer = 1 To 9\n            power(1,  i) = i\n        Next i\n        For j As Integer =  2 To 9\n            For i As Integer = 1 To 9\n                power(j, i) = power(j - 1, i) * i\n            Next i\n        Next j\n        \n        \n        Dim lowestDigit(9) As Integer\n        lowestDigit(1) = -1\n        lowestDigit(2) = -1\n        Dim p10 As Long = 100\n        For i As Integer = 3 To 9\n            For p As Integer = 2 To 9\n                Dim np As Long = power(i, p) * i\n                If Not ( np < p10) Then Exit For\n                lowestDigit(i) = p\n            Next p\n            p10 *= 10\n        Next i\n        \n        Dim maxZeros(9, 9) As Integer\n        For i As Integer = 1 To 9\n            For j As Integer = 1 To 9\n                maxZeros(i, j) = 0\n            Next j\n        Next i\n        p10 = 1000\n        For w As Integer = 3 To 9\n            For d As Integer = lowestDigit(w) To 9\n                Dim nz As Integer = 9\n                Do\n                    If nz < 0 Then\n                        Exit Do\n                    Else\n                        Dim np As Long = power(w, d) * nz\n                        IF Not ( np > p10) Then Exit Do\n                    End If\n                    nz -= 1\n                Loop\n                maxZeros(w, d) = If(nz > w, 0, w - nz)\n            Next d\n            p10 *= 10\n        Next w\n        \n        \n        Dim numbers(100) As Long     \n        Dim nCount As Integer = 0    \n        Dim tryCount As Integer = 0  \n        Dim digits(9) As Integer     \n        For d As Integer = 1 To 9\n             digits(d) = 9\n        Next d\n        For d As Integer = 0 To 8\n            used(d) = 0\n        Next d\n        used(9) = 9\n        Dim width As Integer = 9     \n        Dim last As Integer = width  \n        p10 = 100000000              \n        Do While width > 2\n            tryCount += 1\n            Dim dps As Long = 0      \n            check(0) = used(0)\n            For i As Integer = 1 To 9\n                check(i) = used(i)\n                If used(i) <> 0 Then\n                    dps += used(i) * power(width, i)\n                End If\n            Next i\n            \n            Dim n As Long = dps\n            Do\n                check(CInt(n Mod 10)) -= 1 \n                n \\= 10\n            Loop Until n <= 0\n            Dim reduceWidth As Boolean = dps <= p10\n            If Not reduceWidth Then\n                \n                \n                \n                Dim zCount As Integer = 0\n                For i As Integer = 0 To 9\n                    If check(i) <> 0 Then Exit For\n                    zCount+= 1\n                Next i\n                If zCount = 10 Then\n                    nCount += 1\n                    numbers(nCount) = dps\n                End If\n                \n                used(digits(last)) -= 1\n                digits(last) -= 1\n                If digits(last) = 0 Then\n                    \n                    If used(0) >= maxZeros(width, digits(1)) Then\n                        \n                        digits(last) = -1\n                    End If\n                End If\n                If digits(last) >= 0 Then\n                    \n                    used(digits(last)) += 1\n                Else\n                    \n                    Dim prev As Integer = last\n                    Do\n                        prev -= 1\n                        If prev < 1 Then\n                            Exit Do\n                        Else\n                            used(digits(prev)) -= 1\n                            digits(prev) -= 1\n                            IF digits(prev) >= 0 Then Exit Do\n                        End If\n                    Loop\n                    If prev > 0 Then\n                        \n                        If prev = 1 Then\n                            If digits(1) <= lowestDigit(width) Then\n                               \n                               prev = 0\n                            End If\n                        End If\n                        If prev <> 0 Then\n                           \n                            used(digits(prev)) += 1\n                            For i As Integer = prev + 1 To width\n                                digits(i) = digits(prev)\n                                used(digits(prev)) += 1\n                            Next i\n                        End If\n                    End If\n                    If prev <= 0 Then\n                        \n                        reduceWidth = True\n                    End If\n                End If\n            End If\n            If reduceWidth Then\n                \n                last -= 1\n                width = last\n                If last > 0 Then\n                    \n                    For d As Integer = 1 To last\n                        digits(d) = 9\n                    Next d\n                    For d As Integer = last + 1 To 9\n                        digits(d) = -1\n                    Next d\n                    For d As Integer = 0 To 8\n                        used(d) = 0\n                    Next d\n                    used(9) = last\n                    p10 \\= 10\n                End If\n            End If\n        Loop\n        \n        Console.Out.WriteLine(\"Own digits power sums for N = 3 to 9 inclusive:\")\n        For i As Integer = nCount To 1 Step -1\n            Console.Out.WriteLine(numbers(i))\n        Next i\n        Console.Out.WriteLine(\"Considered \" & tryCount & \" digit combinations\")\n\n    End Sub\n\n\nEnd Module\n"}
{"id": 47114, "name": "Klarner-Rado sequence", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n"}
{"id": 47115, "name": "Klarner-Rado sequence", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n"}
{"id": 47116, "name": "Sorting algorithms_Pancake sort", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n"}
{"id": 47117, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n"}
{"id": 47118, "name": "Long stairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n    int trial, secs_tot=0, steps_tot=0;     \n    int sbeh, slen, wiz, secs;              \n    time_t t;\n    srand((unsigned) time(&t));             \n    printf( \"Seconds    steps behind    steps ahead\\n\" );\n    for( trial=1;trial<=10000;trial++ ) {   \n        sbeh = 0; slen = 100; secs = 0;     \n        while(sbeh<slen) {                  \n            sbeh+=1;                        \n            for(wiz=1;wiz<=5;wiz++) {       \n                if(rand()%slen < sbeh)\n                    sbeh+=1;                \n                slen+=1;                    \n            }\n            secs+=1;                        \n            if(trial==1&&599<secs&&secs<610)\n                printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh );\n            \n        }\n        secs_tot+=secs;\n        steps_tot+=slen;\n    }\n    printf( \"Average secs taken: %f\\n\", secs_tot/10000.0 );\n    printf( \"Average final length of staircase: %f\\n\", steps_tot/10000.0 ); \n    return 0;\n}\n", "VB": "Option Explicit\nRandomize Timer\n\nFunction pad(s,n) \n  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If \nEnd Function\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\nFunction Rounds(maxsecs,wiz,a)\n  Dim mystep,maxstep,toend,j,i,x,d \n  If IsArray(a) Then d=True: print \"seconds behind pending\"   \n  maxstep=100\n  For j=1 To maxsecs\n    For i=1 To wiz\n      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1\n      maxstep=maxstep+1  \n    Next \n    mystep=mystep+1 \n    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function\n    If d Then\n      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)\n    End If     \n  Next \n  Rounds=Array(maxsecs,maxstep)\nEnd Function\n\n\nDim n,r,a,sumt,sums,ntests,t,maxsecs\nntests=10000\nmaxsecs=7000\nt=timer\na=Array(600,609)\nFor n=1 To ntests\n  r=Rounds(maxsecs,5,a)\n  If r(0)<>maxsecs Then \n    sumt=sumt+r(0)\n    sums=sums+r(1)\n  End if  \n  a=\"\"\nNext  \n\nprint vbcrlf & \"Done \" & ntests & \" tests in \" & Timer-t & \" seconds\" \nprint \"escaped in \" & sumt/ntests  & \" seconds with \" & sums/ntests & \" stairs\"\n"}
{"id": 47119, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 47120, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 47121, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 47122, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 47123, "name": "Rosetta Code_Find unimplemented tasks", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n"}
{"id": 47124, "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": 47125, "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", "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": 47126, "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", "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": 47127, "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", "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": 47128, "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", "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": 47129, "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", "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": 47130, "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", "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": 47131, "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", "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": 47132, "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", "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": 47133, "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", "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": 47134, "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", "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": 47135, "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", "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": 47136, "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", "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": 47137, "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", "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": 47138, "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", "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": 47139, "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", "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": 47140, "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", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n"}
{"id": 47141, "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", "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": 47142, "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", "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": 47143, "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", "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": 47144, "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", "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": 47145, "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", "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": 47146, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\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": 47147, "name": "Peano curve", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\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": 47148, "name": "Seven-sided dice from five-sided dice", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\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": 47149, "name": "Solve the no connection puzzle", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 1);\n    return 0;\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": 47150, "name": "Magnanimous numbers", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\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": 47151, "name": "Extensible prime generator", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\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": 47152, "name": "Rock-paper-scissors", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\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": 47153, "name": "Create a two-dimensional array at runtime", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\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": 47154, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\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": 47155, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\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": 47156, "name": "Vigenère cipher_Cryptanalysis", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\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": 47157, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \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": 47158, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \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": 47159, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\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": 47160, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\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": 47161, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\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": 47162, "name": "Return multiple values", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\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": 47163, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 47164, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 47165, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 47166, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 47167, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\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": 47168, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\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": 47169, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\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": 47170, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\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": 47171, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\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": 47172, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 47173, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 47174, "name": "LU decomposition", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\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": 47175, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\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": 47176, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 47177, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 47178, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 47179, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 47180, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 47181, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 47182, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 47183, "name": "Checkpoint synchronization", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 47184, "name": "Checkpoint synchronization", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 47185, "name": "Variable-length quantity", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 47186, "name": "SHA-256 Merkle tree", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\n';\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << \"\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\n"}
{"id": 47187, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 47188, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 47189, "name": "User input_Graphical", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n"}
{"id": 47190, "name": "User input_Graphical", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n"}
{"id": 47191, "name": "Sierpinski arrowhead curve", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\n", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\n"}
{"id": 47192, "name": "Text processing_1", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n"}
{"id": 47193, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 47194, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 47195, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 47196, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 47197, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 47198, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 47199, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 47200, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 47201, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 47202, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 47203, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 47204, "name": "Stack", "C++": "#include <stack>\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 47205, "name": "Stack", "C++": "#include <stack>\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 47206, "name": "Totient function", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 47207, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 47208, "name": "Fractran", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n"}
{"id": 47209, "name": "Sorting algorithms_Stooge sort", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 47210, "name": "Galton box animation", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n"}
{"id": 47211, "name": "Galton box animation", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n"}
{"id": 47212, "name": "Sorting Algorithms_Circle Sort", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\n", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\n"}
{"id": 47213, "name": "Kronecker product based fractals", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\n", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\n"}
{"id": 47214, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 47215, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 47216, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 47217, "name": "Circular primes", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n"}
{"id": 47218, "name": "Animation", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 47219, "name": "Sorting algorithms_Radix sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n"}
{"id": 47220, "name": "List comprehensions", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n"}
{"id": 47221, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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 sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 47222, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 47223, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 47224, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 47225, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 47226, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 47227, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 47228, "name": "Safe addition", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n"}
{"id": 47229, "name": "Case-sensitivity of identifiers", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 47230, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 47231, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 47232, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 47233, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 47234, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 47235, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 47236, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 47237, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n"}
{"id": 47238, "name": "Fibonacci word_fractal", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 47239, "name": "Twin primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 47240, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 47241, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 47242, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 47243, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 47244, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 47245, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 47246, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 47247, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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 <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 47248, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 47249, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 47250, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 47251, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 47252, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 47253, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 47254, "name": "Man or boy test", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 47255, "name": "Short-circuit evaluation", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 47256, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 47257, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 47258, "name": "Carmichael 3 strong pseudoprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 47259, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 47260, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 47261, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 47262, "name": "Sorting algorithms_Bead sort", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 47263, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 47264, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 47265, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 47266, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 47267, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 47268, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 47269, "name": "Inverted index", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 47270, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 47271, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 47272, "name": "Fermat numbers", "C++": "#include <iostream>\n#include <vector>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntypedef boost::multiprecision::cpp_int integer;\n\ninteger fermat(unsigned int n) {\n    unsigned int p = 1;\n    for (unsigned int i = 0; i < n; ++i)\n        p *= 2;\n    return 1 + pow(integer(2), p);\n}\n\ninline void g(integer& x, const integer& n) {\n    x *= x;\n    x += 1;\n    x %= n;\n}\n\ninteger pollard_rho(const integer& n) {\n    integer x = 2, y = 2, d = 1, z = 1;\n    int count = 0;\n    for (;;) {\n        g(x, n);\n        g(y, n);\n        g(y, n);\n        d = abs(x - y);\n        z = (z * d) % n;\n        ++count;\n        if (count == 100) {\n            d = gcd(z, n);\n            if (d != 1)\n                break;\n            z = 1;\n            count = 0;\n        }\n    }\n    if (d == n)\n        return 0;\n    return d;\n}\n\nstd::vector<integer> get_prime_factors(integer n) {\n    std::vector<integer> factors;\n    for (;;) {\n        if (miller_rabin_test(n, 25)) {\n            factors.push_back(n);\n            break;\n        }\n        integer f = pollard_rho(n);\n        if (f == 0) {\n            factors.push_back(n);\n            break;\n        }\n        factors.push_back(f);\n        n /= f;\n    }\n    return factors;\n}\n\nvoid print_vector(const std::vector<integer>& factors) {\n    if (factors.empty())\n        return;\n    auto i = factors.begin();\n    std::cout << *i++;\n    for (; i != factors.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout << \"First 10 Fermat numbers:\\n\";\n    for (unsigned int i = 0; i < 10; ++i)\n        std::cout << \"F(\" << i << \") = \" << fermat(i) << '\\n';\n    std::cout << \"\\nPrime factors:\\n\";\n    for (unsigned int i = 0; i < 9; ++i) {\n        std::cout << \"F(\" << i << \"): \";\n        print_vector(get_prime_factors(fermat(i)));\n    }\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class FermatNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 Fermat numbers:\");\n        for ( int i = 0 ; i < 10 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, fermat(i));\n        }\n        System.out.printf(\"%nFirst 12 Fermat numbers factored:%n\");\n        for ( int i = 0 ; i < 13 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, getString(getFactors(i, fermat(i))));\n        }\n    }\n    \n    private static String getString(List<BigInteger> factors) {\n        if ( factors.size() == 1 ) {\n            return factors.get(0) + \" (PRIME)\";\n        }\n        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith(\"-\") ? \"(C\" + v.replace(\"-\", \"\") + \")\" : v).collect(Collectors.joining(\" * \"));\n    }\n\n    private static Map<Integer, String> COMPOSITE = new HashMap<>();\n    static {\n        COMPOSITE.put(9, \"5529\");\n        COMPOSITE.put(10, \"6078\");\n        COMPOSITE.put(11, \"1037\");\n        COMPOSITE.put(12, \"5488\");\n        COMPOSITE.put(13, \"2884\");\n    }\n\n    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {\n        List<BigInteger> factors = new ArrayList<>();\n        BigInteger factor = BigInteger.ONE;\n        while ( true ) {\n            if ( n.isProbablePrime(100) ) {\n                factors.add(n);\n                break;\n            }\n            else {\n                if ( COMPOSITE.containsKey(fermatIndex) ) {\n                    String stop = COMPOSITE.get(fermatIndex);\n                    if ( n.toString().startsWith(stop) ) {\n                        factors.add(new BigInteger(\"-\" + n.toString().length()));\n                        break;\n                    }\n                }\n                factor = pollardRhoFast(n);\n                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {\n                    factors.add(n);\n                    break;\n                }\n                else {\n                    factors.add(factor);\n                    n = n.divide(factor);\n                }\n            }\n        }\n        return factors;\n    }\n    \n    private static final BigInteger TWO = BigInteger.valueOf(2);\n    \n    private static BigInteger fermat(int n) {\n        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);\n    }\n        \n    \n    @SuppressWarnings(\"unused\")\n    private static BigInteger pollardRho(BigInteger n) {\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        while ( d.compareTo(BigInteger.ONE) == 0 ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs().gcd(n);\n        }\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n    \n    \n    \n    \n    \n    \n    private static BigInteger pollardRhoFast(BigInteger n) {\n        long start = System.currentTimeMillis();\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        int count = 0;\n        BigInteger z = BigInteger.ONE;\n        while ( true ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs();\n            z = z.multiply(d).mod(n);\n            count++;\n            if ( count == 100 ) {\n                d = z.gcd(n);\n                if ( d.compareTo(BigInteger.ONE) != 0 ) {\n                    break;\n                }\n                z = BigInteger.ONE;\n                count = 0;\n            }\n        }\n        long end = System.currentTimeMillis();\n        System.out.printf(\"    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n\", n, (end-start), d);\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n\n    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {\n        return x.multiply(x).add(BigInteger.ONE).mod(n);\n    }\n\n}\n"}
{"id": 47273, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 47274, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 47275, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 47276, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 47277, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n"}
{"id": 47278, "name": "Square-free integers", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 47279, "name": "Square-free integers", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 47280, "name": "Jaro similarity", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n"}
{"id": 47281, "name": "Sum and product puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n"}
{"id": 47282, "name": "Fairshare between two and more", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 47283, "name": "Parsing_Shunting-yard algorithm", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 47284, "name": "Prime triangle", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n"}
{"id": 47285, "name": "Trabb Pardo–Knuth algorithm", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 47286, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 47287, "name": "Sequence_ nth number with exactly n divisors", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\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 SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n"}
{"id": 47288, "name": "Sequence_ smallest number with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n"}
{"id": 47289, "name": "Sequence_ smallest number with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n"}
{"id": 47290, "name": "Pancake numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47291, "name": "Pancake numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47292, "name": "Generate random chess position", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n"}
{"id": 47293, "name": "Esthetic numbers", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n"}
{"id": 47294, "name": "Topswops", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n"}
{"id": 47295, "name": "Old Russian measure of length", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n"}
{"id": 47296, "name": "Rate counter", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n"}
{"id": 47297, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 47298, "name": "Pythagoras tree", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 47299, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 47300, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 47301, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n"}
{"id": 47302, "name": "Numeric error propagation", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n"}
{"id": 47303, "name": "Numeric error propagation", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n"}
{"id": 47304, "name": "List rooted trees", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n"}
{"id": 47305, "name": "Longest common suffix", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n"}
{"id": 47306, "name": "Sum of elements below main diagonal of matrix", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n"}
{"id": 47307, "name": "FASTA format", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 47308, "name": "Pseudo-random numbers_PCG32", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 47309, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n"}
{"id": 47310, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n"}
{"id": 47311, "name": "Rep-string", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n"}
{"id": 47312, "name": "Rep-string", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n"}
{"id": 47313, "name": "Literals_String", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 47314, "name": "Changeable words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n"}
{"id": 47315, "name": "Four is magic", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 47316, "name": "Getting the number of decimals", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n"}
{"id": 47317, "name": "Enumerations", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 47318, "name": "Parse an IP Address", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n"}
{"id": 47319, "name": "Textonyms", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n"}
{"id": 47320, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 47321, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 47322, "name": "Teacup rim text", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n"}
{"id": 47323, "name": "Increasing gaps between consecutive Niven numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n"}
{"id": 47324, "name": "Print debugging statement", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n"}
{"id": 47325, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 47326, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 47327, "name": "Type detection", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n"}
{"id": 47328, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n"}
{"id": 47329, "name": "Zhang-Suen thinning algorithm", "C++": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <valarray>\nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n    friend class ZhangSuen;\n    using pixel_t = char;\n    static const pixel_t BLACK_PIX;\n    static const pixel_t WHITE_PIX;\n\n    Image(unsigned width = 1, unsigned height = 1) \n    : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n    {}\n    Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n    {}\n    Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n    {}\n    ~Image() = default;\n    Image& operator=(const Image& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = i.data_;\n        }\n        return *this;\n    }\n    Image& operator=(Image&& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = std::move(i.data_);\n        }\n        return *this;\n    }\n    size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n    bool operator()(unsigned x, unsigned y) {\n        return data_[idx(x, y)];\n    }\n    friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n        o << i.width_ << \" x \" << i.height_ << std::endl;\n        size_t px = 0;\n        for(const auto& e : i.data_) {\n            o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n            if (++px % i.width_ == 0)\n                o << std::endl;\n        }\n        return o << std::endl;\n    }\n    friend std::istream& operator>>(std::istream& in, Image& img) {\n        auto it = std::begin(img.data_);\n        const auto end = std::end(img.data_);\n        Image::pixel_t tmp;\n        while(in && it != end) {\n            in >> tmp;\n            if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n                throw \"Bad character found in image\";\n            *it = (tmp == Image::BLACK_PIX)?1:0;\n            ++it;\n        }\n        return in;\n    }\n    unsigned width() const noexcept { return width_; }\n    unsigned height() const noexcept { return height_; }\n    struct Neighbours {\n        \n        \n        \n        Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n        : img_{img}\n        , p1_{img.idx(p1_x, p1_y)}\n        , p2_{p1_ - img.width()}\n        , p3_{p2_ + 1}\n        , p4_{p1_ + 1}\n        , p5_{p4_ + img.width()}\n        , p6_{p5_ - 1}\n        , p7_{p6_ - 1}\n        , p8_{p1_ - 1}\n        , p9_{p2_ - 1} \n        {}\n        const Image& img_;\n        const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n        const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n        const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n        const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n        const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n        const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n        const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n        const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n        const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n        const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n    };\n    Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n    unsigned height_ { 0 };\n    unsigned width_ { 0 };\n    std::valarray<pixel_t> data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n    \n    unsigned transitions_white_black(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += (a.p9() == 0) && a.p2();\n        sum += (a.p2() == 0) && a.p3();\n        sum += (a.p3() == 0) && a.p4();\n        sum += (a.p8() == 0) && a.p9();\n        sum += (a.p4() == 0) && a.p5();\n        sum += (a.p7() == 0) && a.p8();\n        sum += (a.p6() == 0) && a.p7();\n        sum += (a.p5() == 0) && a.p6();\n        return sum;\n    }\n\n    \n    unsigned black_pixels(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += a.p9();\n        sum += a.p2();\n        sum += a.p3();\n        sum += a.p8();\n        sum += a.p4();\n        sum += a.p7();\n        sum += a.p6();\n        sum += a.p5();\n        return sum;\n    }\n    const Image& operator()(const Image& img) {\n        tmp_a_ = img;\n        size_t changed_pixels = 0;\n        do {\n            changed_pixels = 0;\n            \n            tmp_b_ = tmp_a_;\n            for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n                    if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n                        auto n = tmp_a_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p6() == 0)\n                                && (n.p4() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_b_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n            \n            tmp_a_ = tmp_b_;\n            for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n                    if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n                        auto n = tmp_b_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p8() == 0)\n                                && (n.p2() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_a_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n        } while(changed_pixels > 0);\n        return tmp_a_;\n    }\nprivate:\n    Image tmp_a_;\n    Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n    using namespace std;\n    Image img(32, 10);\n    istringstream iss{input};\n    iss >> img;\n    cout << img;\n    cout << \"ZhangSuen\" << endl;\n    ZhangSuen zs;\n    Image res = std::move(zs(img));\n    cout << res << endl;\n\n    Image img2(58,18);\n    istringstream iss2{input2};\n    iss2 >> img2;\n    cout << img2;\n    cout << \"ZhangSuen with big image\" << endl;\n    Image res2 = std::move(zs(img2));\n    cout << res2 << endl;\n    return 0;\n}\n", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n"}
{"id": 47330, "name": "Variable declaration reset", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n"}
{"id": 47331, "name": "Numbers with equal rises and falls", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n"}
{"id": 47332, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n"}
{"id": 47333, "name": "Words from neighbour ones", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n"}
{"id": 47334, "name": "Magic squares of singly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n"}
{"id": 47335, "name": "Generate Chess960 starting position", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n"}
{"id": 47336, "name": "Modulinos", "C++": "int meaning_of_life();\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 47337, "name": "Modulinos", "C++": "int meaning_of_life();\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 47338, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 47339, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 47340, "name": "Pseudo-random numbers_Xorshift star", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 47341, "name": "Four is the number of letters in the ...", "C++": "#include <cctype>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        result.push_back(get_name(small[n], ordinal));\n        count = 1;\n    }\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result.push_back(get_name(tens[n/10 - 2], ordinal));\n        } else {\n            std::string name(get_name(tens[n/10 - 2], false));\n            name += \"-\";\n            name += get_name(small[n % 10], ordinal);\n            result.push_back(name);\n        }\n        count = 1;\n    } else {\n        const named_number& num = get_named_number(n);\n        uint64_t p = num.number;\n        count += append_number_name(result, n/p, false);\n        if (n % p == 0) {\n            result.push_back(get_name(num, ordinal));\n            ++count;\n        } else {\n            result.push_back(get_name(num, false));\n            ++count;\n            count += append_number_name(result, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(const std::string& str) {\n    size_t letters = 0;\n    for (size_t i = 0, n = str.size(); i < n; ++i) {\n        if (isalpha(static_cast<unsigned char>(str[i])))\n            ++letters;\n    }\n    return letters;\n}\n\nstd::vector<std::string> sentence(size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    std::vector<std::string> result;\n    result.reserve(count + 10);\n    size_t n = std::size(words);\n    for (size_t i = 0; i < n && i < count; ++i) {\n        result.push_back(words[i]);\n    }\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result[i]), false);\n        result.push_back(\"in\");\n        result.push_back(\"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        result.back() += ',';\n    }\n    return result;\n}\n\nsize_t sentence_length(const std::vector<std::string>& words) {\n    size_t n = words.size();\n    if (n == 0)\n        return 0;\n    size_t length = n - 1;\n    for (size_t i = 0; i < n; ++i)\n        length += words[i].size();\n    return length;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    size_t n = 201;\n    auto result = sentence(n);\n    std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            std::cout << (i % 25 == 0 ? '\\n' : ' ');\n        std::cout << std::setw(2) << count_letters(result[i]);\n    }\n    std::cout << '\\n';\n    std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    for (n = 1000; n <= 10000000; n *= 10) {\n        result = sentence(n);\n        const std::string& word = result[n - 1];\n        std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n            << count_letters(word) << \" letters. \";\n        std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    }\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class FourIsTheNumberOfLetters {\n\n    public static void main(String[] args) {\n        String [] words = neverEndingSentence(201);\n        System.out.printf(\"Display the first 201 numbers in the sequence:%n%3d: \", 1);\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            System.out.printf(\"%2d \", numberOfLetters(words[i]));\n            if ( (i+1) % 25 == 0 ) {\n                System.out.printf(\"%n%3d: \", i+2);\n            }\n        }\n        System.out.printf(\"%nTotal number of characters in the sentence is %d%n\", characterCount(words));\n        for ( int i = 3 ; i <= 7 ; i++ ) {\n            int index = (int) Math.pow(10, i);\n            words = neverEndingSentence(index);\n            String last = words[words.length-1].replace(\",\", \"\");\n            System.out.printf(\"Number of letters of the %s word is %d. The word is \\\"%s\\\".  The sentence length is %,d characters.%n\", toOrdinal(index), numberOfLetters(last), last, characterCount(words));\n        }\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static void displaySentence(String[] words, int lineLength) {\n        int currentLength = 0;\n        for ( String word : words ) {\n            if ( word.length() + currentLength > lineLength ) {\n                String first = word.substring(0, lineLength-currentLength);\n                String second = word.substring(lineLength-currentLength);\n                System.out.println(first);\n                System.out.print(second);\n                currentLength = second.length();\n            }\n            else {\n                System.out.print(word);\n                currentLength += word.length();\n            }\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n            System.out.print(\" \");\n            currentLength++;\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n        }\n        System.out.println();\n    }\n    \n    private static int numberOfLetters(String word) {\n        return word.replace(\",\",\"\").replace(\"-\",\"\").length();\n    }\n    \n    private static long characterCount(String[] words) {\n        int characterCount = 0;\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            characterCount += words[i].length() + 1;\n        }        \n        \n        characterCount--;\n        return characterCount;\n    }\n    \n    private static String[] startSentence = new String[] {\"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\", \"first\", \"word\", \"of\", \"this\", \"sentence,\"};\n    \n    private static String[] neverEndingSentence(int wordCount) {\n        String[] words = new String[wordCount];\n        int index;\n        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {\n            words[index] = startSentence[index];\n        }\n        int sentencePosition = 1;\n        while ( index < wordCount ) {\n            \n            \n            sentencePosition++;\n            String word = words[sentencePosition-1];\n            for ( String wordLoop : numToString(numberOfLetters(word)).split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n            \n            words[index] = \"in\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            words[index] = \"the\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            for ( String wordLoop : (toOrdinal(sentencePosition) + \",\").split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n        }\n        return words;\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n    \n}\n"}
{"id": 47342, "name": "ASCII art diagram converter", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n"}
{"id": 47343, "name": "Same fringe", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n"}
{"id": 47344, "name": "Peaceful chess queen armies", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 47345, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 47346, "name": "Test integerness", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n"}
{"id": 47347, "name": "Execute a system command", "C++": "system(\"pause\");\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 47348, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 47349, "name": "Lucky and even lucky numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nconst int luckySize = 60000;\nstd::vector<int> luckyEven(luckySize);\nstd::vector<int> luckyOdd(luckySize);\n\nvoid init() {\n    for (int i = 0; i < luckySize; ++i) {\n        luckyEven[i] = i * 2 + 2;\n        luckyOdd[i] = i * 2 + 1;\n    }\n}\n\nvoid filterLuckyEven() {\n    for (size_t n = 2; n < luckyEven.size(); ++n) {\n        int m = luckyEven[n - 1];\n        int end = (luckyEven.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n            luckyEven.pop_back();\n        }\n    }\n}\n\nvoid filterLuckyOdd() {\n    for (size_t n = 2; n < luckyOdd.size(); ++n) {\n        int m = luckyOdd[n - 1];\n        int end = (luckyOdd.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n            luckyOdd.pop_back();\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n\n    if (even) {\n        size_t max = luckyEven.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    } else {\n        size_t max = luckyOdd.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    }\n    std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n    if (even) {\n        if (k >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n    } else {\n        if (k >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n    }\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (j >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n    } else {\n        if (j >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n    }\n}\n\nvoid help() {\n    std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"       argument(s)        |  what is displayed\\n\";\n    std::cout << \"==============================================\\n\";\n    std::cout << \"-j=m                      |  mth lucky number\\n\";\n    std::cout << \"-j=m  --lucky             |  mth lucky number\\n\";\n    std::cout << \"-j=m  --evenLucky         |  mth even lucky number\\n\";\n    std::cout << \"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\";\n    std::cout << \"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    \n    if (argc < 2) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    bool good = false;\n    for (int i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n            exit(EXIT_FAILURE);\n        }\n    }\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    init();\n    filterLuckyEven();\n    filterLuckyOdd();\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n"}
{"id": 47350, "name": "Brace expansion", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 47351, "name": "Superpermutation minimisation", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47352, "name": "GUI component interaction", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n"}
{"id": 47353, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n"}
{"id": 47354, "name": "Summarize and say sequence", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n"}
{"id": 47355, "name": "Spelling of ordinal numbers", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 47356, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 47357, "name": "Addition chains", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 47358, "name": "Numeric separator syntax", "C++": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n", "Java": "public class NumericSeparatorSyntax {\n\n    public static void main(String[] args) {\n        runTask(\"Underscore allowed as seperator\", 1_000);\n        runTask(\"Multiple consecutive underscores allowed:\", 1__0_0_0);\n        runTask(\"Many multiple consecutive underscores allowed:\", 1________________________00);\n        runTask(\"Underscores allowed in multiple positions\", 1__4__4);\n        runTask(\"Underscores allowed in negative number\", -1__4__4);\n        runTask(\"Underscores allowed in floating point number\", 1__4__4e-5);\n        runTask(\"Underscores allowed in floating point exponent\", 1__4__440000e-1_2);\n        \n        \n        \n        \n    }\n    \n    private static void runTask(String description, long n) {\n        runTask(description, n, \"%d\");\n    }\n\n    private static void runTask(String description, double n) {\n        runTask(description, n, \"%3.7f\");\n    }\n\n    private static void runTask(String description, Number n, String format) {\n        System.out.printf(\"%s:  \" + format + \"%n\", description, n);\n    }\n\n}\n"}
{"id": 47359, "name": "Repeat", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n"}
{"id": 47360, "name": "Sparkline in unicode", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n"}
{"id": 47361, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 47362, "name": "Sunflower fractal", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n"}
{"id": 47363, "name": "Vogel's approximation method", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n"}
{"id": 47364, "name": "Permutations by swapping", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 47365, "name": "Pythagorean quadruples", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 47366, "name": "Dice game probabilities", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n"}
{"id": 47367, "name": "Sokoban", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n"}
{"id": 47368, "name": "Practical numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n"}
{"id": 47369, "name": "Literals_Floating point", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 47370, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 47371, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 47372, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 47373, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47374, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47375, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 47376, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 47377, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47378, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47379, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 47380, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 47381, "name": "Word search", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n"}
{"id": 47382, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 47383, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 47384, "name": "Object serialization", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 47385, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 47386, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 47387, "name": "Long year", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 47388, "name": "Zumkeller numbers", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n"}
{"id": 47389, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 47390, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 47391, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 47392, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 47393, "name": "Constrained genericity", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n", "Java": "interface Eatable\n{\n    void eat();\n}\n"}
{"id": 47394, "name": "Markov chain text generator", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\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.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n"}
{"id": 47395, "name": "Dijkstra's algorithm", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 47396, "name": "Geometric algebra", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n"}
{"id": 47397, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 47398, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 47399, "name": "Associative array_Iteration", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 47400, "name": "Define a primitive data type", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 47401, "name": "AVL tree", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n"}
{"id": 47402, "name": "AVL tree", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n"}
{"id": 47403, "name": "Penrose tiling", "C++": "#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n\nint main() {\n    std::ofstream out(\"penrose_tiling.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string penrose(\"[N]++[N]++[N]++[N]++[N]\");\n    for (int i = 1; i <= 4; ++i) {\n        std::string next;\n        for (char ch : penrose) {\n            switch (ch) {\n            case 'A':\n                break;\n            case 'M':\n                next += \"OA++PA----NA[-OA----MA]++\";\n                break;\n            case 'N':\n                next += \"+OA--PA[---MA--NA]+\";\n                break;\n            case 'O':\n                next += \"-MA++NA[+++OA++PA]-\";\n                break;\n            case 'P':\n                next += \"--OA++++MA[+PA++++NA]--NA\";\n                break;\n            default:\n                next += ch;\n                break;\n            }\n        }\n        penrose = std::move(next);\n    }\n    const double r = 30;\n    const double pi5 = 0.628318530717959;\n    double x = r * 8, y = r * 8, theta = pi5;\n    std::set<std::string> svg;\n    std::stack<std::tuple<double, double, double>> stack;\n    for (char ch : penrose) {\n        switch (ch) {\n        case 'A': {\n            double nx = x + r * std::cos(theta);\n            double ny = y + r * std::sin(theta);\n            std::ostringstream line;\n            line << std::fixed << std::setprecision(3) << \"<line x1='\" << x\n                 << \"' y1='\" << y << \"' x2='\" << nx << \"' y2='\" << ny << \"'/>\";\n            svg.insert(line.str());\n            x = nx;\n            y = ny;\n        } break;\n        case '+':\n            theta += pi5;\n            break;\n        case '-':\n            theta -= pi5;\n            break;\n        case '[':\n            stack.push({x, y, theta});\n            break;\n        case ']':\n            std::tie(x, y, theta) = stack.top();\n            stack.pop();\n            break;\n        }\n    }\n    out << \"<svg xmlns='http:\n        << \"' width='\" << r * 16 << \"'>\\n\"\n        << \"<rect height='100%' width='100%' fill='black'/>\\n\"\n        << \"<g stroke='rgb(255,165,0)'>\\n\";\n    for (const auto& line : svg)\n        out << line << '\\n';\n    out << \"</g>\\n</svg>\\n\";\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.awt.*;\nimport java.util.List;\nimport java.awt.geom.Path2D;\nimport java.util.*;\nimport javax.swing.*;\nimport static java.lang.Math.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class PenroseTiling extends JPanel {\n    \n    class Tile {\n        double x, y, angle, size;\n        Type type;\n\n        Tile(Type t, double x, double y, double a, double s) {\n            type = t;\n            this.x = x;\n            this.y = y;\n            angle = a;\n            size = s;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Tile) {\n                Tile t = (Tile) o;\n                return type == t.type && x == t.x && y == t.y && angle == t.angle;\n            }\n            return false;\n        }\n    }\n\n    enum Type {\n        Kite, Dart\n    }\n\n    static final double G = (1 + sqrt(5)) / 2; \n    static final double T = toRadians(36); \n\n    List<Tile> tiles = new ArrayList<>();\n\n    public PenroseTiling() {\n        int w = 700, h = 450;\n        setPreferredSize(new Dimension(w, h));\n        setBackground(Color.white);\n\n        tiles = deflateTiles(setupPrototiles(w, h), 5);\n    }\n\n    List<Tile> setupPrototiles(int w, int h) {\n        List<Tile> proto = new ArrayList<>();\n\n        \n        for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)\n            proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));\n\n        return proto;\n    }\n\n    List<Tile> deflateTiles(List<Tile> tls, int generation) {\n        if (generation <= 0)\n            return tls;\n\n        List<Tile> next = new ArrayList<>();\n\n        for (Tile tile : tls) {\n            double x = tile.x, y = tile.y, a = tile.angle, nx, ny;\n            double size = tile.size / G;\n\n            if (tile.type == Type.Dart) {\n                next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    nx = x + cos(a - 4 * T * sign) * G * tile.size;\n                    ny = y - sin(a - 4 * T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));\n                }\n\n            } else {\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));\n\n                    nx = x + cos(a - T * sign) * G * tile.size;\n                    ny = y - sin(a - T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));\n                }\n            }\n        }\n        \n        tls = next.stream().distinct().collect(toList());\n\n        return deflateTiles(tls, generation - 1);\n    }\n\n    void drawTiles(Graphics2D g) {\n        double[][] dist = {{G, G, G}, {-G, -1, -G}};\n        for (Tile tile : tiles) {\n            double angle = tile.angle - T;\n            Path2D path = new Path2D.Double();\n            path.moveTo(tile.x, tile.y);\n\n            int ord = tile.type.ordinal();\n            for (int i = 0; i < 3; i++) {\n                double x = tile.x + dist[ord][i] * tile.size * cos(angle);\n                double y = tile.y - dist[ord][i] * tile.size * sin(angle);\n                path.lineTo(x, y);\n                angle += T;\n            }\n            path.closePath();\n            g.setColor(ord == 0 ? Color.orange : Color.yellow);\n            g.fill(path);\n            g.setColor(Color.darkGray);\n            g.draw(path);\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics og) {\n        super.paintComponent(og);\n        Graphics2D g = (Graphics2D) og;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        drawTiles(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(\"Penrose Tiling\");\n            f.setResizable(false);\n            f.add(new PenroseTiling(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 47404, "name": "Sphenic numbers", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nstd::vector<int> prime_factors(int n) {\n    std::vector<int> factors;\n    if (n > 1 && (n & 1) == 0) {\n        factors.push_back(2);\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            factors.push_back(p);\n            while (n % p == 0)\n                n /= p;\n        }\n    }\n    if (n > 1)\n        factors.push_back(n);\n    return factors;\n}\n\nint main() {\n    const int limit = 1000000;\n    const int imax = limit / 6;\n    std::vector<bool> sieve = prime_sieve(imax + 1);\n    std::vector<bool> sphenic(limit + 1, false);\n    for (int i = 0; i <= imax; ++i) {\n        if (!sieve[i])\n            continue;\n        int jmax = std::min(imax, limit / (i * i));\n        if (jmax <= i)\n            break;\n        for (int j = i + 1; j <= jmax; ++j) {\n            if (!sieve[j])\n                continue;\n            int p = i * j;\n            int kmax = std::min(imax, limit / p);\n            if (kmax <= j)\n                break;\n            for (int k = j + 1; k <= kmax; ++k) {\n                if (!sieve[k])\n                    continue;\n                assert(p * k <= limit);\n                sphenic[p * k] = true;\n            }\n        }\n    }\n\n    std::cout << \"Sphenic numbers < 1000:\\n\";\n    for (int i = 0, n = 0; i < 1000; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++n;\n        std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n    for (int i = 0, n = 0; i < 10000; ++i) {\n        if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n            ++n;\n            std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n                      << (n % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n\n    int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n    for (int i = 0; i < limit; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++count;\n        if (count == 200000)\n            s200000 = i;\n        if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n            ++triplets;\n            if (triplets == 5000)\n                t5000 = i;\n        }\n    }\n\n    std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n    std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n    auto factors = prime_factors(s200000);\n    assert(factors.size() == 3);\n    std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n              << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n              << '\\n';\n\n    std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n              << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}\n", "Java": "import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SphenicNumbers {\n    public static void main(String[] args) {\n        final int limit = 1000000;\n        final int imax = limit / 6;\n        boolean[] sieve = primeSieve(imax + 1);\n        boolean[] sphenic = new boolean[limit + 1];\n        for (int i = 0; i <= imax; ++i) {\n            if (!sieve[i])\n                continue;\n            int jmax = Math.min(imax, limit / (i * i));\n            if (jmax <= i)\n                break;\n            for (int j = i + 1; j <= jmax; ++j) {\n                if (!sieve[j])\n                    continue;\n                int p = i * j;\n                int kmax = Math.min(imax, limit / p);\n                if (kmax <= j)\n                    break;\n                for (int k = j + 1; k <= kmax; ++k) {\n                    if (!sieve[k])\n                        continue;\n                    assert(p * k <= limit);\n                    sphenic[p * k] = true;\n                }\n            }\n        }\n    \n        System.out.println(\"Sphenic numbers < 1000:\");\n        for (int i = 0, n = 0; i < 1000; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++n;\n            System.out.printf(\"%3d%c\", i, n % 15 == 0 ? '\\n' : ' ');\n        }\n    \n        System.out.println(\"\\nSphenic triplets < 10,000:\");\n        for (int i = 0, n = 0; i < 10000; ++i) {\n            if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n                ++n;\n                System.out.printf(\"(%d, %d, %d)%c\",\n                                  i - 2, i - 1, i, n % 3 == 0 ? '\\n' : ' ');\n            }\n        }\n    \n        int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n        for (int i = 0; i < limit; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++count;\n            if (count == 200000)\n                s200000 = i;\n            if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n                ++triplets;\n                if (triplets == 5000)\n                    t5000 = i;\n            }\n        }\n    \n        System.out.printf(\"\\nNumber of sphenic numbers < 1,000,000: %d\\n\", count);\n        System.out.printf(\"Number of sphenic triplets < 1,000,000: %d\\n\", triplets);\n    \n        List<Integer> factors = primeFactors(s200000);\n        assert(factors.size() == 3);\n        System.out.printf(\"The 200,000th sphenic number: %d = %d * %d * %d\\n\",\n                          s200000, factors.get(0), factors.get(1),\n                          factors.get(2));\n        System.out.printf(\"The 5,000th sphenic triplet: (%d, %d, %d)\\n\",\n                          t5000 - 2, t5000 - 1, t5000);\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3, sq = 9; sq < limit; p += 2) {\n            if (sieve[p]) {\n                for (int q = sq; q < limit; q += p << 1)\n                    sieve[q] = false;\n            }\n            sq += (p + 1) << 2;\n        }\n        return sieve;\n    }\n    \n    private static List<Integer> primeFactors(int n) {\n        List<Integer> factors = new ArrayList<>();\n        if (n > 1 && (n & 1) == 0) {\n            factors.add(2);\n            while ((n & 1) == 0)\n                n >>= 1;\n        }\n        for (int p = 3; p * p <= n; p += 2) {\n            if (n % p == 0) {\n                factors.add(p);\n                while (n % p == 0)\n                    n /= p;\n            }\n        }\n        if (n > 1)\n            factors.add(n);\n        return factors;\n    }\n}\n"}
{"id": 47405, "name": "Find duplicate files", "C++": "#include<iostream>\n#include<string>\n#include<boost/filesystem.hpp>\n#include<boost/format.hpp>\n#include<boost/iostreams/device/mapped_file.hpp>\n#include<optional>\n#include<algorithm>\n#include<iterator>\n#include<execution>\n#include\"dependencies/xxhash.hpp\" \n\n\ntemplate<typename  T, typename V, typename F>\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n    size_t partitions = 0;\n    while (begin != end) {\n        auto const& value = getvalue(*begin);\n        auto current = begin;\n        while (++current != end && getvalue(*current) == value);\n        callback(begin, current, value);\n        ++partitions;\n        begin = current;\n    }\n    return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n    explicit file_entry(fs::directory_entry const & entry) \n        : path_{entry.path()}, size_{fs::file_size(entry)}\n    {}\n    auto size() const { return size_; }\n    auto const& path() const { return path_; }\n    auto get_hash() {\n        if (!hash_)\n            hash_ = compute_hash();\n        return *hash_;\n    }\nprivate:\n    xxh::hash64_t compute_hash() {\n        bi::mapped_file_source source;\n        source.open<fs::wpath>(this->path());\n        if (!source.is_open()) {\n            std::cerr << \"Cannot open \" << path() << std::endl;\n            throw std::runtime_error(\"Cannot open file\");\n        }\n        xxh::hash_state64_t hash_stream;\n        hash_stream.update(source.data(), size_);\n        return hash_stream.digest();\n    }\nprivate:\n    fs::wpath path_;\n    uintmax_t size_;\n    std::optional<xxh::hash64_t> hash_;\n};\n\nusing vector_type = std::vector<file_entry>;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n    size_t found = 0, ignored = 0;\n    if (!fs::is_directory(path)) {\n        std::cerr << path << \" is not a directory!\" << std::endl;\n    }\n    else {\n        std::cerr << \"Searching \" << path << std::endl;\n\n        for (auto& e : fs::recursive_directory_iterator(path)) {\n            ++found;\n            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n                file_vector.emplace_back(e);\n            else ++ignored;\n        }\n    }\n    return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n    vector_type files;\n    for (auto i = 1; i < argn; ++i) {\n        fs::wpath path(argv[i]);\n        auto [found, ignored] = find_files_in_dir(path, files);\n        std::cerr << boost::format{\n            \"  %1$6d files found\\n\"\n            \"  %2$6d files ignored\\n\"\n            \"  %3$6d files added\\n\" } % found % ignored % (found - ignored) \n            << std::endl;\n    }\n\n    std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n    \n    std::sort(std::execution::par_unseq, files.begin(), files.end()\n        , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n    );\n    for_each_adjacent_range(\n        std::begin(files)\n        , std::end(files)\n        , [](vector_type::value_type const& f) { return f.size(); }\n        , [](auto start, auto end, auto file_size) {\n            \n            size_t nr_of_files = std::distance(start, end);\n            if (nr_of_files > 1) {\n                \n                std::sort(start, end, [](auto& a, auto& b) { \n                    auto const& ha = a.get_hash();\n                    auto const& hb = b.get_hash();\n                    auto const& pa = a.path();\n                    auto const& pb = b.path();\n                    return std::tie(ha, pa) < std::tie(hb, pb); \n                    });\n                for_each_adjacent_range(\n                    start\n                    , end\n                    , [](vector_type::value_type& f) { return f.get_hash(); }\n                    , [file_size](auto hstart, auto hend, auto hash) {\n                        \n                        \n                        size_t hnr_of_files = std::distance(hstart, hend);\n                        if (hnr_of_files > 1) {\n                            std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n                                % hnr_of_files % file_size % hash;\n                            std::for_each(hstart, hend, [hash, file_size](auto& e) {\n                                std::cout << '\\t' << e.path() << '\\n';\n                                }\n                            );\n                        }\n                    }\n                );\n            }\n        }\n    );\n    \n    return 0;\n}\n", "Java": "import java.io.*;\nimport java.nio.*;\nimport java.nio.file.*;\nimport java.nio.file.attribute.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class DuplicateFiles {\n    public static void main(String[] args) {\n        if (args.length != 2) {\n            System.err.println(\"Directory name and minimum file size are required.\");\n            System.exit(1);\n        }\n        try {\n            findDuplicateFiles(args[0], Long.parseLong(args[1]));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void findDuplicateFiles(String directory, long minimumSize)\n        throws IOException, NoSuchAlgorithmException {\n        System.out.println(\"Directory: '\" + directory + \"', minimum size: \" + minimumSize + \" bytes.\");\n        Path path = FileSystems.getDefault().getPath(directory);\n        FileVisitor visitor = new FileVisitor(path, minimumSize);\n        Files.walkFileTree(path, visitor);\n        System.out.println(\"The following sets of files have the same size and checksum:\");\n        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {\n            Map<Object, List<String>> map = e.getValue();\n            if (!containsDuplicates(map))\n                continue;\n            List<List<String>> fileSets = new ArrayList<>(map.values());\n            for (List<String> files : fileSets)\n                Collections.sort(files);\n            Collections.sort(fileSets, new StringListComparator());\n            FileKey key = e.getKey();\n            System.out.println();\n            System.out.println(\"Size: \" + key.size_ + \" bytes\");\n            for (List<String> files : fileSets) {\n                for (int i = 0, n = files.size(); i < n; ++i) {\n                    if (i > 0)\n                        System.out.print(\" = \");\n                    System.out.print(files.get(i));\n                }\n                System.out.println();\n            }\n        }\n    }\n\n    private static class StringListComparator implements Comparator<List<String>> {\n        public int compare(List<String> a, List<String> b) {\n            int len1 = a.size(), len2 = b.size();\n            for (int i = 0; i < len1 && i < len2; ++i) {\n                int c = a.get(i).compareTo(b.get(i));\n                if (c != 0)\n                    return c;\n            }\n            return Integer.compare(len1, len2);\n        }\n    }\n\n    private static boolean containsDuplicates(Map<Object, List<String>> map) {\n        if (map.size() > 1)\n            return true;\n        for (List<String> files : map.values()) {\n            if (files.size() > 1)\n                return true;\n        }\n        return false;\n    }\n\n    private static class FileVisitor extends SimpleFileVisitor<Path> {\n        private MessageDigest digest_;\n        private Path directory_;\n        private long minimumSize_;\n        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();\n\n        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {\n            directory_ = directory;\n            minimumSize_ = minimumSize;\n            digest_ = MessageDigest.getInstance(\"MD5\");\n        }\n\n        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n            if (attrs.size() >= minimumSize_) {\n                FileKey key = new FileKey(file, attrs, getMD5Sum(file));\n                Map<Object, List<String>> map = fileMap_.get(key);\n                if (map == null)\n                    fileMap_.put(key, map = new HashMap<>());\n                List<String> files = map.get(attrs.fileKey());\n                if (files == null)\n                    map.put(attrs.fileKey(), files = new ArrayList<>());\n                Path relative = directory_.relativize(file);\n                files.add(relative.toString());\n            }\n            return FileVisitResult.CONTINUE;\n        }\n\n        private byte[] getMD5Sum(Path file) throws IOException {\n            digest_.reset();\n            try (InputStream in = new FileInputStream(file.toString())) {\n                byte[] buffer = new byte[8192];\n                int bytes;\n                while ((bytes = in.read(buffer)) != -1) {\n                    digest_.update(buffer, 0, bytes);\n                }\n            }\n            return digest_.digest();\n        }\n    }\n\n    private static class FileKey implements Comparable<FileKey> {\n        private byte[] hash_;\n        private long size_;\n\n        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {\n            size_ = attrs.size();\n            hash_ = hash;\n        }\n\n        public int compareTo(FileKey other) {\n            int c = Long.compare(other.size_, size_);\n            if (c == 0)\n                c = hashCompare(hash_, other.hash_);\n            return c;\n        }\n    }\n\n    private static int hashCompare(byte[] a, byte[] b) {\n        int len1 = a.length, len2 = b.length;\n        for (int i = 0; i < len1 && i < len2; ++i) {\n            int c = Byte.compare(a[i], b[i]);\n            if (c != 0)\n                return c;\n        }\n        return Integer.compare(len1, len2);\n    }\n}\n"}
{"id": 47406, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47407, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 47408, "name": "Order disjoint list items", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\ntemplate <typename T>\nvoid print(const std::vector<T> v) {\n  std::cout << \"{ \";\n  for (const auto& e : v) {\n    std::cout << e << \" \";\n  }\n  std::cout << \"}\";\n}\n\ntemplate <typename T>\nauto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {\n  std::vector<T*> M_p(std::size(M));\n  for (auto i = 0; i < std::size(M_p); ++i) {\n    M_p[i] = &M[i];\n  }\n  for (auto e : N) {\n    auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {\n      if (c != nullptr) {\n        if (*c == e) return true;\n      }\n      return false;\n    });\n    if (i != std::end(M_p)) {\n      *i = nullptr;\n    }\n  }\n  for (auto i = 0; i < std::size(N); ++i) {\n    auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {\n      return c == nullptr;\n    });\n    if (j != std::end(M_p)) {\n      *j = &M[std::distance(std::begin(M_p), j)];\n      **j = N[i];\n    }\n  }\n  return M;\n}\n\nint main() {\n  std::vector<std::vector<std::vector<std::string>>> l = {\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" }, { \"mat\", \"cat\" } },\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" },{ \"cat\", \"mat\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"C\", \"A\", \"B\", \"C\" },{ \"C\", \"A\", \"C\", \"A\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"D\", \"A\", \"B\", \"E\" },{ \"E\", \"A\", \"D\", \"A\" } },\n    { { \"A\", \"B\" },{ \"B\" } },\n    { { \"A\", \"B\" },{ \"B\", \"A\" } },\n    { { \"A\", \"B\", \"B\", \"A\" },{ \"B\", \"A\" } }\n  };\n  for (const auto& e : l) {\n    std::cout << \"M: \";\n    print(e[0]);\n    std::cout << \", N: \";\n    print(e[1]);\n    std::cout << \", M': \";\n    auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);\n    print(res);\n    std::cout << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.BitSet;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class OrderDisjointItems {\n\n    public static void main(String[] args) {\n        final String[][] MNs = {{\"the cat sat on the mat\", \"mat cat\"},\n        {\"the cat sat on the mat\", \"cat mat\"},\n        {\"A B C A B C A B C\", \"C A C A\"}, {\"A B C A B D A B E\", \"E A D A\"},\n        {\"A B\", \"B\"}, {\"A B\", \"B A\"}, {\"A B B A\", \"B A\"}, {\"X X Y\", \"X\"}};\n\n        for (String[] a : MNs) {\n            String[] r = orderDisjointItems(a[0].split(\" \"), a[1].split(\" \"));\n            System.out.printf(\"%s | %s -> %s%n\", a[0], a[1], Arrays.toString(r));\n        }\n    }\n\n    \n    static String[] orderDisjointItems(String[] m, String[] n) {\n        for (String e : n) {\n            int idx = ArrayUtils.indexOf(m, e);\n            if (idx != -1)\n                m[idx] = null;\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (m[i] == null)\n                m[i] = n[j++];\n        }\n        return m;\n    }\n\n    \n    static String[] orderDisjointItems2(String[] m, String[] n) {\n        BitSet bitSet = new BitSet(m.length);\n        for (String e : n) {\n            int idx = -1;\n            do {\n                idx = ArrayUtils.indexOf(m, e, idx + 1);\n            } while (idx != -1 && bitSet.get(idx));\n            if (idx != -1)\n                bitSet.set(idx);\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (bitSet.get(i))\n                m[i] = n[j++];\n        }\n        return m;\n    }\n}\n"}
{"id": 47409, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 47410, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 47411, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 47412, "name": "Ramanujan primes", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n"}
{"id": 47413, "name": "Ramanujan primes", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n"}
{"id": 47414, "name": "Ramanujan primes", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n"}
{"id": 47415, "name": "Sierpinski curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 47416, "name": "Sierpinski curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 47417, "name": "Most frequent k chars distance", "C++": "#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <sstream>\n\nstd::string mostFreqKHashing ( const std::string & input , int k ) {\n   std::ostringstream oss ;\n   std::map<char, int> frequencies ;\n   for ( char c : input ) {\n      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;\n   }\n   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;\n   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,\n\t         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; \n\t         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }\n\t         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;\n   for ( int i = 0 ; i < letters.size( ) ; i++ ) {\n      oss << std::get<0>( letters[ i ] ) ;\n      oss << std::get<1>( letters[ i ] ) ;\n   }\n   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;\n   if ( letters.size( ) >= k ) {\n      return output ;\n   }\n   else {\n      return output.append( \"NULL0\" ) ;\n   }\n}\n\nint mostFreqKSimilarity ( const std::string & first , const std::string & second ) {\n   int i = 0 ;\n   while ( i < first.length( ) - 1  ) {\n      auto found = second.find_first_of( first.substr( i , 2 ) ) ;\n      if ( found != std::string::npos ) \n\t return std::stoi ( first.substr( i , 2 )) ;\n      else \n\t i += 2 ;\n   }\n   return 0 ;\n}\n\nint mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {\n   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;\n}\n\nint main( ) {\n   std::string s1(\"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\" ) ;\n   std::string s2( \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\" ) ;\n   std::cout << \"MostFreqKHashing( s1 , 2 ) = \" << mostFreqKHashing( s1 , 2 ) << '\\n' ;\n   std::cout << \"MostFreqKHashing( s2 , 2 ) = \" << mostFreqKHashing( s2 , 2 ) << '\\n' ;\n   return 0 ;\n}\n", "Java": "import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class SDF {\n\n    \n    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {\n\n        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();\n\n        for (char element : array) {\n            Integer count = countMap.get(element);\n            count = (count == null) ? 1 : count + 1;\n            countMap.put(element, count);\n        }\n\n        return countMap;\n    }\n    \n    \n    private static <K, V extends Comparable<? super V>>\n            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { \n\tList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());\n\t\n\tCollections.sort(list, new Comparator<Map.Entry<K, V>>() {\n\t\tpublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n\t\t    return o2.getValue().compareTo(o1.getValue());\n\t\t}\n\t    });\n\n\t\n\t\n\tHashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();\n\tfor (Map.Entry<K, V> entry : list) {\n\t    sortedHashMap.put(entry.getKey(), entry.getValue());\n\t} \n\treturn sortedHashMap;\n    }\n    \n    public static String mostOcurrencesElement(char[] array, int k) {\n        HashMap<Character, Integer> countMap = countElementOcurrences(array);\n        System.out.println(countMap);\n        Map<Character, Integer> map = descendingSortByValues(countMap); \n        System.out.println(map);\n        int i = 0;\n        String output = \"\";\n        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {\n\t    if (i++ >= k)\n\t\tbreak;\n            output += \"\" + pairs.getKey() + pairs.getValue();\n        }\n        return output;\n    }\n    \n    public static int getDiff(String str1, String str2, int limit) {\n        int similarity = 0;\n\tint k = 0;\n\tfor (int i = 0; i < str1.length() ; i = k) {\n\t    k ++;\n\t    if (Character.isLetter(str1.charAt(i))) {\n\t\tint pos = str2.indexOf(str1.charAt(i));\n\t\t\t\t\n\t\tif (pos >= 0) {\t\n\t\t    String digitStr1 = \"\";\n\t\t    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {\n\t\t\tdigitStr1 += str1.charAt(k);\n\t\t\tk++;\n\t\t    }\n\t\t\t\t\t\n\t\t    int k2 = pos+1;\n\t\t    String digitStr2 = \"\";\n\t\t    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {\n\t\t\tdigitStr2 += str2.charAt(k2);\n\t\t\tk2++;\n\t\t    }\n\t\t\t\t\t\n\t\t    similarity += Integer.parseInt(digitStr2)\n\t\t\t+ Integer.parseInt(digitStr1);\n\t\t\t\t\t\n\t\t} \n\t    }\n\t}\n\treturn Math.abs(limit - similarity);\n    }\n    \n    public static int SDFfunc(String str1, String str2, int limit) {\n        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);\n    }\n\n    public static void main(String[] args) {\n        String input1 = \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\";\n        String input2 = \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\";\n        System.out.println(SDF.SDFfunc(input1,input2,100));\n\n    }\n\n}\n"}
{"id": 47418, "name": "Text completion", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\n\nint levenshtein_distance(const std::string& str1, const std::string& str2) {\n    size_t m = str1.size(), n = str2.size();\n    std::vector<int> cost(n + 1);\n    std::iota(cost.begin(), cost.end(), 0);\n    for (size_t i = 0; i < m; ++i) {\n        cost[0] = i + 1;\n        int prev = i;\n        for (size_t j = 0; j < n; ++j) {\n            int c = (str1[i] == str2[j]) ? prev\n                : 1 + std::min(std::min(cost[j + 1], cost[j]), prev);\n            prev = cost[j + 1];\n            cost[j + 1] = c;\n        }\n    }\n    return cost[n];\n}\n\ntemplate <typename T>\nvoid print_vector(const std::vector<T>& vec) {\n    auto i = vec.begin();\n    if (i == vec.end())\n        return;\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 3) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary word\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1]);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << '\\n';\n        return EXIT_FAILURE;\n    }\n    std::string word(argv[2]);\n    if (word.empty()) {\n        std::cerr << \"Word must not be empty\\n\";\n        return EXIT_FAILURE;\n    }\n    constexpr size_t max_dist = 4;\n    std::vector<std::string> matches[max_dist + 1];\n    std::string match;\n    while (getline(in, match)) {\n        int distance = levenshtein_distance(word, match);\n        if (distance <= max_dist)\n            matches[distance].push_back(match);\n    }\n    for (size_t dist = 0; dist <= max_dist; ++dist) {\n        if (matches[dist].empty())\n            continue;\n        std::cout << \"Words at Levenshtein distance of \" << dist\n            << \" (\" << 100 - (100 * dist)/word.size()\n            << \"% similarity) from '\" << word << \"':\\n\";\n        print_vector(matches[dist]);\n        std::cout << \"\\n\\n\";\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\n\n\npublic class textCompletionConcept {\n    public static int correct = 0;\n    public static ArrayList<String> listed = new ArrayList<>();\n    public static void main(String[]args) throws IOException, URISyntaxException {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Input word: \");\n        String errorRode = input.next();\n        File file = new File(new \n        File(textCompletionConcept.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath() + File.separator + \"words.txt\");\n        Scanner reader = new Scanner(file);\n        while(reader.hasNext()){\n            double percent;\n            String compareToThis = reader.nextLine();\n                    char[] s1 = errorRode.toCharArray();\n                    char[] s2 = compareToThis.toCharArray();\n                    int maxlen = Math.min(s1.length, s2.length);\n                    for (int index = 0; index < maxlen; index++) {\n                        String x = String.valueOf(s1[index]);\n                        String y = String.valueOf(s2[index]);\n                        if (x.equals(y)) {\n                            correct++;\n                        }\n                    }\n                    double length = Math.max(s1.length, s2.length);\n                    percent = correct / length;\n                    percent *= 100;\n                    boolean perfect = false;\n                    if (percent >= 80 && compareToThis.charAt(0) == errorRode.charAt(0)) {\n                        if(String.valueOf(percent).equals(\"100.00\")){\n                            perfect = true;\n                        }\n                        String addtoit = compareToThis + \" : \" + String.format(\"%.2f\", percent) + \"% similar.\";\n                        listed.add(addtoit);\n                    }\n                    if(compareToThis.contains(errorRode) && !perfect && errorRode.length() * 2 > compareToThis.length()){\n                        String addtoit = compareToThis + \" : 80.00% similar.\";\n                        listed.add(addtoit);\n                    }\n            correct = 0;\n        }\n\n        for(String x : listed){\n            if(x.contains(\"100.00% similar.\")){\n                System.out.println(x);\n                listed.clear();\n                break;\n            }\n        }\n\n        for(String x : listed){\n            System.out.println(x);\n        }\n    }\n}\n"}
{"id": 47419, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 47420, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 47421, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 47422, "name": "Lychrel numbers", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n"}
{"id": 47423, "name": "Lychrel numbers", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n"}
{"id": 47424, "name": "Erdös-Selfridge categorization of primes", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <primesieve.hpp>\n\nclass erdos_selfridge {\npublic:\n    explicit erdos_selfridge(int limit);\n    uint64_t get_prime(int index) const { return primes_[index].first; }\n    int get_category(int index);\n\nprivate:\n    std::vector<std::pair<uint64_t, int>> primes_;\n    size_t get_index(uint64_t prime) const;\n};\n\nerdos_selfridge::erdos_selfridge(int limit) {\n    primesieve::iterator iter;\n    for (int i = 0; i < limit; ++i)\n        primes_.emplace_back(iter.next_prime(), 0);\n}\n\nint erdos_selfridge::get_category(int index) {\n    auto& pair = primes_[index];\n    if (pair.second != 0)\n        return pair.second;\n    int max_category = 0;\n    uint64_t n = pair.first + 1;\n    for (int i = 0; n > 1; ++i) {\n        uint64_t p = primes_[i].first;\n        if (p * p > n)\n            break;\n        int count = 0;\n        for (; n % p == 0; ++count)\n            n /= p;\n        if (count != 0) {\n            int category = (p <= 3) ? 1 : 1 + get_category(i);\n            max_category = std::max(max_category, category);\n        }\n    }\n    if (n > 1) {\n        int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));\n        max_category = std::max(max_category, category);\n    }\n    pair.second = max_category;\n    return max_category;\n}\n\nsize_t erdos_selfridge::get_index(uint64_t prime) const {\n    auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,\n                               [](const std::pair<uint64_t, int>& p,\n                                  uint64_t n) { return p.first < n; });\n    assert(it != primes_.end());\n    assert(it->first == prime);\n    return std::distance(primes_.begin(), it);\n}\n\nauto get_primes_by_category(erdos_selfridge& es, int limit) {\n    std::map<int, std::vector<uint64_t>> primes_by_category;\n    for (int i = 0; i < limit; ++i) {\n        uint64_t prime = es.get_prime(i);\n        int category = es.get_category(i);\n        primes_by_category[category].push_back(prime);\n    }\n    return primes_by_category;\n}\n\nint main() {\n    const int limit1 = 200, limit2 = 1000000;\n\n    erdos_selfridge es(limit2);\n\n    std::cout << \"First 200 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit1)) {\n        std::cout << \"Category \" << p.first << \":\\n\";\n        for (size_t i = 0, n = p.second.size(); i != n; ++i) {\n            std::cout << std::setw(4) << p.second[i]\n                      << ((i + 1) % 15 == 0 ? '\\n' : ' ');\n        }\n        std::cout << \"\\n\\n\";\n    }\n\n    std::cout << \"First 1,000,000 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit2)) {\n        const auto& v = p.second;\n        std::cout << \"Category \" << std::setw(2) << p.first << \": \"\n                  << \"first = \" << std::setw(7) << v.front()\n                  << \"  last = \" << std::setw(8) << v.back()\n                  << \"  count = \" << v.size() << '\\n';\n    }\n}\n", "Java": "import java.util.*;\n\npublic class ErdosSelfridge {\n    private int[] primes;\n    private int[] category;\n\n    public static void main(String[] args) {\n        ErdosSelfridge es = new ErdosSelfridge(1000000);\n\n        System.out.println(\"First 200 primes:\");\n        for (var e : es.getPrimesByCategory(200).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %d:\\n\", category);\n            for (int i = 0, n = primes.size(); i != n; ++i)\n                System.out.printf(\"%4d%c\", primes.get(i), (i + 1) % 15 == 0 ? '\\n' : ' ');\n            System.out.printf(\"\\n\\n\");\n        }\n\n        System.out.println(\"First 1,000,000 primes:\");\n        for (var e : es.getPrimesByCategory(1000000).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %2d: first = %7d  last = %8d  count = %d\\n\", category,\n                              primes.get(0), primes.get(primes.size() - 1), primes.size());\n        }\n    }\n\n    private ErdosSelfridge(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);\n        List<Integer> primeList = new ArrayList<>();\n        for (int i = 0; i < limit; ++i)\n            primeList.add(primeGen.nextPrime());\n        primes = new int[primeList.size()];\n        for (int i = 0; i < primes.length; ++i)\n            primes[i] = primeList.get(i);\n        category = new int[primes.length];\n    }\n\n    private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {\n        Map<Integer, List<Integer>> result = new TreeMap<>();\n        for (int i = 0; i < limit; ++i) {\n            var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());\n            p.add(primes[i]);\n        }\n        return result;\n    }\n\n    private int getCategory(int index) {\n        if (category[index] != 0)\n            return category[index];\n        int maxCategory = 0;\n        int n = primes[index] + 1;\n        for (int i = 0; n > 1; ++i) {\n            int p = primes[i];\n            if (p * p > n)\n                break;\n            int count = 0;\n            for (; n % p == 0; ++count)\n                n /= p;\n            if (count != 0) {\n                int category = (p <= 3) ? 1 : 1 + getCategory(i);\n                maxCategory = Math.max(maxCategory, category);\n            }\n        }\n        if (n > 1) {\n            int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));\n            maxCategory = Math.max(maxCategory, category);\n        }\n        category[index] = maxCategory;\n        return maxCategory;\n    }\n\n    private int getIndex(int prime) {\n       return Arrays.binarySearch(primes, prime);\n    }\n}\n"}
{"id": 47425, "name": "Sierpinski square curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n"}
{"id": 47426, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 47427, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 47428, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 47429, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 47430, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 47431, "name": "Odd words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing word_list = std::vector<std::pair<std::string, std::string>>;\n\nvoid print_words(std::ostream& out, const word_list& words) {\n    int n = 1;\n    for (const auto& pair : words) {\n        out << std::right << std::setw(2) << n++ << \": \"\n            << std::left << std::setw(14) << pair.first\n            << pair.second << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    const int min_length = 5;\n    std::string line;\n    std::set<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            dictionary.insert(line);\n    }\n\n    word_list odd_words, even_words;\n\n    for (const std::string& word : dictionary) {\n        if (word.size() < min_length + 2*(min_length/2))\n            continue;\n        std::string odd_word, even_word;\n        for (auto w = word.begin(); w != word.end(); ++w) {\n            odd_word += *w;\n            if (++w == word.end())\n                break;\n            even_word += *w;\n        }\n\n        if (dictionary.find(odd_word) != dictionary.end())\n            odd_words.emplace_back(word, odd_word);\n\n        if (dictionary.find(even_word) != dictionary.end())\n            even_words.emplace_back(word, even_word);\n    }\n\n    std::cout << \"Odd words:\\n\";\n    print_words(std::cout, odd_words);\n\n    std::cout << \"\\nEven words:\\n\";\n    print_words(std::cout, even_words);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class OddWords {\n    public static void main(String[] args) {\n        try {\n            Set<String> dictionary = new TreeSet<>();\n            final int minLength = 5;\n            String fileName = \"unixdict.txt\";\n            if (args.length != 0)\n                fileName = args[0];\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        dictionary.add(line);\n                }\n            }\n            StringBuilder word1 = new StringBuilder();\n            StringBuilder word2 = new StringBuilder();\n            List<StringPair> evenWords = new ArrayList<>();\n            List<StringPair> oddWords = new ArrayList<>();\n            for (String word : dictionary) {\n                int length = word.length();\n                if (length < minLength + 2 * (minLength/2))\n                    continue;\n                word1.setLength(0);\n                word2.setLength(0);\n                for (int i = 0; i < length; ++i) {\n                    if ((i & 1) == 0)\n                        word1.append(word.charAt(i));\n                    else\n                        word2.append(word.charAt(i));\n                }\n                String oddWord = word1.toString();\n                String evenWord = word2.toString();\n                if (dictionary.contains(oddWord))\n                    oddWords.add(new StringPair(word, oddWord));\n                if (dictionary.contains(evenWord))\n                    evenWords.add(new StringPair(word, evenWord));\n            }\n            System.out.println(\"Odd words:\");\n            printWords(oddWords);\n            System.out.println(\"\\nEven words:\");\n            printWords(evenWords);\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n\n    private static void printWords(List<StringPair> strings) {\n        int n = 1;\n        for (StringPair pair : strings) {\n            System.out.printf(\"%2d: %-14s%s\\n\", n++,\n                                    pair.string1, pair.string2);\n        }\n    }\n\n    private static class StringPair {\n        private String string1;\n        private String string2;\n        private StringPair(String s1, String s2) {\n            string1 = s1;\n            string2 = s2;\n        }\n    }\n}\n"}
{"id": 47432, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n"}
{"id": 47433, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n"}
{"id": 47434, "name": "Word break problem", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n"}
{"id": 47435, "name": "Brilliant numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n"}
{"id": 47436, "name": "Brilliant numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n"}
{"id": 47437, "name": "Word ladder", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n\nbool one_away(const std::string& s1, const std::string& s2) {\n    if (s1.size() != s2.size())\n        return false;\n    bool result = false;\n    for (size_t i = 0, n = s1.size(); i != n; ++i) {\n        if (s1[i] != s2[i]) {\n            if (result)\n                return false;\n            result = true;\n        }\n    }\n    return result;\n}\n\n\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n                 separator_type separator) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += separator;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\n\n\n\nbool word_ladder(const word_map& words, const std::string& from,\n                 const std::string& to) {\n    auto w = words.find(from.size());\n    if (w != words.end()) {\n        auto poss = w->second;\n        std::vector<std::vector<std::string>> queue{{from}};\n        while (!queue.empty()) {\n            auto curr = queue.front();\n            queue.erase(queue.begin());\n            for (auto i = poss.begin(); i != poss.end();) {\n                if (!one_away(*i, curr.back())) {\n                    ++i;\n                    continue;\n                }\n                if (to == *i) {\n                    curr.push_back(to);\n                    std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n                    return true;\n                }\n                std::vector<std::string> temp(curr);\n                temp.push_back(*i);\n                queue.push_back(std::move(temp));\n                i = poss.erase(i);\n            }\n        }\n    }\n    std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n    return false;\n}\n\nint main() {\n    word_map words;\n    std::ifstream in(\"unixdict.txt\");\n    if (!in) {\n        std::cerr << \"Cannot open file unixdict.txt.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    while (getline(in, word))\n        words[word.size()].push_back(word);\n    word_ladder(words, \"boy\", \"man\");\n    word_ladder(words, \"girl\", \"lady\");\n    word_ladder(words, \"john\", \"jane\");\n    word_ladder(words, \"child\", \"adult\");\n    word_ladder(words, \"cat\", \"dog\");\n    word_ladder(words, \"lead\", \"gold\");\n    word_ladder(words, \"white\", \"black\");\n    word_ladder(words, \"bubble\", \"tickle\");\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n"}
{"id": 47438, "name": "Earliest difference between prime gaps", "C++": "#include <iostream>\n#include <locale>\n#include <unordered_map>\n\n#include <primesieve.hpp>\n\nclass prime_gaps {\npublic:\n    prime_gaps() { last_prime_ = iterator_.next_prime(); }\n    uint64_t find_gap_start(uint64_t gap);\nprivate:\n    primesieve::iterator iterator_;\n    uint64_t last_prime_;\n    std::unordered_map<uint64_t, uint64_t> gap_starts_;\n};\n\nuint64_t prime_gaps::find_gap_start(uint64_t gap) {\n    auto i = gap_starts_.find(gap);\n    if (i != gap_starts_.end())\n        return i->second;\n    for (;;) {\n        uint64_t prev = last_prime_;\n        last_prime_ = iterator_.next_prime();\n        uint64_t diff = last_prime_ - prev;\n        gap_starts_.emplace(diff, prev);\n        if (gap == diff)\n            return prev;\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const uint64_t limit = 100000000000;\n    prime_gaps pg;\n    for (uint64_t pm = 10, gap1 = 2;;) {\n        uint64_t start1 = pg.find_gap_start(gap1);\n        uint64_t gap2 = gap1 + 2;\n        uint64_t start2 = pg.find_gap_start(gap2);\n        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;\n        if (diff > pm) {\n            std::cout << \"Earliest difference > \" << pm\n                      << \" between adjacent prime gap starting primes:\\n\"\n                      << \"Gap \" << gap1 << \" starts at \" << start1 << \", gap \"\n                      << gap2 << \" starts at \" << start2 << \", difference is \"\n                      << diff << \".\\n\\n\";\n            if (pm == limit)\n                break;\n            pm *= 10;\n        } else {\n            gap1 = gap2;\n        }\n    }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n"}
{"id": 47439, "name": "Latin Squares in reduced form", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n"}
{"id": 47440, "name": "UPC", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n"}
{"id": 47441, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 47442, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 47443, "name": "Closest-pair problem", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n"}
{"id": 47444, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 47445, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 47446, "name": "Associative array_Creation", "C++": "#include <map>\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 47447, "name": "Wilson primes of order n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\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\nint main() {\n    using big_int = mpz_class;\n    const int limit = 11000;\n    std::vector<big_int> f{1};\n    f.reserve(limit);\n    big_int factorial = 1;\n    for (int i = 1; i < limit; ++i) {\n        factorial *= i;\n        f.push_back(factorial);\n    }\n    std::vector<int> primes = generate_primes(limit);\n    std::cout << \" n | Wilson primes\\n--------------------\\n\";\n    for (int n = 1, s = -1; n <= 11; ++n, s = -s) {\n        std::cout << std::setw(2) << n << \" |\";\n        for (int p : primes) {\n            if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)\n                std::cout << ' ' << p;\n        }\n        std::cout << '\\n';\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class WilsonPrimes {\n    public static void main(String[] args) {\n        final int limit = 11000;\n        BigInteger[] f = new BigInteger[limit];\n        f[0] = BigInteger.ONE;\n        BigInteger factorial = BigInteger.ONE;\n        for (int i = 1; i < limit; ++i) {\n            factorial = factorial.multiply(BigInteger.valueOf(i));\n            f[i] = factorial;\n        }\n        List<Integer> primes = generatePrimes(limit);\n        System.out.printf(\" n | Wilson primes\\n--------------------\\n\");\n        BigInteger s = BigInteger.valueOf(-1);\n        for (int n = 1; n <= 11; ++n) {\n            System.out.printf(\"%2d |\", n);\n            for (int p : primes) {\n                if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)\n                        .mod(BigInteger.valueOf(p * p))\n                        .equals(BigInteger.ZERO))\n                    System.out.printf(\" %d\", p);\n            }\n            s = s.negate();\n            System.out.println();\n        }\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": 47448, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n"}
{"id": 47449, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n"}
{"id": 47450, "name": "Plasma effect", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 47451, "name": "Plasma effect", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 47452, "name": "Rhonda numbers", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint digit_product(int base, int n) {\n    int product = 1;\n    for (; n != 0; n /= base)\n        product *= n % base;\n    return product;\n}\n\nint prime_factor_sum(int n) {\n    int sum = 0;\n    for (; (n & 1) == 0; n >>= 1)\n        sum += 2;\n    for (int p = 3; p * p <= n; p += 2)\n        for (; n % p == 0; n /= p)\n            sum += p;\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nbool is_prime(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 (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\nbool is_rhonda(int base, int n) {\n    return digit_product(base, n) == base * prime_factor_sum(n);\n}\n\nstd::string to_string(int base, int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nint main() {\n    const int limit = 15;\n    for (int base = 2; base <= 36; ++base) {\n        if (is_prime(base))\n            continue;\n        std::cout << \"First \" << limit << \" Rhonda numbers to base \" << base\n                  << \":\\n\";\n        int numbers[limit];\n        for (int n = 1, count = 0; count < limit; ++n) {\n            if (is_rhonda(base, n))\n                numbers[count++] = n;\n        }\n        std::cout << \"In base 10:\";\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << numbers[i];\n        std::cout << \"\\nIn base \" << base << ':';\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << to_string(base, numbers[i]);\n        std::cout << \"\\n\\n\";\n    }\n}\n", "Java": "public class RhondaNumbers {\n    public static void main(String[] args) {\n        final int limit = 15;\n        for (int base = 2; base <= 36; ++base) {\n            if (isPrime(base))\n                continue;\n            System.out.printf(\"First %d Rhonda numbers to base %d:\\n\", limit, base);\n            int numbers[] = new int[limit];\n            for (int n = 1, count = 0; count < limit; ++n) {\n                if (isRhonda(base, n))\n                    numbers[count++] = n;\n            }\n            System.out.printf(\"In base 10:\");\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %d\", numbers[i]);\n            System.out.printf(\"\\nIn base %d:\", base);\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %s\", Integer.toString(numbers[i], base));\n            System.out.printf(\"\\n\\n\");\n        }\n    }\n    \n    private static int digitProduct(int base, int n) {\n        int product = 1;\n        for (; n != 0; n /= base)\n            product *= n % base;\n        return product;\n    }\n     \n    private static int primeFactorSum(int n) {\n        int sum = 0;\n        for (; (n & 1) == 0; n >>= 1)\n            sum += 2;\n        for (int p = 3; p * p <= n; p += 2)\n            for (; n % p == 0; n /= p)\n                sum += p;\n        if (n > 1)\n            sum += n;\n        return sum;\n    }\n     \n    private static boolean isPrime(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 (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     \n    private static boolean isRhonda(int base, int n) {\n        return digitProduct(base, n) == base * primeFactorSum(n);\n    }\n}\n"}
{"id": 47453, "name": "Hello world_Newbie", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n"}
{"id": 47454, "name": "Hello world_Newbie", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n"}
{"id": 47455, "name": "Polymorphism", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n"}
{"id": 47456, "name": "Wagstaff primes", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n"}
{"id": 47457, "name": "Wagstaff primes", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n"}
{"id": 47458, "name": "Create an object_Native demonstration", "C++": "#include <iostream>\n#include <map>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nclass FixedMap : private T\n{\n    \n    \n    \n    \n    \n    T m_defaultValues;\n    \npublic:\n    FixedMap(T map)\n    : T(map), m_defaultValues(move(map)){}\n    \n    \n    using T::cbegin;\n    using T::cend;\n    using T::empty;\n    using T::find;\n    using T::size;\n\n    \n    using T::at;\n    using T::begin;\n    using T::end;\n    \n    \n    \n    auto& operator[](typename T::key_type&& key)\n    {\n        \n        return this->at(forward<typename T::key_type>(key));\n    }\n    \n    \n    \n    void erase(typename T::key_type&& key)\n    {\n        T::operator[](key) = m_defaultValues.at(key);\n    }\n\n    \n    void clear()\n    {\n        \n        T::operator=(m_defaultValues);\n    }\n    \n};\n\n\nauto PrintMap = [](const auto &map)\n{\n    for(auto &[key, value] : map)\n    {\n        cout << \"{\" << key << \" : \" << value << \"} \";\n    }\n    cout << \"\\n\\n\";\n};\n\nint main(void) \n{\n    \n    cout << \"Map intialized with values\\n\";\n    FixedMap<map<string, int>> fixedMap ({\n        {\"a\", 1},\n        {\"b\", 2}});\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values of the keys\\n\";\n    fixedMap[\"a\"] = 55;\n    fixedMap[\"b\"] = 56;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset the 'a' key\\n\";\n    fixedMap.erase(\"a\");\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values the again\\n\";\n    fixedMap[\"a\"] = 88;\n    fixedMap[\"b\"] = 99;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset all keys\\n\";\n    fixedMap.clear();\n    PrintMap(fixedMap);\n  \n    try\n    {\n        \n        cout << \"Try to add a new key\\n\";\n        fixedMap[\"newKey\"] = 99;\n    }\n    catch (exception &ex)\n    {\n        cout << \"error: \" << ex.what();\n    }\n}\n", "Java": "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\npublic class ImmutableMap {\n\n    public static void main(String[] args) {\n        Map<String,Integer> hashMap = getImmutableMap();\n        try {\n            hashMap.put(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put new value.\");\n        }\n        try {\n            hashMap.clear();\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to clear map.\");\n        }\n        try {\n            hashMap.putIfAbsent(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put if absent.\");\n        }\n        \n        for ( String key : hashMap.keySet() ) {\n            System.out.printf(\"key = %s, value = %s%n\", key, hashMap.get(key));\n        }\n    }\n    \n    private static Map<String,Integer> getImmutableMap() {\n        Map<String,Integer> hashMap = new HashMap<>();\n        hashMap.put(\"Key 1\", 34);\n        hashMap.put(\"Key 2\", 105);\n        hashMap.put(\"Key 3\", 144);\n\n        return Collections.unmodifiableMap(hashMap);\n    }\n    \n}\n"}
{"id": 47459, "name": "Factorial primes", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    big_int f = 1;\n    for (int i = 0, n = 1; i < 31; ++n) {\n        f *= n;\n        if (is_probably_prime(f - 1)) {\n            ++i;\n            std::cout << std::setw(2) << i << \": \" << std::setw(3) << n\n                      << \"! - 1 = \" << to_string(f - 1, 40) << '\\n';\n        }\n        if (is_probably_prime(f + 1)) {\n            ++i;\n            std::cout << std::setw(2) << i << \": \" << std::setw(3) << n\n                      << \"! + 1 = \" << to_string(f + 1, 40) << '\\n';\n        }\n    }\n}\n", "Java": "public class MainApp {\n    public static void main(String[] args) {\n        int countOfPrimes = 0;\n        final int targetCountOfPrimes = 10;\n        long f = 1;\n        while (countOfPrimes < targetCountOfPrimes) {\n            long factorialNum = getFactorial(f);\n            boolean primePlus = isPrime(factorialNum + 1);\n            boolean primeMinus = isPrime(factorialNum - 1);\n            if (primeMinus) {\n                countOfPrimes++;\n                System.out.println(countOfPrimes + \": \" + factorialNum + \"! - 1 = \" + (factorialNum - 1));\n\n            }\n            if (primePlus  && f > 1) {\n                countOfPrimes++;\n                System.out.println(countOfPrimes + \": \" + factorialNum + \"! + 1 = \" + (factorialNum + 1));\n            }\n            f++;\n        }\n    }\n\n    private static long getFactorial(long f) {\n        long factorial = 1;\n        for (long i = 1; i < f; i++) {\n            factorial *= i;\n        }\n        return factorial;\n    }\n\n    private static boolean isPrime(long num) {\n        if (num < 2) {return false;}\n        for (long i = 2; i < num; i++) {\n            if (num % i == 0) {return false;}\n        }\n        return true;\n    }\n}\n"}
{"id": 47460, "name": "Arithmetic evaluation", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n"}
{"id": 47461, "name": "Arithmetic evaluation", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n"}
{"id": 47462, "name": "Arithmetic evaluation", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n"}
{"id": 47463, "name": "Special variables", "C++": "#include <iostream>\n\nstruct SpecialVariables\n{\n    int i = 0;\n\n    SpecialVariables& operator++()\n    {\n        \n        \n        \n        this->i++;  \n\n        \n        return *this;\n    }\n\n};\n\nint main()\n{\n    SpecialVariables sv;\n    auto sv2 = ++sv;     \n    std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}\n", "Java": "import java.util.Arrays;\n\npublic class SpecialVariables {\n\n    public static void main(String[] args) {\n\n        \n        \n        System.out.println(Arrays.toString(args));\n\n        \n        \n        System.out.println(SpecialVariables.class);\n\n\n        \n\n        \n        System.out.println(System.getenv());\n\n        \n        \n        System.out.println(System.getProperties());\n\n        \n        \n        System.out.println(Runtime.getRuntime().availableProcessors());\n\n    }\n}\n"}
{"id": 47464, "name": "Special variables", "C++": "#include <iostream>\n\nstruct SpecialVariables\n{\n    int i = 0;\n\n    SpecialVariables& operator++()\n    {\n        \n        \n        \n        this->i++;  \n\n        \n        return *this;\n    }\n\n};\n\nint main()\n{\n    SpecialVariables sv;\n    auto sv2 = ++sv;     \n    std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}\n", "Java": "import java.util.Arrays;\n\npublic class SpecialVariables {\n\n    public static void main(String[] args) {\n\n        \n        \n        System.out.println(Arrays.toString(args));\n\n        \n        \n        System.out.println(SpecialVariables.class);\n\n\n        \n\n        \n        System.out.println(System.getenv());\n\n        \n        \n        System.out.println(System.getProperties());\n\n        \n        \n        System.out.println(Runtime.getRuntime().availableProcessors());\n\n    }\n}\n"}
{"id": 47465, "name": "Execute CopyPasta Language", "C++": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n\n#include <stdlib.h>\n\nusing namespace std;\n\n\nvoid fatal_error(string errtext, char *argv[])\n{\n\tcout << \"%\" << errtext << endl;\n\tcout << \"usage: \" << argv[0] << \" [filename.cp]\" << endl;\n\texit(1);\n}\n\n\n\nstring& ltrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(0, str.find_first_not_of(chars));\n\treturn str;\n}\nstring& rtrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(str.find_last_not_of(chars) + 1);\n\treturn str;\n}\nstring& trim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\treturn ltrim(rtrim(str, chars), chars);\n}\n\nint main(int argc, char *argv[])\n{\n\t\n\tstring fname = \"\";\n\tstring source = \"\";\n\ttry\n\t{\n\t\tfname = argv[1];\n\t\tifstream t(fname);\n\n\t\tt.seekg(0, ios::end);\n\t\tsource.reserve(t.tellg());\n\t\tt.seekg(0, ios::beg);\n\n\t\tsource.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t}\n\tcatch(const exception& e)\n\t{\n\t\tfatal_error(\"error while trying to read from specified file\", argv);\n\t}\n\n\t\n\tstring clipboard = \"\";\n\n\t\n\tint loc = 0;\n\tstring remaining = source;\n\tstring line = \"\";\n\tstring command = \"\";\n\tstringstream ss;\n\twhile(remaining.find(\"\\n\") != string::npos)\n\t{\n\t\t\n\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\tcommand = trim(line);\n\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\n\t\ttry\n\t\t{\n\t\t\tif(line == \"Copy\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tclipboard += line;\n\t\t\t}\n\t\t\telse if(line == \"CopyFile\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tif(line == \"TheF*ckingCode\")\n\t\t\t\t\tclipboard += source;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring filetext = \"\";\n\t\t\t\t\tifstream t(line);\n\n\t\t\t\t\tt.seekg(0, ios::end);\n\t\t\t\t\tfiletext.reserve(t.tellg());\n\t\t\t\t\tt.seekg(0, ios::beg);\n\n\t\t\t\t\tfiletext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t\t\t\t\tclipboard += filetext;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Duplicate\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tint amount = stoi(line);\n\t\t\t\tstring origClipboard = clipboard;\n\t\t\t\tfor(int i = 0; i < amount - 1; i++) {\n\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Pasta!\")\n\t\t\t{\n\t\t\t\tcout << clipboard << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss << (loc + 1);\n\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encounter on line \" + ss.str(), argv);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception& e)\n\t\t{\n\t\t\tss << (loc + 1);\n\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + ss.str(), argv);\n\t\t}\n\n\t\t\n\t\tloc += 2;\n\t}\n\n\t\n\treturn 0;\n}\n", "Java": "import java.io.File;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class Copypasta\n{\n\t\n\tpublic static void fatal_error(String errtext)\n\t{\n\t\tStackTraceElement[] stack = Thread.currentThread().getStackTrace();\n\t\tStackTraceElement main = stack[stack.length - 1];\n\t\tString mainClass = main.getClassName();\n\t\tSystem.out.println(\"%\" + errtext);\n\t\tSystem.out.println(\"usage: \" + mainClass + \" [filename.cp]\");\n\t\tSystem.exit(1);\n\t}\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tString fname = null;\n\t\tString source = null;\n\t\ttry\n\t\t{\n\t\t\tfname = args[0];\n\t\t\tsource = new String(Files.readAllBytes(new File(fname).toPath()));\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tfatal_error(\"error while trying to read from specified file\");\n\t\t}\n\n\t\t\n\t\tArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split(\"\\n\")));\n\t\t\n\t\t\n\t\tString clipboard = \"\";\n\t\t\n\t\t\n\t\tint loc = 0;\n\t\twhile(loc < lines.size())\n\t\t{\n\t\t\t\n\t\t\tString command = lines.get(loc).trim();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(command.equals(\"Copy\"))\n\t\t\t\t\tclipboard += lines.get(loc + 1);\n\t\t\t\telse if(command.equals(\"CopyFile\"))\n\t\t\t\t{\n\t\t\t\t\tif(lines.get(loc + 1).equals(\"TheF*ckingCode\"))\n\t\t\t\t\t\tclipboard += source;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tString filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));\n\t\t\t\t\t\tclipboard += filetext;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Duplicate\"))\n\t\t\t\t{\n\t\t\t\t\tString origClipboard = clipboard;\n\n\t\t\t\t\tint amount = Integer.parseInt(lines.get(loc + 1)) - 1;\n\t\t\t\t\tfor(int i = 0; i < amount; i++)\n\t\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Pasta!\"))\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(clipboard);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\n\t\t\t\n\t\t\tloc += 2;\n\t\t}\n\t}\n}\n"}
{"id": 47466, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n"}
{"id": 47467, "name": "Special characters", "C++": "std::cout << \"Tür\\n\";\nstd::cout << \"T\\u00FC\\n\";\n", "Java": "& | ^ ~ \n>> << \n>>> \n+ - * / = % \n"}
{"id": 47468, "name": "Special characters", "C++": "std::cout << \"Tür\\n\";\nstd::cout << \"T\\u00FC\\n\";\n", "Java": "& | ^ ~ \n>> << \n>>> \n+ - * / = % \n"}
{"id": 47469, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\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": 47470, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\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": 47471, "name": "Checkpoint synchronization", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\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": 47472, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\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": 47473, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\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": 47474, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\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": 47475, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\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": 47476, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\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": 47477, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\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": 47478, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\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": 47479, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\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": 47480, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\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": 47481, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "Go": "var intStack []int\n"}
{"id": 47482, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\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    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": 47483, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 47484, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\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": 47485, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\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": 47486, "name": "Sorting algorithms_Radix sort", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\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": 47487, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\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": 47488, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\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": 47489, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\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    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": 47490, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\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": 47491, "name": "Singleton", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\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": 47492, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\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": 47493, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\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": 47494, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 47495, "name": "Write entire file", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 47496, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\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": 47497, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\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": 47498, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\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": 47499, "name": "Roots of unity", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\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": 47500, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\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": 47501, "name": "Pell's equation", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\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": 47502, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\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": 47503, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\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": 47504, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\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": 47505, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\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": 47506, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\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": 47507, "name": "Man or boy test", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\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": 47508, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\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": 47509, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\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": 47510, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\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": 47511, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\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": 47512, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 47513, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 47514, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 47515, "name": "Inverted index", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 47516, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 47517, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 47518, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 47519, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 47520, "name": "Descending primes", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 47521, "name": "Sum and product puzzle", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n"}
{"id": 47522, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 47523, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 47524, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 47525, "name": "Include a file", "C#": "\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 47526, "name": "Include a file", "C#": "\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 47527, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n"}
{"id": 47528, "name": "Documentation", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n"}
{"id": 47529, "name": "Problem of Apollonius", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n"}
{"id": 47530, "name": "Chat server", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n"}
{"id": 47531, "name": "FASTA format", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n"}
{"id": 47532, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 47533, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 47534, "name": "Terminal control_Dimensions", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n"}
{"id": 47535, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 47536, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 47537, "name": "Minimum primes", "C#": "using System;\nusing System.Linq;\nusing static System.Console;\n\nclass Program {\n\n  static int nxtPrime(int x) {\n    int j = 2; do {\n        if (x % j == 0) { j = 2; x++; }\n        else j += j < 3 ? 1 : 2;\n    } while (j * j <= x); return x; }\n\n  static void Main(string[] args) {\n    WriteLine(\"working...\");\n    int[] Num1 = new int[]{  5, 45, 23, 21, 67 },\n          Num2 = new int[]{ 43, 22, 78, 46, 38 },\n          Num3 = new int[]{  9, 98, 12, 54, 53 };\n    int n = Num1.Length; int[] Nums = new int[n];\n    for (int i = 0; i < n; i++)\n      Nums[i] = nxtPrime(new int[]{ Num1[i], Num2[i], Num3[i] }.Max());\n    WriteLine(\"The minimum prime numbers of three lists = [{0}]\", string.Join(\",\", Nums));\n    Write(\"done...\"); } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 54, 53}\n    primes := [5]int{}\n    for n := 0; n < 5; n++ {\n        max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])\n        if max % 2 == 0 {\n            max++\n        }\n        for !rcu.IsPrime(max) {\n            max += 2\n        }\n        primes[n] = max\n    }\n    fmt.Println(primes)\n}\n"}
{"id": 47538, "name": "Literals_String", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 47539, "name": "GUI_Maximum window dimensions", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n"}
{"id": 47540, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 47541, "name": "Knapsack problem_Unbounded", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n"}
{"id": 47542, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 47543, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 47544, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 47545, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n"}
{"id": 47546, "name": "Type detection", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n"}
{"id": 47547, "name": "Maximum triangle path sum", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 47548, "name": "Terminal control_Cursor movement", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc main() {\n    tput(\"clear\") \n    tput(\"cup\", \"6\", \"3\") \n    time.Sleep(1 * time.Second)\n    tput(\"cub1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuf1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuu1\") \n    time.Sleep(1 * time.Second)\n    \n    tput(\"cud\", \"1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cr\") \n    time.Sleep(1 * time.Second)\n    \n    var h, w int\n    cmd := exec.Command(\"stty\", \"size\")\n    cmd.Stdin = os.Stdin\n    d, _ := cmd.Output()\n    fmt.Sscan(string(d), &h, &w)\n    \n    tput(\"hpa\", strconv.Itoa(w-1))\n    time.Sleep(2 * time.Second)\n    \n    tput(\"home\")\n    time.Sleep(2 * time.Second)\n    \n    tput(\"cup\", strconv.Itoa(h-1), strconv.Itoa(w-1))\n    time.Sleep(3 * time.Second)\n}\n\nfunc tput(args ...string) error {\n    cmd := exec.Command(\"tput\", args...)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n"}
{"id": 47549, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 47550, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 47551, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 47552, "name": "UTF-8 encode and decode", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n"}
{"id": 47553, "name": "Magic squares of doubly even order", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 47554, "name": "Same fringe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n"}
{"id": 47555, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n"}
{"id": 47556, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n"}
{"id": 47557, "name": "Peaceful chess queen armies", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n"}
{"id": 47558, "name": "Loops_Infinite", "C#": "while (true)\n{\n    Console.WriteLine(\"SPAM\");\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 47559, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 47560, "name": "Sum of first n cubes", "C#": "using System; using static System.Console;\nclass Program { static void Main(string[] args) {\n    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)\n      Write(\"{0,-7}{1}\",s, (i+=i==3?-4:1)==0?\"\\n\":\" \"); } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n"}
{"id": 47561, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 47562, "name": "XML validation", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 47563, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 47564, "name": "Brace expansion", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 47565, "name": "GUI component interaction", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 47566, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 47567, "name": "Addition chains", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n"}
{"id": 47568, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 47569, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 47570, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 47571, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 47572, "name": "The sieve of Sundaram", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nfunc sos(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        p := 2*i + 3\n        s := (p*p - 3) / 2\n        for j := s; j < k; j += p {\n            marked[j] = true\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\n\nfunc soe(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        if !marked[i] {\n            p := 2*i + 3\n            s := (p*p - 3) / 2\n            for j := s; j < k; j += p {\n                marked[j] = true\n            }\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\nfunc main() {\n    const limit = int(16e6) \n    start := time.Now()\n    primes := sos(limit)\n    elapsed := int(time.Since(start).Milliseconds())\n    climit := rcu.Commatize(limit)\n    celapsed := rcu.Commatize(elapsed)\n    million := rcu.Commatize(1e6)\n    millionth := rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"Using the Sieve of Sundaram generated primes up to %s in %s ms.\\n\\n\", climit, celapsed)\n    fmt.Println(\"First 100 odd primes generated by the Sieve of Sundaram:\")\n    for i, p := range primes[0:100] {\n        fmt.Printf(\"%3d \", p)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThe %s Sundaram prime is %s\\n\", million, millionth)\n\n    start = time.Now()\n    primes = soe(limit)\n    elapsed = int(time.Since(start).Milliseconds())\n    celapsed = rcu.Commatize(elapsed)\n    millionth = rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"\\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\\n\", celapsed)\n    fmt.Printf(\"\\nAs a check, the %s Sundaram prime would again have been %s\\n\", million, millionth)\n}\n"}
{"id": 47573, "name": "Chemical calculator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n"}
{"id": 47574, "name": "Active Directory_Connect", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n"}
{"id": 47575, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n"}
{"id": 47576, "name": "Zebra puzzle", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"log\"\n        \"strings\"\n)\n\n\n\ntype HouseSet [5]*House\ntype House struct {\n        n Nationality\n        c Colour\n        a Animal\n        d Drink\n        s Smoke\n}\ntype Nationality int8\ntype Colour int8\ntype Animal int8\ntype Drink int8\ntype Smoke int8\n\n\n\nconst (\n        English Nationality = iota\n        Swede\n        Dane\n        Norwegian\n        German\n)\nconst (\n        Red Colour = iota\n        Green\n        White\n        Yellow\n        Blue\n)\nconst (\n        Dog Animal = iota\n        Birds\n        Cats\n        Horse\n        Zebra\n)\nconst (\n        Tea Drink = iota\n        Coffee\n        Milk\n        Beer\n        Water\n)\nconst (\n        PallMall Smoke = iota\n        Dunhill\n        Blend\n        BlueMaster\n        Prince\n)\n\n\n\nvar nationalities = [...]string{\"English\", \"Swede\", \"Dane\", \"Norwegian\", \"German\"}\nvar colours = [...]string{\"red\", \"green\", \"white\", \"yellow\", \"blue\"}\nvar animals = [...]string{\"dog\", \"birds\", \"cats\", \"horse\", \"zebra\"}\nvar drinks = [...]string{\"tea\", \"coffee\", \"milk\", \"beer\", \"water\"}\nvar smokes = [...]string{\"Pall Mall\", \"Dunhill\", \"Blend\", \"Blue Master\", \"Prince\"}\n\nfunc (n Nationality) String() string { return nationalities[n] }\nfunc (c Colour) String() string      { return colours[c] }\nfunc (a Animal) String() string      { return animals[a] }\nfunc (d Drink) String() string       { return drinks[d] }\nfunc (s Smoke) String() string       { return smokes[s] }\nfunc (h House) String() string {\n        return fmt.Sprintf(\"%-9s  %-6s  %-5s  %-6s  %s\", h.n, h.c, h.a, h.d, h.s)\n}\nfunc (hs HouseSet) String() string {\n        lines := make([]string, 0, len(hs))\n        for i, h := range hs {\n                s := fmt.Sprintf(\"%d  %s\", i, h)\n                lines = append(lines, s)\n        }\n        return strings.Join(lines, \"\\n\")\n}\n\n\n\nfunc simpleBruteForce() (int, HouseSet) {\n        var v []House\n        for n := range nationalities {\n                for c := range colours {\n                        for a := range animals {\n                                for d := range drinks {\n                                        for s := range smokes {\n                                                h := House{\n                                                        n: Nationality(n),\n                                                        c: Colour(c),\n                                                        a: Animal(a),\n                                                        d: Drink(d),\n                                                        s: Smoke(s),\n                                                }\n                                                if !h.Valid() {\n                                                        continue\n                                                }\n                                                v = append(v, h)\n                                        }\n                                }\n                        }\n                }\n        }\n        n := len(v)\n        log.Println(\"Generated\", n, \"valid houses\")\n\n        combos := 0\n        first := 0\n        valid := 0\n        var validSet HouseSet\n        for a := 0; a < n; a++ {\n                if v[a].n != Norwegian { \n                        continue\n                }\n                for b := 0; b < n; b++ {\n                        if b == a {\n                                continue\n                        }\n                        if v[b].anyDups(&v[a]) {\n                                continue\n                        }\n                        for c := 0; c < n; c++ {\n                                if c == b || c == a {\n                                        continue\n                                }\n                                if v[c].d != Milk { \n                                        continue\n                                }\n                                if v[c].anyDups(&v[b], &v[a]) {\n                                        continue\n                                }\n                                for d := 0; d < n; d++ {\n                                        if d == c || d == b || d == a {\n                                                continue\n                                        }\n                                        if v[d].anyDups(&v[c], &v[b], &v[a]) {\n                                                continue\n                                        }\n                                        for e := 0; e < n; e++ {\n                                                if e == d || e == c || e == b || e == a {\n                                                        continue\n                                                }\n                                                if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {\n                                                        continue\n                                                }\n                                                combos++\n                                                set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}\n                                                if set.Valid() {\n                                                        valid++\n                                                        if valid == 1 {\n                                                                first = combos\n                                                        }\n                                                        validSet = set\n                                                        \n                                                }\n                                        }\n                                }\n                        }\n                }\n        }\n        log.Println(\"Tested\", first, \"different combinations of valid houses before finding solution\")\n        log.Println(\"Tested\", combos, \"different combinations of valid houses in total\")\n        return valid, validSet\n}\n\n\nfunc (h *House) anyDups(list ...*House) bool {\n        for _, b := range list {\n                if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {\n                        return true\n                }\n        }\n        return false\n}\n\nfunc (h *House) Valid() bool {\n        \n        if h.n == English && h.c != Red || h.n != English && h.c == Red {\n                return false\n        }\n        \n        if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {\n                return false\n        }\n        \n        if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {\n                return false\n        }\n        \n        if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {\n                return false\n        }\n        \n        if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {\n                return false\n        }\n        \n        if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {\n                return false\n        }\n        \n        if h.a == Cats && h.s == Blend {\n                return false\n        }\n        \n        if h.a == Horse && h.s == Dunhill {\n                return false\n        }\n        \n        if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {\n                return false\n        }\n        \n        if h.n == German && h.s != Prince || h.n != German && h.s == Prince {\n                return false\n        }\n        \n        if h.n == Norwegian && h.c == Blue {\n                return false\n        }\n        \n        if h.d == Water && h.s == Blend {\n                return false\n        }\n        return true\n}\n\nfunc (hs *HouseSet) Valid() bool {\n        ni := make(map[Nationality]int, 5)\n        ci := make(map[Colour]int, 5)\n        ai := make(map[Animal]int, 5)\n        di := make(map[Drink]int, 5)\n        si := make(map[Smoke]int, 5)\n        for i, h := range hs {\n                ni[h.n] = i\n                ci[h.c] = i\n                ai[h.a] = i\n                di[h.d] = i\n                si[h.s] = i\n        }\n        \n        if ci[Green]+1 != ci[White] {\n                return false\n        }\n        \n        if dist(ai[Cats], si[Blend]) != 1 {\n                return false\n        }\n        \n        if dist(ai[Horse], si[Dunhill]) != 1 {\n                return false\n        }\n        \n        if dist(ni[Norwegian], ci[Blue]) != 1 {\n                return false\n        }\n        \n        if dist(di[Water], si[Blend]) != 1 {\n                return false\n        }\n\n        \n        if hs[2].d != Milk {\n                return false\n        }\n        \n        if hs[0].n != Norwegian {\n                return false\n        }\n        return true\n}\n\nfunc dist(a, b int) int {\n        if a > b {\n                return a - b\n        }\n        return b - a\n}\n\nfunc main() {\n        log.SetFlags(0)\n        n, sol := simpleBruteForce()\n        fmt.Println(n, \"solution found\")\n        fmt.Println(sol)\n}\n"}
{"id": 47577, "name": "Rosetta Code_Find unimplemented tasks", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n"}
{"id": 47578, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 47579, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 47580, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 47581, "name": "Sokoban", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n"}
{"id": 47582, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 47583, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 47584, "name": "Practical numbers", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n"}
{"id": 47585, "name": "Consecutive primes with ascending or descending differences", "C#": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        const int mil = (int)1e6;\n        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n        {\n            int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n            var desc = new string[] { \"A\", \"\", \"De\" };\n            int[] mx = new int[] { 0, 0, 0 },\n                  bi = new int[] { 0, 0, 0 },\n                   c = new int[] { 2, 2, 2 };\n            WriteLine(\"For primes up to {0:n0}:\", lmt);\n            var pr = PG.Primes(lmt).ToArray();\n            for (int i = 0; i < pr.Length; i++)\n            {\n                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n                if (ld == d)\n                    c[2 - d]++;\n                else\n                {\n                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n                    c[d] = 2;\n                }\n                ld = d; lg = ng;\n            }\n            for (int r = 0; r <= 2; r += 2)\n            {\n                Write(\"{0}scending, found run of {1} consecutive primes:\\n  {2} \",\n                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n                    Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n            }\n        }\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<TG> Primes(int lim)\n    {\n        bool[] flags = new bool[lim + 1];\n        int j = 3, lj = 2;\n        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n            }\n        for (; j <= lim; j += 2)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n            }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n    pd := 0\n    longSeqs := [][]int{{2}}\n    currSeq := []int{2}\n    for i := 1; i < len(primes); i++ {\n        d := primes[i] - primes[i-1]\n        if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n            if len(currSeq) > len(longSeqs[0]) {\n                longSeqs = [][]int{currSeq}\n            } else if len(currSeq) == len(longSeqs[0]) {\n                longSeqs = append(longSeqs, currSeq)\n            }\n            currSeq = []int{primes[i-1], primes[i]}\n        } else {\n            currSeq = append(currSeq, primes[i])\n        }\n        pd = d\n    }\n    if len(currSeq) > len(longSeqs[0]) {\n        longSeqs = [][]int{currSeq}\n    } else if len(currSeq) == len(longSeqs[0]) {\n        longSeqs = append(longSeqs, currSeq)\n    }\n    fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n    for _, ls := range longSeqs {\n        var diffs []int\n        for i := 1; i < len(ls); i++ {\n            diffs = append(diffs, ls[i]-ls[i-1])\n        }\n        for i := 0; i < len(ls)-1; i++ {\n            fmt.Print(ls[i], \" (\", diffs[i], \") \")\n        }\n        fmt.Println(ls[len(ls)-1])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    fmt.Println(\"For primes < 1 million:\\n\")\n    for _, dir := range []string{\"ascending\", \"descending\"} {\n        longestSeq(dir)\n    }\n}\n"}
{"id": 47586, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 47587, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 47588, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 47589, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 47590, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 47591, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 47592, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 47593, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 47594, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 47595, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 47596, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 47597, "name": "Word search", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n"}
{"id": 47598, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 47599, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 47600, "name": "Object serialization", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 47601, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 47602, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 47603, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 47604, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 47605, "name": "Zumkeller numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 47606, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 47607, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 47608, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 47609, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 47610, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 47611, "name": "Halt and catch fire", "C#": "int a=0,b=1/a;\n", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n"}
{"id": 47612, "name": "Markov chain text generator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 47613, "name": "Markov chain text generator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 47614, "name": "Dijkstra's algorithm", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 47615, "name": "Geometric algebra", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n"}
{"id": 47616, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 47617, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 47618, "name": "Associative array_Iteration", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 47619, "name": "Define a primitive data type", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n"}
{"id": 47620, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 47621, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 47622, "name": "Hash join", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 47623, "name": "Odd squarefree semiprimes", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n"}
{"id": 47624, "name": "Odd squarefree semiprimes", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n"}
{"id": 47625, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 47626, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 47627, "name": "Respond to an unknown method call", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n"}
{"id": 47628, "name": "Latin Squares in reduced form", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n"}
{"id": 47629, "name": "Closest-pair problem", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n"}
{"id": 47630, "name": "Address of a variable", "C#": "int i = 5;\nint* p = &i;\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n"}
{"id": 47631, "name": "Inheritance_Single", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 47632, "name": "Associative array_Creation", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 47633, "name": "Color wheel", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n"}
{"id": 47634, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 47635, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 47636, "name": "Square root by hand", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 47637, "name": "Square root by hand", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 47638, "name": "Pandigital prime", "C#": "using System;\n \nclass Program {\n  \n \n  \n  \n \n  static void fun(char sp) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    \n    \n    \n \n    for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {\n \n      \n      \n      \n      var s = x.ToString();\n      for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;\n \n      \n      \n      if (x % 3 == 0) continue;\n      for (int i = 1; i * i < x; ) {\n        if (x % (i += 4) == 0) goto nxt;\n        if (x % (i += 2) == 0) goto nxt;\n      }\n      sw.Stop(); Console.WriteLine(\"{0}..7: {1,10:n0} {2} μs\", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;\n      nxt: ;\n    }\n  }\n\nstatic void Main(string[] args) {\n    fun('1');\n    fun('0');\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\n\nfunc permutations(input []int) [][]int {\n    perms := [][]int{input}\n    a := make([]int, len(input))\n    copy(a, input)\n    var n = len(input) - 1\n    for c := 1; c < factorial(n+1); c++ {\n        i := n - 1\n        j := n\n        for a[i] > a[i+1] {\n            i--\n        }\n        for a[j] < a[i] {\n            j--\n        }\n        a[i], a[j] = a[j], a[i]\n        j = n\n        i += 1\n        for i < j {\n            a[i], a[j] = a[j], a[i]\n            i++\n            j--\n        }\n        b := make([]int, len(input))\n        copy(b, a)\n        perms = append(perms, b)\n    }\n    return perms\n}\n\nfunc main() {\nouter:\n    for _, start := range []int{1, 0} {\n        fmt.Printf(\"The largest pandigital decimal prime which uses all the digits %d..n once is:\\n\", start)\n        for _, n := range []int{7, 4} {\n            m := n + 1 - start\n            list := make([]int, m)\n            for i := 0; i < m; i++ {\n                list[i] = i + start\n            }\n            perms := permutations(list)\n            for i := len(perms) - 1; i >= 0; i-- {\n                le := len(perms[i])\n                if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {\n                    continue\n                }\n                p := 0\n                pow := 1\n                for j := le - 1; j >= 0; j-- {\n                    p += perms[i][j] * pow\n                    pow *= 10\n                }\n                if rcu.IsPrime(p) {\n                    fmt.Println(rcu.Commatize(p) + \"\\n\")\n                    continue outer\n                }\n            }\n        }\n    }\n}\n"}
{"id": 47639, "name": "Pandigital prime", "C#": "using System;\n \nclass Program {\n  \n \n  \n  \n \n  static void fun(char sp) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    \n    \n    \n \n    for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {\n \n      \n      \n      \n      var s = x.ToString();\n      for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;\n \n      \n      \n      if (x % 3 == 0) continue;\n      for (int i = 1; i * i < x; ) {\n        if (x % (i += 4) == 0) goto nxt;\n        if (x % (i += 2) == 0) goto nxt;\n      }\n      sw.Stop(); Console.WriteLine(\"{0}..7: {1,10:n0} {2} μs\", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;\n      nxt: ;\n    }\n  }\n\nstatic void Main(string[] args) {\n    fun('1');\n    fun('0');\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\n\nfunc permutations(input []int) [][]int {\n    perms := [][]int{input}\n    a := make([]int, len(input))\n    copy(a, input)\n    var n = len(input) - 1\n    for c := 1; c < factorial(n+1); c++ {\n        i := n - 1\n        j := n\n        for a[i] > a[i+1] {\n            i--\n        }\n        for a[j] < a[i] {\n            j--\n        }\n        a[i], a[j] = a[j], a[i]\n        j = n\n        i += 1\n        for i < j {\n            a[i], a[j] = a[j], a[i]\n            i++\n            j--\n        }\n        b := make([]int, len(input))\n        copy(b, a)\n        perms = append(perms, b)\n    }\n    return perms\n}\n\nfunc main() {\nouter:\n    for _, start := range []int{1, 0} {\n        fmt.Printf(\"The largest pandigital decimal prime which uses all the digits %d..n once is:\\n\", start)\n        for _, n := range []int{7, 4} {\n            m := n + 1 - start\n            list := make([]int, m)\n            for i := 0; i < m; i++ {\n                list[i] = i + start\n            }\n            perms := permutations(list)\n            for i := len(perms) - 1; i >= 0; i-- {\n                le := len(perms[i])\n                if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {\n                    continue\n                }\n                p := 0\n                pow := 1\n                for j := le - 1; j >= 0; j-- {\n                    p += perms[i][j] * pow\n                    pow *= 10\n                }\n                if rcu.IsPrime(p) {\n                    fmt.Println(rcu.Commatize(p) + \"\\n\")\n                    continue outer\n                }\n            }\n        }\n    }\n}\n"}
{"id": 47640, "name": "Primes with digits in nondecreasing order", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n"}
{"id": 47641, "name": "Primes with digits in nondecreasing order", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n"}
{"id": 47642, "name": "Numbers which are not the sum of distinct squares", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n \nclass Program {\n \n  \n  static bool soms(int n, IEnumerable<int> f) {\n    if (n <= 0) return false;\n    if (f.Contains(n)) return true;\n    switch(n.CompareTo(f.Sum())) {\n      case 1: return false;\n      case 0: return true;\n      case -1:\n        var rf = f.Reverse().Skip(1).ToList();\n        return soms(n - f.Last(), rf) || soms(n, rf);\n    }\n    return false;\n  }\n\n  static void Main() {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>();\n    var sf = \"stopped checking after finding {0} sequential non-gaps after the final gap of {1}\";\n    for (i = 1, g = 1; g >= (i >> 1); i++) {\n      if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i);\n      if (!soms(i, s)) a.Add(g = i);\n    }\n    sw.Stop();\n    Console.WriteLine(\"Numbers which are not the sum of distinct squares:\");\n    Console.WriteLine(string.Join(\", \", a));\n    Console.WriteLine(sf, i - g, g);\n    Console.Write(\"found {0} total in {1} ms\",\n      a.Count, sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc contains(a []int, n int) bool {\n    for _, e := range a {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\n\nfunc soms(n int, f []int) bool {\n    if n <= 0 {\n        return false\n    }\n    if contains(f, n) {\n        return true\n    }\n    sum := rcu.SumInts(f)\n    if n > sum {\n        return false\n    }\n    if n == sum {\n        return true\n    }\n    rf := make([]int, len(f))\n    copy(rf, f)\n    for i, j := 0, len(rf)-1; i < j; i, j = i+1, j-1 {\n        rf[i], rf[j] = rf[j], rf[i]\n    }\n    rf = rf[1:]\n    return soms(n-f[len(f)-1], rf) || soms(n, rf)\n}\n\nfunc main() {\n    var s, a []int\n    sf := \"\\nStopped checking after finding %d sequential non-gaps after the final gap of %d\\n\"\n    i, g := 1, 1\n    for g >= (i >> 1) {\n        r := int(math.Sqrt(float64(i)))\n        if r*r == i {\n            s = append(s, i)\n        }\n        if !soms(i, s) {\n            g = i\n            a = append(a, g)\n        }\n        i++\n    }\n    fmt.Println(\"Numbers which are not the sum of distinct squares:\")\n    fmt.Println(a)\n    fmt.Printf(sf, i-g, g)\n    fmt.Printf(\"Found %d in total\\n\", len(a))\n}\n\nvar r int\n"}
{"id": 47643, "name": "Primes which contain only one odd digit", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    \n    \n    static List<uint> sieve(uint max, bool ordinary = false)\n    {\n        uint k = ((max - 3) >> 1) + 1,\n           lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;\n        var pl = new List<uint> { };\n        var ic = new bool[k];\n        for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])\n                for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;\n        if (ordinary)\n        {\n            pl.Add(2);\n            for (uint i = 0, j = 3; i < k; i++, j += 2)\n                if (!ic[i]) pl.Add(j);\n        }\n        else\n            for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)\n                if (!ic[i])\n                {\n                    while ((t /= 10) > 0)\n                        if (((t % 10) & 1) == 1) goto skip;\n                    pl.Add(j);\n                skip:;\n                }\n        return pl;\n    }\n\n    static void Main(string[] args)\n    {\n        var pl = sieve((uint)1e9);\n        uint c = 0, l = 10, p = 1;\n        Console.WriteLine(\"List of one-odd-digit primes < 1,000:\");\n        for (int i = 0; pl[i] < 1000; i++)\n            Console.Write(\"{0,3}{1}\", pl[i], i % 9 == 8 ? \"\\n\" : \"  \");\n        string fmt = \"\\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})\";\n        foreach (var itm in pl)\n            if (itm < l) c++;\n            else Console.Write(fmt, c++, p++, l, l *= 10);\n        Console.Write(fmt, c++, p++, l);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc allButOneEven(prime int) bool {\n    digits := rcu.Digits(prime, 10)\n    digits = digits[:len(digits)-1]\n    allEven := true\n    for _, d := range digits {\n        if d&1 == 1 {\n            allEven = false\n            break\n        }\n    }\n    return allEven\n}\n\nfunc main() {\n    const (\n        LIMIT      = 999\n        LIMIT2     = 9999999999\n        MAX_DIGITS = 3\n    )\n    primes := rcu.Primes(LIMIT)\n    var results []int\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            results = append(results, prime)\n        }\n    }\n    fmt.Println(\"Primes under\", rcu.Commatize(LIMIT+1), \"which contain only one odd digit:\")\n    for i, p := range results {\n        fmt.Printf(\"%*s \", MAX_DIGITS, rcu.Commatize(p))\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(results), \"such primes.\\n\")\n\n    primes = rcu.Primes(LIMIT2)\n    count := 0\n    pow := 10\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            count++\n        }\n        if prime > pow {\n            fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n            pow *= 10\n        }\n    }\n    fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n}\n"}
{"id": 47644, "name": "Primes which contain only one odd digit", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    \n    \n    static List<uint> sieve(uint max, bool ordinary = false)\n    {\n        uint k = ((max - 3) >> 1) + 1,\n           lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;\n        var pl = new List<uint> { };\n        var ic = new bool[k];\n        for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])\n                for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;\n        if (ordinary)\n        {\n            pl.Add(2);\n            for (uint i = 0, j = 3; i < k; i++, j += 2)\n                if (!ic[i]) pl.Add(j);\n        }\n        else\n            for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)\n                if (!ic[i])\n                {\n                    while ((t /= 10) > 0)\n                        if (((t % 10) & 1) == 1) goto skip;\n                    pl.Add(j);\n                skip:;\n                }\n        return pl;\n    }\n\n    static void Main(string[] args)\n    {\n        var pl = sieve((uint)1e9);\n        uint c = 0, l = 10, p = 1;\n        Console.WriteLine(\"List of one-odd-digit primes < 1,000:\");\n        for (int i = 0; pl[i] < 1000; i++)\n            Console.Write(\"{0,3}{1}\", pl[i], i % 9 == 8 ? \"\\n\" : \"  \");\n        string fmt = \"\\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})\";\n        foreach (var itm in pl)\n            if (itm < l) c++;\n            else Console.Write(fmt, c++, p++, l, l *= 10);\n        Console.Write(fmt, c++, p++, l);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc allButOneEven(prime int) bool {\n    digits := rcu.Digits(prime, 10)\n    digits = digits[:len(digits)-1]\n    allEven := true\n    for _, d := range digits {\n        if d&1 == 1 {\n            allEven = false\n            break\n        }\n    }\n    return allEven\n}\n\nfunc main() {\n    const (\n        LIMIT      = 999\n        LIMIT2     = 9999999999\n        MAX_DIGITS = 3\n    )\n    primes := rcu.Primes(LIMIT)\n    var results []int\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            results = append(results, prime)\n        }\n    }\n    fmt.Println(\"Primes under\", rcu.Commatize(LIMIT+1), \"which contain only one odd digit:\")\n    for i, p := range results {\n        fmt.Printf(\"%*s \", MAX_DIGITS, rcu.Commatize(p))\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(results), \"such primes.\\n\")\n\n    primes = rcu.Primes(LIMIT2)\n    count := 0\n    pow := 10\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            count++\n        }\n        if prime > pow {\n            fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n            pow *= 10\n        }\n    }\n    fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n}\n"}
{"id": 47645, "name": "Reflection_List properties", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 47646, "name": "Minimal steps down to 1", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class MinimalSteps\n{\n    public static void Main() {\n        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });\n        var lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n        Console.WriteLine();\n\n        subtractors = new [] { 2 };\n        lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n    }\n\n    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {\n        for (int goal = 1; goal <= limit; goal++) {\n            var x = lookup[goal];\n            if (x.param == 0) {\n                Console.WriteLine($\"{goal} cannot be reached with these numbers.\");\n                continue;\n            }\n            Console.Write($\"{goal} takes {x.steps} {(x.steps == 1 ? \"step\" : \"steps\")}: \");\n            for (int n = goal; n > 1; ) {\n                Console.Write($\"{n},{x.op}{x.param}=> \");\n                n = x.op == '/' ? n / x.param : n - x.param;\n                x = lookup[n];\n            }\n            Console.WriteLine(\"1\");\n        }\n    }\n\n    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {\n        var maxSteps = lookup.Max(x => x.steps);\n        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();\n        Console.WriteLine(items.Count == 1\n            ? $\"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}\"\n            : $\"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}\"\n        );\n    }\n\n    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)\n    {\n        var lookup = new (char op, int param, int steps)[goal+1];\n        lookup[1] = ('/', 1, 0);\n        for (int n = 1; n < lookup.Length; n++) {\n            var ln = lookup[n];\n            if (ln.param == 0) continue;\n            for (int d = 0; d < divisors.Length; d++) {\n                int target = n * divisors[d];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);\n            }\n            for (int s = 0; s < subtractors.Length; s++) {\n                int target = n + subtractors[s];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);\n            }\n        }\n        return lookup;\n    }\n\n    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(\", \", source);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n    divs, subs []int\n    mins       [][]string\n)\n\n\nfunc minsteps(n int) {\n    if n == 1 {\n        mins[1] = []string{}\n        return\n    }\n    min := limit\n    var p, q int\n    var op byte\n    for _, div := range divs {\n        if n%div == 0 {\n            d := n / div\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, div, '/'\n            }\n        }\n    }\n    for _, sub := range subs {\n        if d := n - sub; d >= 1 {\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, sub, '-'\n            }\n        }\n    }\n    mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n    mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n    for r := 0; r < 2; r++ {\n        divs = []int{2, 3}\n        if r == 0 {\n            subs = []int{1}\n        } else {\n            subs = []int{2}\n        }\n        mins = make([][]string, limit+1)\n        fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n        fmt.Println(\"  Minimum number of steps to diminish the following numbers down to 1 is:\")\n        for i := 1; i <= limit; i++ {\n            minsteps(i)\n            if i <= 10 {\n                steps := len(mins[i])\n                plural := \"s\"\n                if steps == 1 {\n                    plural = \" \"\n                }\n                fmt.Printf(\"    %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n            }\n        }\n        for _, lim := range []int{2000, 20000, 50000} {\n            max := 0\n            for _, min := range mins[0 : lim+1] {\n                m := len(min)\n                if m > max {\n                    max = m\n                }\n            }\n            var maxs []int\n            for i, min := range mins[0 : lim+1] {\n                if len(min) == max {\n                    maxs = append(maxs, i)\n                }\n            }\n            nums := len(maxs)\n            verb, verb2, plural := \"are\", \"have\", \"s\"\n            if nums == 1 {\n                verb, verb2, plural = \"is\", \"has\", \"\"\n            }\n            fmt.Printf(\"  There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n            fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n            fmt.Println(\"   \", maxs)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 47647, "name": "Align columns", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n"}
{"id": 47648, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 47649, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 47650, "name": "Idoneal numbers", "C#": "using System;\n\nclass Program {\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int a, b, c, i, n, s3, ab; var res = new int[65];\n    for (n = 1, i = 0; n < 1850; n++) {\n      bool found = true;\n      for (a = 1; a < n; a++)\n         for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {\n            if (ab > n) break;\n            for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {\n                if (s3 == n) found = false;\n                if (s3 >= n) break;\n            }\n         }\n      if (found) res[i++] = n;\n    }\n    sw.Stop();\n    Console.WriteLine(\"The 65 known Idoneal numbers:\");\n    for (i = 0; i < res.Length; i++)\n      Console.Write(\"{0,5}{1}\", res[i], i % 13 == 12 ? \"\\n\" : \"\");\n    Console.Write(\"Calculations took {0} ms\", sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "Go": "package main\n\nimport \"rcu\"\n\nfunc isIdoneal(n int) bool {\n    for a := 1; a < n; a++ {\n        for b := a + 1; b < n; b++ {\n            if a*b+a+b > n {\n                break\n            }\n            for c := b + 1; c < n; c++ {\n                sum := a*b + b*c + a*c\n                if sum == n {\n                    return false\n                }\n                if sum > n {\n                    break\n                }\n            }\n        }\n    }\n    return true\n}\n\nfunc main() {\n    var idoneals []int\n    for n := 1; n <= 1850; n++ {\n        if isIdoneal(n) {\n            idoneals = append(idoneals, n)\n        }\n    }\n    rcu.PrintTable(idoneals, 13, 4, false)\n}\n"}
{"id": 47651, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 47652, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 47653, "name": "Dynamic variable names", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n"}
{"id": 47654, "name": "Data Encryption Standard", "C#": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace DES {\n    class Program {\n        \n        static string ByteArrayToString(byte[] ba) {\n            return BitConverter.ToString(ba).Replace(\"-\", \"\");\n        }\n\n        \n        \n        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(messageBytes, 0, messageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] encryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n\n            return encryptedMessageBytes;\n        }\n\n        \n        \n        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] decryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);\n\n            return decryptedMessageBytes;\n        }\n\n        static void Main(string[] args) {\n            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };\n            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };\n\n            byte[] encStr = Encrypt(plainBytes, keyBytes);\n            Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr));\n\n            byte[] decBytes = Decrypt(encStr, keyBytes);\n            Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decBytes));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n"}
{"id": 47655, "name": "Multidimensional Newton-Raphson method", "C#": "using System;\n\nnamespace Rosetta\n{\n    internal interface IFun\n    {\n        double F(int index, Vector x);\n        double df(int index, int derivative, Vector x);\n        double[] weights();\n    }\n\n    class Newton\n    {                \n        internal Vector Do(int size, IFun fun, Vector start)\n        {\n            Vector X = start.Clone();\n            Vector F = new Vector(size);\n            Matrix J = new Matrix(size, size);\n            Vector D;\n            do\n            {\n                for (int i = 0; i < size; i++)\n                    F[i] = fun.F(i, X);\n                for (int i = 0; i < size; i++)\n                    for (int j = 0; j < size; j++)\n                        J[i, j] = fun.df(i, j, X);\n                J.ElimPartial(F);\n                X -= F;\n                \n            } while (F.norm(fun.weights()) > 1e-12);\n            return X;\n        }       \n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\ntype fun = func(vector) float64\ntype funs = []fun\ntype jacobian = []funs\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m1 matrix) sub(m2 matrix) matrix {\n    rows, cols := len(m1), len(m1[0])\n    if rows != len(m2) || cols != len(m2[0]) {\n        panic(\"Matrices cannot be subtracted.\")\n    }\n    result := make(matrix, rows)\n    for i := 0; i < rows; i++ {\n        result[i] = make(vector, cols)\n        for j := 0; j < cols; j++ {\n            result[i][j] = m1[i][j] - m2[i][j]\n        }\n    }\n    return result\n}\n\nfunc (m matrix) transpose() matrix {\n    rows, cols := len(m), len(m[0])\n    trans := make(matrix, cols)\n    for i := 0; i < cols; i++ {\n        trans[i] = make(vector, rows)\n        for j := 0; j < rows; j++ {\n            trans[i][j] = m[j][i]\n        }\n    }\n    return trans\n}\n\nfunc (m matrix) inverse() matrix {\n    le := len(m)\n    for _, v := range m {\n        if len(v) != le {\n            panic(\"Not a square matrix\")\n        }\n    }\n    aug := make(matrix, le)\n    for i := 0; i < le; i++ {\n        aug[i] = make(vector, 2*le)\n        copy(aug[i], m[i])\n        \n        aug[i][i+le] = 1\n    }\n    aug.toReducedRowEchelonForm()\n    inv := make(matrix, le)\n    \n    for i := 0; i < le; i++ {\n        inv[i] = make(vector, le)\n        copy(inv[i], aug[i][le:])\n    }\n    return inv\n}\n\n\nfunc (m matrix) toReducedRowEchelonForm() {\n    lead := 0\n    rowCount, colCount := len(m), len(m[0])\n    for r := 0; r < rowCount; r++ {\n        if colCount <= lead {\n            return\n        }\n        i := r\n\n        for m[i][lead] == 0 {\n            i++\n            if rowCount == i {\n                i = r\n                lead++\n                if colCount == lead {\n                    return\n                }\n            }\n        }\n\n        m[i], m[r] = m[r], m[i]\n        if div := m[r][lead]; div != 0 {\n            for j := 0; j < colCount; j++ {\n                m[r][j] /= div\n            }\n        }\n\n        for k := 0; k < rowCount; k++ {\n            if k != r {\n                mult := m[k][lead]\n                for j := 0; j < colCount; j++ {\n                    m[k][j] -= m[r][j] * mult\n                }\n            }\n        }\n        lead++\n    }\n}\n\nfunc solve(fs funs, jacob jacobian, guesses vector) vector {\n    size := len(fs)\n    var gu1 vector\n    gu2 := make(vector, len(guesses))\n    copy(gu2, guesses)\n    jac := make(matrix, size)\n    for i := 0; i < size; i++ {\n        jac[i] = make(vector, size)\n    }\n    tol := 1e-8\n    maxIter := 12\n    iter := 0\n    for {\n        gu1 = gu2\n        g := matrix{gu1}.transpose()\n        t := make(vector, size)\n        for i := 0; i < size; i++ {\n            t[i] = fs[i](gu1)\n        }\n        f := matrix{t}.transpose()\n        for i := 0; i < size; i++ {\n            for j := 0; j < size; j++ {\n                jac[i][j] = jacob[i][j](gu1)\n            }\n        }\n        g1 := g.sub(jac.inverse().mul(f))\n        gu2 = make(vector, size)\n        for i := 0; i < size; i++ {\n            gu2[i] = g1[i][0]\n        }\n        iter++\n        any := false\n        for i, v := range gu2 {\n            if math.Abs(v)-gu1[i] > tol {\n                any = true\n                break\n            }\n        }\n        if !any || iter >= maxIter {\n            break\n        }\n    }\n    return gu2\n}\n\nfunc main() {\n    \n    f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }\n    f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }\n    fs := funs{f1, f2}\n    jacob := jacobian{\n        funs{\n            func(x vector) float64 { return -2*x[0] + 1 },\n            func(x vector) float64 { return -1 },\n        },\n        funs{\n            func(x vector) float64 { return 5*x[1] - 2*x[0] },\n            func(x vector) float64 { return 1 + 5*x[0] },\n        },\n    }\n    guesses := vector{1.2, 1.2}\n    sol := solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f\\n\", sol[0], sol[1])\n\n    \n\n    fmt.Println()\n    f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }\n    f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }\n    f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }\n    fs = funs{f3, f4, f5}\n    jacob = jacobian{\n        funs{\n            func(x vector) float64 { return 18 * x[0] },\n            func(x vector) float64 { return 72 * x[1] },\n            func(x vector) float64 { return 8 * x[2] },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -4 * x[1] },\n            func(x vector) float64 { return -20 },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -2 * x[1] },\n            func(x vector) float64 { return 2 * x[2] },\n        },\n    }\n    guesses = vector{1, 1, 0}\n    sol = solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f,  z = %.7f\\n\", sol[0], sol[1], sol[2])\n}\n"}
{"id": 47656, "name": "Multidimensional Newton-Raphson method", "C#": "using System;\n\nnamespace Rosetta\n{\n    internal interface IFun\n    {\n        double F(int index, Vector x);\n        double df(int index, int derivative, Vector x);\n        double[] weights();\n    }\n\n    class Newton\n    {                \n        internal Vector Do(int size, IFun fun, Vector start)\n        {\n            Vector X = start.Clone();\n            Vector F = new Vector(size);\n            Matrix J = new Matrix(size, size);\n            Vector D;\n            do\n            {\n                for (int i = 0; i < size; i++)\n                    F[i] = fun.F(i, X);\n                for (int i = 0; i < size; i++)\n                    for (int j = 0; j < size; j++)\n                        J[i, j] = fun.df(i, j, X);\n                J.ElimPartial(F);\n                X -= F;\n                \n            } while (F.norm(fun.weights()) > 1e-12);\n            return X;\n        }       \n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\ntype fun = func(vector) float64\ntype funs = []fun\ntype jacobian = []funs\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m1 matrix) sub(m2 matrix) matrix {\n    rows, cols := len(m1), len(m1[0])\n    if rows != len(m2) || cols != len(m2[0]) {\n        panic(\"Matrices cannot be subtracted.\")\n    }\n    result := make(matrix, rows)\n    for i := 0; i < rows; i++ {\n        result[i] = make(vector, cols)\n        for j := 0; j < cols; j++ {\n            result[i][j] = m1[i][j] - m2[i][j]\n        }\n    }\n    return result\n}\n\nfunc (m matrix) transpose() matrix {\n    rows, cols := len(m), len(m[0])\n    trans := make(matrix, cols)\n    for i := 0; i < cols; i++ {\n        trans[i] = make(vector, rows)\n        for j := 0; j < rows; j++ {\n            trans[i][j] = m[j][i]\n        }\n    }\n    return trans\n}\n\nfunc (m matrix) inverse() matrix {\n    le := len(m)\n    for _, v := range m {\n        if len(v) != le {\n            panic(\"Not a square matrix\")\n        }\n    }\n    aug := make(matrix, le)\n    for i := 0; i < le; i++ {\n        aug[i] = make(vector, 2*le)\n        copy(aug[i], m[i])\n        \n        aug[i][i+le] = 1\n    }\n    aug.toReducedRowEchelonForm()\n    inv := make(matrix, le)\n    \n    for i := 0; i < le; i++ {\n        inv[i] = make(vector, le)\n        copy(inv[i], aug[i][le:])\n    }\n    return inv\n}\n\n\nfunc (m matrix) toReducedRowEchelonForm() {\n    lead := 0\n    rowCount, colCount := len(m), len(m[0])\n    for r := 0; r < rowCount; r++ {\n        if colCount <= lead {\n            return\n        }\n        i := r\n\n        for m[i][lead] == 0 {\n            i++\n            if rowCount == i {\n                i = r\n                lead++\n                if colCount == lead {\n                    return\n                }\n            }\n        }\n\n        m[i], m[r] = m[r], m[i]\n        if div := m[r][lead]; div != 0 {\n            for j := 0; j < colCount; j++ {\n                m[r][j] /= div\n            }\n        }\n\n        for k := 0; k < rowCount; k++ {\n            if k != r {\n                mult := m[k][lead]\n                for j := 0; j < colCount; j++ {\n                    m[k][j] -= m[r][j] * mult\n                }\n            }\n        }\n        lead++\n    }\n}\n\nfunc solve(fs funs, jacob jacobian, guesses vector) vector {\n    size := len(fs)\n    var gu1 vector\n    gu2 := make(vector, len(guesses))\n    copy(gu2, guesses)\n    jac := make(matrix, size)\n    for i := 0; i < size; i++ {\n        jac[i] = make(vector, size)\n    }\n    tol := 1e-8\n    maxIter := 12\n    iter := 0\n    for {\n        gu1 = gu2\n        g := matrix{gu1}.transpose()\n        t := make(vector, size)\n        for i := 0; i < size; i++ {\n            t[i] = fs[i](gu1)\n        }\n        f := matrix{t}.transpose()\n        for i := 0; i < size; i++ {\n            for j := 0; j < size; j++ {\n                jac[i][j] = jacob[i][j](gu1)\n            }\n        }\n        g1 := g.sub(jac.inverse().mul(f))\n        gu2 = make(vector, size)\n        for i := 0; i < size; i++ {\n            gu2[i] = g1[i][0]\n        }\n        iter++\n        any := false\n        for i, v := range gu2 {\n            if math.Abs(v)-gu1[i] > tol {\n                any = true\n                break\n            }\n        }\n        if !any || iter >= maxIter {\n            break\n        }\n    }\n    return gu2\n}\n\nfunc main() {\n    \n    f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }\n    f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }\n    fs := funs{f1, f2}\n    jacob := jacobian{\n        funs{\n            func(x vector) float64 { return -2*x[0] + 1 },\n            func(x vector) float64 { return -1 },\n        },\n        funs{\n            func(x vector) float64 { return 5*x[1] - 2*x[0] },\n            func(x vector) float64 { return 1 + 5*x[0] },\n        },\n    }\n    guesses := vector{1.2, 1.2}\n    sol := solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f\\n\", sol[0], sol[1])\n\n    \n\n    fmt.Println()\n    f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }\n    f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }\n    f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }\n    fs = funs{f3, f4, f5}\n    jacob = jacobian{\n        funs{\n            func(x vector) float64 { return 18 * x[0] },\n            func(x vector) float64 { return 72 * x[1] },\n            func(x vector) float64 { return 8 * x[2] },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -4 * x[1] },\n            func(x vector) float64 { return -20 },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -2 * x[1] },\n            func(x vector) float64 { return 2 * x[2] },\n        },\n    }\n    guesses = vector{1, 1, 0}\n    sol = solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f,  z = %.7f\\n\", sol[0], sol[1], sol[2])\n}\n"}
{"id": 47657, "name": "Multidimensional Newton-Raphson method", "C#": "using System;\n\nnamespace Rosetta\n{\n    internal interface IFun\n    {\n        double F(int index, Vector x);\n        double df(int index, int derivative, Vector x);\n        double[] weights();\n    }\n\n    class Newton\n    {                \n        internal Vector Do(int size, IFun fun, Vector start)\n        {\n            Vector X = start.Clone();\n            Vector F = new Vector(size);\n            Matrix J = new Matrix(size, size);\n            Vector D;\n            do\n            {\n                for (int i = 0; i < size; i++)\n                    F[i] = fun.F(i, X);\n                for (int i = 0; i < size; i++)\n                    for (int j = 0; j < size; j++)\n                        J[i, j] = fun.df(i, j, X);\n                J.ElimPartial(F);\n                X -= F;\n                \n            } while (F.norm(fun.weights()) > 1e-12);\n            return X;\n        }       \n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\ntype fun = func(vector) float64\ntype funs = []fun\ntype jacobian = []funs\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m1 matrix) sub(m2 matrix) matrix {\n    rows, cols := len(m1), len(m1[0])\n    if rows != len(m2) || cols != len(m2[0]) {\n        panic(\"Matrices cannot be subtracted.\")\n    }\n    result := make(matrix, rows)\n    for i := 0; i < rows; i++ {\n        result[i] = make(vector, cols)\n        for j := 0; j < cols; j++ {\n            result[i][j] = m1[i][j] - m2[i][j]\n        }\n    }\n    return result\n}\n\nfunc (m matrix) transpose() matrix {\n    rows, cols := len(m), len(m[0])\n    trans := make(matrix, cols)\n    for i := 0; i < cols; i++ {\n        trans[i] = make(vector, rows)\n        for j := 0; j < rows; j++ {\n            trans[i][j] = m[j][i]\n        }\n    }\n    return trans\n}\n\nfunc (m matrix) inverse() matrix {\n    le := len(m)\n    for _, v := range m {\n        if len(v) != le {\n            panic(\"Not a square matrix\")\n        }\n    }\n    aug := make(matrix, le)\n    for i := 0; i < le; i++ {\n        aug[i] = make(vector, 2*le)\n        copy(aug[i], m[i])\n        \n        aug[i][i+le] = 1\n    }\n    aug.toReducedRowEchelonForm()\n    inv := make(matrix, le)\n    \n    for i := 0; i < le; i++ {\n        inv[i] = make(vector, le)\n        copy(inv[i], aug[i][le:])\n    }\n    return inv\n}\n\n\nfunc (m matrix) toReducedRowEchelonForm() {\n    lead := 0\n    rowCount, colCount := len(m), len(m[0])\n    for r := 0; r < rowCount; r++ {\n        if colCount <= lead {\n            return\n        }\n        i := r\n\n        for m[i][lead] == 0 {\n            i++\n            if rowCount == i {\n                i = r\n                lead++\n                if colCount == lead {\n                    return\n                }\n            }\n        }\n\n        m[i], m[r] = m[r], m[i]\n        if div := m[r][lead]; div != 0 {\n            for j := 0; j < colCount; j++ {\n                m[r][j] /= div\n            }\n        }\n\n        for k := 0; k < rowCount; k++ {\n            if k != r {\n                mult := m[k][lead]\n                for j := 0; j < colCount; j++ {\n                    m[k][j] -= m[r][j] * mult\n                }\n            }\n        }\n        lead++\n    }\n}\n\nfunc solve(fs funs, jacob jacobian, guesses vector) vector {\n    size := len(fs)\n    var gu1 vector\n    gu2 := make(vector, len(guesses))\n    copy(gu2, guesses)\n    jac := make(matrix, size)\n    for i := 0; i < size; i++ {\n        jac[i] = make(vector, size)\n    }\n    tol := 1e-8\n    maxIter := 12\n    iter := 0\n    for {\n        gu1 = gu2\n        g := matrix{gu1}.transpose()\n        t := make(vector, size)\n        for i := 0; i < size; i++ {\n            t[i] = fs[i](gu1)\n        }\n        f := matrix{t}.transpose()\n        for i := 0; i < size; i++ {\n            for j := 0; j < size; j++ {\n                jac[i][j] = jacob[i][j](gu1)\n            }\n        }\n        g1 := g.sub(jac.inverse().mul(f))\n        gu2 = make(vector, size)\n        for i := 0; i < size; i++ {\n            gu2[i] = g1[i][0]\n        }\n        iter++\n        any := false\n        for i, v := range gu2 {\n            if math.Abs(v)-gu1[i] > tol {\n                any = true\n                break\n            }\n        }\n        if !any || iter >= maxIter {\n            break\n        }\n    }\n    return gu2\n}\n\nfunc main() {\n    \n    f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }\n    f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }\n    fs := funs{f1, f2}\n    jacob := jacobian{\n        funs{\n            func(x vector) float64 { return -2*x[0] + 1 },\n            func(x vector) float64 { return -1 },\n        },\n        funs{\n            func(x vector) float64 { return 5*x[1] - 2*x[0] },\n            func(x vector) float64 { return 1 + 5*x[0] },\n        },\n    }\n    guesses := vector{1.2, 1.2}\n    sol := solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f\\n\", sol[0], sol[1])\n\n    \n\n    fmt.Println()\n    f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }\n    f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }\n    f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }\n    fs = funs{f3, f4, f5}\n    jacob = jacobian{\n        funs{\n            func(x vector) float64 { return 18 * x[0] },\n            func(x vector) float64 { return 72 * x[1] },\n            func(x vector) float64 { return 8 * x[2] },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -4 * x[1] },\n            func(x vector) float64 { return -20 },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -2 * x[1] },\n            func(x vector) float64 { return 2 * x[2] },\n        },\n    }\n    guesses = vector{1, 1, 0}\n    sol = solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f,  z = %.7f\\n\", sol[0], sol[1], sol[2])\n}\n"}
{"id": 47658, "name": "Fibonacci matrix-exponentiation", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 47659, "name": "Fibonacci matrix-exponentiation", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 47660, "name": "Largest palindrome product", "C#": "using System;\nclass Program {\n\n  static bool isPal(int n) {\n    int rev = 0, lr = -1, rem;\n    while (n > rev) {\n      n = Math.DivRem(n, 10, out rem);\n      if (lr < 0 && rem == 0) return false;\n      lr = rev; rev = 10 * rev + rem;\n      if (n == rev || n == lr) return true;\n    } return false; }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;\n    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = \"\";\n    y /= 11;\n    if ((y & 1) == 0) y--;\n    if (y % 5 == 0) y -= 2;\n    y *= 11;\n    while (y <= max) {\n      c = 0;\n      y10 = y * 10;\n      z = max9 + a[ld = y % 10];\n      p = y * z;\n      while (p >= bp) {\n        if (isPal(p)) {\n          if (p > bp) bp = p;\n          bs = string.Format(\"{0} x {1} = {2}\", y, z - c, bp);\n        }\n        p -= y10; c += 10;\n      }\n      y += ld == 3 ? 44 : 22;\n    }\n    sw.Stop();\n    Console.Write(\"{0} {1} μs\", bs, sw.Elapsed.TotalMilliseconds * 1000.0);\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(n uint64) uint64 {\n    r := uint64(0)\n    for n > 0 {\n        r = n%10 + r*10\n        n /= 10\n    }\n    return r\n}\n\nfunc main() {\n    pow := uint64(10)\nnextN:\n    for n := 2; n < 10; n++ {\n        low := pow * 9\n        pow *= 10\n        high := pow - 1\n        fmt.Printf(\"Largest palindromic product of two %d-digit integers: \", n)\n        for i := high; i >= low; i-- {\n            j := reverse(i)\n            p := i*pow + j\n            \n            for k := high; k > low; k -= 2 {\n                if k % 10 == 5 {\n                    continue\n                }\n                l := p / k\n                if l > high {\n                    break\n                }\n                if p%k == 0 {\n                    fmt.Printf(\"%d x %d = %d\\n\", k, l, p)\n                    continue nextN\n                }\n            }\n        }\n    }\n}\n"}
{"id": 47661, "name": "Commatizing numbers", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n"}
{"id": 47662, "name": "Arithmetic coding_As a generalized change of radix", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n"}
{"id": 47663, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n"}
{"id": 47664, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n"}
{"id": 47665, "name": "Reflection_List methods", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 47666, "name": "Send an unknown method call", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n"}
{"id": 47667, "name": "Twelve statements", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 47668, "name": "Twelve statements", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 47669, "name": "Add a variable to a class instance at runtime", "C#": "\n\n\n\n\n\n\n\nusing System;\nusing System.Dynamic;\n\nnamespace DynamicClassVariable\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            \n            \n            dynamic sampleObj = new ExpandoObject();\n            \n            sampleObj.bar = 1;\n            Console.WriteLine( \"sampleObj.bar = {0}\", sampleObj.bar );\n\n            \n            \n            \n            \n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n"}
{"id": 47670, "name": "Time-based one-time password algorithm", "C#": "using System;\nusing System.Security.Cryptography;\n\nnamespace RosettaTOTP\n{\n    public class TOTP_SHA1\n    {\n        private byte[] K;\n        public TOTP_SHA1()\n        {\n            GenerateKey();\n        }\n        public void GenerateKey()\n        {\n            using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())\n            {\n                \n                K = new byte[HMACSHA1.Create().HashSize / 8];\n                rng.GetBytes(K);\n            }\n        }\n        public int HOTP(UInt64 C, int digits = 6)\n        {\n            var hmac = HMACSHA1.Create();\n            hmac.Key = K;\n            hmac.ComputeHash(BitConverter.GetBytes(C));\n            return Truncate(hmac.Hash, digits);\n        }\n        public UInt64 CounterNow(int T1 = 30)\n        {\n            var secondsSinceEpoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;\n            return (UInt64)Math.Floor(secondsSinceEpoch / T1);\n        }\n        private int DT(byte[] hmac_result)\n        {\n            int offset = hmac_result[19] & 0xf;\n            int bin_code = (hmac_result[offset] & 0x7f) << 24\n               | (hmac_result[offset + 1] & 0xff) << 16\n               | (hmac_result[offset + 2] & 0xff) << 8\n               | (hmac_result[offset + 3] & 0xff);\n            return bin_code;\n        }\n\n        private int Truncate(byte[] hmac_result, int digits)\n        {\n            var Snum = DT(hmac_result);\n            return Snum % (int)Math.Pow(10, digits);\n        }\n    }\n\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var totp = new TOTP_SHA1();\n            Console.WriteLine(totp.HOTP(totp.CounterNow()));\n        }\n    }\n}\n", "Go": "\n\n\npackage onetime\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"hash\"\n\t\"math\"\n\t\"time\"\n)\n\n\ntype OneTimePassword struct {\n\tDigit    int              \n\tTimeStep time.Duration    \n\tBaseTime time.Time        \n\tHash     func() hash.Hash \n}\n\n\nfunc (otp *OneTimePassword) HOTP(secret []byte, count uint64) uint {\n\ths := otp.hmacSum(secret, count)\n\treturn otp.truncate(hs)\n}\n\nfunc (otp *OneTimePassword) hmacSum(secret []byte, count uint64) []byte {\n\tmac := hmac.New(otp.Hash, secret)\n\tbinary.Write(mac, binary.BigEndian, count)\n\treturn mac.Sum(nil)\n}\n\nfunc (otp *OneTimePassword) truncate(hs []byte) uint {\n\tsbits := dt(hs)\n\tsnum := uint(sbits[3]) | uint(sbits[2])<<8\n\tsnum |= uint(sbits[1])<<16 | uint(sbits[0])<<24\n\treturn snum % uint(math.Pow(10, float64(otp.Digit)))\n}\n\n\n\n\nfunc Simple(digit int) (otp OneTimePassword, err error) {\n\tif digit < 6 {\n\t\terr = errors.New(\"minimum of 6 digits is required for a valid HTOP code\")\n\t\treturn\n\t} else if digit > 9 {\n\t\terr = errors.New(\"HTOP code cannot be longer than 9 digits\")\n\t\treturn\n\t}\n\tconst step = 30 * time.Second\n\totp = OneTimePassword{digit, step, time.Unix(0, 0), sha1.New}\n\treturn\n}\n\n\nfunc (otp *OneTimePassword) TOTP(secret []byte) uint {\n\treturn otp.HOTP(secret, otp.steps(time.Now()))\n}\n\nfunc (otp *OneTimePassword) steps(now time.Time) uint64 {\n\telapsed := now.Unix() - otp.BaseTime.Unix()\n\treturn uint64(float64(elapsed) / otp.TimeStep.Seconds())\n}\n\nfunc dt(hs []byte) []byte {\n\toffset := int(hs[len(hs)-1] & 0xf)\n\tp := hs[offset : offset+4]\n\tp[0] &= 0x7f\n\treturn p\n}\n"}
{"id": 47671, "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", "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": 47672, "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", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 47673, "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", "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": 47674, "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", "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": 47675, "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", "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": 47676, "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", "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": 47677, "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", "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": 47678, "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", "Python": "for i in range(1, 11):\n    if i % 5 == 0:\n        print(i)\n        continue\n    print(i, end=', ')\n"}
{"id": 47679, "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", "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": 47680, "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", "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": 47681, "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", "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": 47682, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\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": 47683, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\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": 47684, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\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": 47685, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 47686, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 47687, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\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": 47688, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\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": 47689, "name": "Checkpoint synchronization", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\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": 47690, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\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": 47691, "name": "Record sound", "C": "#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <fcntl.h>\n\nvoid * record(size_t bytes)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_RDONLY))) return 0;\n\tvoid *a = malloc(bytes);\n\tread(fd, a, bytes);\n\tclose(fd);\n\treturn a;\n}\n\nint play(void *buf, size_t len)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_WRONLY))) return 0;\n\twrite(fd, buf, len);\n\tclose(fd);\n\treturn 1;\n}\n\nint main()\n{\n\tvoid *p = record(65536);\n\tplay(p, 65536);\n\treturn 0;\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": 47692, "name": "SHA-256 Merkle tree", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\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": 47693, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\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": 47694, "name": "User input_Graphical", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\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": 47695, "name": "Sierpinski arrowhead curve", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\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": 47696, "name": "Text processing_1", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\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": 47697, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\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": 47698, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\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": 47699, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\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": 47700, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\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": 47701, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\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": 47702, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\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": 47703, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\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": 47704, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\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": 47705, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\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": 47706, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 47707, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\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": 47708, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 47709, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\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": 47710, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\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": 47711, "name": "Fractran", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\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": 47712, "name": "Fractran", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\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": 47713, "name": "Sorting algorithms_Stooge sort", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\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": 47714, "name": "Galton box animation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\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": 47715, "name": "Sorting Algorithms_Circle Sort", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\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": 47716, "name": "Kronecker product based fractals", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\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": 47717, "name": "Kronecker product based fractals", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\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": 47718, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\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": 47719, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\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": 47720, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\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": 47721, "name": "Circular primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\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": 47722, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\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": 47723, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\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": 47724, "name": "Sorting algorithms_Radix sort", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\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": 47725, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\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": 47726, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\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": 47727, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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 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": 47728, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\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": 47729, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\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": 47730, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\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": 47731, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\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": 47732, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\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": 47733, "name": "Singleton", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\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": 47734, "name": "Safe addition", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\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": 47735, "name": "Case-sensitivity of identifiers", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\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": 47736, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 47737, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n"}
{"id": 47738, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 47739, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\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": 47740, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\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": 47741, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\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": 47742, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\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": 47743, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\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": 47744, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\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": 47745, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\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": 47746, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\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": 47747, "name": "Non-continuous subsequences", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\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": 47748, "name": "Fibonacci word_fractal", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\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": 47749, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\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": 47750, "name": "Roots of unity", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\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": 47751, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 47752, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\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": 47753, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\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": 47754, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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 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": 47755, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\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": 47756, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\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": 47757, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 47758, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\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": 47759, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\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": 47760, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 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": 47761, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\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": 47762, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\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": 47763, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 47764, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 47765, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 47766, "name": "Carmichael 3 strong pseudoprimes", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n"}
{"id": 47767, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n"}
{"id": 47768, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 47769, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 47770, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 47771, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 47772, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 47773, "name": "Conjugate transpose", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n"}
{"id": 47774, "name": "Conjugate transpose", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n"}
{"id": 47775, "name": "Jacobsthal numbers", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 47776, "name": "Jacobsthal numbers", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 47777, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 47778, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 47779, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 47780, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 47781, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 47782, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 47783, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 47784, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 47785, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 47786, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 47787, "name": "Fermat numbers", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <gmp.h>\n\nvoid mpz_factors(mpz_t n) {\n  int factors = 0;\n  mpz_t s, m, p;\n  mpz_init(s), mpz_init(m), mpz_init(p);\n\n  mpz_set_ui(m, 3);\n  mpz_set(p, n);\n  mpz_sqrt(s, p);\n\n  while (mpz_cmp(m, s) < 0) {\n    if (mpz_divisible_p(p, m)) {\n      gmp_printf(\"%Zd \", m);\n      mpz_fdiv_q(p, p, m);\n      mpz_sqrt(s, p);\n      factors ++;\n    }\n    mpz_add_ui(m, m, 2);\n  }\n\n  if (factors == 0) printf(\"PRIME\\n\");\n  else gmp_printf(\"%Zd\\n\", p);\n}\n\nint main(int argc, char const *argv[]) {\n  mpz_t fermat;\n  mpz_init_set_ui(fermat, 3);\n  printf(\"F(0) = 3 -> PRIME\\n\");\n  for (unsigned i = 1; i < 10; i ++) {\n    mpz_sub_ui(fermat, fermat, 1);\n    mpz_mul(fermat, fermat, fermat);\n    mpz_add_ui(fermat, fermat, 1);\n    gmp_printf(\"F(%d) = %Zd -> \", i, fermat);\n    mpz_factors(fermat);\n  }\n\n  return 0;\n}\n", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n"}
{"id": 47788, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 47789, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 47790, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 47791, "name": "Water collected between towers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n"}
{"id": 47792, "name": "Descending primes", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n"}
{"id": 47793, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"}
{"id": 47794, "name": "Jaro similarity", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47795, "name": "Sum and product puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n"}
{"id": 47796, "name": "Fairshare between two and more", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n"}
{"id": 47797, "name": "Two bullet roulette", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstatic int nextInt(int size) {\n    return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n    bool t = cylinder[5];\n    int i;\n    for (i = 4; i >= 0; i--) {\n        cylinder[i + 1] = cylinder[i];\n    }\n    cylinder[0] = t;\n}\n\nstatic void unload() {\n    int i;\n    for (i = 0; i < 6; i++) {\n        cylinder[i] = false;\n    }\n}\n\nstatic void load() {\n    while (cylinder[0]) {\n        rshift();\n    }\n    cylinder[0] = true;\n    rshift();\n}\n\nstatic void spin() {\n    int lim = nextInt(6) + 1;\n    int i;\n    for (i = 1; i < lim; i++) {\n        rshift();\n    }\n}\n\nstatic bool fire() {\n    bool shot = cylinder[0];\n    rshift();\n    return shot;\n}\n\nstatic int method(const char *s) {\n    unload();\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            load();\n            break;\n        case 'S':\n            spin();\n            break;\n        case 'F':\n            if (fire()) {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n    if (*out != '\\0') {\n        strcat(out, \", \");\n    }\n    strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            append(out, \"load\");\n            break;\n        case 'S':\n            append(out, \"spin\");\n            break;\n        case 'F':\n            append(out, \"fire\");\n            break;\n        }\n    }\n}\n\nstatic void test(char *src) {\n    char buffer[41] = \"\";\n    const int tests = 100000;\n    int sum = 0;\n    int t;\n    double pc;\n\n    for (t = 0; t < tests; t++) {\n        sum += method(src);\n    }\n\n    mstring(src, buffer);\n    pc = 100.0 * sum / tests;\n\n    printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n    srand(time(0));\n\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n", "Python": "\nimport numpy as np\n\nclass Revolver:\n    \n\n    def __init__(self):\n        \n        self.cylinder = np.array([False] * 6)\n\n    def unload(self):\n        \n        self.cylinder[:] = False\n\n    def load(self):\n        \n        while self.cylinder[1]:\n            self.cylinder[:] = np.roll(self.cylinder, 1)\n        self.cylinder[1] = True\n\n    def spin(self):\n        \n        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n    def fire(self):\n        \n        shot = self.cylinder[0]\n        self.cylinder[:] = np.roll(self.cylinder, 1)\n        return shot\n\n    def LSLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LSLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n    def LLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n\nif __name__ == '__main__':\n\n    REV = Revolver()\n    TESTCOUNT = 100000\n    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n                           ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n        print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\n"}
{"id": 47798, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 47799, "name": "Trabb Pardo–Knuth algorithm", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 47800, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 47801, "name": "Sequence_ nth number with exactly n divisors", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 47802, "name": "Sequence_ smallest number with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 47803, "name": "Sequence_ smallest number with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 47804, "name": "Pancake numbers", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n"}
{"id": 47805, "name": "Generate random chess position", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n"}
{"id": 47806, "name": "Esthetic numbers", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n"}
{"id": 47807, "name": "Topswops", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n"}
{"id": 47808, "name": "Old Russian measure of length", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n"}
{"id": 47809, "name": "Rate counter", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n"}
{"id": 47810, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 47811, "name": "Padovan sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n", "Python": "from math import floor\nfrom collections import deque\nfrom typing import Dict, Generator\n\n\ndef padovan_r() -> Generator[int, None, None]:\n    last = deque([1, 1, 1], 4)\n    while True:\n        last.append(last[-2] + last[-3])\n        yield last.popleft()\n\n_p, _s = 1.324717957244746025960908854, 1.0453567932525329623\n\ndef padovan_f(n: int) -> int:\n    return floor(_p**(n-1) / _s + .5)\n\ndef padovan_l(start: str='A',\n             rules: Dict[str, str]=dict(A='B', B='C', C='AB')\n             ) -> Generator[str, None, None]:\n    axiom = start\n    while True:\n        yield axiom\n        axiom = ''.join(rules[ch] for ch in axiom)\n\n\nif __name__ == \"__main__\":\n    from itertools import islice\n\n    print(\"The first twenty terms of the sequence.\")\n    print(str([padovan_f(n) for n in range(20)])[1:-1])\n\n    r_generator = padovan_r()\n    if all(next(r_generator) == padovan_f(n) for n in range(64)):\n        print(\"\\nThe recurrence and floor based algorithms match to n=63 .\")\n    else:\n        print(\"\\nThe recurrence and floor based algorithms DIFFER!\")\n\n    print(\"\\nThe first 10 L-system string-lengths and strings\")\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    print('\\n'.join(f\"  {len(string):3} {repr(string)}\"\n                    for string in islice(l_generator, 10)))\n\n    r_generator = padovan_r()\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)\n           for n in range(32)):\n        print(\"\\nThe L-system, recurrence and floor based algorithms match to n=31 .\")\n    else:\n        print(\"\\nThe L-system, recurrence and floor based algorithms DIFFER!\")\n"}
{"id": 47812, "name": "Pythagoras tree", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n"}
{"id": 47813, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 47814, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 47815, "name": "Colorful numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 47816, "name": "Colorful numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 47817, "name": "Biorhythms", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"}
{"id": 47818, "name": "Biorhythms", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"}
{"id": 47819, "name": "Table creation_Postal addresses", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n"}
{"id": 47820, "name": "Sine wave", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n\nint header[] = {46, 115, 110, 100, 0, 0, 0, 24,\n                255, 255, 255, 255, 0, 0, 0, 3,\n                0, 0, 172, 68, 0, 0, 0, 1};\n\nint main(int argc, char *argv[]){\n        float freq, dur;\n        long i, v;\n\n        if (argc < 3) {\n                printf(\"Usage:\\n\");\n                printf(\"  csine <frequency> <duration>\\n\");\n                exit(1);\n        }\n        freq = atof(argv[1]);\n        dur = atof(argv[2]);\n        for (i = 0; i < 24; i++)\n                putchar(header[i]);\n        for (i = 0; i < dur * 44100; i++) {\n                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));\n                v = v % 65536;\n                putchar(v >> 8);\n                putchar(v % 256);\n        }\n}\n", "Python": "\n\nimport os\nfrom math import pi, sin\n\n\nau_header = bytearray(\n            [46, 115, 110, 100,   \n              0,   0,   0,  24,   \n            255, 255, 255, 255,   \n              0,   0,   0,   3,   \n              0,   0, 172,  68,   \n              0,   0,   0,   1])  \n\ndef f(x, freq):\n    \"Compute sine wave as 16-bit integer\"\n    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536\n\ndef play_sine(freq=440, duration=5, oname=\"pysine.au\"):\n    \"Play a sine wave for `duration` seconds\"\n    out = open(oname, 'wb')\n    out.write(au_header)\n    v = [f(x, freq) for x in range(duration * 44100 + 1)]\n    s = []\n    for i in v:\n        s.append(i >> 8)\n        s.append(i % 256)\n    out.write(bytearray(s))\n    out.close()\n    os.system(\"vlc \" + oname)   \n\nplay_sine()\n"}
{"id": 47821, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 47822, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 47823, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 47824, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 47825, "name": "Numeric error propagation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n"}
{"id": 47826, "name": "Soundex", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 47827, "name": "List rooted trees", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n"}
{"id": 47828, "name": "Documentation", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n"}
{"id": 47829, "name": "Table creation", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n"}
{"id": 47830, "name": "Table creation", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n"}
{"id": 47831, "name": "Problem of Apollonius", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n"}
{"id": 47832, "name": "Append numbers at same position in strings", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n"}
{"id": 47833, "name": "Append numbers at same position in strings", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n"}
{"id": 47834, "name": "Append numbers at same position in strings", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n"}
{"id": 47835, "name": "Longest common suffix", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47836, "name": "Longest common suffix", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47837, "name": "Chat server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n"}
{"id": 47838, "name": "Idiomatically determine all the lowercase and uppercase letters", "C": "#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n  putchar('\\n');\n  for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n  putchar('\\n');\n  return 0;\n}\n", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n"}
{"id": 47839, "name": "Sum of elements below main diagonal of matrix", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n"}
{"id": 47840, "name": "Retrieve and search chat history", "C": "#include<curl/curl.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAX_LEN 1000\n\nvoid searchChatLogs(char* searchString){\n\tchar* baseURL = \"http:\n\ttime_t t;\n\tstruct tm* currentDate;\n\tchar dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];\n\tint i,flag;\n\tFILE *fp;\n\t\n\tCURL *curl;\n\tCURLcode res;\n\t\n\ttime(&t);\n\tcurrentDate = localtime(&t);\n\t\n\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\n\tprintf(\"Today is : %s\",dateString);\n\t\n\tif((curl = curl_easy_init())!=NULL){\n\t\tfor(i=0;i<=10;i++){\n\t\t\t\n\t\tflag = 0;\n\t\tsprintf(targetURL,\"%s%s.tcl\",baseURL,dateString);\n\t\t\n\t\tstrcpy(dateStringFile,dateString);\n\t\t\n\t\tprintf(\"\\nRetrieving chat logs from %s\\n\",targetURL);\n\t\t\n\t\tif((fp = fopen(\"nul\",\"w\"))==0){\n\t\t\tprintf(\"Cant's read from %s\",targetURL);\n\t\t}\n\t\telse{\n\t\t\tcurl_easy_setopt(curl, CURLOPT_URL, targetURL);\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);\n\t\t\n\t\tres = curl_easy_perform(curl);\n\t\t\n\t\tif(res == CURLE_OK){\n\t\t\twhile(fgets(lineData,MAX_LEN,fp)!=NULL){\n\t\t\t\tif(strstr(lineData,searchString)!=NULL){\n\t\t\t\t\tflag = 1;\n\t\t\t\t\tfputs(lineData,stdout);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(flag==0)\n\t\t\t\tprintf(\"\\nNo matching lines found.\");\n\t\t}\n\t\tfflush(fp);\n\t\tfclose(fp);\n\t\t}\n\t\t\n\t\tcurrentDate->tm_mday--;\n\t\tmktime(currentDate);\n\t\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\t\n\t\t\t\n\t}\n\tcurl_easy_cleanup(curl);\n\t\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <followed by search string, enclosed by \\\" if it contains spaces>\",argV[0]);\n\telse\n\t\tsearchChatLogs(argV[1]);\n\treturn 0;\n}\n", "Python": "\nimport datetime\nimport re\nimport urllib.request\nimport sys\n\ndef get(url):\n    with urllib.request.urlopen(url) as response:\n       html = response.read().decode('utf-8')\n    if re.match(r'<!Doctype HTML[\\s\\S]*<Title>URL Not Found</Title>', html):\n        return None\n    return html\n\ndef main():\n    template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'\n    today = datetime.datetime.utcnow()\n    back = 10\n    needle = sys.argv[1]\n    \n    \n    \n    for i in range(-back, 2):\n        day = today + datetime.timedelta(days=i)\n        url = day.strftime(template)\n        haystack = get(url)\n        if haystack:\n            mentions = [x for x in haystack.split('\\n') if needle in x]\n            if mentions:\n                print('{}\\n------\\n{}\\n------\\n'\n                          .format(url, '\\n'.join(mentions)))\n\nmain()\n"}
{"id": 47841, "name": "Rosetta Code_Rank languages by number of users", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n"}
{"id": 47842, "name": "Rosetta Code_Rank languages by number of users", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n"}
{"id": 47843, "name": "Addition-chain exponentiation", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n", "Python": "\n\nfrom math import sqrt\nfrom numpy import array\nfrom mpmath import mpf\n\n\nclass AdditionChains:\n    \n\n    def __init__(self):\n        \n        self.chains, self.idx, self.pos = [[1]], 0, 0\n        self.pat, self.lvl = {1: 0}, [[1]]\n\n    def add_chain(self):\n        \n        newchain = self.chains[self.idx].copy()\n        newchain.append(self.chains[self.idx][-1] +\n                        self.chains[self.idx][self.pos])\n        self.chains.append(newchain)\n        if self.pos == len(self.chains[self.idx])-1:\n            self.idx += 1\n            self.pos = 0\n        else:\n            self.pos += 1\n        return newchain\n\n    def find_chain(self, nexp):\n        \n        assert nexp > 0\n        if nexp == 1:\n            return [1]\n        chn = next((a for a in self.chains if a[-1] == nexp), None)\n        if chn is None:\n            while True:\n                chn = self.add_chain()\n                if chn[-1] == nexp:\n                    break\n\n        return chn\n\n    def knuth_path(self, ngoal):\n        \n        if ngoal < 1:\n            return []\n        while not ngoal in self.pat:\n            new_lvl = []\n            for i in self.lvl[0]:\n                for j in self.knuth_path(i):\n                    if not i + j in self.pat:\n                        self.pat[i + j] = i\n                        new_lvl.append(i + j)\n\n            self.lvl[0] = new_lvl\n\n        returnpath = self.knuth_path(self.pat[ngoal])\n        returnpath.append(ngoal)\n        return returnpath\n\n\ndef cpow(xbase, chain):\n    \n    pows, products = 0, {0: 1, 1: xbase}\n    for i in chain:\n        products[i] = products[pows] * products[i - pows]\n        pows = i\n    return products[chain[-1]]\n\n\nif __name__ == '__main__':\n    \n    acs = AdditionChains()\n    print('First one hundred addition chain lengths:')\n    for k in range(1, 101):\n        print(f'{len(acs.find_chain(k))-1:3}', end='\\n'if k % 10 == 0 else '')\n\n    print('\\nKnuth chains for addition chains of 31415 and 27182:')\n    chns = {m: acs.knuth_path(m) for m in [31415, 27182]}\n    for (num, cha) in chns.items():\n        print(f'Exponent: {num:10}\\n  Addition Chain: {cha[:-1]}')\n    print('\\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))\n    print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))\n    print('1.000025 + 0.000058i)^27182 =',\n          cpow(complex(1.000025, 0.000058), chns[27182]))\n    print('1.000022 + 0.000050i)^31415 =',\n          cpow(complex(1.000022, 0.000050), chns[31415]))\n    sq05 = mpf(sqrt(0.5))\n    mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],\n                 [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])\n    print('matrix A ^ 27182 =')\n    print(cpow(mat, chns[27182]))\n    print('matrix A ^ 31415 =')\n    print(cpow(mat, chns[31415]))\n    print('(matrix A ** 27182) ** 31415 =')\n    print(cpow(cpow(mat, chns[27182]), chns[31415]))\n"}
{"id": 47844, "name": "Addition-chain exponentiation", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n", "Python": "\n\nfrom math import sqrt\nfrom numpy import array\nfrom mpmath import mpf\n\n\nclass AdditionChains:\n    \n\n    def __init__(self):\n        \n        self.chains, self.idx, self.pos = [[1]], 0, 0\n        self.pat, self.lvl = {1: 0}, [[1]]\n\n    def add_chain(self):\n        \n        newchain = self.chains[self.idx].copy()\n        newchain.append(self.chains[self.idx][-1] +\n                        self.chains[self.idx][self.pos])\n        self.chains.append(newchain)\n        if self.pos == len(self.chains[self.idx])-1:\n            self.idx += 1\n            self.pos = 0\n        else:\n            self.pos += 1\n        return newchain\n\n    def find_chain(self, nexp):\n        \n        assert nexp > 0\n        if nexp == 1:\n            return [1]\n        chn = next((a for a in self.chains if a[-1] == nexp), None)\n        if chn is None:\n            while True:\n                chn = self.add_chain()\n                if chn[-1] == nexp:\n                    break\n\n        return chn\n\n    def knuth_path(self, ngoal):\n        \n        if ngoal < 1:\n            return []\n        while not ngoal in self.pat:\n            new_lvl = []\n            for i in self.lvl[0]:\n                for j in self.knuth_path(i):\n                    if not i + j in self.pat:\n                        self.pat[i + j] = i\n                        new_lvl.append(i + j)\n\n            self.lvl[0] = new_lvl\n\n        returnpath = self.knuth_path(self.pat[ngoal])\n        returnpath.append(ngoal)\n        return returnpath\n\n\ndef cpow(xbase, chain):\n    \n    pows, products = 0, {0: 1, 1: xbase}\n    for i in chain:\n        products[i] = products[pows] * products[i - pows]\n        pows = i\n    return products[chain[-1]]\n\n\nif __name__ == '__main__':\n    \n    acs = AdditionChains()\n    print('First one hundred addition chain lengths:')\n    for k in range(1, 101):\n        print(f'{len(acs.find_chain(k))-1:3}', end='\\n'if k % 10 == 0 else '')\n\n    print('\\nKnuth chains for addition chains of 31415 and 27182:')\n    chns = {m: acs.knuth_path(m) for m in [31415, 27182]}\n    for (num, cha) in chns.items():\n        print(f'Exponent: {num:10}\\n  Addition Chain: {cha[:-1]}')\n    print('\\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))\n    print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))\n    print('1.000025 + 0.000058i)^27182 =',\n          cpow(complex(1.000025, 0.000058), chns[27182]))\n    print('1.000022 + 0.000050i)^31415 =',\n          cpow(complex(1.000022, 0.000050), chns[31415]))\n    sq05 = mpf(sqrt(0.5))\n    mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],\n                 [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])\n    print('matrix A ^ 27182 =')\n    print(cpow(mat, chns[27182]))\n    print('matrix A ^ 31415 =')\n    print(cpow(mat, chns[31415]))\n    print('(matrix A ** 27182) ** 31415 =')\n    print(cpow(cpow(mat, chns[27182]), chns[31415]))\n"}
{"id": 47845, "name": "Terminal control_Unicode output", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n"}
{"id": 47846, "name": "Terminal control_Unicode output", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n"}
{"id": 47847, "name": "Find adjacent primes which differ by a square integer", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n"}
{"id": 47848, "name": "Find adjacent primes which differ by a square integer", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n"}
{"id": 47849, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 47850, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 47851, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 47852, "name": "Video display modes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n"}
{"id": 47853, "name": "Video display modes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n"}
{"id": 47854, "name": "Keyboard input_Flush the keyboard buffer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char* argv[])\n{\n    \n    \n    char text[256];\n    getchar();\n\n    \n    \n    \n    \n\n    \n    \n    fseek(stdin, 0, SEEK_END);\n\n    \n    \n    \n\n    \n    \n    fgets(text, sizeof(text), stdin);\n    puts(text);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "def flush_input():\n    try:\n        import msvcrt\n        while msvcrt.kbhit():\n            msvcrt.getch()\n    except ImportError:\n        import sys, termios\n        termios.tcflush(sys.stdin, termios.TCIOFLUSH)\n"}
{"id": 47855, "name": "Numerical integration_Adaptive Simpson's method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 47856, "name": "Numerical integration_Adaptive Simpson's method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 47857, "name": "FASTA format", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n"}
{"id": 47858, "name": "Cousin primes", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47859, "name": "Cousin primes", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47860, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 47861, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 47862, "name": "Check input device is a terminal", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n"}
{"id": 47863, "name": "Check input device is a terminal", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n"}
{"id": 47864, "name": "Window creation_X11", "C": "'--- added a flush to exit cleanly   \nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n \n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n \n'---pointer to X Display structure\nDECLARE d TYPE  Display*\n \n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n \n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n \nDECLARE msg TYPE char*\n \n'--- number of screen to place the window on\nDECLARE s TYPE int\n \n \n \n  msg = \"Hello, World!\"\n \n \n   d = DISPLAY(NULL)\n   IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n   END IF\n \n   s = SCREEN(d)\n   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n \n   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n   MAP_EVENT(d, w)\n \n   WHILE  (1) \n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t    BREAK\n\t END IF   \n   WEND\n   FLUSH(d)\n   CLOSE_DISPLAY(d)\n", "Python": "from Xlib import X, display\n\nclass Window:\n    def __init__(self, display, msg):\n        self.display = display\n        self.msg = msg\n        \n        self.screen = self.display.screen()\n        self.window = self.screen.root.create_window(\n            10, 10, 100, 100, 1,\n            self.screen.root_depth,\n            background_pixel=self.screen.white_pixel,\n            event_mask=X.ExposureMask | X.KeyPressMask,\n            )\n        self.gc = self.window.create_gc(\n            foreground = self.screen.black_pixel,\n            background = self.screen.white_pixel,\n            )\n\n        self.window.map()\n\n    def loop(self):\n        while True:\n            e = self.display.next_event()\n                \n            if e.type == X.Expose:\n                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n                self.window.draw_text(self.gc, 10, 50, self.msg)\n            elif e.type == X.KeyPress:\n                raise SystemExit\n\n                \nif __name__ == \"__main__\":\n    Window(display.Display(), \"Hello, World!\").loop()\n"}
{"id": 47865, "name": "Elementary cellular automaton_Random number generator", "C": "#include <stdio.h>\n#include <limits.h>\n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}\n", "Python": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n    cells = '1' + '0' * (lencells - 1)\n    gen = eca(cells, 30)\n    while True:\n        yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n    print([b for i,b in zip(range(10), rule30bytes())])\n"}
{"id": 47866, "name": "Terminal control_Dimensions", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n"}
{"id": 47867, "name": "Finite state machine", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n"}
{"id": 47868, "name": "Vibrating rectangles", "C": "\n\n#include<graphics.h>\n\nvoid vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)\n{\n\tint color = 1,i,x = winWidth/2, y = winHeight/2;\n\t\n\twhile(!kbhit()){\n\t\tsetcolor(color++);\n\t\tfor(i=num;i>0;i--){\n\t\t\trectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);\n\t\t\tdelay(msec);\n\t\t}\n\n\t\tif(color>MAXCOLORS){\n\t\t\tcolor = 1;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Vibrating Rectangles...\");\n\t\n\tvibratingRectangles(1000,1000,30,15,20,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n"}
{"id": 47869, "name": "Last list item", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint compare(const void *a, const void *b) {\n    int aa = *(const int *)a;\n    int bb = *(const int *)b;\n    if (aa < bb) return -1;\n    if (aa > bb) return 1;\n    return 0;\n}\n\nint main() {\n    int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};\n    int isize = sizeof(int);\n    int asize = sizeof(a) / isize;\n    int i, sum;\n    while (asize > 1) {\n        qsort(a, asize, isize, compare);\n        printf(\"Sorted list: \");\n        for (i = 0; i < asize; ++i) printf(\"%d \", a[i]);\n        printf(\"\\n\");\n        sum = a[0] + a[1];\n        printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum);\n        for (i = 2; i < asize; ++i) a[i-2] = a[i];\n        a[asize - 2] = sum;\n        asize--;\n    }\n    printf(\"Last item is %d.\\n\", a[0]);\n    return 0;\n}\n", "Python": "\n\ndef add_least_reduce(lis):\n    \n    while len(lis) > 1:\n        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))\n        print('Interim list:', lis)\n    return lis\n\nLIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]\n\nprint(LIST, ' ==> ', add_least_reduce(LIST.copy()))\n"}
{"id": 47870, "name": "Minimum numbers of three lists", "C": "#include <stdio.h>\n\nint min(int a, int b) {\n    if (a < b) return a;\n    return b;\n}\n\nint main() {\n    int n;\n    int numbers1[5] = {5, 45, 23, 21, 67};\n    int numbers2[5] = {43, 22, 78, 46, 38};\n    int numbers3[5] = {9, 98, 12, 98, 53};\n    int numbers[5]  = {};\n    for (n = 0; n < 5; ++n) {\n        numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);\n        printf(\"%d \", numbers[n]);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "numbers1 = [5,45,23,21,67]\nnumbers2 = [43,22,78,46,38]\nnumbers3 = [9,98,12,98,53]\n\nnumbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]\n\nprint(numbers)\n"}
{"id": 47871, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 47872, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 47873, "name": "Pseudo-random numbers_PCG32", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 47874, "name": "Deconvolution_1D", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n", "Python": "def ToReducedRowEchelonForm( M ):\n    if not M: return\n    lead = 0\n    rowCount = len(M)\n    columnCount = len(M[0])\n    for r in range(rowCount):\n        if lead >= columnCount:\n            return\n        i = r\n        while M[i][lead] == 0:\n            i += 1\n            if i == rowCount:\n                i = r\n                lead += 1\n                if columnCount == lead:\n                    return\n        M[i],M[r] = M[r],M[i]\n        lv = M[r][lead]\n        M[r] = [ mrx / lv for mrx in M[r]]\n        for i in range(rowCount):\n            if i != r:\n                lv = M[i][lead]\n                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n        lead += 1\n    return M\n \ndef pmtx(mtx):\n    print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n \ndef convolve(f, h):\n    g = [0] * (len(f) + len(h) - 1)\n    for hindex, hval in enumerate(h):\n        for findex, fval in enumerate(f):\n            g[hindex + findex] += fval * hval\n    return g\n\ndef deconvolve(g, f):\n    lenh = len(g) - len(f) + 1\n    mtx = [[0 for x in range(lenh+1)] for y in g]\n    for hindex in range(lenh):\n        for findex, fval in enumerate(f):\n            gindex = hindex + findex\n            mtx[gindex][hindex] = fval\n    for gindex, gval in enumerate(g):        \n        mtx[gindex][lenh] = gval\n    ToReducedRowEchelonForm( mtx )\n    return [mtx[i][lenh] for i in range(lenh)]  \n\nif __name__ == '__main__':\n    h = [-8,-9,-3,-1,-6,7]\n    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n    assert convolve(f,h) == g\n    assert deconvolve(g, f) == h\n"}
{"id": 47875, "name": "Bitmap_PPM conversion through a pipe", "C": "\nvoid print_jpg(image img, int qual);\n", "Python": "\n\nfrom PIL import Image\n\nim = Image.open(\"boxes_1.ppm\")\nim.save(\"boxes_1.jpg\")\n"}
{"id": 47876, "name": "Bitcoin_public point to address", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n"}
{"id": 47877, "name": "Bitcoin_public point to address", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n"}
{"id": 47878, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 47879, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 47880, "name": "Disarium numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n"}
{"id": 47881, "name": "Disarium numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n"}
{"id": 47882, "name": "Sierpinski pentagon", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n"}
{"id": 47883, "name": "Bitmap_Histogram", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 47884, "name": "Padovan n-step number sequences", "C": "#include <stdio.h>\n\nvoid padovanN(int n, size_t t, int *p) {\n    int i, j;\n    if (n < 2 || t < 3) {\n        for (i = 0; i < t; ++i) p[i] = 1;\n        return;\n    }\n    padovanN(n-1, t, p);\n    for (i = n + 1; i < t; ++i) {\n        p[i] = 0;\n        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];\n    }\n}\n\nint main() {\n    int n, i;\n    const size_t t = 15;\n    int p[t];\n    printf(\"First %ld terms of the Padovan n-step number sequences:\\n\", t);\n    for (n = 2; n <= 8; ++n) {\n        for (i = 0; i < t; ++i) p[i] = 0;\n        padovanN(n, t, p);\n        printf(\"%d: \", n);\n        for (i = 0; i < t; ++i) printf(\"%3d \", p[i]);\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "Python": "def pad_like(max_n=8, t=15):\n    \n    start = [[], [1, 1, 1]]     \n    for n in range(2, max_n+1):\n        this = start[n-1][:n+1]     \n        while len(this) < t:\n            this.append(sum(this[i] for i in range(-2, -n - 2, -1)))\n        start.append(this)\n    return start[2:]\n\ndef pr(p):\n    print(.strip())\n    for n, seq in enumerate(p, 2):\n        print(f\"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\\n|-\")\n    print('|}')\n\nif __name__ == '__main__':\n    p = pad_like()\n    pr(p)\n"}
{"id": 47885, "name": "Mutex", "C": "HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);\n", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n"}
{"id": 47886, "name": "Metronome", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/time.h>\n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); \n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec)   \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}\n", "Python": "\nimport time\n\ndef main(bpm = 72, bpb = 4):\n    sleep = 60.0 / bpm\n    counter = 0\n    while True:\n        counter += 1\n        if counter % bpb:\n            print 'tick'\n        else:\n            print 'TICK'\n        time.sleep(sleep)\n        \n\n\nmain()\n"}
{"id": 47887, "name": "Native shebang", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n"}
{"id": 47888, "name": "Native shebang", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n"}
{"id": 47889, "name": "EKG sequence convergence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n    int aa = *(int *)a;\n    int bb = *(int *)b;\n    return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n    int i;\n    for (i = 0; i < len; ++i) {\n        if (a[i] == b) return TRUE;\n    }\n    return FALSE;\n}\n\nint gcd(int a, int b) {\n    while (a != b) {\n        if (a > b)\n            a -= b;\n        else\n            b -= a;\n    }\n    return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n    int i;\n    qsort(s, len, sizeof(int), compareInts);    \n    qsort(t, len, sizeof(int), compareInts);\n    for (i = 0; i < len; ++i) {\n        if (s[i] != t[i]) return FALSE;\n    }\n    return TRUE;\n}\n\nint main() {\n    int s, n, i;\n    int starts[5] = {2, 5, 7, 9, 10};\n    int ekg[5][LIMIT];\n    for (s = 0; s < 5; ++s) {\n        ekg[s][0] = 1;\n        ekg[s][1] = starts[s];\n        for (n = 2; n < LIMIT; ++n) {\n            for (i = 2; ; ++i) {\n                \n                \n                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n                    ekg[s][n] = i;\n                    break;\n                }\n            }\n        }\n        printf(\"EKG(%2d): [\", starts[s]);\n        for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n        printf(\"\\b]\\n\");\n    }\n    \n    \n    for (i = 2; i < LIMIT; ++i) {\n        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n            printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n            return 0;\n        }\n    }\n    printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n    return 0;\n}\n", "Python": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n    \n    c = count(start + 1)\n    last, so_far = start, list(range(2, start))\n    yield 1, []\n    yield last, []\n    while True:\n        for index, sf in enumerate(so_far):\n            if gcd(last, sf) > 1:\n                last = so_far.pop(index)\n                yield last, so_far[::]\n                break\n        else:\n            so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n    \"Returns the convergence point or zero if not found within the limit\"\n    ekg = [EKG_gen(n) for n in ekgs]\n    for e in ekg:\n        next(e)    \n    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),\n                                  zip(*ekg))))\n\nif __name__ == '__main__':\n    for start in 2, 5, 7, 9, 10:\n        print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n    print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")\n"}
{"id": 47890, "name": "Rep-string", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n"}
{"id": 47891, "name": "Terminal control_Preserve screen", "C": "#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n\tint i;\n\tprintf(\"\\033[?1049h\\033[H\");\n\tprintf(\"Alternate screen buffer\\n\");\n\tfor (i = 5; i; i--) {\n\t\tprintf(\"\\rgoing back in %d...\", i);\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tprintf(\"\\033[?1049l\");\n\n\treturn 0;\n}\n", "Python": "\n\nimport time\n\nprint \"\\033[?1049h\\033[H\"\nprint \"Alternate buffer!\"\n\nfor i in xrange(5, 0, -1):\n    print \"Going back in:\", i\n    time.sleep(1)\n\nprint \"\\033[?1049l\"\n"}
{"id": 47892, "name": "Literals_String", "C": "char ch = 'z';\n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 47893, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n"}
{"id": 47894, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n"}
{"id": 47895, "name": "Window management", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n"}
{"id": 47896, "name": "Monads_List monad", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n    return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n    char buf[100];\n    char*str= malloc(1+sprintf(buf, \"%d\", *x));\n    sprintf(str, \"%d\", *x);\n    return (MONAD)(str);\n}\n\nvoid task(int y) {\n    char *z= INTBIND(boundInt2str, boundInt, &y);\n    printf(\"%s\\n\", z);\n    free(z);\n}\n\nint main() {\n    task(13);\n}\n", "Python": "\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n    @classmethod\n    def unit(cls, value: Iterable[T]) -> MList[T]:\n        return cls(value)\n\n    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return MList(chain.from_iterable(map(func, self)))\n\n    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return self.bind(func)\n\n\nif __name__ == \"__main__\":\n    \n    print(\n        MList([1, 99, 4])\n        .bind(lambda val: MList([val + 1]))\n        .bind(lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList([1, 99, 4])\n        >> (lambda val: MList([val + 1]))\n        >> (lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList(range(1, 6)).bind(\n            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n        )\n    )\n\n    \n    print(\n        MList(range(1, 26)).bind(\n            lambda x: MList(range(x + 1, 26)).bind(\n                lambda y: MList(range(y + 1, 26)).bind(\n                    lambda z: MList([(x, y, z)])\n                    if x * x + y * y == z * z\n                    else MList([])\n                )\n            )\n        )\n    )\n"}
{"id": 47897, "name": "Find squares n where n+1 is prime", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n"}
{"id": 47898, "name": "Find squares n where n+1 is prime", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n"}
{"id": 47899, "name": "Find squares n where n+1 is prime", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n"}
{"id": 47900, "name": "Next special primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n"}
{"id": 47901, "name": "Next special primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n"}
{"id": 47902, "name": "Mayan numerals", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47903, "name": "Mayan numerals", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47904, "name": "Special factorials", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "Python": "\n\nfrom math import prod\n\ndef superFactorial(n):\n    return prod([prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef hyperFactorial(n):\n    return prod([i**i for i in range(1,n+1)])\n\ndef alternatingFactorial(n):\n    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef exponentialFactorial(n):\n    if n in [0,1]:\n        return 1\n    else:\n        return n**exponentialFactorial(n-1)\n        \ndef inverseFactorial(n):\n    i = 1\n    while True:\n        if n == prod(range(1,i)):\n            return i-1\n        elif n < prod(range(1,i)):\n            return \"undefined\"\n        i+=1\n\nprint(\"Superfactorials for [0,9] :\")\nprint({\"sf(\" + str(i) + \") \" : superFactorial(i) for i in range(0,10)})\n\nprint(\"\\nHyperfactorials for [0,9] :\")\nprint({\"H(\" + str(i) + \") \"  : hyperFactorial(i) for i in range(0,10)})\n\nprint(\"\\nAlternating factorials for [0,9] :\")\nprint({\"af(\" + str(i) + \") \" : alternatingFactorial(i) for i in range(0,10)})\n\nprint(\"\\nExponential factorials for [0,4] :\")\nprint({str(i) + \"$ \" : exponentialFactorial(i) for i in range(0,5)})\n\nprint(\"\\nDigits in 5$ : \" , len(str(exponentialFactorial(5))))\n\nfactorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n\nprint(\"\\nInverse factorials for \" , factorialSet)\nprint({\"rf(\" + str(i) + \") \":inverseFactorial(i) for i in factorialSet})\n\nprint(\"\\nrf(119) : \" + inverseFactorial(119))\n"}
{"id": 47905, "name": "Special neighbor primes", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n"}
{"id": 47906, "name": "Special neighbor primes", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n"}
{"id": 47907, "name": "Ramsey's theorem", "C": "#include <stdio.h>\n\nint a[17][17], idx[4];\n\nint find_group(int type, int min_n, int max_n, int depth)\n{\n\tint i, n;\n\tif (depth == 4) {\n\t\tprintf(\"totally %sconnected group:\", type ? \"\" : \"un\");\n\t\tfor (i = 0; i < 4; i++) printf(\" %d\", idx[i]);\n\t\tputchar('\\n');\n\t\treturn 1;\n\t}\n\n\tfor (i = min_n; i < max_n; i++) {\n\t\tfor (n = 0; n < depth; n++)\n\t\t\tif (a[idx[n]][i] != type) break;\n\n\t\tif (n == depth) {\n\t\t\tidx[n] = i;\n\t\t\tif (find_group(type, 1, max_n, depth + 1))\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tconst char *mark = \"01-\";\n\n\tfor (i = 0; i < 17; i++)\n\t\ta[i][i] = 2;\n\n\tfor (k = 1; k <= 8; k <<= 1) {\n\t\tfor (i = 0; i < 17; i++) {\n\t\t\tj = (i + k) % 17;\n\t\t\ta[i][j] = a[j][i] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < 17; i++) {\n\t\tfor (j = 0; j < 17; j++)\n\t\t\tprintf(\"%c \", mark[a[i][j]]);\n\t\tputchar('\\n');\n\t}\n\n\t\n\t\n\n\t\n\tfor (i = 0; i < 17; i++) {\n\t\tidx[0] = i;\n\t\tif (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {\n\t\t\tputs(\"no good\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"all good\");\n\treturn 0;\n}\n", "Python": "range17 = range(17)\na = [['0'] * 17 for i in range17]\nidx = [0] * 4\n\n\ndef find_group(mark, min_n, max_n, depth=1):\n    if (depth == 4):\n        prefix = \"\" if (mark == '1') else \"un\"\n        print(\"Fail, found totally {}connected group:\".format(prefix))\n        for i in range(4):\n            print(idx[i])\n        return True\n\n    for i in range(min_n, max_n):\n        n = 0\n        while (n < depth):\n            if (a[idx[n]][i] != mark):\n                break\n            n += 1\n\n        if (n == depth):\n            idx[n] = i\n            if (find_group(mark, 1, max_n, depth + 1)):\n                return True\n\n    return False\n\n\nif __name__ == '__main__':\n    for i in range17:\n        a[i][i] = '-'\n    for k in range(4):\n        for i in range17:\n            j = (i + pow(2, k)) % 17\n            a[i][j] = a[j][i] = '1'\n\n    \n    \n\n    for row in a:\n        print(' '.join(row))\n\n    for i in range17:\n        idx[0] = i\n        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):\n            print(\"no good\")\n            exit()\n\n    print(\"all good\")\n"}
{"id": 47908, "name": "GUI_Maximum window dimensions", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n"}
{"id": 47909, "name": "Terminal control_Inverse video", "C": "#include <stdio.h>\n\nint main()\n{\n\tprintf(\"\\033[7mReversed\\033[m Normal\\n\");\n\n\treturn 0;\n}\n", "Python": "\n\nprint \"\\033[7mReversed\\033[m Normal\"\n"}
{"id": 47910, "name": "Four is magic", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n"}
{"id": 47911, "name": "Getting the number of decimals", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n"}
{"id": 47912, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 47913, "name": "Paraffins", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 47914, "name": "Paraffins", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 47915, "name": "Minimum number of cells after, before, above and below NxN squares", "C": "#include<stdio.h>\n#include<stdlib.h>\n\n#define min(a, b) (a<=b?a:b)\n\nvoid minab( unsigned int n ) {\n    int i, j;\n    for(i=0;i<n;i++) {\n        for(j=0;j<n;j++) {\n            printf( \"%2d  \", min( min(i, n-1-i), min(j, n-1-j) ));\n        }\n        printf( \"\\n\" );\n    }\n    return;\n}\n\nint main(void) {\n    minab(10);\n    return 0;\n}\n", "Python": "def min_cells_matrix(siz):\n    return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]\n\ndef display_matrix(mat):\n    siz = len(mat)\n    spaces = 2 if siz < 20 else 3 if siz < 200 else 4\n    print(f\"\\nMinimum number of cells after, before, above and below {siz} x {siz} square:\")\n    for row in range(siz):\n        print(\"\".join([f\"{n:{spaces}}\" for n in mat[row]]))\n\ndef test_min_mat():\n    for siz in [23, 10, 9, 2, 1]:\n        display_matrix(min_cells_matrix(siz))\n\nif __name__ == \"__main__\":\n    test_min_mat()\n"}
{"id": 47916, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 47917, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 47918, "name": "Parse an IP Address", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n"}
{"id": 47919, "name": "Matrix digital rain", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n"}
{"id": 47920, "name": "Matrix digital rain", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n"}
{"id": 47921, "name": "Mind boggling card trick", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n"}
{"id": 47922, "name": "Mind boggling card trick", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n"}
{"id": 47923, "name": "Textonyms", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n"}
{"id": 47924, "name": "A_ search algorithm", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 47925, "name": "A_ search algorithm", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 47926, "name": "Teacup rim text", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47927, "name": "Increasing gaps between consecutive Niven numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n"}
{"id": 47928, "name": "Print debugging statement", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n"}
{"id": 47929, "name": "Find prime n such that reversed n is also prime", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n"}
{"id": 47930, "name": "Find prime n such that reversed n is also prime", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n"}
{"id": 47931, "name": "Find prime n such that reversed n is also prime", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n"}
{"id": 47932, "name": "Superellipse", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n"}
{"id": 47933, "name": "Superellipse", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n"}
{"id": 47934, "name": "Permutations_Rank of a permutation", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n"}
{"id": 47935, "name": "Permutations_Rank of a permutation", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n"}
{"id": 47936, "name": "Banker's algorithm", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint main() {\n    int curr[5][5];\n    int max_claim[5][5];\n    int avl[5];\n    int alloc[5] = {0, 0, 0, 0, 0};\n    int max_res[5];\n    int running[5];\n\n    int i, j, exec, r, p;\n    int count = 0;\n    bool safe = false;\n\n    printf(\"\\nEnter the number of resources: \");\n    scanf(\"%d\", &r);\n\n    printf(\"\\nEnter the number of processes: \");\n    scanf(\"%d\", &p);\n    for (i = 0; i < p; i++) {\n        running[i] = 1;\n        count++;\n    }\n\n    printf(\"\\nEnter Claim Vector: \");\n    for (i = 0; i < r; i++)\n        scanf(\"%d\", &max_res[i]);\n\n    printf(\"\\nEnter Allocated Resource Table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &curr[i][j]);\n    }\n\n    printf(\"\\nEnter Maximum Claim table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &max_claim[i][j]);\n    }\n\n    printf(\"\\nThe Claim Vector is: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", max_res[i]);\n\n    printf(\"\\nThe Allocated Resource Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", curr[i][j]);\n        printf(\"\\n\");\n    }\n\n    printf(\"\\nThe Maximum Claim Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", max_claim[i][j]);\n        printf(\"\\n\");\n    }\n\n    for (i = 0; i < p; i++)\n        for (j = 0; j < r; j++)\n            alloc[j] += curr[i][j];\n\n    printf(\"\\nAllocated resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", alloc[i]);\n    for (i = 0; i < r; i++)\n        avl[i] = max_res[i] - alloc[i];\n\n    printf(\"\\nAvailable resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", avl[i]);\n    printf(\"\\n\");\n\n    while (count != 0) {\n        safe = false;\n        for (i = 0; i < p; i++) {\n            if (running[i]) {\n                exec = 1;\n                for (j = 0; j < r; j++) {\n                    if (max_claim[i][j] - curr[i][j] > avl[j]) {\n                        exec = 0;\n                        break;\n                    }\n                }\n\n                if (exec) {\n                    printf(\"\\nProcess%d is executing.\\n\", i + 1);\n                    running[i] = 0;\n                    count--;\n                    safe = true;\n                    for (j = 0; j < r; j++)\n                        avl[j] += curr[i][j];\n                    break;\n                }\n            }\n        }\n\n        if (!safe) {\n            printf(\"\\nThe processes are in unsafe state.\");\n            break;\n        }\n\n        if (safe)\n            printf(\"\\nThe process is in safe state.\");\n\n        printf(\"\\nAvailable vector: \");\n        for (i = 0; i < r; i++)\n            printf(\"%d \", avl[i]);\n    }\n\n    return 0;\n}\n", "Python": "def main():\n    resources = int(input(\"Cantidad de recursos: \"))\n    processes = int(input(\"Cantidad de procesos: \"))\n    max_resources = [int(i) for i in input(\"Recursos máximos: \").split()]\n\n    print(\"\\n-- recursos asignados para cada proceso  --\")\n    currently_allocated = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    print(\"\\n--- recursos máximos para cada proceso  ---\")\n    max_need = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    allocated = [0] * resources\n    for i in range(processes):\n        for j in range(resources):\n            allocated[j] += currently_allocated[i][j]\n    print(f\"\\nRecursos totales asignados  : {allocated}\")\n\n    available = [max_resources[i] - allocated[i] for i in range(resources)]\n    print(f\"Recursos totales disponibles: {available}\\n\")\n\n    running = [True] * processes\n    count = processes\n    while count != 0:\n        safe = False\n        for i in range(processes):\n            if running[i]:\n                executing = True\n                for j in range(resources):\n                    if max_need[i][j] - currently_allocated[i][j] > available[j]:\n                        executing = False\n                        break\n                if executing:\n                    print(f\"proceso {i + 1} ejecutándose\")\n                    running[i] = False\n                    count -= 1\n                    safe = True\n                    for j in range(resources):\n                        available[j] += currently_allocated[i][j]\n                    break\n        if not safe:\n            print(\"El proceso está en un estado inseguro.\")\n            break\n\n        print(f\"El proceso está en un estado seguro.\\nRecursos disponibles: {available}\\n\")\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47937, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n"}
{"id": 47938, "name": "Machine code", "C": "#include <stdio.h>\n#include <sys/mman.h>\n#include <string.h>\n\nint test (int a, int b)\n{\n  \n  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};\n  void *buf;\n  int c;\n  \n  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,\n             MAP_PRIVATE|MAP_ANON,-1,0);\n\n  memcpy (buf, code, sizeof(code));\n  \n  c = ((int (*) (int, int))buf)(a, b);\n  \n  munmap (buf, sizeof(code));\n  return c;\n}\n\nint main ()\n{\n  printf(\"%d\\n\", test(7,12));\n  return 0;\n}\n", "Python": "import ctypes\nimport os\nfrom ctypes import c_ubyte, c_int\n\ncode = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])\n\ncode_size = len(code)\n\nif (os.name == 'posix'):\n    import mmap\n    executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)\n    \n    executable_map.write(code)\n    \n    \n    func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))\nelif (os.name == 'nt'):\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    PAGE_EXECUTE_READWRITE = 0x40  \n    MEM_COMMIT = 0x1000\n    executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)\n    if (executable_buffer_address == 0):\n        print('Warning: Failed to enable code execution, call will likely cause a protection fault.')\n        func_address = ctypes.addressof(code_buffer)\n    else:\n        ctypes.memmove(executable_buffer_address, code_buffer, code_size)\n        func_address = executable_buffer_address\nelse:\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    func_address = ctypes.addressof(code_buffer)\n\nprototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) \nfunc = prototype(func_address)                        \nres = func(7,12)\nprint(res)\n"}
{"id": 47939, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 47940, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 47941, "name": "Zhang-Suen thinning algorithm", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n"}
{"id": 47942, "name": "Median filter", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef struct { unsigned char r, g, b; } rgb_t;\ntypedef struct {\n\tint w, h;\n\trgb_t **pix;\n} image_t, *image;\n\ntypedef struct {\n\tint r[256], g[256], b[256];\n\tint n;\n} color_histo_t;\n\nint write_ppm(image im, char *fn)\n{\n\tFILE *fp = fopen(fn, \"w\");\n\tif (!fp) return 0;\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", im->w, im->h);\n\tfwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);\n\tfclose(fp);\n\treturn 1;\n}\n\nimage img_new(int w, int h)\n{\n\tint i;\n\timage im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)\n\t\t\t+ sizeof(rgb_t) * w * h);\n\tim->w = w; im->h = h;\n\tim->pix = (rgb_t**)(im + 1);\n\tfor (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)\n\t\tim->pix[i] = im->pix[i - 1] + w;\n\treturn im;\n}\n\nint read_num(FILE *f)\n{\n\tint n;\n\twhile (!fscanf(f, \"%d \", &n)) {\n\t\tif ((n = fgetc(f)) == '#') {\n\t\t\twhile ((n = fgetc(f)) != '\\n')\n\t\t\t\tif (n == EOF) break;\n\t\t\tif (n == '\\n') continue;\n\t\t} else return 0;\n\t}\n\treturn n;\n}\n\nimage read_ppm(char *fn)\n{\n\tFILE *fp = fopen(fn, \"r\");\n\tint w, h, maxval;\n\timage im = 0;\n\tif (!fp) return 0;\n\n\tif (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))\n\t\tgoto bail;\n\n\tw = read_num(fp);\n\th = read_num(fp);\n\tmaxval = read_num(fp);\n\tif (!w || !h || !maxval) goto bail;\n\n\tim = img_new(w, h);\n\tfread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);\nbail:\n\tif (fp) fclose(fp);\n\treturn im;\n}\n\nvoid del_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]--;\n\t\th->g[pix->g]--;\n\t\th->b[pix->b]--;\n\t\th->n--;\n\t}\n}\n\nvoid add_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]++;\n\t\th->g[pix->g]++;\n\t\th->b[pix->b]++;\n\t\th->n++;\n\t}\n}\n\nvoid init_histo(image im, int row, int size, color_histo_t*h)\n{\n\tint j;\n\n\tmemset(h, 0, sizeof(color_histo_t));\n\n\tfor (j = 0; j < size && j < im->w; j++)\n\t\tadd_pixels(im, row, j, size, h);\n}\n\nint median(const int *x, int n)\n{\n\tint i;\n\tfor (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);\n\treturn i;\n}\n\nvoid median_color(rgb_t *pix, const color_histo_t *h)\n{\n\tpix->r = median(h->r, h->n);\n\tpix->g = median(h->g, h->n);\n\tpix->b = median(h->b, h->n);\n}\n\nimage median_filter(image in, int size)\n{\n\tint row, col;\n\timage out = img_new(in->w, in->h);\n\tcolor_histo_t h;\n\n\tfor (row = 0; row < in->h; row ++) {\n\t\tfor (col = 0; col < in->w; col++) {\n\t\t\tif (!col) init_histo(in, row, size, &h);\n\t\t\telse {\n\t\t\t\tdel_pixels(in, row, col - size, size, &h);\n\t\t\t\tadd_pixels(in, row, col + size, size, &h);\n\t\t\t}\n\t\t\tmedian_color(out->pix[row] + col, &h);\n\t\t}\n\t}\n\n\treturn out;\n}\n\nint main(int c, char **v)\n{\n\tint size;\n\timage in, out;\n\tif (c <= 3) {\n\t\tprintf(\"Usage: %s size ppm_in ppm_out\\n\", v[0]);\n\t\treturn 0;\n\t}\n\tsize = atoi(v[1]);\n\tprintf(\"filter size %d\\n\", size);\n\tif (size < 0) size = 1;\n\n\tin = read_ppm(v[2]);\n\tout = median_filter(in, size);\n\twrite_ppm(out, v[3]);\n\tfree(in);\n\tfree(out);\n\n\treturn 0;\n}\n", "Python": "import Image, ImageFilter\nim = Image.open('image.ppm')\n\nmedian = im.filter(ImageFilter.MedianFilter(3))\nmedian.save('image2.ppm')\n"}
{"id": 47943, "name": "Run as a daemon or service", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n"}
{"id": 47944, "name": "Run as a daemon or service", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n"}
{"id": 47945, "name": "Coprime triplets", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n"}
{"id": 47946, "name": "Coprime triplets", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n"}
{"id": 47947, "name": "Coprime triplets", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n"}
{"id": 47948, "name": "Variable declaration reset", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n"}
{"id": 47949, "name": "SOAP", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n"}
{"id": 47950, "name": "SOAP", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n"}
{"id": 47951, "name": "Pragmatic directives", "C": "\n#include<stdio.h> \n\n\n#define Hi printf(\"Hi There.\");\n\n\n\n#define start int main(){\n#define end return 0;}\n\nstart\n\nHi\n\n\n#warning \"Don't you have anything better to do ?\"\n\n#ifdef __unix__\n#warning \"What are you doing still working on Unix ?\"\nprintf(\"\\nThis is an Unix system.\");\n#elif _WIN32\n#warning \"You couldn't afford a 64 bit ?\"\nprintf(\"\\nThis is a 32 bit Windows system.\");\n#elif _WIN64\n#warning \"You couldn't afford an Apple ?\"\nprintf(\"\\nThis is a 64 bit Windows system.\");\n#endif\n\nend\n\n\n", "Python": "Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> import __future__\n>>> __future__.all_feature_names\n['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']\n>>>\n"}
{"id": 47952, "name": "Find first and last set bit of a long integer", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 47953, "name": "Find first and last set bit of a long integer", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 47954, "name": "Numbers with equal rises and falls", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n"}
{"id": 47955, "name": "Terminal control_Cursor movement", "C": "#include<conio.h>\n#include<dos.h>\n\nchar *strings[] = {\"The cursor will move one position to the left\", \n  \t\t   \"The cursor will move one position to the right\",\n \t\t   \"The cursor will move vetically up one line\", \n \t\t   \"The cursor will move vertically down one line\", \n \t\t   \"The cursor will move to the beginning of the line\", \n \t\t   \"The cursor will move to the end of the line\", \n \t\t   \"The cursor will move to the top left corner of the screen\", \n \t\t   \"The cursor will move to the bottom right corner of the screen\"};\n \t\t             \nint main()\n{\n\tint i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\t\n\tclrscr();\n\tcprintf(\"This is a demonstration of cursor control using gotoxy(). Press any key to continue.\");\n\tgetch();\n\t\n\tfor(i=0;i<8;i++)\n\t{\n\t\tclrscr();\n\t\tgotoxy(5,MAXROW/2);\n\t\t\n\t\tcprintf(\"%s\",strings[i]);\n\t\tgetch();\n\t\t\n\t\tswitch(i){\n\t\t\tcase 0:gotoxy(wherex()-1,wherey());\n\t\t\tbreak;\n\t\t\tcase 1:gotoxy(wherex()+1,wherey());\n\t\t\tbreak;\n\t\t\tcase 2:gotoxy(wherex(),wherey()-1);\n\t\t\tbreak;\n\t\t\tcase 3:gotoxy(wherex(),wherey()+1);\n\t\t\tbreak;\n\t\t\tcase 4:for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()-1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 5:gotoxy(wherex()-strlen(strings[i]),wherey());\n\t\t\t       for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()+1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 6:while(wherex()!=1)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()-1,wherey());\n\t\t\t\t     delay(100);\n\t\t               }\n\t\t\t       while(wherey()!=1)\n\t\t\t       {\n\t\t\t             gotoxy(wherex(),wherey()-1);\n\t\t\t             delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 7:while(wherex()!=MAXCOL)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()+1,wherey());\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\t       while(wherey()!=MAXROW)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex(),wherey()+1);\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\t};\n\t\t\tgetch();\n\t}\n\t\n\tclrscr();\n\tcprintf(\"End of demonstration.\");\n\tgetch();\n\treturn 0;\n}\n", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n"}
{"id": 47956, "name": "Summation of primes", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n    int p;\n    long int s = 2;\n    for(p=3;p<2000000;p+=2) {\n        if(isprime(p)) s+=p;\n    }\n    printf( \"%ld\\n\", s );\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    suma = 2\n    n = 1\n    for i in range(3, 2000000, 2):\n        if isPrime(i):\n            suma += i\n            n+=1 \n    print(suma)\n"}
{"id": 47957, "name": "Koch curve", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n"}
{"id": 47958, "name": "Draw pixel 2", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<time.h>\n\nint main()\n{\n\tsrand(time(NULL));\n\t\n\tinitwindow(640,480,\"Yellow Random Pixel\");\n\t\n\tputpixel(rand()%640,rand()%480,YELLOW);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "Python": "import Tkinter,random\ndef draw_pixel_2 ( sizex=640,sizey=480 ):\n    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )\n    root = Tkinter.Tk()\n    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )\n    can.create_rectangle( pos*2,outline='yellow' )\n    can.pack()\n    root.title('press ESCAPE to quit')\n    root.bind('<Escape>',lambda e : root.quit())\n    root.mainloop()\n\ndraw_pixel_2()\n"}
{"id": 47959, "name": "Count how many vowels and consonants occur in a string", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n"}
{"id": 47960, "name": "Count how many vowels and consonants occur in a string", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n"}
{"id": 47961, "name": "Compiler_syntax analyzer", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n"}
{"id": 47962, "name": "Compiler_syntax analyzer", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n"}
{"id": 47963, "name": "Compiler_syntax analyzer", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n"}
{"id": 47964, "name": "Draw a pixel", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n"}
{"id": 47965, "name": "Numbers whose binary and ternary digit sums are prime", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47966, "name": "Numbers whose binary and ternary digit sums are prime", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47967, "name": "Words from neighbour ones", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n"}
{"id": 47968, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "C": "#include <stdio.h>\n\nint divisible(int n) {\n    int p = 1;\n    int c, d;\n    \n    for (c=n; c; c /= 10) {\n        d = c % 10;\n        if (!d || n % d) return 0;\n        p *= d;\n    }\n    \n    return n % p;\n}\n\nint main() {\n    int n, c=0;\n    \n    for (n=1; n<1000; n++) {\n        if (divisible(n)) {\n            printf(\"%5d\", n);\n            if (!(++c % 10)) printf(\"\\n\");\n        }\n    }\n    printf(\"\\n\");\n    \n    return 0;\n}\n", "Python": "\n\nfrom functools import reduce\nfrom operator import mul\n\n\n\ndef p(n):\n    \n    digits = [int(c) for c in str(n)]\n    return not 0 in digits and (\n        0 != (n % reduce(mul, digits, 1))\n    ) and all(0 == n % d for d in digits)\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1000)\n        if p(n)\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matching numbers:\\n')\n    print('\\n'.join(\n        ' '.join(cell.rjust(w, ' ') for cell in row)\n        for row in chunksOf(10)(xs)\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47969, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "C": "#include <stdio.h>\n\nint divisible(int n) {\n    int p = 1;\n    int c, d;\n    \n    for (c=n; c; c /= 10) {\n        d = c % 10;\n        if (!d || n % d) return 0;\n        p *= d;\n    }\n    \n    return n % p;\n}\n\nint main() {\n    int n, c=0;\n    \n    for (n=1; n<1000; n++) {\n        if (divisible(n)) {\n            printf(\"%5d\", n);\n            if (!(++c % 10)) printf(\"\\n\");\n        }\n    }\n    printf(\"\\n\");\n    \n    return 0;\n}\n", "Python": "\n\nfrom functools import reduce\nfrom operator import mul\n\n\n\ndef p(n):\n    \n    digits = [int(c) for c in str(n)]\n    return not 0 in digits and (\n        0 != (n % reduce(mul, digits, 1))\n    ) and all(0 == n % d for d in digits)\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1000)\n        if p(n)\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matching numbers:\\n')\n    print('\\n'.join(\n        ' '.join(cell.rjust(w, ' ') for cell in row)\n        for row in chunksOf(10)(xs)\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 47970, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 47971, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 47972, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 47973, "name": "Magic squares of singly even order", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n"}
{"id": 47974, "name": "Generate Chess960 starting position", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n"}
{"id": 47975, "name": "Modulinos", "C": "int meaning_of_life();\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 47976, "name": "Modulinos", "C": "int meaning_of_life();\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 47977, "name": "Perlin noise", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n", "Python": "import math\n\ndef perlin_noise(x, y, z):\n    X = math.floor(x) & 255                  \n    Y = math.floor(y) & 255                  \n    Z = math.floor(z) & 255\n    x -= math.floor(x)                                \n    y -= math.floor(y)                                \n    z -= math.floor(z)\n    u = fade(x)                                \n    v = fade(y)                                \n    w = fade(z)\n    A = p[X  ]+Y; AA = p[A]+Z; AB = p[A+1]+Z      \n    B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z      \n \n    return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                   grad(p[BA  ], x-1, y  , z   )), \n                           lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                   grad(p[BB  ], x-1, y-1, z   ))),\n                   lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                   grad(p[BA+1], x-1, y  , z-1 )), \n                           lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                   grad(p[BB+1], x-1, y-1, z-1 ))))\n                                   \ndef fade(t): \n    return t ** 3 * (t * (t * 6 - 15) + 10)\n    \ndef lerp(t, a, b):\n    return a + t * (b - a)\n    \ndef grad(hash, x, y, z):\n    h = hash & 15                      \n    u = x if h<8 else y                \n    v = y if h<4 else (x if h in (12, 14) else z)\n    return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n    p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n    print(\"%1.17f\" % perlin_noise(3.14, 42, 7))\n"}
{"id": 47978, "name": "File size distribution", "C": "#include<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n", "Python": "import sys, os\nfrom collections import Counter\n\ndef dodir(path):\n    global h\n\n    for name in os.listdir(path):\n        p = os.path.join(path, name)\n\n        if os.path.islink(p):\n            pass\n        elif os.path.isfile(p):\n            h[os.stat(p).st_size] += 1\n        elif os.path.isdir(p):\n            dodir(p)\n        else:\n            pass\n\ndef main(arg):\n    global h\n    h = Counter()\n    for dir in arg:\n        dodir(dir)\n\n    s = n = 0\n    for k, v in sorted(h.items()):\n        print(\"Size %d -> %d file(s)\" % (k, v))\n        n += v\n        s += k * v\n    print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])\n"}
{"id": 47979, "name": "Unix_ls", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 47980, "name": "Rendezvous", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <pthread.h>\n\n\n\n\ntypedef struct rendezvous {\n    pthread_mutex_t lock;        \n    pthread_cond_t cv_entering;  \n    pthread_cond_t cv_accepting; \n    pthread_cond_t cv_done;      \n    int (*accept_func)(void*);   \n    int entering;                \n    int accepting;               \n    int done;                    \n} rendezvous_t;\n\n\n#define RENDEZVOUS_INITILIZER(accept_function) {   \\\n        .lock         = PTHREAD_MUTEX_INITIALIZER, \\\n        .cv_entering  = PTHREAD_COND_INITIALIZER,  \\\n        .cv_accepting = PTHREAD_COND_INITIALIZER,  \\\n        .cv_done      = PTHREAD_COND_INITIALIZER,  \\\n        .accept_func  = accept_function,           \\\n        .entering     = 0,                         \\\n        .accepting    = 0,                         \\\n        .done         = 0,                         \\\n    }\n\nint enter_rendezvous(rendezvous_t *rv, void* data)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n\n    rv->entering++;\n    pthread_cond_signal(&rv->cv_entering);\n\n    while (!rv->accepting) {\n        \n        pthread_cond_wait(&rv->cv_accepting, &rv->lock);\n    }\n\n    \n    int ret = rv->accept_func(data);\n\n    \n    rv->done = 1;\n    pthread_cond_signal(&rv->cv_done);\n\n    rv->entering--;\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n\n    return ret;\n}\n\nvoid accept_rendezvous(rendezvous_t *rv)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n    rv->accepting = 1;\n\n    while (!rv->entering) {\n        \n        pthread_cond_wait(&rv->cv_entering, &rv->lock);\n    }\n\n    pthread_cond_signal(&rv->cv_accepting);\n\n    while (!rv->done) {\n        \n        pthread_cond_wait(&rv->cv_done, &rv->lock);\n    }\n    rv->done = 0;\n\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n}\n\n\n\ntypedef struct printer {\n    rendezvous_t rv;\n    struct printer *backup;\n    int id;\n    int remaining_lines;\n} printer_t;\n\ntypedef struct print_args {\n    struct printer *printer;\n    const char* line;\n} print_args_t;\n\nint print_line(printer_t *printer, const char* line) {\n    print_args_t args;\n    args.printer = printer;\n    args.line = line;\n    return enter_rendezvous(&printer->rv, &args);\n}\n\nint accept_print(void* data) {\n    \n    print_args_t *args = (print_args_t*)data;\n    printer_t *printer = args->printer;\n    const char* line = args->line;\n\n    if (printer->remaining_lines) {\n        \n        printf(\"%d: \", printer->id);\n        while (*line != '\\0') {\n            putchar(*line++);\n        }\n        putchar('\\n');\n        printer->remaining_lines--;\n        return 1;\n    }\n    else if (printer->backup) {\n        \n        return print_line(printer->backup, line);\n    }\n    else {\n        \n        return -1;\n    }\n}\n\nprinter_t backup_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = NULL,\n    .id = 2,\n    .remaining_lines = 5,\n};\n\nprinter_t main_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = &backup_printer,\n    .id = 1,\n    .remaining_lines = 5,\n};\n\nvoid* printer_thread(void* thread_data) {\n    printer_t *printer = (printer_t*) thread_data;\n    while (1) {\n        accept_rendezvous(&printer->rv);\n    }\n}\n\ntypedef struct poem {\n    char* name;\n    char* lines[];\n} poem_t;\n\npoem_t humpty_dumpty = {\n    .name = \"Humpty Dumpty\",\n    .lines = {\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men\",\n        \"Couldn't put Humpty together again.\",\n        \"\"\n    },\n};\n\npoem_t mother_goose = {\n    .name = \"Mother Goose\",\n    .lines = {\n        \"Old Mother Goose\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n        \"\"\n    },\n};\n\nvoid* poem_thread(void* thread_data) {\n    poem_t *poem = (poem_t*)thread_data;\n\n    for (unsigned i = 0; poem->lines[i] != \"\"; i++) {\n        int ret = print_line(&main_printer, poem->lines[i]);\n        if (ret < 0) {\n            printf(\"      %s out of ink!\\n\", poem->name);\n            exit(1);\n        }\n    }\n    return NULL;\n}\n\nint main(void)\n{\n    pthread_t threads[4];\n\n    pthread_create(&threads[0], NULL, poem_thread,    &humpty_dumpty);\n    pthread_create(&threads[1], NULL, poem_thread,    &mother_goose);\n    pthread_create(&threads[2], NULL, printer_thread, &main_printer);\n    pthread_create(&threads[3], NULL, printer_thread, &backup_printer);\n\n    pthread_join(threads[0], NULL);\n    pthread_join(threads[1], NULL);\n    pthread_cancel(threads[2]);\n    pthread_cancel(threads[3]);\n\n    return 0;\n}\n", "Python": "\nfrom __future__ import annotations\n\nimport asyncio\nimport sys\n\nfrom typing import Optional\nfrom typing import TextIO\n\n\nclass OutOfInkError(Exception):\n    \n\n\nclass Printer:\n    def __init__(self, name: str, backup: Optional[Printer]):\n        self.name = name\n        self.backup = backup\n\n        self.ink_level: int = 5\n        self.output_stream: TextIO = sys.stdout\n\n    async def print(self, msg):\n        if self.ink_level <= 0:\n            if self.backup:\n                await self.backup.print(msg)\n            else:\n                raise OutOfInkError(self.name)\n        else:\n            self.ink_level -= 1\n            self.output_stream.write(f\"({self.name}): {msg}\\n\")\n\n\nasync def main():\n    reserve = Printer(\"reserve\", None)\n    main = Printer(\"main\", reserve)\n\n    humpty_lines = [\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men,\",\n        \"Couldn't put Humpty together again.\",\n    ]\n\n    goose_lines = [\n        \"Old Mother Goose,\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air,\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n    ]\n\n    async def print_humpty():\n        for line in humpty_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Humpty Dumpty out of ink!\")\n                break\n\n    async def print_goose():\n        for line in goose_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Mother Goose out of ink!\")\n                break\n\n    await asyncio.gather(print_goose(), print_humpty())\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main(), debug=True)\n"}
{"id": 47981, "name": "First class environments", "C": "#include <stdio.h>\n\n#define JOBS 12\n#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf(\"\\n\"); switch_to(++a))\ntypedef struct { int seq, cnt; } env_t;\n\nenv_t env[JOBS] = {{0, 0}};\nint *seq, *cnt;\n\nvoid hail()\n{\n\tprintf(\"% 4d\", *seq);\n\tif (*seq == 1) return;\n\t++*cnt;\n\t*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;\n}\n\nvoid switch_to(int id)\n{\n\tseq = &env[id].seq;\n\tcnt = &env[id].cnt;\n}\n\nint main()\n{\n\tint i;\n\tjobs(i) { env[i].seq = i + 1; }\n\nagain:\tjobs(i) { hail(); }\n\tjobs(i) { if (1 != *seq) goto again; }\n\n\tprintf(\"COUNTS:\\n\");\n\tjobs(i) { printf(\"% 4d\", *cnt); }\n\n\treturn 0;\n}\n", "Python": "environments = [{'cnt':0, 'seq':i+1} for i in range(12)]\n\ncode = \n\nwhile any(env['seq'] > 1 for env in environments):\n    for env in environments:\n        exec(code, globals(), env)\n    print()\n\nprint('Counts')\nfor env in environments:\n    print('% 4d' % env['cnt'], end='')\nprint()\n"}
{"id": 47982, "name": "UTF-8 encode and decode", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n"}
{"id": 47983, "name": "Xiaolin Wu's line algorithm", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Python": "\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n    return x - int(x)\n\ndef _rfpart(x):\n    return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n    \n    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n    c = compose_color(img.getpixel(xy), color)\n    img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n    \n    x1, y1 = p1\n    x2, y2 = p2\n    dx, dy = x2-x1, y2-y1\n    steep = abs(dx) < abs(dy)\n    p = lambda px, py: ((px,py), (py,px))[steep]\n\n    if steep:\n        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n    if x2 < x1:\n        x1, x2, y1, y2 = x2, x1, y2, y1\n\n    grad = dy/dx\n    intery = y1 + _rfpart(x1) * grad\n    def draw_endpoint(pt):\n        x, y = pt\n        xend = round(x)\n        yend = y + grad * (xend - x)\n        xgap = _rfpart(x + 0.5)\n        px, py = int(xend), int(yend)\n        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n        return px\n\n    xstart = draw_endpoint(p(*p1)) + 1\n    xend = draw_endpoint(p(*p2))\n\n    for x in range(xstart, xend):\n        y = int(intery)\n        putpixel(img, p(x, y), color, _rfpart(intery))\n        putpixel(img, p(x, y+1), color, _fpart(intery))\n        intery += grad\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print 'usage: python xiaolinwu.py [output-file]'\n        sys.exit(-1)\n\n    blue = (0, 0, 255)\n    yellow = (255, 255, 0)\n    img = Image.new(\"RGB\", (500,500), blue)\n    for a in range(10, 431, 60):\n        draw_line(img, (10, 10), (490, a), yellow)\n        draw_line(img, (10, 10), (a, 490), yellow)\n    draw_line(img, (10, 10), (490, 490), yellow)\n    filename = sys.argv[1]\n    img.save(filename)\n    print 'image saved to', filename\n"}
{"id": 47984, "name": "Keyboard macros", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/keysym.h>\n\nint main()\n{\n  Display *d;\n  XEvent event;\n  \n  d = XOpenDisplay(NULL);\n  if ( d != NULL ) {\n                \n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), \n\t     Mod1Mask,  \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), \n\t     Mod1Mask, \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n\n    for(;;)\n    {\n      XNextEvent(d, &event);\n      if ( event.type == KeyPress ) {\n\tKeySym s = XLookupKeysym(&event.xkey, 0);\n\tif ( s == XK_F7 ) {\n\t  printf(\"something's happened\\n\");\n\t} else if ( s == XK_F6 ) {\n\t  break;\n\t}\n      }\n    }\n\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), Mod1Mask, DefaultRootWindow(d));\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), Mod1Mask, DefaultRootWindow(d));\n  }\n  return EXIT_SUCCESS;\n}\n", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n"}
{"id": 47985, "name": "McNuggets problem", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n"}
{"id": 47986, "name": "McNuggets problem", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n"}
{"id": 47987, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 47988, "name": "Extreme floating point values", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 47989, "name": "Extreme floating point values", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 47990, "name": "Pseudo-random numbers_Xorshift star", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 47991, "name": "Four is the number of letters in the ...", "C": "#include <ctype.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\ntypedef struct word_tag {\n    size_t offset;\n    size_t length;\n} word_t;\n\ntypedef struct word_list_tag {\n    GArray* words;\n    GString* str;\n} word_list;\n\nvoid word_list_create(word_list* words) {\n    words->words = g_array_new(FALSE, FALSE, sizeof(word_t));\n    words->str = g_string_new(NULL);\n}\n\nvoid word_list_destroy(word_list* words) {\n    g_string_free(words->str, TRUE);\n    g_array_free(words->words, TRUE);\n}\n\nvoid word_list_clear(word_list* words) {\n    g_string_truncate(words->str, 0);\n    g_array_set_size(words->words, 0);\n}\n\nvoid word_list_append(word_list* words, const char* str) {\n    size_t offset = words->str->len;\n    size_t len = strlen(str);\n    g_string_append_len(words->str, str, len);\n    word_t word;\n    word.offset = offset;\n    word.length = len;\n    g_array_append_val(words->words, word);\n}\n\nword_t* word_list_get(word_list* words, size_t index) {\n    return &g_array_index(words->words, word_t, index);\n}\n\nvoid word_list_extend(word_list* words, const char* str) {\n    word_t* word = word_list_get(words, words->words->len - 1);\n    size_t len = strlen(str);\n    word->length += len;\n    g_string_append_len(words->str, str, len);\n}\n\nsize_t append_number_name(word_list* words, integer n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        word_list_append(words, get_small_name(&small[n], ordinal));\n        count = 1;\n    } else if (n < 100) {\n        if (n % 10 == 0) {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], false));\n            word_list_extend(words, \"-\");\n            word_list_extend(words, get_small_name(&small[n % 10], ordinal));\n        }\n        count = 1;\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        count += append_number_name(words, n/p, false);\n        if (n % p == 0) {\n            word_list_append(words, get_big_name(num, ordinal));\n            ++count;\n        } else {\n            word_list_append(words, get_big_name(num, false));\n            ++count;\n            count += append_number_name(words, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(word_list* words, size_t index) {\n    const word_t* word = word_list_get(words, index);\n    size_t letters = 0;\n    const char* s = words->str->str + word->offset;\n    for (size_t i = 0, n = word->length; i < n; ++i) {\n        if (isalpha((unsigned char)s[i]))\n            ++letters;\n    }\n    return letters;\n}\n\nvoid sentence(word_list* result, size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    word_list_clear(result);\n    size_t n = sizeof(words)/sizeof(words[0]);\n    for (size_t i = 0; i < n; ++i)\n        word_list_append(result, words[i]);\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result, i), false);\n        word_list_append(result, \"in\");\n        word_list_append(result, \"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        \n        word_list_extend(result, \",\");\n    }\n}\n\nsize_t sentence_length(const word_list* words) {\n    size_t n = words->words->len;\n    if (n == 0)\n        return 0;\n    return words->str->len + n - 1;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    size_t n = 201;\n    word_list result = { 0 };\n    word_list_create(&result);\n    sentence(&result, n);\n    printf(\"Number of letters in first %'lu words in the sequence:\\n\", n);\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            printf(\"%c\", i % 25 == 0 ? '\\n' : ' ');\n        printf(\"%'2lu\", count_letters(&result, i));\n    }\n    printf(\"\\nSentence length: %'lu\\n\", sentence_length(&result));\n    for (n = 1000; n <= 10000000; n *= 10) {\n        sentence(&result, n);\n        const word_t* word = word_list_get(&result, n - 1);\n        const char* s = result.str->str + word->offset;\n        printf(\"The %'luth word is '%.*s' and has %lu letters. \", n,\n               (int)word->length, s, count_letters(&result, n - 1));\n        printf(\"Sentence length: %'lu\\n\" , sentence_length(&result));\n    }\n    word_list_destroy(&result);\n    return 0;\n}\n", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n"}
{"id": 47992, "name": "ASCII art diagram converter", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n"}
{"id": 47993, "name": "Levenshtein distance_Alignment", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}\n", "Python": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n    result = \"\"\n    pos, removed = 0, 0\n    for x in ndiff(str1, str2):\n        if pos<len(str1) and str1[pos] == x[2]:\n          pos += 1\n          result += x[2]\n          if x[0] == \"-\":\n              removed += 1\n          continue\n        else:\n          if removed > 0:\n            removed -=1\n          else:\n            result += \"-\"\n    print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")\n"}
{"id": 47994, "name": "Compare sorting algorithms' performance", "C": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n", "Python": "def builtinsort(x):\n    x.sort()\n\ndef partition(seq, pivot):\n   low, middle, up = [], [], []\n   for x in seq:\n       if x < pivot:\n           low.append(x)\n       elif x == pivot:\n           middle.append(x)\n       else:\n           up.append(x)\n   return low, middle, up\nimport random\ndef qsortranpart(seq):\n   size = len(seq)\n   if size < 2: return seq\n   low, middle, up = partition(seq, random.choice(seq))\n   return qsortranpart(low) + middle + qsortranpart(up)\n"}
{"id": 47995, "name": "Compare sorting algorithms' performance", "C": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n", "Python": "def builtinsort(x):\n    x.sort()\n\ndef partition(seq, pivot):\n   low, middle, up = [], [], []\n   for x in seq:\n       if x < pivot:\n           low.append(x)\n       elif x == pivot:\n           middle.append(x)\n       else:\n           up.append(x)\n   return low, middle, up\nimport random\ndef qsortranpart(seq):\n   size = len(seq)\n   if size < 2: return seq\n   low, middle, up = partition(seq, random.choice(seq))\n   return qsortranpart(low) + middle + qsortranpart(up)\n"}
{"id": 47996, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 47997, "name": "Parse command-line arguments", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n"}
{"id": 47998, "name": "Parse command-line arguments", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n"}
{"id": 47999, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n"}
{"id": 48000, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n"}
{"id": 48001, "name": "Simulate input_Keyboard", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n\nint main(int argc, char *argv[])\n{\n  Display *dpy;\n  Window win;\n  GC gc;\n  int scr;\n  Atom WM_DELETE_WINDOW;\n  XEvent ev;\n  XEvent ev2;\n  KeySym keysym;\n  int loop;\n\n  \n  dpy = XOpenDisplay(NULL);\n  if (dpy == NULL) {\n    fputs(\"Cannot open display\", stderr);\n    exit(1);\n  }\n  scr = XDefaultScreen(dpy);\n\n  \n  win = XCreateSimpleWindow(dpy,\n          XRootWindow(dpy, scr),\n          \n          10, 10, 300, 200, 1,\n          \n          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));\n\n  \n  XStoreName(dpy, win, argv[0]);\n\n  \n  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);\n\n  \n  XMapWindow(dpy, win);\n  XFlush(dpy);\n\n  \n  gc = XDefaultGC(dpy, scr);\n\n  \n  WM_DELETE_WINDOW = XInternAtom(dpy, \"WM_DELETE_WINDOW\", True);\n  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);\n\n  \n  loop = 1;\n  while (loop) {\n    XNextEvent(dpy, &ev);\n    switch (ev.type)\n    {\n      case Expose:\n        \n        {\n          char msg1[] = \"Clic in the window to generate\";\n          char msg2[] = \"a key press event\";\n          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);\n          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);\n        }\n        break;\n\n      case ButtonPress:\n        puts(\"ButtonPress event received\");\n        \n        ev2.type = KeyPress;\n        ev2.xkey.state = ShiftMask;\n        ev2.xkey.keycode = 24 + (rand() % 33);\n        ev2.xkey.same_screen = True;\n        XSendEvent(dpy, win, True, KeyPressMask, &ev2);\n        break;\n   \n      case ClientMessage:\n        \n        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)\n          loop = 0;\n        break;\n   \n      case KeyPress:\n        \n        puts(\"KeyPress event received\");\n        printf(\"> keycode: %d\\n\", ev.xkey.keycode);\n        \n        keysym = XLookupKeysym(&(ev.xkey), 0);\n        if (keysym == XK_q ||\n            keysym == XK_Escape) {\n          loop = 0;\n        } else {\n          char buffer[] = \"  \";\n          int nchars = XLookupString(\n                &(ev.xkey),\n                buffer,\n                2,  \n                &keysym,\n                NULL );\n          if (nchars == 1)\n            printf(\"> Key '%c' pressed\\n\", buffer[0]);\n        }\n        break;\n    }\n  }\n  XDestroyWindow(dpy, win);\n  \n  XCloseDisplay(dpy);\n  return 1;\n}\n", "Python": "import autopy\nautopy.key.type_string(\"Hello, world!\") \nautopy.key.type_string(\"Hello, world!\", wpm=60) \nautopy.key.tap(autopy.key.Code.RETURN)\nautopy.key.tap(autopy.key.Code.F1)\nautopy.key.tap(autopy.key.Code.LEFT_ARROW)\n"}
{"id": 48002, "name": "Peaceful chess queen armies", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n"}
{"id": 48003, "name": "Metaprogramming", "C": "\n#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]\n\n#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)\n#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)\n#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)\n\nCOMPILE_TIME_ASSERT(sizeof(long)==8); \nint main()\n{\n    COMPILE_TIME_ASSERT(sizeof(int)==4); \n}\n", "Python": "from macropy.core.macros import *\nfrom macropy.core.quotes import macros, q, ast, u\n\nmacros = Macros()\n\n@macros.expr\ndef expand(tree, **kw):\n    addition = 10\n    return q[lambda x: x * ast[tree] + u[addition]]\n"}
{"id": 48004, "name": "Numbers with same digit set in base 10 and base 16", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "col = 0\nfor i in range(100000):\n    if set(str(i)) == set(hex(i)[2:]):\n        col += 1\n        print(\"{:7}\".format(i), end='\\n'[:col % 10 == 0])\nprint()\n"}
{"id": 48005, "name": "Largest prime factor", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( long int n ) {\n    int i=3;\n    if(!(n%2)) return 0;\n    while( i*i < n ) {\n        if(!(n%i)) return 0;\n        i+=2;\n    }\n    return 1;\n}\n\nint main(void) {\n    long int n=600851475143, j=3;\n\n    while(!isprime(n)) {\n        if(!(n%j)) n/=j;\n        j+=2;\n    }\n    printf( \"%ld\\n\", n );\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    n = 600851475143\n    j = 3\n    while not isPrime(n):\n        if n % j == 0:\n            n /= j\n        j += 2\n    print(n);\n"}
{"id": 48006, "name": "Largest prime factor", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( long int n ) {\n    int i=3;\n    if(!(n%2)) return 0;\n    while( i*i < n ) {\n        if(!(n%i)) return 0;\n        i+=2;\n    }\n    return 1;\n}\n\nint main(void) {\n    long int n=600851475143, j=3;\n\n    while(!isprime(n)) {\n        if(!(n%j)) n/=j;\n        j+=2;\n    }\n    printf( \"%ld\\n\", n );\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    n = 600851475143\n    j = 3\n    while not isPrime(n):\n        if n % j == 0:\n            n /= j\n        j += 2\n    print(n);\n"}
{"id": 48007, "name": "Largest proper divisor of n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "Python": "def lpd(n):\n    for i in range(n-1,0,-1):\n        if n%i==0: return i\n    return 1\n\nfor i in range(1,101):\n    print(\"{:3}\".format(lpd(i)), end=i%10==0 and '\\n' or '')\n"}
{"id": 48008, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 48009, "name": "Active Directory_Search for a user", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n"}
{"id": 48010, "name": "Singular value decomposition", "C": "#include <stdio.h>\n#include <gsl/gsl_linalg.h>\n\n\nvoid gsl_matrix_print(const gsl_matrix *M) {\n    int rows = M->size1;\n    int cols = M->size2;\n    for (int i = 0; i < rows; i++) {\n        printf(\"|\");\n        for (int j = 0; j < cols; j++) {\n            printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n        }\n        printf(\"\\b|\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main(){\n    double a[] = {3, 0, 4, 5};\n    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n    gsl_matrix *V = gsl_matrix_alloc(2, 2);\n    gsl_vector *S = gsl_vector_alloc(2);\n    gsl_vector *work = gsl_vector_alloc(2);\n\n    \n    gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n    gsl_matrix_transpose(V);\n    double s[] = {S->data[0], 0, 0, S->data[1]};\n    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n    printf(\"U:\\n\");\n    gsl_matrix_print(&A.matrix);\n\n    printf(\"S:\\n\");\n    gsl_matrix_print(&SM.matrix);\n\n    printf(\"VT:\\n\");\n    gsl_matrix_print(V);\n    \n    gsl_matrix_free(V);\n    gsl_vector_free(S);\n    gsl_vector_free(work);\n    return 0;\n}\n", "Python": "from numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n"}
{"id": 48011, "name": "Sum of first n cubes", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n"}
{"id": 48012, "name": "Test integerness", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n"}
{"id": 48013, "name": "Execute a system command", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 48014, "name": "XML validation", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 48015, "name": "Longest increasing subsequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 48016, "name": "Death Star", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n"}
{"id": 48017, "name": "Lucky and even lucky numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define LUCKY_SIZE 60000\nint luckyOdd[LUCKY_SIZE];\nint luckyEven[LUCKY_SIZE];\n\nvoid compactLucky(int luckyArray[]) {\n    int i, j, k;\n\n    for (i = 0; i < LUCKY_SIZE; i++) {\n        if (luckyArray[i] == 0) {\n            j = i;\n            break;\n        }\n    }\n\n    for (j = i + 1; j < LUCKY_SIZE; j++) {\n        if (luckyArray[j] > 0) {\n            luckyArray[i++] = luckyArray[j];\n        }\n    }\n\n    for (; i < LUCKY_SIZE; i++) {\n        luckyArray[i] = 0;\n    }\n}\n\nvoid initialize() {\n    int i, j;\n\n    \n    for (i = 0; i < LUCKY_SIZE; i++) {\n        luckyEven[i] = 2 * i + 2;\n        luckyOdd[i] = 2 * i + 1;\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyOdd[i] > 0) {\n            for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {\n                luckyOdd[j] = 0;\n            }\n            compactLucky(luckyOdd);\n        }\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyEven[i] > 0) {\n            for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {\n                luckyEven[j] = 0;\n            }\n            compactLucky(luckyEven);\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[j] == 0 || luckyEven[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyEven[i] != 0; i++) {\n            if (luckyEven[i] > k) {\n                break;\n            }\n            if (luckyEven[i] > j) {\n                printf(\" %d\", luckyEven[i]);\n            }\n        }\n    } else {\n        if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyOdd[i] != 0; i++) {\n            if (luckyOdd[i] > k) {\n                break;\n            }\n            if (luckyOdd[i] > j) {\n                printf(\" %d\", luckyOdd[i]);\n            }\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyEven[i]);\n        }\n    } else {\n        if (luckyOdd[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyOdd[i]);\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (luckyEven[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even number %d=%d\\n\", j, luckyEven[j - 1]);\n    } else {\n        if (luckyOdd[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky number %d=%d\\n\", j, luckyOdd[j - 1]);\n    }\n}\n\nvoid help() {\n    printf(\"./lucky j [k] [--lucky|--evenLucky]\\n\");\n    printf(\"\\n\");\n    printf(\"       argument(s)        |  what is displayed\\n\");\n    printf(\"==============================================\\n\");\n    printf(\"-j=m                      |  mth lucky number\\n\");\n    printf(\"-j=m  --lucky             |  mth lucky number\\n\");\n    printf(\"-j=m  --evenLucky         |  mth even lucky number\\n\");\n    printf(\"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\");\n    printf(\"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\");\n}\n\nvoid process(int argc, char *argv[]) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    bool good = false;\n    int i;\n\n    for (i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    fprintf(stderr, \"Unknown long argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    fprintf(stderr, \"Unknown short argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            fprintf(stderr, \"Unknown argument: [%s]\\n\", argv[i]);\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n}\n\nvoid test() {\n    printRange(1, 20, false);\n    printRange(1, 20, true);\n\n    printBetween(6000, 6100, false);\n    printBetween(6000, 6100, true);\n\n    printSingle(10000, false);\n    printSingle(10000, true);\n}\n\nint main(int argc, char *argv[]) {\n    initialize();\n\n    \n\n    if (argc < 2) {\n        help();\n        return 1;\n    }\n    process(argc, argv);\n\n    return 0;\n}\n", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n"}
{"id": 48018, "name": "Scope modifiers", "C": "int a;          \nstatic int p;   \n\nextern float v; \n\n\nint code(int arg)\n{\n  int myp;        \n                  \n                  \n  static int myc; \n                  \n                  \n                  \n                  \n}\n\n\nstatic void code2(void)\n{\n  v = v * 1.02;    \n  \n}\n", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n"}
{"id": 48019, "name": "Simple database", "C": "#include <stdio.h>\n#include <stdlib.h> \n#include <string.h> \n#define _XOPEN_SOURCE \n#define __USE_XOPEN\n#include <time.h>\n#define DB \"database.csv\" \n#define TRY(a)  if (!(a)) {perror(#a);exit(1);}\n#define TRY2(a) if((a)<0) {perror(#a);exit(1);}\n#define FREE(a) if(a) {free(a);a=NULL;}\n#define sort_by(foo) \\\nstatic int by_##foo (const void*p1, const void*p2) { \\\n    return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); }\ntypedef struct db {\n    char title[26];\n    char first_name[26];\n    char last_name[26];\n    time_t date;\n    char publ[100];\n    struct db *next;\n}\ndb_t,*pdb_t;\ntypedef int (sort)(const void*, const void*);\nenum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY};\nstatic pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby);\nstatic char *time2str (time_t *time);\nstatic time_t str2time (char *date);\n\nsort_by(last_name);\nsort_by(title);\nstatic int by_date(pdb_t *p1, pdb_t *p2);\n\nint main (int argc, char **argv) {\n    char buf[100];\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    db_t db;\n    db.next=NULL;\n    pdb_t dblist;\n    int i;\n    FILE *f;\n    TRY (f=fopen(DB,\"a+\"));\n    if (argc<2) {\nusage:  printf (\"Usage: %s [commands]\\n\"\n        \"-c  Create new entry.\\n\"\n        \"-p  Print the latest entry.\\n\"\n        \"-t  Print all entries sorted by title.\\n\"\n        \"-d  Print all entries sorted by date.\\n\"\n        \"-a  Print all entries sorted by author.\\n\",argv[0]);\n        fclose (f);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n        case CREATE:\n        printf(\"-c  Create a new entry.\\n\");\n        printf(\"Title           :\");if((scanf(\" %25[^\\n]\",db.title     ))<0)break;\n        printf(\"Author Firstname:\");if((scanf(\" %25[^\\n]\",db.first_name))<0)break;\n        printf(\"Author Lastname :\");if((scanf(\" %25[^\\n]\",db.last_name ))<0)break;\n        printf(\"Date 10-12-2000 :\");if((scanf(\" %10[^\\n]\",buf          ))<0)break;\n        printf(\"Publication     :\");if((scanf(\" %99[^\\n]\",db.publ      ))<0)break;\n        db.date=str2time (buf);\n        dao (CREATE,f,&db,NULL);\n        break;\n        case PRINT:\n        printf (\"-p  Print the latest entry.\\n\");\n        while (!feof(f)) dao (READLINE,f,&db,NULL);\n        dao (PRINT,f,&db,NULL);\n        break;\n        case TITLE:\n        printf (\"-t  Print all entries sorted by title.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_title);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case DATE:\n        printf (\"-d  Print all entries sorted by date.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,(int (*)(const void *,const  void *)) by_date);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case AUTH:\n        printf (\"-a  Print all entries sorted by author.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_last_name);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        default: {\n            printf (\"Unknown command: %s.\\n\",strlen(argv[1])<10?argv[1]:\"\");\n            goto usage;\n    }   }\n    fclose (f);\n    return 0;\n}\n\nstatic pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) {\n    pdb_t *pdb=NULL,rec=NULL,hd=NULL;\n    int i=0,ret;\n    char buf[100];\n    switch (cmd) {\n        case CREATE:\n        fprintf (f,\"\\\"%s\\\",\",in_db->title);\n        fprintf (f,\"\\\"%s\\\",\",in_db->first_name);\n        fprintf (f,\"\\\"%s\\\",\",in_db->last_name);\n        fprintf (f,\"\\\"%s\\\",\",time2str(&in_db->date));\n        fprintf (f,\"\\\"%s\\\" \\n\",in_db->publ);\n        break;\n        case PRINT:\n        for (;in_db;i++) {\n            printf (\"Title       : %s\\n\",     in_db->title);\n            printf (\"Author      : %s %s\\n\",  in_db->first_name, in_db->last_name);\n            printf (\"Date        : %s\\n\",     time2str(&in_db->date));\n            printf (\"Publication : %s\\n\\n\",   in_db->publ);\n            if (!((i+1)%3)) {\n                printf (\"Press Enter to continue.\\n\");\n                ret = scanf (\"%*[^\\n]\");\n                if (ret<0) return rec; \n                else getchar();\n            }\n            in_db=in_db->next;\n        }\n        break;\n        case READLINE:\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->title     ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->first_name))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->last_name ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",buf              ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\" \",in_db->publ      ))<0)break;\n        in_db->date=str2time (buf);\n        break;\n        case READ:\n        while (!feof(f)) {\n            dao (READLINE,f,in_db,NULL);\n            TRY (rec=malloc(sizeof(db_t)));\n            *rec=*in_db; \n            rec->next=hd;\n            hd=rec;i++;\n        }\n        if (i<2) {\n            puts (\"Empty database. Please create some entries.\");\n            fclose (f);\n            exit (0);\n        }\n        break;\n        case SORT:\n        rec=in_db;\n        for (;in_db;i++) in_db=in_db->next;\n        TRY (pdb=malloc(i*sizeof(pdb_t)));\n        in_db=rec;\n        for (i=0;in_db;i++) {\n            pdb[i]=in_db;\n            in_db=in_db->next;\n        }\n        qsort (pdb,i,sizeof in_db,sortby);\n        pdb[i-1]->next=NULL;\n        for (i=i-1;i;i--) {\n            pdb[i-1]->next=pdb[i];\n        }\n        rec=pdb[0];\n        FREE (pdb);\n        pdb=NULL;\n        break;\n        case DESTROY: {\n            while ((rec=in_db)) {\n                in_db=in_db->next;\n                FREE (rec);\n    }   }   }\n    return rec;\n}\n\nstatic char *time2str (time_t *time) {\n    static char buf[255];\n    struct tm *ptm;\n    ptm=localtime (time);\n    strftime(buf, 255, \"%m-%d-%Y\", ptm);\n    return buf;\n}\n\nstatic time_t str2time (char *date) {\n    struct tm tm;\n    memset (&tm, 0, sizeof(struct tm));\n    strptime(date, \"%m-%d-%Y\", &tm);\n    return mktime(&tm);\n}\n\nstatic int by_date (pdb_t *p1, pdb_t *p2) {\n    if ((*p1)->date < (*p2)->date) {\n        return -1;\n    }\n    else return ((*p1)->date > (*p2)->date);\n}\n", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n"}
{"id": 48020, "name": "Total circles area", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 48021, "name": "Total circles area", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 48022, "name": "Hough transform", "C": "#include \"SL_Generated.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nint main( int argc, char** argv )\n{\n    string fileName = \"Pentagon.bmp\";\n    if(argc > 1) fileName = argv[1];\n    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);\n    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);\n    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);\n    int threads = 0; if(argc > 5) threads = atoi(argv[5]);\n    char titleBuffer[200];\n    SLTimer t;\n\n    CImg<int> image(fileName.c_str());\n    int imageDimensions[] = {image.height(), image.width(), 0};\n    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);\n    Sequence< Sequence<int> > result;\n\n    sl_init(threads);\n\n    t.start();\n    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);\n    t.stop();\n    \n    CImg<int> resultImage(result[1].size(), result.size());\n    for(int y = 0; y < result.size(); y++)\n        for(int x = 0; x < result[y+1].size(); x++)\n            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];\n    \n    sprintf(titleBuffer, \"SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\\0\", \n                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());\n    resultImage.display(titleBuffer);\n\n    sl_done();\n    return 0;\n}\n", "Python": "from math import hypot, pi, cos, sin\nfrom PIL import Image\n\n\ndef hough(im, ntx=460, mry=360):\n    \"Calculate Hough transform.\"\n    pim = im.load()\n    nimx, mimy = im.size\n    mry = int(mry/2)*2          \n    him = Image.new(\"L\", (ntx, mry), 255)\n    phim = him.load()\n\n    rmax = hypot(nimx, mimy)\n    dr = rmax / (mry/2)\n    dth = pi / ntx\n\n    for jx in xrange(nimx):\n        for iy in xrange(mimy):\n            col = pim[jx, iy]\n            if col == 255: continue\n            for jtx in xrange(ntx):\n                th = dth * jtx\n                r = jx*cos(th) + iy*sin(th)\n                iry = mry/2 + int(r/dr+0.5)\n                phim[jtx, iry] -= 1\n    return him\n\n\ndef test():\n    \"Test Hough transform with pentagon.\"\n    im = Image.open(\"pentagon.png\").convert(\"L\")\n    him = hough(im)\n    him.save(\"ho5.bmp\")\n\n\nif __name__ == \"__main__\": test()\n"}
{"id": 48023, "name": "Verify distribution uniformity_Chi-squared test", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n"}
{"id": 48024, "name": "Welch's t-test", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 48025, "name": "Welch's t-test", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 48026, "name": "Topological sort_Extracted top item", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n"}
{"id": 48027, "name": "Topological sort_Extracted top item", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n"}
{"id": 48028, "name": "Brace expansion", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 48029, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 48030, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 48031, "name": "Superpermutation minimisation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n"}
{"id": 48032, "name": "GUI component interaction", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n"}
{"id": 48033, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 48034, "name": "Summarize and say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n"}
{"id": 48035, "name": "Spelling of ordinal numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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"}
{"id": 48036, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 48037, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n"}
{"id": 48038, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 48039, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 48040, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n"}
{"id": 48041, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 48042, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 48043, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 48044, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 48045, "name": "Simulate input_Mouse", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n", "Python": "import ctypes\n\ndef click():\n    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    \n    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    \n\nclick()\n"}
{"id": 48046, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 48047, "name": "Sunflower fractal", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n"}
{"id": 48048, "name": "Vogel's approximation method", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n"}
{"id": 48049, "name": "Vogel's approximation method", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n"}
{"id": 48050, "name": "Air mass", "C": "#include <math.h>\n#include <stdio.h>\n\n#define DEG 0.017453292519943295769236907684886127134  \n#define RE 6371000.0 \n#define DD 0.001 \n#define FIN 10000000.0 \n\nstatic double rho(double a) {\n    \n    return exp(-a / 8500.0);\n}\n\nstatic double height(double a, double z, double d) {\n    \n    \n    \n    double aa = RE + a;\n    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));\n    return hh - RE;\n}\n\nstatic double column_density(double a, double z) {\n    \n    double sum = 0.0, d = 0.0;\n    while (d < FIN) {\n        \n        double delta = DD * d;\n        if (delta < DD)\n            delta = DD;\n        sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n        d += delta;\n    }\n    return sum;\n}\n\nstatic double airmass(double a, double z) {\n    return column_density(a, z) / column_density(a, 0.0);\n}\n\nint main() {\n    puts(\"Angle     0 m              13700 m\");\n    puts(\"------------------------------------\");\n    for (double z = 0; z <= 90; z+= 5) {\n        printf(\"%2.0f      %11.8f      %11.8f\\n\",\n               z, airmass(0.0, z), airmass(13700.0, z));\n    }\n}\n", "Python": "\n\nfrom math import sqrt, cos, exp\n\nDEG = 0.017453292519943295769236907684886127134  \nRE = 6371000                                     \ndd = 0.001      \nFIN = 10000000  \n \ndef rho(a):\n    \n    return exp(-a / 8500.0)\n \ndef height(a, z, d):\n     \n    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE\n \ndef column_density(a, z):\n    \n    dsum, d = 0.0, 0.0\n    while d < FIN:\n        delta = max(dd, (dd)*d)  \n        dsum += rho(height(a, z, d + 0.5 * delta)) * delta\n        d += delta\n    return dsum\n\ndef airmass(a, z):\n    return column_density(a, z) / column_density(a, 0)\n\nprint('Angle           0 m          13700 m\\n', '-' * 36)\nfor z in range(0, 91, 5):\n    print(f\"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}\")\n"}
{"id": 48051, "name": "Day of the week of Christmas and New Year", "C": "#define _XOPEN_SOURCE\n#include <stdio.h>\n#include <time.h>\n\nint main() {\n    struct tm t[2];\n    strptime(\"2021-12-25\", \"%F\", &t[0]);\n    strptime(\"2022-01-01\", \"%F\", &t[1]);\n    for (int i=0; i<2; i++) {\n        char buf[32];\n        strftime(buf, 32, \"%F is a %A\", &t[i]);\n        puts(buf);\n    }\n    return 0;\n}\n", "Python": "import datetime\n\nweekDays = (\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\")\nthisXMas  = datetime.date(2021,12,25)\nthisXMasDay = thisXMas.weekday()\nthisXMasDayAsString = weekDays[thisXMasDay]\nprint(\"This year's Christmas is on a {}\".format(thisXMasDayAsString))\n\nnextNewYear = datetime.date(2022,1,1)\nnextNewYearDay = nextNewYear.weekday()\nnextNewYearDayAsString = weekDays[nextNewYearDay]\nprint(\"Next new year is on a {}\".format(nextNewYearDayAsString))\n"}
{"id": 48052, "name": "Formal power series", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h> \n\nenum fps_type {\n        FPS_CONST = 0,\n        FPS_ADD,\n        FPS_SUB,\n        FPS_MUL,\n        FPS_DIV,\n        FPS_DERIV,\n        FPS_INT,\n};\n\ntypedef struct fps_t *fps;\ntypedef struct fps_t {\n        int type;\n        fps s1, s2;\n        double a0;\n} fps_t;\n\nfps fps_new()\n{\n        fps x = malloc(sizeof(fps_t));\n        x->a0 = 0;\n        x->s1 = x->s2 = 0;\n        x->type = 0;\n        return x;\n}\n\n\nvoid fps_redefine(fps x, int op, fps y, fps z)\n{\n        x->type = op;\n        x->s1 = y;\n        x->s2 = z;\n}\n\nfps _binary(fps x, fps y, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->s2 = y;\n        s->type = op;\n        return s;\n}\n\nfps _unary(fps x, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->type = op;\n        return s;\n}\n\n\ndouble term(fps x, int n)\n{\n        double ret = 0;\n        int i;\n\n        switch (x->type) {\n        case FPS_CONST: return n > 0 ? 0 : x->a0;\n        case FPS_ADD:\n                ret = term(x->s1, n) + term(x->s2, n); break;\n\n        case FPS_SUB:\n                ret = term(x->s1, n) - term(x->s2, n); break;\n\n        case FPS_MUL:\n                for (i = 0; i <= n; i++)\n                        ret += term(x->s1, i) * term(x->s2, n - i);\n                break;\n\n        case FPS_DIV:\n                if (! term(x->s2, 0)) return NAN;\n\n                ret = term(x->s1, n);\n                for (i = 1; i <= n; i++)\n                        ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0);\n                break;\n\n        case FPS_DERIV:\n                ret = n * term(x->s1, n + 1);\n                break;\n\n        case FPS_INT:\n                if (!n) return x->a0;\n                ret = term(x->s1, n - 1) / n;\n                break;\n\n        default:\n                fprintf(stderr, \"Unknown operator %d\\n\", x->type);\n                exit(1);\n        }\n\n        return ret;\n}\n\n#define _add(x, y) _binary(x, y, FPS_ADD)\n#define _sub(x, y) _binary(x, y, FPS_SUB)\n#define _mul(x, y) _binary(x, y, FPS_MUL)\n#define _div(x, y) _binary(x, y, FPS_DIV)\n#define _integ(x)  _unary(x, FPS_INT)\n#define _deriv(x)  _unary(x, FPS_DERIV)\n\nfps fps_const(double a0)\n{\n        fps x = fps_new();\n        x->type = FPS_CONST;\n        x->a0 = a0;\n        return x;\n}\n\nint main()\n{\n        int i;\n        fps one = fps_const(1);\n        fps fcos = fps_new();           \n        fps fsin = _integ(fcos);        \n        fps ftan = _div(fsin, fcos);    \n\n        \n        fps_redefine(fcos, FPS_SUB, one, _integ(fsin));\n\n        fps fexp = fps_const(1);        \n        \n        fps_redefine(fexp, FPS_INT, fexp, 0);\n\n        printf(\"Sin:\");   for (i = 0; i < 10; i++) printf(\" %g\", term(fsin, i));\n        printf(\"\\nCos:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fcos, i));\n        printf(\"\\nTan:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(ftan, i));\n        printf(\"\\nExp:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fexp, i));\n\n        return 0;\n}\n", "Python": "\n\nfrom itertools import islice\nfrom fractions import Fraction\nfrom functools import reduce\ntry:\n    from itertools import izip as zip \nexcept:\n    pass\n\ndef head(n):\n    \n    return lambda seq: islice(seq, n)\n\ndef pipe(gen, *cmds):\n    \n    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)\n\ndef sinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    zero = 0\n    yield zero\n    while True:\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\n        sign = -sign\n        n +=1\n        fac *= n\n        yield zero\ndef cosinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    yield Fraction(1,fac)\n    zero = 0\n    while True:\n        n +=1\n        fac *= n\n        yield zero\n        sign = -sign\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\ndef pluspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield sum(elements)\ndef minuspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield elements[0] - sum(elements[1:])\ndef mulpower(fgen,ggen):\n    'From: http://en.wikipedia.org/wiki/Power_series\n    a,b = [],[]\n    for f,g in zip(fgen, ggen):\n        a.append(f)\n        b.append(g)\n        yield sum(f*g for f,g in zip(a, reversed(b)))\ndef constpower(n):\n    yield n\n    while True:\n        yield 0\ndef diffpower(gen):\n    'differentiatiate power series'\n    next(gen)\n    for n, an in enumerate(gen, start=1):\n        yield an*n\ndef intgpower(k=0):\n    'integrate power series with constant k'\n    def _intgpower(gen):\n        yield k\n        for n, an in enumerate(gen, start=1):\n            yield an * Fraction(1,n)\n    return _intgpower\n\n\nprint(\"cosine\")\nc = list(pipe(cosinepower(), head(10)))\nprint(c)\nprint(\"sine\")\ns = list(pipe(sinepower(), head(10)))\nprint(s)\n\nintegc = list(pipe(cosinepower(),intgpower(0), head(10)))\n\nintegs1 = list(minuspower(pipe(constpower(1), head(10)),\n                          pipe(sinepower(),intgpower(0), head(10))))\n\nassert s == integc, \"The integral of cos should be sin\"\nassert c == integs1, \"1 minus the integral of sin should be cos\"\n"}
{"id": 48053, "name": "Own digits power sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define MAX_DIGITS 9\n\nint digits[MAX_DIGITS];\n\nvoid getDigits(int i) {\n    int ix = 0;\n    while (i > 0) {\n        digits[ix++] = i % 10;\n        i /= 10;\n    }\n}\n\nint main() {\n    int n, d, i, max, lastDigit, sum, dp;\n    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};\n    printf(\"Own digits power sums for N = 3 to 9 inclusive:\\n\");\n    for (n = 3; n < 10; ++n) {\n        for (d = 2; d < 10; ++d) powers[d] *= d;\n        i = (int)pow(10, n-1);\n        max = i * 10;\n        lastDigit = 0;\n        while (i < max) {\n            if (!lastDigit) {\n                getDigits(i);\n                sum = 0;\n                for (d = 0; d < n; ++d) {\n                    dp = digits[d];\n                    sum += powers[dp];\n                }\n            } else if (lastDigit == 1) {\n                sum++;\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1];\n            }\n            if (sum == i) {\n                printf(\"%d\\n\", i);\n                if (lastDigit == 0) printf(\"%d\\n\", i + 1);\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (sum > i) {\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (lastDigit < 9) {\n                i++;\n                lastDigit++;\n            } else {\n                i++;\n                lastDigit = 0;\n            }\n        }\n    }\n    return 0;\n}\n", "Python": "\n\ndef isowndigitspowersum(integer):\n    \n    digits = [int(c) for c in str(integer)]\n    exponent = len(digits)\n    return sum(x ** exponent for x in digits) == integer\n\nprint(\"Own digits power sums for N = 3 to 9 inclusive:\")\nfor i in range(100, 1000000000):\n    if isowndigitspowersum(i):\n        print(i)\n"}
{"id": 48054, "name": "Compiler_virtual machine interpreter", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <stdint.h>\n#include <ctype.h>\n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type)  type *name = NULL;          \\\n                            int _qy_ ## name ## _p = 0;  \\\n                            int _qy_ ## name ## _max = 0\n\n#define da_redim(name)      do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n                                name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name)     _qy_ ## name ## _p = 0\n\n#define da_append(name, x)  do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n    OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n    char    *text;\n    Code_t   op;\n} Code_map;\n\nCode_map code_map[] = {\n    {\"fetch\",  FETCH},\n    {\"store\",  STORE},\n    {\"push\",   PUSH },\n    {\"add\",    ADD  },\n    {\"sub\",    SUB  },\n    {\"mul\",    MUL  },\n    {\"div\",    DIV  },\n    {\"mod\",    MOD  },\n    {\"lt\",     LT   },\n    {\"gt\",     GT   },\n    {\"le\",     LE   },\n    {\"ge\",     GE   },\n    {\"eq\",     EQ   },\n    {\"ne\",     NE   },\n    {\"and\",    AND  },\n    {\"or\",     OR   },\n    {\"neg\",    NEG  },\n    {\"not\",    NOT  },\n    {\"jmp\",    JMP  },\n    {\"jz\",     JZ   },\n    {\"prtc\",   PRTC },\n    {\"prts\",   PRTS },\n    {\"prti\",   PRTI },\n    {\"halt\",   HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n    va_list ap;\n    char buf[1000];\n\n    va_start(ap, fmt);\n    vsprintf(buf, fmt, ap);\n    va_end(ap);\n    printf(\"error: %s\\n\", buf);\n    exit(1);\n}\n\n\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n    int32_t *sp = &data[g_size + 1];\n    const code *pc = obj;\n\n    again:\n    switch (*pc++) {\n        case FETCH: *sp++ = data[*(int32_t *)pc];  pc += sizeof(int32_t); goto again;\n        case STORE: data[*(int32_t *)pc] = *--sp;  pc += sizeof(int32_t); goto again;\n        case PUSH:  *sp++ = *(int32_t *)pc;        pc += sizeof(int32_t); goto again;\n        case ADD:   sp[-2] += sp[-1]; --sp;                             goto again;\n        case SUB:   sp[-2] -= sp[-1]; --sp;                             goto again;\n        case MUL:   sp[-2] *= sp[-1]; --sp;                             goto again;\n        case DIV:   sp[-2] /= sp[-1]; --sp;                             goto again;\n        case MOD:   sp[-2] %= sp[-1]; --sp;                             goto again;\n        case LT:    sp[-2] = sp[-2] <  sp[-1]; --sp;                    goto again;\n        case GT:    sp[-2] = sp[-2] >  sp[-1]; --sp;                    goto again;\n        case LE:    sp[-2] = sp[-2] <= sp[-1]; --sp;                    goto again;\n        case GE:    sp[-2] = sp[-2] >= sp[-1]; --sp;                    goto again;\n        case EQ:    sp[-2] = sp[-2] == sp[-1]; --sp;                    goto again;\n        case NE:    sp[-2] = sp[-2] != sp[-1]; --sp;                    goto again;\n        case AND:   sp[-2] = sp[-2] && sp[-1]; --sp;                    goto again;\n        case OR:    sp[-2] = sp[-2] || sp[-1]; --sp;                    goto again;\n        case NEG:   sp[-1] = -sp[-1];                                   goto again;\n        case NOT:   sp[-1] = !sp[-1];                                   goto again;\n        case JMP:   pc += *(int32_t *)pc;                               goto again;\n        case JZ:    pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n        case PRTC:  printf(\"%c\", sp[-1]); --sp;                         goto again;\n        case PRTS:  printf(\"%s\", string_pool[sp[-1]]); --sp;            goto again;\n        case PRTI:  printf(\"%d\", sp[-1]); --sp;                         goto again;\n        case HALT:                                                      break;\n        default:    error(\"Unknown opcode %d\\n\", *(pc - 1));\n    }\n}\n\nchar *read_line(int *len) {\n    static char *text = NULL;\n    static int textmax = 0;\n\n    for (*len = 0; ; (*len)++) {\n        int ch = fgetc(source_fp);\n        if (ch == EOF || ch == '\\n') {\n            if (*len == 0)\n                return NULL;\n            break;\n        }\n        if (*len + 1 >= textmax) {\n            textmax = (textmax == 0 ? 128 : textmax * 2);\n            text = realloc(text, textmax);\n        }\n        text[*len] = ch;\n    }\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *rtrim(char *text, int *len) {         \n    for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n        ;\n\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *translate(char *st) {\n    char *p, *q;\n    if (st[0] == '\"')                       \n        ++st;\n    p = q = st;\n\n    while ((*p++ = *q++) != '\\0') {\n        if (q[-1] == '\\\\') {\n            if (q[0] == 'n') {\n                p[-1] = '\\n';\n                ++q;\n            } else if (q[0] == '\\\\') {\n                ++q;\n            }\n        }\n        if (q[0] == '\"' && q[1] == '\\0')    \n            ++q;\n    }\n\n    return st;\n}\n\n\nint findit(const char text[], int offset) {\n    for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n        if (strcmp(code_map[i].text, text) == 0)\n            return code_map[i].op;\n    }\n    error(\"Unknown instruction %s at %d\\n\", text, offset);\n    return -1;\n}\n\nvoid emit_byte(int c) {\n    da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n    union {\n        int32_t n;\n        unsigned char c[sizeof(int32_t)];\n    } x;\n\n    x.n = n;\n\n    for (size_t i = 0; i < sizeof(x.n); ++i) {\n        emit_byte(x.c[i]);\n    }\n}\n\n\n\n\nchar **load_code(int *ds) {\n    int line_len, n_strings;\n    char **string_pool;\n    char *text = read_line(&line_len);\n    text = rtrim(text, &line_len);\n\n    strtok(text, \" \");                      \n    *ds = atoi(strtok(NULL, \" \"));          \n    strtok(NULL, \" \");                      \n    n_strings = atoi(strtok(NULL, \" \"));    \n\n    string_pool = malloc(n_strings * sizeof(char *));\n    for (int i = 0; i < n_strings; ++i) {\n        text = read_line(&line_len);\n        text = rtrim(text, &line_len);\n        text = translate(text);\n        string_pool[i] = strdup(text);\n    }\n\n    for (;;) {\n        int len;\n\n        text = read_line(&line_len);\n        if (text == NULL)\n            break;\n        text = rtrim(text, &line_len);\n\n        int offset = atoi(strtok(text, \" \"));   \n        char *instr = strtok(NULL, \" \");    \n        int opcode = findit(instr, offset);\n        emit_byte(opcode);\n        char *operand = strtok(NULL, \" \");\n\n        switch (opcode) {\n            case JMP: case JZ:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n            case PUSH:\n                emit_int(atoi(operand));\n                break;\n            case FETCH: case STORE:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n        }\n    }\n    return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n    if (fn[0] == '\\0')\n        *fp = std;\n    else if ((*fp = fopen(fn, mode)) == NULL)\n        error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n    init_io(&source_fp, stdin,  \"r\",  argc > 1 ? argv[1] : \"\");\n    int data_size;\n    char **string_pool = load_code(&data_size);\n    int data[1000 + data_size];\n    run_vm(object, data, data_size, string_pool);\n}\n", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n"}
{"id": 48055, "name": "Compiler_virtual machine interpreter", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <stdint.h>\n#include <ctype.h>\n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type)  type *name = NULL;          \\\n                            int _qy_ ## name ## _p = 0;  \\\n                            int _qy_ ## name ## _max = 0\n\n#define da_redim(name)      do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n                                name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name)     _qy_ ## name ## _p = 0\n\n#define da_append(name, x)  do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n    OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n    char    *text;\n    Code_t   op;\n} Code_map;\n\nCode_map code_map[] = {\n    {\"fetch\",  FETCH},\n    {\"store\",  STORE},\n    {\"push\",   PUSH },\n    {\"add\",    ADD  },\n    {\"sub\",    SUB  },\n    {\"mul\",    MUL  },\n    {\"div\",    DIV  },\n    {\"mod\",    MOD  },\n    {\"lt\",     LT   },\n    {\"gt\",     GT   },\n    {\"le\",     LE   },\n    {\"ge\",     GE   },\n    {\"eq\",     EQ   },\n    {\"ne\",     NE   },\n    {\"and\",    AND  },\n    {\"or\",     OR   },\n    {\"neg\",    NEG  },\n    {\"not\",    NOT  },\n    {\"jmp\",    JMP  },\n    {\"jz\",     JZ   },\n    {\"prtc\",   PRTC },\n    {\"prts\",   PRTS },\n    {\"prti\",   PRTI },\n    {\"halt\",   HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n    va_list ap;\n    char buf[1000];\n\n    va_start(ap, fmt);\n    vsprintf(buf, fmt, ap);\n    va_end(ap);\n    printf(\"error: %s\\n\", buf);\n    exit(1);\n}\n\n\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n    int32_t *sp = &data[g_size + 1];\n    const code *pc = obj;\n\n    again:\n    switch (*pc++) {\n        case FETCH: *sp++ = data[*(int32_t *)pc];  pc += sizeof(int32_t); goto again;\n        case STORE: data[*(int32_t *)pc] = *--sp;  pc += sizeof(int32_t); goto again;\n        case PUSH:  *sp++ = *(int32_t *)pc;        pc += sizeof(int32_t); goto again;\n        case ADD:   sp[-2] += sp[-1]; --sp;                             goto again;\n        case SUB:   sp[-2] -= sp[-1]; --sp;                             goto again;\n        case MUL:   sp[-2] *= sp[-1]; --sp;                             goto again;\n        case DIV:   sp[-2] /= sp[-1]; --sp;                             goto again;\n        case MOD:   sp[-2] %= sp[-1]; --sp;                             goto again;\n        case LT:    sp[-2] = sp[-2] <  sp[-1]; --sp;                    goto again;\n        case GT:    sp[-2] = sp[-2] >  sp[-1]; --sp;                    goto again;\n        case LE:    sp[-2] = sp[-2] <= sp[-1]; --sp;                    goto again;\n        case GE:    sp[-2] = sp[-2] >= sp[-1]; --sp;                    goto again;\n        case EQ:    sp[-2] = sp[-2] == sp[-1]; --sp;                    goto again;\n        case NE:    sp[-2] = sp[-2] != sp[-1]; --sp;                    goto again;\n        case AND:   sp[-2] = sp[-2] && sp[-1]; --sp;                    goto again;\n        case OR:    sp[-2] = sp[-2] || sp[-1]; --sp;                    goto again;\n        case NEG:   sp[-1] = -sp[-1];                                   goto again;\n        case NOT:   sp[-1] = !sp[-1];                                   goto again;\n        case JMP:   pc += *(int32_t *)pc;                               goto again;\n        case JZ:    pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n        case PRTC:  printf(\"%c\", sp[-1]); --sp;                         goto again;\n        case PRTS:  printf(\"%s\", string_pool[sp[-1]]); --sp;            goto again;\n        case PRTI:  printf(\"%d\", sp[-1]); --sp;                         goto again;\n        case HALT:                                                      break;\n        default:    error(\"Unknown opcode %d\\n\", *(pc - 1));\n    }\n}\n\nchar *read_line(int *len) {\n    static char *text = NULL;\n    static int textmax = 0;\n\n    for (*len = 0; ; (*len)++) {\n        int ch = fgetc(source_fp);\n        if (ch == EOF || ch == '\\n') {\n            if (*len == 0)\n                return NULL;\n            break;\n        }\n        if (*len + 1 >= textmax) {\n            textmax = (textmax == 0 ? 128 : textmax * 2);\n            text = realloc(text, textmax);\n        }\n        text[*len] = ch;\n    }\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *rtrim(char *text, int *len) {         \n    for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n        ;\n\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *translate(char *st) {\n    char *p, *q;\n    if (st[0] == '\"')                       \n        ++st;\n    p = q = st;\n\n    while ((*p++ = *q++) != '\\0') {\n        if (q[-1] == '\\\\') {\n            if (q[0] == 'n') {\n                p[-1] = '\\n';\n                ++q;\n            } else if (q[0] == '\\\\') {\n                ++q;\n            }\n        }\n        if (q[0] == '\"' && q[1] == '\\0')    \n            ++q;\n    }\n\n    return st;\n}\n\n\nint findit(const char text[], int offset) {\n    for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n        if (strcmp(code_map[i].text, text) == 0)\n            return code_map[i].op;\n    }\n    error(\"Unknown instruction %s at %d\\n\", text, offset);\n    return -1;\n}\n\nvoid emit_byte(int c) {\n    da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n    union {\n        int32_t n;\n        unsigned char c[sizeof(int32_t)];\n    } x;\n\n    x.n = n;\n\n    for (size_t i = 0; i < sizeof(x.n); ++i) {\n        emit_byte(x.c[i]);\n    }\n}\n\n\n\n\nchar **load_code(int *ds) {\n    int line_len, n_strings;\n    char **string_pool;\n    char *text = read_line(&line_len);\n    text = rtrim(text, &line_len);\n\n    strtok(text, \" \");                      \n    *ds = atoi(strtok(NULL, \" \"));          \n    strtok(NULL, \" \");                      \n    n_strings = atoi(strtok(NULL, \" \"));    \n\n    string_pool = malloc(n_strings * sizeof(char *));\n    for (int i = 0; i < n_strings; ++i) {\n        text = read_line(&line_len);\n        text = rtrim(text, &line_len);\n        text = translate(text);\n        string_pool[i] = strdup(text);\n    }\n\n    for (;;) {\n        int len;\n\n        text = read_line(&line_len);\n        if (text == NULL)\n            break;\n        text = rtrim(text, &line_len);\n\n        int offset = atoi(strtok(text, \" \"));   \n        char *instr = strtok(NULL, \" \");    \n        int opcode = findit(instr, offset);\n        emit_byte(opcode);\n        char *operand = strtok(NULL, \" \");\n\n        switch (opcode) {\n            case JMP: case JZ:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n            case PUSH:\n                emit_int(atoi(operand));\n                break;\n            case FETCH: case STORE:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n        }\n    }\n    return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n    if (fn[0] == '\\0')\n        *fp = std;\n    else if ((*fp = fopen(fn, mode)) == NULL)\n        error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n    init_io(&source_fp, stdin,  \"r\",  argc > 1 ? argv[1] : \"\");\n    int data_size;\n    char **string_pool = load_code(&data_size);\n    int data[1000 + data_size];\n    run_vm(object, data, data_size, string_pool);\n}\n", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n"}
{"id": 48056, "name": "Klarner-Rado sequence", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n"}
{"id": 48057, "name": "Klarner-Rado sequence", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n"}
{"id": 48058, "name": "Bitmap_Bézier curves_Cubic", "C": "void cubic_bezier(\n       \timage img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        unsigned int x4, unsigned int y4,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n"}
{"id": 48059, "name": "Sorting algorithms_Pancake sort", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n"}
{"id": 48060, "name": "Largest five adjacent number", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\n#define DIGITS 1000\n#define NUMSIZE 5\n\nuint8_t randomDigit() {\n    uint8_t d;\n    do {d = rand() & 0xF;} while (d >= 10);\n    return d;\n}\n\nint numberAt(uint8_t *d, int size) {\n    int acc = 0;\n    while (size--) acc = 10*acc + *d++;\n    return acc;\n}\n\nint main() {\n    uint8_t digits[DIGITS];\n    int i, largest = 0;\n    \n    srand(time(NULL));\n    \n    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();\n    for (i=0; i<DIGITS-NUMSIZE; i++) {\n        int here = numberAt(&digits[i], NUMSIZE);\n        if (here > largest) largest = here;\n    }\n\n    printf(\"%d\\n\", largest);\n    return 0;\n}\n", "Python": "\n\nfrom random import seed,randint\nfrom datetime import datetime\n\nseed(str(datetime.now()))\n\nlargeNum = [randint(1,9)]\n\nfor i in range(1,1000):\n    largeNum.append(randint(0,9))\n\nmaxNum,minNum = 0,99999\n\nfor i in range(0,994):\n    num = int(\"\".join(map(str,largeNum[i:i+5])))\n    if num > maxNum:\n        maxNum = num\n    elif num < minNum:\n        minNum = num\n\nprint(\"Largest 5-adjacent number found \", maxNum)\nprint(\"Smallest 5-adjacent number found \", minNum)\n"}
{"id": 48061, "name": "Sum of square and cube digits of an integer are primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint digit_sum(int n) {\n    int sum;\n    for (sum = 0; n; n /= 10) sum += n % 10;\n    return sum;\n}\n\n\nbool prime(int n) {\n    if (n<4) return n>=2;\n    for (int d=2; d*d <= n; d++)\n        if (n%d == 0) return false;\n    return true;\n}\n\nint main() {\n    for (int i=1; i<100; i++)\n        if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i)))\n            printf(\"%d \", i);\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef digSum(n, b):\n    s = 0\n    while n:\n        s += (n % b)\n        n = n // b\n    return s\n\nif __name__ == '__main__':\n    for n in range(11, 99):\n        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):\n            print(n, end = \"  \")\n"}
{"id": 48062, "name": "The sieve of Sundaram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\nint main(void) {\n    int nprimes =  1000000;\n    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  \n      \n      \n    int i, j, m, k; int *a;\n    k = (nmax-2)/2; \n    a = (int *)calloc(k + 1, sizeof(int));\n    for(i = 0; i <= k; i++)a[i] = 2*i+1; \n    for (i = 1; (i+1)*i*2 <= k; i++)\n        for (j = i; j <= (k-i)/(2*i+1); j++) {\n            m = i + j + 2*i*j;\n            if(a[m]) a[m] = 0;\n            }            \n        \n    for (i = 1, j = 0; i <= k; i++) \n       if (a[i]) {\n           if(j%10 == 0 && j <= 100)printf(\"\\n\");\n           j++; \n           if(j <= 100)printf(\"%3d \", a[i]);\n           else if(j == nprimes){\n               printf(\"\\n%d th prime is %d\\n\",j,a[i]);\n               break;\n               }\n           }\n}\n", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n"}
{"id": 48063, "name": "Chemical calculator", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef char *string;\n\ntypedef struct node_t {\n    string symbol;\n    double weight;\n    struct node_t *next;\n} node;\n\nnode *make_node(string symbol, double weight) {\n    node *nptr = malloc(sizeof(node));\n    if (nptr) {\n        nptr->symbol = symbol;\n        nptr->weight = weight;\n        nptr->next = NULL;\n        return nptr;\n    }\n    return NULL;\n}\n\nvoid free_node(node *ptr) {\n    if (ptr) {\n        free_node(ptr->next);\n        ptr->next = NULL;\n        free(ptr);\n    }\n}\n\nnode *insert(string symbol, double weight, node *head) {\n    node *nptr = make_node(symbol, weight);\n    nptr->next = head;\n    return nptr;\n}\n\nnode *dic;\nvoid init() {\n    dic = make_node(\"H\", 1.008);\n    dic = insert(\"He\", 4.002602, dic);\n    dic = insert(\"Li\", 6.94, dic);\n    dic = insert(\"Be\", 9.0121831, dic);\n    dic = insert(\"B\", 10.81, dic);\n    dic = insert(\"C\", 12.011, dic);\n    dic = insert(\"N\", 14.007, dic);\n    dic = insert(\"O\", 15.999, dic);\n    dic = insert(\"F\", 18.998403163, dic);\n    dic = insert(\"Ne\", 20.1797, dic);\n    dic = insert(\"Na\", 22.98976928, dic);\n    dic = insert(\"Mg\", 24.305, dic);\n    dic = insert(\"Al\", 26.9815385, dic);\n    dic = insert(\"Si\", 28.085, dic);\n    dic = insert(\"P\", 30.973761998, dic);\n    dic = insert(\"S\", 32.06, dic);\n    dic = insert(\"Cl\", 35.45, dic);\n    dic = insert(\"Ar\", 39.948, dic);\n    dic = insert(\"K\", 39.0983, dic);\n    dic = insert(\"Ca\", 40.078, dic);\n    dic = insert(\"Sc\", 44.955908, dic);\n    dic = insert(\"Ti\", 47.867, dic);\n    dic = insert(\"V\", 50.9415, dic);\n    dic = insert(\"Cr\", 51.9961, dic);\n    dic = insert(\"Mn\", 54.938044, dic);\n    dic = insert(\"Fe\", 55.845, dic);\n    dic = insert(\"Co\", 58.933194, dic);\n    dic = insert(\"Ni\", 58.6934, dic);\n    dic = insert(\"Cu\", 63.546, dic);\n    dic = insert(\"Zn\", 65.38, dic);\n    dic = insert(\"Ga\", 69.723, dic);\n    dic = insert(\"Ge\", 72.630, dic);\n    dic = insert(\"As\", 74.921595, dic);\n    dic = insert(\"Se\", 78.971, dic);\n    dic = insert(\"Br\", 79.904, dic);\n    dic = insert(\"Kr\", 83.798, dic);\n    dic = insert(\"Rb\", 85.4678, dic);\n    dic = insert(\"Sr\", 87.62, dic);\n    dic = insert(\"Y\", 88.90584, dic);\n    dic = insert(\"Zr\", 91.224, dic);\n    dic = insert(\"Nb\", 92.90637, dic);\n    dic = insert(\"Mo\", 95.95, dic);\n    dic = insert(\"Ru\", 101.07, dic);\n    dic = insert(\"Rh\", 102.90550, dic);\n    dic = insert(\"Pd\", 106.42, dic);\n    dic = insert(\"Ag\", 107.8682, dic);\n    dic = insert(\"Cd\", 112.414, dic);\n    dic = insert(\"In\", 114.818, dic);\n    dic = insert(\"Sn\", 118.710, dic);\n    dic = insert(\"Sb\", 121.760, dic);\n    dic = insert(\"Te\", 127.60, dic);\n    dic = insert(\"I\", 126.90447, dic);\n    dic = insert(\"Xe\", 131.293, dic);\n    dic = insert(\"Cs\", 132.90545196, dic);\n    dic = insert(\"Ba\", 137.327, dic);\n    dic = insert(\"La\", 138.90547, dic);\n    dic = insert(\"Ce\", 140.116, dic);\n    dic = insert(\"Pr\", 140.90766, dic);\n    dic = insert(\"Nd\", 144.242, dic);\n    dic = insert(\"Pm\", 145, dic);\n    dic = insert(\"Sm\", 150.36, dic);\n    dic = insert(\"Eu\", 151.964, dic);\n    dic = insert(\"Gd\", 157.25, dic);\n    dic = insert(\"Tb\", 158.92535, dic);\n    dic = insert(\"Dy\", 162.500, dic);\n    dic = insert(\"Ho\", 164.93033, dic);\n    dic = insert(\"Er\", 167.259, dic);\n    dic = insert(\"Tm\", 168.93422, dic);\n    dic = insert(\"Yb\", 173.054, dic);\n    dic = insert(\"Lu\", 174.9668, dic);\n    dic = insert(\"Hf\", 178.49, dic);\n    dic = insert(\"Ta\", 180.94788, dic);\n    dic = insert(\"W\", 183.84, dic);\n    dic = insert(\"Re\", 186.207, dic);\n    dic = insert(\"Os\", 190.23, dic);\n    dic = insert(\"Ir\", 192.217, dic);\n    dic = insert(\"Pt\", 195.084, dic);\n    dic = insert(\"Au\", 196.966569, dic);\n    dic = insert(\"Hg\", 200.592, dic);\n    dic = insert(\"Tl\", 204.38, dic);\n    dic = insert(\"Pb\", 207.2, dic);\n    dic = insert(\"Bi\", 208.98040, dic);\n    dic = insert(\"Po\", 209, dic);\n    dic = insert(\"At\", 210, dic);\n    dic = insert(\"Rn\", 222, dic);\n    dic = insert(\"Fr\", 223, dic);\n    dic = insert(\"Ra\", 226, dic);\n    dic = insert(\"Ac\", 227, dic);\n    dic = insert(\"Th\", 232.0377, dic);\n    dic = insert(\"Pa\", 231.03588, dic);\n    dic = insert(\"U\", 238.02891, dic);\n    dic = insert(\"Np\", 237, dic);\n    dic = insert(\"Pu\", 244, dic);\n    dic = insert(\"Am\", 243, dic);\n    dic = insert(\"Cm\", 247, dic);\n    dic = insert(\"Bk\", 247, dic);\n    dic = insert(\"Cf\", 251, dic);\n    dic = insert(\"Es\", 252, dic);\n    dic = insert(\"Fm\", 257, dic);\n    dic = insert(\"Uue\", 315, dic);\n    dic = insert(\"Ubn\", 299, dic);\n}\n\ndouble lookup(string symbol) {\n    for (node *ptr = dic; ptr; ptr = ptr->next) {\n        if (strcmp(symbol, ptr->symbol) == 0) {\n            return ptr->weight;\n        }\n    }\n\n    printf(\"symbol not found: %s\\n\", symbol);\n    return 0.0;\n}\n\ndouble total(double mass, int count) {\n    if (count > 0) {\n        return mass * count;\n    }\n    return mass;\n}\n\ndouble total_s(string sym, int count) {\n    double mass = lookup(sym);\n    return total(mass, count);\n}\n\ndouble evaluate_c(string expr, size_t *pos, double mass) {\n    int count = 0;\n    if (expr[*pos] < '0' || '9' < expr[*pos]) {\n        printf(\"expected to find a count, saw the character: %c\\n\", expr[*pos]);\n    }\n    for (; expr[*pos]; (*pos)++) {\n        char c = expr[*pos];\n        if ('0' <= c && c <= '9') {\n            count = count * 10 + c - '0';\n        } else {\n            break;\n        }\n    }\n    return total(mass, count);\n}\n\ndouble evaluate_p(string expr, size_t limit, size_t *pos) {\n    char sym[4];\n    int sym_pos = 0;\n    int count = 0;\n    double sum = 0.0;\n\n    for (; *pos < limit && expr[*pos]; (*pos)++) {\n        char c = expr[*pos];\n        if ('A' <= c && c <= 'Z') {\n            if (sym_pos > 0) {\n                sum += total_s(sym, count);\n                sym_pos = 0;\n                count = 0;\n            }\n            sym[sym_pos++] = c;\n            sym[sym_pos] = 0;\n        } else if ('a' <= c && c <= 'z') {\n            sym[sym_pos++] = c;\n            sym[sym_pos] = 0;\n        } else if ('0' <= c && c <= '9') {\n            count = count * 10 + c - '0';\n        } else if (c == '(') {\n            if (sym_pos > 0) {\n                sum += total_s(sym, count);\n                sym_pos = 0;\n                count = 0;\n            }\n\n            (*pos)++; \n            double mass = evaluate_p(expr, limit, pos);\n\n            sum += evaluate_c(expr, pos, mass);\n            (*pos)--; \n        } else if (c == ')') {\n            if (sym_pos > 0) {\n                sum += total_s(sym, count);\n                sym_pos = 0;\n                count = 0;\n            }\n\n            (*pos)++;\n            return sum;\n        } else {\n            printf(\"Unexpected character encountered: %c\\n\", c);\n        }\n    }\n\n    if (sym_pos > 0) {\n        sum += total_s(sym, count);\n    }\n    return sum;\n}\n\ndouble evaluate(string expr) {\n    size_t limit = strlen(expr);\n    size_t pos = 0;\n    return evaluate_p(expr, limit, &pos);\n}\n\nvoid test(string expr) {\n    double mass = evaluate(expr);\n    printf(\"%17s -> %7.3f\\n\", expr, mass);\n}\n\nint main() {\n    init();\n\n    test(\"H\");\n    test(\"H2\");\n    test(\"H2O\");\n    test(\"H2O2\");\n    test(\"(HO)2\");\n    test(\"Na2SO4\");\n    test(\"C6H12\");\n    test(\"COOH(C(CH3)2)3CH3\");\n    test(\"C6H4O2(OH)4\");\n    test(\"C27H46O\");\n    test(\"Uue\");\n\n    free_node(dic);\n    dic = NULL;\n    return 0;\n}\n", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n"}
{"id": 48064, "name": "Active Directory_Connect", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 48065, "name": "Exactly three adjacent 3 in lists", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool three_3s(const int *items, size_t len) {\n    int threes = 0;    \n    while (len--) \n        if (*items++ == 3)\n            if (threes<3) threes++;\n            else return false;\n        else if (threes != 0 && threes != 3) \n            return false;\n    return true;\n}\n\nvoid print_list(const int *items, size_t len) {\n    while (len--) printf(\"%d \", *items++);\n}\n\nint main() {\n    int lists[][9] = {\n        {9,3,3,3,2,1,7,8,5},\n        {5,2,9,3,3,6,8,4,1},\n        {1,4,3,6,7,3,8,3,2},\n        {1,2,3,4,5,6,7,8,9},\n        {4,6,8,7,2,3,3,3,1}\n    };\n    \n    size_t list_length = sizeof(lists[0]) / sizeof(int);\n    size_t n_lists = sizeof(lists) / sizeof(lists[0]);\n    \n    for (size_t i=0; i<n_lists; i++) {\n        print_list(lists[i], list_length);\n        printf(\"-> %s\\n\", three_3s(lists[i], list_length) ? \"true\" : \"false\");\n    }\n    \n    return 0;\n}\n", "Python": "\n\nfrom itertools import dropwhile, takewhile\n\n\n\ndef nnPeers(n):\n    \n    def p(x):\n        return n == x\n\n    def go(xs):\n        fromFirstMatch = list(dropwhile(\n            lambda v: not p(v),\n            xs\n        ))\n        ns = list(takewhile(p, fromFirstMatch))\n        rest = fromFirstMatch[len(ns):]\n\n        return p(len(ns)) and (\n            not any(p(x) for x in rest)\n        )\n\n    return go\n\n\n\n\ndef main():\n    \n    print(\n        '\\n'.join([\n            f'{xs} -> {nnPeers(3)(xs)}' for xs in [\n                [9, 3, 3, 3, 2, 1, 7, 8, 5],\n                [5, 2, 9, 3, 3, 7, 8, 4, 1],\n                [1, 4, 3, 6, 7, 3, 8, 3, 2],\n                [1, 2, 3, 4, 5, 6, 7, 8, 9],\n                [4, 6, 8, 7, 2, 3, 3, 3, 1]\n            ]\n        ])\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48066, "name": "Permutations by swapping", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n"}
{"id": 48067, "name": "Minimum multiple of m where digital sum equals m", "C": "#include <stdio.h>\n\nunsigned digit_sum(unsigned n) {\n    unsigned sum = 0;\n    do { sum += n % 10; }\n    while(n /= 10);\n    return sum;\n}\n\nunsigned a131382(unsigned n) {\n    unsigned m;\n    for (m = 1; n != digit_sum(m*n); m++);\n    return m;\n}\n\nint main() {\n    unsigned n;\n    for (n = 1; n <= 70; n++) {\n        printf(\"%9u\", a131382(n));\n        if (n % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48068, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 48069, "name": "Verhoeff algorithm", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic const int d[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n};\n\nstatic const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};\n\nstatic const int p[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n};\n\nint verhoeff(const char* s, bool validate, bool verbose) {\n    if (verbose) {\n        const char* t = validate ? \"Validation\" : \"Check digit\";\n        printf(\"%s calculations for '%s':\\n\\n\", t, s);\n        puts(u8\" i  n\\xE1\\xB5\\xA2  p[i,n\\xE1\\xB5\\xA2]  c\");\n        puts(\"------------------\");\n    }\n    int len = strlen(s);\n    if (validate)\n        --len;\n    int c = 0;\n    for (int i = len; i >= 0; --i) {\n        int ni = (i == len && !validate) ? 0 : s[i] - '0';\n        assert(ni >= 0 && ni < 10);\n        int pi = p[(len - i) % 8][ni];\n        c = d[c][pi];\n        if (verbose)\n            printf(\"%2d  %d      %d     %d\\n\", len - i, ni, pi, c);\n    }\n    if (verbose && !validate)\n        printf(\"\\ninv[%d] = %d\\n\", c, inv[c]);\n    return validate ? c == 0 : inv[c];\n}\n\nint main() {\n    const char* ss[3] = {\"236\", \"12345\", \"123456789012\"};\n    for (int i = 0; i < 3; ++i) {\n        const char* s = ss[i];\n        bool verbose = i < 2;\n        int c = verhoeff(s, false, verbose);\n        printf(\"\\nThe check digit for '%s' is '%d'.\\n\", s, c);\n        int len = strlen(s);\n        char sc[len + 2];\n        strncpy(sc, s, len + 2);\n        for (int j = 0; j < 2; ++j) {\n            sc[len] = (j == 0) ? c + '0' : '9';\n            int v = verhoeff(sc, true, verbose);\n            printf(\"\\nThe validation for '%s' is %s.\\n\", sc,\n                   v ? \"correct\" : \"incorrect\");\n        }\n    }\n    return 0;\n}\n", "Python": "MULTIPLICATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),\n    (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),\n    (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),\n    (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),\n    (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),\n    (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),\n    (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),\n    (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),\n    (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),\n]\n\nINV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)\n\nPERMUTATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),\n    (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),\n    (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),\n    (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),\n    (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),\n    (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),\n    (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),\n]\n\ndef verhoeffchecksum(n, validate=True, terse=True, verbose=False):\n    \n    if verbose:\n        print(f\"\\n{'Validation' if validate else 'Check digit'}\",\\\n            f\"calculations for {n}:\\n\\n i  nᵢ  p[i,nᵢ]   c\\n------------------\")\n    \n    c, dig = 0, list(str(n if validate else 10 * n))\n    for i, ni in enumerate(dig[::-1]):\n        p = PERMUTATION_TABLE[i % 8][int(ni)]\n        c = MULTIPLICATION_TABLE[c][p]\n        if verbose:\n            print(f\"{i:2}  {ni}      {p}    {c}\")\n\n    if verbose and not validate:\n        print(f\"\\ninv({c}) = {INV[c]}\")\n    if not terse:\n        print(f\"\\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}.\"\\\n              if validate else f\"\\nThe check digit for '{n}' is {INV[c]}.\")\n    return c == 0 if validate else INV[c]\n\nif __name__ == '__main__':\n\n    for n, va, t, ve in [\n        (236, False, False, True), (2363, True, False, True), (2369, True, False, True),\n        (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),\n        (123456789012, False, False, False), (1234567890120, True, False, False),\n        (1234567890129, True, False, False)]:\n        verhoeffchecksum(n, va, t, ve)\n"}
{"id": 48070, "name": "Steady squares", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n", "Python": "print(\"working...\")\nprint(\"Steady squares under 10.000 are:\")\nlimit = 10000\n\nfor n in range(1,limit):\n    nstr = str(n)\n    nlen = len(nstr)\n    square = str(pow(n,2))\n    rn = square[-nlen:]\n    if nstr == rn:\n       print(str(n) + \" \" + str(square))\n\nprint(\"done...\")\n"}
{"id": 48071, "name": "Numbers in base 10 that are palindromic in bases 2, 4, and 16", "C": "#include <stdio.h>\n#define MAXIMUM 25000\n\nint reverse(int n, int base) {\n    int r;\n    for (r = 0; n; n /= base)\n        r = r*base + n%base;\n    return r;\n}\n\nint palindrome(int n, int base) {\n    return n == reverse(n, base);\n}\n\nint main() {\n    int i, c = 0;\n    \n    for (i = 0; i < MAXIMUM; i++) {\n        if (palindrome(i, 2) &&\n            palindrome(i, 4) &&\n            palindrome(i, 16)) {\n            printf(\"%5d%c\", i, ++c % 12 ? ' ' : '\\n');\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Python": "def reverse(n, base):\n    r = 0\n    while n > 0:\n        r = r*base + n%base\n        n = n//base\n    return r\n    \ndef palindrome(n, base):\n    return n == reverse(n, base)\n    \ncnt = 0\nfor i in range(25000):\n    if all(palindrome(i, base) for base in (2,4,16)):\n        cnt += 1\n        print(\"{:5}\".format(i), end=\" \\n\"[cnt % 12 == 0])\n\nprint()\n"}
{"id": 48072, "name": "Long stairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n    int trial, secs_tot=0, steps_tot=0;     \n    int sbeh, slen, wiz, secs;              \n    time_t t;\n    srand((unsigned) time(&t));             \n    printf( \"Seconds    steps behind    steps ahead\\n\" );\n    for( trial=1;trial<=10000;trial++ ) {   \n        sbeh = 0; slen = 100; secs = 0;     \n        while(sbeh<slen) {                  \n            sbeh+=1;                        \n            for(wiz=1;wiz<=5;wiz++) {       \n                if(rand()%slen < sbeh)\n                    sbeh+=1;                \n                slen+=1;                    \n            }\n            secs+=1;                        \n            if(trial==1&&599<secs&&secs<610)\n                printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh );\n            \n        }\n        secs_tot+=secs;\n        steps_tot+=slen;\n    }\n    printf( \"Average secs taken: %f\\n\", secs_tot/10000.0 );\n    printf( \"Average final length of staircase: %f\\n\", steps_tot/10000.0 ); \n    return 0;\n}\n", "Python": "\n\nfrom numpy import mean\nfrom random import sample\n\ndef gen_long_stairs(start_step, start_length, climber_steps, add_steps):\n    secs, behind, total = 0, start_step, start_length\n    while True:\n        behind += climber_steps\n        behind += sum([behind > n for n in sample(range(total), add_steps)])\n        total += add_steps\n        secs += 1\n        yield (secs, behind, total)\n        \n\nls = gen_long_stairs(1, 100, 1, 5)\n\nprint(\"Seconds  Behind  Ahead\\n----------------------\")\nwhile True:\n    secs, pos, len = next(ls)\n    if 600 <= secs < 610:\n        print(secs, \"     \", pos, \"   \", len - pos)\n    elif secs == 610:\n        break\n\nprint(\"\\nTen thousand trials to top:\")\ntimes, heights = [], []\nfor trial in range(10_000):\n    trialstairs = gen_long_stairs(1, 100, 1, 5)\n    while True:\n        sec, step, height = next(trialstairs)\n        if step >= height:\n            times.append(sec)\n            heights.append(height)\n            break\n\nprint(\"Mean time:\", mean(times), \"secs. Mean height:\", mean(heights))\n"}
{"id": 48073, "name": "Terminal control_Positional read", "C": "#include <windows.h>\n#include <wchar.h>\n\nint\nmain()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n\tCOORD pos;\n\tHANDLE conout;\n\tlong len;\n\twchar_t c;\n\n\t\n\tconout = CreateFileW(L\"CONOUT$\", GENERIC_READ | GENERIC_WRITE,\n\t    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t    0, NULL);\n\tif (conout == INVALID_HANDLE_VALUE)\n\t\treturn 1;\n\n\t\n\tif (GetConsoleScreenBufferInfo(conout, &info) == 0)\n\t\treturn 1;\n\n\t\n\tpos.X = info.srWindow.Left + 3;  \n\tpos.Y = info.srWindow.Top  + 6;  \n\tif (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||\n\t    len <= 0)\n\t\treturn 1;\n\n\twprintf(L\"Character at (3, 6) had been '%lc'\\n\", c);\n\treturn 0;\n}\n", "Python": "import curses\nfrom random import randint\n\n\n\nstdscr = curses.initscr()\nfor rows in range(10):\n    line = ''.join([chr(randint(41, 90)) for i in range(10)])\n    stdscr.addstr(line + '\\n')\n\n\nicol = 3 - 1\nirow = 6 - 1\nch = stdscr.instr(irow, icol, 1).decode(encoding=\"utf-8\")\n\n\nstdscr.move(irow, icol + 10)\nstdscr.addstr('Character at column 3, row 6 = ' + ch + '\\n')\nstdscr.getch()\n\ncurses.endwin()\n"}
{"id": 48074, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 48075, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 48076, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 48077, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 48078, "name": "Image convolution", "C": "image filter(image img, double *K, int Ks, double, double);\n", "Python": "\nfrom PIL import Image, ImageFilter\n\nif __name__==\"__main__\":\n\tim = Image.open(\"test.jpg\")\n\n\tkernelValues = [-2,-1,0,-1,1,1,0,1,2] \n\tkernel = ImageFilter.Kernel((3,3), kernelValues)\n\n\tim2 = im.filter(kernel)\n\n\tim2.show()\n"}
{"id": 48079, "name": "Deconvolution_2D+", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n \n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n \n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n \nvoid deconv(double g[], int lg, double f[], int lf, double out[], int row_len) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n \n\tfft(g2, ns);\n\tfft(f2, ns);\n \n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i < ns; i++) {\n\t\tif (cabs(creal(h[i])) < 1e-10) \n\t\t\th[i] = 0;\n\t}\n\n\tfor (int i = 0; i > lf - lg - row_len; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\ndouble* unpack2(void *m, int rows, int len, int to_len)\n{\n\tdouble *buf = calloc(sizeof(double), rows * to_len);\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < len; j++)\n\t\t\tbuf[i * to_len + j] = ((double(*)[len])m)[i][j];\n\treturn buf;\n}\n\nvoid pack2(double * buf, int rows, int from_len, int to_len, void *out)\n{\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < to_len; j++)\n\t\t\t((double(*)[to_len])out)[i][j] = buf[i * from_len + j] / 4;\n}\n\nvoid deconv2(void *g, int row_g, int col_g, void *f, int row_f, int col_f, void *out) {\n\tdouble *g2 = unpack2(g, row_g, col_g, col_g);\n\tdouble *f2 = unpack2(f, row_f, col_f, col_g);\n\n\tdouble ff[(row_g - row_f + 1) * col_g];\n\tdeconv(g2, row_g * col_g, f2, row_f * col_g, ff, col_g);\n\tpack2(ff, row_g - row_f + 1, col_g, col_g - col_f + 1, out);\n\n\tfree(g2);\n\tfree(f2);\n}\n\ndouble* unpack3(void *m, int x, int y, int z, int to_y, int to_z)\n{\n\tdouble *buf = calloc(sizeof(double), x * to_y * to_z);\n\tfor (int i = 0; i < x; i++)\n\t\tfor (int j = 0; j < y; j++) {\n\t\t\tfor (int k = 0; k < z; k++)\n\t\t\t\tbuf[(i * to_y + j) * to_z + k] =\n\t\t\t\t\t((double(*)[y][z])m)[i][j][k];\n\t\t}\n\treturn buf;\n}\n\nvoid pack3(double * buf, int x, int y, int z, int to_y, int to_z, void *out)\n{\n\tfor (int i = 0; i < x; i++)\n\t\tfor (int j = 0; j < to_y; j++)\n\t\t\tfor (int k = 0; k < to_z; k++)\n\t\t\t\t((double(*)[to_y][to_z])out)[i][j][k] =\n\t\t\t\t\tbuf[(i * y + j) * z + k] / 4;\n}\n\nvoid deconv3(void *g, int gx, int gy, int gz, void *f, int fx, int fy, int fz, void *out) {\n\tdouble *g2 = unpack3(g, gx, gy, gz, gy, gz);\n\tdouble *f2 = unpack3(f, fx, fy, fz, gy, gz);\n\n\tdouble ff[(gx - fx + 1) * gy * gz];\n\tdeconv(g2, gx * gy * gz, f2, fx * gy * gz, ff, gy * gz);\n\tpack3(ff, gx - fx + 1, gy, gz, gy - fy + 1, gz - fz + 1, out);\n\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble h[2][3][4] = {\n\t\t{{-6, -8, -5,  9}, {-7, 9, -6, -8}, { 2, -7,  9,  8}},\n\t\t{{ 7,  4,  4, -6}, { 9, 9,  4, -4}, {-3,  7, -2, -3}}\n\t};\n\tint hx = 2, hy = 3, hz = 4;\n\tdouble f[3][2][3] = {\t{{-9,  5, -8}, { 3,  5,  1}},\n\t\t\t\t{{-1, -7,  2}, {-5, -6,  6}},\n\t\t\t\t{{ 8,  5,  8}, {-2, -6, -4}} };\n\tint fx = 3, fy = 2, fz = 3;\n\tdouble g[4][4][6] = {\n\t\t{\t{ 54,  42,  53, -42,  85, -72}, { 45,-170,  94, -36,  48,  73},\n\t\t\t{-39,  65,-112, -16, -78, -72}, {  6, -11,  -6,  62,  49,   8} },\n\t\t{ \t{-57,  49, -23,   52, -135,  66},{-23, 127, -58,   -5, -118,  64},\n\t\t\t{ 87, -16,  121,  23,  -41, -12},{-19,  29,   35,-148,  -11,  45} },\n\t\t{\t{-55, -147, -146, -31,  55,  60},{-88,  -45,  -28,  46, -26,-144},\n\t\t\t{-12, -107,  -34, 150, 249,  66},{ 11,  -15,  -34,  27, -78, -50} },\n\t\t{\t{ 56,  67, 108,   4,  2,-48},{ 58,  67,  89,  32, 32, -8},\n\t\t\t{-42, -31,-103, -30,-23, -8},{  6,   4, -26, -10, 26, 12}\n\t\t}\n\t};\n\tint gx = 4, gy = 4, gz = 6;\n\n\tdouble h2[gx - fx + 1][gy - fy + 1][gz - fz + 1];\n\tdeconv3(g, gx, gy, gz, f, fx, fy, fz, h2);\n\tprintf(\"deconv3(g, f):\\n\");\n\tfor (int i = 0; i < gx - fx + 1; i++) {\n\t\tfor (int j = 0; j < gy - fy + 1; j++) {\n\t\t\tfor (int k = 0; k < gz - fz + 1; k++)\n\t\t\t\tprintf(\"%g \", h2[i][j][k]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tif (i < gx - fx) printf(\"\\n\");\n\t}\n\n\tdouble f2[gx - hx + 1][gy - hy + 1][gz - hz + 1];\n\tdeconv3(g, gx, gy, gz, h, hx, hy, hz, f2);\n\tprintf(\"\\ndeconv3(g, h):\\n\");\n\tfor (int i = 0; i < gx - hx + 1; i++) {\n\t\tfor (int j = 0; j < gy - hy + 1; j++) {\n\t\t\tfor (int k = 0; k < gz - hz + 1; k++)\n\t\t\t\tprintf(\"%g \", f2[i][j][k]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tif (i < gx - hx) printf(\"\\n\");\n\t}\n}\n\n\n\n", "Python": "\n\nimport numpy\nimport pprint\n\nh =  [\n      [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], \n      [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf =  [\n      [[-9, 5, -8], [3, 5, 1]], \n      [[-1, -7, 2], [-5, -6, 6]], \n      [[8, 5, 8],[-2, -6, -4]]]\ng =  [\n      [\n         [54, 42, 53, -42, 85, -72], \n         [45, -170, 94, -36, 48, 73], \n         [-39, 65, -112, -16, -78, -72], \n         [6, -11, -6, 62, 49, 8]], \n      [\n         [-57, 49, -23, 52, -135, 66], \n         [-23, 127, -58, -5, -118, 64], \n         [87, -16, 121, 23, -41, -12], \n         [-19, 29, 35, -148, -11, 45]], \n      [\n         [-55, -147, -146, -31, 55, 60], \n         [-88, -45, -28, 46, -26, -144], \n         [-12, -107, -34, 150, 249, 66], \n         [11, -15, -34, 27, -78, -50]], \n      [\n         [56, 67, 108, 4, 2, -48], \n         [58, 67, 89, 32, 32, -8], \n         [-42, -31, -103, -30, -23, -8],\n         [6, 4, -26, -10, 26, 12]]]\n      \ndef trim_zero_empty(x):\n    \n    \n    if len(x) > 0:\n        if type(x[0]) != numpy.ndarray:\n            \n            return list(numpy.trim_zeros(x))\n        else:\n            \n            new_x = []\n            for l in x:\n               tl = trim_zero_empty(l)\n               if len(tl) > 0:\n                   new_x.append(tl)\n            return new_x\n    else:\n        \n        return x\n       \ndef deconv(a, b):\n    \n    \n    \n\n    ffta = numpy.fft.fftn(a)\n    \n    \n    \n    \n    ashape = numpy.shape(a)\n    \n    \n    \n\n    fftb = numpy.fft.fftn(b,ashape)\n    \n    \n\n    fftquotient = ffta / fftb\n    \n    \n    \n\n    c = numpy.fft.ifftn(fftquotient)\n    \n    \n    \n\n    trimmedc = numpy.around(numpy.real(c),decimals=6)\n    \n    \n    \n    \n    cleanc = trim_zero_empty(trimmedc)\n                \n    return cleanc\n    \nprint(\"deconv(g,h)=\")\n\npprint.pprint(deconv(g,h))\n\nprint(\" \")\n\nprint(\"deconv(g,f)=\")\n\npprint.pprint(deconv(g,f))\n"}
{"id": 48080, "name": "Dice game probabilities", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n"}
{"id": 48081, "name": "Zebra puzzle", "C": "#include <stdio.h>\n#include <string.h>\n\nenum HouseStatus { Invalid, Underfull, Valid };\n\nenum Attrib { C, M, D, A, S };\n\n\nenum Colors { Red, Green, White, Yellow, Blue };\nenum Mans { English, Swede, Dane, German, Norwegian };\nenum Drinks { Tea, Coffee, Milk, Beer, Water };\nenum Animals { Dog, Birds, Cats, Horse, Zebra };\nenum Smokes { PallMall, Dunhill, Blend, BlueMaster, Prince };\n\n\nvoid printHouses(int ha[5][5]) {\n    const char *color[] =  { \"Red\", \"Green\", \"White\", \"Yellow\", \"Blue\" };\n    const char *man[] =    { \"English\", \"Swede\", \"Dane\", \"German\", \"Norwegian\" };\n    const char *drink[] =  { \"Tea\", \"Coffee\", \"Milk\", \"Beer\", \"Water\" };\n    const char *animal[] = { \"Dog\", \"Birds\", \"Cats\", \"Horse\", \"Zebra\" };\n    const char *smoke[] =  { \"PallMall\", \"Dunhill\", \"Blend\", \"BlueMaster\", \"Prince\" };\n\n    printf(\"%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s\\n\",\n           \"House\", \"Color\", \"Man\", \"Drink\", \"Animal\", \"Smoke\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        if (ha[i][C] >= 0)\n            printf(\"%-10.10s\", color[ha[i][C]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][M] >= 0)\n            printf(\"%-10.10s\", man[ha[i][M]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][D] >= 0)\n            printf(\"%-10.10s\", drink[ha[i][D]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][A] >= 0)\n            printf(\"%-10.10s\", animal[ha[i][A]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][S] >= 0)\n            printf(\"%-10.10s\\n\", smoke[ha[i][S]]);\n        else\n            printf(\"-\\n\");\n    }\n}\n\n\nint checkHouses(int ha[5][5]) {\n    int c_add = 0, c_or = 0;\n    int m_add = 0, m_or = 0;\n    int d_add = 0, d_or = 0;\n    int a_add = 0, a_or = 0;\n    int s_add = 0, s_or = 0;\n\n    \n    if (ha[2][D] >= 0 && ha[2][D] != Milk)\n        return Invalid;\n\n    \n    if (ha[0][M] >= 0 && ha[0][M] != Norwegian)\n        return Invalid;\n\n    for (int i = 0; i < 5; i++) {\n        \n        if (ha[i][C] >= 0) {\n            c_add += (1 << ha[i][C]);\n            c_or |= (1 << ha[i][C]);\n        }\n        if (ha[i][M] >= 0) {\n            m_add += (1 << ha[i][M]);\n            m_or |= (1 << ha[i][M]);\n        }\n        if (ha[i][D] >= 0) {\n            d_add += (1 << ha[i][D]);\n            d_or |= (1 << ha[i][D]);\n        }\n        if (ha[i][A] >= 0) {\n            a_add += (1 << ha[i][A]);\n            a_or |= (1 << ha[i][A]);\n        }\n        if (ha[i][S] >= 0) {\n            s_add += (1 << ha[i][S]);\n            s_or |= (1 << ha[i][S]);\n        }\n\n        \n        if ((ha[i][M] >= 0 && ha[i][C] >= 0) &&\n            ((ha[i][M] == English && ha[i][C] != Red) || \n             (ha[i][M] != English && ha[i][C] == Red)))  \n            return Invalid;\n\n        \n        if ((ha[i][M] >= 0 && ha[i][A] >= 0) &&\n            ((ha[i][M] == Swede && ha[i][A] != Dog) ||\n             (ha[i][M] != Swede && ha[i][A] == Dog)))\n            return Invalid;\n\n        \n        if ((ha[i][M] >= 0 && ha[i][D] >= 0) &&\n            ((ha[i][M] == Dane && ha[i][D] != Tea) ||\n             (ha[i][M] != Dane && ha[i][D] == Tea)))\n            return Invalid;\n\n        \n        if ((i > 0 && ha[i][C] >= 0  ) &&\n            ((ha[i - 1][C] == Green && ha[i][C] != White) ||\n             (ha[i - 1][C] != Green && ha[i][C] == White)))\n            return Invalid;\n\n        \n        if ((ha[i][C] >= 0 && ha[i][D] >= 0) &&\n            ((ha[i][C] == Green && ha[i][D] != Coffee) ||\n             (ha[i][C] != Green && ha[i][D] == Coffee)))\n            return Invalid;\n\n        \n        if ((ha[i][S] >= 0 && ha[i][A] >= 0) &&\n            ((ha[i][S] == PallMall && ha[i][A] != Birds) ||\n             (ha[i][S] != PallMall && ha[i][A] == Birds)))\n            return Invalid;\n\n        \n        if ((ha[i][S] >= 0 && ha[i][C] >= 0) &&\n            ((ha[i][S] == Dunhill && ha[i][C] != Yellow) ||\n             (ha[i][S] != Dunhill && ha[i][C] == Yellow)))\n            return Invalid;\n\n        \n        if (ha[i][S] == Blend) {\n            if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats)\n                return Invalid;\n            else if (i == 4 && ha[i - 1][A] != Cats)\n                return Invalid;\n            else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats && ha[i - 1][A] != Cats)\n                return Invalid;\n        }\n\n        \n        if (ha[i][S] == Dunhill) {\n            if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse)\n                return Invalid;\n            else if (i == 4 && ha[i - 1][A] != Horse)\n                return Invalid;\n            else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse && ha[i - 1][A] != Horse)\n                return Invalid;\n        }\n\n        \n        if ((ha[i][S] >= 0 && ha[i][D] >= 0) &&\n            ((ha[i][S] == BlueMaster && ha[i][D] != Beer) ||\n             (ha[i][S] != BlueMaster && ha[i][D] == Beer)))\n            return Invalid;\n\n        \n        if ((ha[i][M] >= 0 && ha[i][S] >= 0) &&\n            ((ha[i][M] == German && ha[i][S] != Prince) ||\n             (ha[i][M] != German && ha[i][S] == Prince)))\n            return Invalid;\n\n        \n        if (ha[i][M] == Norwegian &&\n            ((i < 4 && ha[i + 1][C] >= 0 && ha[i + 1][C] != Blue) ||\n             (i > 0 && ha[i - 1][C] != Blue)))\n            return Invalid;\n\n        \n        if (ha[i][S] == Blend) {\n            if (i == 0 && ha[i + 1][D] >= 0 && ha[i + 1][D] != Water)\n                return Invalid;\n            else if (i == 4 && ha[i - 1][D] != Water)\n                return Invalid;\n            else if (ha[i + 1][D] >= 0 && ha[i + 1][D] != Water && ha[i - 1][D] != Water)\n                return Invalid;\n        }\n\n    }\n\n    if ((c_add != c_or) || (m_add != m_or) || (d_add != d_or)\n        || (a_add != a_or) || (s_add != s_or)) {\n        return Invalid;\n    }\n\n    if ((c_add != 0b11111) || (m_add != 0b11111) || (d_add != 0b11111)\n        || (a_add != 0b11111) || (s_add != 0b11111)) {\n        return Underfull;\n    }\n\n    return Valid;\n}\n\n\nint bruteFill(int ha[5][5], int hno, int attr) {\n    int stat = checkHouses(ha);\n    if ((stat == Valid) || (stat == Invalid))\n        return stat;\n\n    int hb[5][5];\n    memcpy(hb, ha, sizeof(int) * 5 * 5);\n    for (int i = 0; i < 5; i++) {\n        hb[hno][attr] = i;\n        stat = checkHouses(hb);\n        if (stat != Invalid) {\n            int nexthno, nextattr;\n            if (attr < 4) {\n                nextattr = attr + 1;\n                nexthno = hno;\n            } else {\n                nextattr = 0;\n                nexthno = hno + 1;\n            }\n\n            stat = bruteFill(hb, nexthno, nextattr);\n            if (stat != Invalid) {\n                memcpy(ha, hb, sizeof(int) * 5 * 5);\n                return stat;\n            }\n        }\n    }\n\n    \n    return Invalid;\n}\n\n\nint main() {\n    int ha[5][5] = {{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},\n                    {-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},\n                    {-1, -1, -1, -1, -1}};\n\n    bruteFill(ha, 0, 0);\n    printHouses(ha);\n\n    return 0;\n}\n", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n"}
{"id": 48082, "name": "Rosetta Code_Find unimplemented tasks", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n"}
{"id": 48083, "name": "Rosetta Code_Find unimplemented tasks", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n"}
{"id": 48084, "name": "Plasma effect", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n"}
{"id": 48085, "name": "Plasma effect", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n"}
{"id": 48086, "name": "Variables", "C": "int j;\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 48087, "name": "Wordle comparison", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid wordle(const char *answer, const char *guess, int *result) {\n    int i, ix, n = strlen(guess);\n    char *ptr;\n    if (n != strlen(answer)) {\n        printf(\"The words must be of the same length.\\n\");\n        exit(1);\n    }\n    char answer2[n+1];\n    strcpy(answer2, answer);\n    for (i = 0; i < n; ++i) {\n        if (guess[i] == answer2[i]) {\n            answer2[i] = '\\v';\n            result[i] = 2;\n        }\n    }\n    for (i = 0; i < n; ++i) {\n        if ((ptr = strchr(answer2, guess[i])) != NULL) {\n            ix = ptr - answer2;\n            answer2[ix] = '\\v';\n            result[i] = 1;\n        }\n    }\n}\n\nint main() {\n    int i, j;\n    const char *answer, *guess;\n    int res[5];\n    const char *res2[5];\n    const char *colors[3] = {\"grey\", \"yellow\", \"green\"};\n    const char *pairs[5][2] = {\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"}\n    };\n    for (i = 0; i < 5; ++i) {\n        answer = pairs[i][0];\n        guess  = pairs[i][1];\n        for (j = 0; j < 5; ++j) res[j] = 0;\n        wordle(answer, guess, res);\n        for (j = 0; j < 5; ++j) res2[j] = colors[res[j]];\n        printf(\"%s v %s => { \", answer, guess);\n        for (j = 0; j < 5; ++j) printf(\"%d \", res[j]);\n        printf(\"} => { \");\n        for (j = 0; j < 5; ++j) printf(\"%s \", res2[j]);\n        printf(\"}\\n\");\n    }\n    return 0;\n}\n", "Python": "\n\nfrom functools import reduce\nfrom operator import add\n\n\n\ndef wordleScore(target, guess):\n    \n    return mapAccumL(amber)(\n        *first(charCounts)(\n            mapAccumL(green)(\n                [], zip(target, guess)\n            )\n        )\n    )[1]\n\n\n\ndef green(residue, tg):\n    \n    t, g = tg\n    return (residue, (g, 2)) if t == g else (\n        [t] + residue, (g, 0)\n    )\n\n\n\ndef amber(tally, cn):\n    \n    c, n = cn\n    return (tally, 2) if 2 == n else (\n        adjust(\n            lambda x: x - 1,\n            c, tally\n        ),\n        1\n    ) if 0 < tally.get(c, 0) else (tally, 0)\n\n\n\n\ndef main():\n    \n    print(' -> '.join(['Target', 'Guess', 'Scores']))\n    print()\n    print(\n        '\\n'.join([\n            wordleReport(*tg) for tg in [\n                (\"ALLOW\", \"LOLLY\"),\n                (\"CHANT\", \"LATTE\"),\n                (\"ROBIN\", \"ALERT\"),\n                (\"ROBIN\", \"SONIC\"),\n                (\"ROBIN\", \"ROBIN\"),\n                (\"BULLY\", \"LOLLY\"),\n                (\"ADAPT\", \"SÅLÅD\"),\n                (\"Ukraine\", \"Ukraíne\"),\n                (\"BBAAB\", \"BBBBBAA\"),\n                (\"BBAABBB\", \"AABBBAA\")\n            ]\n        ])\n    )\n\n\n\ndef wordleReport(target, guess):\n    \n    scoreName = {2: 'green', 1: 'amber', 0: 'gray'}\n\n    if 5 != len(target):\n        return f'{target}: Expected 5 character target.'\n    elif 5 != len(guess):\n        return f'{guess}: Expected 5 character guess.'\n    else:\n        scores = wordleScore(target, guess)\n        return ' -> '.join([\n            target, guess, repr(scores),\n            ' '.join([\n                scoreName[n] for n in scores\n            ])\n        ])\n\n\n\n\n\ndef adjust(f, k, dct):\n    \n    return dict(\n        dct,\n        **{k: f(dct[k]) if k in dct else None}\n    )\n\n\n\ndef charCounts(s):\n    \n    return reduce(\n        lambda a, c: insertWith(add)(c)(1)(a),\n        list(s),\n        {}\n    )\n\n\n\ndef first(f):\n    \n    return lambda xy: (f(xy[0]), xy[1])\n\n\n\n\ndef insertWith(f):\n    \n    return lambda k: lambda x: lambda dct: dict(\n        dct,\n        **{k: f(dct[k], x) if k in dct else x}\n    )\n\n\n\n\ndef mapAccumL(f):\n    \n    def nxt(a, x):\n        return second(lambda v: a[1] + [v])(\n            f(a[0], x)\n        )\n    return lambda acc, xs: reduce(\n        nxt, xs, (acc, [])\n    )\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48088, "name": "Color quantization", "C": "typedef struct oct_node_t oct_node_t, *oct_node;\nstruct oct_node_t{\n\t\n\tuint64_t r, g, b;\n\tint count, heap_idx;\n\toct_node kids[8], parent;\n\tunsigned char n_kids, kid_idx, flags, depth;\n};\n\n\ninline int cmp_node(oct_node a, oct_node b)\n{\n\tif (a->n_kids < b->n_kids) return -1;\n\tif (a->n_kids > b->n_kids) return 1;\n\n\tint ac = a->count * (1 + a->kid_idx) >> a->depth;\n\tint bc = b->count * (1 + b->kid_idx) >> b->depth;\n\treturn ac < bc ? -1 : ac > bc;\n}\n\n\noct_node node_insert(oct_node root, unsigned char *pix)\n{\n#\tdefine OCT_DEPTH 8\n\t\n\n\tunsigned char i, bit, depth = 0;\n\tfor (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i])\n\t\t\troot->kids[i] = node_new(i, depth, root);\n\n\t\troot = root->kids[i];\n\t}\n\n\troot->r += pix[0];\n\troot->g += pix[1];\n\troot->b += pix[2];\n\troot->count++;\n\treturn root;\n}\n\n\noct_node node_fold(oct_node p)\n{\n\tif (p->n_kids) abort();\n\toct_node q = p->parent;\n\tq->count += p->count;\n\n\tq->r += p->r;\n\tq->g += p->g;\n\tq->b += p->b;\n\tq->n_kids --;\n\tq->kids[p->kid_idx] = 0;\n\treturn q;\n}\n\n\nvoid color_replace(oct_node root, unsigned char *pix)\n{\n\tunsigned char i, bit;\n\n\tfor (bit = 1 << 7; bit; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i]) break;\n\t\troot = root->kids[i];\n\t}\n\n\tpix[0] = root->r;\n\tpix[1] = root->g;\n\tpix[2] = root->b;\n}\n\n\nvoid color_quant(image im, int n_colors)\n{\n\tint i;\n\tunsigned char *pix = im->pix;\n\tnode_heap heap = { 0, 0, 0 };\n\n\toct_node root = node_new(0, 0, 0), got;\n\tfor (i = 0; i < im->w * im->h; i++, pix += 3)\n\t\theap_add(&heap, node_insert(root, pix));\n\n\twhile (heap.n > n_colors + 1)\n\t\theap_add(&heap, node_fold(pop_heap(&heap)));\n\n\tdouble c;\n\tfor (i = 1; i < heap.n; i++) {\n\t\tgot = heap.buf[i];\n\t\tc = got->count;\n\t\tgot->r = got->r / c + .5;\n\t\tgot->g = got->g / c + .5;\n\t\tgot->b = got->b / c + .5;\n\t\tprintf(\"%2d | %3llu %3llu %3llu (%d pixels)\\n\",\n\t\t\ti, got->r, got->g, got->b, got->count);\n\t}\n\n\tfor (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)\n\t\tcolor_replace(root, pix);\n\n\tnode_free();\n\tfree(heap.buf);\n}\n", "Python": "from PIL import Image\n\nif __name__==\"__main__\":\n\tim = Image.open(\"frog.png\")\n\tim2 = im.quantize(16)\n\tim2.show()\n"}
{"id": 48089, "name": "Function frequency", "C": "#define _POSIX_SOURCE\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <stddef.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\nstruct functionInfo {\n    char* name;\n    int timesCalled;\n    char marked;\n};\nvoid addToList(struct functionInfo** list, struct functionInfo toAdd, \\\n               size_t* numElements, size_t* allocatedSize)\n{\n    static const char* keywords[32] = {\"auto\", \"break\", \"case\", \"char\", \"const\", \\\n                                       \"continue\", \"default\", \"do\", \"double\", \\\n                                       \"else\", \"enum\", \"extern\", \"float\", \"for\", \\\n                                       \"goto\", \"if\", \"int\", \"long\", \"register\", \\\n                                       \"return\", \"short\", \"signed\", \"sizeof\", \\\n                                       \"static\", \"struct\", \"switch\", \"typedef\", \\\n                                       \"union\", \"unsigned\", \"void\", \"volatile\", \\\n                                       \"while\"\n                                      };\n    int i;\n    \n    for (i = 0; i < 32; i++) {\n        if (!strcmp(toAdd.name, keywords[i])) {\n            return;\n        }\n    }\n    if (!*list) {\n        *allocatedSize = 10;\n        *list = calloc(*allocatedSize, sizeof(struct functionInfo));\n        if (!*list) {\n            printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                   *allocatedSize, sizeof(struct functionInfo));\n            abort();\n        }\n        (*list)[0].name = malloc(strlen(toAdd.name)+1);\n        if (!(*list)[0].name) {\n            printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n            abort();\n        }\n        strcpy((*list)[0].name, toAdd.name);\n        (*list)[0].timesCalled = 1;\n        (*list)[0].marked = 0;\n        *numElements = 1;\n    } else {\n        char found = 0;\n        unsigned int i;\n        for (i = 0; i < *numElements; i++) {\n            if (!strcmp((*list)[i].name, toAdd.name)) {\n                found = 1;\n                (*list)[i].timesCalled++;\n                break;\n            }\n        }\n        if (!found) {\n            struct functionInfo* newList = calloc((*allocatedSize)+10, \\\n                                                  sizeof(struct functionInfo));\n            if (!newList) {\n                printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                       (*allocatedSize)+10, sizeof(struct functionInfo));\n                abort();\n            }\n            memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo));\n            free(*list);\n            *allocatedSize += 10;\n            *list = newList;\n            (*list)[*numElements].name = malloc(strlen(toAdd.name)+1);\n            if (!(*list)[*numElements].name) {\n                printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n                abort();\n            }\n            strcpy((*list)[*numElements].name, toAdd.name);\n            (*list)[*numElements].timesCalled = 1;\n            (*list)[*numElements].marked = 0;\n            (*numElements)++;\n        }\n    }\n}\nvoid printList(struct functionInfo** list, size_t numElements)\n{\n    char maxSet = 0;\n    unsigned int i;\n    size_t maxIndex = 0;\n    for (i = 0; i<10; i++) {\n        maxSet = 0;\n        size_t j;\n        for (j = 0; j<numElements; j++) {\n            if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) {\n                if (!(*list)[j].marked) {\n                    maxSet = 1;\n                    maxIndex = j;\n                }\n            }\n        }\n        (*list)[maxIndex].marked = 1;\n        printf(\"%s() called %d times.\\n\", (*list)[maxIndex].name, \\\n               (*list)[maxIndex].timesCalled);\n    }\n}\nvoid freeList(struct functionInfo** list, size_t numElements)\n{\n    size_t i;\n    for (i = 0; i<numElements; i++) {\n        free((*list)[i].name);\n    }\n    free(*list);\n}\nchar* extractFunctionName(char* readHead)\n{\n    char* identifier = readHead;\n    if (isalpha(*identifier) || *identifier == '_') {\n        while (isalnum(*identifier) || *identifier == '_') {\n            identifier++;\n        }\n    }\n    \n    char* toParen = identifier;\n    if (toParen == readHead) return NULL;\n    while (isspace(*toParen)) {\n        toParen++;\n    }\n    if (*toParen != '(') return NULL;\n    \n    ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \\\n                     - ((ptrdiff_t)readHead)+1;\n    char* const name = malloc(size);\n    if (!name) {\n        printf(\"Failed to allocate %lu bytes.\\n\", size);\n        abort();\n    }\n    name[size-1] = '\\0';\n    memcpy(name, readHead, size-1);\n    \n    if (strcmp(name, \"\")) {\n        return name;\n    }\n    free(name);\n    return NULL;\n}\nint main(int argc, char** argv)\n{\n    int i;\n    for (i = 1; i<argc; i++) {\n        errno = 0;\n        FILE* file = fopen(argv[i], \"r\");\n        if (errno || !file) {\n            printf(\"fopen() failed with error code \\\"%s\\\"\\n\", \\\n                   strerror(errno));\n            abort();\n        }\n        char comment = 0;\n#define DOUBLEQUOTE 1\n#define SINGLEQUOTE 2\n        int string = 0;\n        struct functionInfo* functions = NULL;\n        struct functionInfo toAdd;\n        size_t numElements = 0;\n        size_t allocatedSize = 0;\n        struct stat metaData;\n        errno = 0;\n        if (fstat(fileno(file), &metaData) < 0) {\n            printf(\"fstat() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \\\n                                          MAP_PRIVATE, fileno(file), 0);\n        if (errno) {\n            printf(\"mmap() failed with error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        if (!mmappedSource) {\n            printf(\"mmap() returned NULL.\\n\");\n            abort();\n        }\n        char* readHead = mmappedSource;\n        while (readHead < mmappedSource + metaData.st_size) {\n            while (*readHead) {\n                \n                if (!string) {\n                    if (*readHead == '/' && !strncmp(readHead, \"\", 2)) {\n                        comment = 0;\n                    }\n                }\n                \n                if (!comment) {\n                    if (*readHead == '\"') {\n                        if (!string) {\n                            string = DOUBLEQUOTE;\n                        } else if (string == DOUBLEQUOTE) {\n                            \n                            if (strncmp((readHead-1), \"\\\\\\\"\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                    if (*readHead == '\\'') {\n                        if (!string) {\n                            string = SINGLEQUOTE;\n                        } else if (string == SINGLEQUOTE) {\n                            if (strncmp((readHead-1), \"\\\\\\'\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                }\n                \n                if (!comment && !string) {\n                    char* name = extractFunctionName(readHead);\n                    \n                    if (name) {\n                        toAdd.name = name;\n                        addToList(&functions, toAdd, &numElements, &allocatedSize);\n                        readHead += strlen(name);\n                    }\n                    free(name);\n                }\n                readHead++;\n            }\n        }\n        errno = 0;\n        munmap(mmappedSource, metaData.st_size);\n        if (errno) {\n            printf(\"munmap() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        errno = 0;\n        fclose(file);\n        if (errno) {\n            printf(\"fclose() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        printList(&functions, numElements);\n        freeList(&functions, numElements);\n    }\n    return 0;\n}\n", "Python": "import ast\n\nclass CallCountingVisitor(ast.NodeVisitor):\n\n    def __init__(self):\n        self.calls = {}\n\n    def visit_Call(self, node):\n        if isinstance(node.func, ast.Name):\n            fun_name = node.func.id\n            call_count = self.calls.get(fun_name, 0)\n            self.calls[fun_name] = call_count + 1\n        self.generic_visit(node)\n\nfilename = input('Enter a filename to parse: ')\nwith open(filename, encoding='utf-8') as f:\n    contents = f.read()\nroot = ast.parse(contents, filename=filename) \nvisitor = CallCountingVisitor()\nvisitor.visit(root)\ntop10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10]\nfor name, count in top10:\n    print(name,'called',count,'times')\n"}
{"id": 48090, "name": "Unicode strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n", "Python": "\n\n\nu = 'abcdé'\nprint(ord(u[-1]))\n"}
{"id": 48091, "name": "Unicode strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n", "Python": "\n\n\nu = 'abcdé'\nprint(ord(u[-1]))\n"}
{"id": 48092, "name": "Bitmap_Read an image through a pipe", "C": "image read_image(const char *name);\n", "Python": "\n\nfrom PIL import Image\n\n\n\nim = Image.open(\"boxes_1.jpg\")\nim.save(\"boxes_1v2.ppm\")\n"}
{"id": 48093, "name": "Memory layout of a data structure", "C": "struct RS232_data\n{\n  unsigned carrier_detect        : 1;\n  unsigned received_data         : 1;\n  unsigned transmitted_data      : 1;\n  unsigned data_terminal_ready   : 1;\n  unsigned signal_ground         : 1;\n  unsigned data_set_ready        : 1;\n  unsigned request_to_send       : 1;\n  unsigned clear_to_send         : 1;\n  unsigned ring_indicator        : 1;\n};\n", "Python": "from ctypes import Structure, c_int\n\nrs232_9pin  = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg\"\n                \"_11 SCD SCS STD TC  SRD RC\"\n                \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]\n"}
{"id": 48094, "name": "Sum of two adjacent numbers are primes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nvoid primeSieve(int *c, int limit, bool processEven, bool primesOnly) {\n    int i, ix, p, p2;\n    limit++;\n    c[0] = TRUE;\n    c[1] = TRUE;\n    if (processEven) {\n        for (i = 4; i < limit; i +=2) c[i] = TRUE;\n    }\n    p = 3;\n    while (TRUE) {\n        p2 = p * p;\n        if (p2 >= limit) break;\n        for (i = p2; i < limit; i += 2*p) c[i] = TRUE;\n        while (TRUE) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    if (primesOnly) {\n        \n        c[0] = 2;\n        for (i = 3, ix = 1; i < limit; i += 2) {\n            if (!c[i]) c[ix++] = i;\n        }\n    }\n}\n\nint main() {\n    int i, p, hp, n = 10000000;\n    int limit = (int)(log(n) * (double)n * 1.2);  \n    int *primes = (int *)calloc(limit, sizeof(int));\n    primeSieve(primes, limit-1, FALSE, TRUE);\n    printf(\"The first 20 pairs of natural numbers whose sum is prime are:\\n\");\n    for (i = 1; i <= 20; ++i) {\n        p = primes[i];\n        hp = p / 2;\n        printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    }\n    printf(\"\\nThe 10 millionth such pair is:\\n\");\n    p = primes[n];\n    hp = p / 2;\n    printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    free(primes);\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == \"__main__\":\n    n = 0\n    num = 0\n\n    print('The first 20 pairs of numbers whose sum is prime:') \n    while True:\n        n += 1\n        suma = 2*n+1\n        if isPrime(suma):\n            num += 1\n            if num < 21:\n                print('{:2}'.format(n), \"+\", '{:2}'.format(n+1), \"=\", '{:2}'.format(suma))\n            else:\n                break\n"}
{"id": 48095, "name": "Sum of two adjacent numbers are primes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nvoid primeSieve(int *c, int limit, bool processEven, bool primesOnly) {\n    int i, ix, p, p2;\n    limit++;\n    c[0] = TRUE;\n    c[1] = TRUE;\n    if (processEven) {\n        for (i = 4; i < limit; i +=2) c[i] = TRUE;\n    }\n    p = 3;\n    while (TRUE) {\n        p2 = p * p;\n        if (p2 >= limit) break;\n        for (i = p2; i < limit; i += 2*p) c[i] = TRUE;\n        while (TRUE) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    if (primesOnly) {\n        \n        c[0] = 2;\n        for (i = 3, ix = 1; i < limit; i += 2) {\n            if (!c[i]) c[ix++] = i;\n        }\n    }\n}\n\nint main() {\n    int i, p, hp, n = 10000000;\n    int limit = (int)(log(n) * (double)n * 1.2);  \n    int *primes = (int *)calloc(limit, sizeof(int));\n    primeSieve(primes, limit-1, FALSE, TRUE);\n    printf(\"The first 20 pairs of natural numbers whose sum is prime are:\\n\");\n    for (i = 1; i <= 20; ++i) {\n        p = primes[i];\n        hp = p / 2;\n        printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    }\n    printf(\"\\nThe 10 millionth such pair is:\\n\");\n    p = primes[n];\n    hp = p / 2;\n    printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    free(primes);\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == \"__main__\":\n    n = 0\n    num = 0\n\n    print('The first 20 pairs of numbers whose sum is prime:') \n    while True:\n        n += 1\n        suma = 2*n+1\n        if isPrime(suma):\n            num += 1\n            if num < 21:\n                print('{:2}'.format(n), \"+\", '{:2}'.format(n+1), \"=\", '{:2}'.format(suma))\n            else:\n                break\n"}
{"id": 48096, "name": "Periodic table", "C": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\n\nGD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );\nint select_box_chemical_elem( RDS(MT_CELL, Elements) );\nvoid put_information(RDS( MT_CELL, elem), int i);\n\nMain\n   \n   GD_VIDEO table;\n   \n   Resize_terminal(42,135);\n   Init_video( &table );\n   \n   Gpm_Connect conn;\n\n   if ( ! Init_mouse(&conn)){\n        Msg_red(\"No se puede conectar al servidor del ratón\\n\");\n        Stop(1);\n   }  \n   Enable_raw_mode();\n   Hide_cursor;\n\n   \n   New multitype Elements;\n   Elements = load_chem_elements( pSDS(Elements) );\n   Throw( load_fail );\n   \n  \n   New objects Btn_exit;\n   Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, \"  Terminar  \", 6,44, 15, 0);\n\n  \n   table = put_chemical_cell( table, SDS(Elements) );\n\n  \n   Refresh(table);\n   Put object Btn_exit;\n  \n  \n   int c;\n   Waiting_some_clic(c)\n   {\n       if( select_box_chemical_elem(SDS(Elements)) ){\n           Waiting_some_clic(c) break;\n       }\n       if (Object_mouse( Btn_exit)) break;\n       \n       Refresh(table);\n       Put object Btn_exit;\n   }\n\n   Free object Btn_exit;\n   Free multitype Elements;\n   \n   Exception( load_fail ){\n      Msg_red(\"No es un archivo matriciable\");\n   }\n\n   Free video table;\n   Disable_raw_mode();\n   Close_mouse();\n   Show_cursor;\n   \n   At SIZE_TERM_ROWS,0;\n   Prnl;\nEnd\n\nvoid put_information(RDS(MT_CELL, elem), int i)\n{\n    At 2,19;\n    Box_solid(11,64,67,17);\n    Color(15,17);\n    At 4,22; Print \"Elemento (%s) = %s\", (char*)$s-elem[i,5],(char*)$s-elem[i,6];\n    if (Cell_type(elem,i,7) == double_TYPE ){\n        At 5,22; Print \"Peso atómico  = %f\", $d-elem[i,7];\n    }else{\n        At 5,22; Print \"Peso atómico  = (%ld)\", $l-elem[i,7];\n    }\n    At 6,22; Print \"Posición      = (%ld, %ld)\",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;\n    At 8,22; Print \"1ª energía de\";\n    if (Cell_type(elem,i,12) == double_TYPE ){\n        At 9,22; Print \"ionización (kJ/mol) = %.*f\",2,$d-elem[i,12];\n    }else{\n        At 9,22; Print \"ionización (kJ/mol) = ---\";\n    }\n    if (Cell_type(elem,i,13) == double_TYPE ){\n        At 10,22; Print \"Electronegatividad  = %.*f\",2,$d-elem[i,13];\n    }else{\n        At 10,22; Print \"Electronegatividad  = ---\";\n    }\n    At 4,56; Print \"Conf. electrónica:\";\n    At 5,56; Print \"       %s\", (char*)$s-elem[i,14];\n    At 7,56; Print \"Estados de oxidación:\";\n    if ( Cell_type(elem,i,15) == string_TYPE ){\n        At 8,56; Print \"       %s\", (char*)$s-elem[i,15];\n    }else{\n       \n        At 8,56; Print \"       %ld\", $l-elem[i,15];\n    }\n    At 10,56; Print \"Número Atómico: %ld\",$l-elem[i,4];\n    Reset_color;\n}\n\nint select_box_chemical_elem( RDS(MT_CELL, elem) )\n{\n   int i;\n   Iterator up i [0:1:Rows(elem)]{\n       if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){\n           Gotoxy( $l-elem[i,8], $l-elem[i,9] );\n           Color_fore( 15 ); Color_back( 0 );\n           Box( 4,5, DOUB_ALL );\n\n           Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print \"%ld\",$l-elem[i,4];\n           Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print \"%s\",(char*)$s-elem[i,5];\n           Flush_out;\n           Reset_color;\n           put_information(SDS(elem),i);\n           return 1;\n       }\n   }\n   return 0;\n}\n\nGD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)\n{\n   int i;\n   \n   \n   Iterator up i [0:1:Rows(elem)]{\n       long rx = 2+($l-elem[i,0]*4);\n       long cx = 3+($l-elem[i,1]*7);\n       long offr = rx+3;\n       long offc = cx+6;\n\n       Gotoxy(table, rx, cx);\n\n       Color_fore(table, $l-elem[i,2]);\n       Color_back(table,$l-elem[i,3]);\n\n       Box(table, 4,5, SING_ALL );\n\n       char Atnum[50], Elem[50];\n       sprintf(Atnum,\"\\x1b[3m%ld\\x1b[23m\",$l-elem[i,4]);\n       sprintf(Elem, \"\\x1b[1m%s\\x1b[22m\",(char*)$s-elem[i,5]);\n\n       Outvid(table,rx+1, cx+2, Atnum);\n       Outvid(table,rx+2, cx+2, Elem);\n\n       Reset_text(table);\n       \n       $l-elem[i,8] = rx;\n       $l-elem[i,9] = cx;\n       $l-elem[i,10] = offr;\n       $l-elem[i,11] = offc;\n       \n   }\n   \n   Iterator up i [ 1: 1: 19 ]{\n       Gotoxy(table, 31, 5+(i-1)*7);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Iterator up i [ 1: 1: 8 ]{\n       Gotoxy(table, 3+(i-1)*4, 130);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Outvid( table, 35,116, \"8\");\n   Outvid( table, 39,116, \"9\");\n   \n   \n   Color_fore(table, 15);\n   Color_back(table, 0);\n   Outvid(table,35,2,\"Lantánidos ->\");\n   Outvid(table,39,2,\"Actínidos  ->\");\n   Reset_text(table);\n   return table;\n}\n\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )\n{\n   F_STAT dataFile = Stat_file(\"chem_table.txt\");\n   if( dataFile.is_matrix ){\n       \n       Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n       E = Load_matrix_mt( SDS(E), \"chem_table.txt\", dataFile, DET_LONG);\n   }else{\n       Is_ok=0;\n   }\n   return E;\n}\n", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n"}
{"id": 48097, "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", "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": 48098, "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", "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": 48099, "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", "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": 48100, "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", "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": 48101, "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", "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": 48102, "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", "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": 48103, "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", "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": 48104, "name": "String comparison", "C": "\nif (strcmp(a,b)) action_on_equality();\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": 48105, "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", "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": 48106, "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", "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": 48107, "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", "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": 48108, "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", "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": 48109, "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", "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": 48110, "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", "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": 48111, "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", "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": 48112, "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", "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": 48113, "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", "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": 48114, "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", "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": 48115, "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", "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": 48116, "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", "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": 48117, "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", "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": 48118, "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", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n"}
{"id": 48119, "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", "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": 48120, "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", "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": 48121, "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", "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": 48122, "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", "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": 48123, "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", "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": 48124, "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", "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": 48125, "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", "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": 48126, "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", "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": 48127, "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", "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": 48128, "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", "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": 48129, "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", "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": 48130, "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", "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": 48131, "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", "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": 48132, "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", "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": 48133, "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", "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": 48134, "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", "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": 48135, "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", "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": 48136, "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", "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": 48137, "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", "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": 48138, "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", "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": 48139, "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", "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": 48140, "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", "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": 48141, "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", "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": 48142, "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", "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": 48143, "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", "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": 48144, "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", "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": 48145, "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", "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": 48146, "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", "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": 48147, "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", "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": 48148, "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", "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": 48149, "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", "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": 48150, "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", "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": 48151, "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", "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": 48152, "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", "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": 48153, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\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": 48154, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\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": 48155, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 48156, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 48157, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 48158, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 48159, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 48160, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 48161, "name": "Checkpoint synchronization", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 48162, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 48163, "name": "SHA-256 Merkle tree", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\n"}
{"id": 48164, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 48165, "name": "User input_Graphical", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n"}
{"id": 48166, "name": "Sierpinski arrowhead curve", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\n"}
{"id": 48167, "name": "Text processing_1", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n"}
{"id": 48168, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 48169, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 48170, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 48171, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 48172, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 48173, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 48174, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 48175, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 48176, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 48177, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 48178, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 48179, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 48180, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 48181, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 48182, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 48183, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 48184, "name": "Fractran", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n"}
{"id": 48185, "name": "Sorting algorithms_Stooge sort", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 48186, "name": "Galton box animation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\n", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n"}
{"id": 48187, "name": "Sorting Algorithms_Circle Sort", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\n"}
{"id": 48188, "name": "Kronecker product based fractals", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\n"}
{"id": 48189, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 48190, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 48191, "name": "Circular primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n"}
{"id": 48192, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 48193, "name": "Sorting algorithms_Radix sort", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n"}
{"id": 48194, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n"}
{"id": 48195, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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 sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 48196, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 48197, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 48198, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 48199, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 48200, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 48201, "name": "Singleton", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 48202, "name": "Safe addition", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n"}
{"id": 48203, "name": "Case-sensitivity of identifiers", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 48204, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 48205, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 48206, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 48207, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 48208, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 48209, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 48210, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 48211, "name": "Non-continuous subsequences", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n"}
{"id": 48212, "name": "Fibonacci word_fractal", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48213, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 48214, "name": "Roots of unity", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 48215, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 48216, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 48217, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 48218, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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 <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 48219, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 48220, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 48221, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 48222, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 48223, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 48224, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 48225, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 48226, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 48227, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 48228, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 48229, "name": "Carmichael 3 strong pseudoprimes", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 48230, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 48231, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 48232, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 48233, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 48234, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 48235, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 48236, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 48237, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 48238, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 48239, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 48240, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 48241, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 48242, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 48243, "name": "Fermat numbers", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <gmp.h>\n\nvoid mpz_factors(mpz_t n) {\n  int factors = 0;\n  mpz_t s, m, p;\n  mpz_init(s), mpz_init(m), mpz_init(p);\n\n  mpz_set_ui(m, 3);\n  mpz_set(p, n);\n  mpz_sqrt(s, p);\n\n  while (mpz_cmp(m, s) < 0) {\n    if (mpz_divisible_p(p, m)) {\n      gmp_printf(\"%Zd \", m);\n      mpz_fdiv_q(p, p, m);\n      mpz_sqrt(s, p);\n      factors ++;\n    }\n    mpz_add_ui(m, m, 2);\n  }\n\n  if (factors == 0) printf(\"PRIME\\n\");\n  else gmp_printf(\"%Zd\\n\", p);\n}\n\nint main(int argc, char const *argv[]) {\n  mpz_t fermat;\n  mpz_init_set_ui(fermat, 3);\n  printf(\"F(0) = 3 -> PRIME\\n\");\n  for (unsigned i = 1; i < 10; i ++) {\n    mpz_sub_ui(fermat, fermat, 1);\n    mpz_mul(fermat, fermat, fermat);\n    mpz_add_ui(fermat, fermat, 1);\n    gmp_printf(\"F(%d) = %Zd -> \", i, fermat);\n    mpz_factors(fermat);\n  }\n\n  return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class FermatNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 Fermat numbers:\");\n        for ( int i = 0 ; i < 10 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, fermat(i));\n        }\n        System.out.printf(\"%nFirst 12 Fermat numbers factored:%n\");\n        for ( int i = 0 ; i < 13 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, getString(getFactors(i, fermat(i))));\n        }\n    }\n    \n    private static String getString(List<BigInteger> factors) {\n        if ( factors.size() == 1 ) {\n            return factors.get(0) + \" (PRIME)\";\n        }\n        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith(\"-\") ? \"(C\" + v.replace(\"-\", \"\") + \")\" : v).collect(Collectors.joining(\" * \"));\n    }\n\n    private static Map<Integer, String> COMPOSITE = new HashMap<>();\n    static {\n        COMPOSITE.put(9, \"5529\");\n        COMPOSITE.put(10, \"6078\");\n        COMPOSITE.put(11, \"1037\");\n        COMPOSITE.put(12, \"5488\");\n        COMPOSITE.put(13, \"2884\");\n    }\n\n    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {\n        List<BigInteger> factors = new ArrayList<>();\n        BigInteger factor = BigInteger.ONE;\n        while ( true ) {\n            if ( n.isProbablePrime(100) ) {\n                factors.add(n);\n                break;\n            }\n            else {\n                if ( COMPOSITE.containsKey(fermatIndex) ) {\n                    String stop = COMPOSITE.get(fermatIndex);\n                    if ( n.toString().startsWith(stop) ) {\n                        factors.add(new BigInteger(\"-\" + n.toString().length()));\n                        break;\n                    }\n                }\n                factor = pollardRhoFast(n);\n                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {\n                    factors.add(n);\n                    break;\n                }\n                else {\n                    factors.add(factor);\n                    n = n.divide(factor);\n                }\n            }\n        }\n        return factors;\n    }\n    \n    private static final BigInteger TWO = BigInteger.valueOf(2);\n    \n    private static BigInteger fermat(int n) {\n        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);\n    }\n        \n    \n    @SuppressWarnings(\"unused\")\n    private static BigInteger pollardRho(BigInteger n) {\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        while ( d.compareTo(BigInteger.ONE) == 0 ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs().gcd(n);\n        }\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n    \n    \n    \n    \n    \n    \n    private static BigInteger pollardRhoFast(BigInteger n) {\n        long start = System.currentTimeMillis();\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        int count = 0;\n        BigInteger z = BigInteger.ONE;\n        while ( true ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs();\n            z = z.multiply(d).mod(n);\n            count++;\n            if ( count == 100 ) {\n                d = z.gcd(n);\n                if ( d.compareTo(BigInteger.ONE) != 0 ) {\n                    break;\n                }\n                z = BigInteger.ONE;\n                count = 0;\n            }\n        }\n        long end = System.currentTimeMillis();\n        System.out.printf(\"    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n\", n, (end-start), d);\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n\n    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {\n        return x.multiply(x).add(BigInteger.ONE).mod(n);\n    }\n\n}\n"}
{"id": 48244, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 48245, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 48246, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 48247, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 48248, "name": "Water collected between towers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n"}
{"id": 48249, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 48250, "name": "Jaro similarity", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n"}
{"id": 48251, "name": "Sum and product puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n"}
{"id": 48252, "name": "Fairshare between two and more", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 48253, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 48254, "name": "Prime triangle", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n"}
{"id": 48255, "name": "Trabb Pardo–Knuth algorithm", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 48256, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 48257, "name": "Sequence_ nth number with exactly n divisors", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(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 SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n"}
{"id": 48258, "name": "Sequence_ smallest number with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n"}
{"id": 48259, "name": "Pancake numbers", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 48260, "name": "Generate random chess position", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n"}
{"id": 48261, "name": "Esthetic numbers", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n"}
{"id": 48262, "name": "Topswops", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n"}
{"id": 48263, "name": "Old Russian measure of length", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n"}
{"id": 48264, "name": "Old Russian measure of length", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n"}
{"id": 48265, "name": "Rate counter", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n"}
{"id": 48266, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 48267, "name": "Pythagoras tree", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48268, "name": "Pythagoras tree", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48269, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 48270, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 48271, "name": "Colorful numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 48272, "name": "Colorful numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 48273, "name": "Rosetta Code_Tasks without examples", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_tasks_without_examples.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Java": "import java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\n\npublic class TasksWithoutExamples {\n    private static String readPage(HttpClient client, URI uri) throws IOException, InterruptedException {\n        var request = HttpRequest.newBuilder()\n            .GET()\n            .uri(uri)\n            .timeout(Duration.ofSeconds(5))\n            .setHeader(\"accept\", \"text/html\")\n            .build();\n\n        var response = client.send(request, HttpResponse.BodyHandlers.ofString());\n        return response.body();\n    }\n\n    private static void process(HttpClient client, String base, String task) {\n        try {\n            var re = Pattern.compile(\".*using any language you may know.</div>(.*?)<div id=\\\"toc\\\".*\", Pattern.DOTALL + Pattern.MULTILINE);\n            var re2 = Pattern.compile(\"</?[^>]*>\");\n\n            var page = base + task;\n            String body = readPage(client, new URI(page));\n\n            var matcher = re.matcher(body);\n            if (matcher.matches()) {\n                var group = matcher.group(1);\n                var m2 = re2.matcher(group);\n                var text = m2.replaceAll(\"\");\n                System.out.println(text);\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {\n        var re = Pattern.compile(\"<li><a href=\\\"/wiki/(.*?)\\\"\", Pattern.DOTALL + Pattern.MULTILINE);\n\n        var client = HttpClient.newBuilder()\n            .version(HttpClient.Version.HTTP_1_1)\n            .followRedirects(HttpClient.Redirect.NORMAL)\n            .connectTimeout(Duration.ofSeconds(5))\n            .build();\n\n        var uri = new URI(\"http\", \"rosettacode.org\", \"/wiki/Category:Programming_Tasks\", \"\");\n        var body = readPage(client, uri);\n        var matcher = re.matcher(body);\n\n        var tasks = new ArrayList<String>();\n        while (matcher.find()) {\n            tasks.add(matcher.group(1));\n        }\n\n        var base = \"http:\n        var limit = 3L;\n\n        tasks.stream().limit(limit).forEach(task -> process(client, base, task));\n    }\n}\n"}
{"id": 48274, "name": "Sine wave", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n\nint header[] = {46, 115, 110, 100, 0, 0, 0, 24,\n                255, 255, 255, 255, 0, 0, 0, 3,\n                0, 0, 172, 68, 0, 0, 0, 1};\n\nint main(int argc, char *argv[]){\n        float freq, dur;\n        long i, v;\n\n        if (argc < 3) {\n                printf(\"Usage:\\n\");\n                printf(\"  csine <frequency> <duration>\\n\");\n                exit(1);\n        }\n        freq = atof(argv[1]);\n        dur = atof(argv[2]);\n        for (i = 0; i < 24; i++)\n                putchar(header[i]);\n        for (i = 0; i < dur * 44100; i++) {\n                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));\n                v = v % 65536;\n                putchar(v >> 8);\n                putchar(v % 256);\n        }\n}\n", "Java": "import processing.sound.*;\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\nsine.freq(500);\nsine.play();\n\ndelay(5000);\n"}
{"id": 48275, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n"}
{"id": 48276, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n"}
{"id": 48277, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n"}
{"id": 48278, "name": "Numeric error propagation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n"}
{"id": 48279, "name": "Soundex", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n"}
{"id": 48280, "name": "List rooted trees", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n"}
{"id": 48281, "name": "List rooted trees", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n"}
{"id": 48282, "name": "Documentation", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n"}
{"id": 48283, "name": "Problem of Apollonius", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n"}
{"id": 48284, "name": "Longest common suffix", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n"}
{"id": 48285, "name": "Chat server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 48286, "name": "Idiomatically determine all the lowercase and uppercase letters", "C": "#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n  putchar('\\n');\n  for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n  putchar('\\n');\n  return 0;\n}\n", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n"}
{"id": 48287, "name": "Sum of elements below main diagonal of matrix", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n"}
{"id": 48288, "name": "Sorting algorithms_Tree sort on a linked list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n"}
{"id": 48289, "name": "Sorting algorithms_Tree sort on a linked list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n"}
{"id": 48290, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 48291, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 48292, "name": "Numerical integration_Adaptive Simpson's method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n"}
{"id": 48293, "name": "Numerical integration_Adaptive Simpson's method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n"}
{"id": 48294, "name": "FASTA format", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 48295, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48296, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48297, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48298, "name": "Window creation_X11", "C": "'--- added a flush to exit cleanly   \nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n \n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n \n'---pointer to X Display structure\nDECLARE d TYPE  Display*\n \n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n \n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n \nDECLARE msg TYPE char*\n \n'--- number of screen to place the window on\nDECLARE s TYPE int\n \n \n \n  msg = \"Hello, World!\"\n \n \n   d = DISPLAY(NULL)\n   IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n   END IF\n \n   s = SCREEN(d)\n   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n \n   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n   MAP_EVENT(d, w)\n \n   WHILE  (1) \n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t    BREAK\n\t END IF   \n   WEND\n   FLUSH(d)\n   CLOSE_DISPLAY(d)\n", "Java": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n  public static void main(String[] args) {\n    Runnable runnable = new Runnable() {\n      public void run() {\n\tcreateAndShow();\n      }\n    };\n    SwingUtilities.invokeLater(runnable);\n  }\n\t\n  static void createAndShow() {\n    JFrame frame = new JFrame(\"Hello World\");\n    frame.setSize(640,480);\n    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n}\n"}
{"id": 48299, "name": "Finite state machine", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n"}
{"id": 48300, "name": "Vibrating rectangles", "C": "\n\n#include<graphics.h>\n\nvoid vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)\n{\n\tint color = 1,i,x = winWidth/2, y = winHeight/2;\n\t\n\twhile(!kbhit()){\n\t\tsetcolor(color++);\n\t\tfor(i=num;i>0;i--){\n\t\t\trectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);\n\t\t\tdelay(msec);\n\t\t}\n\n\t\tif(color>MAXCOLORS){\n\t\t\tcolor = 1;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Vibrating Rectangles...\");\n\t\n\tvibratingRectangles(1000,1000,30,15,20,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Java": "\n\nint counter = 100;\n\nvoid setup(){\n  size(1000,1000);\n}\n\nvoid draw(){\n  \n  for(int i=0;i<20;i++){\n    fill(counter - 5*i);\n    rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);\n  }\n  counter++;\n  \n  if(counter > 255)\n    counter = 100;\n  \n  delay(100);\n}\n"}
{"id": 48301, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 48302, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 48303, "name": "Pseudo-random numbers_PCG32", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 48304, "name": "Deconvolution_1D", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n", "Java": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n    public static int[] deconv(int[] g, int[] f) {\n        int[] h = new int[g.length - f.length + 1];\n        for (int n = 0; n < h.length; n++) {\n            h[n] = g[n];\n            int lower = Math.max(n - f.length + 1, 0);\n            for (int i = lower; i < n; i++)\n                h[n] -= h[i] * f[n - i];\n            h[n] /= f[0];\n        }\n        return h;\n    }\n\n    public static void main(String[] args) {\n        int[] h = { -8, -9, -3, -1, -6, 7 };\n        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n                96, 31, 55, 36, 29, -43, -7 };\n\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n        sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n        sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n        sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n        System.out.println(sb.toString());\n    }\n}\n"}
{"id": 48305, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 48306, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 48307, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 48308, "name": "Disarium numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n"}
{"id": 48309, "name": "Disarium numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n"}
{"id": 48310, "name": "Sierpinski pentagon", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n"}
{"id": 48311, "name": "Bitmap_Histogram", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n"}
{"id": 48312, "name": "Mutex", "C": "HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);\n", "Java": "import java.util.concurrent.Semaphore;\n\npublic class VolatileClass{\n   public Semaphore mutex = new Semaphore(1); \n                                              \n   public void needsToBeSynched(){\n      \n   }\n   \n}\n"}
{"id": 48313, "name": "Metronome", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/time.h>\n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); \n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec)   \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}\n", "Java": "class Metronome{\n\tdouble bpm;\n\tint measure, counter;\n\tpublic Metronome(double bpm, int measure){\n\t\tthis.bpm = bpm;\n\t\tthis.measure = measure;\t\n\t}\n\tpublic void start(){\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tThread.sleep((long)(1000*(60.0/bpm)));\n\t\t\t}catch(InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tcounter++;\n\t\t\tif (counter%measure==0){\n\t\t\t\t System.out.println(\"TICK\");\n\t\t\t}else{\n\t\t\t\t System.out.println(\"TOCK\");\n\t\t\t}\n\t\t}\n\t}\n}\npublic class test {\n\tpublic static void main(String[] args) {\n\t\tMetronome metronome1 = new Metronome(120,4);\n\t\tmetronome1.start();\n\t}\n}\n"}
{"id": 48314, "name": "EKG sequence convergence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n    int aa = *(int *)a;\n    int bb = *(int *)b;\n    return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n    int i;\n    for (i = 0; i < len; ++i) {\n        if (a[i] == b) return TRUE;\n    }\n    return FALSE;\n}\n\nint gcd(int a, int b) {\n    while (a != b) {\n        if (a > b)\n            a -= b;\n        else\n            b -= a;\n    }\n    return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n    int i;\n    qsort(s, len, sizeof(int), compareInts);    \n    qsort(t, len, sizeof(int), compareInts);\n    for (i = 0; i < len; ++i) {\n        if (s[i] != t[i]) return FALSE;\n    }\n    return TRUE;\n}\n\nint main() {\n    int s, n, i;\n    int starts[5] = {2, 5, 7, 9, 10};\n    int ekg[5][LIMIT];\n    for (s = 0; s < 5; ++s) {\n        ekg[s][0] = 1;\n        ekg[s][1] = starts[s];\n        for (n = 2; n < LIMIT; ++n) {\n            for (i = 2; ; ++i) {\n                \n                \n                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n                    ekg[s][n] = i;\n                    break;\n                }\n            }\n        }\n        printf(\"EKG(%2d): [\", starts[s]);\n        for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n        printf(\"\\b]\\n\");\n    }\n    \n    \n    for (i = 2; i < LIMIT; ++i) {\n        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n            printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n            return 0;\n        }\n    }\n    printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n    public static void main(String[] args) {\n        System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n        for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n            System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n        }\n        System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n        List<Integer> ekg5 = ekg(5, 100);\n        List<Integer> ekg7 = ekg(7, 100);\n        for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n            if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n                System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n                break;\n            }\n        }\n    }\n    \n    \n    private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {\n        List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));\n        Collections.sort(list1);\n        List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));\n        Collections.sort(list2);\n        for ( int i = 0 ; i < n ; i++ ) {\n            if ( list1.get(i) != list2.get(i) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    \n    \n    private static List<Integer> ekg(int two, int maxN) {\n        List<Integer> result = new ArrayList<>();\n        result.add(1);\n        result.add(two);\n        Map<Integer,Integer> seen = new HashMap<>();\n        seen.put(1, 1);\n        seen.put(two, 1);\n        int minUnseen = two == 2 ? 3 : 2;\n        int prev = two;\n        for ( int n = 3 ; n <= maxN ; n++ ) {\n            int test = minUnseen - 1;\n            while ( true ) {\n                test++;\n                if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n                    \n                    result.add(test);\n                    seen.put(test, n);\n                    prev = test;\n                    if ( minUnseen == test ) {\n                        do {\n                            minUnseen++;\n                        } while ( seen.containsKey(minUnseen) );\n                    }\n                    break;\n                }\n            }\n        }\n        return result;\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": 48315, "name": "Rep-string", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n"}
{"id": 48316, "name": "Terminal control_Preserve screen", "C": "#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n\tint i;\n\tprintf(\"\\033[?1049h\\033[H\");\n\tprintf(\"Alternate screen buffer\\n\");\n\tfor (i = 5; i; i--) {\n\t\tprintf(\"\\rgoing back in %d...\", i);\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tprintf(\"\\033[?1049l\");\n\n\treturn 0;\n}\n", "Java": "public class PreserveScreen\n{\n    public static void main(String[] args) throws InterruptedException {\n        System.out.print(\"\\033[?1049h\\033[H\");\n        System.out.println(\"Alternate screen buffer\\n\");\n        for (int i = 5; i > 0; i--) {\n            String s = (i > 1) ? \"s\" : \"\";\n            System.out.printf(\"\\rgoing back in %d second%s...\", i, s);\n            Thread.sleep(1000);\n        }\n        System.out.print(\"\\033[?1049l\");\n    }\n}\n"}
{"id": 48317, "name": "Literals_String", "C": "char ch = 'z';\n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 48318, "name": "Literals_String", "C": "char ch = 'z';\n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 48319, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n"}
{"id": 48320, "name": "Window management", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n"}
{"id": 48321, "name": "Window management", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n"}
{"id": 48322, "name": "Next special primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 48323, "name": "Next special primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 48324, "name": "Mayan numerals", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\n\npublic class MayanNumerals {\n\n    public static void main(String[] args) {\n        for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {\n            displayMyan(BigInteger.valueOf(base10));\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static char[] digits = \"0123456789ABCDEFGHJK\".toCharArray();\n    private static BigInteger TWENTY = BigInteger.valueOf(20);\n    \n    private static void displayMyan(BigInteger numBase10) {\n        System.out.printf(\"As base 10:  %s%n\", numBase10);\n        String numBase20 = \"\";\n        while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {\n            numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;\n            numBase10 = numBase10.divide(TWENTY);\n        }\n        System.out.printf(\"As base 20:  %s%nAs Mayan:%n\", numBase20);\n        displayMyanLine1(numBase20);\n        displayMyanLine2(numBase20);\n        displayMyanLine3(numBase20);\n        displayMyanLine4(numBase20);\n        displayMyanLine5(numBase20);\n        displayMyanLine6(numBase20);\n    }\n \n    private static char boxUL = Character.toChars(9556)[0];\n    private static char boxTeeUp = Character.toChars(9574)[0];\n    private static char boxUR = Character.toChars(9559)[0];\n    private static char boxHorz = Character.toChars(9552)[0];\n    private static char boxVert = Character.toChars(9553)[0];\n    private static char theta = Character.toChars(952)[0];\n    private static char boxLL = Character.toChars(9562)[0];\n    private static char boxLR = Character.toChars(9565)[0];\n    private static char boxTeeLow = Character.toChars(9577)[0];\n    private static char bullet = Character.toChars(8729)[0];\n    private static char dash = Character.toChars(9472)[0];\n    \n    private static void displayMyanLine1(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxUL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeUp : boxUR);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String getBullet(int count) {\n        StringBuilder sb = new StringBuilder();\n        switch ( count ) {\n        case 1:  sb.append(\" \" + bullet + \"  \"); break;\n        case 2:  sb.append(\" \" + bullet + bullet + \" \"); break;\n        case 3:  sb.append(\"\" + bullet + bullet + bullet + \" \"); break;\n        case 4:  sb.append(\"\" + bullet + bullet + bullet + bullet); break;\n        default:  throw new IllegalArgumentException(\"Must be 1-4:  \" + count);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine2(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'G':  sb.append(getBullet(1)); break;\n            case 'H':  sb.append(getBullet(2)); break;\n            case 'J':  sb.append(getBullet(3)); break;\n            case 'K':  sb.append(getBullet(4)); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String DASH = getDash();\n    \n    private static String getDash() {\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < 4 ; i++ ) {\n            sb.append(dash);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine3(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'B':  sb.append(getBullet(1)); break;\n            case 'C':  sb.append(getBullet(2)); break;\n            case 'D':  sb.append(getBullet(3)); break;\n            case 'E':  sb.append(getBullet(4)); break;\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine4(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '6':  sb.append(getBullet(1)); break;\n            case '7':  sb.append(getBullet(2)); break;\n            case '8':  sb.append(getBullet(3)); break;\n            case '9':  sb.append(getBullet(4)); break;\n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine5(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '0':  sb.append(\" \" + theta + \"  \"); break;\n            case '1':  sb.append(getBullet(1)); break;\n            case '2':  sb.append(getBullet(2)); break;\n            case '3':  sb.append(getBullet(3)); break;\n            case '4':  sb.append(getBullet(4)); break;\n            case '5': case '6': case '7': case '8': case '9': \n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine6(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxLL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeLow : boxLR);\n        }\n        System.out.println(sb.toString());\n    }\n\n}\n"}
{"id": 48325, "name": "Ramsey's theorem", "C": "#include <stdio.h>\n\nint a[17][17], idx[4];\n\nint find_group(int type, int min_n, int max_n, int depth)\n{\n\tint i, n;\n\tif (depth == 4) {\n\t\tprintf(\"totally %sconnected group:\", type ? \"\" : \"un\");\n\t\tfor (i = 0; i < 4; i++) printf(\" %d\", idx[i]);\n\t\tputchar('\\n');\n\t\treturn 1;\n\t}\n\n\tfor (i = min_n; i < max_n; i++) {\n\t\tfor (n = 0; n < depth; n++)\n\t\t\tif (a[idx[n]][i] != type) break;\n\n\t\tif (n == depth) {\n\t\t\tidx[n] = i;\n\t\t\tif (find_group(type, 1, max_n, depth + 1))\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tconst char *mark = \"01-\";\n\n\tfor (i = 0; i < 17; i++)\n\t\ta[i][i] = 2;\n\n\tfor (k = 1; k <= 8; k <<= 1) {\n\t\tfor (i = 0; i < 17; i++) {\n\t\t\tj = (i + k) % 17;\n\t\t\ta[i][j] = a[j][i] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < 17; i++) {\n\t\tfor (j = 0; j < 17; j++)\n\t\t\tprintf(\"%c \", mark[a[i][j]]);\n\t\tputchar('\\n');\n\t}\n\n\t\n\t\n\n\t\n\tfor (i = 0; i < 17; i++) {\n\t\tidx[0] = i;\n\t\tif (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {\n\t\t\tputs(\"no good\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"all good\");\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n"}
{"id": 48326, "name": "GUI_Maximum window dimensions", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n"}
{"id": 48327, "name": "Four is magic", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 48328, "name": "Getting the number of decimals", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n"}
{"id": 48329, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 48330, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 48331, "name": "Paraffins", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 48332, "name": "Paraffins", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 48333, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48334, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48335, "name": "Parse an IP Address", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n"}
{"id": 48336, "name": "Knapsack problem_Unbounded", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n"}
{"id": 48337, "name": "Textonyms", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n"}
{"id": 48338, "name": "Teacup rim text", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n"}
{"id": 48339, "name": "Teacup rim text", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n"}
{"id": 48340, "name": "Increasing gaps between consecutive Niven numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n"}
{"id": 48341, "name": "Print debugging statement", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n"}
{"id": 48342, "name": "Superellipse", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48343, "name": "Permutations_Rank of a permutation", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n"}
{"id": 48344, "name": "Permutations_Rank of a permutation", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n"}
{"id": 48345, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 48346, "name": "Type detection", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n"}
{"id": 48347, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n"}
{"id": 48348, "name": "Zhang-Suen thinning algorithm", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n"}
{"id": 48349, "name": "Variable declaration reset", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n"}
{"id": 48350, "name": "Find first and last set bit of a long integer", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 48351, "name": "Find first and last set bit of a long integer", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 48352, "name": "Numbers with equal rises and falls", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n"}
{"id": 48353, "name": "Koch curve", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n"}
{"id": 48354, "name": "Draw pixel 2", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<time.h>\n\nint main()\n{\n\tsrand(time(NULL));\n\t\n\tinitwindow(640,480,\"Yellow Random Pixel\");\n\t\n\tputpixel(rand()%640,rand()%480,YELLOW);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "Java": "\n\nsize(640,480);\n\nstroke(#ffff00);\n\nellipse(random(640),random(480),1,1);\n"}
{"id": 48355, "name": "Draw a pixel", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n"}
{"id": 48356, "name": "Words from neighbour ones", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n"}
{"id": 48357, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 48358, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 48359, "name": "Magic squares of singly even order", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n"}
{"id": 48360, "name": "Generate Chess960 starting position", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n"}
{"id": 48361, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 48362, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 48363, "name": "Modulinos", "C": "int meaning_of_life();\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 48364, "name": "Modulinos", "C": "int meaning_of_life();\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 48365, "name": "Perlin noise", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n"}
{"id": 48366, "name": "Perlin noise", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n"}
{"id": 48367, "name": "Unix_ls", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 48368, "name": "UTF-8 encode and decode", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n"}
{"id": 48369, "name": "Xiaolin Wu's line algorithm", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48370, "name": "Xiaolin Wu's line algorithm", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48371, "name": "Keyboard macros", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/keysym.h>\n\nint main()\n{\n  Display *d;\n  XEvent event;\n  \n  d = XOpenDisplay(NULL);\n  if ( d != NULL ) {\n                \n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), \n\t     Mod1Mask,  \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), \n\t     Mod1Mask, \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n\n    for(;;)\n    {\n      XNextEvent(d, &event);\n      if ( event.type == KeyPress ) {\n\tKeySym s = XLookupKeysym(&event.xkey, 0);\n\tif ( s == XK_F7 ) {\n\t  printf(\"something's happened\\n\");\n\t} else if ( s == XK_F6 ) {\n\t  break;\n\t}\n      }\n    }\n\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), Mod1Mask, DefaultRootWindow(d));\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), Mod1Mask, DefaultRootWindow(d));\n  }\n  return EXIT_SUCCESS;\n}\n", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n"}
{"id": 48372, "name": "McNuggets problem", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n", "Java": "public class McNuggets {\n\n    public static void main(String... args) {\n        int[] SIZES = new int[] { 6, 9, 20 };\n        int MAX_TOTAL = 100;\n        \n        int numSizes = SIZES.length;\n        int[] counts = new int[numSizes];\n        int maxFound = MAX_TOTAL + 1;\n        boolean[] found = new boolean[maxFound];\n        int numFound = 0;\n        int total = 0;\n        boolean advancedState = false;\n        do {\n            if (!found[total]) {\n                found[total] = true;\n                numFound++;\n            }\n            \n            \n            advancedState = false;\n            for (int i = 0; i < numSizes; i++) {\n                int curSize = SIZES[i];\n                if ((total + curSize) > MAX_TOTAL) {\n                    \n                    total -= counts[i] * curSize;\n                    counts[i] = 0;\n                }\n                else {\n                    \n                    counts[i]++;\n                    total += curSize;\n                    advancedState = true;\n                    break;\n                }\n            }\n            \n        } while ((numFound < maxFound) && advancedState);\n        \n        if (numFound < maxFound) {\n            \n            for (int i = MAX_TOTAL; i >= 0; i--) {\n                if (!found[i]) {\n                    System.out.println(\"Largest non-McNugget number in the search space is \" + i);\n                    break;\n                }\n            }\n        }\n        else {\n            System.out.println(\"All numbers in the search space are McNugget numbers\");\n        }\n        \n        return;\n    }\n}\n"}
{"id": 48373, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 48374, "name": "Extreme floating point values", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 48375, "name": "Extreme floating point values", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 48376, "name": "Pseudo-random numbers_Xorshift star", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 48377, "name": "ASCII art diagram converter", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n"}
{"id": 48378, "name": "ASCII art diagram converter", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n"}
{"id": 48379, "name": "Levenshtein distance_Alignment", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}\n", "Java": "public class LevenshteinAlignment {\n\n    public static String[] alignment(String a, String b) {\n        a = a.toLowerCase();\n        b = b.toLowerCase();\n        \n        int[][] costs = new int[a.length()+1][b.length()+1];\n        for (int j = 0; j <= b.length(); j++)\n            costs[0][j] = j;\n        for (int i = 1; i <= a.length(); i++) {\n            costs[i][0] = i;\n            for (int j = 1; j <= b.length(); j++) {\n                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);\n            }\n        }\n\n\t\n\tStringBuilder aPathRev = new StringBuilder();\n\tStringBuilder bPathRev = new StringBuilder();\n\tfor (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {\n\t    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append(b.charAt(--j));\n\t    } else if (costs[i][j] == 1 + costs[i-1][j]) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append('-');\n\t    } else if (costs[i][j] == 1 + costs[i][j-1]) {\n\t\taPathRev.append('-');\n\t\tbPathRev.append(b.charAt(--j));\n\t    }\n\t}\n        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};\n    }\n\n    public static void main(String[] args) {\n\tString[] result = alignment(\"rosettacode\", \"raisethysword\");\n\tSystem.out.println(result[0]);\n\tSystem.out.println(result[1]);\n    }\n}\n"}
{"id": 48380, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n"}
{"id": 48381, "name": "Simulate input_Keyboard", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n\nint main(int argc, char *argv[])\n{\n  Display *dpy;\n  Window win;\n  GC gc;\n  int scr;\n  Atom WM_DELETE_WINDOW;\n  XEvent ev;\n  XEvent ev2;\n  KeySym keysym;\n  int loop;\n\n  \n  dpy = XOpenDisplay(NULL);\n  if (dpy == NULL) {\n    fputs(\"Cannot open display\", stderr);\n    exit(1);\n  }\n  scr = XDefaultScreen(dpy);\n\n  \n  win = XCreateSimpleWindow(dpy,\n          XRootWindow(dpy, scr),\n          \n          10, 10, 300, 200, 1,\n          \n          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));\n\n  \n  XStoreName(dpy, win, argv[0]);\n\n  \n  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);\n\n  \n  XMapWindow(dpy, win);\n  XFlush(dpy);\n\n  \n  gc = XDefaultGC(dpy, scr);\n\n  \n  WM_DELETE_WINDOW = XInternAtom(dpy, \"WM_DELETE_WINDOW\", True);\n  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);\n\n  \n  loop = 1;\n  while (loop) {\n    XNextEvent(dpy, &ev);\n    switch (ev.type)\n    {\n      case Expose:\n        \n        {\n          char msg1[] = \"Clic in the window to generate\";\n          char msg2[] = \"a key press event\";\n          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);\n          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);\n        }\n        break;\n\n      case ButtonPress:\n        puts(\"ButtonPress event received\");\n        \n        ev2.type = KeyPress;\n        ev2.xkey.state = ShiftMask;\n        ev2.xkey.keycode = 24 + (rand() % 33);\n        ev2.xkey.same_screen = True;\n        XSendEvent(dpy, win, True, KeyPressMask, &ev2);\n        break;\n   \n      case ClientMessage:\n        \n        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)\n          loop = 0;\n        break;\n   \n      case KeyPress:\n        \n        puts(\"KeyPress event received\");\n        printf(\"> keycode: %d\\n\", ev.xkey.keycode);\n        \n        keysym = XLookupKeysym(&(ev.xkey), 0);\n        if (keysym == XK_q ||\n            keysym == XK_Escape) {\n          loop = 0;\n        } else {\n          char buffer[] = \"  \";\n          int nchars = XLookupString(\n                &(ev.xkey),\n                buffer,\n                2,  \n                &keysym,\n                NULL );\n          if (nchars == 1)\n            printf(\"> Key '%c' pressed\\n\", buffer[0]);\n        }\n        break;\n    }\n  }\n  XDestroyWindow(dpy, win);\n  \n  XCloseDisplay(dpy);\n  return 1;\n}\n", "Java": "import java.awt.Robot\npublic static void type(String str){\n   Robot robot = new Robot();\n   for(char ch:str.toCharArray()){\n      if(Character.isUpperCase(ch)){\n         robot.keyPress(KeyEvent.VK_SHIFT);\n         robot.keyPress((int)ch);\n         robot.keyRelease((int)ch);\n         robot.keyRelease(KeyEvent.VK_SHIFT);\n      }else{\n         char upCh = Character.toUpperCase(ch);\n         robot.keyPress((int)upCh);\n         robot.keyRelease((int)upCh);\n      }\n   }\n}\n"}
{"id": 48382, "name": "Peaceful chess queen armies", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 48383, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 48384, "name": "Active Directory_Search for a user", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n"}
{"id": 48385, "name": "Active Directory_Search for a user", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n"}
{"id": 48386, "name": "Singular value decomposition", "C": "#include <stdio.h>\n#include <gsl/gsl_linalg.h>\n\n\nvoid gsl_matrix_print(const gsl_matrix *M) {\n    int rows = M->size1;\n    int cols = M->size2;\n    for (int i = 0; i < rows; i++) {\n        printf(\"|\");\n        for (int j = 0; j < cols; j++) {\n            printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n        }\n        printf(\"\\b|\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main(){\n    double a[] = {3, 0, 4, 5};\n    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n    gsl_matrix *V = gsl_matrix_alloc(2, 2);\n    gsl_vector *S = gsl_vector_alloc(2);\n    gsl_vector *work = gsl_vector_alloc(2);\n\n    \n    gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n    gsl_matrix_transpose(V);\n    double s[] = {S->data[0], 0, 0, S->data[1]};\n    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n    printf(\"U:\\n\");\n    gsl_matrix_print(&A.matrix);\n\n    printf(\"S:\\n\");\n    gsl_matrix_print(&SM.matrix);\n\n    printf(\"VT:\\n\");\n    gsl_matrix_print(V);\n    \n    gsl_matrix_free(V);\n    gsl_vector_free(S);\n    gsl_vector_free(work);\n    return 0;\n}\n", "Java": "import Jama.Matrix;\npublic class SingularValueDecomposition {\n    public static void main(String[] args) {\n        double[][] matrixArray = {{3, 0}, {4, 5}};\n        var matrix = new Matrix(matrixArray);\n        var svd = matrix.svd();\n        svd.getU().print(0, 10); \n        svd.getS().print(0, 10);\n        svd.getV().print(0, 10);\n    }\n}\n"}
{"id": 48387, "name": "Test integerness", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n"}
{"id": 48388, "name": "Execute a system command", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 48389, "name": "Rodrigues’ rotation formula", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct {\n    double x, y, z;\n} vector;\n\ntypedef struct {\n    vector i, j, k;\n} matrix;\n\ndouble norm(vector v) {\n    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);\n}\n\nvector normalize(vector v){\n    double length = norm(v);\n    vector n = {v.x / length, v.y / length, v.z / length};\n    return n;\n}\n\ndouble dotProduct(vector v1, vector v2) {\n    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;\n}\n\nvector crossProduct(vector v1, vector v2) {\n    vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x};\n    return cp;\n}\n\ndouble getAngle(vector v1, vector v2) {\n    return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2)));\n}\n\nvector matrixMultiply(matrix m ,vector v) {\n    vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)};\n    return mm;\n}\n\nvector aRotate(vector p, vector v, double a) {\n    double ca = cos(a), sa = sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    matrix r = {\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}\n    };\n    return matrixMultiply(r, p);\n}\n\nint main() {\n    vector v1 = {5, -6, 4}, v2 = {8, 5, -30};\n    double a = getAngle(v1, v2);\n    vector cp = crossProduct(v1, v2);\n    vector ncp = normalize(cp);\n    vector np = aRotate(v1, ncp, a);\n    printf(\"[%.13f, %.13f, %.13f]\\n\", np.x, np.y, np.z);\n    return 0;\n}\n", "Java": "\n\nclass Vector{\n  private double x, y, z;\n\n  public Vector(double x1,double y1,double z1){\n    x = x1;\n    y = y1;\n    z = z1;\n  }\n  \n  void printVector(int x,int y){\n    text(\"( \" + this.x + \" )  \\u00ee + ( \" + this.y + \" ) + \\u0135 ( \" + this.z + \") \\u006b\\u0302\",x,y);\n  }\n\n  public double norm() {\n    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);\n  }\n  \n  public Vector normalize(){\n    double length = this.norm();\n    return new Vector(this.x / length, this.y / length, this.z / length);\n  }\n  \n  public double dotProduct(Vector v2) {\n    return this.x*v2.x + this.y*v2.y + this.z*v2.z;\n  }\n  \n  public Vector crossProduct(Vector v2) {\n    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);\n  }\n  \n  public double getAngle(Vector v2) {\n    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));\n  }\n  \n  public Vector aRotate(Vector v, double a) {\n    double ca = Math.cos(a), sa = Math.sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    Vector[] r = {\n        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),\n        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),\n        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)\n    };\n    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));\n  }\n}\n\nvoid setup(){\n  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);\n  double a = v1.getAngle(v2);\n  Vector cp = v1.crossProduct(v2);\n  Vector normCP = cp.normalize();\n  Vector np = v1.aRotate(normCP,a);\n  \n  size(1200,600);\n  fill(#000000);\n  textSize(30);\n  \n  text(\"v1 = \",10,100);\n  v1.printVector(60,100);\n  text(\"v2 = \",10,150);\n  v2.printVector(60,150);\n  text(\"rV = \",10,200);\n  np.printVector(60,200);\n}\n"}
{"id": 48390, "name": "XML validation", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 48391, "name": "Death Star", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n"}
{"id": 48392, "name": "Lucky and even lucky numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define LUCKY_SIZE 60000\nint luckyOdd[LUCKY_SIZE];\nint luckyEven[LUCKY_SIZE];\n\nvoid compactLucky(int luckyArray[]) {\n    int i, j, k;\n\n    for (i = 0; i < LUCKY_SIZE; i++) {\n        if (luckyArray[i] == 0) {\n            j = i;\n            break;\n        }\n    }\n\n    for (j = i + 1; j < LUCKY_SIZE; j++) {\n        if (luckyArray[j] > 0) {\n            luckyArray[i++] = luckyArray[j];\n        }\n    }\n\n    for (; i < LUCKY_SIZE; i++) {\n        luckyArray[i] = 0;\n    }\n}\n\nvoid initialize() {\n    int i, j;\n\n    \n    for (i = 0; i < LUCKY_SIZE; i++) {\n        luckyEven[i] = 2 * i + 2;\n        luckyOdd[i] = 2 * i + 1;\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyOdd[i] > 0) {\n            for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {\n                luckyOdd[j] = 0;\n            }\n            compactLucky(luckyOdd);\n        }\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyEven[i] > 0) {\n            for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {\n                luckyEven[j] = 0;\n            }\n            compactLucky(luckyEven);\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[j] == 0 || luckyEven[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyEven[i] != 0; i++) {\n            if (luckyEven[i] > k) {\n                break;\n            }\n            if (luckyEven[i] > j) {\n                printf(\" %d\", luckyEven[i]);\n            }\n        }\n    } else {\n        if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyOdd[i] != 0; i++) {\n            if (luckyOdd[i] > k) {\n                break;\n            }\n            if (luckyOdd[i] > j) {\n                printf(\" %d\", luckyOdd[i]);\n            }\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyEven[i]);\n        }\n    } else {\n        if (luckyOdd[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyOdd[i]);\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (luckyEven[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even number %d=%d\\n\", j, luckyEven[j - 1]);\n    } else {\n        if (luckyOdd[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky number %d=%d\\n\", j, luckyOdd[j - 1]);\n    }\n}\n\nvoid help() {\n    printf(\"./lucky j [k] [--lucky|--evenLucky]\\n\");\n    printf(\"\\n\");\n    printf(\"       argument(s)        |  what is displayed\\n\");\n    printf(\"==============================================\\n\");\n    printf(\"-j=m                      |  mth lucky number\\n\");\n    printf(\"-j=m  --lucky             |  mth lucky number\\n\");\n    printf(\"-j=m  --evenLucky         |  mth even lucky number\\n\");\n    printf(\"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\");\n    printf(\"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\");\n}\n\nvoid process(int argc, char *argv[]) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    bool good = false;\n    int i;\n\n    for (i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    fprintf(stderr, \"Unknown long argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    fprintf(stderr, \"Unknown short argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            fprintf(stderr, \"Unknown argument: [%s]\\n\", argv[i]);\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n}\n\nvoid test() {\n    printRange(1, 20, false);\n    printRange(1, 20, true);\n\n    printBetween(6000, 6100, false);\n    printBetween(6000, 6100, true);\n\n    printSingle(10000, false);\n    printSingle(10000, true);\n}\n\nint main(int argc, char *argv[]) {\n    initialize();\n\n    \n\n    if (argc < 2) {\n        help();\n        return 1;\n    }\n    process(argc, argv);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n"}
{"id": 48393, "name": "Scope modifiers", "C": "int a;          \nstatic int p;   \n\nextern float v; \n\n\nint code(int arg)\n{\n  int myp;        \n                  \n                  \n  static int myc; \n                  \n                  \n                  \n                  \n}\n\n\nstatic void code2(void)\n{\n  v = v * 1.02;    \n  \n}\n", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n"}
{"id": 48394, "name": "Simple database", "C": "#include <stdio.h>\n#include <stdlib.h> \n#include <string.h> \n#define _XOPEN_SOURCE \n#define __USE_XOPEN\n#include <time.h>\n#define DB \"database.csv\" \n#define TRY(a)  if (!(a)) {perror(#a);exit(1);}\n#define TRY2(a) if((a)<0) {perror(#a);exit(1);}\n#define FREE(a) if(a) {free(a);a=NULL;}\n#define sort_by(foo) \\\nstatic int by_##foo (const void*p1, const void*p2) { \\\n    return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); }\ntypedef struct db {\n    char title[26];\n    char first_name[26];\n    char last_name[26];\n    time_t date;\n    char publ[100];\n    struct db *next;\n}\ndb_t,*pdb_t;\ntypedef int (sort)(const void*, const void*);\nenum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY};\nstatic pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby);\nstatic char *time2str (time_t *time);\nstatic time_t str2time (char *date);\n\nsort_by(last_name);\nsort_by(title);\nstatic int by_date(pdb_t *p1, pdb_t *p2);\n\nint main (int argc, char **argv) {\n    char buf[100];\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    db_t db;\n    db.next=NULL;\n    pdb_t dblist;\n    int i;\n    FILE *f;\n    TRY (f=fopen(DB,\"a+\"));\n    if (argc<2) {\nusage:  printf (\"Usage: %s [commands]\\n\"\n        \"-c  Create new entry.\\n\"\n        \"-p  Print the latest entry.\\n\"\n        \"-t  Print all entries sorted by title.\\n\"\n        \"-d  Print all entries sorted by date.\\n\"\n        \"-a  Print all entries sorted by author.\\n\",argv[0]);\n        fclose (f);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n        case CREATE:\n        printf(\"-c  Create a new entry.\\n\");\n        printf(\"Title           :\");if((scanf(\" %25[^\\n]\",db.title     ))<0)break;\n        printf(\"Author Firstname:\");if((scanf(\" %25[^\\n]\",db.first_name))<0)break;\n        printf(\"Author Lastname :\");if((scanf(\" %25[^\\n]\",db.last_name ))<0)break;\n        printf(\"Date 10-12-2000 :\");if((scanf(\" %10[^\\n]\",buf          ))<0)break;\n        printf(\"Publication     :\");if((scanf(\" %99[^\\n]\",db.publ      ))<0)break;\n        db.date=str2time (buf);\n        dao (CREATE,f,&db,NULL);\n        break;\n        case PRINT:\n        printf (\"-p  Print the latest entry.\\n\");\n        while (!feof(f)) dao (READLINE,f,&db,NULL);\n        dao (PRINT,f,&db,NULL);\n        break;\n        case TITLE:\n        printf (\"-t  Print all entries sorted by title.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_title);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case DATE:\n        printf (\"-d  Print all entries sorted by date.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,(int (*)(const void *,const  void *)) by_date);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case AUTH:\n        printf (\"-a  Print all entries sorted by author.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_last_name);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        default: {\n            printf (\"Unknown command: %s.\\n\",strlen(argv[1])<10?argv[1]:\"\");\n            goto usage;\n    }   }\n    fclose (f);\n    return 0;\n}\n\nstatic pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) {\n    pdb_t *pdb=NULL,rec=NULL,hd=NULL;\n    int i=0,ret;\n    char buf[100];\n    switch (cmd) {\n        case CREATE:\n        fprintf (f,\"\\\"%s\\\",\",in_db->title);\n        fprintf (f,\"\\\"%s\\\",\",in_db->first_name);\n        fprintf (f,\"\\\"%s\\\",\",in_db->last_name);\n        fprintf (f,\"\\\"%s\\\",\",time2str(&in_db->date));\n        fprintf (f,\"\\\"%s\\\" \\n\",in_db->publ);\n        break;\n        case PRINT:\n        for (;in_db;i++) {\n            printf (\"Title       : %s\\n\",     in_db->title);\n            printf (\"Author      : %s %s\\n\",  in_db->first_name, in_db->last_name);\n            printf (\"Date        : %s\\n\",     time2str(&in_db->date));\n            printf (\"Publication : %s\\n\\n\",   in_db->publ);\n            if (!((i+1)%3)) {\n                printf (\"Press Enter to continue.\\n\");\n                ret = scanf (\"%*[^\\n]\");\n                if (ret<0) return rec; \n                else getchar();\n            }\n            in_db=in_db->next;\n        }\n        break;\n        case READLINE:\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->title     ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->first_name))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->last_name ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",buf              ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\" \",in_db->publ      ))<0)break;\n        in_db->date=str2time (buf);\n        break;\n        case READ:\n        while (!feof(f)) {\n            dao (READLINE,f,in_db,NULL);\n            TRY (rec=malloc(sizeof(db_t)));\n            *rec=*in_db; \n            rec->next=hd;\n            hd=rec;i++;\n        }\n        if (i<2) {\n            puts (\"Empty database. Please create some entries.\");\n            fclose (f);\n            exit (0);\n        }\n        break;\n        case SORT:\n        rec=in_db;\n        for (;in_db;i++) in_db=in_db->next;\n        TRY (pdb=malloc(i*sizeof(pdb_t)));\n        in_db=rec;\n        for (i=0;in_db;i++) {\n            pdb[i]=in_db;\n            in_db=in_db->next;\n        }\n        qsort (pdb,i,sizeof in_db,sortby);\n        pdb[i-1]->next=NULL;\n        for (i=i-1;i;i--) {\n            pdb[i-1]->next=pdb[i];\n        }\n        rec=pdb[0];\n        FREE (pdb);\n        pdb=NULL;\n        break;\n        case DESTROY: {\n            while ((rec=in_db)) {\n                in_db=in_db->next;\n                FREE (rec);\n    }   }   }\n    return rec;\n}\n\nstatic char *time2str (time_t *time) {\n    static char buf[255];\n    struct tm *ptm;\n    ptm=localtime (time);\n    strftime(buf, 255, \"%m-%d-%Y\", ptm);\n    return buf;\n}\n\nstatic time_t str2time (char *date) {\n    struct tm tm;\n    memset (&tm, 0, sizeof(struct tm));\n    strptime(date, \"%m-%d-%Y\", &tm);\n    return mktime(&tm);\n}\n\nstatic int by_date (pdb_t *p1, pdb_t *p2) {\n    if ((*p1)->date < (*p2)->date) {\n        return -1;\n    }\n    else return ((*p1)->date > (*p2)->date);\n}\n", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n"}
{"id": 48395, "name": "Total circles area", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n"}
{"id": 48396, "name": "Total circles area", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n"}
{"id": 48397, "name": "Hough transform", "C": "#include \"SL_Generated.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nint main( int argc, char** argv )\n{\n    string fileName = \"Pentagon.bmp\";\n    if(argc > 1) fileName = argv[1];\n    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);\n    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);\n    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);\n    int threads = 0; if(argc > 5) threads = atoi(argv[5]);\n    char titleBuffer[200];\n    SLTimer t;\n\n    CImg<int> image(fileName.c_str());\n    int imageDimensions[] = {image.height(), image.width(), 0};\n    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);\n    Sequence< Sequence<int> > result;\n\n    sl_init(threads);\n\n    t.start();\n    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);\n    t.stop();\n    \n    CImg<int> resultImage(result[1].size(), result.size());\n    for(int y = 0; y < result.size(); y++)\n        for(int x = 0; x < result[y+1].size(); x++)\n            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];\n    \n    sprintf(titleBuffer, \"SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\\0\", \n                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());\n    resultImage.display(titleBuffer);\n\n    sl_done();\n    return 0;\n}\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\n  }\n}\n"}
{"id": 48398, "name": "Verify distribution uniformity_Chi-squared test", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n"}
{"id": 48399, "name": "Welch's t-test", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 48400, "name": "Welch's t-test", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 48401, "name": "Topological sort_Extracted top item", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n"}
{"id": 48402, "name": "Topological sort_Extracted top item", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n"}
{"id": 48403, "name": "Brace expansion", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 48404, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 48405, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 48406, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 48407, "name": "Superpermutation minimisation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 48408, "name": "GUI component interaction", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n"}
{"id": 48409, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n"}
{"id": 48410, "name": "Summarize and say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n"}
{"id": 48411, "name": "Spelling of ordinal numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 48412, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 48413, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 48414, "name": "Numeric separator syntax", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n", "Java": "public class NumericSeparatorSyntax {\n\n    public static void main(String[] args) {\n        runTask(\"Underscore allowed as seperator\", 1_000);\n        runTask(\"Multiple consecutive underscores allowed:\", 1__0_0_0);\n        runTask(\"Many multiple consecutive underscores allowed:\", 1________________________00);\n        runTask(\"Underscores allowed in multiple positions\", 1__4__4);\n        runTask(\"Underscores allowed in negative number\", -1__4__4);\n        runTask(\"Underscores allowed in floating point number\", 1__4__4e-5);\n        runTask(\"Underscores allowed in floating point exponent\", 1__4__440000e-1_2);\n        \n        \n        \n        \n    }\n    \n    private static void runTask(String description, long n) {\n        runTask(description, n, \"%d\");\n    }\n\n    private static void runTask(String description, double n) {\n        runTask(description, n, \"%3.7f\");\n    }\n\n    private static void runTask(String description, Number n, String format) {\n        System.out.printf(\"%s:  \" + format + \"%n\", description, n);\n    }\n\n}\n"}
{"id": 48415, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n"}
{"id": 48416, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n"}
{"id": 48417, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48418, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48419, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48420, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 48421, "name": "Simulate input_Mouse", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n", "Java": "Point p = component.getLocation();\nRobot robot = new Robot();\nrobot.mouseMove(p.getX(), p.getY()); \nrobot.mousePress(InputEvent.BUTTON1_MASK); \n                                       \nrobot.mouseRelease(InputEvent.BUTTON1_MASK);\n"}
{"id": 48422, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 48423, "name": "Terminal control_Clear the screen", "C": "void cls(void) {\n    printf(\"\\33[2J\");\n}\n", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n"}
{"id": 48424, "name": "Sunflower fractal", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n"}
{"id": 48425, "name": "Vogel's approximation method", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n"}
{"id": 48426, "name": "Air mass", "C": "#include <math.h>\n#include <stdio.h>\n\n#define DEG 0.017453292519943295769236907684886127134  \n#define RE 6371000.0 \n#define DD 0.001 \n#define FIN 10000000.0 \n\nstatic double rho(double a) {\n    \n    return exp(-a / 8500.0);\n}\n\nstatic double height(double a, double z, double d) {\n    \n    \n    \n    double aa = RE + a;\n    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));\n    return hh - RE;\n}\n\nstatic double column_density(double a, double z) {\n    \n    double sum = 0.0, d = 0.0;\n    while (d < FIN) {\n        \n        double delta = DD * d;\n        if (delta < DD)\n            delta = DD;\n        sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n        d += delta;\n    }\n    return sum;\n}\n\nstatic double airmass(double a, double z) {\n    return column_density(a, z) / column_density(a, 0.0);\n}\n\nint main() {\n    puts(\"Angle     0 m              13700 m\");\n    puts(\"------------------------------------\");\n    for (double z = 0; z <= 90; z+= 5) {\n        printf(\"%2.0f      %11.8f      %11.8f\\n\",\n               z, airmass(0.0, z), airmass(13700.0, z));\n    }\n}\n", "Java": "public class AirMass {\n    public static void main(String[] args) {\n        System.out.println(\"Angle     0 m              13700 m\");\n        System.out.println(\"------------------------------------\");\n        for (double z = 0; z <= 90; z+= 5) {\n            System.out.printf(\"%2.0f      %11.8f      %11.8f\\n\",\n                            z, airmass(0.0, z), airmass(13700.0, z));\n        }\n    }\n\n    private static double rho(double a) {\n        \n        return Math.exp(-a / 8500.0);\n    }\n\n    private static double height(double a, double z, double d) {\n        \n        \n        \n        double aa = RE + a;\n        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));\n        return hh - RE;\n    }\n\n    private static double columnDensity(double a, double z) {\n        \n        double sum = 0.0, d = 0.0;\n        while (d < FIN) {\n            \n            double delta = Math.max(DD * d, DD);\n            sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n            d += delta;\n        }\n        return sum;\n    }\n     \n    private static double airmass(double a, double z) {\n        return columnDensity(a, z) / columnDensity(a, 0.0);\n    }\n\n    private static final double RE = 6371000.0; \n    private static final double DD = 0.001; \n    private static final double FIN = 10000000.0; \n}\n"}
{"id": 48427, "name": "Sorting algorithms_Pancake sort", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n"}
{"id": 48428, "name": "Sorting algorithms_Pancake sort", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n"}
{"id": 48429, "name": "Active Directory_Connect", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n"}
{"id": 48430, "name": "Permutations by swapping", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 48431, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 48432, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 48433, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 48434, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 48435, "name": "Image convolution", "C": "image filter(image img, double *K, int Ks, double, double);\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class ImageConvolution\n{\n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n  }\n  \n  private static int bound(int value, int endIndex)\n  {\n    if (value < 0)\n      return 0;\n    if (value < endIndex)\n      return value;\n    return endIndex - 1;\n  }\n  \n  public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)\n  {\n    int inputWidth = inputData.width;\n    int inputHeight = inputData.height;\n    int kernelWidth = kernel.width;\n    int kernelHeight = kernel.height;\n    if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd width\");\n    if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd height\");\n    int kernelWidthRadius = kernelWidth >>> 1;\n    int kernelHeightRadius = kernelHeight >>> 1;\n    \n    ArrayData outputData = new ArrayData(inputWidth, inputHeight);\n    for (int i = inputWidth - 1; i >= 0; i--)\n    {\n      for (int j = inputHeight - 1; j >= 0; j--)\n      {\n        double newValue = 0.0;\n        for (int kw = kernelWidth - 1; kw >= 0; kw--)\n          for (int kh = kernelHeight - 1; kh >= 0; kh--)\n            newValue += kernel.get(kw, kh) * inputData.get(\n                          bound(i + kw - kernelWidthRadius, inputWidth),\n                          bound(j + kh - kernelHeightRadius, inputHeight));\n        outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));\n      }\n    }\n    return outputData;\n  }\n  \n  public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData reds = new ArrayData(width, height);\n    ArrayData greens = new ArrayData(width, height);\n    ArrayData blues = new ArrayData(width, height);\n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        reds.set(x, y, (rgbValue >>> 16) & 0xFF);\n        greens.set(x, y, (rgbValue >>> 8) & 0xFF);\n        blues.set(x, y, rgbValue & 0xFF);\n      }\n    }\n    return new ArrayData[] { reds, greens, blues };\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException\n  {\n    ArrayData reds = redGreenBlue[0];\n    ArrayData greens = redGreenBlue[1];\n    ArrayData blues = redGreenBlue[2];\n    BufferedImage outputImage = new BufferedImage(reds.width, reds.height,\n                                                  BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < reds.height; y++)\n    {\n      for (int x = 0; x < reds.width; x++)\n      {\n        int red = bound(reds.get(x, y), 256);\n        int green = bound(greens.get(x, y), 256);\n        int blue = bound(blues.get(x, y), 256);\n        outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    int kernelWidth = Integer.parseInt(args[2]);\n    int kernelHeight = Integer.parseInt(args[3]);\n    int kernelDivisor = Integer.parseInt(args[4]);\n    System.out.println(\"Kernel size: \" + kernelWidth + \"x\" + kernelHeight +\n                       \", divisor=\" + kernelDivisor);\n    int y = 5;\n    ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);\n    for (int i = 0; i < kernelHeight; i++)\n    {\n      System.out.print(\"[\");\n      for (int j = 0; j < kernelWidth; j++)\n      {\n        kernel.set(j, i, Integer.parseInt(args[y++]));\n        System.out.print(\" \" + kernel.get(j, i) + \" \");\n      }\n      System.out.println(\"]\");\n    }\n    \n    ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);\n    for (int i = 0; i < dataArrays.length; i++)\n      dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);\n    writeOutputImage(args[1], dataArrays);\n    return;\n  }\n}\n"}
{"id": 48436, "name": "Dice game probabilities", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n"}
{"id": 48437, "name": "Plasma effect", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 48438, "name": "WiktionaryDumps to words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <expat.h>\n#include <pcre.h>\n\n#ifdef XML_LARGE_SIZE\n#  define XML_FMT_INT_MOD \"ll\"\n#else\n#  define XML_FMT_INT_MOD \"l\"\n#endif\n\n#ifdef XML_UNICODE_WCHAR_T\n#  define XML_FMT_STR \"ls\"\n#else\n#  define XML_FMT_STR \"s\"\n#endif\n\nvoid reset_char_data_buffer();\nvoid process_char_data_buffer();\n\nstatic bool last_tag_is_title;\nstatic bool last_tag_is_text;\n\nstatic pcre *reCompiled;\nstatic pcre_extra *pcreExtra;\n\n\nvoid start_element(void *data, const char *element, const char **attribute) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n\n    if (strcmp(\"title\", element) == 0) {\n        last_tag_is_title = true;\n    }\n    if (strcmp(\"text\", element) == 0) {\n        last_tag_is_text = true;\n    }\n}\n\nvoid end_element(void *data, const char *el) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n}\n\n\n#define TITLE_BUF_SIZE (1024 * 8)\n\nstatic char char_data_buffer[1024 * 64 * 8];\nstatic char title_buffer[TITLE_BUF_SIZE];\nstatic size_t offs;\nstatic bool overflow;\n\n\nvoid reset_char_data_buffer(void) {\n    offs = 0;\n    overflow = false;\n}\n\n\nvoid char_data(void *userData, const XML_Char *s, int len) {\n    if (!overflow) {\n        if (len + offs >= sizeof(char_data_buffer)) {\n            overflow = true;\n            fprintf(stderr, \"Warning: buffer overflow\\n\");\n            fflush(stderr);\n        } else {\n            memcpy(char_data_buffer + offs, s, len);\n            offs += len;\n        }\n    }\n}\n\nvoid try_match();\n\n\nvoid process_char_data_buffer(void) {\n    if (offs > 0) {\n        char_data_buffer[offs] = '\\0';\n\n        if (last_tag_is_title) {\n            unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1);\n            memcpy(title_buffer, char_data_buffer, n);\n            last_tag_is_title = false;\n        }\n        if (last_tag_is_text) {\n            try_match();\n            last_tag_is_text = false;\n        }\n    }\n}\n\nvoid try_match()\n{\n    int subStrVec[80];\n    int subStrVecLen;\n    int pcreExecRet;\n    subStrVecLen = sizeof(subStrVec) / sizeof(int);\n\n    pcreExecRet = pcre_exec(\n            reCompiled, pcreExtra,\n            char_data_buffer, strlen(char_data_buffer),\n            0, 0,\n            subStrVec, subStrVecLen);\n\n    if (pcreExecRet < 0) {\n        switch (pcreExecRet) {\n            case PCRE_ERROR_NOMATCH      : break;\n            case PCRE_ERROR_NULL         : fprintf(stderr, \"Something was null\\n\");                      break;\n            case PCRE_ERROR_BADOPTION    : fprintf(stderr, \"A bad option was passed\\n\");                 break;\n            case PCRE_ERROR_BADMAGIC     : fprintf(stderr, \"Magic number bad (compiled re corrupt?)\\n\"); break;\n            case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, \"Something kooky in the compiled re\\n\");      break;\n            case PCRE_ERROR_NOMEMORY     : fprintf(stderr, \"Ran out of memory\\n\");                       break;\n            default                      : fprintf(stderr, \"Unknown error\\n\");                           break;\n        }\n    } else {\n        puts(title_buffer);  \n    }\n}\n\n\n#define BUF_SIZE 1024\n\nint main(int argc, char *argv[])\n{\n    char buffer[BUF_SIZE];\n    int n;\n\n    const char *pcreErrorStr;\n    int pcreErrorOffset;\n    char *aStrRegex;\n    char **aLineToMatch;\n\n    \n\n    aStrRegex = \"(.*)(==French==)(.*)\";  \n\n    reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL);\n    if (reCompiled == NULL) {\n        fprintf(stderr, \"ERROR: Could not compile regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr);\n    if (pcreErrorStr != NULL) {\n        fprintf(stderr, \"ERROR: Could not study regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    \n\n    XML_Parser parser = XML_ParserCreate(NULL);\n\n    XML_SetElementHandler(parser, start_element, end_element);\n    XML_SetCharacterDataHandler(parser, char_data);\n\n    reset_char_data_buffer();\n\n    while (1) {\n        int done;\n        int len;\n\n        len = (int)fread(buffer, 1, BUF_SIZE, stdin);\n        if (ferror(stdin)) {\n            fprintf(stderr, \"Read error\\n\");\n            exit(1);\n        }\n        done = feof(stdin);\n\n        if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) {\n            fprintf(stderr,\n                \"Parse error at line %\" XML_FMT_INT_MOD \"u:\\n%\" XML_FMT_STR \"\\n\",\n                XML_GetCurrentLineNumber(parser),\n                XML_ErrorString(XML_GetErrorCode(parser)));\n            exit(1);\n        }\n\n        if (done) break;\n    }\n\n    XML_ParserFree(parser);\n\n    pcre_free(reCompiled);\n\n    if (pcreExtra != NULL) {\n#ifdef PCRE_CONFIG_JIT\n        pcre_free_study(pcreExtra);\n#else\n        pcre_free(pcreExtra);\n#endif\n    }\n\n    return 0;\n}\n", "Java": "import org.xml.sax.*;\nimport org.xml.sax.helpers.DefaultHandler;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nclass MyHandler extends DefaultHandler {\n    private static final String TITLE = \"title\";\n    private static final String TEXT = \"text\";\n\n    private String lastTag = \"\";\n    private String title = \"\";\n\n    @Override\n    public void characters(char[] ch, int start, int length) throws SAXException {\n        String regex = \".*==French==.*\";\n        Pattern pat = Pattern.compile(regex, Pattern.DOTALL);\n\n        switch (lastTag) {\n            case TITLE:\n                title = new String(ch, start, length);\n                break;\n            case TEXT:\n                String text = new String(ch, start, length);\n                Matcher mat = pat.matcher(text);\n                if (mat.matches()) {\n                    System.out.println(title);\n                }\n                break;\n        }\n    }\n\n    @Override\n    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n        lastTag = qName;\n    }\n\n    @Override\n    public void endElement(String uri, String localName, String qName) throws SAXException {\n        lastTag = \"\";\n    }\n}\n\npublic class WiktoWords {\n    public static void main(java.lang.String[] args) {\n        try {\n            SAXParserFactory spFactory = SAXParserFactory.newInstance();\n            SAXParser saxParser = spFactory.newSAXParser();\n            MyHandler handler = new MyHandler();\n            saxParser.parse(new InputSource(System.in), handler);\n        } catch(Exception e) {\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 48439, "name": "WiktionaryDumps to words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <expat.h>\n#include <pcre.h>\n\n#ifdef XML_LARGE_SIZE\n#  define XML_FMT_INT_MOD \"ll\"\n#else\n#  define XML_FMT_INT_MOD \"l\"\n#endif\n\n#ifdef XML_UNICODE_WCHAR_T\n#  define XML_FMT_STR \"ls\"\n#else\n#  define XML_FMT_STR \"s\"\n#endif\n\nvoid reset_char_data_buffer();\nvoid process_char_data_buffer();\n\nstatic bool last_tag_is_title;\nstatic bool last_tag_is_text;\n\nstatic pcre *reCompiled;\nstatic pcre_extra *pcreExtra;\n\n\nvoid start_element(void *data, const char *element, const char **attribute) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n\n    if (strcmp(\"title\", element) == 0) {\n        last_tag_is_title = true;\n    }\n    if (strcmp(\"text\", element) == 0) {\n        last_tag_is_text = true;\n    }\n}\n\nvoid end_element(void *data, const char *el) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n}\n\n\n#define TITLE_BUF_SIZE (1024 * 8)\n\nstatic char char_data_buffer[1024 * 64 * 8];\nstatic char title_buffer[TITLE_BUF_SIZE];\nstatic size_t offs;\nstatic bool overflow;\n\n\nvoid reset_char_data_buffer(void) {\n    offs = 0;\n    overflow = false;\n}\n\n\nvoid char_data(void *userData, const XML_Char *s, int len) {\n    if (!overflow) {\n        if (len + offs >= sizeof(char_data_buffer)) {\n            overflow = true;\n            fprintf(stderr, \"Warning: buffer overflow\\n\");\n            fflush(stderr);\n        } else {\n            memcpy(char_data_buffer + offs, s, len);\n            offs += len;\n        }\n    }\n}\n\nvoid try_match();\n\n\nvoid process_char_data_buffer(void) {\n    if (offs > 0) {\n        char_data_buffer[offs] = '\\0';\n\n        if (last_tag_is_title) {\n            unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1);\n            memcpy(title_buffer, char_data_buffer, n);\n            last_tag_is_title = false;\n        }\n        if (last_tag_is_text) {\n            try_match();\n            last_tag_is_text = false;\n        }\n    }\n}\n\nvoid try_match()\n{\n    int subStrVec[80];\n    int subStrVecLen;\n    int pcreExecRet;\n    subStrVecLen = sizeof(subStrVec) / sizeof(int);\n\n    pcreExecRet = pcre_exec(\n            reCompiled, pcreExtra,\n            char_data_buffer, strlen(char_data_buffer),\n            0, 0,\n            subStrVec, subStrVecLen);\n\n    if (pcreExecRet < 0) {\n        switch (pcreExecRet) {\n            case PCRE_ERROR_NOMATCH      : break;\n            case PCRE_ERROR_NULL         : fprintf(stderr, \"Something was null\\n\");                      break;\n            case PCRE_ERROR_BADOPTION    : fprintf(stderr, \"A bad option was passed\\n\");                 break;\n            case PCRE_ERROR_BADMAGIC     : fprintf(stderr, \"Magic number bad (compiled re corrupt?)\\n\"); break;\n            case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, \"Something kooky in the compiled re\\n\");      break;\n            case PCRE_ERROR_NOMEMORY     : fprintf(stderr, \"Ran out of memory\\n\");                       break;\n            default                      : fprintf(stderr, \"Unknown error\\n\");                           break;\n        }\n    } else {\n        puts(title_buffer);  \n    }\n}\n\n\n#define BUF_SIZE 1024\n\nint main(int argc, char *argv[])\n{\n    char buffer[BUF_SIZE];\n    int n;\n\n    const char *pcreErrorStr;\n    int pcreErrorOffset;\n    char *aStrRegex;\n    char **aLineToMatch;\n\n    \n\n    aStrRegex = \"(.*)(==French==)(.*)\";  \n\n    reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL);\n    if (reCompiled == NULL) {\n        fprintf(stderr, \"ERROR: Could not compile regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr);\n    if (pcreErrorStr != NULL) {\n        fprintf(stderr, \"ERROR: Could not study regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    \n\n    XML_Parser parser = XML_ParserCreate(NULL);\n\n    XML_SetElementHandler(parser, start_element, end_element);\n    XML_SetCharacterDataHandler(parser, char_data);\n\n    reset_char_data_buffer();\n\n    while (1) {\n        int done;\n        int len;\n\n        len = (int)fread(buffer, 1, BUF_SIZE, stdin);\n        if (ferror(stdin)) {\n            fprintf(stderr, \"Read error\\n\");\n            exit(1);\n        }\n        done = feof(stdin);\n\n        if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) {\n            fprintf(stderr,\n                \"Parse error at line %\" XML_FMT_INT_MOD \"u:\\n%\" XML_FMT_STR \"\\n\",\n                XML_GetCurrentLineNumber(parser),\n                XML_ErrorString(XML_GetErrorCode(parser)));\n            exit(1);\n        }\n\n        if (done) break;\n    }\n\n    XML_ParserFree(parser);\n\n    pcre_free(reCompiled);\n\n    if (pcreExtra != NULL) {\n#ifdef PCRE_CONFIG_JIT\n        pcre_free_study(pcreExtra);\n#else\n        pcre_free(pcreExtra);\n#endif\n    }\n\n    return 0;\n}\n", "Java": "import org.xml.sax.*;\nimport org.xml.sax.helpers.DefaultHandler;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nclass MyHandler extends DefaultHandler {\n    private static final String TITLE = \"title\";\n    private static final String TEXT = \"text\";\n\n    private String lastTag = \"\";\n    private String title = \"\";\n\n    @Override\n    public void characters(char[] ch, int start, int length) throws SAXException {\n        String regex = \".*==French==.*\";\n        Pattern pat = Pattern.compile(regex, Pattern.DOTALL);\n\n        switch (lastTag) {\n            case TITLE:\n                title = new String(ch, start, length);\n                break;\n            case TEXT:\n                String text = new String(ch, start, length);\n                Matcher mat = pat.matcher(text);\n                if (mat.matches()) {\n                    System.out.println(title);\n                }\n                break;\n        }\n    }\n\n    @Override\n    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n        lastTag = qName;\n    }\n\n    @Override\n    public void endElement(String uri, String localName, String qName) throws SAXException {\n        lastTag = \"\";\n    }\n}\n\npublic class WiktoWords {\n    public static void main(java.lang.String[] args) {\n        try {\n            SAXParserFactory spFactory = SAXParserFactory.newInstance();\n            SAXParser saxParser = spFactory.newSAXParser();\n            MyHandler handler = new MyHandler();\n            saxParser.parse(new InputSource(System.in), handler);\n        } catch(Exception e) {\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 48440, "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": 48441, "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", "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": 48442, "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", "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": 48443, "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", "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": 48444, "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", "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": 48445, "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", "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": 48446, "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", "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": 48447, "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", "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": 48448, "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", "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": 48449, "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", "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": 48450, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\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": 48451, "name": "Seven-sided dice from five-sided dice", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\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": 48452, "name": "Magnanimous numbers", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\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": 48453, "name": "Create a two-dimensional array at runtime", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\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": 48454, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\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": 48455, "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", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 48456, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \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": 48457, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\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": 48458, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 48459, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 48460, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 48461, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 48462, "name": "Checkpoint synchronization", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n"}
{"id": 48463, "name": "Variable-length quantity", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 48464, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 48465, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 48466, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 48467, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 48468, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 48469, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 48470, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 48471, "name": "Stack", "C++": "#include <stack>\n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 48472, "name": "Totient function", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 48473, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 48474, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 48475, "name": "Animation", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 48476, "name": "Sorting algorithms_Radix sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n"}
{"id": 48477, "name": "List comprehensions", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 48478, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 48479, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 48480, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n"}
{"id": 48481, "name": "Safe addition", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 48482, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 48483, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n"}
{"id": 48484, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 48485, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 48486, "name": "Twin primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 48487, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n"}
{"id": 48488, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 48489, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n"}
{"id": 48490, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 48491, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 48492, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 48493, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 48494, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 48495, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 48496, "name": "Man or boy test", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n"}
{"id": 48497, "name": "Short-circuit evaluation", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 48498, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 48499, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 48500, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 48501, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 48502, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 48503, "name": "Inverted index", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n"}
{"id": 48504, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 48505, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 48506, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 48507, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 48508, "name": "Descending primes", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 48509, "name": "Descending primes", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 48510, "name": "Sum and product puzzle", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n"}
{"id": 48511, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n"}
{"id": 48512, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 48513, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 48514, "name": "FASTA format", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 48515, "name": "Literals_String", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n"}
{"id": 48516, "name": "Enumerations", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 48517, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 48518, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 48519, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 48520, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 48521, "name": "Type detection", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n"}
{"id": 48522, "name": "Type detection", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n"}
{"id": 48523, "name": "Maximum triangle path sum", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 48524, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 48525, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 48526, "name": "Magic squares of doubly even order", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 48527, "name": "Same fringe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n"}
{"id": 48528, "name": "Peaceful chess queen armies", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 48529, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 48530, "name": "Sum of first n cubes", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "C#": "using System; using static System.Console;\nclass Program { static void Main(string[] args) {\n    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)\n      Write(\"{0,-7}{1}\",s, (i+=i==3?-4:1)==0?\"\\n\":\" \"); } }\n"}
{"id": 48531, "name": "Execute a system command", "C++": "system(\"pause\");\n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 48532, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 48533, "name": "Brace expansion", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n"}
{"id": 48534, "name": "GUI component interaction", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n"}
{"id": 48535, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 48536, "name": "Addition chains", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n"}
{"id": 48537, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n"}
{"id": 48538, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 48539, "name": "Chemical calculator", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n"}
{"id": 48540, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n"}
{"id": 48541, "name": "Zebra puzzle", "C++": "#include <stdio.h>\n#include <string.h>\n\n#define defenum(name, val0, val1, val2, val3, val4) \\\n    enum name { val0, val1, val2, val3, val4 }; \\\n    const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }\n\ndefenum( Attrib,    Color, Man, Drink, Animal, Smoke );\ndefenum( Colors,    Red, Green, White, Yellow, Blue );\ndefenum( Mans,      English, Swede, Dane, German, Norwegian );\ndefenum( Drinks,    Tea, Coffee, Milk, Beer, Water );\ndefenum( Animals,   Dog, Birds, Cats, Horse, Zebra );\ndefenum( Smokes,    PallMall, Dunhill, Blend, BlueMaster, Prince );\n\nvoid printHouses(int ha[5][5]) {\n    const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};\n\n    printf(\"%-10s\", \"House\");\n    for (const char *name : Attrib_str) printf(\"%-10s\", name);\n    printf(\"\\n\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        for (int j = 0; j < 5; j++) printf(\"%-10s\", attr_names[j][ha[i][j]]);\n        printf(\"\\n\");\n    }\n}\n\nstruct HouseNoRule {\n    int houseno;\n    Attrib a; int v;\n} housenos[] = {\n    {2, Drink, Milk},     \n    {0, Man, Norwegian}   \n};\n\nstruct AttrPairRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&\n               ((ha[i][a1] == v1 && ha[i][a2] != v2) ||\n                (ha[i][a1] != v1 && ha[i][a2] == v2));\n    }\n} pairs[] = {\n    {Man, English,      Color, Red},     \n    {Man, Swede,        Animal, Dog},    \n    {Man, Dane,         Drink, Tea},     \n    {Color, Green,      Drink, Coffee},  \n    {Smoke, PallMall,   Animal, Birds},  \n    {Smoke, Dunhill,    Color, Yellow},  \n    {Smoke, BlueMaster, Drink, Beer},    \n    {Man, German,       Smoke, Prince}    \n};\n\nstruct NextToRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] == v1) &&\n               ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||\n                (i == 4 && ha[i - 1][a2] != v2) ||\n                (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));\n    }\n} nexttos[] = {\n    {Smoke, Blend,      Animal, Cats},    \n    {Smoke, Dunhill,    Animal, Horse},   \n    {Man, Norwegian,    Color, Blue},     \n    {Smoke, Blend,      Drink, Water}     \n};\n\nstruct LeftOfRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5]) {\n        return (ha[0][a2] == v2) || (ha[4][a1] == v1);\n    }\n\n    bool invalid(int ha[5][5], int i) {\n        return ((i > 0 && ha[i][a1] >= 0) &&\n                ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||\n                 (ha[i - 1][a1] != v1 && ha[i][a2] == v2)));\n    }\n} leftofs[] = {\n    {Color, Green,  Color, White}     \n};\n\nbool invalid(int ha[5][5]) {\n    for (auto &rule : leftofs) if (rule.invalid(ha)) return true;\n\n    for (int i = 0; i < 5; i++) {\n#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;\n        eval_rules(pairs);\n        eval_rules(nexttos);\n        eval_rules(leftofs);\n    }\n    return false;\n}\n\nvoid search(bool used[5][5], int ha[5][5], const int hno, const int attr) {\n    int nexthno, nextattr;\n    if (attr < 4) {\n        nextattr = attr + 1;\n        nexthno = hno;\n    } else {\n        nextattr = 0;\n        nexthno = hno + 1;\n    }\n\n    if (ha[hno][attr] != -1) {\n        search(used, ha, nexthno, nextattr);\n    } else {\n        for (int i = 0; i < 5; i++) {\n            if (used[attr][i]) continue;\n            used[attr][i] = true;\n            ha[hno][attr] = i;\n\n            if (!invalid(ha)) {\n                if ((hno == 4) && (attr == 4)) {\n                    printHouses(ha);\n                } else {\n                    search(used, ha, nexthno, nextattr);\n                }\n            }\n\n            used[attr][i] = false;\n        }\n        ha[hno][attr] = -1;\n    }\n}\n\nint main() {\n    bool used[5][5] = {};\n    int ha[5][5]; memset(ha, -1, sizeof(ha));\n\n    for (auto &rule : housenos) {\n        ha[rule.houseno][rule.a] = rule.v;\n        used[rule.a][rule.v] = true;\n    }\n\n    search(used, ha, 0, 0);\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n"}
{"id": 48542, "name": "First-class functions_Use numbers analogously", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 48543, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n"}
{"id": 48544, "name": "Sokoban", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n"}
{"id": 48545, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 48546, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 48547, "name": "Practical numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n"}
{"id": 48548, "name": "Consecutive primes with ascending or descending differences", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n", "C#": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        const int mil = (int)1e6;\n        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n        {\n            int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n            var desc = new string[] { \"A\", \"\", \"De\" };\n            int[] mx = new int[] { 0, 0, 0 },\n                  bi = new int[] { 0, 0, 0 },\n                   c = new int[] { 2, 2, 2 };\n            WriteLine(\"For primes up to {0:n0}:\", lmt);\n            var pr = PG.Primes(lmt).ToArray();\n            for (int i = 0; i < pr.Length; i++)\n            {\n                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n                if (ld == d)\n                    c[2 - d]++;\n                else\n                {\n                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n                    c[d] = 2;\n                }\n                ld = d; lg = ng;\n            }\n            for (int r = 0; r <= 2; r += 2)\n            {\n                Write(\"{0}scending, found run of {1} consecutive primes:\\n  {2} \",\n                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n                    Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n            }\n        }\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<TG> Primes(int lim)\n    {\n        bool[] flags = new bool[lim + 1];\n        int j = 3, lj = 2;\n        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n            }\n        for (; j <= lim; j += 2)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n            }\n    }\n}\n"}
{"id": 48549, "name": "Literals_Floating point", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n"}
{"id": 48550, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 48551, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 48552, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 48553, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 48554, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 48555, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 48556, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 48557, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 48558, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 48559, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 48560, "name": "Word search", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n"}
{"id": 48561, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 48562, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 48563, "name": "Object serialization", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n"}
{"id": 48564, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 48565, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 48566, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n"}
{"id": 48567, "name": "Zumkeller numbers", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 48568, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 48569, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 48570, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 48571, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 48572, "name": "Halt and catch fire", "C#": "int a=0,b=1/a;\n", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n"}
{"id": 48573, "name": "Constrained genericity", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n", "C#": "interface IEatable\n{\n    void Eat();\n}\n"}
{"id": 48574, "name": "Markov chain text generator", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n"}
{"id": 48575, "name": "Dijkstra's algorithm", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n"}
{"id": 48576, "name": "Geometric algebra", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n"}
{"id": 48577, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 48578, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 48579, "name": "Associative array_Iteration", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 48580, "name": "Define a primitive data type", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n"}
{"id": 48581, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 48582, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 48583, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 48584, "name": "Hash join", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 48585, "name": "Odd squarefree semiprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 48586, "name": "Odd squarefree semiprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 48587, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 48588, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 48589, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 48590, "name": "Respond to an unknown method call", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n"}
{"id": 48591, "name": "Latin Squares in reduced form", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 48592, "name": "Closest-pair problem", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n"}
{"id": 48593, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n"}
{"id": 48594, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n"}
{"id": 48595, "name": "Polymorphism", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 48596, "name": "Polymorphism", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 48597, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 48598, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 48599, "name": "Sieve of Pritchard", "C++": "\n\n\n\n#include <cstring>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <ctime>\n\nvoid Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) {\n    \n    uint32_t i, j, x;\n    i = 0; j = w_end;\n    x = length + 1; \n    while (x <= n) {\n        w[++j] = x; \n        d[x] = false;\n        x = length + w[++i];\n    }\n    length = n; w_end = j;\n    if (w_end > w_end_max) w_end_max = w_end;\n}\n\nvoid Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) {\n    \n    uint32_t i, x;\n    i = 0;\n    x = p; \n    while (x <= length) {\n        d[x] = true; \n        x = p*w[++i];\n    }\n    imaxf = i-1;\n}\n\nvoid Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) {\n    \n    uint32_t i, j;\n    j = 0;\n    for (i=1; i <= to; i++) {\n        if (!d[w[i]]) {\n            w[++j] = w[i];\n        }\n    }\n    if (to == w_end) {\n        w_end = j;\n    } else {\n        for (uint32_t k=j+1; k <= to; k++) w[k] = 0;\n    }\n}\n\nvoid Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) {\n    \n    uint32_t *w = new uint32_t[N/4+5];\n    bool *d = new bool[N+1];\n    uint32_t w_end, length;\n    \n    \n    \n    \n    uint32_t w_end_max, p, imaxf;\n    \n    w_end = 0; w[0] = 1;\n    w_end_max = 0;\n    length = 2;\n    \n    nrPrimes = 1;\n    if (printPrimes) printf(\"%d\", 2);\n    p = 3;\n    \n    \n    while (p*p <= N) {\n        \n        nrPrimes++;\n        if (printPrimes) printf(\" %d\", p);\n        if (length < N) {\n            \n            Extend (w, w_end, length, std::min(p*length,N), d, w_end_max);\n        }\n        Delete(w, length, p, d, imaxf);\n        Compress(w, d, (length < N ? w_end : imaxf), w_end);\n        \n        p = w[1];\n        if (p == 0) break; \n        \n    }\n    if (length < N) {\n        \n        Extend (w, w_end, length, N, d, w_end_max);\n    }\n    \n    for (uint32_t i=1; i <= w_end; i++) {\n        if (w[i] == 0 || d[w[i]]) continue;\n        if (printPrimes) printf(\" %d\", w[i]);\n        nrPrimes++;\n    }\n    vBound = w_end_max+1;\n}\n\nint main (int argc, char *argw[]) {\n    bool error = false;\n    bool printPrimes = false;\n    uint32_t N, nrPrimes, vBound;\n    if (argc == 3) {\n        if (strcmp(argw[2], \"-p\") == 0) {\n            printPrimes = true;\n            argc--;\n        } else {\n            error = true;\n        }\n    }\n    if (argc == 2) {\n        N = atoi(argw[1]);\n        if (N < 2 || N > 1000000000) error = true;\n    } else {\n        error = true;\n    }\n    if (error) {\n        printf(\"call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \\n\", argw[0]);\n        exit(1);\n    }\n    int start_s = clock();\n    Sift(N, printPrimes, nrPrimes, vBound);\n    int stop_s=clock();\n    printf(\"\\n%d primes up to %lu found in %.3f ms using array w[%d]\\n\", nrPrimes,\n      (unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program {\n\n    \n    static List<int> PrimesUpTo(int limit, bool verbose = false) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var members = new SortedSet<int>{ 1 };\n        int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1;\n        List<int> primes = new List<int>(), tl = new List<int>();\n        while (prime < rtlim) {\n            nl = Math.Min(prime * stp, limit);\n            if (stp < limit) {\n                tl.Clear(); \n                foreach (var w in members)\n                    for (n = w + stp; n <= nl; n += stp) tl.Add(n);\n                members.UnionWith(tl); ac += tl.Count;\n            }\n            stp = nl; \n            nxtpr = 5; \n            tl.Clear();\n            foreach (var w in members) {\n                if (nxtpr == 5 && w > prime) nxtpr = w;\n                if ((n = prime * w) > nl) break; else tl.Add(n);\n            }\n            foreach (var itm in tl) members.Remove(itm); rc += tl.Count;\n            primes.Add(prime);\n            prime = prime == 2 ? 3 : nxtpr;\n        }\n        members.Remove(1); primes.AddRange(members); sw.Stop();\n        if (verbose) Console.WriteLine(\"Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms\", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds);\n        return primes;\n    }\n\n    static void Main(string[] args) {\n        Console.WriteLine(\"[{0}]\", string.Join(\", \", PrimesUpTo(150, true)));\n        PrimesUpTo(1000000, true);\n    }\n}\n"}
{"id": 48600, "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": 48601, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\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": 48602, "name": "Peano curve", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 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": 48603, "name": "Seven-sided dice from five-sided dice", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\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": 48604, "name": "Solve the no connection puzzle", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 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": 48605, "name": "Extensible prime generator", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n", "Python": "islice(count(7), 0, None, 2)\n"}
{"id": 48606, "name": "Extensible prime generator", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n", "Python": "islice(count(7), 0, None, 2)\n"}
{"id": 48607, "name": "Rock-paper-scissors", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\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": 48608, "name": "Create a two-dimensional array at runtime", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\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": 48609, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \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": 48610, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \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": 48611, "name": "Vigenère cipher_Cryptanalysis", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\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": 48612, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \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": 48613, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 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": 48614, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 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": 48615, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\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": 48616, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\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": 48617, "name": "Return multiple values", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 48618, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 48619, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 48620, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 48621, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\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": 48622, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\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": 48623, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\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": 48624, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\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": 48625, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\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": 48626, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 48627, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 48628, "name": "LU decomposition", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\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": 48629, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\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": 48630, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\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": 48631, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\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": 48632, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 48633, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 48634, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\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": 48635, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\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": 48636, "name": "Checkpoint synchronization", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\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": 48637, "name": "Variable-length quantity", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\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": 48638, "name": "Record sound", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\nusing namespace std;\n\nclass recorder\n{\npublic:\n    void start()\n    {\n\tpaused = rec = false; action = \"IDLE\";\n\twhile( true )\n\t{\n\t    cout << endl << \"==\" << action << \"==\" << endl << endl;\n\t    cout << \"1) Record\" << endl << \"2) Play\" << endl << \"3) Pause\" << endl << \"4) Stop\" << endl << \"5) Quit\" << endl;\n\t    char c; cin >> c;\n\t    if( c > '0' && c < '6' )\n\t    {\n\t\tswitch( c )\n\t\t{\n\t\t    case '1': record(); break;\n\t\t    case '2': play();   break;\n\t\t    case '3': pause();  break;\n\t\t    case '4': stop();   break;\n\t\t    case '5': stop();   return;\n\t\t}\n\t    }\n\t}\n    }\nprivate:\n    void record()\n    {\n\tif( mciExecute( \"open new type waveaudio alias my_sound\") )\n\t{ \n\t    mciExecute( \"record my_sound\" ); \n\t    action = \"RECORDING\"; rec = true; \n\t}\n    }\n    void play()\n    {\n\tif( paused )\n\t    mciExecute( \"play my_sound\" );\n\telse\n\t    if( mciExecute( \"open tmp.wav alias my_sound\" ) )\n\t\tmciExecute( \"play my_sound\" );\n\n\taction = \"PLAYING\";\n\tpaused = false;\n    }\n    void pause()\n    {\n\tif( rec ) return;\n\tmciExecute( \"pause my_sound\" );\n\tpaused = true; action = \"PAUSED\";\n    }\n    void stop()\n    {\n\tif( rec )\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"save my_sound tmp.wav\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\"; rec = false;\n\t}\n\telse\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\";\n\t}\n    }\n    bool mciExecute( string cmd )\n    {\n\tif( mciSendString( cmd.c_str(), NULL, 0, NULL ) )\n\t{\n\t    cout << \"Can't do this: \" << cmd << endl;\n\t    return false;\n\t}\n\treturn true;\n    }\n\n    bool paused, rec;\n    string action;\n};\n\nint main( int argc, char* argv[] )\n{\n    recorder r; r.start();\n    return 0;\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": 48639, "name": "SHA-256 Merkle tree", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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": "\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": 48640, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\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": 48641, "name": "User input_Graphical", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\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": 48642, "name": "Sierpinski arrowhead curve", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\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": 48643, "name": "Text processing_1", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\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": 48644, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\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": 48645, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\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": 48646, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\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": 48647, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\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": 48648, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\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": 48649, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\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": 48650, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\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": 48651, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\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": 48652, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\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": 48653, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 48654, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\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": 48655, "name": "Totient function", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\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": 48656, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \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": 48657, "name": "Fractran", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\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": 48658, "name": "Fractran", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\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": 48659, "name": "Sorting algorithms_Stooge sort", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\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": 48660, "name": "Galton box animation", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\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": 48661, "name": "Sorting Algorithms_Circle Sort", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\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": 48662, "name": "Kronecker product based fractals", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\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": 48663, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\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": 48664, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\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": 48665, "name": "Circular primes", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\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": 48666, "name": "Circular primes", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\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": 48667, "name": "Animation", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\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": 48668, "name": "Sorting algorithms_Radix sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\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": 48669, "name": "List comprehensions", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\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": 48670, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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 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": 48671, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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 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": 48672, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\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": 48673, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\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": 48674, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\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": 48675, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\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": 48676, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\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": 48677, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\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": 48678, "name": "Safe addition", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\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": 48679, "name": "Case-sensitivity of identifiers", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\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": 48680, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 48681, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n"}
{"id": 48682, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 48683, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\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": 48684, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\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": 48685, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\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": 48686, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\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": 48687, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\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": 48688, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\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": 48689, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\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": 48690, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\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": 48691, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\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": 48692, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\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": 48693, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\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": 48694, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\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": 48695, "name": "Fibonacci word_fractal", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\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": 48696, "name": "Twin primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\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": 48697, "name": "15 puzzle solver", "C++": "\nclass fifteenSolver{\n  const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};\n  int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};\n  unsigned long N2[100]{};\n  const bool fY(){\n    if (N4[n]<_n) return fN();\n    if (N2[n]==0x123456789abcdef0) {std::cout<<\"Solution found in \"<<n<<\" moves :\"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};\n    if (N4[n]==_n) return fN(); else return false;\n  }\n  const bool                     fN(){\n    if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}\n    return false;\n  }\n  void fI(){\n    const int           g = (11-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);\n  } \n  void fG(){\n    const int           g = (19-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);\n  } \n  void fE(){\n    const int           g = (14-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);\n  } \n  void fL(){\n    const int           g = (16-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);\n  }\npublic:\n  fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}\n  void Solve(){for(;not fY();++_n);}\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": 48698, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\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": 48699, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 48700, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\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": 48701, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\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": 48702, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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 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": 48703, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\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": 48704, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\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": 48705, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 48706, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\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": 48707, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\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": 48708, "name": "Man or boy test", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 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": 48709, "name": "Short-circuit evaluation", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\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": 48710, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 48711, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 48712, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 48713, "name": "Carmichael 3 strong pseudoprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n"}
{"id": 48714, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n"}
{"id": 48715, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 48716, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 48717, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 48718, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 48719, "name": "Conjugate transpose", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n"}
{"id": 48720, "name": "Conjugate transpose", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n"}
{"id": 48721, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 48722, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 48723, "name": "Sorting algorithms_Bead sort", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 48724, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 48725, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 48726, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 48727, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 48728, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 48729, "name": "Inverted index", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 48730, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 48731, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 48732, "name": "Fermat numbers", "C++": "#include <iostream>\n#include <vector>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntypedef boost::multiprecision::cpp_int integer;\n\ninteger fermat(unsigned int n) {\n    unsigned int p = 1;\n    for (unsigned int i = 0; i < n; ++i)\n        p *= 2;\n    return 1 + pow(integer(2), p);\n}\n\ninline void g(integer& x, const integer& n) {\n    x *= x;\n    x += 1;\n    x %= n;\n}\n\ninteger pollard_rho(const integer& n) {\n    integer x = 2, y = 2, d = 1, z = 1;\n    int count = 0;\n    for (;;) {\n        g(x, n);\n        g(y, n);\n        g(y, n);\n        d = abs(x - y);\n        z = (z * d) % n;\n        ++count;\n        if (count == 100) {\n            d = gcd(z, n);\n            if (d != 1)\n                break;\n            z = 1;\n            count = 0;\n        }\n    }\n    if (d == n)\n        return 0;\n    return d;\n}\n\nstd::vector<integer> get_prime_factors(integer n) {\n    std::vector<integer> factors;\n    for (;;) {\n        if (miller_rabin_test(n, 25)) {\n            factors.push_back(n);\n            break;\n        }\n        integer f = pollard_rho(n);\n        if (f == 0) {\n            factors.push_back(n);\n            break;\n        }\n        factors.push_back(f);\n        n /= f;\n    }\n    return factors;\n}\n\nvoid print_vector(const std::vector<integer>& factors) {\n    if (factors.empty())\n        return;\n    auto i = factors.begin();\n    std::cout << *i++;\n    for (; i != factors.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout << \"First 10 Fermat numbers:\\n\";\n    for (unsigned int i = 0; i < 10; ++i)\n        std::cout << \"F(\" << i << \") = \" << fermat(i) << '\\n';\n    std::cout << \"\\nPrime factors:\\n\";\n    for (unsigned int i = 0; i < 9; ++i) {\n        std::cout << \"F(\" << i << \"): \";\n        print_vector(get_prime_factors(fermat(i)));\n    }\n    return 0;\n}\n", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n"}
{"id": 48733, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 48734, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 48735, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 48736, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n"}
{"id": 48737, "name": "Descending primes", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n"}
{"id": 48738, "name": "Square-free integers", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"}
{"id": 48739, "name": "Jaro similarity", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48740, "name": "Sum and product puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n"}
{"id": 48741, "name": "Fairshare between two and more", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n"}
{"id": 48742, "name": "Two bullet roulette", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <sstream>\n\nclass Roulette {\nprivate:\n    std::array<bool, 6> cylinder;\n\n    std::mt19937 gen;\n    std::uniform_int_distribution<> distrib;\n\n    int next_int() {\n        return distrib(gen);\n    }\n\n    void rshift() {\n        std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n    }\n\n    void unload() {\n        std::fill(cylinder.begin(), cylinder.end(), false);\n    }\n\n    void load() {\n        while (cylinder[0]) {\n            rshift();\n        }\n        cylinder[0] = true;\n        rshift();\n    }\n\n    void spin() {\n        int lim = next_int();\n        for (int i = 1; i < lim; i++) {\n            rshift();\n        }\n    }\n\n    bool fire() {\n        auto shot = cylinder[0];\n        rshift();\n        return shot;\n    }\n\npublic:\n    Roulette() {\n        std::random_device rd;\n        gen = std::mt19937(rd());\n        distrib = std::uniform_int_distribution<>(1, 6);\n\n        unload();\n    }\n\n    int method(const std::string &s) {\n        unload();\n        for (auto c : s) {\n            switch (c) {\n            case 'L':\n                load();\n                break;\n            case 'S':\n                spin();\n                break;\n            case 'F':\n                if (fire()) {\n                    return 1;\n                }\n                break;\n            }\n        }\n        return 0;\n    }\n};\n\nstd::string mstring(const std::string &s) {\n    std::stringstream ss;\n    bool first = true;\n\n    auto append = [&ss, &first](const std::string s) {\n        if (first) {\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << s;\n    };\n\n    for (auto c : s) {\n        switch (c) {\n        case 'L':\n            append(\"load\");\n            break;\n        case 'S':\n            append(\"spin\");\n            break;\n        case 'F':\n            append(\"fire\");\n            break;\n        }\n    }\n\n    return ss.str();\n}\n\nvoid test(const std::string &src) {\n    const int tests = 100000;\n    int sum = 0;\n\n    Roulette r;\n    for (int t = 0; t < tests; t++) {\n        sum += r.method(src);\n    }\n\n    double pc = 100.0 * sum / tests;\n\n    std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n", "Python": "\nimport numpy as np\n\nclass Revolver:\n    \n\n    def __init__(self):\n        \n        self.cylinder = np.array([False] * 6)\n\n    def unload(self):\n        \n        self.cylinder[:] = False\n\n    def load(self):\n        \n        while self.cylinder[1]:\n            self.cylinder[:] = np.roll(self.cylinder, 1)\n        self.cylinder[1] = True\n\n    def spin(self):\n        \n        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n    def fire(self):\n        \n        shot = self.cylinder[0]\n        self.cylinder[:] = np.roll(self.cylinder, 1)\n        return shot\n\n    def LSLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LSLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n    def LLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n\nif __name__ == '__main__':\n\n    REV = Revolver()\n    TESTCOUNT = 100000\n    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n                           ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n        print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\n"}
{"id": 48743, "name": "Parsing_Shunting-yard algorithm", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 48744, "name": "Trabb Pardo–Knuth algorithm", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 48745, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 48746, "name": "Sequence_ nth number with exactly n divisors", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 48747, "name": "Sequence_ smallest number with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 48748, "name": "Pancake numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n"}
{"id": 48749, "name": "Generate random chess position", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n"}
{"id": 48750, "name": "Esthetic numbers", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n"}
{"id": 48751, "name": "Topswops", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n"}
{"id": 48752, "name": "Old Russian measure of length", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n"}
{"id": 48753, "name": "Rate counter", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n"}
{"id": 48754, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 48755, "name": "Padovan sequence", "C++": "#include <iostream>\n#include <map>\n#include <cmath>\n\n\n\nint pRec(int n) {\n    static std::map<int,int> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n\n    if (n <= 2) memo[n] = 1;\n    else memo[n] = pRec(n-2) + pRec(n-3);\n    return memo[n];\n}\n\n\n\nint pFloor(int n) {\n    long const double p = 1.324717957244746025960908854;\n    long const double s = 1.0453567932525329623;\n    return std::pow(p, n-1)/s + 0.5;\n}\n\n\nstd::string& lSystem(int n) {\n    static std::map<int,std::string> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n    \n    if (n == 0) memo[n] = \"A\";\n    else {\n        memo[n] = \"\";\n        for (char ch : memo[n-1]) {\n            switch(ch) {\n                case 'A': memo[n].push_back('B'); break;\n                case 'B': memo[n].push_back('C'); break;\n                case 'C': memo[n].append(\"AB\"); break;\n            }\n        }\n    }\n    return memo[n];\n}\n\n\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n    std::cout << \"The \" << descr << \" functions \";\n    int i;\n    for (i=0; i<stop; i++) {\n        int n1 = f1(i);\n        int n2 = f2(i);\n        if (n1 != n2) {\n            std::cout << \"do not match at \" << i\n                      << \": \" << n1 << \" != \" << n2 << \".\\n\";\n            break;\n        }\n    }\n    if (i == stop) {\n        std::cout << \"match from P_0 to P_\" << stop << \".\\n\";\n    }\n}\n\nint main() {\n    \n    std::cout << \"P_0 .. P_19: \";\n    for (int i=0; i<20; i++) std::cout << pRec(i) << \" \";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, pRec, \"floor- and recurrence-based\", 64);\n    \n    \n    std::cout << \"\\nThe first 10 L-system strings are:\\n\";\n    for (int i=0; i<10; i++) std::cout << lSystem(i) << \"\\n\";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, [](int n){return (int)lSystem(n).length();}, \n                            \"floor- and L-system-based\", 32);\n    return 0;\n}\n", "Python": "from math import floor\nfrom collections import deque\nfrom typing import Dict, Generator\n\n\ndef padovan_r() -> Generator[int, None, None]:\n    last = deque([1, 1, 1], 4)\n    while True:\n        last.append(last[-2] + last[-3])\n        yield last.popleft()\n\n_p, _s = 1.324717957244746025960908854, 1.0453567932525329623\n\ndef padovan_f(n: int) -> int:\n    return floor(_p**(n-1) / _s + .5)\n\ndef padovan_l(start: str='A',\n             rules: Dict[str, str]=dict(A='B', B='C', C='AB')\n             ) -> Generator[str, None, None]:\n    axiom = start\n    while True:\n        yield axiom\n        axiom = ''.join(rules[ch] for ch in axiom)\n\n\nif __name__ == \"__main__\":\n    from itertools import islice\n\n    print(\"The first twenty terms of the sequence.\")\n    print(str([padovan_f(n) for n in range(20)])[1:-1])\n\n    r_generator = padovan_r()\n    if all(next(r_generator) == padovan_f(n) for n in range(64)):\n        print(\"\\nThe recurrence and floor based algorithms match to n=63 .\")\n    else:\n        print(\"\\nThe recurrence and floor based algorithms DIFFER!\")\n\n    print(\"\\nThe first 10 L-system string-lengths and strings\")\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    print('\\n'.join(f\"  {len(string):3} {repr(string)}\"\n                    for string in islice(l_generator, 10)))\n\n    r_generator = padovan_r()\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)\n           for n in range(32)):\n        print(\"\\nThe L-system, recurrence and floor based algorithms match to n=31 .\")\n    else:\n        print(\"\\nThe L-system, recurrence and floor based algorithms DIFFER!\")\n"}
{"id": 48756, "name": "Pythagoras tree", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n"}
{"id": 48757, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 48758, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 48759, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 48760, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 48761, "name": "Numeric error propagation", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n"}
{"id": 48762, "name": "List rooted trees", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n"}
{"id": 48763, "name": "List rooted trees", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n"}
{"id": 48764, "name": "Longest common suffix", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48765, "name": "Sum of elements below main diagonal of matrix", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n"}
{"id": 48766, "name": "FASTA format", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n"}
{"id": 48767, "name": "Elementary cellular automaton_Random number generator", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n", "Python": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n    cells = '1' + '0' * (lencells - 1)\n    gen = eca(cells, 30)\n    while True:\n        yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n    print([b for i,b in zip(range(10), rule30bytes())])\n"}
{"id": 48768, "name": "Pseudo-random numbers_PCG32", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 48769, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n"}
{"id": 48770, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n"}
{"id": 48771, "name": "Rep-string", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n"}
{"id": 48772, "name": "Literals_String", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 48773, "name": "Changeable words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n"}
{"id": 48774, "name": "Monads_List monad", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate <typename T>\nauto operator>>(const vector<T>& monad, auto f)\n{\n    \n    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;\n    for(auto& item : monad)\n    {\n        \n        \n        const auto r = f(item);\n        \n        result.insert(result.end(), begin(r), end(r));\n    }\n    \n    return result;\n}\n\n\nauto Pure(auto t)\n{\n    return vector{t};\n}\n\n\nauto Double(int i)\n{\n    return Pure(2 * i);\n}\n\n\nauto Increment(int i)\n{\n    return Pure(i + 1);\n}\n\n\nauto NiceNumber(int i)\n{\n    return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n\n\nauto UpperSequence = [](auto startingVal)\n{\n    const int MaxValue = 500;\n    vector<decltype(startingVal)> sequence;\n    while(startingVal <= MaxValue) \n        sequence.push_back(startingVal++);\n    return sequence;\n};\n\n\nvoid PrintVector(const auto& vec)\n{\n    cout << \" \";\n    for(auto value : vec)\n    {\n        cout << value << \" \";\n    }\n    cout << \"\\n\";\n}\n\n\nvoid PrintTriples(const auto& vec)\n{\n    cout << \"Pythagorean triples:\\n\";\n    for(auto it = vec.begin(); it != vec.end();)\n    {\n        auto x = *it++;\n        auto y = *it++;\n        auto z = *it++;\n        \n        cout << x << \", \" << y << \", \" << z << \"\\n\";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    \n    auto listMonad = \n        vector<int> {2, 3, 4} >> \n        Increment >> \n        Double >>\n        NiceNumber;\n        \n    PrintVector(listMonad);\n    \n    \n    \n    \n    \n    auto pythagoreanTriples = UpperSequence(1) >> \n        [](int x){return UpperSequence(x) >>\n        [x](int y){return UpperSequence(y) >>\n        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};\n    \n    PrintTriples(pythagoreanTriples);\n}\n", "Python": "\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n    @classmethod\n    def unit(cls, value: Iterable[T]) -> MList[T]:\n        return cls(value)\n\n    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return MList(chain.from_iterable(map(func, self)))\n\n    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return self.bind(func)\n\n\nif __name__ == \"__main__\":\n    \n    print(\n        MList([1, 99, 4])\n        .bind(lambda val: MList([val + 1]))\n        .bind(lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList([1, 99, 4])\n        >> (lambda val: MList([val + 1]))\n        >> (lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList(range(1, 6)).bind(\n            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n        )\n    )\n\n    \n    print(\n        MList(range(1, 26)).bind(\n            lambda x: MList(range(x + 1, 26)).bind(\n                lambda y: MList(range(y + 1, 26)).bind(\n                    lambda z: MList([(x, y, z)])\n                    if x * x + y * y == z * z\n                    else MList([])\n                )\n            )\n        )\n    )\n"}
{"id": 48775, "name": "Special factorials", "C++": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "Python": "\n\nfrom math import prod\n\ndef superFactorial(n):\n    return prod([prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef hyperFactorial(n):\n    return prod([i**i for i in range(1,n+1)])\n\ndef alternatingFactorial(n):\n    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef exponentialFactorial(n):\n    if n in [0,1]:\n        return 1\n    else:\n        return n**exponentialFactorial(n-1)\n        \ndef inverseFactorial(n):\n    i = 1\n    while True:\n        if n == prod(range(1,i)):\n            return i-1\n        elif n < prod(range(1,i)):\n            return \"undefined\"\n        i+=1\n\nprint(\"Superfactorials for [0,9] :\")\nprint({\"sf(\" + str(i) + \") \" : superFactorial(i) for i in range(0,10)})\n\nprint(\"\\nHyperfactorials for [0,9] :\")\nprint({\"H(\" + str(i) + \") \"  : hyperFactorial(i) for i in range(0,10)})\n\nprint(\"\\nAlternating factorials for [0,9] :\")\nprint({\"af(\" + str(i) + \") \" : alternatingFactorial(i) for i in range(0,10)})\n\nprint(\"\\nExponential factorials for [0,4] :\")\nprint({str(i) + \"$ \" : exponentialFactorial(i) for i in range(0,5)})\n\nprint(\"\\nDigits in 5$ : \" , len(str(exponentialFactorial(5))))\n\nfactorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n\nprint(\"\\nInverse factorials for \" , factorialSet)\nprint({\"rf(\" + str(i) + \") \":inverseFactorial(i) for i in factorialSet})\n\nprint(\"\\nrf(119) : \" + inverseFactorial(119))\n"}
{"id": 48776, "name": "Four is magic", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n"}
{"id": 48777, "name": "Getting the number of decimals", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n"}
{"id": 48778, "name": "Enumerations", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 48779, "name": "Parse an IP Address", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n"}
{"id": 48780, "name": "Textonyms", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n"}
{"id": 48781, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 48782, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 48783, "name": "Teacup rim text", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48784, "name": "Increasing gaps between consecutive Niven numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n"}
{"id": 48785, "name": "Print debugging statement", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n"}
{"id": 48786, "name": "Print debugging statement", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n"}
{"id": 48787, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n"}
{"id": 48788, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 48789, "name": "Zhang-Suen thinning algorithm", "C++": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <valarray>\nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n    friend class ZhangSuen;\n    using pixel_t = char;\n    static const pixel_t BLACK_PIX;\n    static const pixel_t WHITE_PIX;\n\n    Image(unsigned width = 1, unsigned height = 1) \n    : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n    {}\n    Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n    {}\n    Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n    {}\n    ~Image() = default;\n    Image& operator=(const Image& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = i.data_;\n        }\n        return *this;\n    }\n    Image& operator=(Image&& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = std::move(i.data_);\n        }\n        return *this;\n    }\n    size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n    bool operator()(unsigned x, unsigned y) {\n        return data_[idx(x, y)];\n    }\n    friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n        o << i.width_ << \" x \" << i.height_ << std::endl;\n        size_t px = 0;\n        for(const auto& e : i.data_) {\n            o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n            if (++px % i.width_ == 0)\n                o << std::endl;\n        }\n        return o << std::endl;\n    }\n    friend std::istream& operator>>(std::istream& in, Image& img) {\n        auto it = std::begin(img.data_);\n        const auto end = std::end(img.data_);\n        Image::pixel_t tmp;\n        while(in && it != end) {\n            in >> tmp;\n            if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n                throw \"Bad character found in image\";\n            *it = (tmp == Image::BLACK_PIX)?1:0;\n            ++it;\n        }\n        return in;\n    }\n    unsigned width() const noexcept { return width_; }\n    unsigned height() const noexcept { return height_; }\n    struct Neighbours {\n        \n        \n        \n        Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n        : img_{img}\n        , p1_{img.idx(p1_x, p1_y)}\n        , p2_{p1_ - img.width()}\n        , p3_{p2_ + 1}\n        , p4_{p1_ + 1}\n        , p5_{p4_ + img.width()}\n        , p6_{p5_ - 1}\n        , p7_{p6_ - 1}\n        , p8_{p1_ - 1}\n        , p9_{p2_ - 1} \n        {}\n        const Image& img_;\n        const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n        const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n        const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n        const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n        const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n        const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n        const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n        const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n        const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n        const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n    };\n    Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n    unsigned height_ { 0 };\n    unsigned width_ { 0 };\n    std::valarray<pixel_t> data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n    \n    unsigned transitions_white_black(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += (a.p9() == 0) && a.p2();\n        sum += (a.p2() == 0) && a.p3();\n        sum += (a.p3() == 0) && a.p4();\n        sum += (a.p8() == 0) && a.p9();\n        sum += (a.p4() == 0) && a.p5();\n        sum += (a.p7() == 0) && a.p8();\n        sum += (a.p6() == 0) && a.p7();\n        sum += (a.p5() == 0) && a.p6();\n        return sum;\n    }\n\n    \n    unsigned black_pixels(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += a.p9();\n        sum += a.p2();\n        sum += a.p3();\n        sum += a.p8();\n        sum += a.p4();\n        sum += a.p7();\n        sum += a.p6();\n        sum += a.p5();\n        return sum;\n    }\n    const Image& operator()(const Image& img) {\n        tmp_a_ = img;\n        size_t changed_pixels = 0;\n        do {\n            changed_pixels = 0;\n            \n            tmp_b_ = tmp_a_;\n            for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n                    if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n                        auto n = tmp_a_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p6() == 0)\n                                && (n.p4() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_b_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n            \n            tmp_a_ = tmp_b_;\n            for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n                    if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n                        auto n = tmp_b_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p8() == 0)\n                                && (n.p2() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_a_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n        } while(changed_pixels > 0);\n        return tmp_a_;\n    }\nprivate:\n    Image tmp_a_;\n    Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n    using namespace std;\n    Image img(32, 10);\n    istringstream iss{input};\n    iss >> img;\n    cout << img;\n    cout << \"ZhangSuen\" << endl;\n    ZhangSuen zs;\n    Image res = std::move(zs(img));\n    cout << res << endl;\n\n    Image img2(58,18);\n    istringstream iss2{input2};\n    iss2 >> img2;\n    cout << img2;\n    cout << \"ZhangSuen with big image\" << endl;\n    Image res2 = std::move(zs(img2));\n    cout << res2 << endl;\n    return 0;\n}\n", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n"}
{"id": 48790, "name": "Variable declaration reset", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n"}
{"id": 48791, "name": "Numbers with equal rises and falls", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n"}
{"id": 48792, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n"}
{"id": 48793, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n"}
{"id": 48794, "name": "Words from neighbour ones", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n"}
{"id": 48795, "name": "Magic squares of singly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n"}
{"id": 48796, "name": "Generate Chess960 starting position", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n"}
{"id": 48797, "name": "Modulinos", "C++": "int meaning_of_life();\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 48798, "name": "Modulinos", "C++": "int meaning_of_life();\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 48799, "name": "File size distribution", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\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 sys, os\nfrom collections import Counter\n\ndef dodir(path):\n    global h\n\n    for name in os.listdir(path):\n        p = os.path.join(path, name)\n\n        if os.path.islink(p):\n            pass\n        elif os.path.isfile(p):\n            h[os.stat(p).st_size] += 1\n        elif os.path.isdir(p):\n            dodir(p)\n        else:\n            pass\n\ndef main(arg):\n    global h\n    h = Counter()\n    for dir in arg:\n        dodir(dir)\n\n    s = n = 0\n    for k, v in sorted(h.items()):\n        print(\"Size %d -> %d file(s)\" % (k, v))\n        n += v\n        s += k * v\n    print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])\n"}
{"id": 48800, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 48801, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 48802, "name": "Pseudo-random numbers_Xorshift star", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 48803, "name": "Four is the number of letters in the ...", "C++": "#include <cctype>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        result.push_back(get_name(small[n], ordinal));\n        count = 1;\n    }\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result.push_back(get_name(tens[n/10 - 2], ordinal));\n        } else {\n            std::string name(get_name(tens[n/10 - 2], false));\n            name += \"-\";\n            name += get_name(small[n % 10], ordinal);\n            result.push_back(name);\n        }\n        count = 1;\n    } else {\n        const named_number& num = get_named_number(n);\n        uint64_t p = num.number;\n        count += append_number_name(result, n/p, false);\n        if (n % p == 0) {\n            result.push_back(get_name(num, ordinal));\n            ++count;\n        } else {\n            result.push_back(get_name(num, false));\n            ++count;\n            count += append_number_name(result, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(const std::string& str) {\n    size_t letters = 0;\n    for (size_t i = 0, n = str.size(); i < n; ++i) {\n        if (isalpha(static_cast<unsigned char>(str[i])))\n            ++letters;\n    }\n    return letters;\n}\n\nstd::vector<std::string> sentence(size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    std::vector<std::string> result;\n    result.reserve(count + 10);\n    size_t n = std::size(words);\n    for (size_t i = 0; i < n && i < count; ++i) {\n        result.push_back(words[i]);\n    }\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result[i]), false);\n        result.push_back(\"in\");\n        result.push_back(\"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        result.back() += ',';\n    }\n    return result;\n}\n\nsize_t sentence_length(const std::vector<std::string>& words) {\n    size_t n = words.size();\n    if (n == 0)\n        return 0;\n    size_t length = n - 1;\n    for (size_t i = 0; i < n; ++i)\n        length += words[i].size();\n    return length;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    size_t n = 201;\n    auto result = sentence(n);\n    std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            std::cout << (i % 25 == 0 ? '\\n' : ' ');\n        std::cout << std::setw(2) << count_letters(result[i]);\n    }\n    std::cout << '\\n';\n    std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    for (n = 1000; n <= 10000000; n *= 10) {\n        result = sentence(n);\n        const std::string& word = result[n - 1];\n        std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n            << count_letters(word) << \" letters. \";\n        std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    }\n    return 0;\n}\n", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n"}
{"id": 48804, "name": "ASCII art diagram converter", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n"}
{"id": 48805, "name": "Same fringe", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 48806, "name": "Peaceful chess queen armies", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n"}
{"id": 48807, "name": "Numbers with same digit set in base 10 and base 16", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n", "Python": "col = 0\nfor i in range(100000):\n    if set(str(i)) == set(hex(i)[2:]):\n        col += 1\n        print(\"{:7}\".format(i), end='\\n'[:col % 10 == 0])\nprint()\n"}
{"id": 48808, "name": "Largest proper divisor of n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n", "Python": "def lpd(n):\n    for i in range(n-1,0,-1):\n        if n%i==0: return i\n    return 1\n\nfor i in range(1,101):\n    print(\"{:3}\".format(lpd(i)), end=i%10==0 and '\\n' or '')\n"}
{"id": 48809, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 48810, "name": "Sum of first n cubes", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n"}
{"id": 48811, "name": "Sum of first n cubes", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n"}
{"id": 48812, "name": "Test integerness", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n"}
{"id": 48813, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 48814, "name": "Lucky and even lucky numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nconst int luckySize = 60000;\nstd::vector<int> luckyEven(luckySize);\nstd::vector<int> luckyOdd(luckySize);\n\nvoid init() {\n    for (int i = 0; i < luckySize; ++i) {\n        luckyEven[i] = i * 2 + 2;\n        luckyOdd[i] = i * 2 + 1;\n    }\n}\n\nvoid filterLuckyEven() {\n    for (size_t n = 2; n < luckyEven.size(); ++n) {\n        int m = luckyEven[n - 1];\n        int end = (luckyEven.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n            luckyEven.pop_back();\n        }\n    }\n}\n\nvoid filterLuckyOdd() {\n    for (size_t n = 2; n < luckyOdd.size(); ++n) {\n        int m = luckyOdd[n - 1];\n        int end = (luckyOdd.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n            luckyOdd.pop_back();\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n\n    if (even) {\n        size_t max = luckyEven.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    } else {\n        size_t max = luckyOdd.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    }\n    std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n    if (even) {\n        if (k >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n    } else {\n        if (k >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n    }\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (j >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n    } else {\n        if (j >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n    }\n}\n\nvoid help() {\n    std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"       argument(s)        |  what is displayed\\n\";\n    std::cout << \"==============================================\\n\";\n    std::cout << \"-j=m                      |  mth lucky number\\n\";\n    std::cout << \"-j=m  --lucky             |  mth lucky number\\n\";\n    std::cout << \"-j=m  --evenLucky         |  mth even lucky number\\n\";\n    std::cout << \"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\";\n    std::cout << \"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    \n    if (argc < 2) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    bool good = false;\n    for (int i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n            exit(EXIT_FAILURE);\n        }\n    }\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    init();\n    filterLuckyEven();\n    filterLuckyOdd();\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n\n    return 0;\n}\n", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n"}
{"id": 48815, "name": "Brace expansion", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 48816, "name": "Superpermutation minimisation", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n"}
{"id": 48817, "name": "GUI component interaction", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n"}
{"id": 48818, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 48819, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 48820, "name": "Summarize and say sequence", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n"}
{"id": 48821, "name": "Spelling of ordinal numbers", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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"}
{"id": 48822, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 48823, "name": "Addition chains", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n"}
{"id": 48824, "name": "Repeat", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 48825, "name": "Sparkline in unicode", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n"}
{"id": 48826, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 48827, "name": "Sunflower fractal", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n"}
{"id": 48828, "name": "Vogel's approximation method", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n"}
{"id": 48829, "name": "Chemical calculator", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n"}
{"id": 48830, "name": "Permutations by swapping", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n"}
{"id": 48831, "name": "Minimum multiple of m where digital sum equals m", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48832, "name": "Minimum multiple of m where digital sum equals m", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48833, "name": "Pythagorean quadruples", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 48834, "name": "Steady squares", "C++": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n", "Python": "print(\"working...\")\nprint(\"Steady squares under 10.000 are:\")\nlimit = 10000\n\nfor n in range(1,limit):\n    nstr = str(n)\n    nlen = len(nstr)\n    square = str(pow(n,2))\n    rn = square[-nlen:]\n    if nstr == rn:\n       print(str(n) + \" \" + str(square))\n\nprint(\"done...\")\n"}
{"id": 48835, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 48836, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 48837, "name": "Dice game probabilities", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n"}
{"id": 48838, "name": "Dice game probabilities", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n"}
{"id": 48839, "name": "Zebra puzzle", "C++": "#include <stdio.h>\n#include <string.h>\n\n#define defenum(name, val0, val1, val2, val3, val4) \\\n    enum name { val0, val1, val2, val3, val4 }; \\\n    const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }\n\ndefenum( Attrib,    Color, Man, Drink, Animal, Smoke );\ndefenum( Colors,    Red, Green, White, Yellow, Blue );\ndefenum( Mans,      English, Swede, Dane, German, Norwegian );\ndefenum( Drinks,    Tea, Coffee, Milk, Beer, Water );\ndefenum( Animals,   Dog, Birds, Cats, Horse, Zebra );\ndefenum( Smokes,    PallMall, Dunhill, Blend, BlueMaster, Prince );\n\nvoid printHouses(int ha[5][5]) {\n    const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};\n\n    printf(\"%-10s\", \"House\");\n    for (const char *name : Attrib_str) printf(\"%-10s\", name);\n    printf(\"\\n\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        for (int j = 0; j < 5; j++) printf(\"%-10s\", attr_names[j][ha[i][j]]);\n        printf(\"\\n\");\n    }\n}\n\nstruct HouseNoRule {\n    int houseno;\n    Attrib a; int v;\n} housenos[] = {\n    {2, Drink, Milk},     \n    {0, Man, Norwegian}   \n};\n\nstruct AttrPairRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&\n               ((ha[i][a1] == v1 && ha[i][a2] != v2) ||\n                (ha[i][a1] != v1 && ha[i][a2] == v2));\n    }\n} pairs[] = {\n    {Man, English,      Color, Red},     \n    {Man, Swede,        Animal, Dog},    \n    {Man, Dane,         Drink, Tea},     \n    {Color, Green,      Drink, Coffee},  \n    {Smoke, PallMall,   Animal, Birds},  \n    {Smoke, Dunhill,    Color, Yellow},  \n    {Smoke, BlueMaster, Drink, Beer},    \n    {Man, German,       Smoke, Prince}    \n};\n\nstruct NextToRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] == v1) &&\n               ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||\n                (i == 4 && ha[i - 1][a2] != v2) ||\n                (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));\n    }\n} nexttos[] = {\n    {Smoke, Blend,      Animal, Cats},    \n    {Smoke, Dunhill,    Animal, Horse},   \n    {Man, Norwegian,    Color, Blue},     \n    {Smoke, Blend,      Drink, Water}     \n};\n\nstruct LeftOfRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5]) {\n        return (ha[0][a2] == v2) || (ha[4][a1] == v1);\n    }\n\n    bool invalid(int ha[5][5], int i) {\n        return ((i > 0 && ha[i][a1] >= 0) &&\n                ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||\n                 (ha[i - 1][a1] != v1 && ha[i][a2] == v2)));\n    }\n} leftofs[] = {\n    {Color, Green,  Color, White}     \n};\n\nbool invalid(int ha[5][5]) {\n    for (auto &rule : leftofs) if (rule.invalid(ha)) return true;\n\n    for (int i = 0; i < 5; i++) {\n#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;\n        eval_rules(pairs);\n        eval_rules(nexttos);\n        eval_rules(leftofs);\n    }\n    return false;\n}\n\nvoid search(bool used[5][5], int ha[5][5], const int hno, const int attr) {\n    int nexthno, nextattr;\n    if (attr < 4) {\n        nextattr = attr + 1;\n        nexthno = hno;\n    } else {\n        nextattr = 0;\n        nexthno = hno + 1;\n    }\n\n    if (ha[hno][attr] != -1) {\n        search(used, ha, nexthno, nextattr);\n    } else {\n        for (int i = 0; i < 5; i++) {\n            if (used[attr][i]) continue;\n            used[attr][i] = true;\n            ha[hno][attr] = i;\n\n            if (!invalid(ha)) {\n                if ((hno == 4) && (attr == 4)) {\n                    printHouses(ha);\n                } else {\n                    search(used, ha, nexthno, nextattr);\n                }\n            }\n\n            used[attr][i] = false;\n        }\n        ha[hno][attr] = -1;\n    }\n}\n\nint main() {\n    bool used[5][5] = {};\n    int ha[5][5]; memset(ha, -1, sizeof(ha));\n\n    for (auto &rule : housenos) {\n        ha[rule.houseno][rule.a] = rule.v;\n        used[rule.a][rule.v] = true;\n    }\n\n    search(used, ha, 0, 0);\n\n    return 0;\n}\n", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n"}
{"id": 48840, "name": "First-class functions_Use numbers analogously", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n"}
{"id": 48841, "name": "First-class functions_Use numbers analogously", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n"}
{"id": 48842, "name": "Sokoban", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n"}
{"id": 48843, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 48844, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 48845, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 48846, "name": "Practical numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n"}
{"id": 48847, "name": "Consecutive primes with ascending or descending differences", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n"}
{"id": 48848, "name": "Consecutive primes with ascending or descending differences", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n"}
{"id": 48849, "name": "Literals_Floating point", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 48850, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 48851, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 48852, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48853, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48854, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 48855, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 48856, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 48857, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 48858, "name": "Word search", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n"}
{"id": 48859, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 48860, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 48861, "name": "Object serialization", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 48862, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 48863, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 48864, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 48865, "name": "Long year", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48866, "name": "Zumkeller numbers", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n"}
{"id": 48867, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 48868, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 48869, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 48870, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 48871, "name": "Markov chain text generator", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 48872, "name": "Dijkstra's algorithm", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 48873, "name": "Geometric algebra", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n"}
{"id": 48874, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 48875, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 48876, "name": "Associative array_Iteration", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 48877, "name": "Define a primitive data type", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n"}
{"id": 48878, "name": "Arithmetic derivative", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\ntemplate <typename IntegerType>\nIntegerType arithmetic_derivative(IntegerType n) {\n    bool negative = n < 0;\n    if (negative)\n        n = -n;\n    if (n < 2)\n        return 0;\n    IntegerType sum = 0, count = 0, m = n;\n    while ((m & 1) == 0) {\n        m >>= 1;\n        count += n;\n    }\n    if (count > 0)\n        sum += count / 2;\n    for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {\n        count = 0;\n        while (m % p == 0) {\n            m /= p;\n            count += n;\n        }\n        if (count > 0)\n            sum += count / p;\n        sq += (p + 1) << 2;\n    }\n    if (m > 1)\n        sum += n / m;\n    if (negative)\n        sum = -sum;\n    return sum;\n}\n\nint main() {\n    using boost::multiprecision::int128_t;\n\n    for (int n = -99, i = 0; n <= 100; ++n, ++i) {\n        std::cout << std::setw(4) << arithmetic_derivative(n)\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    int128_t p = 10;\n    std::cout << '\\n';\n    for (int i = 0; i < 20; ++i, p *= 10) {\n        std::cout << \"D(10^\" << std::setw(2) << i + 1\n                  << \") / 7 = \" << arithmetic_derivative(p) / 7 << '\\n';\n    }\n}\n", "Python": "from sympy.ntheory import factorint\n\ndef D(n):\n    if n < 0:\n        return -D(-n)\n    elif n < 2:\n        return 0\n    else:\n        fdict = factorint(n)\n        if len(fdict) == 1 and 1 in fdict: \n            return 1\n        return sum([n * e // p for p, e in fdict.items()])\n\nfor n in range(-99, 101):\n    print('{:5}'.format(D(n)), end='\\n' if n % 10 == 0 else '')\n\nprint()\nfor m in range(1, 21):\n    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))\n"}
{"id": 48879, "name": "Permutations with some identical elements", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n    std::string str(\"AABBBC\");\n    int count = 0;\n    do {\n        std::cout << str << (++count % 10 == 0 ? '\\n' : ' ');\n    } while (std::next_permutation(str.begin(), str.end()));\n}\n", "Python": "\n\nfrom itertools import permutations\n\nnumList = [2,3,1]\n\nbaseList = []\n\nfor i in numList:\n    for j in range(0,i):\n        baseList.append(i)\n\nstringDict = {'A':2,'B':3,'C':1}\n\nbaseString=\"\"\n\nfor i in stringDict:\n    for j in range(0,stringDict[i]):\n        baseString+=i\n\nprint(\"Permutations for \" + str(baseList) + \" : \")\n[print(i) for i in set(permutations(baseList))]\n\nprint(\"Permutations for \" + baseString + \" : \")\n[print(i) for i in set(permutations(baseString))]\n"}
{"id": 48880, "name": "Penrose tiling", "C++": "#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n\nint main() {\n    std::ofstream out(\"penrose_tiling.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string penrose(\"[N]++[N]++[N]++[N]++[N]\");\n    for (int i = 1; i <= 4; ++i) {\n        std::string next;\n        for (char ch : penrose) {\n            switch (ch) {\n            case 'A':\n                break;\n            case 'M':\n                next += \"OA++PA----NA[-OA----MA]++\";\n                break;\n            case 'N':\n                next += \"+OA--PA[---MA--NA]+\";\n                break;\n            case 'O':\n                next += \"-MA++NA[+++OA++PA]-\";\n                break;\n            case 'P':\n                next += \"--OA++++MA[+PA++++NA]--NA\";\n                break;\n            default:\n                next += ch;\n                break;\n            }\n        }\n        penrose = std::move(next);\n    }\n    const double r = 30;\n    const double pi5 = 0.628318530717959;\n    double x = r * 8, y = r * 8, theta = pi5;\n    std::set<std::string> svg;\n    std::stack<std::tuple<double, double, double>> stack;\n    for (char ch : penrose) {\n        switch (ch) {\n        case 'A': {\n            double nx = x + r * std::cos(theta);\n            double ny = y + r * std::sin(theta);\n            std::ostringstream line;\n            line << std::fixed << std::setprecision(3) << \"<line x1='\" << x\n                 << \"' y1='\" << y << \"' x2='\" << nx << \"' y2='\" << ny << \"'/>\";\n            svg.insert(line.str());\n            x = nx;\n            y = ny;\n        } break;\n        case '+':\n            theta += pi5;\n            break;\n        case '-':\n            theta -= pi5;\n            break;\n        case '[':\n            stack.push({x, y, theta});\n            break;\n        case ']':\n            std::tie(x, y, theta) = stack.top();\n            stack.pop();\n            break;\n        }\n    }\n    out << \"<svg xmlns='http:\n        << \"' width='\" << r * 16 << \"'>\\n\"\n        << \"<rect height='100%' width='100%' fill='black'/>\\n\"\n        << \"<g stroke='rgb(255,165,0)'>\\n\";\n    for (const auto& line : svg)\n        out << line << '\\n';\n    out << \"</g>\\n</svg>\\n\";\n    return EXIT_SUCCESS;\n}\n", "Python": "def penrose(depth):\n    print(\t<g id=\"A{d+1}\" transform=\"translate(100, 0) scale(0.6180339887498949)\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n\t<g id=\"B{d+1}\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\t<g id=\"G\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n  </defs>\n  <g transform=\"scale(2, 2)\">\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n  </g>\n</svg>''')\n\npenrose(6)\n"}
{"id": 48881, "name": "Sphenic numbers", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nstd::vector<int> prime_factors(int n) {\n    std::vector<int> factors;\n    if (n > 1 && (n & 1) == 0) {\n        factors.push_back(2);\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            factors.push_back(p);\n            while (n % p == 0)\n                n /= p;\n        }\n    }\n    if (n > 1)\n        factors.push_back(n);\n    return factors;\n}\n\nint main() {\n    const int limit = 1000000;\n    const int imax = limit / 6;\n    std::vector<bool> sieve = prime_sieve(imax + 1);\n    std::vector<bool> sphenic(limit + 1, false);\n    for (int i = 0; i <= imax; ++i) {\n        if (!sieve[i])\n            continue;\n        int jmax = std::min(imax, limit / (i * i));\n        if (jmax <= i)\n            break;\n        for (int j = i + 1; j <= jmax; ++j) {\n            if (!sieve[j])\n                continue;\n            int p = i * j;\n            int kmax = std::min(imax, limit / p);\n            if (kmax <= j)\n                break;\n            for (int k = j + 1; k <= kmax; ++k) {\n                if (!sieve[k])\n                    continue;\n                assert(p * k <= limit);\n                sphenic[p * k] = true;\n            }\n        }\n    }\n\n    std::cout << \"Sphenic numbers < 1000:\\n\";\n    for (int i = 0, n = 0; i < 1000; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++n;\n        std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n    for (int i = 0, n = 0; i < 10000; ++i) {\n        if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n            ++n;\n            std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n                      << (n % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n\n    int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n    for (int i = 0; i < limit; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++count;\n        if (count == 200000)\n            s200000 = i;\n        if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n            ++triplets;\n            if (triplets == 5000)\n                t5000 = i;\n        }\n    }\n\n    std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n    std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n    auto factors = prime_factors(s200000);\n    assert(factors.size() == 3);\n    std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n              << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n              << '\\n';\n\n    std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n              << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}\n", "Python": "\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n    d = factorint(i)\n    if len(d) == 3 and sum(d.values()) == 3:\n        sphenics1m.append(i)\n        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n            sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n    if n < 1000:\n        print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n    else:\n        break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n    if n < 10_000:\n        print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else '  ')\n    else:\n        break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n      'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n"}
{"id": 48882, "name": "Tree from nesting levels", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n"}
{"id": 48883, "name": "Tree from nesting levels", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n"}
{"id": 48884, "name": "Tree from nesting levels", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n"}
{"id": 48885, "name": "Find duplicate files", "C++": "#include<iostream>\n#include<string>\n#include<boost/filesystem.hpp>\n#include<boost/format.hpp>\n#include<boost/iostreams/device/mapped_file.hpp>\n#include<optional>\n#include<algorithm>\n#include<iterator>\n#include<execution>\n#include\"dependencies/xxhash.hpp\" \n\n\ntemplate<typename  T, typename V, typename F>\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n    size_t partitions = 0;\n    while (begin != end) {\n        auto const& value = getvalue(*begin);\n        auto current = begin;\n        while (++current != end && getvalue(*current) == value);\n        callback(begin, current, value);\n        ++partitions;\n        begin = current;\n    }\n    return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n    explicit file_entry(fs::directory_entry const & entry) \n        : path_{entry.path()}, size_{fs::file_size(entry)}\n    {}\n    auto size() const { return size_; }\n    auto const& path() const { return path_; }\n    auto get_hash() {\n        if (!hash_)\n            hash_ = compute_hash();\n        return *hash_;\n    }\nprivate:\n    xxh::hash64_t compute_hash() {\n        bi::mapped_file_source source;\n        source.open<fs::wpath>(this->path());\n        if (!source.is_open()) {\n            std::cerr << \"Cannot open \" << path() << std::endl;\n            throw std::runtime_error(\"Cannot open file\");\n        }\n        xxh::hash_state64_t hash_stream;\n        hash_stream.update(source.data(), size_);\n        return hash_stream.digest();\n    }\nprivate:\n    fs::wpath path_;\n    uintmax_t size_;\n    std::optional<xxh::hash64_t> hash_;\n};\n\nusing vector_type = std::vector<file_entry>;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n    size_t found = 0, ignored = 0;\n    if (!fs::is_directory(path)) {\n        std::cerr << path << \" is not a directory!\" << std::endl;\n    }\n    else {\n        std::cerr << \"Searching \" << path << std::endl;\n\n        for (auto& e : fs::recursive_directory_iterator(path)) {\n            ++found;\n            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n                file_vector.emplace_back(e);\n            else ++ignored;\n        }\n    }\n    return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n    vector_type files;\n    for (auto i = 1; i < argn; ++i) {\n        fs::wpath path(argv[i]);\n        auto [found, ignored] = find_files_in_dir(path, files);\n        std::cerr << boost::format{\n            \"  %1$6d files found\\n\"\n            \"  %2$6d files ignored\\n\"\n            \"  %3$6d files added\\n\" } % found % ignored % (found - ignored) \n            << std::endl;\n    }\n\n    std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n    \n    std::sort(std::execution::par_unseq, files.begin(), files.end()\n        , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n    );\n    for_each_adjacent_range(\n        std::begin(files)\n        , std::end(files)\n        , [](vector_type::value_type const& f) { return f.size(); }\n        , [](auto start, auto end, auto file_size) {\n            \n            size_t nr_of_files = std::distance(start, end);\n            if (nr_of_files > 1) {\n                \n                std::sort(start, end, [](auto& a, auto& b) { \n                    auto const& ha = a.get_hash();\n                    auto const& hb = b.get_hash();\n                    auto const& pa = a.path();\n                    auto const& pb = b.path();\n                    return std::tie(ha, pa) < std::tie(hb, pb); \n                    });\n                for_each_adjacent_range(\n                    start\n                    , end\n                    , [](vector_type::value_type& f) { return f.get_hash(); }\n                    , [file_size](auto hstart, auto hend, auto hash) {\n                        \n                        \n                        size_t hnr_of_files = std::distance(hstart, hend);\n                        if (hnr_of_files > 1) {\n                            std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n                                % hnr_of_files % file_size % hash;\n                            std::for_each(hstart, hend, [hash, file_size](auto& e) {\n                                std::cout << '\\t' << e.path() << '\\n';\n                                }\n                            );\n                        }\n                    }\n                );\n            }\n        }\n    );\n    \n    return 0;\n}\n", "Python": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n    knownFiles = {}\n\n    \n    for root, dirs, files in os.walk(pth):\n        for fina in files:\n            fullFina = os.path.join(root, fina)\n            isSymLink = os.path.islink(fullFina)\n            if isSymLink:\n                continue \n            si = os.path.getsize(fullFina)\n            if si < minSize:\n                continue\n            if si not in knownFiles:\n                knownFiles[si] = {}\n            h = hashlib.new(hashName)\n            h.update(open(fullFina, \"rb\").read())\n            hashed = h.digest()\n            if hashed in knownFiles[si]:\n                fileRec = knownFiles[si][hashed]\n                fileRec.append(fullFina)\n            else:\n                knownFiles[si][hashed] = [fullFina]\n\n    \n    sizeList = list(knownFiles.keys())\n    sizeList.sort(reverse=True)\n    for si in sizeList:\n        filesAtThisSize = knownFiles[si]\n        for hashVal in filesAtThisSize:\n            if len(filesAtThisSize[hashVal]) < 2:\n                continue\n            fullFinaLi = filesAtThisSize[hashVal]\n            print (\"=======Duplicate=======\")\n            for fullFina in fullFinaLi:\n                st = os.stat(fullFina)\n                isHardLink = st.st_nlink > 1 \n                infoStr = []\n                if isHardLink:\n                    infoStr.append(\"(Hard linked)\")\n                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n                print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n"}
{"id": 48886, "name": "Sylvester's sequence", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing integer = boost::multiprecision::cpp_int;\nusing rational = boost::rational<integer>;\n\ninteger sylvester_next(const integer& n) {\n    return n * n - n + 1;\n}\n\nint main() {\n    std::cout << \"First 10 elements in Sylvester's sequence:\\n\";\n    integer term = 2;\n    rational sum = 0;\n    for (int i = 1; i <= 10; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        sum += rational(1, term);\n        term = sylvester_next(term);\n    }\n    std::cout << \"Sum of reciprocals: \" << sum << '\\n';\n}\n", "Python": "\n\nfrom functools import reduce\nfrom itertools import count, islice\n\n\n\ndef sylvester():\n    \n    def go(n):\n        return 1 + reduce(\n            lambda a, x: a * go(x),\n            range(0, n),\n            1\n        ) if 0 != n else 2\n\n    return map(go, count(0))\n\n\n\n\ndef main():\n    \n\n    print(\"First 10 terms of OEIS A000058:\")\n    xs = list(islice(sylvester(), 10))\n    print('\\n'.join([\n        str(x) for x in xs\n    ]))\n\n    print(\"\\nSum of the reciprocals of the first 10 terms:\")\n    print(\n        reduce(lambda a, x: a + 1 / x, xs, 0)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48887, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 48888, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 48889, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 48890, "name": "Order disjoint list items", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\ntemplate <typename T>\nvoid print(const std::vector<T> v) {\n  std::cout << \"{ \";\n  for (const auto& e : v) {\n    std::cout << e << \" \";\n  }\n  std::cout << \"}\";\n}\n\ntemplate <typename T>\nauto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {\n  std::vector<T*> M_p(std::size(M));\n  for (auto i = 0; i < std::size(M_p); ++i) {\n    M_p[i] = &M[i];\n  }\n  for (auto e : N) {\n    auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {\n      if (c != nullptr) {\n        if (*c == e) return true;\n      }\n      return false;\n    });\n    if (i != std::end(M_p)) {\n      *i = nullptr;\n    }\n  }\n  for (auto i = 0; i < std::size(N); ++i) {\n    auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {\n      return c == nullptr;\n    });\n    if (j != std::end(M_p)) {\n      *j = &M[std::distance(std::begin(M_p), j)];\n      **j = N[i];\n    }\n  }\n  return M;\n}\n\nint main() {\n  std::vector<std::vector<std::vector<std::string>>> l = {\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" }, { \"mat\", \"cat\" } },\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" },{ \"cat\", \"mat\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"C\", \"A\", \"B\", \"C\" },{ \"C\", \"A\", \"C\", \"A\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"D\", \"A\", \"B\", \"E\" },{ \"E\", \"A\", \"D\", \"A\" } },\n    { { \"A\", \"B\" },{ \"B\" } },\n    { { \"A\", \"B\" },{ \"B\", \"A\" } },\n    { { \"A\", \"B\", \"B\", \"A\" },{ \"B\", \"A\" } }\n  };\n  for (const auto& e : l) {\n    std::cout << \"M: \";\n    print(e[0]);\n    std::cout << \", N: \";\n    print(e[1]);\n    std::cout << \", M': \";\n    auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);\n    print(res);\n    std::cout << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Python": "from __future__ import print_function\n\ndef order_disjoint_list_items(data, items):\n    \n    itemindices = []\n    for item in set(items):\n        itemcount = items.count(item)\n        \n        lastindex = [-1]\n        for i in range(itemcount):\n            lastindex.append(data.index(item, lastindex[-1] + 1))\n        itemindices += lastindex[1:]\n    itemindices.sort()\n    for index, item in zip(itemindices, items):\n        data[index] = item\n\nif __name__ == '__main__':\n    tostring = ' '.join\n    for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),\n                         (str.split('the cat sat on the mat'), str.split('cat mat')),\n                         (list('ABCABCABC'), list('CACA')),\n                         (list('ABCABDABE'), list('EADA')),\n                         (list('AB'), list('B')),\n                         (list('AB'), list('BA')),\n                         (list('ABBA'), list('BA')),\n                         (list(''), list('')),\n                         (list('A'), list('A')),\n                         (list('AB'), list('')),\n                         (list('ABBA'), list('AB')),\n                         (list('ABAB'), list('AB')),\n                         (list('ABAB'), list('BABA')),\n                         (list('ABCCBA'), list('ACAC')),\n                         (list('ABCCBA'), list('CACA')),\n                       ]:\n        print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')\n        order_disjoint_list_items(data, items)\n        print(\"-> M' %r\" % tostring(data))\n"}
{"id": 48891, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Python": "print()\n"}
{"id": 48892, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Python": "print()\n"}
{"id": 48893, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Python": "print()\n"}
{"id": 48894, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Python": "print()\n"}
{"id": 48895, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 48896, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 48897, "name": "Achilles numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n"}
{"id": 48898, "name": "Achilles numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n"}
{"id": 48899, "name": "Odd squarefree semiprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n"}
{"id": 48900, "name": "Odd squarefree semiprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n"}
{"id": 48901, "name": "Sierpinski curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n"}
{"id": 48902, "name": "Sierpinski curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n"}
{"id": 48903, "name": "Most frequent k chars distance", "C++": "#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <sstream>\n\nstd::string mostFreqKHashing ( const std::string & input , int k ) {\n   std::ostringstream oss ;\n   std::map<char, int> frequencies ;\n   for ( char c : input ) {\n      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;\n   }\n   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;\n   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,\n\t         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; \n\t         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }\n\t         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;\n   for ( int i = 0 ; i < letters.size( ) ; i++ ) {\n      oss << std::get<0>( letters[ i ] ) ;\n      oss << std::get<1>( letters[ i ] ) ;\n   }\n   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;\n   if ( letters.size( ) >= k ) {\n      return output ;\n   }\n   else {\n      return output.append( \"NULL0\" ) ;\n   }\n}\n\nint mostFreqKSimilarity ( const std::string & first , const std::string & second ) {\n   int i = 0 ;\n   while ( i < first.length( ) - 1  ) {\n      auto found = second.find_first_of( first.substr( i , 2 ) ) ;\n      if ( found != std::string::npos ) \n\t return std::stoi ( first.substr( i , 2 )) ;\n      else \n\t i += 2 ;\n   }\n   return 0 ;\n}\n\nint mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {\n   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;\n}\n\nint main( ) {\n   std::string s1(\"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\" ) ;\n   std::string s2( \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\" ) ;\n   std::cout << \"MostFreqKHashing( s1 , 2 ) = \" << mostFreqKHashing( s1 , 2 ) << '\\n' ;\n   std::cout << \"MostFreqKHashing( s2 , 2 ) = \" << mostFreqKHashing( s2 , 2 ) << '\\n' ;\n   return 0 ;\n}\n", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n"}
{"id": 48904, "name": "Palindromic primes", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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": 48905, "name": "Palindromic primes", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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": 48906, "name": "Find words which contains all the vowels", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\nbool contains_all_vowels_once(const std::string& word) {\n    std::bitset<5> vowels;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        size_t bit = 0;\n        switch (ch) {\n        case 'a': bit = 0; break;\n        case 'e': bit = 1; break;\n        case 'i': bit = 2; break;\n        case 'o': bit = 3; break;\n        case 'u': bit = 4; break;\n        default: continue;\n        }\n        if (vowels.test(bit))\n            return false;\n        vowels.set(bit);\n    }\n    return vowels.all();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        if (word.size() > 10 && contains_all_vowels_once(word))\n            std::cout << std::setw(2) << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "import urllib.request\nfrom collections import Counter\n\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>10:\n        frequency = Counter(word.lower())\n        if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:\n            print(word)\n"}
{"id": 48907, "name": "Tropical algebra overloading", "C++": "#include <iostream>\n#include <optional>\n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n    \n    optional<double> m_value;\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n    \n    \n    TropicalAlgebra() = default;\n\n    \n    explicit TropicalAlgebra(double value) noexcept\n        : m_value{value} {}\n\n    \n    \n    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            *this = rhs;\n        }\n        else if (!rhs.m_value)\n        {\n            \n        }\n        else\n        {\n            \n            *m_value = max(*rhs.m_value, *m_value);\n        }\n\n        return *this;\n    }\n    \n    \n    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            \n        }\n        else if (!rhs.m_value)\n        {\n            \n            *this = rhs;\n        }\n        else\n        {\n            *m_value += *rhs.m_value;\n        }\n\n        return *this;\n    }\n};\n\n\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n    \n    lhs += rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n    auto result = base;\n    for(unsigned int i = 1; i < exponent; i++)\n    {\n        \n        result *= base;\n    }\n    return result;\n}\n\n\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n    if(!pt.m_value) cout << \"-Inf\\n\";\n    else cout << *pt.m_value << \"\\n\";\n    return os;\n}\n\nint main(void) {\n    const TropicalAlgebra a(-2);\n    const TropicalAlgebra b(-1);\n    const TropicalAlgebra c(-0.5);\n    const TropicalAlgebra d(-0.001);\n    const TropicalAlgebra e(0);\n    const TropicalAlgebra h(1.5);\n    const TropicalAlgebra i(2);\n    const TropicalAlgebra j(5);\n    const TropicalAlgebra k(7);\n    const TropicalAlgebra l(8);\n    const TropicalAlgebra m; \n    \n    cout << \"2 * -2 == \" << i * a;\n    cout << \"-0.001 + -Inf == \" << d + m;\n    cout << \"0 * -Inf == \" << e * m;\n    cout << \"1.5 + -1 == \" << h + b;\n    cout << \"-0.5 * 0 == \" << c * e;\n    cout << \"pow(5, 7) == \" << pow(j, 7);\n    cout << \"5 * (8 + 7)) == \" << j * (l + k);\n    cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n", "Python": "from numpy import Inf\n\nclass MaxTropical:\n    \n    def __init__(self, x=0):\n        self.x = x\n\n    def __str__(self):\n        return str(self.x)\n\n    def __add__(self, other):\n        return MaxTropical(max(self.x, other.x))\n\n    def __mul__(self, other):\n        return MaxTropical(self.x + other.x)\n\n    def __pow__(self, other):\n        assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n        return MaxTropical(self.x * other.x)\n\n    def __eq__(self, other):\n        return self.x == other.x\n\n\nif __name__ == \"__main__\":\n    a = MaxTropical(-2)\n    b = MaxTropical(-1)\n    c = MaxTropical(-0.5)\n    d = MaxTropical(-0.001)\n    e = MaxTropical(0)\n    f = MaxTropical(0.5)\n    g = MaxTropical(1)\n    h = MaxTropical(1.5)\n    i = MaxTropical(2)\n    j = MaxTropical(5)\n    k = MaxTropical(7)\n    l = MaxTropical(8)\n    m = MaxTropical(-Inf)\n\n    print(\"2 * -2 == \", i * a)\n    print(\"-0.001 + -Inf == \", d + m)\n    print(\"0 * -Inf == \", e * m)\n    print(\"1.5 + -1 == \", h + b)\n    print(\"-0.5 * 0 == \", c * e)\n    print(\"5**7 == \", j**k)\n    print(\"5 * (8 + 7)) == \", j * (l + k))\n    print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n    print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n"}
{"id": 48908, "name": "Tropical algebra overloading", "C++": "#include <iostream>\n#include <optional>\n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n    \n    optional<double> m_value;\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n    \n    \n    TropicalAlgebra() = default;\n\n    \n    explicit TropicalAlgebra(double value) noexcept\n        : m_value{value} {}\n\n    \n    \n    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            *this = rhs;\n        }\n        else if (!rhs.m_value)\n        {\n            \n        }\n        else\n        {\n            \n            *m_value = max(*rhs.m_value, *m_value);\n        }\n\n        return *this;\n    }\n    \n    \n    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            \n        }\n        else if (!rhs.m_value)\n        {\n            \n            *this = rhs;\n        }\n        else\n        {\n            *m_value += *rhs.m_value;\n        }\n\n        return *this;\n    }\n};\n\n\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n    \n    lhs += rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n    auto result = base;\n    for(unsigned int i = 1; i < exponent; i++)\n    {\n        \n        result *= base;\n    }\n    return result;\n}\n\n\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n    if(!pt.m_value) cout << \"-Inf\\n\";\n    else cout << *pt.m_value << \"\\n\";\n    return os;\n}\n\nint main(void) {\n    const TropicalAlgebra a(-2);\n    const TropicalAlgebra b(-1);\n    const TropicalAlgebra c(-0.5);\n    const TropicalAlgebra d(-0.001);\n    const TropicalAlgebra e(0);\n    const TropicalAlgebra h(1.5);\n    const TropicalAlgebra i(2);\n    const TropicalAlgebra j(5);\n    const TropicalAlgebra k(7);\n    const TropicalAlgebra l(8);\n    const TropicalAlgebra m; \n    \n    cout << \"2 * -2 == \" << i * a;\n    cout << \"-0.001 + -Inf == \" << d + m;\n    cout << \"0 * -Inf == \" << e * m;\n    cout << \"1.5 + -1 == \" << h + b;\n    cout << \"-0.5 * 0 == \" << c * e;\n    cout << \"pow(5, 7) == \" << pow(j, 7);\n    cout << \"5 * (8 + 7)) == \" << j * (l + k);\n    cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n", "Python": "from numpy import Inf\n\nclass MaxTropical:\n    \n    def __init__(self, x=0):\n        self.x = x\n\n    def __str__(self):\n        return str(self.x)\n\n    def __add__(self, other):\n        return MaxTropical(max(self.x, other.x))\n\n    def __mul__(self, other):\n        return MaxTropical(self.x + other.x)\n\n    def __pow__(self, other):\n        assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n        return MaxTropical(self.x * other.x)\n\n    def __eq__(self, other):\n        return self.x == other.x\n\n\nif __name__ == \"__main__\":\n    a = MaxTropical(-2)\n    b = MaxTropical(-1)\n    c = MaxTropical(-0.5)\n    d = MaxTropical(-0.001)\n    e = MaxTropical(0)\n    f = MaxTropical(0.5)\n    g = MaxTropical(1)\n    h = MaxTropical(1.5)\n    i = MaxTropical(2)\n    j = MaxTropical(5)\n    k = MaxTropical(7)\n    l = MaxTropical(8)\n    m = MaxTropical(-Inf)\n\n    print(\"2 * -2 == \", i * a)\n    print(\"-0.001 + -Inf == \", d + m)\n    print(\"0 * -Inf == \", e * m)\n    print(\"1.5 + -1 == \", h + b)\n    print(\"-0.5 * 0 == \", c * e)\n    print(\"5**7 == \", j**k)\n    print(\"5 * (8 + 7)) == \", j * (l + k))\n    print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n    print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n"}
{"id": 48909, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n"}
{"id": 48910, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n"}
{"id": 48911, "name": "Lychrel numbers", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 48912, "name": "Lychrel numbers", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 48913, "name": "Base 16 numbers needing a to f", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48914, "name": "Base 16 numbers needing a to f", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48915, "name": "Base 16 numbers needing a to f", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48916, "name": "Range modifications", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <list>\n\nstruct range {\n    range(int lo, int hi) : low(lo), high(hi) {}\n    int low;\n    int high;\n};\n\nstd::ostream& operator<<(std::ostream& out, const range& r) {\n    return out << r.low << '-' << r.high;\n}\n\nclass ranges {\npublic:\n    ranges() {}\n    explicit ranges(std::initializer_list<range> init) : ranges_(init) {}\n    void add(int n);\n    void remove(int n);\n    bool empty() const { return ranges_.empty(); }\nprivate:\n    friend std::ostream& operator<<(std::ostream& out, const ranges& r);\n    std::list<range> ranges_;\n};\n\nvoid ranges::add(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n + 1 < i->low) {\n            ranges_.emplace(i, n, n);\n            return;\n        }\n        if (n > i->high + 1)\n            continue;\n        if (n + 1 == i->low)\n            i->low = n;\n        else if (n == i->high + 1)\n            i->high = n;\n        else\n            return;\n        if (i != ranges_.begin()) {\n            auto prev = std::prev(i);\n            if (prev->high + 1 == i->low) {\n                i->low = prev->low;\n                ranges_.erase(prev);\n            }\n        }\n        auto next = std::next(i);\n        if (next != ranges_.end() && next->low - 1 == i->high) {\n            i->high = next->high;\n            ranges_.erase(next);\n        }\n        return;\n    }\n    ranges_.emplace_back(n, n);\n}\n\nvoid ranges::remove(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n < i->low)\n            return;\n        if (n == i->low) {\n            if (++i->low > i->high)\n                ranges_.erase(i);\n            return;\n        }\n        if (n == i->high) {\n            if (--i->high < i->low)\n                ranges_.erase(i);\n            return;\n        }\n        if (n > i->low & n < i->high) {\n            int low = i->low;\n            i->low = n + 1;\n            ranges_.emplace(i, low, n - 1);\n            return;\n        }\n    }\n}\n\nstd::ostream& operator<<(std::ostream& out, const ranges& r) {\n    if (!r.empty()) {\n        auto i = r.ranges_.begin();\n        out << *i++;\n        for (; i != r.ranges_.end(); ++i)\n            out << ',' << *i;\n    }\n    return out;\n}\n\nvoid test_add(ranges& r, int n) {\n    r.add(n);\n    std::cout << \"       add \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test_remove(ranges& r, int n) {\n    r.remove(n);\n    std::cout << \"    remove \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test1() {\n    ranges r;\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 77);\n    test_add(r, 79);\n    test_add(r, 78);\n    test_remove(r, 77);\n    test_remove(r, 78);\n    test_remove(r, 79);\n}\n\nvoid test2() {\n    ranges r{{1,3}, {5,5}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 1);\n    test_remove(r, 4);\n    test_add(r, 7);\n    test_add(r, 8);\n    test_add(r, 6);\n    test_remove(r, 7);\n}\n\nvoid test3() {\n    ranges r{{1,5}, {10,25}, {27,30}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 26);\n    test_add(r, 9);\n    test_add(r, 7);\n    test_remove(r, 26);\n    test_remove(r, 9);\n    test_remove(r, 7);\n}\n\nint main() {\n    test1();\n    std::cout << '\\n';\n    test2();\n    std::cout << '\\n';\n    test3();\n    return 0;\n}\n", "Python": "class Sequence():\n    \n    def __init__(self, sequence_string):\n        self.ranges = self.to_ranges(sequence_string)\n        assert self.ranges == sorted(self.ranges), \"Sequence order error\"\n        \n    def to_ranges(self, txt):\n        return [[int(x) for x in r.strip().split('-')]\n                for r in txt.strip().split(',') if r]\n    \n    def remove(self, rem):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= rem <= r[1]:\n                if r[0] == rem:     \n                    if r[1] > rem:\n                        r[0] += 1\n                    else:\n                        del ranges[i]\n                elif r[1] == rem:   \n                    if r[0] < rem:\n                        r[1] -= 1\n                    else:\n                        del ranges[i]\n                else:               \n                    r[1], splitrange = rem - 1, [rem + 1, r[1]]\n                    ranges.insert(i + 1, splitrange)\n                break\n            if r[0] > rem:  \n                break\n        return self\n            \n    def add(self, add):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= add <= r[1]:     \n                break\n            elif r[0] - 1 == add:      \n                r[0] = add\n                break\n            elif r[1] + 1 == add:      \n                r[1] = add\n                break\n            elif r[0] > add:      \n                ranges.insert(i, [add, add])\n                break\n        else:\n            ranges.append([add, add])\n            return self\n        return self.consolidate()\n    \n    def consolidate(self):\n        \"Combine overlapping ranges\"\n        ranges = self.ranges\n        for this, that in zip(ranges, ranges[1:]):\n            if this[1] + 1 >= that[0]:  \n                if this[1] >= that[1]:  \n                    this[:], that[:] = [], this\n                else:   \n                    this[:], that[:] = [], [this[0], that[1]]\n        ranges[:] = [r for r in ranges if r]\n        return self\n    def __repr__(self):\n        rr = self.ranges\n        return \",\".join(f\"{r[0]}-{r[1]}\" for r in rr)\n\ndef demo(opp_txt):\n    by_line = opp_txt.strip().split('\\n')\n    start = by_line.pop(0)\n    ex = Sequence(start.strip().split()[-1][1:-1])    \n    lines = [line.strip().split() for line in by_line]\n    opps = [((ex.add if word[0] == \"add\" else ex.remove), int(word[1]))\n            for word in lines]\n    print(f\"Start: \\\"{ex}\\\"\")\n    for op, val in opps:\n        print(f\"    {op.__name__:>6} {val:2} => {op(val)}\")\n    print()\n                    \nif __name__ == '__main__':\n    demo()\n    demo()\n    demo()\n"}
{"id": 48917, "name": "Juggler sequence", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n"}
{"id": 48918, "name": "Juggler sequence", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n"}
{"id": 48919, "name": "Sierpinski square curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n"}
{"id": 48920, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 48921, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 48922, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 48923, "name": "Fixed length records", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nvoid reverse(std::istream& in, std::ostream& out) {\n    constexpr size_t record_length = 80;\n    char record[record_length];\n    while (in.read(record, record_length)) {\n        std::reverse(std::begin(record), std::end(record));\n        out.write(record, record_length);\n    }\n    out.flush();\n}\n\nint main(int argc, char** argv) {\n    std::ifstream in(\"infile.dat\", std::ios_base::binary);\n    if (!in) {\n        std::cerr << \"Cannot open input file\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ofstream out(\"outfile.dat\", std::ios_base::binary);\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        in.exceptions(std::ios_base::badbit);\n        out.exceptions(std::ios_base::badbit);\n        reverse(in, out);\n    } catch (const std::exception& ex) {\n        std::cerr << \"I/O error: \" << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "infile = open('infile.dat', 'rb')\noutfile = open('outfile.dat', 'wb')\n\nwhile True:\n    onerecord = infile.read(80)\n    if len(onerecord) < 80:\n        break\n    onerecordreversed = bytes(reversed(onerecord))\n    outfile.write(onerecordreversed)\n\ninfile.close()\noutfile.close()\n"}
{"id": 48924, "name": "Find words whose first and last three letters are equal", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        const size_t len = word.size();\n        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)\n            std::cout << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "import urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>5 and word[:3].lower()==word[-3:].lower():\n        print(word)\n"}
{"id": 48925, "name": "Giuga numbers", "C++": "#include <iostream>\n\n\nbool is_giuga(unsigned int n) {\n    unsigned int m = n / 2;\n    auto test_factor = [&m, n](unsigned int p) -> bool {\n        if (m % p != 0)\n            return true;\n        m /= p;\n        return m % p != 0 && (n / p - 1) % p == 0;\n    };\n    if (!test_factor(3) || !test_factor(5))\n        return false;\n    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n    for (unsigned int p = 7, i = 0; p * p <= m; ++i) {\n        if (!test_factor(p))\n            return false;\n        p += wheel[i & 7];\n    }\n    return m == 1 || (n / m - 1) % m == 0;\n}\n\nint main() {\n    std::cout << \"First 5 Giuga numbers:\\n\";\n    \n    for (unsigned int i = 0, n = 6; i < 5; n += 4) {\n        if (is_giuga(n)) {\n            std::cout << n << '\\n';\n            ++i;\n        }\n    }\n}\n", "Python": "\n\nfrom math import sqrt\n\ndef isGiuga(m):\n    n = m\n    f = 2\n    l = sqrt(n)\n    while True:\n        if n % f == 0:\n            if ((m / f) - 1) % f != 0:\n                return False\n            n /= f\n            if f > n:\n                return True\n        else:\n            f += 1\n            if f > l:\n                return False\n\n\nif __name__ == '__main__':\n    n = 3\n    c = 0\n    print(\"The first 4 Giuga numbers are: \")\n    while c < 4:\n        if isGiuga(n):\n            c += 1\n            print(n)\n        n += 1\n"}
{"id": 48926, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 48927, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 48928, "name": "Odd words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing word_list = std::vector<std::pair<std::string, std::string>>;\n\nvoid print_words(std::ostream& out, const word_list& words) {\n    int n = 1;\n    for (const auto& pair : words) {\n        out << std::right << std::setw(2) << n++ << \": \"\n            << std::left << std::setw(14) << pair.first\n            << pair.second << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    const int min_length = 5;\n    std::string line;\n    std::set<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            dictionary.insert(line);\n    }\n\n    word_list odd_words, even_words;\n\n    for (const std::string& word : dictionary) {\n        if (word.size() < min_length + 2*(min_length/2))\n            continue;\n        std::string odd_word, even_word;\n        for (auto w = word.begin(); w != word.end(); ++w) {\n            odd_word += *w;\n            if (++w == word.end())\n                break;\n            even_word += *w;\n        }\n\n        if (dictionary.find(odd_word) != dictionary.end())\n            odd_words.emplace_back(word, odd_word);\n\n        if (dictionary.find(even_word) != dictionary.end())\n            even_words.emplace_back(word, even_word);\n    }\n\n    std::cout << \"Odd words:\\n\";\n    print_words(std::cout, odd_words);\n\n    std::cout << \"\\nEven words:\\n\";\n    print_words(std::cout, even_words);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n"}
{"id": 48929, "name": "Tree datastructures", "C++": "#include <iomanip>\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n#include <utility>\n#include <vector>\n\nclass nest_tree;\n\nbool operator==(const nest_tree&, const nest_tree&);\n\nclass nest_tree {\npublic:\n    explicit nest_tree(const std::string& name) : name_(name) {}\n    nest_tree& add_child(const std::string& name) {\n        children_.emplace_back(name);\n        return children_.back();\n    }\n    void print(std::ostream& out) const {\n        print(out, 0);\n    }\n    const std::string& name() const {\n        return name_;\n    }\n    const std::list<nest_tree>& children() const {\n        return children_;\n    }\n    bool equals(const nest_tree& n) const {\n        return name_ == n.name_ && children_ == n.children_;\n    }\nprivate:\n    void print(std::ostream& out, int level) const {\n        std::string indent(level * 4, ' ');\n        out << indent << name_ << '\\n';\n        for (const nest_tree& child : children_)\n            child.print(out, level + 1);\n    }\n    std::string name_;\n    std::list<nest_tree> children_;\n};\n\nbool operator==(const nest_tree& a, const nest_tree& b) {\n    return a.equals(b);\n}\n\nclass indent_tree {\npublic:\n    explicit indent_tree(const nest_tree& n) {\n        items_.emplace_back(0, n.name());\n        from_nest(n, 0);\n    }\n    void print(std::ostream& out) const {\n        for (const auto& item : items_)\n            std::cout << item.first << ' ' << item.second << '\\n';\n    }\n    nest_tree to_nest() const {\n        nest_tree n(items_[0].second);\n        to_nest_(n, 1, 0);\n        return n;\n    }\nprivate:\n    void from_nest(const nest_tree& n, int level) {\n        for (const nest_tree& child : n.children()) {\n            items_.emplace_back(level + 1, child.name());\n            from_nest(child, level + 1);\n        }\n    }\n    size_t to_nest_(nest_tree& n, size_t pos, int level) const {\n        while (pos < items_.size() && items_[pos].first == level + 1) {\n            nest_tree& child = n.add_child(items_[pos].second);\n            pos = to_nest_(child, pos + 1, level + 1);\n        }\n        return pos;\n    }\n    std::vector<std::pair<int, std::string>> items_;\n};\n\nint main() {\n    nest_tree n(\"RosettaCode\");\n    auto& child1 = n.add_child(\"rocks\");\n    auto& child2 = n.add_child(\"mocks\");\n    child1.add_child(\"code\");\n    child1.add_child(\"comparison\");\n    child1.add_child(\"wiki\");\n    child2.add_child(\"trolling\");\n    \n    std::cout << \"Initial nest format:\\n\";\n    n.print(std::cout);\n    \n    indent_tree i(n);\n    std::cout << \"\\nIndent format:\\n\";\n    i.print(std::cout);\n    \n    nest_tree n2(i.to_nest());\n    std::cout << \"\\nFinal nest format:\\n\";\n    n2.print(std::cout);\n\n    std::cout << \"\\nAre initial and final nest formats equal? \"\n        << std::boolalpha << n.equals(n2) << '\\n';\n    \n    return 0;\n}\n", "Python": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n    if flat is None:\n        flat = []\n    if node:\n        flat.append((depth, node[0]))\n    for child in node[1]:\n        to_indent(child, depth + 1, flat)\n    return flat\n\ndef to_nest(lst, depth=0, level=None):\n    if level is None:\n        level = []\n    while lst:\n        d, name = lst[0]\n        if d == depth:\n            children = []\n            level.append((name, children))\n            lst.pop(0)\n        elif d > depth:  \n            to_nest(lst, d, children)\n        elif d < depth:  \n            return\n    return level[0] if level else None\n                    \nif __name__ == '__main__':\n    print('Start Nest format:')\n    nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n                            ('mocks', [('trolling', [])])])\n    pp(nest, width=25)\n\n    print('\\n... To Indent format:')\n    as_ind = to_indent(nest)\n    pp(as_ind, width=25)\n\n    print('\\n... To Nest format:')\n    as_nest = to_nest(as_ind)\n    pp(as_nest, width=25)\n\n    if nest != as_nest:\n        print(\"Whoops round-trip issues\")\n"}
{"id": 48930, "name": "Selectively replace multiple instances of a character within a string", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n"}
{"id": 48931, "name": "Selectively replace multiple instances of a character within a string", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n"}
{"id": 48932, "name": "Repunit primes", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n"}
{"id": 48933, "name": "Repunit primes", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n"}
{"id": 48934, "name": "Curzon numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n"}
{"id": 48935, "name": "Curzon numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n"}
{"id": 48936, "name": "Curzon numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n"}
{"id": 48937, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 48938, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 48939, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 48940, "name": "Respond to an unknown method call", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n"}
{"id": 48941, "name": "Word break problem", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 48942, "name": "Brilliant numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n"}
{"id": 48943, "name": "Brilliant numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n"}
{"id": 48944, "name": "Word ladder", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n\nbool one_away(const std::string& s1, const std::string& s2) {\n    if (s1.size() != s2.size())\n        return false;\n    bool result = false;\n    for (size_t i = 0, n = s1.size(); i != n; ++i) {\n        if (s1[i] != s2[i]) {\n            if (result)\n                return false;\n            result = true;\n        }\n    }\n    return result;\n}\n\n\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n                 separator_type separator) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += separator;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\n\n\n\nbool word_ladder(const word_map& words, const std::string& from,\n                 const std::string& to) {\n    auto w = words.find(from.size());\n    if (w != words.end()) {\n        auto poss = w->second;\n        std::vector<std::vector<std::string>> queue{{from}};\n        while (!queue.empty()) {\n            auto curr = queue.front();\n            queue.erase(queue.begin());\n            for (auto i = poss.begin(); i != poss.end();) {\n                if (!one_away(*i, curr.back())) {\n                    ++i;\n                    continue;\n                }\n                if (to == *i) {\n                    curr.push_back(to);\n                    std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n                    return true;\n                }\n                std::vector<std::string> temp(curr);\n                temp.push_back(*i);\n                queue.push_back(std::move(temp));\n                i = poss.erase(i);\n            }\n        }\n    }\n    std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n    return false;\n}\n\nint main() {\n    word_map words;\n    std::ifstream in(\"unixdict.txt\");\n    if (!in) {\n        std::cerr << \"Cannot open file unixdict.txt.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    while (getline(in, word))\n        words[word.size()].push_back(word);\n    word_ladder(words, \"boy\", \"man\");\n    word_ladder(words, \"girl\", \"lady\");\n    word_ladder(words, \"john\", \"jane\");\n    word_ladder(words, \"child\", \"adult\");\n    word_ladder(words, \"cat\", \"dog\");\n    word_ladder(words, \"lead\", \"gold\");\n    word_ladder(words, \"white\", \"black\");\n    word_ladder(words, \"bubble\", \"tickle\");\n    return EXIT_SUCCESS;\n}\n", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n"}
{"id": 48945, "name": "Joystick position", "C++": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid clear() {\n\tfor(int n = 0;n < 10; n++) {\n\t\tprintf(\"\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\r\\n\\r\\n\\r\\n\");\n\t}\n}\n\n#define UP    \"00^00\\r\\n00|00\\r\\n00000\\r\\n\"\n#define DOWN  \"00000\\r\\n00|00\\r\\n00v00\\r\\n\"\n#define LEFT  \"00000\\r\\n<--00\\r\\n00000\\r\\n\"\n#define RIGHT \"00000\\r\\n00-->\\r\\n00000\\r\\n\"\n#define HOME  \"00000\\r\\n00+00\\r\\n00000\\r\\n\"\n\nint main() {\n\tclear();\n\tsystem(\"stty raw\");\n\n\tprintf(HOME);\n\tprintf(\"space to exit; wasd to move\\r\\n\");\n\tchar c = 1;\n\n\twhile(c) {\n\t\tc = getc(stdin);\n\t\tclear();\n\n\t\tswitch (c)\n\t\t{\n\t\t\tcase 'a':\n\t\t\t\tprintf(LEFT);\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tprintf(RIGHT);\n\t\t\t\tbreak;\n\t\t\tcase 'w':\n\t\t\t\tprintf(UP);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tprintf(DOWN);\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tc = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprintf(HOME);\n\t\t};\n\n\t\tprintf(\"space to exit; wasd key to move\\r\\n\");\n\t}\n\n\tsystem(\"stty cooked\");\n\tsystem(\"clear\"); \n\treturn 1;\n}\n", "Python": "import sys\nimport pygame\n\npygame.init()\n\n\nclk = pygame.time.Clock()\n\n\nif pygame.joystick.get_count() == 0:\n    raise IOError(\"No joystick detected\")\njoy = pygame.joystick.Joystick(0)\njoy.init()\n\n\nsize = width, height = 600, 600\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Joystick Tester\")\n\n\nframeRect = pygame.Rect((45, 45), (510, 510))\n\n\ncrosshair = pygame.surface.Surface((10, 10))\ncrosshair.fill(pygame.Color(\"magenta\"))\npygame.draw.circle(crosshair, pygame.Color(\"blue\"), (5,5), 5, 0)\ncrosshair.set_colorkey(pygame.Color(\"magenta\"), pygame.RLEACCEL)\ncrosshair = crosshair.convert()\n\n\nwriter = pygame.font.Font(pygame.font.get_default_font(), 15)\nbuttons = {}\nfor b in range(joy.get_numbuttons()):\n    buttons[b] = [\n        writer.render(\n            hex(b)[2:].upper(),\n            1,\n            pygame.Color(\"red\"),\n            pygame.Color(\"black\")\n        ).convert(),\n        \n        \n        ((15*b)+45, 560)\n    ]\n\nwhile True:\n    \n    pygame.event.pump()\n    for events in pygame.event.get():\n        if events.type == pygame.QUIT:\n            pygame.quit()\n            sys.exit()\n\n    \n    screen.fill(pygame.Color(\"black\"))\n\n    \n    x = joy.get_axis(0)\n    y = joy.get_axis(1)\n\n    \n    \n    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))\n    pygame.draw.rect(screen, pygame.Color(\"red\"), frameRect, 1)\n\n    \n    for b in range(joy.get_numbuttons()):\n        if joy.get_button(b):\n            screen.blit(buttons[b][0], buttons[b][1])\n\n    \n    pygame.display.flip()\n    clk.tick(40) \n"}
{"id": 48946, "name": "Earliest difference between prime gaps", "C++": "#include <iostream>\n#include <locale>\n#include <unordered_map>\n\n#include <primesieve.hpp>\n\nclass prime_gaps {\npublic:\n    prime_gaps() { last_prime_ = iterator_.next_prime(); }\n    uint64_t find_gap_start(uint64_t gap);\nprivate:\n    primesieve::iterator iterator_;\n    uint64_t last_prime_;\n    std::unordered_map<uint64_t, uint64_t> gap_starts_;\n};\n\nuint64_t prime_gaps::find_gap_start(uint64_t gap) {\n    auto i = gap_starts_.find(gap);\n    if (i != gap_starts_.end())\n        return i->second;\n    for (;;) {\n        uint64_t prev = last_prime_;\n        last_prime_ = iterator_.next_prime();\n        uint64_t diff = last_prime_ - prev;\n        gap_starts_.emplace(diff, prev);\n        if (gap == diff)\n            return prev;\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const uint64_t limit = 100000000000;\n    prime_gaps pg;\n    for (uint64_t pm = 10, gap1 = 2;;) {\n        uint64_t start1 = pg.find_gap_start(gap1);\n        uint64_t gap2 = gap1 + 2;\n        uint64_t start2 = pg.find_gap_start(gap2);\n        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;\n        if (diff > pm) {\n            std::cout << \"Earliest difference > \" << pm\n                      << \" between adjacent prime gap starting primes:\\n\"\n                      << \"Gap \" << gap1 << \" starts at \" << start1 << \", gap \"\n                      << gap2 << \" starts at \" << start2 << \", difference is \"\n                      << diff << \".\\n\\n\";\n            if (pm == limit)\n                break;\n            pm *= 10;\n        } else {\n            gap1 = gap2;\n        }\n    }\n}\n", "Python": "\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n    if pri[i] - pri[i - 1] not in gapstarts:\n        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n    while GAP1 not in gapstarts:\n        GAP1 += 2\n    start1 = gapstarts[GAP1]\n    GAP2 = GAP1 + 2\n    if GAP2 not in gapstarts:\n        GAP1 = GAP2 + 2\n        continue\n    start2 = gapstarts[GAP2]\n    diff = abs(start2 - start1)\n    if diff > PM:\n        print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n        print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n        if PM == LIMIT:\n            break\n        PM *= 10\n    else:\n        GAP1 = GAP2\n"}
{"id": 48947, "name": "Latin Squares in reduced form", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n"}
{"id": 48948, "name": "Ormiston pairs", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <utility>\n\n#include <primesieve.hpp>\n\nclass ormiston_pair_generator {\npublic:\n    ormiston_pair_generator() { prime_ = pi_.next_prime(); }\n    std::pair<uint64_t, uint64_t> next_pair() {\n        for (;;) {\n            uint64_t prime = prime_;\n            auto digits = digits_;\n            prime_ = pi_.next_prime();\n            digits_ = get_digits(prime_);\n            if (digits_ == digits)\n                return std::make_pair(prime, prime_);\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    uint64_t prime_;\n    std::array<int, 10> digits_;\n};\n\nint main() {\n    ormiston_pair_generator generator;\n    int count = 0;\n    std::cout << \"First 30 Ormiston pairs:\\n\";\n    for (; count < 30; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        std::cout << '(' << std::setw(5) << p1 << \", \" << std::setw(5) << p2\n                  << ')' << ((count + 1) % 3 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        if (p1 > limit) {\n            std::cout << \"Number of Ormiston pairs < \" << limit << \": \" << count\n                      << '\\n';\n            limit *= 10;\n        }\n    }\n}\n", "Python": "\n\nfrom sympy import primerange\n\n\nPRIMES1M = list(primerange(1, 1_000_000))\nASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M]\nORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M))\n             if ASBASE10SORT[i - 1] == ASBASE10SORT[i]]\n\nprint('First 30 Ormiston pairs:')\nfor (i, o) in enumerate(ORMISTONS):\n    if i < 30:\n        print(f'({o[0] : 6} {o[1] : 6} )',\n              end='\\n' if (i + 1) % 5 == 0 else '  ')\n    else:\n        break\n\nprint(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')\n"}
{"id": 48949, "name": "UPC", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 48950, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 48951, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 48952, "name": "Harmonic series", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\nusing integer = boost::multiprecision::mpz_int;\nusing rational = boost::rational<integer>;\n\nclass harmonic_generator {\npublic:\n    rational next() {\n        rational result = term_;\n        term_ += rational(1, ++n_);\n        return result;\n    }\n    void reset() {\n        n_ = 1;\n        term_ = 1;\n    }\nprivate:\n    integer n_ = 1;\n    rational term_ = 1;\n};\n\nint main() {\n    std::cout << \"First 20 harmonic numbers:\\n\";\n    harmonic_generator hgen;\n    for (int i = 1; i <= 20; ++i)\n        std::cout << std::setw(2) << i << \". \" << hgen.next() << '\\n';\n    \n    rational h;\n    for (int i = 1; i <= 80; ++i)\n        h = hgen.next();\n    std::cout << \"\\n100th harmonic number: \" << h << \"\\n\\n\";\n\n    int n = 1;\n    hgen.reset();\n    for (int i = 1; n <= 10; ++i) {\n        if (hgen.next() > n)\n            std::cout << \"Position of first term > \" << std::setw(2) << n++ << \": \" << i << '\\n';\n    }\n}\n", "Python": "from  fractions import Fraction\n\ndef harmonic_series():\n    n, h = Fraction(1), Fraction(1)\n    while True:\n        yield h\n        h += 1 / (n + 1)\n        n += 1\n\nif __name__ == '__main__':\n    from itertools import islice\n    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):\n        print(n, '/', d)\n"}
{"id": 48953, "name": "External sort", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n"}
{"id": 48954, "name": "External sort", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n"}
{"id": 48955, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n)", "C++": "\nclass matrixNG {\n  private:\n  virtual void consumeTerm(){}\n  virtual void consumeTerm(int n){}\n  virtual const bool needTerm(){}\n  protected: int cfn = 0, thisTerm;\n             bool haveTerm = false;\n  friend class NG;\n};\n\nclass NG_4 : public matrixNG {\n  private: int a1, a, b1, b, t;\n  const bool needTerm() {\n    if (b1==0 and b==0) return false;\n    if (b1==0 or b==0) return true; else thisTerm = a/b;\n    if (thisTerm==(int)(a1/b1)){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;\n      haveTerm=true; return false;\n    }\n    return true;\n  }\n  void consumeTerm(){a=a1; b=b1;}\n  void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}\n  public:\n  NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}\n};\n\nclass NG : public ContinuedFraction {\n  private:\n   matrixNG* ng;\n   ContinuedFraction* n[2];\n  public:\n  NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}\n  NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}\n  const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}\n  const bool moreTerms(){\n    while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();\n    return ng->haveTerm;\n  }\n};\n", "Python": "class NG:\n  def __init__(self, a1, a, b1, b):\n    self.a1, self.a, self.b1, self.b = a1, a, b1, b\n\n  def ingress(self, n):\n    self.a, self.a1 = self.a1, self.a + self.a1 * n\n    self.b, self.b1 = self.b1, self.b + self.b1 * n\n\n  @property\n  def needterm(self):\n    return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1\n\n  @property\n  def egress(self):\n    n = self.a // self.b\n    self.a,  self.b  = self.b,  self.a  - self.b  * n\n    self.a1, self.b1 = self.b1, self.a1 - self.b1 * n\n    return n\n\n  @property\n  def egress_done(self):\n    if self.needterm: self.a, self.b = self.a1, self.b1\n    return self.egress\n\n  @property\n  def done(self):\n    return self.b == 0 and self.b1 == 0\n"}
{"id": 48956, "name": "Calkin-Wilf sequence", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n"}
{"id": 48957, "name": "Calkin-Wilf sequence", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n"}
{"id": 48958, "name": "Distribution of 0 digits in factorial series", "C++": "#include <array>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nauto init_zc() {\n    std::array<int, 1000> zc;\n    zc.fill(0);\n    zc[0] = 3;\n    for (int x = 1; x <= 9; ++x) {\n        zc[x] = 2;\n        zc[10 * x] = 2;\n        zc[100 * x] = 2;\n        for (int y = 10; y <= 90; y += 10) {\n            zc[y + x] = 1;\n            zc[10 * y + x] = 1;\n            zc[10 * (y + x)] = 1;\n        }\n    }\n    return zc;\n}\n\ntemplate <typename clock_type>\nauto elapsed(const std::chrono::time_point<clock_type>& t0) {\n    auto t1 = clock_type::now();\n    auto duration =\n        std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);\n    return duration.count();\n}\n\nint main() {\n    auto zc = init_zc();\n    auto t0 = std::chrono::high_resolution_clock::now();\n    int trail = 1, first = 0;\n    double total = 0;\n    std::vector<int> rfs{1};\n    std::cout << std::fixed << std::setprecision(10);\n    for (int f = 2; f <= 50000; ++f) {\n        int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();\n        for (int j = trail - 1; j < len || carry != 0; ++j) {\n            if (j < len)\n                carry += rfs[j] * f;\n            d999 = carry % 1000;\n            if (j < len)\n                rfs[j] = d999;\n            else\n                rfs.push_back(d999);\n            zeroes += zc[d999];\n            carry /= 1000;\n        }\n        while (rfs[trail - 1] == 0)\n            ++trail;\n        d999 = rfs.back();\n        d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;\n        zeroes -= d999;\n        int digits = rfs.size() * 3 - d999;\n        total += double(zeroes) / digits;\n        double ratio = total / f;\n        if (ratio >= 0.16)\n            first = 0;\n        else if (first == 0)\n            first = f;\n        if (f == 100 || f == 1000 || f == 10000) {\n            std::cout << \"Mean proportion of zero digits in factorials to \" << f\n                      << \" is \" << ratio << \". (\" << elapsed(t0) << \"ms)\\n\";\n        }\n    }\n    std::cout << \"The mean proportion dips permanently below 0.16 at \" << first\n              << \". (\" << elapsed(t0) << \"ms)\\n\";\n}\n", "Python": "def facpropzeros(N, verbose = True):\n    proportions = [0.0] * N\n    fac, psum = 1, 0.0\n    for i in range(N):\n        fac *= i + 1\n        d = list(str(fac))\n        psum += sum(map(lambda x: x == '0', d)) / len(d)\n        proportions[i] = psum / (i + 1)\n\n    if verbose:\n        print(\"The mean proportion of 0 in factorials from 1 to {} is {}.\".format(N, psum / N))\n\n    return proportions\n\n\nfor n in [100, 1000, 10000]:\n    facpropzeros(n)\n\nprops = facpropzeros(47500, False)\nn = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))\n\nprint(\"The mean proportion dips permanently below 0.16 at {}.\".format(n + 2))\n"}
{"id": 48959, "name": "Closest-pair problem", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 48960, "name": "Closest-pair problem", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 48961, "name": "Address of a variable", "C++": "int i;\nvoid* address_of_i = &i;\n", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n"}
{"id": 48962, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 48963, "name": "Associative array_Creation", "C++": "#include <map>\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 48964, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n"}
{"id": 48965, "name": "Plasma effect", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n"}
{"id": 48966, "name": "Abelian sandpile model_Identity", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n"}
{"id": 48967, "name": "Abelian sandpile model_Identity", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n"}
{"id": 48968, "name": "Hello world_Newbie", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n", "Python": "print \"Goodbye, World!\"\n"}
{"id": 48969, "name": "Hello world_Newbie", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n", "Python": "print \"Goodbye, World!\"\n"}
{"id": 48970, "name": "Polymorphism", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 48971, "name": "Wagstaff primes", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n"}
{"id": 48972, "name": "Wagstaff primes", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n"}
{"id": 48973, "name": "Create an object_Native demonstration", "C++": "#include <iostream>\n#include <map>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nclass FixedMap : private T\n{\n    \n    \n    \n    \n    \n    T m_defaultValues;\n    \npublic:\n    FixedMap(T map)\n    : T(map), m_defaultValues(move(map)){}\n    \n    \n    using T::cbegin;\n    using T::cend;\n    using T::empty;\n    using T::find;\n    using T::size;\n\n    \n    using T::at;\n    using T::begin;\n    using T::end;\n    \n    \n    \n    auto& operator[](typename T::key_type&& key)\n    {\n        \n        return this->at(forward<typename T::key_type>(key));\n    }\n    \n    \n    \n    void erase(typename T::key_type&& key)\n    {\n        T::operator[](key) = m_defaultValues.at(key);\n    }\n\n    \n    void clear()\n    {\n        \n        T::operator=(m_defaultValues);\n    }\n    \n};\n\n\nauto PrintMap = [](const auto &map)\n{\n    for(auto &[key, value] : map)\n    {\n        cout << \"{\" << key << \" : \" << value << \"} \";\n    }\n    cout << \"\\n\\n\";\n};\n\nint main(void) \n{\n    \n    cout << \"Map intialized with values\\n\";\n    FixedMap<map<string, int>> fixedMap ({\n        {\"a\", 1},\n        {\"b\", 2}});\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values of the keys\\n\";\n    fixedMap[\"a\"] = 55;\n    fixedMap[\"b\"] = 56;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset the 'a' key\\n\";\n    fixedMap.erase(\"a\");\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values the again\\n\";\n    fixedMap[\"a\"] = 88;\n    fixedMap[\"b\"] = 99;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset all keys\\n\";\n    fixedMap.clear();\n    PrintMap(fixedMap);\n  \n    try\n    {\n        \n        cout << \"Try to add a new key\\n\";\n        fixedMap[\"newKey\"] = 99;\n    }\n    catch (exception &ex)\n    {\n        cout << \"error: \" << ex.what();\n    }\n}\n", "Python": "from collections import UserDict\nimport copy\n\nclass Dict(UserDict):\n    \n    def __init__(self, dict=None, **kwargs):\n        self.__init = True\n        super().__init__(dict, **kwargs)\n        self.default = copy.deepcopy(self.data)\n        self.__init = False\n    \n    def __delitem__(self, key):\n        if key in self.default:\n            self.data[key] = self.default[key]\n        else:\n            raise NotImplementedError\n\n    def __setitem__(self, key, item):\n        if self.__init:\n            super().__setitem__(key, item)\n        elif key in self.data:\n            self.data[key] = item\n        else:\n            raise KeyError\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, super().__repr__())\n    \n    def fromkeys(cls, iterable, value=None):\n        if self.__init:\n            super().fromkeys(cls, iterable, value)\n        else:\n            for key in iterable:\n                if key in self.data:\n                    self.data[key] = value\n                else:\n                    raise KeyError\n\n    def clear(self):\n        self.data.update(copy.deepcopy(self.default))\n\n    def pop(self, key, default=None):\n        raise NotImplementedError\n\n    def popitem(self):\n        raise NotImplementedError\n\n    def update(self, E, **F):\n        if self.__init:\n            super().update(E, **F)\n        else:\n            haskeys = False\n            try:\n                keys = E.keys()\n                haskeys = Ture\n            except AttributeError:\n                pass\n            if haskeys:\n                for key in keys:\n                    self[key] = E[key]\n            else:\n                for key, val in E:\n                    self[key] = val\n            for key in F:\n                self[key] = F[key]\n\n    def setdefault(self, key, default=None):\n        if key not in self.data:\n            raise KeyError\n        else:\n            return super().setdefault(key, default)\n"}
{"id": 48974, "name": "Magic numbers", "C++": "#include <array>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\nclass magic_number_generator {\npublic:\n    magic_number_generator() : magic_(10) {\n        std::iota(magic_.begin(), magic_.end(), 0);\n    }\n    bool next(uint128_t& n);\n\npublic:\n    std::vector<uint128_t> magic_;\n    size_t index_ = 0;\n    int digits_ = 2;\n};\n\nbool magic_number_generator::next(uint128_t& n) {\n    if (index_ == magic_.size()) {\n        std::vector<uint128_t> magic;\n        for (uint128_t m : magic_) {\n            if (m == 0)\n                continue;\n            uint128_t n = 10 * m;\n            for (int d = 0; d < 10; ++d, ++n) {\n                if (n % digits_ == 0)\n                    magic.push_back(n);\n            }\n        }\n        index_ = 0;\n        ++digits_;\n        magic_ = std::move(magic);\n    }\n    if (magic_.empty())\n        return false;\n    n = magic_[index_++];\n    return true;\n}\n\nstd::array<int, 10> get_digits(uint128_t n) {\n    std::array<int, 10> result = {};\n    for (; n > 0; n /= 10)\n        ++result[static_cast<int>(n % 10)];\n    return result;\n}\n\nint main() {\n    int count = 0, dcount = 0;\n    uint128_t magic = 0, p = 10;\n    std::vector<int> digit_count;\n\n    std::array<int, 10> digits0 = {1,1,1,1,1,1,1,1,1,1};\n    std::array<int, 10> digits1 = {0,1,1,1,1,1,1,1,1,1};\n    std::vector<uint128_t> pandigital0, pandigital1;\n\n    for (magic_number_generator gen; gen.next(magic);) {\n        if (magic >= p) {\n            p *= 10;\n            digit_count.push_back(dcount);\n            dcount = 0;\n        }\n        auto digits = get_digits(magic);\n        if (digits == digits0)\n            pandigital0.push_back(magic);\n        else if (digits == digits1)\n            pandigital1.push_back(magic);\n        ++count;\n        ++dcount;\n    }\n    digit_count.push_back(dcount);\n\n    std::cout << \"There are \" << count << \" magic numbers.\\n\\n\";\n    std::cout << \"The largest magic number is \" << magic << \".\\n\\n\";\n\n    std::cout << \"Magic number count by digits:\\n\";\n    for (int i = 0; i < digit_count.size(); ++i)\n        std::cout << i + 1 << '\\t' << digit_count[i] << '\\n';\n\n    std::cout << \"\\nMagic numbers that are minimally pandigital in 1-9:\\n\";\n    for (auto m : pandigital1)\n        std::cout << m << '\\n';\n\n    std::cout << \"\\nMagic numbers that are minimally pandigital in 0-9:\\n\";\n    for (auto m : pandigital0)\n        std::cout << m << '\\n';\n}\n", "Python": "from itertools import groupby\n\ndef magic_numbers(base):\n    hist = []\n    n = l = i = 0\n    while True:\n        l += 1\n        hist.extend((n + digit, l) for digit in range(-n % l, base, l))\n        i += 1\n        if i == len(hist):\n            return hist\n        n, l = hist[i]\n        n *= base\n\nmn = magic_numbers(10)\nprint(\"found\", len(mn), \"magic numbers\")\nprint(\"the largest one is\", mn[-1][0])\n\nprint(\"count by number of digits:\")\nprint(*(f\"{l}:{sum(1 for _ in g)}\" for l, g in groupby(l for _, l in mn)))\n\nprint(end=\"minimally pandigital in 1..9: \")\nprint(*(m for m, l in mn if l == 9 == len(set(str(m)) - {\"0\"})))\nprint(end=\"minimally pandigital in 0..9: \")\nprint(*(m for m, l in mn if l == 10 == len(set(str(m)))))\n"}
{"id": 48975, "name": "Iterators", "C++": "#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\n\n\nvoid PrintContainer(forward_iterator auto start, forward_iterator auto sentinel)\n{\n  for(auto it = start; it != sentinel; ++it)\n  {\n    cout << *it << \" \"; \n  }\n  cout << \"\\n\";\n}\n\n\nvoid FirstFourthFifth(input_iterator auto it)\n{\n  cout << *it;\n  advance(it, 3);\n  cout << \", \" << *it;\n  advance(it, 1);\n  cout << \", \" << *it;\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  vector<string> days{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n   \"Thursday\", \"Friday\", \"Saturday\"};\n  list<string> colors{\"Red\", \"Orange\", \"Yellow\", \"Green\", \"Blue\", \"Purple\"};\n\n  cout << \"All elements:\\n\";\n  PrintContainer(days.begin(), days.end());\n  PrintContainer(colors.begin(), colors.end());\n  \n  cout << \"\\nFirst, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.begin());\n  FirstFourthFifth(colors.begin());\n\n  cout << \"\\nReverse first, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.rbegin());\n  FirstFourthFifth(colors.rbegin());\n}\n", "Python": "\nfrom collections import deque\nfrom typing import Iterable\nfrom typing import Iterator\nfrom typing import Reversible\n\n\ndays = [\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n    \"Sunday\",\n]\n\n\ncolors = deque(\n    [\n        \"red\",\n        \"yellow\",\n        \"pink\",\n        \"green\",\n        \"purple\",\n        \"orange\",\n        \"blue\",\n    ]\n)\n\n\nclass MyIterable:\n    class MyIterator:\n        def __init__(self) -> None:\n            self._day = -1\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day >= 6:\n                raise StopIteration\n\n            self._day += 1\n            return days[self._day]\n\n    class MyReversedIterator:\n        def __init__(self) -> None:\n            self._day = 7\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day <= 0:\n                raise StopIteration\n\n            self._day -= 1\n            return days[self._day]\n\n    def __iter__(self):\n        return self.MyIterator()\n\n    def __reversed__(self):\n        return self.MyReversedIterator()\n\n\ndef print_elements(container: Iterable[object]) -> None:\n    for element in container:\n        print(element, end=\" \")\n    print(\"\")  \n\n\ndef _drop(it: Iterator[object], n: int) -> None:\n    \n    try:\n        for _ in range(n):\n            next(it)\n    except StopIteration:\n        pass\n\n\ndef print_first_fourth_fifth(container: Iterable[object]) -> None:\n    \n    it = iter(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:\n    \n    it = reversed(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef main() -> None:\n    my_iterable = MyIterable()\n\n    print(\"All elements:\")\n    print_elements(days)\n    print_elements(colors)\n    print_elements(my_iterable)\n\n    print(\"\\nFirst, fourth, fifth:\")\n    print_first_fourth_fifth(days)\n    print_first_fourth_fifth(colors)\n    print_first_fourth_fifth(my_iterable)\n\n    print(\"\\nLast, fourth to last, fifth to last:\")\n    print_reversed_first_fourth_fifth(days)\n    print_reversed_first_fourth_fifth(colors)\n    print_reversed_first_fourth_fifth(my_iterable)\n\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 48976, "name": "Iterators", "C++": "#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\n\n\nvoid PrintContainer(forward_iterator auto start, forward_iterator auto sentinel)\n{\n  for(auto it = start; it != sentinel; ++it)\n  {\n    cout << *it << \" \"; \n  }\n  cout << \"\\n\";\n}\n\n\nvoid FirstFourthFifth(input_iterator auto it)\n{\n  cout << *it;\n  advance(it, 3);\n  cout << \", \" << *it;\n  advance(it, 1);\n  cout << \", \" << *it;\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  vector<string> days{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n   \"Thursday\", \"Friday\", \"Saturday\"};\n  list<string> colors{\"Red\", \"Orange\", \"Yellow\", \"Green\", \"Blue\", \"Purple\"};\n\n  cout << \"All elements:\\n\";\n  PrintContainer(days.begin(), days.end());\n  PrintContainer(colors.begin(), colors.end());\n  \n  cout << \"\\nFirst, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.begin());\n  FirstFourthFifth(colors.begin());\n\n  cout << \"\\nReverse first, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.rbegin());\n  FirstFourthFifth(colors.rbegin());\n}\n", "Python": "\nfrom collections import deque\nfrom typing import Iterable\nfrom typing import Iterator\nfrom typing import Reversible\n\n\ndays = [\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n    \"Sunday\",\n]\n\n\ncolors = deque(\n    [\n        \"red\",\n        \"yellow\",\n        \"pink\",\n        \"green\",\n        \"purple\",\n        \"orange\",\n        \"blue\",\n    ]\n)\n\n\nclass MyIterable:\n    class MyIterator:\n        def __init__(self) -> None:\n            self._day = -1\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day >= 6:\n                raise StopIteration\n\n            self._day += 1\n            return days[self._day]\n\n    class MyReversedIterator:\n        def __init__(self) -> None:\n            self._day = 7\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day <= 0:\n                raise StopIteration\n\n            self._day -= 1\n            return days[self._day]\n\n    def __iter__(self):\n        return self.MyIterator()\n\n    def __reversed__(self):\n        return self.MyReversedIterator()\n\n\ndef print_elements(container: Iterable[object]) -> None:\n    for element in container:\n        print(element, end=\" \")\n    print(\"\")  \n\n\ndef _drop(it: Iterator[object], n: int) -> None:\n    \n    try:\n        for _ in range(n):\n            next(it)\n    except StopIteration:\n        pass\n\n\ndef print_first_fourth_fifth(container: Iterable[object]) -> None:\n    \n    it = iter(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:\n    \n    it = reversed(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef main() -> None:\n    my_iterable = MyIterable()\n\n    print(\"All elements:\")\n    print_elements(days)\n    print_elements(colors)\n    print_elements(my_iterable)\n\n    print(\"\\nFirst, fourth, fifth:\")\n    print_first_fourth_fifth(days)\n    print_first_fourth_fifth(colors)\n    print_first_fourth_fifth(my_iterable)\n\n    print(\"\\nLast, fourth to last, fifth to last:\")\n    print_reversed_first_fourth_fifth(days)\n    print_reversed_first_fourth_fifth(colors)\n    print_reversed_first_fourth_fifth(my_iterable)\n\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 48977, "name": "Rare numbers", "C++": "\n\n#include <functional>\n#include <bitset>\n#include <cmath>\nusing namespace std;\nusing Z2 = optional<long long>; using Z1 = function<Z2()>;\n\nconstexpr auto pow10 = [] { array <long long, 19> n {1}; for (int j{0}, i{1}; i < 19; j = i++) n[i] = n[j] * 10; return n; } ();\nlong long acc, l;\nbool izRev(int n, unsigned long long i, unsigned long long g) {\n  return (i / pow10[n - 1] != g % 10) ? false : n < 2 ? true : izRev(n - 1, i % pow10[n - 1], g / 10);\n}\nconst Z1 fG(Z1 n, int start, int end, int reset, const long long step, long long &l) {\n  return [n, i{step * start}, g{step * end}, e{step * reset}, &l, step] () mutable {\n    while (i<g){i+=step; return Z2(l+=step);}\n    l-=g-(i=e); return n();};\n}\nstruct nLH {\n  vector<unsigned long long>even{}, odd{};\n  nLH(const Z1 a, const vector<long long> b, long long llim){while (auto i = a()) for (auto ng : b)\n    if(ng>0 | *i>llim){unsigned long long sq{ng+ *i}, r{sqrt(sq)}; if (r*r == sq) ng&1 ? odd.push_back(sq) : even.push_back(sq);}}\n};\nconst double fac = 3.94;\nconst int mbs = (int)sqrt(fac * pow10[9]), mbt = (int)sqrt(fac * fac * pow10[9]) >> 3;\nconst bitset<100000>bs {[]{bitset<100000>n{false}; for(int g{3};g<mbs;++g) n[(g*g)%100000]=true; return n;}()};\nconstexpr array<const int,  7>li{1,3,0,0,1,1,1},lin{0,-7,0,0,-8,-3,-9},lig{0,9,0,0,8,7,9},lil{0,2,0,0,2,10,2};\nconst nLH makeL(const int n){\n  constexpr int r{9}; acc=0; Z1 g{[]{return Z2{};}}; int s{-r}, q{(n>11)*5}; vector<long long> w{};\n  for (int i{1};i<n/2-q+1;++i){l=pow10[n-i-q]-pow10[i+q-1]; s-=i==n/2-q; g=fG(g,s,r,-r,l,acc+=l*s);}\n  if(q){long long g0{0}, g1{0}, g2{0}, g3{0}, g4{0}, l3{pow10[n-5]}; while (g0<7){const long long g{-10000*g4-1000*g3-100*g2-10*g1-g0};\n    if (bs[(g+1000000000000LL)%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);\n    if(g4<r) ++g4; else{g4= -r; if(g3<r) ++g3; else{g3= -r; if(g2<r) ++g2; else{g2= -r; if(g1<lig[g0]) g1+=lil[g0]; else {g0+=li[g0];g1=lin[g0];}}}}}}\n  return q ? nLH(g,w,0) : nLH(g,{0},0);\n}\nconst bitset<100000>bt {[]{bitset<100000>n{false}; for(int g{11};g<mbt;++g) n[(g*g)%100000]=true; return n;}()};\nconstexpr array<const int, 17>lu{0,0,0,0,2,0,4,0,0,0,1,4,0,0,0,1,1},lun{0,0,0,0,0,0,1,0,0,0,9,1,0,0,0,1,0},lug{0,0,0,0,18,0,17,0,0,0,9,17,0,0,0,11,18},lul{0,0,0,0,2,0,2,0,0,0,0,2,0,0,0,10,2};\nconst nLH makeH(const int n){\n  acc= -pow10[n>>1]-pow10[(n-1)>>1]; Z1 g{[]{ return Z2{};}}; int q{(n>11)*5}; vector<long long> w {};\n  for (int i{1}; i<(n>>1)-q+1; ++i) g = fG(g,0,18,0,pow10[n-i-q]+pow10[i+q-1], acc); \n  if (n & 1){l=pow10[n>>1]<<1; g=fG(g,0,9,0,l,acc+=l);}\n  if(q){long long g0{4}, g1{0}, g2{0}, g3{0}, g4{0},l3{pow10[n-5]}; while (g0<17){const long long g{g4*10000+g3*1000+g2*100+g1*10+g0};\n    if (bt[g%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);\n    if (g4<18) ++g4; else{g4=0; if(g3<18) ++g3; else{g3=0; if(g2<18) ++g2; else{g2=0; if(g1<lug[g0]) g1+=lul[g0]; else{g0+=lu[g0];g1=lun[g0];}}}}}}\n  return q ? nLH(g,w,0) : nLH(g,{0},pow10[n-1]<<2);\n}\n#include <chrono>\nusing namespace chrono; using VU = vector<unsigned long long>; using VS = vector<string>;\ntemplate <typename T> \nvector<T>& operator +=(vector<T>& v, const vector<T>& w) { v.insert(v.end(), w.begin(), w.end()); return v; }\nint c{0}; \nauto st{steady_clock::now()}, st0{st}, tmp{st}; \n\nstring dFmt(duration<double> et, int digs) {\n  string res{\"\"}; double dt{et.count()};\n  if (dt > 60.0) { int m = (int)(dt / 60.0); dt -= m * 60.0; res = to_string(m) + \"m\"; }\n  res += to_string(dt); return res.substr(0, digs - 1) + 's';\n}\n\nVS dump(int nd, VU lo, VU hi) {\n  VS res {};\n  for (auto l : lo) for (auto h : hi) {\n    auto r { (h - l) >> 1 }, z { h - r };\n    if (izRev(nd, r, z)) {\n      char buf[99]; sprintf(buf, \"%20llu %11lu %10lu\", z, (long long)sqrt(h), (long long)sqrt(l));\n      res.push_back(buf); } } return res;\n}\n\nvoid doOne(int n, nLH L, nLH H) {\n  VS lines = dump(n, L.even, H.even); lines += dump(n, L.odd , H.odd); sort(lines.begin(), lines.end());\n  duration<double> tet = (tmp = steady_clock::now()) - st; int ls = lines.size();\n  if (ls-- > 0)\n    for (int i{0}; i <= ls; ++i)\n      printf(\"%3d %s%s\", ++c, lines[i].c_str(), i == ls ? \"\" : \"\\n\");\n  else printf(\"%s\", string(47, ' ').c_str());\n  printf(\"  %2d:     %s  %s\\n\", n, dFmt(tmp - st0, 8).c_str(), dFmt(tet, 8).c_str()); st0 = tmp;\n}\nvoid Rare(int n) { doOne(n, makeL(n), makeH(n)); }\nint main(int argc, char *argv[]) {\n  int max{argc > 1 ? stoi(argv[1]) : 19}; if (max < 2) max = 2; if (max > 19 ) max = 19;\n  printf(\"%4s %19s %11s %10s %5s %11s %9s\\n\", \"nth\", \"forward\", \"rt.sum\", \"rt.diff\", \"digs\", \"block.et\", \"total.et\");\n  for (int nd{2}; nd <= max; ++nd) Rare(nd);\n}\n", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n"}
{"id": 48978, "name": "Find words which contain the most consonants", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n"}
{"id": 48979, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n"}
{"id": 48980, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n"}
{"id": 48981, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n"}
{"id": 48982, "name": "Riordan numbers", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nclass riordan_number_generator {\npublic:\n    big_int next();\n\nprivate:\n    big_int a0_ = 1;\n    big_int a1_ = 0;\n    int n_ = 0;\n};\n\nbig_int riordan_number_generator::next() {\n    int n = n_++;\n    if (n == 0)\n        return a0_;\n    if (n == 1)\n        return a1_;\n    big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1);\n    a0_ = a1_;\n    a1_ = a;\n    return a;\n}\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n)\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n    return str;\n}\n\nint main() {\n    riordan_number_generator rng;\n    std::cout << \"First 32 Riordan numbers:\\n\";\n    int i = 1;\n    for (; i <= 32; ++i) {\n        std::cout << std::setw(14) << rng.next()\n                  << (i % 4 == 0 ? '\\n' : ' ');\n    }\n    for (; i < 1000; ++i)\n        rng.next();\n    auto num = rng.next();\n    ++i;\n    std::cout << \"\\nThe 1000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n    for (; i < 10000; ++i)\n        rng.next();\n    num = rng.next();\n    std::cout << \"The 10000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n}\n", "Python": "def Riordan(N):\n    a = [1, 0, 1]\n    for n in range(3, N):\n        a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))\n    return a\n\nrios = Riordan(10_000)\n\nfor i in range(32):\n    print(f'{rios[i] : 18,}', end='\\n' if (i + 1) % 4 == 0 else '')\n\nprint(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')\nprint(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')\n"}
{"id": 48983, "name": "Riordan numbers", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nclass riordan_number_generator {\npublic:\n    big_int next();\n\nprivate:\n    big_int a0_ = 1;\n    big_int a1_ = 0;\n    int n_ = 0;\n};\n\nbig_int riordan_number_generator::next() {\n    int n = n_++;\n    if (n == 0)\n        return a0_;\n    if (n == 1)\n        return a1_;\n    big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1);\n    a0_ = a1_;\n    a1_ = a;\n    return a;\n}\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n)\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n    return str;\n}\n\nint main() {\n    riordan_number_generator rng;\n    std::cout << \"First 32 Riordan numbers:\\n\";\n    int i = 1;\n    for (; i <= 32; ++i) {\n        std::cout << std::setw(14) << rng.next()\n                  << (i % 4 == 0 ? '\\n' : ' ');\n    }\n    for (; i < 1000; ++i)\n        rng.next();\n    auto num = rng.next();\n    ++i;\n    std::cout << \"\\nThe 1000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n    for (; i < 10000; ++i)\n        rng.next();\n    num = rng.next();\n    std::cout << \"The 10000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n}\n", "Python": "def Riordan(N):\n    a = [1, 0, 1]\n    for n in range(3, N):\n        a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))\n    return a\n\nrios = Riordan(10_000)\n\nfor i in range(32):\n    print(f'{rios[i] : 18,}', end='\\n' if (i + 1) % 4 == 0 else '')\n\nprint(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')\nprint(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')\n"}
{"id": 48984, "name": "Numbers which are the cube roots of the product of their proper divisors", "C++": "#include <iomanip>\n#include <iostream>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\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    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"First 50 numbers which are the cube roots of the products of \"\n                 \"their proper divisors:\\n\";\n    for (unsigned int n = 1, count = 0; count < 50000; ++n) {\n        if (n == 1 || divisor_count(n) == 8) {\n            ++count;\n            if (count <= 50)\n                std::cout << std::setw(3) << n\n                          << (count % 10 == 0 ? '\\n' : ' ');\n            else if (count == 500 || count == 5000 || count == 50000)\n                std::cout << std::setw(6) << count << \"th: \" << n << '\\n';\n        }\n    }\n}\n", "Python": "\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n    if num * num * num == divprod:\n        FOUND += 1\n        if FOUND <= 50:\n            print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n        if FOUND == 500:\n            print(f'\\nFive hundreth: {num:,}')\n        if FOUND == 5000:\n            print(f'\\nFive thousandth: {num:,}')\n        if FOUND == 50000:\n            print(f'\\nFifty thousandth: {num:,}')\n            break\n"}
{"id": 48985, "name": "Arithmetic evaluation", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n"}
{"id": 48986, "name": "Arithmetic evaluation", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n"}
{"id": 48987, "name": "Ormiston triples", "C++": "#include <array>\n#include <iostream>\n\n#include <primesieve.hpp>\n\nclass ormiston_triple_generator {\npublic:\n    ormiston_triple_generator() {\n        for (int i = 0; i < 2; ++i) {\n            primes_[i] = pi_.next_prime();\n            digits_[i] = get_digits(primes_[i]);\n        }\n    }\n    std::array<uint64_t, 3> next_triple() {\n        for (;;) {\n            uint64_t prime = pi_.next_prime();\n            auto digits = get_digits(prime);\n            bool is_triple = digits == digits_[0] && digits == digits_[1];\n            uint64_t prime0 = primes_[0];\n            primes_[0] = primes_[1];\n            primes_[1] = prime;\n            digits_[0] = digits_[1];\n            digits_[1] = digits;\n            if (is_triple)\n                return {prime0, primes_[0], primes_[1]};\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    std::array<uint64_t, 2> primes_;\n    std::array<std::array<int, 10>, 2> digits_;\n};\n\nint main() {\n    ormiston_triple_generator generator;\n    int count = 0;\n    std::cout << \"Smallest members of first 25 Ormiston triples:\\n\";\n    for (; count < 25; ++count) {\n        auto primes = generator.next_triple();\n        std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {\n        auto primes = generator.next_triple();\n        if (primes[2] > limit) {\n            std::cout << \"Number of Ormiston triples < \" << limit << \": \"\n                      << count << '\\n';\n            limit *= 10;\n        }\n    }\n}\n", "Python": "import textwrap\n\nfrom itertools import pairwise\nfrom typing import Iterator\nfrom typing import List\n\nimport primesieve\n\n\ndef primes() -> Iterator[int]:\n    it = primesieve.Iterator()\n    while True:\n        yield it.next_prime()\n\n\ndef triplewise(iterable):\n    for (a, _), (b, c) in pairwise(pairwise(iterable)):\n        yield a, b, c\n\n\ndef is_anagram(a: int, b: int, c: int) -> bool:\n    return sorted(str(a)) == sorted(str(b)) == sorted(str(c))\n\n\ndef up_to_one_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 1_000_000_000:\n            break\n    return count\n\n\ndef up_to_ten_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 10_000_000_000:\n            break\n    return count\n\n\ndef first_25() -> List[int]:\n    rv: List[int] = []\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            rv.append(triple[0])\n            if len(rv) >= 25:\n                break\n    return rv\n\n\nif __name__ == \"__main__\":\n    print(\"Smallest members of first 25 Ormiston triples:\")\n    print(textwrap.fill(\" \".join(str(i) for i in first_25())), \"\\n\")\n    print(up_to_one_billion(), \"Ormiston triples before 1,000,000,000\")\n    print(up_to_ten_billion(), \"Ormiston triples before 10,000,000,000\")\n"}
{"id": 48988, "name": "Super-Poulet numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nstd::vector<unsigned int> divisors(unsigned int n) {\n    std::vector<unsigned int> result{1};\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        result.push_back(power);\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        size_t size = result.size();\n        for (power = p; n % p == 0; power *= p, n /= p)\n            for (size_t i = 0; i != size; ++i)\n                result.push_back(power * result[i]);\n    }\n    if (n > 1) {\n        size_t size = result.size();\n        for (size_t i = 0; i != size; ++i)\n            result.push_back(n * result[i]);\n    }\n    return result;\n}\n\nunsigned long long modpow(unsigned long long base, unsigned int exp,\n                          unsigned int mod) {\n    if (mod == 1)\n        return 0;\n    unsigned long long result = 1;\n    base %= mod;\n    for (; exp != 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\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    if (n % 5 == 0)\n        return n == 5;\n    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n    for (unsigned int p = 7;;) {\n        for (unsigned int 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\nbool is_poulet_number(unsigned int n) {\n    return modpow(2, n - 1, n) == 1 && !is_prime(n);\n}\n\nbool is_sp_num(unsigned int n) {\n    if (!is_poulet_number(n))\n        return false;\n    auto div = divisors(n);\n    return all_of(div.begin() + 1, div.end(),\n                  [](unsigned int d) { return modpow(2, d, d) == 2; });\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    unsigned int n = 1, count = 0;\n    std::cout << \"First 20 super-Poulet numbers:\\n\";\n    for (; count < 20; n += 2) {\n        if (is_sp_num(n)) {\n            ++count;\n            std::cout << n << ' ';\n        }\n    }\n    std::cout << '\\n';\n    for (unsigned int limit = 1000000; limit <= 10000000; limit *= 10) {\n        for (;;) {\n            n += 2;\n            if (is_sp_num(n)) {\n                ++count;\n                if (n > limit)\n                    break;\n            }\n        }\n        std::cout << \"\\nIndex and value of first super-Poulet greater than \"\n                  << limit << \":\\n#\" << count << \" is \" << n << '\\n';\n    }\n}\n", "Python": "from sympy import isprime, divisors\n \ndef is_super_Poulet(n):\n    return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n))\n\nspoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)]\n\nprint('The first 20 super-Poulet numbers are:', spoulets[:20])\n\nidx1m, val1m = next((i, v) for i, v in enumerate(spoulets) if v > 1_000_000)\nprint(f'The first super-Poulet number over 1 million is the {idx1m}th one, which is {val1m}')\n"}
{"id": 48989, "name": "Special variables", "C++": "#include <iostream>\n\nstruct SpecialVariables\n{\n    int i = 0;\n\n    SpecialVariables& operator++()\n    {\n        \n        \n        \n        this->i++;  \n\n        \n        return *this;\n    }\n\n};\n\nint main()\n{\n    SpecialVariables sv;\n    auto sv2 = ++sv;     \n    std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}\n", "Python": "names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))\nprint( '\\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )\n"}
{"id": 48990, "name": "Minesweeper game", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\nusing namespace std;\ntypedef unsigned char byte;\n\nenum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };\n\nclass fieldData\n{\npublic:\n    fieldData() : value( CLOSED ), open( false ) {}\n    byte value;\n    bool open, mine;\n};\n\nclass game\n{\npublic:\n    ~game()\n    { if( field ) delete [] field; }\n\n    game( int x, int y )\n    {\n        go = false; wid = x; hei = y;\n\tfield = new fieldData[x * y];\n\tmemset( field, 0, x * y * sizeof( fieldData ) );\n\toMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;\n\tmMines = 0;\n\tint mx, my, m = 0;\n\tfor( ; m < oMines; m++ )\n\t{\n\t    do\n\t    { mx = rand() % wid; my = rand() % hei; }\n\t    while( field[mx + wid * my].mine );\n\t    field[mx + wid * my].mine = true;\n\t}\n\tgraphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; \n\tgraphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; \n    }\n\t\n    void gameLoop()\n    {\n\tstring c, r, a;\n\tint col, row;\n\twhile( !go )\n\t{\n\t    drawBoard();\n\t    cout << \"Enter column, row and an action( c r a ):\\nActions: o => open, f => flag, ? => unknown\\n\";\n\t    cin >> c >> r >> a;\n\t    if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;\n\t    col = c[0] - 65; row = r[0] - 49;\n\t    makeMove( col, row, a );\n\t}\n    }\n\nprivate:\n    void makeMove( int x, int y, string a )\n    {\n\tfieldData* fd = &field[wid * y + x];\n\tif( fd->open && fd->value < CLOSED )\n\t{\n\t    cout << \"This cell is already open!\";\n\t    Sleep( 3000 ); return;\n\t}\n\tif( a[0] == 'O' ) openCell( x, y );\n\telse if( a[0] == 'F' ) \n\t{\n\t    fd->open = true;\n\t    fd->value = FLAG;\n\t    mMines++;\n\t    checkWin();\n\t}\n\telse\n\t{\n\t    fd->open = true;\n\t    fd->value = UNKNOWN;\n\t}\n    }\n\n    bool openCell( int x, int y )\n    {\n\tif( !isInside( x, y ) ) return false;\n\tif( field[x + y * wid].mine ) boom();\n\telse \n\t{\n\t    if( field[x + y * wid].value == FLAG )\n\t    {\n\t\tfield[x + y * wid].value = CLOSED;\n\t\tfield[x + y * wid].open = false;\n\t\tmMines--;\n\t    }\n\t    recOpen( x, y );\n\t    checkWin();\n\t}\n\treturn true;\n    }\n\n    void drawBoard()\n    {\n\tsystem( \"cls\" );\n\tcout << \"Marked mines: \" << mMines << \" from \" << oMines << \"\\n\\n\";\t\t\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"  \" << ( char )( 65 + x ) << \" \"; \n\tcout << \"\\n\"; int yy;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = y * wid;\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << \"+---\";\n\n\t    cout << \"+\\n\"; fieldData* fd;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy]; cout<< \"| \";\n\t\tif( !fd->open ) cout << ( char )graphs[1] << \" \";\n\t\telse \n\t\t{\n\t\t    if( fd->value > 9 )\n\t\t\tcout << ( char )graphs[fd->value - 9] << \" \";\n\t\t    else\n\t\t    {\n\t\t\tif( fd->value < 1 ) cout << \"  \";\n\t\t\t    else cout << ( char )(fd->value + 48 ) << \" \";\n\t\t    }\n\t\t}\n\t    }\n\t    cout << \"| \" << y + 1 << \"\\n\";\n\t}\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"+---\";\n\n\tcout << \"+\\n\\n\";\n    }\n\n    void checkWin()\n    {\n\tint z = wid * hei - oMines, yy;\n\tfieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->open && fd->value != FLAG ) z--;\n\t    }\n\t}\n\tif( !z ) lastMsg( \"Congratulations, you won the game!\");\n    }\n\n    void boom()\n    {\n\tint yy; fieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->value == FLAG )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = fd->mine ? MINE : ERR;\n\t\t}\n\t\telse if( fd->mine )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = MINE;\n\t\t}\n\t    }\n\t}\n\tlastMsg( \"B O O O M M M M M !\" );\n    }\n\n    void lastMsg( string s )\n    {\n\tgo = true; drawBoard();\n\tcout << s << \"\\n\\n\";\n    }\n\n    bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }\n\n    void recOpen( int x, int y )\n    {\n\tif( !isInside( x, y ) || field[x + y * wid].open ) return;\n\tint bc = getMineCount( x, y );\n\tfield[x + y * wid].open = true;\n\tfield[x + y * wid].value = bc;\n\tif( bc ) return;\n\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\trecOpen( x + xx, y + yy );\n\t    }\n    }\n\n    int getMineCount( int x, int y )\n    {\n\tint m = 0;\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\tif( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;\n\t    }\n\t\t\n\treturn m;\n    }\n\t\n    int wid, hei, mMines, oMines;\n    fieldData* field; bool go;\n    int graphs[6];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    game g( 4, 6 ); g.gameLoop();\n    return system( \"pause\" );\n}\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 48991, "name": "Elementary cellular automaton_Infinite length", "C++": "#include <iostream>\n#include <iomanip>\n#include <string>\n\nclass oo {\npublic:\n    void evolve( int l, int rule ) {\n        std::string    cells = \"O\";\n        std::cout << \" Rule #\" << rule << \":\\n\";\n        for( int x = 0; x < l; x++ ) {\n            addNoCells( cells );\n            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n            step( cells, rule );\n        }\n    }\nprivate:\n    void step( std::string& cells, int rule ) {\n        int bin;\n        std::string newCells;\n        for( size_t i = 0; i < cells.length() - 2; i++ ) {\n            bin = 0;\n            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n            }\n            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n        }\n        cells = newCells;\n    }\n    void addNoCells( std::string& s ) {\n        char l = s.at( 0 ) == 'O' ? '.' : 'O',\n             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n        s = l + s + r;\n        s = l + s + r;\n    }\n};\nint main( int argc, char* argv[] ) {\n    oo o;\n    o.evolve( 35, 90 );\n    std::cout << \"\\n\";\n    return 0;\n}\n", "Python": "def _notcell(c):\n    return '0' if c == '1' else '1'\n\ndef eca_infinite(cells, rule):\n    lencells = len(cells)\n    rulebits = '{0:08b}'.format(rule)\n    neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n    c = cells\n    while True:\n        yield c\n        c = _notcell(c[0])*2 + c + _notcell(c[-1])*2    \n\n        c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))\n        \n\nif __name__ == '__main__':\n    lines = 25\n    for rule in (90, 30):\n        print('\\nRule: %i' % rule)\n        for i, c in zip(range(lines), eca_infinite('1', rule)):\n            print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '\n"}
{"id": 48992, "name": "Execute CopyPasta Language", "C++": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n\n#include <stdlib.h>\n\nusing namespace std;\n\n\nvoid fatal_error(string errtext, char *argv[])\n{\n\tcout << \"%\" << errtext << endl;\n\tcout << \"usage: \" << argv[0] << \" [filename.cp]\" << endl;\n\texit(1);\n}\n\n\n\nstring& ltrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(0, str.find_first_not_of(chars));\n\treturn str;\n}\nstring& rtrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(str.find_last_not_of(chars) + 1);\n\treturn str;\n}\nstring& trim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\treturn ltrim(rtrim(str, chars), chars);\n}\n\nint main(int argc, char *argv[])\n{\n\t\n\tstring fname = \"\";\n\tstring source = \"\";\n\ttry\n\t{\n\t\tfname = argv[1];\n\t\tifstream t(fname);\n\n\t\tt.seekg(0, ios::end);\n\t\tsource.reserve(t.tellg());\n\t\tt.seekg(0, ios::beg);\n\n\t\tsource.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t}\n\tcatch(const exception& e)\n\t{\n\t\tfatal_error(\"error while trying to read from specified file\", argv);\n\t}\n\n\t\n\tstring clipboard = \"\";\n\n\t\n\tint loc = 0;\n\tstring remaining = source;\n\tstring line = \"\";\n\tstring command = \"\";\n\tstringstream ss;\n\twhile(remaining.find(\"\\n\") != string::npos)\n\t{\n\t\t\n\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\tcommand = trim(line);\n\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\n\t\ttry\n\t\t{\n\t\t\tif(line == \"Copy\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tclipboard += line;\n\t\t\t}\n\t\t\telse if(line == \"CopyFile\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tif(line == \"TheF*ckingCode\")\n\t\t\t\t\tclipboard += source;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring filetext = \"\";\n\t\t\t\t\tifstream t(line);\n\n\t\t\t\t\tt.seekg(0, ios::end);\n\t\t\t\t\tfiletext.reserve(t.tellg());\n\t\t\t\t\tt.seekg(0, ios::beg);\n\n\t\t\t\t\tfiletext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t\t\t\t\tclipboard += filetext;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Duplicate\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tint amount = stoi(line);\n\t\t\t\tstring origClipboard = clipboard;\n\t\t\t\tfor(int i = 0; i < amount - 1; i++) {\n\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Pasta!\")\n\t\t\t{\n\t\t\t\tcout << clipboard << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss << (loc + 1);\n\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encounter on line \" + ss.str(), argv);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception& e)\n\t\t{\n\t\t\tss << (loc + 1);\n\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + ss.str(), argv);\n\t\t}\n\n\t\t\n\t\tloc += 2;\n\t}\n\n\t\n\treturn 0;\n}\n", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n"}
{"id": 48993, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nvoid print_non_twin_prime_sums(const std::vector<bool>& sums) {\n    int count = 0;\n    for (size_t i = 2; i < sums.size(); i += 2) {\n        if (!sums[i]) {\n            ++count;\n            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nFound \" << count << '\\n';\n}\n\nint main() {\n    const int limit = 100001;\n\n    std::vector<bool> sieve = prime_sieve(limit + 2);\n    \n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))\n            sieve[i] = false;\n    }\n\n    std::vector<bool> twin_prime_sums(limit, false);\n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i]) {\n            for (size_t j = i; i + j < limit; ++j) {\n                if (sieve[j])\n                    twin_prime_sums[i + j] = true;\n            }\n        }\n    }\n\n    std::cout << \"Non twin prime sums:\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n\n    sieve[1] = true;\n    for (size_t i = 1; i + 1 < limit; ++i) {\n        if (sieve[i])\n            twin_prime_sums[i + 1] = true;\n    }\n\n    std::cout << \"\\nNon twin prime sums (including 1):\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n}\n", "Python": "\n\nfrom sympy import sieve\n\n\ndef nonpairsums(include1=False, limit=20_000):\n    \n    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)\n            for i in range(limit+2)]\n    if include1:\n        tpri[1] = True\n    twinsums = [False] * (limit * 2)\n    for i in range(limit):\n        for j in range(limit-i+1):\n            if tpri[i] and tpri[j]:\n                twinsums[i + j] = True\n\n    return [i for i in range(2, limit+1, 2) if not twinsums[i]]\n\n\nprint('Non twin prime sums:')\nfor k, p in enumerate(nonpairsums()):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n\nprint('\\n\\nNon twin prime sums (including 1):')\nfor k, p in enumerate(nonpairsums(include1=True)):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n"}
{"id": 48994, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n"}
{"id": 48995, "name": "Variables", "C++": "int a;\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 48996, "name": "Sieve of Pritchard", "C++": "\n\n\n\n#include <cstring>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <ctime>\n\nvoid Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) {\n    \n    uint32_t i, j, x;\n    i = 0; j = w_end;\n    x = length + 1; \n    while (x <= n) {\n        w[++j] = x; \n        d[x] = false;\n        x = length + w[++i];\n    }\n    length = n; w_end = j;\n    if (w_end > w_end_max) w_end_max = w_end;\n}\n\nvoid Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) {\n    \n    uint32_t i, x;\n    i = 0;\n    x = p; \n    while (x <= length) {\n        d[x] = true; \n        x = p*w[++i];\n    }\n    imaxf = i-1;\n}\n\nvoid Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) {\n    \n    uint32_t i, j;\n    j = 0;\n    for (i=1; i <= to; i++) {\n        if (!d[w[i]]) {\n            w[++j] = w[i];\n        }\n    }\n    if (to == w_end) {\n        w_end = j;\n    } else {\n        for (uint32_t k=j+1; k <= to; k++) w[k] = 0;\n    }\n}\n\nvoid Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) {\n    \n    uint32_t *w = new uint32_t[N/4+5];\n    bool *d = new bool[N+1];\n    uint32_t w_end, length;\n    \n    \n    \n    \n    uint32_t w_end_max, p, imaxf;\n    \n    w_end = 0; w[0] = 1;\n    w_end_max = 0;\n    length = 2;\n    \n    nrPrimes = 1;\n    if (printPrimes) printf(\"%d\", 2);\n    p = 3;\n    \n    \n    while (p*p <= N) {\n        \n        nrPrimes++;\n        if (printPrimes) printf(\" %d\", p);\n        if (length < N) {\n            \n            Extend (w, w_end, length, std::min(p*length,N), d, w_end_max);\n        }\n        Delete(w, length, p, d, imaxf);\n        Compress(w, d, (length < N ? w_end : imaxf), w_end);\n        \n        p = w[1];\n        if (p == 0) break; \n        \n    }\n    if (length < N) {\n        \n        Extend (w, w_end, length, N, d, w_end_max);\n    }\n    \n    for (uint32_t i=1; i <= w_end; i++) {\n        if (w[i] == 0 || d[w[i]]) continue;\n        if (printPrimes) printf(\" %d\", w[i]);\n        nrPrimes++;\n    }\n    vBound = w_end_max+1;\n}\n\nint main (int argc, char *argw[]) {\n    bool error = false;\n    bool printPrimes = false;\n    uint32_t N, nrPrimes, vBound;\n    if (argc == 3) {\n        if (strcmp(argw[2], \"-p\") == 0) {\n            printPrimes = true;\n            argc--;\n        } else {\n            error = true;\n        }\n    }\n    if (argc == 2) {\n        N = atoi(argw[1]);\n        if (N < 2 || N > 1000000000) error = true;\n    } else {\n        error = true;\n    }\n    if (error) {\n        printf(\"call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \\n\", argw[0]);\n        exit(1);\n    }\n    int start_s = clock();\n    Sift(N, printPrimes, nrPrimes, vBound);\n    int stop_s=clock();\n    printf(\"\\n%d primes up to %lu found in %.3f ms using array w[%d]\\n\", nrPrimes,\n      (unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound);\n}\n", "Python": "\n\nfrom numpy import ndarray\nfrom math import isqrt\n\n\ndef pritchard(limit):\n    \n    members = ndarray(limit + 1, dtype=bool)\n    members.fill(False)\n    members[1] = True\n    steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2\n    primes = []\n    while prime <= rtlim:\n        if steplength < limit:\n            for w in range(1, len(members)):\n                if members[w]:\n                    n = w + steplength\n                    while n <= nlimit:\n                        members[n] = True\n                        n += steplength\n            steplength = nlimit\n\n        np = 5\n        mcpy = members.copy()\n        for w in range(1, len(members)):\n            if mcpy[w]:\n                if np == 5 and w > prime:\n                    np = w\n                n = prime * w\n                if n > nlimit:\n                    break  \n                members[n] = False  \n\n        if np < prime:\n            break\n        primes.append(prime)\n        prime = 3 if prime == 2 else np\n        nlimit = min(steplength * prime, limit)  \n\n    newprimes = [i for i in range(2, len(members)) if members[i]]\n    return sorted(primes + newprimes)\n\n\nprint(pritchard(150))\nprint('Number of primes up to 1,000,000:', len(pritchard(1000000)))\n"}
{"id": 48997, "name": "Monads_Writer monad", "C++": "#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct LoggingMonad\n{\n    double Value;\n    string Log;\n};\n\n\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n    auto result = f(monad.Value);\n    return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n\nauto MakeWriter = [](auto f, string message)\n{\n    return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n    \n    auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n    cout << result.Log << \"\\nResult: \" << result.Value;\n}\n", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n"}
{"id": 48998, "name": "Nested templated data", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n"}
{"id": 48999, "name": "Nested templated data", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n"}
{"id": 49000, "name": "Honaker primes", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <utility>\n\n#include <primesieve.hpp>\n\nuint64_t digit_sum(uint64_t n) {\n    uint64_t sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nclass honaker_prime_generator {\npublic:\n    std::pair<uint64_t, uint64_t> next();\n\nprivate:\n    primesieve::iterator pi_;\n    uint64_t index_ = 0;\n};\n\nstd::pair<uint64_t, uint64_t> honaker_prime_generator::next() {\n    for (;;) {\n        uint64_t prime = pi_.next_prime();\n        ++index_;\n        if (digit_sum(index_) == digit_sum(prime))\n            return std::make_pair(index_, prime);\n    }\n}\n\nstd::ostream& operator<<(std::ostream& os,\n                         const std::pair<uint64_t, uint64_t>& p) {\n    std::ostringstream str;\n    str << '(' << p.first << \", \" << p.second << ')';\n    return os << str.str();\n}\n\nint main() {\n    honaker_prime_generator hpg;\n    std::cout << \"First 50 Honaker primes (index, prime):\\n\";\n    int i = 1;\n    for (; i <= 50; ++i)\n        std::cout << std::setw(11) << hpg.next() << (i % 5 == 0 ? '\\n' : ' ');\n    for (; i < 10000; ++i)\n        hpg.next();\n    std::cout << \"\\nTen thousandth: \" << hpg.next() << '\\n';\n}\n", "Python": "\n\n\nfrom pyprimesieve import primes\n\n\ndef digitsum(num):\n    \n    return sum(int(c) for c in str(num))\n\n\ndef generate_honaker(limit=5_000_000):\n    \n    honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]\n    for hcount, (ppi, pri) in enumerate(honaker):\n        yield hcount + 1, ppi, pri\n\n\nprint('First 50 Honaker primes:')\nfor p in generate_honaker():\n    if p[0] < 51:\n        print(f'{str(p):16}', end='\\n' if p[0] % 5 == 0 else '')\n    elif p[0] == 10_000:\n        print(f'\\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.')\n        break\n"}
{"id": 49001, "name": "De Polignac numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(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 (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\nbool is_depolignac_number(int n) {\n    for (int p = 1; p < n; p <<= 1) {\n        if (is_prime(n - p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"First 50 de Polignac numbers:\\n\";\n    for (int n = 1, count = 0; count < 10000; n += 2) {\n        if (is_depolignac_number(n)) {\n            ++count;\n            if (count <= 50)\n                std::cout << std::setw(5) << n\n                          << (count % 10 == 0 ? '\\n' : ' ');\n            else if (count == 1000)\n                std::cout << \"\\nOne thousandth: \" << n << '\\n';\n            else if (count == 10000)\n                std::cout << \"\\nTen thousandth: \" << n << '\\n';\n        }\n    }\n}\n", "Python": "\n\nfrom sympy import isprime\nfrom math import log\nfrom numpy import ndarray\n\nmax_value = 1_000_000\n\nall_primes = [i for i in range(max_value + 1) if isprime(i)]\npowers_of_2 = [2**i for i in range(int(log(max_value, 2)))]\n\nallvalues = ndarray(max_value, dtype=bool)\nallvalues[:] = True\n\nfor i in all_primes:\n    for j in powers_of_2:\n        if i + j < max_value:\n            allvalues[i + j] = False\n        \ndePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]]\n\nprint('First fifty de Polignac numbers:')\nfor i, n in enumerate(dePolignac[:50]):\n    print(f'{n:5}', end='\\n' if (i + 1) % 10 == 0 else '')\n    \nprint(f'\\nOne thousandth: {dePolignac[999]:,}')\nprint(f'\\nTen thousandth: {dePolignac[9999]:,}')\n"}
{"id": 49002, "name": "Mastermind", "C++": "#include <iostream>\n#include <algorithm>\n#include <ctime>\n#include <string>\n#include <vector>\n\ntypedef std::vector<char> vecChar;\n\nclass master {\npublic:\n    master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {\n        std::string color = \"ABCDEFGHIJKLMNOPQRST\";\n\n        if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;\n        if( !rpt && clr_count < code_len ) clr_count = code_len; \n        if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;\n        if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;\n        \n        codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;\n\n        for( size_t s = 0; s < colorsCnt; s++ ) {\n            colors.append( 1, color.at( s ) );\n        }\n    }\n    void play() {\n        bool win = false;\n        combo = getCombo();\n\n        while( guessCnt ) {\n            showBoard();\n            if( checkInput( getInput() ) ) {\n                win = true;\n                break;\n            }\n            guessCnt--;\n        }\n        if( win ) {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"Very well done!\\nYou found the code: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        } else {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"I am sorry, you couldn't make it!\\nThe code was: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        }\n    }\nprivate:\n    void showBoard() {\n        vecChar::iterator y;\n        for( int x = 0; x < guesses.size(); x++ ) {\n            std::cout << \"\\n--------------------------------\\n\";\n            std::cout << x + 1 << \": \";\n            for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            std::cout << \" :  \";\n            for( y = results[x].begin(); y != results[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            int z = codeLen - results[x].size();\n            if( z > 0 ) {\n                for( int x = 0; x < z; x++ ) std::cout << \"- \";\n            }\n        }\n        std::cout << \"\\n\\n\";\n    }\n    std::string getInput() {\n        std::string a;\n        while( true ) {\n            std::cout << \"Enter your guess (\" << colors << \"): \";\n            a = \"\"; std::cin >> a;\n            std::transform( a.begin(), a.end(), a.begin(), ::toupper );\n            if( a.length() > codeLen ) a.erase( codeLen );\n            bool r = true;\n            for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n                if( colors.find( *x ) == std::string::npos ) {\n                    r = false;\n                    break;\n                }\n            }\n            if( r ) break;\n        }\n        return a;\n    }\n    bool checkInput( std::string a ) {\n        vecChar g;\n        for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n            g.push_back( *x );\n        }\n        guesses.push_back( g );\n        \n        int black = 0, white = 0;\n        std::vector<bool> gmatch( codeLen, false );\n        std::vector<bool> cmatch( codeLen, false );\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if( a.at( i ) == combo.at( i ) ) {\n                gmatch[i] = true;\n                cmatch[i] = true;\n                black++;\n            }\n        }\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if (gmatch[i]) continue;\n            for( int j = 0; j < codeLen; j++ ) {\n                if (i == j || cmatch[j]) continue;\n                if( a.at( i ) == combo.at( j ) ) {\n                    cmatch[j] = true;\n                    white++;\n                    break;\n                }\n            }\n        }\n       \n        vecChar r;\n        for( int b = 0; b < black; b++ ) r.push_back( 'X' );\n        for( int w = 0; w < white; w++ ) r.push_back( 'O' );\n        results.push_back( r );\n\n        return ( black == codeLen );\n    }\n    std::string getCombo() {\n        std::string c, clr = colors;\n        int l, z;\n\n        for( size_t s = 0; s < codeLen; s++ ) {\n            z = rand() % ( int )clr.length();\n            c.append( 1, clr[z] );\n            if( !repeatClr ) clr.erase( z, 1 );\n        }\n        return c;\n    }\n\n    size_t codeLen, colorsCnt, guessCnt;\n    bool repeatClr;\n    std::vector<vecChar> guesses, results;\n    std::string colors, combo;\n};\n\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    master m( 4, 8, 12, false );\n    m.play();\n    return 0;\n}\n", "Python": "import random\n\n\ndef encode(correct, guess):\n    output_arr = [''] * len(correct)\n\n    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):\n        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'\n\n    return ''.join(output_arr)\n\n\ndef safe_int_input(prompt, min_val, max_val):\n    while True:\n        user_input = input(prompt)\n\n        try:\n            user_input = int(user_input)\n        except ValueError:\n            continue\n\n        if min_val <= user_input <= max_val:\n            return user_input\n\n\ndef play_game():\n    print(\"Welcome to Mastermind.\")\n    print(\"You will need to guess a random code.\")\n    print(\"For each guess, you will receive a hint.\")\n    print(\"In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.\")\n    print()\n\n    number_of_letters = safe_int_input(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n    code_length = safe_int_input(\"Select a length for the code (4-10): \", 4, 10)\n\n    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]\n    code = ''.join(random.choices(letters, k=code_length))\n    guesses = []\n\n    while True:\n        print()\n        guess = input(f\"Enter a guess of length {code_length} ({letters}): \").upper().strip()\n\n        if len(guess) != code_length or any([char not in letters for char in guess]):\n            continue\n        elif guess == code:\n            print(f\"\\nYour guess {guess} was correct!\")\n            break\n        else:\n            guesses.append(f\"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}\")\n\n        for i_guess in guesses:\n            print(\"------------------------------------\")\n            print(i_guess)\n        print(\"------------------------------------\")\n\n\nif __name__ == '__main__':\n    play_game()\n"}
{"id": 49003, "name": "Zsigmondy numbers", "C++": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nstd::vector<uint64_t> divisors(uint64_t n) {\n    std::vector<uint64_t> result{1};\n    uint64_t power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        result.push_back(power);\n    for (uint64_t p = 3; p * p <= n; p += 2) {\n        size_t size = result.size();\n        for (power = p; n % p == 0; power *= p, n /= p)\n            for (size_t i = 0; i != size; ++i)\n                result.push_back(power * result[i]);\n    }\n    if (n > 1) {\n        size_t size = result.size();\n        for (size_t i = 0; i != size; ++i)\n            result.push_back(n * result[i]);\n    }\n    sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t ipow(uint64_t base, uint64_t exp) {\n    if (exp == 0)\n        return 1;\n    if ((exp & 1) == 0)\n        return ipow(base * base, exp >> 1);\n    return base * ipow(base * base, (exp - 1) >> 1);\n}\n\nuint64_t zsigmondy(uint64_t n, uint64_t a, uint64_t b) {\n    auto p = ipow(a, n) - ipow(b, n);\n    auto d = divisors(p);\n    if (d.size() == 2)\n        return p;\n    std::vector<uint64_t> dms(n - 1);\n    for (uint64_t m = 1; m < n; ++m)\n        dms[m - 1] = ipow(a, m) - ipow(b, m);\n    for (auto i = d.rbegin(); i != d.rend(); ++i) {\n        uint64_t z = *i;\n        if (all_of(dms.begin(), dms.end(),\n                   [z](uint64_t x) { return std::gcd(x, z) == 1; }))\n            return z;\n    }\n    return 1;\n}\n\nvoid test(uint64_t a, uint64_t b) {\n    std::cout << \"Zsigmondy(n, \" << a << \", \" << b << \"):\\n\";\n    for (uint64_t n = 1; n <= 20; ++n) {\n        std::cout << zsigmondy(n, a, b) << ' ';\n    }\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    test(2, 1);\n    test(3, 1);\n    test(4, 1);\n    test(5, 1);\n    test(6, 1);\n    test(7, 1);\n    test(3, 2);\n    test(5, 3);\n    test(7, 3);\n    test(7, 5);\n}\n", "Python": "\n\nfrom math import gcd\nfrom sympy import divisors\n\n\ndef zsig(num, aint, bint):\n    \n    assert aint > bint\n    dexpms = [aint**i - bint**i for i in range(1, num)]\n    dexpn = aint**num - bint**num\n    return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)])\n\n\ntests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1),\n         (7, 1), (3, 2), (5, 3), (7, 3), (7, 5)]\nfor (a, b) in tests:\n    print(f'\\nZsigmondy(n, {a}, {b}):', ', '.join(\n        [str(zsig(n, a, b)) for n in range(1, 21)]))\n"}
{"id": 49004, "name": "Sorensen–Dice coefficient", "C++": "#include <algorithm>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <set>\n#include <sstream>\n#include <string>\n#include <vector>\n\nusing bigram = std::pair<char, char>;\n\nstd::multiset<bigram> bigrams(const std::string& phrase) {\n    std::multiset<bigram> result;\n    std::istringstream is(phrase);\n    std::string word;\n    while (is >> word) {\n        for (char& ch : word) {\n            ch = std::tolower(static_cast<unsigned char>(ch));\n        }\n        size_t length = word.size();\n        if (length == 1) {\n            result.emplace(word[0], '\\0');\n        } else {\n            for (size_t i = 0; i + 1 < length; ++i) {\n                result.emplace(word[i], word[i + 1]);\n            }\n        }\n    }\n    return result;\n}\n\ndouble sorensen(const std::string& s1, const std::string& s2) {\n    auto a = bigrams(s1);\n    auto b = bigrams(s2);\n    std::multiset<bigram> c;\n    std::set_intersection(a.begin(), a.end(), b.begin(), b.end(),\n                          std::inserter(c, c.begin()));\n    return (2.0 * c.size()) / (a.size() + b.size());\n}\n\nint main() {\n    std::vector<std::string> tasks;\n    std::ifstream is(\"tasks.txt\");\n    if (!is) {\n        std::cerr << \"Cannot open tasks file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string task;\n    while (getline(is, task)) {\n        tasks.push_back(task);\n    }\n    const size_t tc = tasks.size();\n    const std::string tests[] = {\"Primordial primes\",\n                                 \"Sunkist-Giuliani formula\",\n                                 \"Sieve of Euripides\", \"Chowder numbers\"};\n    std::vector<std::pair<double, size_t>> sdi(tc);\n    std::cout << std::fixed;\n    for (const std::string& test : tests) {\n        for (size_t i = 0; i != tc; ++i) {\n            sdi[i] = std::make_pair(sorensen(tasks[i], test), i);\n        }\n        std::partial_sort(sdi.begin(), sdi.begin() + 5, sdi.end(),\n                          [](const std::pair<double, size_t>& a,\n                             const std::pair<double, size_t>& b) {\n                              return a.first > b.first;\n                          });\n        std::cout << test << \" >\\n\";\n        for (size_t i = 0; i < 5 && i < tc; ++i) {\n            std::cout << \"  \" << sdi[i].first << ' ' << tasks[sdi[i].second]\n                      << '\\n';\n        }\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "\n\nfrom multiset import Multiset\n\n\ndef tokenizetext(txt):\n    \n    arr = []\n    for wrd in txt.lower().split(' '):\n        arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2]\n                for i in range(len(wrd)-1)])\n    return Multiset(arr)\n\n\ndef sorenson_dice(text1, text2):\n    \n    bc1, bc2 = tokenizetext(text1), tokenizetext(text2)\n    return 2 * len(bc1 & bc2) / (len(bc1) + len(bc2))\n\n\nwith open('tasklist_sorenson.txt', 'r') as fd:\n    alltasks = fd.read().split('\\n')\n\nfor testtext in ['Primordial primes', 'Sunkist-Giuliani formula',\n                 'Sieve of Euripides', 'Chowder numbers']:\n    taskvalues = sorted([(sorenson_dice(testtext, t), t)\n                        for t in alltasks], reverse=True)\n    print(f'\\n{testtext}:')\n    for (val, task) in taskvalues[:5]:\n        print(f'  {val:.6f}  {task}')\n"}
{"id": 49005, "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": 49006, "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", "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": 49007, "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", "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": 49008, "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", "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": 49009, "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", "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": 49010, "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", "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": 49011, "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", "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": 49012, "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", "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": 49013, "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", "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": 49014, "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", "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": 49015, "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", "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": 49016, "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", "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": 49017, "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", "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": 49018, "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", "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": 49019, "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", "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": 49020, "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", "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": 49021, "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", "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": 49022, "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", "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": 49023, "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", "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": 49024, "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", "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": 49025, "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", "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": 49026, "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", "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": 49027, "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", "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": 49028, "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", "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": 49029, "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", "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": 49030, "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", "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": 49031, "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", "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": 49032, "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", "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": 49033, "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", "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": 49034, "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", "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": 49035, "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", "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": 49036, "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", "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": 49037, "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", "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": 49038, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 49039, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 49040, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 49041, "name": "Checkpoint synchronization", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n"}
{"id": 49042, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 49043, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 49044, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 49045, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 49046, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 49047, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 49048, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 49049, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 49050, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 49051, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 49052, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 49053, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 49054, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 49055, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 49056, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 49057, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 49058, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 49059, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 49060, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 49061, "name": "Sorting algorithms_Radix sort", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n"}
{"id": 49062, "name": "Sorting algorithms_Radix sort", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n"}
{"id": 49063, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 49064, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 49065, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 49066, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 49067, "name": "Singleton", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n"}
{"id": 49068, "name": "Safe addition", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 49069, "name": "Safe addition", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 49070, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 49071, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n"}
{"id": 49072, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 49073, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 49074, "name": "Non-continuous subsequences", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 49075, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 49076, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 49077, "name": "Roots of unity", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n"}
{"id": 49078, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 49079, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n"}
{"id": 49080, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 49081, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 49082, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "C#": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 49083, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "C#": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 49084, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 49085, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 49086, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 49087, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 49088, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n"}
{"id": 49089, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 49090, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 49091, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 49092, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 49093, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 49094, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 49095, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 49096, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 49097, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 49098, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n"}
{"id": 49099, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 49100, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 49101, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 49102, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 49103, "name": "Water collected between towers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 49104, "name": "Descending primes", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n"}
{"id": 49105, "name": "Sum and product puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n"}
{"id": 49106, "name": "Sum and product puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n"}
{"id": 49107, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 49108, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 49109, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 49110, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 49111, "name": "Documentation", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n"}
{"id": 49112, "name": "Problem of Apollonius", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n"}
{"id": 49113, "name": "Longest common suffix", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n"}
{"id": 49114, "name": "Chat server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49115, "name": "Chat server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49116, "name": "FASTA format", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n"}
{"id": 49117, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 49118, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 49119, "name": "Terminal control_Dimensions", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n"}
{"id": 49120, "name": "Terminal control_Dimensions", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n"}
{"id": 49121, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 49122, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "C#": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 49123, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "C#": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 49124, "name": "Special factorials", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "C#": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 49125, "name": "GUI_Maximum window dimensions", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n"}
{"id": 49126, "name": "GUI_Maximum window dimensions", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n"}
{"id": 49127, "name": "Getting the number of decimals", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "C#": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 49128, "name": "Getting the number of decimals", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "C#": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 49129, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 49130, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 49131, "name": "Knapsack problem_Unbounded", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n"}
{"id": 49132, "name": "Print debugging statement", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n", "C#": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n"}
{"id": 49133, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 49134, "name": "Type detection", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n", "C#": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 49135, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n"}
{"id": 49136, "name": "Terminal control_Cursor movement", "C": "#include<conio.h>\n#include<dos.h>\n\nchar *strings[] = {\"The cursor will move one position to the left\", \n  \t\t   \"The cursor will move one position to the right\",\n \t\t   \"The cursor will move vetically up one line\", \n \t\t   \"The cursor will move vertically down one line\", \n \t\t   \"The cursor will move to the beginning of the line\", \n \t\t   \"The cursor will move to the end of the line\", \n \t\t   \"The cursor will move to the top left corner of the screen\", \n \t\t   \"The cursor will move to the bottom right corner of the screen\"};\n \t\t             \nint main()\n{\n\tint i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\t\n\tclrscr();\n\tcprintf(\"This is a demonstration of cursor control using gotoxy(). Press any key to continue.\");\n\tgetch();\n\t\n\tfor(i=0;i<8;i++)\n\t{\n\t\tclrscr();\n\t\tgotoxy(5,MAXROW/2);\n\t\t\n\t\tcprintf(\"%s\",strings[i]);\n\t\tgetch();\n\t\t\n\t\tswitch(i){\n\t\t\tcase 0:gotoxy(wherex()-1,wherey());\n\t\t\tbreak;\n\t\t\tcase 1:gotoxy(wherex()+1,wherey());\n\t\t\tbreak;\n\t\t\tcase 2:gotoxy(wherex(),wherey()-1);\n\t\t\tbreak;\n\t\t\tcase 3:gotoxy(wherex(),wherey()+1);\n\t\t\tbreak;\n\t\t\tcase 4:for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()-1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 5:gotoxy(wherex()-strlen(strings[i]),wherey());\n\t\t\t       for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()+1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 6:while(wherex()!=1)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()-1,wherey());\n\t\t\t\t     delay(100);\n\t\t               }\n\t\t\t       while(wherey()!=1)\n\t\t\t       {\n\t\t\t             gotoxy(wherex(),wherey()-1);\n\t\t\t             delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 7:while(wherex()!=MAXCOL)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()+1,wherey());\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\t       while(wherey()!=MAXROW)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex(),wherey()+1);\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\t};\n\t\t\tgetch();\n\t}\n\t\n\tclrscr();\n\tcprintf(\"End of demonstration.\");\n\tgetch();\n\treturn 0;\n}\n", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n"}
{"id": 49137, "name": "Words from neighbour ones", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n", "C#": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 49138, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 49139, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 49140, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 49141, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 49142, "name": "Unix_ls", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 49143, "name": "UTF-8 encode and decode", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n"}
{"id": 49144, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n"}
{"id": 49145, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n"}
{"id": 49146, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n"}
{"id": 49147, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n"}
{"id": 49148, "name": "Peaceful chess queen armies", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49149, "name": "Numbers with same digit set in base 10 and base 16", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n"}
{"id": 49150, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 49151, "name": "Sum of first n cubes", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n", "C#": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 49152, "name": "Sum of first n cubes", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n", "C#": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 49153, "name": "Execute a system command", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 49154, "name": "Longest increasing subsequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 49155, "name": "Scope modifiers", "C": "int a;          \nstatic int p;   \n\nextern float v; \n\n\nint code(int arg)\n{\n  int myp;        \n                  \n                  \n  static int myc; \n                  \n                  \n                  \n                  \n}\n\n\nstatic void code2(void)\n{\n  v = v * 1.02;    \n  \n}\n", "C#": "public \nprotected \ninternal \nprotected internal \nprivate \n\nprivate protected \n\n\n\n\n\n\n\n\n\n\n\n"}
{"id": 49156, "name": "GUI component interaction", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n"}
{"id": 49157, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 49158, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 49159, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 49160, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 49161, "name": "Numeric separator syntax", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n", "C#": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n"}
{"id": 49162, "name": "Numeric separator syntax", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n", "C#": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n"}
{"id": 49163, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 49164, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 49165, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 49166, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 49167, "name": "Sunflower fractal", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "C#": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 49168, "name": "The sieve of Sundaram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\nint main(void) {\n    int nprimes =  1000000;\n    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  \n      \n      \n    int i, j, m, k; int *a;\n    k = (nmax-2)/2; \n    a = (int *)calloc(k + 1, sizeof(int));\n    for(i = 0; i <= k; i++)a[i] = 2*i+1; \n    for (i = 1; (i+1)*i*2 <= k; i++)\n        for (j = i; j <= (k-i)/(2*i+1); j++) {\n            m = i + j + 2*i*j;\n            if(a[m]) a[m] = 0;\n            }            \n        \n    for (i = 1, j = 0; i <= k; i++) \n       if (a[i]) {\n           if(j%10 == 0 && j <= 100)printf(\"\\n\");\n           j++; \n           if(j <= 100)printf(\"%3d \", a[i]);\n           else if(j == nprimes){\n               printf(\"\\n%d th prime is %d\\n\",j,a[i]);\n               break;\n               }\n           }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n"}
{"id": 49169, "name": "Active Directory_Connect", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n"}
{"id": 49170, "name": "Active Directory_Connect", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n"}
{"id": 49171, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 49172, "name": "Steady squares", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n", "C#": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n"}
{"id": 49173, "name": "Rosetta Code_Find unimplemented tasks", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n"}
{"id": 49174, "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": 49175, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 49176, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 49177, "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", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 49178, "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", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\n"}
{"id": 49179, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 49180, "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", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\n"}
{"id": 49181, "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", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n"}
{"id": 49182, "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", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n"}
{"id": 49183, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 49184, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 49185, "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", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n"}
{"id": 49186, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 49187, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 49188, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 49189, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 49190, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n"}
{"id": 49191, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 49192, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 49193, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 49194, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 49195, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 49196, "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", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 49197, "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", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 49198, "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", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 49199, "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", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 49200, "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", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 49201, "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", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 49202, "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", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49203, "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", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 49204, "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", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n"}
{"id": 49205, "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", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 49206, "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", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 49207, "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", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 49208, "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", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 49209, "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", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 49210, "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", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 49211, "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", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 49212, "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", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 49213, "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", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 49214, "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", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 49215, "name": "Stack", "Go": "var intStack []int\n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 49216, "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", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 49217, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 49218, "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", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n"}
{"id": 49219, "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", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n"}
{"id": 49220, "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", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 49221, "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", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 49222, "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", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49223, "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", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 49224, "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", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 49225, "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", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n"}
{"id": 49226, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n"}
{"id": 49227, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 49228, "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", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 49229, "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", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 49230, "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", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 49231, "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", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 49232, "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", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 49233, "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", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 49234, "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", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49235, "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", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49236, "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", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 49237, "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", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 49238, "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", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 49239, "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", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 49240, "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", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 49241, "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", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 49242, "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", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 49243, "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", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 49244, "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", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 49245, "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", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 49246, "name": "Arithmetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 49247, "name": "Arithmetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 49248, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 49249, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 49250, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 49251, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 49252, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 49253, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 49254, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 49255, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 49256, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 49257, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 49258, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 49259, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49260, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49261, "name": "Jaro similarity", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n"}
{"id": 49262, "name": "Fairshare between two and more", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 49263, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 49264, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 49265, "name": "Prime triangle", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n"}
{"id": 49266, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n"}
{"id": 49267, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 49268, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 49269, "name": "Biorhythms", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n"}
{"id": 49270, "name": "Biorhythms", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n"}
{"id": 49271, "name": "Table creation_Postal addresses", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n"}
{"id": 49272, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "VB": "\n"}
{"id": 49273, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "VB": "\n"}
{"id": 49274, "name": "Stern-Brocot sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n"}
{"id": 49275, "name": "Soundex", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n"}
{"id": 49276, "name": "Chat server", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49277, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 49278, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 49279, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 49280, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 49281, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 49282, "name": "Terminal control_Dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n"}
{"id": 49283, "name": "Terminal control_Dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n"}
{"id": 49284, "name": "Finite state machine", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n"}
{"id": 49285, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 49286, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 49287, "name": "Sierpinski pentagon", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n"}
{"id": 49288, "name": "Rep-string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n"}
{"id": 49289, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n"}
{"id": 49290, "name": "GUI_Maximum window dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n"}
{"id": 49291, "name": "GUI_Maximum window dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n"}
{"id": 49292, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 49293, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 49294, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 49295, "name": "Parse an IP Address", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n"}
{"id": 49296, "name": "Knapsack problem_Unbounded", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n"}
{"id": 49297, "name": "Textonyms", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n"}
{"id": 49298, "name": "Range extraction", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n"}
{"id": 49299, "name": "Type detection", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n"}
{"id": 49300, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n"}
{"id": 49301, "name": "Zhang-Suen thinning algorithm", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n"}
{"id": 49302, "name": "Variable declaration reset", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n"}
{"id": 49303, "name": "Start from a main routine", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n", "VB": "SUB Main()\n  \nEND\n"}
{"id": 49304, "name": "Start from a main routine", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n", "VB": "SUB Main()\n  \nEND\n"}
{"id": 49305, "name": "Start from a main routine", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n", "VB": "SUB Main()\n  \nEND\n"}
{"id": 49306, "name": "Koch curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n"}
{"id": 49307, "name": "Draw a pixel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n"}
{"id": 49308, "name": "Words from neighbour ones", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n"}
{"id": 49309, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 49310, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 49311, "name": "UTF-8 encode and decode", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n"}
{"id": 49312, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n"}
{"id": 49313, "name": "Calendar - for _REAL_ programmers", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n", "VB": "OPTION COMPARE BINARY\nOPTION EXPLICIT ON\nOPTION INFER ON\nOPTION STRICT ON\n\nIMPORTS SYSTEM.GLOBALIZATION\nIMPORTS SYSTEM.TEXT\nIMPORTS SYSTEM.RUNTIME.INTEROPSERVICES\nIMPORTS SYSTEM.RUNTIME.COMPILERSERVICES\n\nMODULE ARGHELPER\n    READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()\n\n    DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN\n\n    SUB INITIALIZEARGUMENTS(ARGS AS STRING())\n        FOR EACH ITEM IN ARGS\n            ITEM = ITEM.TOUPPERINVARIANT()\n\n            IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> \"\"\"\"C THEN\n                DIM COLONPOS = ITEM.INDEXOF(\":\"C, STRINGCOMPARISON.ORDINAL)\n\n                IF COLONPOS <> -1 THEN\n                    \n                    _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))\n                END IF\n            END IF\n        NEXT\n    END SUB\n\n    SUB FROMARGUMENT(OF T)(\n            KEY AS STRING,\n            <OUT> BYREF VAR AS T,\n            GETDEFAULT AS FUNC(OF T),\n            TRYPARSE AS TRYPARSE(OF STRING, T),\n            OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)\n\n        DIM VALUE AS STRING = NOTHING\n        IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN\n            IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN\n                CONSOLE.WRITELINE($\"INVALID VALUE FOR {KEY}: {VALUE}\")\n                ENVIRONMENT.EXIT(-1)\n            END IF\n        ELSE\n            VAR = GETDEFAULT()\n        END IF\n    END SUB\nEND MODULE\n\nMODULE PROGRAM\n    SUB MAIN(ARGS AS STRING())\n        DIM DT AS DATE\n        DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER\n        DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN\n\n        INITIALIZEARGUMENTS(ARGS)\n        FROMARGUMENT(\"DATE\", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)\n        FROMARGUMENT(\"COLS\", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)\n        FROMARGUMENT(\"ROWS\", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)\n        FROMARGUMENT(\"MS/ROW\", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \\ 20)\n        FROMARGUMENT(\"VSTRETCH\", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"HSTRETCH\", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"WSIZE\", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n\n        \n        IF RESIZEWINDOW THEN\n            CONSOLE.WINDOWWIDTH = COLUMNS + 1\n            CONSOLE.WINDOWHEIGHT = ROWS\n        END IF\n\n        IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \\ 22, 1)\n\n        FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)\n            CONSOLE.WRITE(ROW)\n        NEXT\n    END SUB\n\n    ITERATOR FUNCTION GETCALENDARROWS(\n            DT AS DATE,\n            WIDTH AS INTEGER,\n            HEIGHT AS INTEGER,\n            MONTHSPERROW AS INTEGER,\n            VERTSTRETCH AS BOOLEAN,\n            HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n\n        DIM YEAR = DT.YEAR\n        DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))\n        \n        DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3\n\n        YIELD \"[SNOOPY]\".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD ENVIRONMENT.NEWLINE\n\n        DIM MONTH = 0\n        DO WHILE MONTH < 12\n            DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)\n\n            DIM CELLWIDTH = WIDTH \\ MONTHSPERROW\n            DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \\ 20)\n\n            DIM CELLHEIGHT = MONTHGRIDHEIGHT \\ CALENDARROWCOUNT\n            DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \\ 20\n\n            \n            DIM GETMONTHFROM =\n                FUNCTION(M AS INTEGER) BUILDMONTH(\n                    DT:=NEW DATE(DT.YEAR, M, 1),\n                    WIDTH:=CELLCONTENTWIDTH,\n                    HEIGHT:=CELLCONTENTHEIGHT,\n                    VERTSTRETCH:=VERTSTRETCH,\n                    HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))\n\n            \n            DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =\n                ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)\n\n            DIM CALENDARROW AS IENUMERABLE(OF STRING) =\n                INTERLEAVED(\n                    MONTHSTHISROW,\n                    USEINNERSEPARATOR:=FALSE,\n                    USEOUTERSEPARATOR:=TRUE,\n                    OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)\n\n            DIM EN = CALENDARROW.GETENUMERATOR()\n            DIM HASNEXT = EN.MOVENEXT()\n            DO WHILE HASNEXT\n\n                DIM CURRENT AS STRING = EN.CURRENT\n\n                \n                \n                HASNEXT = EN.MOVENEXT()\n                YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)\n            LOOP\n\n            MONTH += MONTHSPERROW\n        LOOP\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION INTERLEAVED(OF T)(\n            SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),\n            OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL INNERSEPARATOR AS T = NOTHING,\n            OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL OUTERSEPARATOR AS T = NOTHING,\n            OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)\n        DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING\n\n        TRY\n            SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()\n            DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH\n            DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN\n\n            DIM ANYPREVITERS AS BOOLEAN = FALSE\n            DO\n                \n                DIM FIRSTACTIVE = -1, LASTACTIVE = -1\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()\n                    IF ENUMERATORSTATES(I) THEN\n                        IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I\n                        LASTACTIVE = I\n                    END IF\n                NEXT\n\n                \n                \n                DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)\n                IF NOT THISITERHASRESULTS THEN EXIT DO\n\n                \n                IF ANYPREVITERS THEN\n                    IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR\n                ELSE\n                    ANYPREVITERS = TRUE\n                END IF\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    IF ENUMERATORSTATES(I) THEN\n                        \n                        IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR\n                        YIELD SOURCEENUMERATORS(I).CURRENT\n                    END IF\n                NEXT\n            LOOP\n\n        FINALLY\n            IF SOURCEENUMERATORS ISNOT NOTHING THEN\n                FOR EACH EN IN SOURCEENUMERATORS\n                    EN.DISPOSE()\n                NEXT\n            END IF\n        END TRY\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n        CONST DAY_WDT = 2 \n        CONST ALLDAYS_WDT = DAY_WDT * 7 \n\n        \n        DT = NEW DATE(DT.YEAR, DT.MONTH, 1)\n\n        \n        DIM DAYSEP AS NEW STRING(\" \"C, MATH.MIN((WIDTH - ALLDAYS_WDT) \\ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))\n        \n        DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \\ 7)\n\n        \n        DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6\n\n        \n        DIM LEFTPAD AS NEW STRING(\" \"C, (WIDTH - BLOCKWIDTH) \\ 2)\n        \n        DIM FULLPAD AS NEW STRING(\" \"C, WIDTH)\n\n        \n        DIM SB AS NEW STRINGBUILDER(LEFTPAD)\n        DIM NUMLINES = 0\n\n        \n        \n        \n        DIM ENDLINE =\n         FUNCTION() AS IENUMERABLE(OF STRING)\n             DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)\n             SB.CLEAR()\n             SB.APPEND(LEFTPAD)\n\n             \n             RETURN IF(NUMLINES >= HEIGHT,\n                 ENUMERABLE.EMPTY(OF STRING)(),\n                 ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)\n                     YIELD FINISHEDLINE\n                     NUMLINES += 1\n\n                     FOR I = 1 TO VERTBLANKCOUNT\n                         IF NUMLINES >= HEIGHT THEN RETURN\n                         YIELD FULLPAD\n                         NUMLINES += 1\n                     NEXT\n                 END FUNCTION())\n         END FUNCTION\n\n        \n        SB.APPEND(PADCENTER(DT.TOSTRING(\"MMMM\", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())\n        SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM STARTWKDY = CINT(DT.DAYOFWEEK)\n\n        \n        DIM FIRSTPAD AS NEW STRING(\" \"C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)\n        SB.APPEND(FIRSTPAD)\n\n        DIM D = DT\n        DO WHILE D.MONTH = DT.MONTH\n            SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $\"{{0,{DAY_WDT}}}\", D.DAY)\n\n            \n            IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN\n                FOR EACH L IN ENDLINE()\n                    YIELD L\n                NEXT\n            ELSE\n                SB.APPEND(DAYSEP)\n            END IF\n\n            D = D.ADDDAYS(1)\n        LOOP\n\n        \n        DIM NEXTLINES AS IENUMERABLE(OF STRING)\n        DO\n            NEXTLINES = ENDLINE()\n            FOR EACH L IN NEXTLINES\n                YIELD L\n            NEXT\n        LOOP WHILE NEXTLINES.ANY()\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    <EXTENSION()>\n    PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = \" \"C) AS STRING\n        RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \\ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)\n    END FUNCTION\nEND MODULE\n"}
{"id": 49314, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "VB": "Do\n   Debug.Print \"SPAM\"\nLoop\n"}
{"id": 49315, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 49316, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n"}
{"id": 49317, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n"}
{"id": 49318, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n"}
{"id": 49319, "name": "Death Star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n"}
{"id": 49320, "name": "Verify distribution uniformity_Chi-squared test", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 49321, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49322, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 49323, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 49324, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 49325, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n"}
{"id": 49326, "name": "Spelling of ordinal numbers", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n"}
{"id": 49327, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 49328, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 49329, "name": "Addition chains", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 49330, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n"}
{"id": 49331, "name": "Sparkline in unicode", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 49332, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 49333, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n"}
{"id": 49334, "name": "Own digits power sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n    fmt.Println(\"Own digits power sums for N = 3 to 9 inclusive:\")\n    for n := 3; n < 10; n++ {\n        for d := 2; d < 10; d++ {\n            powers[d] *= d\n        }\n        i := int(math.Pow(10, float64(n-1)))\n        max := i * 10\n        lastDigit := 0\n        sum := 0\n        var digits []int\n        for i < max {\n            if lastDigit == 0 {\n                digits = rcu.Digits(i, 10)\n                sum = 0\n                for _, d := range digits {\n                    sum += powers[d]\n                }\n            } else if lastDigit == 1 {\n                sum++\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1]\n            }\n            if sum == i {\n                fmt.Println(i)\n                if lastDigit == 0 {\n                    fmt.Println(i + 1)\n                }\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if sum > i {\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if lastDigit < 9 {\n                i++\n                lastDigit++\n            } else {\n                i++\n                lastDigit = 0\n            }\n        }\n    }\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\n\n\n\nModule OwnDigitsPowerSum\n\n    Public Sub Main\n\n        \n        Dim used(9) As Integer\n        Dim check(9) As Integer\n        Dim power(9, 9) As Long\n        For i As Integer = 0 To 9\n            check(i) = 0\n        Next i\n        For i As Integer = 1 To 9\n            power(1,  i) = i\n        Next i\n        For j As Integer =  2 To 9\n            For i As Integer = 1 To 9\n                power(j, i) = power(j - 1, i) * i\n            Next i\n        Next j\n        \n        \n        Dim lowestDigit(9) As Integer\n        lowestDigit(1) = -1\n        lowestDigit(2) = -1\n        Dim p10 As Long = 100\n        For i As Integer = 3 To 9\n            For p As Integer = 2 To 9\n                Dim np As Long = power(i, p) * i\n                If Not ( np < p10) Then Exit For\n                lowestDigit(i) = p\n            Next p\n            p10 *= 10\n        Next i\n        \n        Dim maxZeros(9, 9) As Integer\n        For i As Integer = 1 To 9\n            For j As Integer = 1 To 9\n                maxZeros(i, j) = 0\n            Next j\n        Next i\n        p10 = 1000\n        For w As Integer = 3 To 9\n            For d As Integer = lowestDigit(w) To 9\n                Dim nz As Integer = 9\n                Do\n                    If nz < 0 Then\n                        Exit Do\n                    Else\n                        Dim np As Long = power(w, d) * nz\n                        IF Not ( np > p10) Then Exit Do\n                    End If\n                    nz -= 1\n                Loop\n                maxZeros(w, d) = If(nz > w, 0, w - nz)\n            Next d\n            p10 *= 10\n        Next w\n        \n        \n        Dim numbers(100) As Long     \n        Dim nCount As Integer = 0    \n        Dim tryCount As Integer = 0  \n        Dim digits(9) As Integer     \n        For d As Integer = 1 To 9\n             digits(d) = 9\n        Next d\n        For d As Integer = 0 To 8\n            used(d) = 0\n        Next d\n        used(9) = 9\n        Dim width As Integer = 9     \n        Dim last As Integer = width  \n        p10 = 100000000              \n        Do While width > 2\n            tryCount += 1\n            Dim dps As Long = 0      \n            check(0) = used(0)\n            For i As Integer = 1 To 9\n                check(i) = used(i)\n                If used(i) <> 0 Then\n                    dps += used(i) * power(width, i)\n                End If\n            Next i\n            \n            Dim n As Long = dps\n            Do\n                check(CInt(n Mod 10)) -= 1 \n                n \\= 10\n            Loop Until n <= 0\n            Dim reduceWidth As Boolean = dps <= p10\n            If Not reduceWidth Then\n                \n                \n                \n                Dim zCount As Integer = 0\n                For i As Integer = 0 To 9\n                    If check(i) <> 0 Then Exit For\n                    zCount+= 1\n                Next i\n                If zCount = 10 Then\n                    nCount += 1\n                    numbers(nCount) = dps\n                End If\n                \n                used(digits(last)) -= 1\n                digits(last) -= 1\n                If digits(last) = 0 Then\n                    \n                    If used(0) >= maxZeros(width, digits(1)) Then\n                        \n                        digits(last) = -1\n                    End If\n                End If\n                If digits(last) >= 0 Then\n                    \n                    used(digits(last)) += 1\n                Else\n                    \n                    Dim prev As Integer = last\n                    Do\n                        prev -= 1\n                        If prev < 1 Then\n                            Exit Do\n                        Else\n                            used(digits(prev)) -= 1\n                            digits(prev) -= 1\n                            IF digits(prev) >= 0 Then Exit Do\n                        End If\n                    Loop\n                    If prev > 0 Then\n                        \n                        If prev = 1 Then\n                            If digits(1) <= lowestDigit(width) Then\n                               \n                               prev = 0\n                            End If\n                        End If\n                        If prev <> 0 Then\n                           \n                            used(digits(prev)) += 1\n                            For i As Integer = prev + 1 To width\n                                digits(i) = digits(prev)\n                                used(digits(prev)) += 1\n                            Next i\n                        End If\n                    End If\n                    If prev <= 0 Then\n                        \n                        reduceWidth = True\n                    End If\n                End If\n            End If\n            If reduceWidth Then\n                \n                last -= 1\n                width = last\n                If last > 0 Then\n                    \n                    For d As Integer = 1 To last\n                        digits(d) = 9\n                    Next d\n                    For d As Integer = last + 1 To 9\n                        digits(d) = -1\n                    Next d\n                    For d As Integer = 0 To 8\n                        used(d) = 0\n                    Next d\n                    used(9) = last\n                    p10 \\= 10\n                End If\n            End If\n        Loop\n        \n        Console.Out.WriteLine(\"Own digits power sums for N = 3 to 9 inclusive:\")\n        For i As Integer = nCount To 1 Step -1\n            Console.Out.WriteLine(numbers(i))\n        Next i\n        Console.Out.WriteLine(\"Considered \" & tryCount & \" digit combinations\")\n\n    End Sub\n\n\nEnd Module\n"}
{"id": 49335, "name": "Sorting algorithms_Pancake sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n"}
{"id": 49336, "name": "Sorting algorithms_Pancake sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n"}
{"id": 49337, "name": "Chemical calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49338, "name": "Chemical calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49339, "name": "Pythagorean quadruples", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n"}
{"id": 49340, "name": "Long stairs", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    totalSecs := 0\n    totalSteps := 0\n    fmt.Println(\"Seconds    steps behind    steps ahead\")\n    fmt.Println(\"-------    ------------    -----------\")\n    for trial := 1; trial < 10000; trial++ {\n        sbeh := 0\n        slen := 100\n        secs := 0\n        for sbeh < slen {\n            sbeh++\n            for wiz := 1; wiz < 6; wiz++ {\n                if rand.Intn(slen) < sbeh {\n                    sbeh++\n                }\n                slen++\n            }\n            secs++\n            if trial == 1 && secs > 599 && secs < 610 {\n                fmt.Printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh)\n            }\n        }\n        totalSecs += secs\n        totalSteps += slen\n    }\n    fmt.Println(\"\\nAverage secs taken:\", float64(totalSecs)/10000)\n    fmt.Println(\"Average final length of staircase:\", float64(totalSteps)/10000)\n}\n", "VB": "Option Explicit\nRandomize Timer\n\nFunction pad(s,n) \n  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If \nEnd Function\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\nFunction Rounds(maxsecs,wiz,a)\n  Dim mystep,maxstep,toend,j,i,x,d \n  If IsArray(a) Then d=True: print \"seconds behind pending\"   \n  maxstep=100\n  For j=1 To maxsecs\n    For i=1 To wiz\n      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1\n      maxstep=maxstep+1  \n    Next \n    mystep=mystep+1 \n    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function\n    If d Then\n      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)\n    End If     \n  Next \n  Rounds=Array(maxsecs,maxstep)\nEnd Function\n\n\nDim n,r,a,sumt,sums,ntests,t,maxsecs\nntests=10000\nmaxsecs=7000\nt=timer\na=Array(600,609)\nFor n=1 To ntests\n  r=Rounds(maxsecs,5,a)\n  If r(0)<>maxsecs Then \n    sumt=sumt+r(0)\n    sums=sums+r(1)\n  End if  \n  a=\"\"\nNext  \n\nprint vbcrlf & \"Done \" & ntests & \" tests in \" & Timer-t & \" seconds\" \nprint \"escaped in \" & sumt/ntests  & \" seconds with \" & sums/ntests & \" stairs\"\n"}
{"id": 49341, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 49342, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 49343, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 49344, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 49345, "name": "Zebra puzzle", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"log\"\n        \"strings\"\n)\n\n\n\ntype HouseSet [5]*House\ntype House struct {\n        n Nationality\n        c Colour\n        a Animal\n        d Drink\n        s Smoke\n}\ntype Nationality int8\ntype Colour int8\ntype Animal int8\ntype Drink int8\ntype Smoke int8\n\n\n\nconst (\n        English Nationality = iota\n        Swede\n        Dane\n        Norwegian\n        German\n)\nconst (\n        Red Colour = iota\n        Green\n        White\n        Yellow\n        Blue\n)\nconst (\n        Dog Animal = iota\n        Birds\n        Cats\n        Horse\n        Zebra\n)\nconst (\n        Tea Drink = iota\n        Coffee\n        Milk\n        Beer\n        Water\n)\nconst (\n        PallMall Smoke = iota\n        Dunhill\n        Blend\n        BlueMaster\n        Prince\n)\n\n\n\nvar nationalities = [...]string{\"English\", \"Swede\", \"Dane\", \"Norwegian\", \"German\"}\nvar colours = [...]string{\"red\", \"green\", \"white\", \"yellow\", \"blue\"}\nvar animals = [...]string{\"dog\", \"birds\", \"cats\", \"horse\", \"zebra\"}\nvar drinks = [...]string{\"tea\", \"coffee\", \"milk\", \"beer\", \"water\"}\nvar smokes = [...]string{\"Pall Mall\", \"Dunhill\", \"Blend\", \"Blue Master\", \"Prince\"}\n\nfunc (n Nationality) String() string { return nationalities[n] }\nfunc (c Colour) String() string      { return colours[c] }\nfunc (a Animal) String() string      { return animals[a] }\nfunc (d Drink) String() string       { return drinks[d] }\nfunc (s Smoke) String() string       { return smokes[s] }\nfunc (h House) String() string {\n        return fmt.Sprintf(\"%-9s  %-6s  %-5s  %-6s  %s\", h.n, h.c, h.a, h.d, h.s)\n}\nfunc (hs HouseSet) String() string {\n        lines := make([]string, 0, len(hs))\n        for i, h := range hs {\n                s := fmt.Sprintf(\"%d  %s\", i, h)\n                lines = append(lines, s)\n        }\n        return strings.Join(lines, \"\\n\")\n}\n\n\n\nfunc simpleBruteForce() (int, HouseSet) {\n        var v []House\n        for n := range nationalities {\n                for c := range colours {\n                        for a := range animals {\n                                for d := range drinks {\n                                        for s := range smokes {\n                                                h := House{\n                                                        n: Nationality(n),\n                                                        c: Colour(c),\n                                                        a: Animal(a),\n                                                        d: Drink(d),\n                                                        s: Smoke(s),\n                                                }\n                                                if !h.Valid() {\n                                                        continue\n                                                }\n                                                v = append(v, h)\n                                        }\n                                }\n                        }\n                }\n        }\n        n := len(v)\n        log.Println(\"Generated\", n, \"valid houses\")\n\n        combos := 0\n        first := 0\n        valid := 0\n        var validSet HouseSet\n        for a := 0; a < n; a++ {\n                if v[a].n != Norwegian { \n                        continue\n                }\n                for b := 0; b < n; b++ {\n                        if b == a {\n                                continue\n                        }\n                        if v[b].anyDups(&v[a]) {\n                                continue\n                        }\n                        for c := 0; c < n; c++ {\n                                if c == b || c == a {\n                                        continue\n                                }\n                                if v[c].d != Milk { \n                                        continue\n                                }\n                                if v[c].anyDups(&v[b], &v[a]) {\n                                        continue\n                                }\n                                for d := 0; d < n; d++ {\n                                        if d == c || d == b || d == a {\n                                                continue\n                                        }\n                                        if v[d].anyDups(&v[c], &v[b], &v[a]) {\n                                                continue\n                                        }\n                                        for e := 0; e < n; e++ {\n                                                if e == d || e == c || e == b || e == a {\n                                                        continue\n                                                }\n                                                if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {\n                                                        continue\n                                                }\n                                                combos++\n                                                set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}\n                                                if set.Valid() {\n                                                        valid++\n                                                        if valid == 1 {\n                                                                first = combos\n                                                        }\n                                                        validSet = set\n                                                        \n                                                }\n                                        }\n                                }\n                        }\n                }\n        }\n        log.Println(\"Tested\", first, \"different combinations of valid houses before finding solution\")\n        log.Println(\"Tested\", combos, \"different combinations of valid houses in total\")\n        return valid, validSet\n}\n\n\nfunc (h *House) anyDups(list ...*House) bool {\n        for _, b := range list {\n                if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {\n                        return true\n                }\n        }\n        return false\n}\n\nfunc (h *House) Valid() bool {\n        \n        if h.n == English && h.c != Red || h.n != English && h.c == Red {\n                return false\n        }\n        \n        if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {\n                return false\n        }\n        \n        if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {\n                return false\n        }\n        \n        if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {\n                return false\n        }\n        \n        if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {\n                return false\n        }\n        \n        if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {\n                return false\n        }\n        \n        if h.a == Cats && h.s == Blend {\n                return false\n        }\n        \n        if h.a == Horse && h.s == Dunhill {\n                return false\n        }\n        \n        if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {\n                return false\n        }\n        \n        if h.n == German && h.s != Prince || h.n != German && h.s == Prince {\n                return false\n        }\n        \n        if h.n == Norwegian && h.c == Blue {\n                return false\n        }\n        \n        if h.d == Water && h.s == Blend {\n                return false\n        }\n        return true\n}\n\nfunc (hs *HouseSet) Valid() bool {\n        ni := make(map[Nationality]int, 5)\n        ci := make(map[Colour]int, 5)\n        ai := make(map[Animal]int, 5)\n        di := make(map[Drink]int, 5)\n        si := make(map[Smoke]int, 5)\n        for i, h := range hs {\n                ni[h.n] = i\n                ci[h.c] = i\n                ai[h.a] = i\n                di[h.d] = i\n                si[h.s] = i\n        }\n        \n        if ci[Green]+1 != ci[White] {\n                return false\n        }\n        \n        if dist(ai[Cats], si[Blend]) != 1 {\n                return false\n        }\n        \n        if dist(ai[Horse], si[Dunhill]) != 1 {\n                return false\n        }\n        \n        if dist(ni[Norwegian], ci[Blue]) != 1 {\n                return false\n        }\n        \n        if dist(di[Water], si[Blend]) != 1 {\n                return false\n        }\n\n        \n        if hs[2].d != Milk {\n                return false\n        }\n        \n        if hs[0].n != Norwegian {\n                return false\n        }\n        return true\n}\n\nfunc dist(a, b int) int {\n        if a > b {\n                return a - b\n        }\n        return b - a\n}\n\nfunc main() {\n        log.SetFlags(0)\n        n, sol := simpleBruteForce()\n        fmt.Println(n, \"solution found\")\n        fmt.Println(sol)\n}\n", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n"}
{"id": 49346, "name": "Rosetta Code_Find unimplemented tasks", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n"}
{"id": 49347, "name": "Rosetta Code_Find unimplemented tasks", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n"}
{"id": 49348, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 49349, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 49350, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 49351, "name": "Practical numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n"}
{"id": 49352, "name": "Word search", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49353, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 49354, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 49355, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 49356, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 49357, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n"}
{"id": 49358, "name": "Zumkeller numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n"}
{"id": 49359, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 49360, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 49361, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 49362, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 49363, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 49364, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n"}
{"id": 49365, "name": "Geometric algebra", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n"}
{"id": 49366, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n"}
{"id": 49367, "name": "Define a primitive data type", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n"}
{"id": 49368, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n"}
{"id": 49369, "name": "Sierpinski square curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n"}
{"id": 49370, "name": "Find words whose first and last three letters are equal", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    count := 0\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {\n            count++\n            fmt.Printf(\"%d: %s\\n\", count, s)\n        }\n    }\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\nset d= createobject(\"Scripting.Dictionary\")\nfor each aa in a\n  x=trim(aa)\n  l=len(x)\n  if l>5 then\n   d.removeall\n   for i=1 to 3\n     m=mid(x,i,1)\n     if not d.exists(m) then d.add m,null\n   next\n   res=true\n   for i=l-2 to l\n     m=mid(x,i,1)\n     if not d.exists(m) then \n       res=false:exit for \n      else\n        d.remove(m)\n      end if        \n   next \n   if res then \n     wscript.stdout.write left(x & space(15),15)\n     if left(x,3)=right(x,3) then  wscript.stdout.write \"*\"\n     wscript.stdout.writeline\n    end if \n  end if\nnext\n"}
{"id": 49371, "name": "Word break problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49372, "name": "Latin Squares in reduced form", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49373, "name": "UPC", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n"}
{"id": 49374, "name": "Closest-pair problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n"}
{"id": 49375, "name": "Address of a variable", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n"}
{"id": 49376, "name": "Address of a variable", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n"}
{"id": 49377, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n"}
{"id": 49378, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 49379, "name": "Color wheel", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n"}
{"id": 49380, "name": "Find words which contain the most consonants", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n"}
{"id": 49381, "name": "Minesweeper game", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\ntype cell struct {\n    isMine  bool\n    display byte \n}\n\nconst lMargin = 4\n\nvar (\n    grid        [][]cell\n    mineCount   int\n    minesMarked int\n    isGameOver  bool\n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc makeGrid(n, m int) {\n    if n <= 0 || m <= 0 {\n        panic(\"Grid dimensions must be positive.\")\n    }\n    grid = make([][]cell, n)\n    for i := 0; i < n; i++ {\n        grid[i] = make([]cell, m)\n        for j := 0; j < m; j++ {\n            grid[i][j].display = '.'\n        }\n    }\n    min := int(math.Round(float64(n*m) * 0.1)) \n    max := int(math.Round(float64(n*m) * 0.2)) \n    mineCount = min + rand.Intn(max-min+1)\n    rm := mineCount\n    for rm > 0 {\n        x, y := rand.Intn(n), rand.Intn(m)\n        if !grid[x][y].isMine {\n            rm--\n            grid[x][y].isMine = true\n        }\n    }\n    minesMarked = 0\n    isGameOver = false\n}\n\nfunc displayGrid(isEndOfGame bool) {\n    if !isEndOfGame {\n        fmt.Println(\"Grid has\", mineCount, \"mine(s),\", minesMarked, \"mine(s) marked.\")\n    }\n    margin := strings.Repeat(\" \", lMargin)\n    fmt.Print(margin, \" \")\n    for i := 1; i <= len(grid); i++ {\n        fmt.Print(i)\n    }\n    fmt.Println()\n    fmt.Println(margin, strings.Repeat(\"-\", len(grid)))\n    for y := 0; y < len(grid[0]); y++ {\n        fmt.Printf(\"%*d:\", lMargin, y+1)\n        for x := 0; x < len(grid); x++ {\n            fmt.Printf(\"%c\", grid[x][y].display)\n        }\n        fmt.Println()\n    }\n}\n\nfunc endGame(msg string) {\n    isGameOver = true\n    fmt.Println(msg)\n    ans := \"\"\n    for ans != \"y\" && ans != \"n\" {\n        fmt.Print(\"Another game (y/n)? : \")\n        scanner.Scan()\n        ans = strings.ToLower(scanner.Text())\n    }\n    if scanner.Err() != nil || ans == \"n\" {\n        return\n    }\n    makeGrid(6, 4)\n    displayGrid(false)\n}\n\nfunc resign() {\n    found := 0\n    for y := 0; y < len(grid[0]); y++ {\n        for x := 0; x < len(grid); x++ {\n            if grid[x][y].isMine {\n                if grid[x][y].display == '?' {\n                    grid[x][y].display = 'Y'\n                    found++\n                } else if grid[x][y].display != 'x' {\n                    grid[x][y].display = 'N'\n                }\n            }\n        }\n    }\n    displayGrid(true)\n    msg := fmt.Sprint(\"You found \", found, \" out of \", mineCount, \" mine(s).\")\n    endGame(msg)\n}\n\nfunc usage() {\n    fmt.Println(\"h or ? - this help,\")\n    fmt.Println(\"c x y  - clear cell (x,y),\")\n    fmt.Println(\"m x y  - marks (toggles) cell (x,y),\")\n    fmt.Println(\"n      - start a new game,\")\n    fmt.Println(\"q      - quit/resign the game,\")\n    fmt.Println(\"where x is the (horizontal) column number and y is the (vertical) row number.\\n\")\n}\n\nfunc markCell(x, y int) {\n    if grid[x][y].display == '?' {\n        minesMarked--\n        grid[x][y].display = '.'\n    } else if grid[x][y].display == '.' {\n        minesMarked++\n        grid[x][y].display = '?'\n    }\n}\n\nfunc countAdjMines(x, y int) int {\n    count := 0\n    for j := y - 1; j <= y+1; j++ {\n        if j >= 0 && j < len(grid[0]) {\n            for i := x - 1; i <= x+1; i++ {\n                if i >= 0 && i < len(grid) {\n                    if grid[i][j].isMine {\n                        count++\n                    }\n                }\n            }\n        }\n    }\n    return count\n}\n\nfunc clearCell(x, y int) bool {\n    if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {\n        if grid[x][y].display == '.' {\n            if !grid[x][y].isMine {\n                count := countAdjMines(x, y)\n                if count > 0 {\n                    grid[x][y].display = string(48 + count)[0]\n                } else {\n                    grid[x][y].display = ' '\n                    clearCell(x+1, y)\n                    clearCell(x+1, y+1)\n                    clearCell(x, y+1)\n                    clearCell(x-1, y+1)\n                    clearCell(x-1, y)\n                    clearCell(x-1, y-1)\n                    clearCell(x, y-1)\n                    clearCell(x+1, y-1)\n                }\n            } else {\n                grid[x][y].display = 'x'\n                fmt.Println(\"Kaboom! You lost!\")\n                return false\n            }\n        }\n    }\n    return true\n}\n\nfunc testForWin() bool {\n    isCleared := false\n    if minesMarked == mineCount {\n        isCleared = true\n        for x := 0; x < len(grid); x++ {\n            for y := 0; y < len(grid[0]); y++ {\n                if grid[x][y].display == '.' {\n                    isCleared = false\n                }\n            }\n        }\n    }\n    if isCleared {\n        fmt.Println(\"You won!\")\n    }\n    return isCleared\n}\n\nfunc splitAction(action string) (int, int, bool) {\n    fields := strings.Fields(action)\n    if len(fields) != 3 {\n        return 0, 0, false\n    }\n    x, err := strconv.Atoi(fields[1])\n    if err != nil || x < 1 || x > len(grid) {\n        return 0, 0, false\n    }\n    y, err := strconv.Atoi(fields[2])\n    if err != nil || y < 1 || y > len(grid[0]) {\n        return 0, 0, false\n    }\n    return x, y, true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    usage()\n    makeGrid(6, 4)\n    displayGrid(false)\n    for !isGameOver {\n        fmt.Print(\"\\n>\")\n        scanner.Scan()\n        action := strings.ToLower(scanner.Text())\n        if scanner.Err() != nil || len(action) == 0 {\n            continue\n        }\n        switch action[0] {\n        case 'h', '?':\n            usage()\n        case 'n':\n            makeGrid(6, 4)\n            displayGrid(false)\n        case 'c':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            if clearCell(x-1, y-1) {\n                displayGrid(false)\n                if testForWin() {\n                    resign()\n                }\n            } else {\n                resign()\n            }\n        case 'm':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            markCell(x-1, y-1)\n            displayGrid(false)\n            if testForWin() {\n                resign()\n            }\n        case 'q':\n            resign()\n        }\n    }\n}\n", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n"}
{"id": 49382, "name": "Square root by hand", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n"}
{"id": 49383, "name": "Square root by hand", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n"}
{"id": 49384, "name": "Primes with digits in nondecreasing order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49385, "name": "Primes with digits in nondecreasing order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49386, "name": "Reflection_List properties", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49387, "name": "Align columns", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n"}
{"id": 49388, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 49389, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 49390, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49391, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49392, "name": "Data Encryption Standard", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n", "VB": "Imports System.IO\nImports System.Security.Cryptography\n\nModule Module1\n\n    \n    Function ByteArrayToString(ba As Byte()) As String\n        Return BitConverter.ToString(ba).Replace(\"-\", \"\")\n    End Function\n\n    \n    \n    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateEncryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(messageBytes, 0, messageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim encryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n\n        Return encryptedMessageBytes\n    End Function\n\n    \n    \n    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateDecryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim decryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)\n\n        Return decryptedMessageBytes\n    End Function\n\n    Sub Main()\n        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}\n        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}\n\n        Dim encStr = Encrypt(plainBytes, keyBytes)\n        Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr))\n\n        Dim decStr = Decrypt(encStr, keyBytes)\n        Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decStr))\n    End Sub\n\nEnd Module\n"}
{"id": 49393, "name": "Commatizing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n"}
{"id": 49394, "name": "Arithmetic coding_As a generalized change of radix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 49395, "name": "Kosaraju", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n"}
{"id": 49396, "name": "Pentomino tiling", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar F = [][]int{\n    {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},\n    {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},\n    {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},\n}\n\nvar I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}\n\nvar L = [][]int{\n    {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},\n}\n\nvar N = [][]int{\n    {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},\n}\n\nvar P = [][]int{\n    {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},\n}\n\nvar T = [][]int{\n    {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},\n}\n\nvar U = [][]int{\n    {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},\n}\n\nvar V = [][]int{\n    {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},\n}\n\nvar W = [][]int{\n    {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},\n}\n\nvar X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}\n\nvar Y = [][]int{\n    {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},\n}\n\nvar Z = [][]int{\n    {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},\n}\n\nvar shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}\n\nvar symbols = []byte(\"FILNPTUVWXYZ-\")\n\nconst (\n    nRows = 8\n    nCols = 8\n    blank = 12\n)\n\nvar grid [nRows][nCols]int\nvar placed [12]bool\n\nfunc tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {\n    for i := 0; i < len(o); i += 2 {\n        x := c + o[i+1]\n        y := r + o[i]\n        if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {\n            return false\n        }\n    }\n    grid[r][c] = shapeIndex\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = shapeIndex\n    }\n    return true\n}\n\nfunc removeOrientation(o []int, r, c int) {\n    grid[r][c] = -1\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = -1\n    }\n}\n\nfunc solve(pos, numPlaced int) bool {\n    if numPlaced == len(shapes) {\n        return true\n    }\n    row := pos / nCols\n    col := pos % nCols\n    if grid[row][col] != -1 {\n        return solve(pos+1, numPlaced)\n    }\n\n    for i := range shapes {\n        if !placed[i] {\n            for _, orientation := range shapes[i] {\n                if !tryPlaceOrientation(orientation, row, col, i) {\n                    continue\n                }\n                placed[i] = true\n                if solve(pos+1, numPlaced+1) {\n                    return true\n                }\n                removeOrientation(orientation, row, col)\n                placed[i] = false\n            }\n        }\n    }\n    return false\n}\n\nfunc shuffleShapes() {\n    rand.Shuffle(len(shapes), func(i, j int) {\n        shapes[i], shapes[j] = shapes[j], shapes[i]\n        symbols[i], symbols[j] = symbols[j], symbols[i]\n    })\n}\n\nfunc printResult() {\n    for _, r := range grid {\n        for _, i := range r {\n            fmt.Printf(\"%c \", symbols[i])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    shuffleShapes()\n    for r := 0; r < nRows; r++ {\n        for i := range grid[r] {\n            grid[r][i] = -1\n        }\n    }\n    for i := 0; i < 4; i++ {\n        var randRow, randCol int\n        for {\n            randRow = rand.Intn(nRows)\n            randCol = rand.Intn(nCols)\n            if grid[randRow][randCol] != blank {\n                break\n            }\n        }\n        grid[randRow][randCol] = blank\n    }\n    if solve(0, 0) {\n        printResult()\n    } else {\n        fmt.Println(\"No solution\")\n    }\n}\n", "VB": "Module Module1\n\n    Dim symbols As Char() = \"XYPFTVNLUZWI█\".ToCharArray(),\n        nRows As Integer = 8, nCols As Integer = 8,\n        target As Integer = 12, blank As Integer = 12,\n        grid As Integer()() = New Integer(nRows - 1)() {},\n        placed As Boolean() = New Boolean(target - 1) {},\n        pens As List(Of List(Of Integer())), rand As Random,\n        seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}\n\n    Sub Main()\n        Unpack(seeds) : rand = New Random() : ShuffleShapes(2)\n        For r As Integer = 0 To nRows - 1\n            grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next\n        For i As Integer = 0 To 3\n            Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)\n            Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank\n        Next\n        If Solve(0, 0) Then\n            PrintResult()\n        Else\n            Console.WriteLine(\"no solution for this configuration:\") : PrintResult()\n        End If\n        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\n    Sub ShuffleShapes(count As Integer) \n        For i As Integer = 0 To count : For j = 0 To pens.Count - 1\n                Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j\n                Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp\n                Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch\n            Next : Next\n    End Sub\n\n    Sub PrintResult() \n        For Each r As Integer() In grid : For Each i As Integer In r\n                Console.Write(\"{0} \", If(i < 0, \".\", symbols(i)))\n            Next : Console.WriteLine() : Next\n    End Sub\n\n    \n    Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean\n        If numPlaced = target Then Return True\n        Dim row As Integer = pos \\ nCols, col As Integer = pos Mod nCols\n        If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)\n        For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then\n                For Each orientation As Integer() In pens(i)\n                    If Not TPO(orientation, row, col, i) Then Continue For\n                    placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True\n                    RmvO(orientation, row, col) : placed(i) = False\n                Next : End If : Next : Return False\n    End Function\n\n    \n    Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)\n        grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = -1 : Next\n    End Sub\n\n    \n    Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,\n                 ByVal sIdx As Integer) As Boolean\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)\n            If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse\n                grid(y)(x) <> -1 Then Return False\n        Next : grid(row)(col) = sIdx\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = sIdx\n        Next : Return True\n    End Function\n\n    \n    \n    \n    \n\n    Sub Unpack(sv As Integer()) \n        pens = New List(Of List(Of Integer())) : For Each item In sv\n            Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),\n                fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7\n                If i = 4 Then Mir(exi) Else Rot(exi)\n                fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))\n            Next : pens.Add(Gen) : Next\n    End Sub\n\n    \n    Function Expand(i As Integer) As List(Of Integer)\n        Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next\n    End Function\n\n    \n    Function ToP(p As List(Of Integer)) As Integer()\n        Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)\n            tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next\n        tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next\n        Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)\n            Dim adj = If((item And 7) > 4, 8, 0)\n            res.Add((adj + item) \\ 8) : res.Add((item And 7) - adj)\n        Next : Return res.ToArray()\n    End Function\n\n    \n    Function TheSame(a As Integer(), b As Integer()) As Boolean\n        For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False\n        Next : Return True\n    End Function\n\n    Sub Rot(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next\n    End Sub\n\n    Sub Mir(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next\n    End Sub\n\nEnd Module\n"}
{"id": 49397, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n"}
{"id": 49398, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n"}
{"id": 49399, "name": "Check Machin-like formulas", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49400, "name": "Check Machin-like formulas", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 49401, "name": "Solve triangle solitare puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype solution struct{ peg, over, land int }\n\ntype move struct{ from, to int }\n\nvar emptyStart = 1\n\nvar board [16]bool\n\nvar jumpMoves = [16][]move{\n    {},\n    {{2, 4}, {3, 6}},\n    {{4, 7}, {5, 9}},\n    {{5, 8}, {6, 10}},\n    {{2, 1}, {5, 6}, {7, 11}, {8, 13}},\n    {{8, 12}, {9, 14}},\n    {{3, 1}, {5, 4}, {9, 13}, {10, 15}},\n    {{4, 2}, {8, 9}},\n    {{5, 3}, {9, 10}},\n    {{5, 2}, {8, 7}},\n    {{9, 8}},\n    {{12, 13}},\n    {{8, 5}, {13, 14}},\n    {{8, 4}, {9, 6}, {12, 11}, {14, 15}},\n    {{9, 5}, {13, 12}},\n    {{10, 6}, {14, 13}},\n}\n\nvar solutions []solution\n\nfunc initBoard() {\n    for i := 1; i < 16; i++ {\n        board[i] = true\n    }\n    board[emptyStart] = false\n}\n\nfunc (sol solution) split() (int, int, int) {\n    return sol.peg, sol.over, sol.land\n}\n\nfunc (mv move) split() (int, int) {\n    return mv.from, mv.to\n}\n\nfunc drawBoard() {\n    var pegs [16]byte\n    for i := 1; i < 16; i++ {\n        if board[i] {\n            pegs[i] = fmt.Sprintf(\"%X\", i)[0]\n        } else {\n            pegs[i] = '-'\n        }\n    }\n    fmt.Printf(\"       %c\\n\", pegs[1])\n    fmt.Printf(\"      %c %c\\n\", pegs[2], pegs[3])\n    fmt.Printf(\"     %c %c %c\\n\", pegs[4], pegs[5], pegs[6])\n    fmt.Printf(\"    %c %c %c %c\\n\", pegs[7], pegs[8], pegs[9], pegs[10])\n    fmt.Printf(\"   %c %c %c %c %c\\n\", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n}\n\nfunc solved() bool {\n    count := 0\n    for _, b := range board {\n        if b {\n            count++\n        }\n    }\n    return count == 1 \n}\n\nfunc solve() {\n    if solved() {\n        return\n    }\n    for peg := 1; peg < 16; peg++ {\n        if board[peg] {\n            for _, mv := range jumpMoves[peg] {\n                over, land := mv.split()\n                if board[over] && !board[land] {\n                    saveBoard := board\n                    board[peg] = false\n                    board[over] = false\n                    board[land] = true\n                    solutions = append(solutions, solution{peg, over, land})\n                    solve()\n                    if solved() {\n                        return \n                    }\n                    board = saveBoard\n                    solutions = solutions[:len(solutions)-1]\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    initBoard()\n    solve()\n    initBoard()\n    drawBoard()\n    fmt.Printf(\"Starting with peg %X removed\\n\\n\", emptyStart)\n    for _, solution := range solutions {\n        peg, over, land := solution.split()\n        board[peg] = false\n        board[over] = false\n        board[land] = true\n        drawBoard()\n        fmt.Printf(\"Peg %X jumped over %X to land on %X\\n\\n\", peg, over, land)\n    }\n}\n", "VB": "Imports System, Microsoft.VisualBasic.DateAndTime\n\nPublic Module Module1\n    Const n As Integer = 5 \n    Dim Board As String \n    Dim Starting As Integer = 1 \n    Dim Target As Integer = 13 \n    Dim Moves As Integer() \n    Dim bi() As Integer \n    Dim ib() As Integer \n    Dim nl As Char = Convert.ToChar(10) \n\n    \n    Public Function Dou(s As String) As String\n        Dou = \"\" : Dim b As Boolean = True\n        For Each ch As Char In s\n            If b Then b = ch <> \" \"\n            If b Then Dou &= ch & \" \" Else Dou = \" \" & Dou\n        Next : Dou = Dou.TrimEnd()\n    End Function\n\n    \n    Public Function Fmt(s As String) As String\n        If s.Length < Board.Length Then Return s\n        Fmt = \"\" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &\n                If(i = n, s.Substring(Board.Length), \"\") & nl\n        Next\n    End Function\n\n    \n    Public Function Triangle(n As Integer) As Integer\n        Return (n * (n + 1)) / 2\n    End Function\n\n    \n    Public Function Init(s As String, pos As Integer) As String\n        Init = s : Mid(Init, pos, 1) = \"0\"\n    End Function\n\n    \n    Public Sub InitIndex()\n        ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0\n        For i As Integer = 0 To ib.Length - 1\n            If i = 0 Then\n                ib(i) = 0 : bi(j) = 0 : j += 1\n            Else\n                If Board(i - 1) = \"1\" Then ib(i) = j : bi(j) = i : j += 1\n            End If\n        Next\n    End Sub\n\n    \n    Public Function solve(brd As String, pegsLeft As Integer) As String\n        If pegsLeft = 1 Then \n            If Target = 0 Then Return \"Completed\" \n            If brd(bi(Target) - 1) = \"1\" Then Return \"Completed\" Else Return \"fail\"\n        End If\n        For i = 1 To Board.Length \n            If brd(i - 1) = \"1\" Then \n                For Each mj In Moves \n                    Dim over As Integer = i + mj \n                    Dim land As Integer = i + 2 * mj \n                    \n                    If land >= 1 AndAlso land <= brd.Length _\n                                AndAlso brd(land - 1) = \"0\" _\n                                AndAlso brd(over - 1) = \"1\" Then\n                        setPegs(brd, \"001\", i, over, land) \n                        \n                        Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)\n                        \n                        If Res.Length <> 4 Then _\n                            Return brd & info(i, over, land) & nl & Res\n                        setPegs(brd, \"110\", i, over, land) \n                    End If\n                Next\n            End If\n        Next\n        Return \"fail\"\n    End Function\n\n    \n    Function info(frm As Integer, over As Integer, dest As Integer) As String\n        Return \"  Peg from \" & ib(frm).ToString() & \" goes to \" & ib(dest).ToString() &\n            \", removing peg at \" & ib(over).ToString()\n    End Function\n\n    \n    Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)\n        Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)\n    End Sub\n\n    \n    Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)\n        x = Math.Max(Math.Min(x, hi), lo)\n    End Sub\n\n    Public Sub Main()\n        Dim t As Integer = Triangle(n) \n        LimitIt(Starting, 1, t) \n        LimitIt(Target, 0, t)\n        Dim stime As Date = Now() \n        Moves = {-n - 1, -n, -1, 1, n, n + 1} \n        Board = New String(\"1\", n * n) \n        For i As Integer = 0 To n - 2 \n            Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(\" \", n - 1 - i)\n        Next\n        InitIndex() \n        Dim B As String = Init(Board, bi(Starting)) \n        Console.WriteLine(Fmt(B & \"  Starting with peg removed from \" & Starting.ToString()))\n        Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)\n        Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & \" ms.\"\n        If res(0).Length = 4 Then\n            If Target = 0 Then\n                Console.WriteLine(\"Unable to find a solution with last peg left anywhere.\")\n            Else\n                Console.WriteLine(\"Unable to find a solution with last peg left at \" &\n                                  Target.ToString() & \".\")\n            End If\n            Console.WriteLine(\"Computation time: \" & ts)\n        Else\n            For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next\n            Console.WriteLine(\"Computation time to first found solution: \" & ts)\n        End If\n        If Diagnostics.Debugger.IsAttached Then Console.ReadLine()\n    End Sub\nEnd Module\n"}
{"id": 49402, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n"}
{"id": 49403, "name": "Suffixation of decimal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n"}
{"id": 49404, "name": "Suffixation of decimal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n"}
{"id": 49405, "name": "Nested templated data", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"text/template\"\n)\n\nfunc main() {\n    const t = `[[[{{index .P 1}}, {{index .P 2}}],\n  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n  {{index .P 5}}]]\n`\n    type S struct {\n        P map[int]string\n    }\n\n    var s S\n    s.P = map[int]string{\n        0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n        4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n    }\n    tmpl := template.Must(template.New(\"\").Parse(t))\n    tmpl.Execute(os.Stdout, s)\n\n    var unused []int\n    for k, _ := range s.P {\n        if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n            unused = append(unused, k)\n        }\n    }\n    sort.Ints(unused)\n    fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}\n", "VB": "Public Sub test()\n    Dim t(2) As Variant\n    t(0) = [{1,2}]\n    t(1) = [{3,4,1}]\n    t(2) = 5\n    p = [{\"Payload#0\",\"Payload#1\",\"Payload#2\",\"Payload#3\",\"Payload#4\",\"Payload#5\",\"Payload#6\"}]\n    Dim q(6) As Boolean\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            For j = LBound(t(i)) To UBound(t(i))\n                q(t(i)(j)) = True\n                t(i)(j) = p(t(i)(j) + 1)\n            Next j\n        Else\n            q(t(i)) = True\n            t(i) = p(t(i) + 1)\n        End If\n    Next i\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            Debug.Print Join(t(i), \", \")\n        Else\n            Debug.Print t(i)\n        End If\n    Next i\n    For i = LBound(q) To UBound(q)\n        If Not q(i) Then Debug.Print p(i + 1); \" is not used\"\n    Next i\nEnd Sub\n"}
{"id": 49406, "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": 49407, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\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": 49408, "name": "Peano curve", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 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": 49409, "name": "Seven-sided dice from five-sided dice", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\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": 49410, "name": "Solve the no connection puzzle", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 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": 49411, "name": "Magnanimous numbers", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\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": 49412, "name": "Extensible prime generator", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\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": 49413, "name": "Rock-paper-scissors", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\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": 49414, "name": "Create a two-dimensional array at runtime", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\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": 49415, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \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": 49416, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \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": 49417, "name": "Vigenère cipher_Cryptanalysis", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\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": 49418, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \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": 49419, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 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": 49420, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 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": 49421, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 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": 49422, "name": "Return multiple values", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 49423, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\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": 49424, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\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": 49425, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\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": 49426, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 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": 49427, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 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": 49428, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\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": 49429, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 49430, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 49431, "name": "LU decomposition", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 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": 49432, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\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": 49433, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\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": 49434, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\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": 49435, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\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": 49436, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\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": 49437, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\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": 49438, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\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": 49439, "name": "Checkpoint synchronization", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\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": 49440, "name": "Variable-length quantity", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\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": 49441, "name": "Record sound", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\nusing namespace std;\n\nclass recorder\n{\npublic:\n    void start()\n    {\n\tpaused = rec = false; action = \"IDLE\";\n\twhile( true )\n\t{\n\t    cout << endl << \"==\" << action << \"==\" << endl << endl;\n\t    cout << \"1) Record\" << endl << \"2) Play\" << endl << \"3) Pause\" << endl << \"4) Stop\" << endl << \"5) Quit\" << endl;\n\t    char c; cin >> c;\n\t    if( c > '0' && c < '6' )\n\t    {\n\t\tswitch( c )\n\t\t{\n\t\t    case '1': record(); break;\n\t\t    case '2': play();   break;\n\t\t    case '3': pause();  break;\n\t\t    case '4': stop();   break;\n\t\t    case '5': stop();   return;\n\t\t}\n\t    }\n\t}\n    }\nprivate:\n    void record()\n    {\n\tif( mciExecute( \"open new type waveaudio alias my_sound\") )\n\t{ \n\t    mciExecute( \"record my_sound\" ); \n\t    action = \"RECORDING\"; rec = true; \n\t}\n    }\n    void play()\n    {\n\tif( paused )\n\t    mciExecute( \"play my_sound\" );\n\telse\n\t    if( mciExecute( \"open tmp.wav alias my_sound\" ) )\n\t\tmciExecute( \"play my_sound\" );\n\n\taction = \"PLAYING\";\n\tpaused = false;\n    }\n    void pause()\n    {\n\tif( rec ) return;\n\tmciExecute( \"pause my_sound\" );\n\tpaused = true; action = \"PAUSED\";\n    }\n    void stop()\n    {\n\tif( rec )\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"save my_sound tmp.wav\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\"; rec = false;\n\t}\n\telse\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\";\n\t}\n    }\n    bool mciExecute( string cmd )\n    {\n\tif( mciSendString( cmd.c_str(), NULL, 0, NULL ) )\n\t{\n\t    cout << \"Can't do this: \" << cmd << endl;\n\t    return false;\n\t}\n\treturn true;\n    }\n\n    bool paused, rec;\n    string action;\n};\n\nint main( int argc, char* argv[] )\n{\n    recorder r; r.start();\n    return 0;\n}\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": 49442, "name": "SHA-256 Merkle tree", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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    \"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": 49443, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\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": 49444, "name": "User input_Graphical", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\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": 49445, "name": "Sierpinski arrowhead curve", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\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": 49446, "name": "Text processing_1", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\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": 49447, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\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": 49448, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\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": 49449, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\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": 49450, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\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": 49451, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\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": 49452, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\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": 49453, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\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": 49454, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\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": 49455, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\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": 49456, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\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": 49457, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\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": 49458, "name": "Totient function", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\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    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": 49459, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 49460, "name": "Fractran", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\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": 49461, "name": "Sorting algorithms_Stooge sort", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\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    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": 49462, "name": "Sorting algorithms_Stooge sort", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\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    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": 49463, "name": "Galton box animation", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\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": 49464, "name": "Sorting Algorithms_Circle Sort", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\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": 49465, "name": "Kronecker product based fractals", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\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": 49466, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\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": 49467, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\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": 49468, "name": "Circular primes", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\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": 49469, "name": "Animation", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\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": 49470, "name": "Sorting algorithms_Radix sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\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": 49471, "name": "List comprehensions", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\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": 49472, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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 \"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": 49473, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\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": 49474, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\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": 49475, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\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": 49476, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\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": 49477, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\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": 49478, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\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": 49479, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\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": 49480, "name": "Safe addition", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\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": 49481, "name": "Case-sensitivity of identifiers", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\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": 49482, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 49483, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 49484, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\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": 49485, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\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": 49486, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\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": 49487, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\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": 49488, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\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": 49489, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\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": 49490, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\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": 49491, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\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": 49492, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\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": 49493, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\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": 49494, "name": "Fibonacci word_fractal", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\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": 49495, "name": "Twin primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\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": 49496, "name": "15 puzzle solver", "C++": "\nclass fifteenSolver{\n  const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};\n  int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};\n  unsigned long N2[100]{};\n  const bool fY(){\n    if (N4[n]<_n) return fN();\n    if (N2[n]==0x123456789abcdef0) {std::cout<<\"Solution found in \"<<n<<\" moves :\"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};\n    if (N4[n]==_n) return fN(); else return false;\n  }\n  const bool                     fN(){\n    if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}\n    return false;\n  }\n  void fI(){\n    const int           g = (11-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);\n  } \n  void fG(){\n    const int           g = (19-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);\n  } \n  void fE(){\n    const int           g = (14-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);\n  } \n  void fL(){\n    const int           g = (16-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);\n  }\npublic:\n  fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}\n  void Solve(){for(;not fY();++_n);}\n};\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": 49497, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\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": 49498, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\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": 49499, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\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": 49500, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\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": 49501, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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 \"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": 49502, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\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": 49503, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\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": 49504, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\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": 49505, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\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": 49506, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\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": 49507, "name": "Man or boy test", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\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": 49508, "name": "Short-circuit evaluation", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\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": 49509, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\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": 49510, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\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": 49511, "name": "Carmichael 3 strong pseudoprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n"}
{"id": 49512, "name": "Arithmetic numbers", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n"}
{"id": 49513, "name": "Arithmetic numbers", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n"}
{"id": 49514, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 49515, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 49516, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 49517, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 49518, "name": "Conjugate transpose", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n"}
{"id": 49519, "name": "Conjugate transpose", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n"}
{"id": 49520, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 49521, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 49522, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 49523, "name": "Sorting algorithms_Bead sort", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 49524, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 49525, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 49526, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 49527, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 49528, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 49529, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 49530, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 49531, "name": "Inverted index", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 49532, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 49533, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 49534, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 49535, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 49536, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 49537, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 49538, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 49539, "name": "Descending primes", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 49540, "name": "Descending primes", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 49541, "name": "Square-free integers", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 49542, "name": "Jaro similarity", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n"}
{"id": 49543, "name": "Sum and product puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n"}
{"id": 49544, "name": "Sum and product puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n"}
{"id": 49545, "name": "Fairshare between two and more", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n"}
{"id": 49546, "name": "Two bullet roulette", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <sstream>\n\nclass Roulette {\nprivate:\n    std::array<bool, 6> cylinder;\n\n    std::mt19937 gen;\n    std::uniform_int_distribution<> distrib;\n\n    int next_int() {\n        return distrib(gen);\n    }\n\n    void rshift() {\n        std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n    }\n\n    void unload() {\n        std::fill(cylinder.begin(), cylinder.end(), false);\n    }\n\n    void load() {\n        while (cylinder[0]) {\n            rshift();\n        }\n        cylinder[0] = true;\n        rshift();\n    }\n\n    void spin() {\n        int lim = next_int();\n        for (int i = 1; i < lim; i++) {\n            rshift();\n        }\n    }\n\n    bool fire() {\n        auto shot = cylinder[0];\n        rshift();\n        return shot;\n    }\n\npublic:\n    Roulette() {\n        std::random_device rd;\n        gen = std::mt19937(rd());\n        distrib = std::uniform_int_distribution<>(1, 6);\n\n        unload();\n    }\n\n    int method(const std::string &s) {\n        unload();\n        for (auto c : s) {\n            switch (c) {\n            case 'L':\n                load();\n                break;\n            case 'S':\n                spin();\n                break;\n            case 'F':\n                if (fire()) {\n                    return 1;\n                }\n                break;\n            }\n        }\n        return 0;\n    }\n};\n\nstd::string mstring(const std::string &s) {\n    std::stringstream ss;\n    bool first = true;\n\n    auto append = [&ss, &first](const std::string s) {\n        if (first) {\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << s;\n    };\n\n    for (auto c : s) {\n        switch (c) {\n        case 'L':\n            append(\"load\");\n            break;\n        case 'S':\n            append(\"spin\");\n            break;\n        case 'F':\n            append(\"fire\");\n            break;\n        }\n    }\n\n    return ss.str();\n}\n\nvoid test(const std::string &src) {\n    const int tests = 100000;\n    int sum = 0;\n\n    Roulette r;\n    for (int t = 0; t < tests; t++) {\n        sum += r.method(src);\n    }\n\n    double pc = 100.0 * sum / tests;\n\n    std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n    t := cylinder[5]\n    for i := 4; i >= 0; i-- {\n        cylinder[i+1] = cylinder[i]\n    }\n    cylinder[0] = t\n}\n\nfunc unload() {\n    for i := 0; i < 6; i++ {\n        cylinder[i] = false\n    }\n}\n\nfunc load() {\n    for cylinder[0] {\n        rshift()\n    }\n    cylinder[0] = true\n    rshift()\n}\n\nfunc spin() {\n    var lim = 1 + rand.Intn(6)\n    for i := 1; i < lim; i++ {\n        rshift()\n    }\n}\n\nfunc fire() bool {\n    shot := cylinder[0]\n    rshift()\n    return shot\n}\n\nfunc method(s string) int {\n    unload()\n    for _, c := range s {\n        switch c {\n        case 'L':\n            load()\n        case 'S':\n            spin()\n        case 'F':\n            if fire() {\n                return 1\n            }\n        }\n    }\n    return 0\n}\n\nfunc mstring(s string) string {\n    var l []string\n    for _, c := range s {\n        switch c {\n        case 'L':\n            l = append(l, \"load\")\n        case 'S':\n            l = append(l, \"spin\")\n        case 'F':\n            l = append(l, \"fire\")\n        }\n    }\n    return strings.Join(l, \", \")\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := 100000\n    for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n        sum := 0\n        for t := 1; t <= tests; t++ {\n            sum += method(m)\n        }\n        pc := float64(sum) * 100 / float64(tests)\n        fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n    }\n}\n"}
{"id": 49547, "name": "Parsing_Shunting-yard algorithm", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 49548, "name": "Prime triangle", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n"}
{"id": 49549, "name": "Trabb Pardo–Knuth algorithm", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 49550, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 49551, "name": "Sequence_ nth number with exactly n divisors", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49552, "name": "Sequence_ smallest number with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n"}
{"id": 49553, "name": "Pancake numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 49554, "name": "Generate random chess position", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n"}
{"id": 49555, "name": "Esthetic numbers", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n"}
{"id": 49556, "name": "Topswops", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n"}
{"id": 49557, "name": "Old Russian measure of length", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n"}
{"id": 49558, "name": "Rate counter", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n"}
{"id": 49559, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 49560, "name": "Padovan sequence", "C++": "#include <iostream>\n#include <map>\n#include <cmath>\n\n\n\nint pRec(int n) {\n    static std::map<int,int> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n\n    if (n <= 2) memo[n] = 1;\n    else memo[n] = pRec(n-2) + pRec(n-3);\n    return memo[n];\n}\n\n\n\nint pFloor(int n) {\n    long const double p = 1.324717957244746025960908854;\n    long const double s = 1.0453567932525329623;\n    return std::pow(p, n-1)/s + 0.5;\n}\n\n\nstd::string& lSystem(int n) {\n    static std::map<int,std::string> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n    \n    if (n == 0) memo[n] = \"A\";\n    else {\n        memo[n] = \"\";\n        for (char ch : memo[n-1]) {\n            switch(ch) {\n                case 'A': memo[n].push_back('B'); break;\n                case 'B': memo[n].push_back('C'); break;\n                case 'C': memo[n].append(\"AB\"); break;\n            }\n        }\n    }\n    return memo[n];\n}\n\n\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n    std::cout << \"The \" << descr << \" functions \";\n    int i;\n    for (i=0; i<stop; i++) {\n        int n1 = f1(i);\n        int n2 = f2(i);\n        if (n1 != n2) {\n            std::cout << \"do not match at \" << i\n                      << \": \" << n1 << \" != \" << n2 << \".\\n\";\n            break;\n        }\n    }\n    if (i == stop) {\n        std::cout << \"match from P_0 to P_\" << stop << \".\\n\";\n    }\n}\n\nint main() {\n    \n    std::cout << \"P_0 .. P_19: \";\n    for (int i=0; i<20; i++) std::cout << pRec(i) << \" \";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, pRec, \"floor- and recurrence-based\", 64);\n    \n    \n    std::cout << \"\\nThe first 10 L-system strings are:\\n\";\n    for (int i=0; i<10; i++) std::cout << lSystem(i) << \"\\n\";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, [](int n){return (int)lSystem(n).length();}, \n                            \"floor- and L-system-based\", 32);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n"}
{"id": 49561, "name": "Pythagoras tree", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n"}
{"id": 49562, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 49563, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 49564, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 49565, "name": "Include a file", "C++": "\nimport <iostream>;\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 49566, "name": "Include a file", "C++": "\nimport <iostream>;\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 49567, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n"}
{"id": 49568, "name": "Numeric error propagation", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n"}
{"id": 49569, "name": "List rooted trees", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n"}
{"id": 49570, "name": "Longest common suffix", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n"}
{"id": 49571, "name": "Arena storage pool", "C++": "T* foo = new(arena) T;\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n"}
{"id": 49572, "name": "Arena storage pool", "C++": "T* foo = new(arena) T;\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n"}
{"id": 49573, "name": "Arena storage pool", "C++": "T* foo = new(arena) T;\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n"}
{"id": 49574, "name": "Sum of elements below main diagonal of matrix", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n"}
{"id": 49575, "name": "FASTA format", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n"}
{"id": 49576, "name": "Elementary cellular automaton_Random number generator", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n"}
{"id": 49577, "name": "Elementary cellular automaton_Random number generator", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n"}
{"id": 49578, "name": "Pseudo-random numbers_PCG32", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 49579, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n"}
{"id": 49580, "name": "Rep-string", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n"}
{"id": 49581, "name": "Literals_String", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 49582, "name": "Changeable words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n"}
{"id": 49583, "name": "Monads_List monad", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate <typename T>\nauto operator>>(const vector<T>& monad, auto f)\n{\n    \n    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;\n    for(auto& item : monad)\n    {\n        \n        \n        const auto r = f(item);\n        \n        result.insert(result.end(), begin(r), end(r));\n    }\n    \n    return result;\n}\n\n\nauto Pure(auto t)\n{\n    return vector{t};\n}\n\n\nauto Double(int i)\n{\n    return Pure(2 * i);\n}\n\n\nauto Increment(int i)\n{\n    return Pure(i + 1);\n}\n\n\nauto NiceNumber(int i)\n{\n    return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n\n\nauto UpperSequence = [](auto startingVal)\n{\n    const int MaxValue = 500;\n    vector<decltype(startingVal)> sequence;\n    while(startingVal <= MaxValue) \n        sequence.push_back(startingVal++);\n    return sequence;\n};\n\n\nvoid PrintVector(const auto& vec)\n{\n    cout << \" \";\n    for(auto value : vec)\n    {\n        cout << value << \" \";\n    }\n    cout << \"\\n\";\n}\n\n\nvoid PrintTriples(const auto& vec)\n{\n    cout << \"Pythagorean triples:\\n\";\n    for(auto it = vec.begin(); it != vec.end();)\n    {\n        auto x = *it++;\n        auto y = *it++;\n        auto z = *it++;\n        \n        cout << x << \", \" << y << \", \" << z << \"\\n\";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    \n    auto listMonad = \n        vector<int> {2, 3, 4} >> \n        Increment >> \n        Double >>\n        NiceNumber;\n        \n    PrintVector(listMonad);\n    \n    \n    \n    \n    \n    auto pythagoreanTriples = UpperSequence(1) >> \n        [](int x){return UpperSequence(x) >>\n        [x](int y){return UpperSequence(y) >>\n        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};\n    \n    PrintTriples(pythagoreanTriples);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n    return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n    return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = v + 1\n    }\n    return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = 2 * v\n    }\n    return unit(lst2)\n}\n\nfunc main() {\n    ml1 := unit([]int{3, 4, 5})\n    ml2 := ml1.bind(increment).bind(double)\n    fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}\n"}
{"id": 49584, "name": "Special factorials", "C++": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc sf(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    sfact := big.NewInt(1)\n    fact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        sfact.Mul(sfact, fact)\n    }\n    return sfact\n}\n\nfunc H(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    hfact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        bi := big.NewInt(int64(i))\n        hfact.Mul(hfact, bi.Exp(bi, bi, nil))\n    }\n    return hfact\n}\n\nfunc af(n int) *big.Int {\n    if n < 1 {\n        return new(big.Int)\n    }\n    afact := new(big.Int)\n    fact := big.NewInt(1)\n    sign := new(big.Int)\n    if n%2 == 0 {\n        sign.SetInt64(-1)\n    } else {\n        sign.SetInt64(1)\n    }\n    t := new(big.Int)\n    for i := 1; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        afact.Add(afact, t.Mul(fact, sign))\n        sign.Neg(sign)\n    }\n    return afact\n}\n\nfunc ef(n int) *big.Int {\n    if n < 1 {\n        return big.NewInt(1)\n    }\n    t := big.NewInt(int64(n))\n    return t.Exp(t, ef(n-1), nil)\n}\n\nfunc rf(n *big.Int) int {\n    i := 0\n    fact := big.NewInt(1)\n    for {\n        if fact.Cmp(n) == 0 {\n            return i\n        }\n        if fact.Cmp(n) > 0 {\n            return -1\n        }\n        i++\n        fact.Mul(fact, big.NewInt(int64(i)))\n    }\n}\n\nfunc main() {\n    fmt.Println(\"First 10 superfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sf(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 hyperfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(H(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 alternating factorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Print(af(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 exponential factorials:\")\n    for i := 0; i <= 4; i++ {\n        fmt.Print(ef(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nThe number of digits in 5$ is\", len(ef(5).String()))\n\n    fmt.Println(\"\\nReverse factorials:\")\n    facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}\n    for _, fact := range facts {\n        bfact := big.NewInt(fact)\n        rfact := rf(bfact)\n        srfact := fmt.Sprintf(\"%d\", rfact)\n        if rfact == -1 {\n            srfact = \"none\"\n        }\n        fmt.Printf(\"%4s <- rf(%d)\\n\", srfact, fact)\n    }\n}\n"}
{"id": 49585, "name": "Four is magic", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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": 49586, "name": "Getting the number of decimals", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n"}
{"id": 49587, "name": "Enumerations", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 49588, "name": "Parse an IP Address", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n"}
{"id": 49589, "name": "Textonyms", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n"}
{"id": 49590, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 49591, "name": "A_ search algorithm", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 49592, "name": "Teacup rim text", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\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    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 49593, "name": "Increasing gaps between consecutive Niven numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n"}
{"id": 49594, "name": "Print debugging statement", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n"}
{"id": 49595, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n"}
{"id": 49596, "name": "Type detection", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n"}
{"id": 49597, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 49598, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 49599, "name": "Variable declaration reset", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n"}
{"id": 49600, "name": "Numbers with equal rises and falls", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n"}
{"id": 49601, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n"}
{"id": 49602, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n"}
{"id": 49603, "name": "Words from neighbour ones", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\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    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n"}
{"id": 49604, "name": "Magic squares of singly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n"}
{"id": 49605, "name": "Magic squares of singly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n"}
{"id": 49606, "name": "Generate Chess960 starting position", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n"}
{"id": 49607, "name": "Modulinos", "C++": "int meaning_of_life();\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 49608, "name": "Modulinos", "C++": "int meaning_of_life();\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 49609, "name": "File size distribution", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\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    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc commatize(n int64) 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 fileSizeDistribution(root string) {\n    var sizes [12]int\n    files := 0\n    directories := 0\n    totalSize := int64(0)\n    walkFunc := func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        files++\n        if info.IsDir() {\n            directories++\n        }\n        size := info.Size()\n        if size == 0 {\n            sizes[0]++\n            return nil\n        }\n        totalSize += size\n        logSize := math.Log10(float64(size))\n        index := int(math.Floor(logSize))\n        sizes[index+1]++\n        return nil\n    }\n    err := filepath.Walk(root, walkFunc)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n    for i := 0; i < len(sizes); i++ {\n        if i == 0 {\n            fmt.Print(\"  \")\n        } else {\n            fmt.Print(\"+ \")\n        }\n        fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n    }\n    fmt.Println(\"                                  -----\")\n    fmt.Printf(\"= Total number of files         : %5d\\n\", files)\n    fmt.Printf(\"  including directories         : %5d\\n\", directories)\n    c := commatize(totalSize)\n    fmt.Println(\"\\n  Total size of files           :\", c, \"bytes\")\n}\n\nfunc main() {\n    fileSizeDistribution(\"./\")\n}\n"}
{"id": 49610, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 49611, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 49612, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 49613, "name": "Pseudo-random numbers_Xorshift star", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 49614, "name": "Four is the number of letters in the ...", "C++": "#include <cctype>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        result.push_back(get_name(small[n], ordinal));\n        count = 1;\n    }\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result.push_back(get_name(tens[n/10 - 2], ordinal));\n        } else {\n            std::string name(get_name(tens[n/10 - 2], false));\n            name += \"-\";\n            name += get_name(small[n % 10], ordinal);\n            result.push_back(name);\n        }\n        count = 1;\n    } else {\n        const named_number& num = get_named_number(n);\n        uint64_t p = num.number;\n        count += append_number_name(result, n/p, false);\n        if (n % p == 0) {\n            result.push_back(get_name(num, ordinal));\n            ++count;\n        } else {\n            result.push_back(get_name(num, false));\n            ++count;\n            count += append_number_name(result, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(const std::string& str) {\n    size_t letters = 0;\n    for (size_t i = 0, n = str.size(); i < n; ++i) {\n        if (isalpha(static_cast<unsigned char>(str[i])))\n            ++letters;\n    }\n    return letters;\n}\n\nstd::vector<std::string> sentence(size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    std::vector<std::string> result;\n    result.reserve(count + 10);\n    size_t n = std::size(words);\n    for (size_t i = 0; i < n && i < count; ++i) {\n        result.push_back(words[i]);\n    }\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result[i]), false);\n        result.push_back(\"in\");\n        result.push_back(\"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        result.back() += ',';\n    }\n    return result;\n}\n\nsize_t sentence_length(const std::vector<std::string>& words) {\n    size_t n = words.size();\n    if (n == 0)\n        return 0;\n    size_t length = n - 1;\n    for (size_t i = 0; i < n; ++i)\n        length += words[i].size();\n    return length;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    size_t n = 201;\n    auto result = sentence(n);\n    std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            std::cout << (i % 25 == 0 ? '\\n' : ' ');\n        std::cout << std::setw(2) << count_letters(result[i]);\n    }\n    std::cout << '\\n';\n    std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    for (n = 1000; n <= 10000000; n *= 10) {\n        result = sentence(n);\n        const std::string& word = result[n - 1];\n        std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n            << count_letters(word) << \" letters. \";\n        std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n"}
{"id": 49615, "name": "ASCII art diagram converter", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n"}
{"id": 49616, "name": "Same fringe", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n"}
{"id": 49617, "name": "Peaceful chess queen armies", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n"}
{"id": 49618, "name": "Loops_Infinite", "C++": "while (true)\n  std::cout << \"SPAM\\n\";\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 49619, "name": "Numbers with same digit set in base 10 and base 16", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n"}
{"id": 49620, "name": "Numbers with same digit set in base 10 and base 16", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n"}
{"id": 49621, "name": "Largest proper divisor of n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            return n / i\n        }\n    }\n    return 1\n}\n\nfunc main() {\n    fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n    fmt.Print(\" 1  \")\n    for n := 2; n <= 100; n++ {\n        if n%2 == 0 {\n            fmt.Printf(\"%2d  \", n/2)\n        } else {\n            fmt.Printf(\"%2d  \", largestProperDivisor(n))\n        }\n        if n%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 49622, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 49623, "name": "Sum of first n cubes", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n"}
{"id": 49624, "name": "Test integerness", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n"}
{"id": 49625, "name": "Execute a system command", "C++": "system(\"pause\");\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 49626, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 49627, "name": "Lucky and even lucky numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nconst int luckySize = 60000;\nstd::vector<int> luckyEven(luckySize);\nstd::vector<int> luckyOdd(luckySize);\n\nvoid init() {\n    for (int i = 0; i < luckySize; ++i) {\n        luckyEven[i] = i * 2 + 2;\n        luckyOdd[i] = i * 2 + 1;\n    }\n}\n\nvoid filterLuckyEven() {\n    for (size_t n = 2; n < luckyEven.size(); ++n) {\n        int m = luckyEven[n - 1];\n        int end = (luckyEven.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n            luckyEven.pop_back();\n        }\n    }\n}\n\nvoid filterLuckyOdd() {\n    for (size_t n = 2; n < luckyOdd.size(); ++n) {\n        int m = luckyOdd[n - 1];\n        int end = (luckyOdd.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n            luckyOdd.pop_back();\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n\n    if (even) {\n        size_t max = luckyEven.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    } else {\n        size_t max = luckyOdd.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    }\n    std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n    if (even) {\n        if (k >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n    } else {\n        if (k >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n    }\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (j >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n    } else {\n        if (j >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n    }\n}\n\nvoid help() {\n    std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"       argument(s)        |  what is displayed\\n\";\n    std::cout << \"==============================================\\n\";\n    std::cout << \"-j=m                      |  mth lucky number\\n\";\n    std::cout << \"-j=m  --lucky             |  mth lucky number\\n\";\n    std::cout << \"-j=m  --evenLucky         |  mth even lucky number\\n\";\n    std::cout << \"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\";\n    std::cout << \"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    \n    if (argc < 2) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    bool good = false;\n    for (int i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n            exit(EXIT_FAILURE);\n        }\n    }\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    init();\n    filterLuckyEven();\n    filterLuckyOdd();\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n    for i := 0; i < luckySize; i++ {\n        luckyOdd[i] = i*2 + 1\n        luckyEven[i] = i*2 + 2\n    }\n}\n\nfunc filterLuckyOdd() {\n    for n := 2; n < len(luckyOdd); n++ {\n        m := luckyOdd[n-1]\n        end := (len(luckyOdd)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyOdd[j:], luckyOdd[j+1:])\n            luckyOdd = luckyOdd[:len(luckyOdd)-1]\n        }\n    }\n}\n\nfunc filterLuckyEven() {\n    for n := 2; n < len(luckyEven); n++ {\n        m := luckyEven[n-1]\n        end := (len(luckyEven)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyEven[j:], luckyEven[j+1:])\n            luckyEven = luckyEven[:len(luckyEven)-1]\n        }\n    }\n}\n\nfunc printSingle(j int, odd bool) error {\n    if odd {\n        if j >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n    } else {\n        if j >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n    }\n    return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n    if odd {\n        if k >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyOdd[j-1 : k])\n    } else {\n        if k >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyEven[j-1 : k])\n    }\n    return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n    var r []int\n    if odd {\n        max := luckyOdd[len(luckyOdd)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyOdd {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    } else {\n        max := luckyEven[len(luckyEven)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyEven {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    }\n    return nil\n}\n\nfunc main() {\n    nargs := len(os.Args)\n    if nargs < 2 || nargs > 4 {\n        log.Fatal(\"there must be between 1 and 3 command line arguments\")\n    }\n    filterLuckyOdd()\n    filterLuckyEven()\n    j, err := strconv.Atoi(os.Args[1])\n    if err != nil || j < 1 {\n        log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n    }\n    if nargs == 2 {\n        if err := printSingle(j, true); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    if nargs == 3 {\n        k, err := strconv.Atoi(os.Args[2])\n        if err != nil {\n            log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n        }\n        if k >= 0 {\n            if j > k {\n                log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n            }\n            if err := printRange(j, k, true); err != nil {\n                log.Fatal(err)\n            }\n        } else {\n            l := -k\n            if j > l {\n                log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n            }\n            if err := printBetween(j, l, true); err != nil {\n                log.Fatal(err)\n            }\n        }\n        return\n    }\n\n    var odd bool\n    switch lucky := strings.ToLower(os.Args[3]); lucky {\n    case \"lucky\":\n        odd = true\n    case \"evenlucky\":\n        odd = false\n    default:\n        log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n    }\n    if os.Args[2] == \",\" {\n        if err := printSingle(j, odd); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    k, err := strconv.Atoi(os.Args[2])\n    if err != nil {\n        log.Fatal(\"second argument must be an integer or a comma\")\n    }\n    if k >= 0 {\n        if j > k {\n            log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n        }\n        if err := printRange(j, k, odd); err != nil {\n            log.Fatal(err)\n        }\n    } else {\n        l := -k\n        if j > l {\n            log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n        }\n        if err := printBetween(j, l, odd); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n"}
{"id": 49628, "name": "Brace expansion", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 49629, "name": "Superpermutation minimisation", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n"}
{"id": 49630, "name": "GUI component interaction", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 49631, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 49632, "name": "Summarize and say sequence", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n"}
{"id": 49633, "name": "Spelling of ordinal numbers", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": 49634, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 49635, "name": "Addition chains", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n"}
{"id": 49636, "name": "Numeric separator syntax", "C++": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n"}
{"id": 49637, "name": "Repeat", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 49638, "name": "Sparkline in unicode", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n"}
{"id": 49639, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 49640, "name": "Sunflower fractal", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n"}
{"id": 49641, "name": "Vogel's approximation method", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 49642, "name": "Chemical calculator", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n"}
{"id": 49643, "name": "Permutations by swapping", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n"}
{"id": 49644, "name": "Minimum multiple of m where digital sum equals m", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n"}
{"id": 49645, "name": "Minimum multiple of m where digital sum equals m", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n"}
{"id": 49646, "name": "Pythagorean quadruples", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n"}
{"id": 49647, "name": "Steady squares", "C++": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc contains(list []int, s int) bool {\n    for _, e := range list {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"Steady squares under 10,000:\")\n    finalDigits := []int{1, 5, 6}\n    for i := 1; i < 10000; i++ {\n        if !contains(finalDigits, i%10) {\n            continue\n        }\n        sq := i * i\n        sqs := strconv.Itoa(sq)\n        is := strconv.Itoa(i)\n        if strings.HasSuffix(sqs, is) {\n            fmt.Printf(\"%5s -> %10s\\n\", rcu.Commatize(i), rcu.Commatize(sq))\n        }\n    }\n}\n"}
{"id": 49648, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 49649, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 49650, "name": "Dice game probabilities", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n"}
{"id": 49651, "name": "First-class functions_Use numbers analogously", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 49652, "name": "First-class functions_Use numbers analogously", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 49653, "name": "Sokoban", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n"}
{"id": 49654, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 49655, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 49656, "name": "Practical numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n"}
{"id": 49657, "name": "Practical numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n"}
{"id": 49658, "name": "Consecutive primes with ascending or descending differences", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n    pd := 0\n    longSeqs := [][]int{{2}}\n    currSeq := []int{2}\n    for i := 1; i < len(primes); i++ {\n        d := primes[i] - primes[i-1]\n        if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n            if len(currSeq) > len(longSeqs[0]) {\n                longSeqs = [][]int{currSeq}\n            } else if len(currSeq) == len(longSeqs[0]) {\n                longSeqs = append(longSeqs, currSeq)\n            }\n            currSeq = []int{primes[i-1], primes[i]}\n        } else {\n            currSeq = append(currSeq, primes[i])\n        }\n        pd = d\n    }\n    if len(currSeq) > len(longSeqs[0]) {\n        longSeqs = [][]int{currSeq}\n    } else if len(currSeq) == len(longSeqs[0]) {\n        longSeqs = append(longSeqs, currSeq)\n    }\n    fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n    for _, ls := range longSeqs {\n        var diffs []int\n        for i := 1; i < len(ls); i++ {\n            diffs = append(diffs, ls[i]-ls[i-1])\n        }\n        for i := 0; i < len(ls)-1; i++ {\n            fmt.Print(ls[i], \" (\", diffs[i], \") \")\n        }\n        fmt.Println(ls[len(ls)-1])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    fmt.Println(\"For primes < 1 million:\\n\")\n    for _, dir := range []string{\"ascending\", \"descending\"} {\n        longestSeq(dir)\n    }\n}\n"}
{"id": 49659, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 49660, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 49661, "name": "Erdős-primes", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 49662, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 49663, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 49664, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 49665, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 49666, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 49667, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 49668, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 49669, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 49670, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 49671, "name": "Word search", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n"}
{"id": 49672, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 49673, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 49674, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 49675, "name": "Object serialization", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 49676, "name": "Object serialization", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 49677, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 49678, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 49679, "name": "Long year", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 49680, "name": "Zumkeller numbers", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 49681, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 49682, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 49683, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 49684, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 49685, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 49686, "name": "Halt and catch fire", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n"}
{"id": 49687, "name": "Halt and catch fire", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n"}
{"id": 49688, "name": "Constrained genericity", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n", "Go": "type eatable interface {\n    eat()\n}\n"}
{"id": 49689, "name": "Constrained genericity", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n", "Go": "type eatable interface {\n    eat()\n}\n"}
{"id": 49690, "name": "Markov chain text generator", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 49691, "name": "Dijkstra's algorithm", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 49692, "name": "Geometric algebra", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n"}
{"id": 49693, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 49694, "name": "Suffix tree", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 49695, "name": "Associative array_Iteration", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 49696, "name": "Define a primitive data type", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n"}
{"id": 49697, "name": "AVL tree", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n"}
{"id": 49698, "name": "AVL tree", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n"}
{"id": 49699, "name": "Arithmetic derivative", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\ntemplate <typename IntegerType>\nIntegerType arithmetic_derivative(IntegerType n) {\n    bool negative = n < 0;\n    if (negative)\n        n = -n;\n    if (n < 2)\n        return 0;\n    IntegerType sum = 0, count = 0, m = n;\n    while ((m & 1) == 0) {\n        m >>= 1;\n        count += n;\n    }\n    if (count > 0)\n        sum += count / 2;\n    for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {\n        count = 0;\n        while (m % p == 0) {\n            m /= p;\n            count += n;\n        }\n        if (count > 0)\n            sum += count / p;\n        sq += (p + 1) << 2;\n    }\n    if (m > 1)\n        sum += n / m;\n    if (negative)\n        sum = -sum;\n    return sum;\n}\n\nint main() {\n    using boost::multiprecision::int128_t;\n\n    for (int n = -99, i = 0; n <= 100; ++n, ++i) {\n        std::cout << std::setw(4) << arithmetic_derivative(n)\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    int128_t p = 10;\n    std::cout << '\\n';\n    for (int i = 0; i < 20; ++i, p *= 10) {\n        std::cout << \"D(10^\" << std::setw(2) << i + 1\n                  << \") / 7 = \" << arithmetic_derivative(p) / 7 << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc D(n float64) float64 {\n    if n < 0 {\n        return -D(-n)\n    }\n    if n < 2 {\n        return 0\n    }\n    var f []int\n    if n < 1e19 {\n        f = rcu.PrimeFactors(int(n))\n    } else {\n        g := int(n / 100)\n        f = rcu.PrimeFactors(g)\n        f = append(f, []int{2, 2, 5, 5}...)\n    }\n    c := len(f)\n    if c == 1 {\n        return 1\n    }\n    if c == 2 {\n        return float64(f[0] + f[1])\n    }\n    d := n / float64(f[0])\n    return D(d)*float64(f[0]) + d\n}\n\nfunc main() {\n    ad := make([]int, 200)\n    for n := -99; n < 101; n++ {\n        ad[n+99] = int(D(float64(n)))\n    }\n    rcu.PrintTable(ad, 10, 4, false)\n    fmt.Println()\n    pow := 1.0\n    for m := 1; m < 21; m++ {\n        pow *= 10\n        fmt.Printf(\"D(10^%-2d) / 7 = %.0f\\n\", m, D(pow)/7)\n    }\n}\n"}
{"id": 49700, "name": "Permutations with some identical elements", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n    std::string str(\"AABBBC\");\n    int count = 0;\n    do {\n        std::cout << str << (++count % 10 == 0 ? '\\n' : ' ');\n    } while (std::next_permutation(str.begin(), str.end()));\n}\n", "Go": "package main\n\nimport \"fmt\"\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 createSlice(nums []int, charSet string) []byte {\n    var chars []byte\n    for i := 0; i < len(nums); i++ {\n        for j := 0; j < nums[i]; j++ {\n            chars = append(chars, charSet[i])\n        }\n    }\n    return chars\n}\n\nfunc main() {\n    var res, res2, res3 []string\n    nums := []int{2, 1}\n    s := createSlice(nums, \"12\")\n    findPerms(s, 0, len(s), &res)\n    fmt.Println(res)\n    fmt.Println()\n\n    nums = []int{2, 3, 1}\n    s = createSlice(nums, \"123\")\n    findPerms(s, 0, len(s), &res2)\n    fmt.Println(res2)\n    fmt.Println()\n\n    s = createSlice(nums, \"ABC\")\n    findPerms(s, 0, len(s), &res3)\n    fmt.Println(res3)\n}\n"}
{"id": 49701, "name": "Penrose tiling", "C++": "#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n\nint main() {\n    std::ofstream out(\"penrose_tiling.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string penrose(\"[N]++[N]++[N]++[N]++[N]\");\n    for (int i = 1; i <= 4; ++i) {\n        std::string next;\n        for (char ch : penrose) {\n            switch (ch) {\n            case 'A':\n                break;\n            case 'M':\n                next += \"OA++PA----NA[-OA----MA]++\";\n                break;\n            case 'N':\n                next += \"+OA--PA[---MA--NA]+\";\n                break;\n            case 'O':\n                next += \"-MA++NA[+++OA++PA]-\";\n                break;\n            case 'P':\n                next += \"--OA++++MA[+PA++++NA]--NA\";\n                break;\n            default:\n                next += ch;\n                break;\n            }\n        }\n        penrose = std::move(next);\n    }\n    const double r = 30;\n    const double pi5 = 0.628318530717959;\n    double x = r * 8, y = r * 8, theta = pi5;\n    std::set<std::string> svg;\n    std::stack<std::tuple<double, double, double>> stack;\n    for (char ch : penrose) {\n        switch (ch) {\n        case 'A': {\n            double nx = x + r * std::cos(theta);\n            double ny = y + r * std::sin(theta);\n            std::ostringstream line;\n            line << std::fixed << std::setprecision(3) << \"<line x1='\" << x\n                 << \"' y1='\" << y << \"' x2='\" << nx << \"' y2='\" << ny << \"'/>\";\n            svg.insert(line.str());\n            x = nx;\n            y = ny;\n        } break;\n        case '+':\n            theta += pi5;\n            break;\n        case '-':\n            theta -= pi5;\n            break;\n        case '[':\n            stack.push({x, y, theta});\n            break;\n        case ']':\n            std::tie(x, y, theta) = stack.top();\n            stack.pop();\n            break;\n        }\n    }\n    out << \"<svg xmlns='http:\n        << \"' width='\" << r * 16 << \"'>\\n\"\n        << \"<rect height='100%' width='100%' fill='black'/>\\n\"\n        << \"<g stroke='rgb(255,165,0)'>\\n\";\n    for (const auto& line : svg)\n        out << line << '\\n';\n    out << \"</g>\\n</svg>\\n\";\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\ntype tiletype int\n\nconst (\n    kite tiletype = iota\n    dart\n)\n\ntype tile struct {\n    tt          tiletype\n    x, y        float64\n    angle, size float64\n}\n\nvar gr = (1 + math.Sqrt(5)) / 2 \n\nconst theta = math.Pi / 5 \n\nfunc setupPrototiles(w, h int) []tile {\n    var proto []tile\n    \n    for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {\n        ww := float64(w / 2)\n        hh := float64(h / 2)\n        proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})\n    }\n    return proto\n}\n\nfunc distinctTiles(tls []tile) []tile {\n    tileset := make(map[tile]bool)\n    for _, tl := range tls {\n        tileset[tl] = true\n    }\n    distinct := make([]tile, len(tileset))\n    for tl, _ := range tileset {\n        distinct = append(distinct, tl)\n    }\n    return distinct\n}\n\nfunc deflateTiles(tls []tile, gen int) []tile {\n    if gen <= 0 {\n        return tls\n    }\n    var next []tile\n    for _, tl := range tls {\n        x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr\n        var nx, ny float64\n        if tl.tt == dart {\n            next = append(next, tile{kite, x, y, a + 5*theta, size})\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                nx = x + math.Cos(a-4*theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-4*theta*sign)*gr*tl.size\n                next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})\n            }\n        } else {\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                next = append(next, tile{dart, x, y, a - 4*theta*sign, size})\n                nx = x + math.Cos(a-theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-theta*sign)*gr*tl.size\n                next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})\n            }\n        }\n    }\n    \n    tls = distinctTiles(next)\n    return deflateTiles(tls, gen-1)\n}\n\nfunc drawTiles(dc *gg.Context, tls []tile) {\n    dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}\n    for _, tl := range tls {\n        angle := tl.angle - theta\n        dc.MoveTo(tl.x, tl.y)\n        ord := tl.tt\n        for i := 0; i < 3; i++ {\n            x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)\n            y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)\n            dc.LineTo(x, y)\n            angle += theta\n        }\n        dc.ClosePath()\n        if ord == kite {\n            dc.SetHexColor(\"FFA500\") \n        } else {\n            dc.SetHexColor(\"FFFF00\") \n        }\n        dc.FillPreserve()\n        dc.SetHexColor(\"A9A9A9\") \n        dc.SetLineWidth(1)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    w, h := 700, 450\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    tiles := deflateTiles(setupPrototiles(w, h), 5)\n    drawTiles(dc, tiles)\n    dc.SavePNG(\"penrose_tiling.png\")\n}\n"}
{"id": 49702, "name": "Greed", "C++": "#include <windows.h>\n#include <iostream>\n#include <ctime>\n\nconst int WID = 79, HEI = 22;\nconst float NCOUNT = ( float )( WID * HEI );\n\nclass coord : public COORD {\npublic:\n    coord( short x = 0, short y = 0 ) { set( x, y ); }\n    void set( short x, short y ) { X = x; Y = y; }\n};\nclass winConsole {\npublic:\n    static winConsole* getInstamnce() { if( 0 == inst ) { inst = new winConsole(); } return inst; }\n    void showCursor( bool s ) { CONSOLE_CURSOR_INFO ci = { 1, s }; SetConsoleCursorInfo( conOut, &ci ); }\n    void setColor( WORD clr ) { SetConsoleTextAttribute( conOut, clr ); }\n    void setCursor( coord p ) { SetConsoleCursorPosition( conOut, p ); }\n    void flush() { FlushConsoleInputBuffer( conIn ); }\n    void kill() { delete inst; }\nprivate:\n    winConsole() { conOut = GetStdHandle( STD_OUTPUT_HANDLE ); \n                   conIn  = GetStdHandle( STD_INPUT_HANDLE ); showCursor( false ); }\n    static winConsole* inst;\n    HANDLE conOut, conIn;\n};\nclass greed {\npublic:\n    greed() { console = winConsole::getInstamnce(); }\n    ~greed() { console->kill(); }\n    void play() {\n        char g; do {\n            console->showCursor( false ); createBoard();\n            do { displayBoard(); getInput(); } while( existsMoves() );\n            displayBoard(); console->setCursor( coord( 0, 24 ) ); console->setColor( 0x07 );\n            console->setCursor( coord( 19,  8 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 19,  9 ) ); std::cout << \"|               GAME OVER                |\";\n            console->setCursor( coord( 19, 10 ) ); std::cout << \"|            PLAY AGAIN(Y/N)?            |\";\n            console->setCursor( coord( 19, 11 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 48, 10 ) ); console->showCursor( true ); console->flush(); std::cin >> g;\n        } while( g == 'Y' || g == 'y' );\n    }\nprivate:\n    void createBoard() {\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                brd[x + WID * y] = rand() % 9 + 1;\n            }\n        }\n        cursor.set( rand() % WID, rand() % HEI );\n        brd[cursor.X + WID * cursor.Y] = 0; score = 0;\n        printScore();\n    }\n    void displayBoard() {\n        console->setCursor( coord() ); int i;\n\t\tfor( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                i = brd[x + WID * y]; console->setColor( 6 + i );\n                if( !i ) std::cout << \" \"; else std::cout << i;\n            }\n            std::cout << \"\\n\";\n        }\n        console->setColor( 15 ); console->setCursor( cursor ); std::cout << \"@\";\n    }\n    void getInput() { \n        while( 1 ) {\n            if( ( GetAsyncKeyState( 'Q' ) & 0x8000 ) && cursor.X > 0 && cursor.Y > 0 ) { execute( -1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'W' ) & 0x8000 ) &&  cursor.Y > 0 ) { execute( 0, -1 ); break; }\n            if( ( GetAsyncKeyState( 'E' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y > 0 ) { execute( 1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'A' ) & 0x8000 ) && cursor.X > 0 ) { execute( -1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'D' ) & 0x8000 ) && cursor.X < WID - 1 ) { execute( 1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'Y' ) & 0x8000 ) && cursor.X > 0 && cursor.Y < HEI - 1 ) { execute( -1, 1 ); break; }\n            if( ( GetAsyncKeyState( 'X' ) & 0x8000 ) && cursor.Y < HEI - 1 ) { execute( 0, 1 ); break; }\n            if( ( GetAsyncKeyState( 'C' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y < HEI - 1 ) { execute( 1, 1 ); break; }\n        }\n        console->flush(); printScore();\n    }\n    void printScore() {\n        console->setCursor( coord( 0, 24 ) ); console->setColor( 0x2a );\n        std::cout << \"      SCORE: \" << score << \" : \" << score * 100.f / NCOUNT << \"%      \";\n    }\n    void execute( int x, int y ) {\n        int i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n        if( countSteps( i, x, y ) ) {\n            score += i;\n            while( i ) {\n                --i; cursor.X += x; cursor.Y += y;\n                brd[cursor.X + WID * cursor.Y] = 0;\n            }\n        }\n    }\n    bool countSteps( int i, int x, int y ) {\n        coord t( cursor.X, cursor.Y );\n        while( i ) {\n            --i; t.X += x; t.Y += y;\n            if( t.X < 0 || t.Y < 0 || t.X >= WID || t.Y >= HEI || !brd[t.X + WID * t.Y] ) return false;\n        }\n        return true;\n    }\n    bool existsMoves() {\n        int i;\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n                if( i > 0 && countSteps( i, x, y ) ) return true;\n            }\n        }\n        return false;\n    }\n    winConsole* console;\n    int brd[WID * HEI];\n    float score; coord cursor;\n};\nwinConsole* winConsole::inst = 0;\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    SetConsoleTitle( \"Greed\" );\n    greed g; g.play(); return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"log\"\n    \"math/rand\"\n    \"strconv\"\n    \"time\"\n)\n\ntype coord struct{ x, y int }\n\nconst (\n    width  = 79\n    height = 22\n    nCount = float64(width * height)\n)\n\nvar (\n    board  [width * height]int\n    score  = 0\n    bold   = termbox.AttrBold\n    cursor coord\n)\n\nvar colors = [10]termbox.Attribute{\n    termbox.ColorDefault,\n    termbox.ColorWhite,\n    termbox.ColorBlack | bold,\n    termbox.ColorBlue | bold,\n    termbox.ColorGreen | bold,\n    termbox.ColorCyan | bold,\n    termbox.ColorRed | bold,\n    termbox.ColorMagenta | bold,\n    termbox.ColorYellow | bold,\n    termbox.ColorWhite | bold,\n}\n\nfunc printAt(x, y int, s string, fg, bg termbox.Attribute) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, fg, bg)\n        x++\n    }\n}\n\nfunc createBoard() {\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            board[x+width*y] = rand.Intn(9) + 1\n        }\n    }\n    cursor = coord{rand.Intn(width), rand.Intn(height)}\n    board[cursor.x+width*cursor.y] = 0\n    score = 0\n    printScore()\n}\n\nfunc displayBoard() {\n    termbox.SetCursor(0, 0)\n    bg := colors[0]\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            i := board[x+width*y]\n            fg := colors[i]\n            s := \" \"\n            if i > 0 {\n                s = strconv.Itoa(i)\n            }\n            printAt(x, y, s, fg, bg)\n        }\n    }\n    fg := colors[9]\n    termbox.SetCursor(cursor.x, cursor.y)\n    printAt(cursor.x, cursor.y, \"@\", fg, bg)\n    termbox.Flush()\n}\n\nfunc printScore() {\n    termbox.SetCursor(0, 24)\n    fg := colors[4]\n    bg := termbox.ColorGreen\n    s := fmt.Sprintf(\"      SCORE: %d : %.3f%%      \", score, float64(score)*100.0/nCount)\n    printAt(0, 24, s, fg, bg)\n    termbox.Flush()\n}\n\nfunc execute(x, y int) {\n    i := board[cursor.x+x+width*(cursor.y+y)]\n    if countSteps(i, x, y) {\n        score += i\n        for i != 0 {\n            i--\n            cursor.x += x\n            cursor.y += y\n            board[cursor.x+width*cursor.y] = 0\n        }\n    }\n}\n\nfunc countSteps(i, x, y int) bool {\n    t := cursor\n    for i != 0 {\n        i--\n        t.x += x\n        t.y += y\n        if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc existsMoves() bool {\n    for y := -1; y < 2; y++ {\n        for x := -1; x < 2; x++ {\n            if x == 0 && y == 0 {\n                continue\n            }\n            ix := cursor.x + x + width*(cursor.y+y)\n            i := 0\n            if ix >= 0 && ix < len(board) {\n                i = board[ix]\n            }\n            if i > 0 && countSteps(i, x, y) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    for {\n        termbox.HideCursor()\n        createBoard()\n        for {\n            displayBoard()\n            select {\n            case ev := <-eventQueue:\n                if ev.Type == termbox.EventKey {\n                    switch ev.Ch {\n                    case 'q', 'Q':\n                        if cursor.x > 0 && cursor.y > 0 {\n                            execute(-1, -1)\n                        }\n                    case 'w', 'W':\n                        if cursor.y > 0 {\n                            execute(0, -1)\n                        }\n                    case 'e', 'E':\n                        if cursor.x < width-1 && cursor.y > 0 {\n                            execute(1, -1)\n                        }\n                    case 'a', 'A':\n                        if cursor.x > 0 {\n                            execute(-1, 0)\n                        }\n                    case 'd', 'D':\n                        if cursor.x < width-1 {\n                            execute(1, 0)\n                        }\n                    case 'z', 'Z':\n                        if cursor.x > 0 && cursor.y < height-1 {\n                            execute(-1, 1)\n                        }\n                    case 'x', 'X':\n                        if cursor.y < height-1 {\n                            execute(0, 1)\n                        }\n                    case 'c', 'C':\n                        if cursor.x < width-1 && cursor.y < height-1 {\n                            execute(1, 1)\n                        }\n                    case 'l', 'L': \n                        return\n                    }\n                } else if ev.Type == termbox.EventResize {\n                    termbox.Flush()\n                }\n            }\n            printScore()\n            if !existsMoves() {\n                break\n            }\n        }\n        displayBoard()\n        fg := colors[7]\n        bg := colors[0]\n        printAt(19, 8, \"+----------------------------------------+\", fg, bg)\n        printAt(19, 9, \"|               GAME OVER                |\", fg, bg)\n        printAt(19, 10, \"|            PLAY AGAIN(Y/N)?            |\", fg, bg)\n        printAt(19, 11, \"+----------------------------------------+\", fg, bg)\n        termbox.SetCursor(48, 10)\n        termbox.Flush()\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'y' || ev.Ch == 'Y' {\n                    break\n                } else {\n                    return\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49703, "name": "Greed", "C++": "#include <windows.h>\n#include <iostream>\n#include <ctime>\n\nconst int WID = 79, HEI = 22;\nconst float NCOUNT = ( float )( WID * HEI );\n\nclass coord : public COORD {\npublic:\n    coord( short x = 0, short y = 0 ) { set( x, y ); }\n    void set( short x, short y ) { X = x; Y = y; }\n};\nclass winConsole {\npublic:\n    static winConsole* getInstamnce() { if( 0 == inst ) { inst = new winConsole(); } return inst; }\n    void showCursor( bool s ) { CONSOLE_CURSOR_INFO ci = { 1, s }; SetConsoleCursorInfo( conOut, &ci ); }\n    void setColor( WORD clr ) { SetConsoleTextAttribute( conOut, clr ); }\n    void setCursor( coord p ) { SetConsoleCursorPosition( conOut, p ); }\n    void flush() { FlushConsoleInputBuffer( conIn ); }\n    void kill() { delete inst; }\nprivate:\n    winConsole() { conOut = GetStdHandle( STD_OUTPUT_HANDLE ); \n                   conIn  = GetStdHandle( STD_INPUT_HANDLE ); showCursor( false ); }\n    static winConsole* inst;\n    HANDLE conOut, conIn;\n};\nclass greed {\npublic:\n    greed() { console = winConsole::getInstamnce(); }\n    ~greed() { console->kill(); }\n    void play() {\n        char g; do {\n            console->showCursor( false ); createBoard();\n            do { displayBoard(); getInput(); } while( existsMoves() );\n            displayBoard(); console->setCursor( coord( 0, 24 ) ); console->setColor( 0x07 );\n            console->setCursor( coord( 19,  8 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 19,  9 ) ); std::cout << \"|               GAME OVER                |\";\n            console->setCursor( coord( 19, 10 ) ); std::cout << \"|            PLAY AGAIN(Y/N)?            |\";\n            console->setCursor( coord( 19, 11 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 48, 10 ) ); console->showCursor( true ); console->flush(); std::cin >> g;\n        } while( g == 'Y' || g == 'y' );\n    }\nprivate:\n    void createBoard() {\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                brd[x + WID * y] = rand() % 9 + 1;\n            }\n        }\n        cursor.set( rand() % WID, rand() % HEI );\n        brd[cursor.X + WID * cursor.Y] = 0; score = 0;\n        printScore();\n    }\n    void displayBoard() {\n        console->setCursor( coord() ); int i;\n\t\tfor( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                i = brd[x + WID * y]; console->setColor( 6 + i );\n                if( !i ) std::cout << \" \"; else std::cout << i;\n            }\n            std::cout << \"\\n\";\n        }\n        console->setColor( 15 ); console->setCursor( cursor ); std::cout << \"@\";\n    }\n    void getInput() { \n        while( 1 ) {\n            if( ( GetAsyncKeyState( 'Q' ) & 0x8000 ) && cursor.X > 0 && cursor.Y > 0 ) { execute( -1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'W' ) & 0x8000 ) &&  cursor.Y > 0 ) { execute( 0, -1 ); break; }\n            if( ( GetAsyncKeyState( 'E' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y > 0 ) { execute( 1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'A' ) & 0x8000 ) && cursor.X > 0 ) { execute( -1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'D' ) & 0x8000 ) && cursor.X < WID - 1 ) { execute( 1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'Y' ) & 0x8000 ) && cursor.X > 0 && cursor.Y < HEI - 1 ) { execute( -1, 1 ); break; }\n            if( ( GetAsyncKeyState( 'X' ) & 0x8000 ) && cursor.Y < HEI - 1 ) { execute( 0, 1 ); break; }\n            if( ( GetAsyncKeyState( 'C' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y < HEI - 1 ) { execute( 1, 1 ); break; }\n        }\n        console->flush(); printScore();\n    }\n    void printScore() {\n        console->setCursor( coord( 0, 24 ) ); console->setColor( 0x2a );\n        std::cout << \"      SCORE: \" << score << \" : \" << score * 100.f / NCOUNT << \"%      \";\n    }\n    void execute( int x, int y ) {\n        int i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n        if( countSteps( i, x, y ) ) {\n            score += i;\n            while( i ) {\n                --i; cursor.X += x; cursor.Y += y;\n                brd[cursor.X + WID * cursor.Y] = 0;\n            }\n        }\n    }\n    bool countSteps( int i, int x, int y ) {\n        coord t( cursor.X, cursor.Y );\n        while( i ) {\n            --i; t.X += x; t.Y += y;\n            if( t.X < 0 || t.Y < 0 || t.X >= WID || t.Y >= HEI || !brd[t.X + WID * t.Y] ) return false;\n        }\n        return true;\n    }\n    bool existsMoves() {\n        int i;\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n                if( i > 0 && countSteps( i, x, y ) ) return true;\n            }\n        }\n        return false;\n    }\n    winConsole* console;\n    int brd[WID * HEI];\n    float score; coord cursor;\n};\nwinConsole* winConsole::inst = 0;\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    SetConsoleTitle( \"Greed\" );\n    greed g; g.play(); return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"log\"\n    \"math/rand\"\n    \"strconv\"\n    \"time\"\n)\n\ntype coord struct{ x, y int }\n\nconst (\n    width  = 79\n    height = 22\n    nCount = float64(width * height)\n)\n\nvar (\n    board  [width * height]int\n    score  = 0\n    bold   = termbox.AttrBold\n    cursor coord\n)\n\nvar colors = [10]termbox.Attribute{\n    termbox.ColorDefault,\n    termbox.ColorWhite,\n    termbox.ColorBlack | bold,\n    termbox.ColorBlue | bold,\n    termbox.ColorGreen | bold,\n    termbox.ColorCyan | bold,\n    termbox.ColorRed | bold,\n    termbox.ColorMagenta | bold,\n    termbox.ColorYellow | bold,\n    termbox.ColorWhite | bold,\n}\n\nfunc printAt(x, y int, s string, fg, bg termbox.Attribute) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, fg, bg)\n        x++\n    }\n}\n\nfunc createBoard() {\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            board[x+width*y] = rand.Intn(9) + 1\n        }\n    }\n    cursor = coord{rand.Intn(width), rand.Intn(height)}\n    board[cursor.x+width*cursor.y] = 0\n    score = 0\n    printScore()\n}\n\nfunc displayBoard() {\n    termbox.SetCursor(0, 0)\n    bg := colors[0]\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            i := board[x+width*y]\n            fg := colors[i]\n            s := \" \"\n            if i > 0 {\n                s = strconv.Itoa(i)\n            }\n            printAt(x, y, s, fg, bg)\n        }\n    }\n    fg := colors[9]\n    termbox.SetCursor(cursor.x, cursor.y)\n    printAt(cursor.x, cursor.y, \"@\", fg, bg)\n    termbox.Flush()\n}\n\nfunc printScore() {\n    termbox.SetCursor(0, 24)\n    fg := colors[4]\n    bg := termbox.ColorGreen\n    s := fmt.Sprintf(\"      SCORE: %d : %.3f%%      \", score, float64(score)*100.0/nCount)\n    printAt(0, 24, s, fg, bg)\n    termbox.Flush()\n}\n\nfunc execute(x, y int) {\n    i := board[cursor.x+x+width*(cursor.y+y)]\n    if countSteps(i, x, y) {\n        score += i\n        for i != 0 {\n            i--\n            cursor.x += x\n            cursor.y += y\n            board[cursor.x+width*cursor.y] = 0\n        }\n    }\n}\n\nfunc countSteps(i, x, y int) bool {\n    t := cursor\n    for i != 0 {\n        i--\n        t.x += x\n        t.y += y\n        if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc existsMoves() bool {\n    for y := -1; y < 2; y++ {\n        for x := -1; x < 2; x++ {\n            if x == 0 && y == 0 {\n                continue\n            }\n            ix := cursor.x + x + width*(cursor.y+y)\n            i := 0\n            if ix >= 0 && ix < len(board) {\n                i = board[ix]\n            }\n            if i > 0 && countSteps(i, x, y) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    for {\n        termbox.HideCursor()\n        createBoard()\n        for {\n            displayBoard()\n            select {\n            case ev := <-eventQueue:\n                if ev.Type == termbox.EventKey {\n                    switch ev.Ch {\n                    case 'q', 'Q':\n                        if cursor.x > 0 && cursor.y > 0 {\n                            execute(-1, -1)\n                        }\n                    case 'w', 'W':\n                        if cursor.y > 0 {\n                            execute(0, -1)\n                        }\n                    case 'e', 'E':\n                        if cursor.x < width-1 && cursor.y > 0 {\n                            execute(1, -1)\n                        }\n                    case 'a', 'A':\n                        if cursor.x > 0 {\n                            execute(-1, 0)\n                        }\n                    case 'd', 'D':\n                        if cursor.x < width-1 {\n                            execute(1, 0)\n                        }\n                    case 'z', 'Z':\n                        if cursor.x > 0 && cursor.y < height-1 {\n                            execute(-1, 1)\n                        }\n                    case 'x', 'X':\n                        if cursor.y < height-1 {\n                            execute(0, 1)\n                        }\n                    case 'c', 'C':\n                        if cursor.x < width-1 && cursor.y < height-1 {\n                            execute(1, 1)\n                        }\n                    case 'l', 'L': \n                        return\n                    }\n                } else if ev.Type == termbox.EventResize {\n                    termbox.Flush()\n                }\n            }\n            printScore()\n            if !existsMoves() {\n                break\n            }\n        }\n        displayBoard()\n        fg := colors[7]\n        bg := colors[0]\n        printAt(19, 8, \"+----------------------------------------+\", fg, bg)\n        printAt(19, 9, \"|               GAME OVER                |\", fg, bg)\n        printAt(19, 10, \"|            PLAY AGAIN(Y/N)?            |\", fg, bg)\n        printAt(19, 11, \"+----------------------------------------+\", fg, bg)\n        termbox.SetCursor(48, 10)\n        termbox.Flush()\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'y' || ev.Ch == 'Y' {\n                    break\n                } else {\n                    return\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49704, "name": "Ruth-Aaron numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nint prime_factor_sum(int n) {\n    int sum = 0;\n    for (; (n & 1) == 0; n >>= 1)\n        sum += 2;\n    for (int p = 3, sq = 9; sq <= n; p += 2) {\n        for (; n % p == 0; n /= p)\n            sum += p;\n        sq += (p + 1) << 2;\n    }\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nint prime_divisor_sum(int n) {\n    int sum = 0;\n    if ((n & 1) == 0) {\n        sum += 2;\n        n >>= 1;\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3, sq = 9; sq <= n; p += 2) {\n        if (n % p == 0) {\n            sum += p;\n            n /= p;\n            while (n % p == 0)\n                n /= p;\n        }\n        sq += (p + 1) << 2;\n    }\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nint main() {\n    const int limit = 30;\n    int dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;\n\n    std::cout << \"First \" << limit << \" Ruth-Aaron numbers (factors):\\n\";\n    for (int n = 2, count = 0; count < limit; ++n) {\n        fsum2 = prime_factor_sum(n);\n        if (fsum1 == fsum2) {\n            ++count;\n            std::cout << std::setw(5) << n - 1\n                      << (count % 10 == 0 ? '\\n' : ' ');\n        }\n        fsum1 = fsum2;\n    }\n\n    std::cout << \"\\nFirst \" << limit << \" Ruth-Aaron numbers (divisors):\\n\";\n    for (int n = 2, count = 0; count < limit; ++n) {\n        dsum2 = prime_divisor_sum(n);\n        if (dsum1 == dsum2) {\n            ++count;\n            std::cout << std::setw(5) << n - 1\n                      << (count % 10 == 0 ? '\\n' : ' ');\n        }\n        dsum1 = dsum2;\n    }\n\n    dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;\n    for (int n = 2;; ++n) {\n        int fsum3 = prime_factor_sum(n);\n        if (fsum1 == fsum2 && fsum2 == fsum3) {\n            std::cout << \"\\nFirst Ruth-Aaron triple (factors): \" << n - 2\n                      << '\\n';\n            break;\n        }\n        fsum1 = fsum2;\n        fsum2 = fsum3;\n    }\n    for (int n = 2;; ++n) {\n        int dsum3 = prime_divisor_sum(n);\n        if (dsum1 == dsum2 && dsum2 == dsum3) {\n            std::cout << \"\\nFirst Ruth-Aaron triple (divisors): \" << n - 2\n                      << '\\n';\n            break;\n        }\n        dsum1 = dsum2;\n        dsum2 = dsum3;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc prune(a []int) []int {\n    prev := a[0]\n    b := []int{prev}\n    for i := 1; i < len(a); i++ {\n        if a[i] != prev {\n            b = append(b, a[i])\n            prev = a[i]\n        }\n    }\n    return b\n}\n\nfunc main() {\n    var resF, resD, resT, factors1 []int\n    factors2 := []int{2}\n    factors3 := []int{3}\n    var sum1, sum2, sum3 int = 0, 2, 3\n    var countF, countD, countT int\n    for n := 2; countT < 1 || countD < 30 || countF < 30; n++ {\n        factors1 = factors2\n        factors2 = factors3\n        factors3 = rcu.PrimeFactors(n + 2)\n        sum1 = sum2\n        sum2 = sum3\n        sum3 = rcu.SumInts(factors3)\n        if countF < 30 && sum1 == sum2 {\n            resF = append(resF, n)\n            countF++\n        }\n        if sum1 == sum2 && sum2 == sum3 {\n            resT = append(resT, n)\n            countT++\n        }\n        if countD < 30 {\n            factors4 := make([]int, len(factors1))\n            copy(factors4, factors1)\n            factors5 := make([]int, len(factors2))\n            copy(factors5, factors2)\n            factors4 = prune(factors4)\n            factors5 = prune(factors5)\n            if rcu.SumInts(factors4) == rcu.SumInts(factors5) {\n                resD = append(resD, n)\n                countD++\n            }\n        }\n    }\n    fmt.Println(\"First 30 Ruth-Aaron numbers (factors):\")\n    fmt.Println(resF)\n    fmt.Println(\"\\nFirst 30 Ruth-Aaron numbers (divisors):\")\n    fmt.Println(resD)\n    fmt.Println(\"\\nFirst Ruth-Aaron triple (factors):\")\n    fmt.Println(resT[0])\n\n    resT = resT[:0]\n    factors1 = factors1[:0]\n    factors2 = factors2[:1]\n    factors2[0] = 2\n    factors3 = factors3[:1]\n    factors3[0] = 3\n    countT = 0\n    for n := 2; countT < 1; n++ {\n        factors1 = factors2\n        factors2 = factors3\n        factors3 = prune(rcu.PrimeFactors(n + 2))\n        sum1 = sum2\n        sum2 = sum3\n        sum3 = rcu.SumInts(factors3)\n        if sum1 == sum2 && sum2 == sum3 {\n            resT = append(resT, n)\n            countT++\n        }\n    }\n    fmt.Println(\"\\nFirst Ruth-Aaron triple (divisors):\")\n    fmt.Println(resT[0])\n}\n"}
{"id": 49705, "name": "Duffinian numbers", "C++": "#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n\nbool duffinian(int n) {\n    if (n == 2)\n        return false;\n    int total = 1, power = 2, m = n;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    for (int p = 3; p * p <= n; p += 2) {\n        int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    if (m == n)\n        return false;\n    if (n > 1)\n        total *= n + 1;\n    return std::gcd(total, m) == 1;\n}\n\nint main() {\n    std::cout << \"First 50 Duffinian numbers:\\n\";\n    for (int n = 1, count = 0; count < 50; ++n) {\n        if (duffinian(n))\n            std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 50 Duffinian triplets:\\n\";\n    for (int n = 1, m = 0, count = 0; count < 50; ++n) {\n        if (duffinian(n))\n            ++m;\n        else\n            m = 0;\n        if (m == 3) {\n            std::ostringstream os;\n            os << '(' << n - 2 << \", \" << n - 1 << \", \" << n << ')';\n            std::cout << std::left << std::setw(24) << os.str()\n                      << (++count % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc main() {\n    limit := 200000 \n    d := rcu.PrimeSieve(limit-1, true)\n    d[1] = false\n    for i := 2; i < limit; i++ {\n        if !d[i] {\n            continue\n        }\n        if i%2 == 0 && !isSquare(i) && !isSquare(i/2) {\n            d[i] = false\n            continue\n        }\n        sigmaSum := rcu.SumInts(rcu.Divisors(i))\n        if rcu.Gcd(sigmaSum, i) != 1 {\n            d[i] = false\n        }\n    }\n\n    var duff []int\n    for i := 1; i < len(d); i++ {\n        if d[i] {\n            duff = append(duff, i)\n        }\n    }\n    fmt.Println(\"First 50 Duffinian numbers:\")\n    rcu.PrintTable(duff[0:50], 10, 3, false)\n\n    var triplets [][3]int\n    for i := 2; i < limit; i++ {\n        if d[i] && d[i-1] && d[i-2] {\n            triplets = append(triplets, [3]int{i - 2, i - 1, i})\n        }\n    }\n    fmt.Println(\"\\nFirst 56 Duffinian triplets:\")\n    for i := 0; i < 14; i++ {\n        s := fmt.Sprintf(\"%6v\", triplets[i*4:i*4+4])\n        fmt.Println(s[1 : len(s)-1])\n    }\n}\n"}
{"id": 49706, "name": "Sphenic numbers", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nstd::vector<int> prime_factors(int n) {\n    std::vector<int> factors;\n    if (n > 1 && (n & 1) == 0) {\n        factors.push_back(2);\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            factors.push_back(p);\n            while (n % p == 0)\n                n /= p;\n        }\n    }\n    if (n > 1)\n        factors.push_back(n);\n    return factors;\n}\n\nint main() {\n    const int limit = 1000000;\n    const int imax = limit / 6;\n    std::vector<bool> sieve = prime_sieve(imax + 1);\n    std::vector<bool> sphenic(limit + 1, false);\n    for (int i = 0; i <= imax; ++i) {\n        if (!sieve[i])\n            continue;\n        int jmax = std::min(imax, limit / (i * i));\n        if (jmax <= i)\n            break;\n        for (int j = i + 1; j <= jmax; ++j) {\n            if (!sieve[j])\n                continue;\n            int p = i * j;\n            int kmax = std::min(imax, limit / p);\n            if (kmax <= j)\n                break;\n            for (int k = j + 1; k <= kmax; ++k) {\n                if (!sieve[k])\n                    continue;\n                assert(p * k <= limit);\n                sphenic[p * k] = true;\n            }\n        }\n    }\n\n    std::cout << \"Sphenic numbers < 1000:\\n\";\n    for (int i = 0, n = 0; i < 1000; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++n;\n        std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n    for (int i = 0, n = 0; i < 10000; ++i) {\n        if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n            ++n;\n            std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n                      << (n % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n\n    int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n    for (int i = 0; i < limit; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++count;\n        if (count == 200000)\n            s200000 = i;\n        if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n            ++triplets;\n            if (triplets == 5000)\n                t5000 = i;\n        }\n    }\n\n    std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n    std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n    auto factors = prime_factors(s200000);\n    assert(factors.size() == 3);\n    std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n              << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n              << '\\n';\n\n    std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n              << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = 1000000\n    limit2 := int(math.Cbrt(limit)) \n    primes := rcu.Primes(limit / 6)\n    pc := len(primes)\n    var sphenic []int\n    fmt.Println(\"Sphenic numbers less than 1,000:\")\n    for i := 0; i < pc-2; i++ {\n        if primes[i] > limit2 {\n            break\n        }\n        for j := i + 1; j < pc-1; j++ {\n            prod := primes[i] * primes[j]\n            if prod+primes[j+1] >= limit {\n                break\n            }\n            for k := j + 1; k < pc; k++ {\n                res := prod * primes[k]\n                if res >= limit {\n                    break\n                }\n                sphenic = append(sphenic, res)\n            }\n        }\n    }\n    sort.Ints(sphenic)\n    ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })\n    rcu.PrintTable(sphenic[:ix], 15, 3, false)\n    fmt.Println(\"\\nSphenic triplets less than 10,000:\")\n    var triplets [][3]int\n    for i := 0; i < len(sphenic)-2; i++ {\n        s := sphenic[i]\n        if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {\n            triplets = append(triplets, [3]int{s, s + 1, s + 2})\n        }\n    }\n    ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })\n    for i := 0; i < ix; i++ {\n        fmt.Printf(\"%4d \", triplets[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThere are %s sphenic numbers less than 1,000,000.\\n\", rcu.Commatize(len(sphenic)))\n    fmt.Printf(\"There are %s sphenic triplets less than 1,000,000.\\n\", rcu.Commatize(len(triplets)))\n    s := sphenic[199999]\n    pf := rcu.PrimeFactors(s)\n    fmt.Printf(\"The 200,000th sphenic number is %s (%d*%d*%d).\\n\", rcu.Commatize(s), pf[0], pf[1], pf[2])\n    fmt.Printf(\"The 5,000th sphenic triplet is %v.\\n.\", triplets[4999])\n}\n"}
{"id": 49707, "name": "Tree from nesting levels", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n"}
{"id": 49708, "name": "Tree from nesting levels", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n"}
{"id": 49709, "name": "Recursive descent parser generator", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <map>\n#include <set>\n#include <regex>\nusing namespace std;\n\nmap<string, string> terminals;\nmap<string, vector<vector<string>>> nonterminalRules;\nmap<string, set<string>> nonterminalFirst;\nmap<string, vector<string>> nonterminalCode;\n\nint main(int argc, char **argv) {\n\tif (argc < 3) {\n\t\tcout << \"Usage: <input file> <output file>\" << endl;\n\t\treturn 1;\n\t}\n\n\tifstream inFile(argv[1]);\n\tofstream outFile(argv[2]);\n\n\tregex blankLine(R\"(^\\s*$)\");\n\tregex terminalPattern(R\"((\\w+)\\s+(.+))\");\n\tregex rulePattern(R\"(^!!\\s*(\\w+)\\s*->\\s*((?:\\w+\\s*)*)$)\");\n\tregex argPattern(R\"(\\$(\\d+))\");\n\tsmatch results;\n\n\t\n\tstring line;\n\twhile (true) {\n\t\tgetline(inFile, line);\n\n\t\t\n\t\tif (regex_match(line, blankLine))\n\t\t\tbreak;\n\n\t\tregex_match(line, results, terminalPattern);\n\t\tterminals[results[1]] = results[2];\n\t}\n\n\toutFile << \"#include <iostream>\" << endl;\n\toutFile << \"#include <fstream>\" << endl;\n\toutFile << \"#include <string>\" << endl;\n\toutFile << \"#include <regex>\" << endl;\n\toutFile << \"using namespace std;\" << endl << endl;\n\n\t\n\toutFile << \"string input, nextToken, nextTokenValue;\" << endl;\n\toutFile << \"string prevToken, prevTokenValue;\" << endl << endl;\n\n\toutFile << \"void advanceToken() {\" << endl;\n\toutFile << \"\tstatic smatch results;\" << endl << endl;\n\n\toutFile << \"\tprevToken = nextToken;\" << endl;\n\toutFile << \"\tprevTokenValue = nextTokenValue;\" << endl << endl;\n\n\tfor (auto i = terminals.begin(); i != terminals.end(); ++i) {\n\t\tstring name = i->first + \"_pattern\";\n\t\tstring pattern = i->second;\n\n\t\toutFile << \"\tstatic regex \" << name << \"(R\\\"(^\\\\s*(\" << pattern << \"))\\\");\" << endl;\n\t\toutFile << \"\tif (regex_search(input, results, \" << name << \", regex_constants::match_continuous)) {\" << endl;\n\t\toutFile << \"\t\tnextToken = \\\"\" << i->first << \"\\\";\" << endl;\n\t\toutFile << \"\t\tnextTokenValue = results[1];\" << endl;\n\t\toutFile << \"\t\tinput = regex_replace(input, \" << name << \", \\\"\\\");\" << endl;\n\t\toutFile << \"\t\treturn;\" << endl;\n\t\toutFile << \"\t}\" << endl << endl;\n\t}\n\n\toutFile << \"\tstatic regex eof(R\\\"(\\\\s*)\\\");\" << endl;\n\toutFile << \"\tif (regex_match(input, results, eof, regex_constants::match_continuous)) {\" << endl;\n\toutFile << \"\t\tnextToken = \\\"\\\";\" << endl;\n\toutFile << \"\t\tnextTokenValue = \\\"\\\";\" << endl;\n\toutFile << \"\t\treturn;\" << endl;\n\toutFile << \"\t}\" << endl << endl;\n\n\toutFile << \"\tthrow \\\"Unknown token\\\";\" << endl;\n\toutFile << \"}\" << endl << endl;\n\n\toutFile << \"bool same(string symbol) {\" << endl;\n\toutFile << \"\tif (symbol == nextToken) {\" << endl;\n\toutFile << \"\t\tadvanceToken();\" << endl;\n\toutFile << \"\t\treturn true;\" << endl;\n\toutFile << \"\t}\" << endl;\n\toutFile << \"\treturn false;\" << endl;\n\toutFile << \"}\" << endl << endl;\n\n\t\n\twhile (true) {\n\t\tgetline(inFile, line);\n\t\t\n\t\t\n\t\tif (regex_match(line, results, rulePattern))\n\t\t\tbreak;\n\n\t\toutFile << line << endl;\n\t}\n\n\t\n\twhile (true) {\n\t\t\n\t\tstring name = results[1];\n\t\tstringstream ss(results[2]);\n\n\t\tstring tempString;\n\t\tvector<string> tempVector;\n\t\twhile (ss >> tempString)\n\t\t\ttempVector.push_back(tempString);\n\t\tnonterminalRules[name].push_back(tempVector);\n\n\t\t\n\t\tstring code = \"\";\n\t\twhile (true) {\n\t\t\tgetline(inFile, line);\n\n\t\t\tif (!inFile || regex_match(line, results, rulePattern))\n\t\t\t\tbreak;\n\n\t\t\t\n\t\t\tline = regex_replace(line, argPattern, \"results[$1]\");\n\n\t\t\tcode += line + \"\\n\";\n\t\t}\n\t\tnonterminalCode[name].push_back(code);\n\n\t\t\n\t\tif (!inFile)\n\t\t\tbreak;\n\t}\n\n\t\n\tbool done = false;\n\twhile (!done)\n\t\tfor (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {\n\t\t\tstring name = i->first;\n\t\t\tdone = true; \n\n\t\t\tif (nonterminalFirst.find(i->first) == nonterminalFirst.end())\n\t\t\t\tnonterminalFirst[i->first] = set<string>();\n\n\t\t\tfor (int j = 0; j < i->second.size(); ++j) {\n\t\t\t\tif (i->second[j].size() == 0)\n\t\t\t\t\tnonterminalFirst[i->first].insert(\"\");\n\t\t\t\telse {\n\t\t\t\t\tstring first = i->second[j][0];\n\t\t\t\t\tif (nonterminalFirst.find(first) != nonterminalFirst.end()) {\n\t\t\t\t\t\tfor (auto k = nonterminalFirst[first].begin(); k != nonterminalFirst[first].end(); ++k) {\n\t\t\t\t\t\t\tif (nonterminalFirst[name].find(*k) == nonterminalFirst[name].end()) {\n\t\t\t\t\t\t\t\tnonterminalFirst[name].insert(*k);\n\t\t\t\t\t\t\t\tdone = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (nonterminalFirst[name].find(first) == nonterminalFirst[name].end()) {\n\t\t\t\t\t\tnonterminalFirst[name].insert(first);\n\t\t\t\t\t\tdone = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\n\tfor (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {\n\t\tstring name = i->first + \"_rule\";\n\t\toutFile << \"string \" << name << \"();\" << endl;\n\t}\n\toutFile << endl;\n\n\t\n\tfor (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {\n\t\tstring name = i->first + \"_rule\";\n\t\toutFile << \"string \" << name << \"() {\" << endl;\n\t\toutFile << \"\tvector<string> results;\" << endl;\n\t\toutFile << \"\tresults.push_back(\\\"\\\");\" << endl << endl;\n\t\t\n\t\t\n\t\tint epsilon = -1;\n\t\tfor (int j = 0; epsilon == -1 && j < i->second.size(); ++j)\n\t\t\tif (i->second[j].size() == 0)\n\t\t\t\tepsilon = j;\n\n\t\t\n\t\tfor (int j = 0; j < i->second.size(); ++j) {\n\t\t\t\n\t\t\tif (j == epsilon)\n\t\t\t\tcontinue;\n\n\t\t\tstring token = i->second[j][0];\n\t\t\tif (terminals.find(token) != terminals.end())\n\t\t\t\toutFile << \"\tif (nextToken == \\\"\" << i->second[j][0] << \"\\\") {\" << endl;\n\t\t\telse {\n\t\t\t\toutFile << \"\tif (\";\n\t\t\t\tbool first = true;\n\t\t\t\tfor (auto k = nonterminalFirst[token].begin(); k != nonterminalFirst[token].end(); ++k, first = false) {\n\t\t\t\t\tif (!first)\n\t\t\t\t\t\toutFile << \" || \";\n\t\t\t\t\toutFile << \"nextToken == \\\"\" << (*k) << \"\\\"\";\n\t\t\t\t}\n\t\t\t\toutFile << \") {\" << endl;\n\t\t\t}\n\t\t\t\n\t\t\tfor (int k = 0; k < i->second[j].size(); ++k) {\n\t\t\t\tif (terminals.find(i->second[j][k]) != terminals.end()) {\n\t\t\t\t\toutFile << \"\t\tif(same(\\\"\" << i->second[j][k] << \"\\\"))\" << endl;\n\t\t\t\t\toutFile << \"\t\t\tresults.push_back(prevTokenValue);\" << endl;\n\t\t\t\t\toutFile << \"\t\telse\" << endl;\n\t\t\t\t\toutFile << \"\t\t\tthrow \\\"Syntax error - mismatched token\\\";\" << endl;\n\t\t\t\t} else\n\t\t\t\t\toutFile << \"\t\tresults.push_back(\" << i->second[j][k] << \"_rule());\" << endl;\n\t\t\t}\n\n\t\t\t\n\t\t\toutFile << nonterminalCode[i->first][j];\n\n\t\t\toutFile << \"\t}\" << endl << endl;\n\t\t}\n\n\t\tif (epsilon == -1)\n\t\t\toutFile << \"\tthrow \\\"Syntax error - unmatched token\\\";\" << endl;\n\t\telse\n\t\t\toutFile << nonterminalCode[i->first][epsilon];\n\n\t\toutFile << \"}\" << endl << endl;\n\t}\n\n\t\n\toutFile << \"int main(int argc, char **argv) {\" << endl;\n\toutFile << \"\tif(argc < 2) {\" << endl;\n\toutFile << \"\t\tcout << \\\"Usage: <input file>\\\" << endl;\" << endl;\n\toutFile << \"\t\treturn 1;\" << endl;\n\toutFile << \"\t}\" << endl << endl;\n\n\toutFile << \"\tifstream file(argv[1]);\" << endl;\n\toutFile << \"\tstring line;\" << endl;\n\toutFile << \"\tinput = \\\"\\\";\" << endl << endl;\n\n\toutFile << \"\twhile(true) {\" << endl;\n\toutFile << \"\t\tgetline(file, line);\" << endl;\n\toutFile << \"\t\tif(!file) break;\" << endl;\n\toutFile << \"\t\tinput += line + \\\"\\\\n\\\";\" << endl;\n\toutFile << \"\t}\" << endl << endl;\n\n\toutFile << \"\tadvanceToken();\" << endl << endl;\n\n\toutFile << \"\tstart_rule();\" << endl;\n\toutFile << \"}\" << endl;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"log\"\n)\n\nfunc labelStr(label int) string {\n    return fmt.Sprintf(\"_%04d\", label)\n}\n\ntype binexp struct {\n    op, left, right string\n    kind, index     int\n}\n\nfunc main() {\n    x := \"(one + two) * three - four * five\"\n    fmt.Println(\"Expression to parse: \", x)\n    f, err := parser.ParseExpr(x)\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Println(\"\\nThe abstract syntax tree for this expression:\")\n    ast.Print(nil, f)\n\n    fmt.Println(\"\\nThe corresponding three-address code:\")\n    var binexps []binexp\n    \n    ast.Inspect(f, func(n ast.Node) bool {\n        switch x := n.(type) {\n        case *ast.BinaryExpr:\n            sx, ok1 := x.X.(*ast.Ident)\n            sy, ok2 := x.Y.(*ast.Ident)\n            op := x.Op.String()\n            if ok1 && ok2 {\n                binexps = append(binexps, binexp{op, sx.Name, sy.Name, 3, 0})\n            } else if !ok1 && ok2 {\n                binexps = append(binexps, binexp{op, \"<addr>\", sy.Name, 2, 0})\n            } else if ok1 && !ok2 {\n                binexps = append(binexps, binexp{op, sx.Name, \"<addr>\", 1, 0})\n            } else {\n                binexps = append(binexps, binexp{op, \"<addr>\", \"<addr>\", 0, 0})\n            }\n        }\n        return true\n    })\n\n    for i := 0; i < len(binexps); i++ {\n        binexps[i].index = i\n    }\n\n    label, last := 0, -1\n    var ops, args []binexp\n    var labels []string\n    for i, be := range binexps {\n        if be.kind == 0 {\n            ops = append(ops, be)\n        }\n        if be.kind != 3 {\n            continue\n        }\n        label++\n        ls := labelStr(label)\n        fmt.Printf(\"    %s = %s %s %s\\n\", ls, be.left, be.op, be.right)\n        for j := i - 1; j > last; j-- {\n            be2 := binexps[j]\n            if be2.kind == 2 {\n                label++\n                ls2 := labelStr(label)\n                fmt.Printf(\"    %s = %s %s %s\\n\", ls2, ls, be2.op, be2.right)\n                ls = ls2\n                be = be2\n            } else if be2.kind == 1 {\n                label++\n                ls2 := labelStr(label)\n                fmt.Printf(\"    %s = %s %s %s\\n\", ls2, be2.left, be2.op, ls)\n                ls = ls2\n                be = be2\n            }\n        }\n        args = append(args, be)\n        labels = append(labels, ls)\n        lea, leo := len(args), len(ops)\n        for lea >= 2 {\n            if i < len(binexps)-1 && args[lea-2].index <= ops[leo-1].index {\n                break\n            }\n            label++\n            ls2 := labelStr(label)\n            fmt.Printf(\"    %s = %s %s %s\\n\", ls2, labels[lea-2], ops[leo-1].op, labels[lea-1])\n            ops = ops[0 : leo-1]\n            args = args[0 : lea-1]\n            labels = labels[0 : lea-1]\n            lea--\n            leo--\n            args[lea-1] = be\n            labels[lea-1] = ls2\n        }\n        last = i\n    }\n}\n"}
{"id": 49710, "name": "Find duplicate files", "C++": "#include<iostream>\n#include<string>\n#include<boost/filesystem.hpp>\n#include<boost/format.hpp>\n#include<boost/iostreams/device/mapped_file.hpp>\n#include<optional>\n#include<algorithm>\n#include<iterator>\n#include<execution>\n#include\"dependencies/xxhash.hpp\" \n\n\ntemplate<typename  T, typename V, typename F>\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n    size_t partitions = 0;\n    while (begin != end) {\n        auto const& value = getvalue(*begin);\n        auto current = begin;\n        while (++current != end && getvalue(*current) == value);\n        callback(begin, current, value);\n        ++partitions;\n        begin = current;\n    }\n    return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n    explicit file_entry(fs::directory_entry const & entry) \n        : path_{entry.path()}, size_{fs::file_size(entry)}\n    {}\n    auto size() const { return size_; }\n    auto const& path() const { return path_; }\n    auto get_hash() {\n        if (!hash_)\n            hash_ = compute_hash();\n        return *hash_;\n    }\nprivate:\n    xxh::hash64_t compute_hash() {\n        bi::mapped_file_source source;\n        source.open<fs::wpath>(this->path());\n        if (!source.is_open()) {\n            std::cerr << \"Cannot open \" << path() << std::endl;\n            throw std::runtime_error(\"Cannot open file\");\n        }\n        xxh::hash_state64_t hash_stream;\n        hash_stream.update(source.data(), size_);\n        return hash_stream.digest();\n    }\nprivate:\n    fs::wpath path_;\n    uintmax_t size_;\n    std::optional<xxh::hash64_t> hash_;\n};\n\nusing vector_type = std::vector<file_entry>;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n    size_t found = 0, ignored = 0;\n    if (!fs::is_directory(path)) {\n        std::cerr << path << \" is not a directory!\" << std::endl;\n    }\n    else {\n        std::cerr << \"Searching \" << path << std::endl;\n\n        for (auto& e : fs::recursive_directory_iterator(path)) {\n            ++found;\n            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n                file_vector.emplace_back(e);\n            else ++ignored;\n        }\n    }\n    return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n    vector_type files;\n    for (auto i = 1; i < argn; ++i) {\n        fs::wpath path(argv[i]);\n        auto [found, ignored] = find_files_in_dir(path, files);\n        std::cerr << boost::format{\n            \"  %1$6d files found\\n\"\n            \"  %2$6d files ignored\\n\"\n            \"  %3$6d files added\\n\" } % found % ignored % (found - ignored) \n            << std::endl;\n    }\n\n    std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n    \n    std::sort(std::execution::par_unseq, files.begin(), files.end()\n        , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n    );\n    for_each_adjacent_range(\n        std::begin(files)\n        , std::end(files)\n        , [](vector_type::value_type const& f) { return f.size(); }\n        , [](auto start, auto end, auto file_size) {\n            \n            size_t nr_of_files = std::distance(start, end);\n            if (nr_of_files > 1) {\n                \n                std::sort(start, end, [](auto& a, auto& b) { \n                    auto const& ha = a.get_hash();\n                    auto const& hb = b.get_hash();\n                    auto const& pa = a.path();\n                    auto const& pb = b.path();\n                    return std::tie(ha, pa) < std::tie(hb, pb); \n                    });\n                for_each_adjacent_range(\n                    start\n                    , end\n                    , [](vector_type::value_type& f) { return f.get_hash(); }\n                    , [file_size](auto hstart, auto hend, auto hash) {\n                        \n                        \n                        size_t hnr_of_files = std::distance(hstart, hend);\n                        if (hnr_of_files > 1) {\n                            std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n                                % hnr_of_files % file_size % hash;\n                            std::for_each(hstart, hend, [hash, file_size](auto& e) {\n                                std::cout << '\\t' << e.path() << '\\n';\n                                }\n                            );\n                        }\n                    }\n                );\n            }\n        }\n    );\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"crypto/md5\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"path/filepath\"\n    \"sort\"\n    \"time\"\n)\n\ntype fileData struct {\n    filePath string\n    info     os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc checksum(filePath string) hash {\n    bytes, err := ioutil.ReadFile(filePath)\n    check(err)\n    return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n    var dups [][2]fileData\n    m := make(map[hash]fileData)\n    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        if !info.IsDir() && info.Size() >= minSize {\n            h := checksum(path)\n            fd, ok := m[h]\n            fd2 := fileData{path, info}\n            if !ok {\n                m[h] = fd2\n            } else {\n                dups = append(dups, [2]fileData{fd, fd2})\n            }\n        }\n        return nil\n    })\n    check(werr)\n    return dups\n}\n\nfunc main() {\n    dups := findDuplicates(\".\", 1)\n    fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n    fmt.Println(\"File name                 Size      Date last modified\")\n    fmt.Println(\"==========================================================\")\n    sort.Slice(dups, func(i, j int) bool {\n        return dups[i][0].info.Size() > dups[j][0].info.Size() \n    })\n    for _, dup := range dups {\n        for i := 0; i < 2; i++ {\n            d := dup[i]\n            fmt.Printf(\"%-20s  %8d    %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 49711, "name": "Substring primes", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(size_t limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (size_t i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (size_t p = 3; ; p += 2) {\n        size_t q = p * p;\n        if (q >= limit)\n            break;\n        if (sieve[p]) {\n            size_t inc = 2 * p;\n            for (; q < limit; q += inc)\n                sieve[q] = false;\n        }\n    }\n    return sieve;\n}\n\nbool substring_prime(const std::vector<bool>& sieve, unsigned int n) {\n    for (; n != 0; n /= 10) {\n        if (!sieve[n])\n            return false;\n        for (unsigned int p = 10; p < n; p *= 10) {\n            if (!sieve[n % p])\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::vector<bool> sieve = prime_sieve(limit);\n    for (unsigned int i = 2; i < limit; ++i) {\n        if (substring_prime(sieve, i))\n            std::cout << i << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(499)\n    var sprimes []int\n    for _, p := range primes {\n        digits := rcu.Digits(p, 10)\n        var b1 = true\n        for _, d := range digits {\n            if !rcu.IsPrime(d) {\n                b1 = false\n                break\n            }\n        }\n        if b1 {\n            if len(digits) < 3 {\n                sprimes = append(sprimes, p)\n            } else {\n                b2 := rcu.IsPrime(digits[0]*10 + digits[1])\n                b3 := rcu.IsPrime(digits[1]*10 + digits[2])\n                if b2 && b3 {\n                    sprimes = append(sprimes, p)\n                }\n            }\n        }\n    }\n    fmt.Println(\"Found\", len(sprimes), \"primes < 500 where all substrings are also primes, namely:\")\n    fmt.Println(sprimes)\n}\n"}
{"id": 49712, "name": "Substring primes", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(size_t limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (size_t i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (size_t p = 3; ; p += 2) {\n        size_t q = p * p;\n        if (q >= limit)\n            break;\n        if (sieve[p]) {\n            size_t inc = 2 * p;\n            for (; q < limit; q += inc)\n                sieve[q] = false;\n        }\n    }\n    return sieve;\n}\n\nbool substring_prime(const std::vector<bool>& sieve, unsigned int n) {\n    for (; n != 0; n /= 10) {\n        if (!sieve[n])\n            return false;\n        for (unsigned int p = 10; p < n; p *= 10) {\n            if (!sieve[n % p])\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::vector<bool> sieve = prime_sieve(limit);\n    for (unsigned int i = 2; i < limit; ++i) {\n        if (substring_prime(sieve, i))\n            std::cout << i << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(499)\n    var sprimes []int\n    for _, p := range primes {\n        digits := rcu.Digits(p, 10)\n        var b1 = true\n        for _, d := range digits {\n            if !rcu.IsPrime(d) {\n                b1 = false\n                break\n            }\n        }\n        if b1 {\n            if len(digits) < 3 {\n                sprimes = append(sprimes, p)\n            } else {\n                b2 := rcu.IsPrime(digits[0]*10 + digits[1])\n                b3 := rcu.IsPrime(digits[1]*10 + digits[2])\n                if b2 && b3 {\n                    sprimes = append(sprimes, p)\n                }\n            }\n        }\n    }\n    fmt.Println(\"Found\", len(sprimes), \"primes < 500 where all substrings are also primes, namely:\")\n    fmt.Println(sprimes)\n}\n"}
{"id": 49713, "name": "Sylvester's sequence", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing integer = boost::multiprecision::cpp_int;\nusing rational = boost::rational<integer>;\n\ninteger sylvester_next(const integer& n) {\n    return n * n - n + 1;\n}\n\nint main() {\n    std::cout << \"First 10 elements in Sylvester's sequence:\\n\";\n    integer term = 2;\n    rational sum = 0;\n    for (int i = 1; i <= 10; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        sum += rational(1, term);\n        term = sylvester_next(term);\n    }\n    std::cout << \"Sum of reciprocals: \" << sum << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    two := big.NewInt(2)\n    next := new(big.Int)\n    sylvester := []*big.Int{two}\n    prod := new(big.Int).Set(two)\n    count := 1\n    for count < 10 {\n        next.Add(prod, one)\n        sylvester = append(sylvester, new(big.Int).Set(next))\n        count++\n        prod.Mul(prod, next)\n    }\n    fmt.Println(\"The first 10 terms in the Sylvester sequence are:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sylvester[i])\n    }\n\n    sumRecip := new(big.Rat)\n    for _, s := range sylvester {\n        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))\n    }\n    fmt.Println(\"\\nThe sum of their reciprocals as a rational number is:\")\n    fmt.Println(sumRecip)\n    fmt.Println(\"\\nThe sum of their reciprocals as a decimal number (to 211 places) is:\")\n    fmt.Println(sumRecip.FloatString(211))\n}\n"}
{"id": 49714, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 49715, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 49716, "name": "Order disjoint list items", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\ntemplate <typename T>\nvoid print(const std::vector<T> v) {\n  std::cout << \"{ \";\n  for (const auto& e : v) {\n    std::cout << e << \" \";\n  }\n  std::cout << \"}\";\n}\n\ntemplate <typename T>\nauto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {\n  std::vector<T*> M_p(std::size(M));\n  for (auto i = 0; i < std::size(M_p); ++i) {\n    M_p[i] = &M[i];\n  }\n  for (auto e : N) {\n    auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {\n      if (c != nullptr) {\n        if (*c == e) return true;\n      }\n      return false;\n    });\n    if (i != std::end(M_p)) {\n      *i = nullptr;\n    }\n  }\n  for (auto i = 0; i < std::size(N); ++i) {\n    auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {\n      return c == nullptr;\n    });\n    if (j != std::end(M_p)) {\n      *j = &M[std::distance(std::begin(M_p), j)];\n      **j = N[i];\n    }\n  }\n  return M;\n}\n\nint main() {\n  std::vector<std::vector<std::vector<std::string>>> l = {\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" }, { \"mat\", \"cat\" } },\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" },{ \"cat\", \"mat\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"C\", \"A\", \"B\", \"C\" },{ \"C\", \"A\", \"C\", \"A\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"D\", \"A\", \"B\", \"E\" },{ \"E\", \"A\", \"D\", \"A\" } },\n    { { \"A\", \"B\" },{ \"B\" } },\n    { { \"A\", \"B\" },{ \"B\", \"A\" } },\n    { { \"A\", \"B\", \"B\", \"A\" },{ \"B\", \"A\" } }\n  };\n  for (const auto& e : l) {\n    std::cout << \"M: \";\n    print(e[0]);\n    std::cout << \", N: \";\n    print(e[1]);\n    std::cout << \", M': \";\n    auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);\n    print(res);\n    std::cout << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype indexSort struct {\n\tval sort.Interface\n\tind []int\n}\n\nfunc (s indexSort) Len() int           { return len(s.ind) }\nfunc (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }\nfunc (s indexSort) Swap(i, j int) {\n\ts.val.Swap(s.ind[i], s.ind[j])\n\ts.ind[i], s.ind[j] = s.ind[j], s.ind[i]\n}\n\nfunc disjointSliceSort(m, n []string) []string {\n\ts := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}\n\tused := make(map[int]bool)\n\tfor _, nw := range n {\n\t\tfor i, mw := range m {\n\t\t\tif used[i] || mw != nw {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tused[i] = true\n\t\t\ts.ind = append(s.ind, i)\n\t\t\tbreak\n\t\t}\n\t}\n\tsort.Sort(s)\n\treturn s.val.(sort.StringSlice)\n}\n\nfunc disjointStringSort(m, n string) string {\n\treturn strings.Join(\n\t\tdisjointSliceSort(strings.Fields(m), strings.Fields(n)), \" \")\n}\n\nfunc main() {\n\tfor _, data := range []struct{ m, n string }{\n\t\t{\"the cat sat on the mat\", \"mat cat\"},\n\t\t{\"the cat sat on the mat\", \"cat mat\"},\n\t\t{\"A B C A B C A B C\", \"C A C A\"},\n\t\t{\"A B C A B D A B E\", \"E A D A\"},\n\t\t{\"A B\", \"B\"},\n\t\t{\"A B\", \"B A\"},\n\t\t{\"A B B A\", \"B A\"},\n\t} {\n\t\tmp := disjointStringSort(data.m, data.n)\n\t\tfmt.Printf(\"%s → %s » %s\\n\", data.m, data.n, mp)\n\t}\n\n}\n"}
{"id": 49717, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 49718, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 49719, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 49720, "name": "Ramanujan primes", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n"}
{"id": 49721, "name": "Ramanujan primes", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n"}
{"id": 49722, "name": "Ramanujan primes", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n"}
{"id": 49723, "name": "Achilles numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n"}
{"id": 49724, "name": "Achilles numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n"}
{"id": 49725, "name": "Odd squarefree semiprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n"}
{"id": 49726, "name": "Odd squarefree semiprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n"}
{"id": 49727, "name": "Sierpinski curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 49728, "name": "Sierpinski curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 49729, "name": "Most frequent k chars distance", "C++": "#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <sstream>\n\nstd::string mostFreqKHashing ( const std::string & input , int k ) {\n   std::ostringstream oss ;\n   std::map<char, int> frequencies ;\n   for ( char c : input ) {\n      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;\n   }\n   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;\n   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,\n\t         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; \n\t         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }\n\t         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;\n   for ( int i = 0 ; i < letters.size( ) ; i++ ) {\n      oss << std::get<0>( letters[ i ] ) ;\n      oss << std::get<1>( letters[ i ] ) ;\n   }\n   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;\n   if ( letters.size( ) >= k ) {\n      return output ;\n   }\n   else {\n      return output.append( \"NULL0\" ) ;\n   }\n}\n\nint mostFreqKSimilarity ( const std::string & first , const std::string & second ) {\n   int i = 0 ;\n   while ( i < first.length( ) - 1  ) {\n      auto found = second.find_first_of( first.substr( i , 2 ) ) ;\n      if ( found != std::string::npos ) \n\t return std::stoi ( first.substr( i , 2 )) ;\n      else \n\t i += 2 ;\n   }\n   return 0 ;\n}\n\nint mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {\n   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;\n}\n\nint main( ) {\n   std::string s1(\"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\" ) ;\n   std::string s2( \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\" ) ;\n   std::cout << \"MostFreqKHashing( s1 , 2 ) = \" << mostFreqKHashing( s1 , 2 ) << '\\n' ;\n   std::cout << \"MostFreqKHashing( s2 , 2 ) = \" << mostFreqKHashing( s2 , 2 ) << '\\n' ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n"}
{"id": 49730, "name": "Palindromic primes", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n"}
{"id": 49731, "name": "Palindromic primes", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n"}
{"id": 49732, "name": "Find words which contains all the vowels", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\nbool contains_all_vowels_once(const std::string& word) {\n    std::bitset<5> vowels;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        size_t bit = 0;\n        switch (ch) {\n        case 'a': bit = 0; break;\n        case 'e': bit = 1; break;\n        case 'i': bit = 2; break;\n        case 'o': bit = 3; break;\n        case 'u': bit = 4; break;\n        default: continue;\n        }\n        if (vowels.test(bit))\n            return false;\n        vowels.set(bit);\n    }\n    return vowels.all();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        if (word.size() > 10 && contains_all_vowels_once(word))\n            std::cout << std::setw(2) << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Words which contain all 5 vowels once in\", wordList, \"\\b:\\n\")\n    for _, word := range words {\n        ca, ce, ci, co, cu := 0, 0, 0, 0, 0\n        for _, r := range word {\n            switch r {\n            case 'a':\n                ca++\n            case 'e':\n                ce++\n            case 'i':\n                ci++\n            case 'o':\n                co++\n            case 'u':\n                cu++\n            }\n        }\n        if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {\n            count++\n            fmt.Printf(\"%2d: %s\\n\", count, word)\n        }\n    }\n}\n"}
{"id": 49733, "name": "Text completion", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\n\nint levenshtein_distance(const std::string& str1, const std::string& str2) {\n    size_t m = str1.size(), n = str2.size();\n    std::vector<int> cost(n + 1);\n    std::iota(cost.begin(), cost.end(), 0);\n    for (size_t i = 0; i < m; ++i) {\n        cost[0] = i + 1;\n        int prev = i;\n        for (size_t j = 0; j < n; ++j) {\n            int c = (str1[i] == str2[j]) ? prev\n                : 1 + std::min(std::min(cost[j + 1], cost[j]), prev);\n            prev = cost[j + 1];\n            cost[j + 1] = c;\n        }\n    }\n    return cost[n];\n}\n\ntemplate <typename T>\nvoid print_vector(const std::vector<T>& vec) {\n    auto i = vec.begin();\n    if (i == vec.end())\n        return;\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 3) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary word\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1]);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << '\\n';\n        return EXIT_FAILURE;\n    }\n    std::string word(argv[2]);\n    if (word.empty()) {\n        std::cerr << \"Word must not be empty\\n\";\n        return EXIT_FAILURE;\n    }\n    constexpr size_t max_dist = 4;\n    std::vector<std::string> matches[max_dist + 1];\n    std::string match;\n    while (getline(in, match)) {\n        int distance = levenshtein_distance(word, match);\n        if (distance <= max_dist)\n            matches[distance].push_back(match);\n    }\n    for (size_t dist = 0; dist <= max_dist; ++dist) {\n        if (matches[dist].empty())\n            continue;\n        std::cout << \"Words at Levenshtein distance of \" << dist\n            << \" (\" << 100 - (100 * dist)/word.size()\n            << \"% similarity) from '\" << word << \"':\\n\";\n        print_vector(matches[dist]);\n        std::cout << \"\\n\\n\";\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n)\n\nfunc levenshtein(s, t string) int {\n    d := make([][]int, len(s)+1)\n    for i := range d {\n        d[i] = make([]int, len(t)+1)\n    }\n    for i := range d {\n        d[i][0] = i\n    }\n    for j := range d[0] {\n        d[0][j] = j\n    }\n    for j := 1; j <= len(t); j++ {\n        for i := 1; i <= len(s); i++ {\n            if s[i-1] == t[j-1] {\n                d[i][j] = d[i-1][j-1]\n            } else {\n                min := d[i-1][j]\n                if d[i][j-1] < min {\n                    min = d[i][j-1]\n                }\n                if d[i-1][j-1] < min {\n                    min = d[i-1][j-1]\n                }\n                d[i][j] = min + 1\n            }\n        }\n\n    }\n    return d[len(s)][len(t)]\n}\n\nfunc main() {\n    search := \"complition\"\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Fields(b)\n    var lev [4][]string\n    for _, word := range words {\n        s := string(word)\n        ld := levenshtein(search, s)\n        if ld < 4 {\n            lev[ld] = append(lev[ld], s)\n        }\n    }\n    fmt.Printf(\"Input word: %s\\n\\n\", search)\n    for i := 1; i < 4; i++ {\n        length := float64(len(search))\n        similarity := (length - float64(i)) * 100 / length\n        fmt.Printf(\"Words which are %4.1f%% similar:\\n\", similarity)\n        fmt.Println(lev[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 49734, "name": "Anaprimes", "C++": "#include <array>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <primesieve.hpp>\n\nusing digit_set = std::array<int, 10>;\n\ndigit_set get_digits(uint64_t n) {\n    digit_set result = {};\n    for (; n > 0; n /= 10)\n        ++result[n % 10];\n    return result;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    primesieve::iterator pi;\n    using map_type =\n        std::map<digit_set, std::vector<uint64_t>, std::greater<digit_set>>;\n    map_type anaprimes;\n    for (uint64_t limit = 1000; limit <= 10000000000;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > limit) {\n            size_t max_length = 0;\n            std::vector<map_type::iterator> groups;\n            for (auto i = anaprimes.begin(); i != anaprimes.end(); ++i) {\n                if (i->second.size() > max_length) {\n                    groups.clear();\n                    max_length = i->second.size();\n                }\n                if (max_length == i->second.size())\n                    groups.push_back(i);\n            }\n            std::cout << \"Largest group(s) of anaprimes before \" << limit\n                      << \": \" << max_length << \" members:\\n\";\n            for (auto i : groups) {\n                std::cout << \"  First: \" << i->second.front()\n                          << \"  Last: \" << i->second.back() << '\\n';\n            }\n            std::cout << '\\n';\n            anaprimes.clear();\n            limit *= 10;\n        }\n        anaprimes[get_digits(prime)].push_back(prime);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = int(1e10)\n    const maxIndex = 9\n    primes := rcu.Primes(limit)\n    anaprimes := make(map[int][]int)\n    for _, p := range primes {\n        digs := rcu.Digits(p, 10)\n        key := 1\n        for _, dig := range digs {\n            key *= primes[dig]\n        }\n        if _, ok := anaprimes[key]; ok {\n            anaprimes[key] = append(anaprimes[key], p)\n        } else {\n            anaprimes[key] = []int{p}\n        }\n    }\n    largest := make([]int, maxIndex+1)\n    groups := make([][][]int, maxIndex+1)\n    for key := range anaprimes {\n        v := anaprimes[key]\n        nd := len(rcu.Digits(v[0], 10))\n        c := len(v)\n        if c > largest[nd-1] {\n            largest[nd-1] = c\n            groups[nd-1] = [][]int{v}\n        } else if c == largest[nd-1] {\n            groups[nd-1] = append(groups[nd-1], v)\n        }\n    }\n    j := 1000\n    for i := 2; i <= maxIndex; i++ {\n        js := rcu.Commatize(j)\n        ls := rcu.Commatize(largest[i])\n        fmt.Printf(\"Largest group(s) of anaprimes before %s: %s members:\\n\", js, ls)\n        sort.Slice(groups[i], func(k, l int) bool {\n            return groups[i][k][0] < groups[i][l][0]\n        })\n        for _, g := range groups[i] {\n            fmt.Printf(\"  First: %s  Last: %s\\n\", rcu.Commatize(g[0]), rcu.Commatize(g[len(g)-1]))\n        }\n        j *= 10\n        fmt.Println()\n    }\n}\n"}
{"id": 49735, "name": "Tropical algebra overloading", "C++": "#include <iostream>\n#include <optional>\n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n    \n    optional<double> m_value;\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n    \n    \n    TropicalAlgebra() = default;\n\n    \n    explicit TropicalAlgebra(double value) noexcept\n        : m_value{value} {}\n\n    \n    \n    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            *this = rhs;\n        }\n        else if (!rhs.m_value)\n        {\n            \n        }\n        else\n        {\n            \n            *m_value = max(*rhs.m_value, *m_value);\n        }\n\n        return *this;\n    }\n    \n    \n    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            \n        }\n        else if (!rhs.m_value)\n        {\n            \n            *this = rhs;\n        }\n        else\n        {\n            *m_value += *rhs.m_value;\n        }\n\n        return *this;\n    }\n};\n\n\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n    \n    lhs += rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n    auto result = base;\n    for(unsigned int i = 1; i < exponent; i++)\n    {\n        \n        result *= base;\n    }\n    return result;\n}\n\n\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n    if(!pt.m_value) cout << \"-Inf\\n\";\n    else cout << *pt.m_value << \"\\n\";\n    return os;\n}\n\nint main(void) {\n    const TropicalAlgebra a(-2);\n    const TropicalAlgebra b(-1);\n    const TropicalAlgebra c(-0.5);\n    const TropicalAlgebra d(-0.001);\n    const TropicalAlgebra e(0);\n    const TropicalAlgebra h(1.5);\n    const TropicalAlgebra i(2);\n    const TropicalAlgebra j(5);\n    const TropicalAlgebra k(7);\n    const TropicalAlgebra l(8);\n    const TropicalAlgebra m; \n    \n    cout << \"2 * -2 == \" << i * a;\n    cout << \"-0.001 + -Inf == \" << d + m;\n    cout << \"0 * -Inf == \" << e * m;\n    cout << \"1.5 + -1 == \" << h + b;\n    cout << \"-0.5 * 0 == \" << c * e;\n    cout << \"pow(5, 7) == \" << pow(j, 7);\n    cout << \"5 * (8 + 7)) == \" << j * (l + k);\n    cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar MinusInf = math.Inf(-1)\n\ntype MaxTropical struct{ r float64 }\n\nfunc newMaxTropical(r float64) MaxTropical {\n    if math.IsInf(r, 1) || math.IsNaN(r) {\n        log.Fatal(\"Argument must be a real number or negative infinity.\")\n    }\n    return MaxTropical{r}\n}\n\nfunc (t MaxTropical) eq(other MaxTropical) bool {\n    return t.r == other.r\n}\n\n\nfunc (t MaxTropical) add(other MaxTropical) MaxTropical {\n    if t.r == MinusInf {\n        return other\n    }\n    if other.r == MinusInf {\n        return t\n    }\n    return newMaxTropical(math.Max(t.r, other.r))\n}\n\n\nfunc (t MaxTropical) mul(other MaxTropical) MaxTropical {\n    if t.r == 0 {\n        return other\n    }\n    if other.r == 0 {\n        return t\n    }\n    return newMaxTropical(t.r + other.r)\n}\n\n\nfunc (t MaxTropical) pow(e int) MaxTropical {\n    if e < 1 {\n        log.Fatal(\"Exponent must be a positive integer.\")\n    }\n    if e == 1 {\n        return t\n    }\n    p := t\n    for i := 2; i <= e; i++ {\n        p = p.mul(t)\n    }\n    return p\n}\n\nfunc (t MaxTropical) String() string {\n    return fmt.Sprintf(\"%g\", t.r)\n}\n\nfunc main() {\n    \n    data := [][]float64{\n        {2, -2, 1},\n        {-0.001, MinusInf, 0},\n        {0, MinusInf, 1},\n        {1.5, -1, 0},\n        {-0.5, 0, 1},\n    }\n    for _, d := range data {\n        a := newMaxTropical(d[0])\n        b := newMaxTropical(d[1])\n        if d[2] == 0 {\n            fmt.Printf(\"%s ⊕ %s = %s\\n\", a, b, a.add(b))\n        } else {\n            fmt.Printf(\"%s ⊗ %s = %s\\n\", a, b, a.mul(b))\n        }\n    }\n\n    c := newMaxTropical(5)\n    fmt.Printf(\"%s ^ 7 = %s\\n\", c, c.pow(7))\n\n    d := newMaxTropical(8)\n    e := newMaxTropical(7)\n    f := c.mul(d.add(e))\n    g := c.mul(d).add(c.mul(e))\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) = %s\\n\", c, d, e, f)\n    fmt.Printf(\"%s ⊗ %s ⊕ %s ⊗ %s = %s\\n\", c, d, c, e, g)\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\\n\", c, d, e, c, d, c, e, f.eq(g))\n}\n"}
{"id": 49736, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 49737, "name": "Pig the dice game_Player", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 49738, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n1, continued fraction n2)", "C++": "\nclass NG_8 : public matrixNG {\n  private: int a12, a1, a2, a, b12, b1, b2, b, t;\n           double ab, a1b1, a2b2, a12b12;\n  const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}\n  const bool needTerm() {\n    if (b1==0 and b==0 and b2==0 and b12==0) return false;\n    if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;\n    if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;\n    if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;\n    if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;\n    thisTerm = (int)ab;\n    if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;\n      haveTerm = true; return false;\n    }\n    cfn = chooseCFN();\n    return true;\n  }\n  void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}\n  void consumeTerm(int n){\n    if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}\n    else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}\n  }\n  public:\n  NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){\n}};\n", "Go": "package cf\n\nimport \"math\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG8 struct {\n\tA12, A1, A2, A int64\n\tB12, B1, B2, B int64\n}\n\n\nvar (\n\tNG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}\n\tNG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}\n\tNG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}\n\tNG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}\n)\n\nfunc (ng *NG8) needsIngest() bool {\n\tif ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {\n\t\treturn true\n\t}\n\tx := ng.A / ng.B\n\treturn ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x\n}\n\nfunc (ng *NG8) isDone() bool {\n\treturn ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0\n}\n\nfunc (ng *NG8) ingestWhich() bool { \n\tif ng.B == 0 && ng.B2 == 0 {\n\t\treturn true\n\t}\n\tif ng.B == 0 || ng.B2 == 0 {\n\t\treturn false\n\t}\n\tx1 := float64(ng.A1) / float64(ng.B1)\n\tx2 := float64(ng.A2) / float64(ng.B2)\n\tx := float64(ng.A) / float64(ng.B)\n\treturn math.Abs(x1-x) > math.Abs(x2-x)\n}\n\nfunc (ng *NG8) ingest(isN1 bool, t int64) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,\n\t\t\tng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,\n\t\t\tng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2\n\t}\n}\n\nfunc (ng *NG8) ingestInfinite(isN1 bool) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A2, ng.A, ng.B2, ng.B =\n\t\t\tng.A12, ng.A1,\n\t\t\tng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A1, ng.A, ng.B1, ng.B =\n\t\t\tng.A12, ng.A2,\n\t\t\tng.B12, ng.B2\n\t}\n}\n\nfunc (ng *NG8) egest(t int64) {\n\t\n\t\n\tng.A12, ng.A1, ng.A2, ng.A,\n\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\tng.B12, ng.B1, ng.B2, ng.B,\n\t\tng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t\n}\n\n\n\n\n\nfunc (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext1, next2 := N1(), N2()\n\t\tdone := false\n\t\tsinceEgest := 0\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tsinceEgest++\n\t\t\t\tif sinceEgest > limit {\n\t\t\t\t\tdone = true\n\t\t\t\t\treturn 0, false\n\t\t\t\t}\n\t\t\t\tisN1 := ng.ingestWhich()\n\t\t\t\tnext := next2\n\t\t\t\tif isN1 {\n\t\t\t\t\tnext = next1\n\t\t\t\t}\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(isN1, t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite(isN1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsinceEgest = 0\n\t\t\tt := ng.A / ng.B\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n"}
{"id": 49739, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n1, continued fraction n2)", "C++": "\nclass NG_8 : public matrixNG {\n  private: int a12, a1, a2, a, b12, b1, b2, b, t;\n           double ab, a1b1, a2b2, a12b12;\n  const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}\n  const bool needTerm() {\n    if (b1==0 and b==0 and b2==0 and b12==0) return false;\n    if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;\n    if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;\n    if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;\n    if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;\n    thisTerm = (int)ab;\n    if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;\n      haveTerm = true; return false;\n    }\n    cfn = chooseCFN();\n    return true;\n  }\n  void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}\n  void consumeTerm(int n){\n    if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}\n    else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}\n  }\n  public:\n  NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){\n}};\n", "Go": "package cf\n\nimport \"math\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG8 struct {\n\tA12, A1, A2, A int64\n\tB12, B1, B2, B int64\n}\n\n\nvar (\n\tNG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}\n\tNG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}\n\tNG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}\n\tNG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}\n)\n\nfunc (ng *NG8) needsIngest() bool {\n\tif ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {\n\t\treturn true\n\t}\n\tx := ng.A / ng.B\n\treturn ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x\n}\n\nfunc (ng *NG8) isDone() bool {\n\treturn ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0\n}\n\nfunc (ng *NG8) ingestWhich() bool { \n\tif ng.B == 0 && ng.B2 == 0 {\n\t\treturn true\n\t}\n\tif ng.B == 0 || ng.B2 == 0 {\n\t\treturn false\n\t}\n\tx1 := float64(ng.A1) / float64(ng.B1)\n\tx2 := float64(ng.A2) / float64(ng.B2)\n\tx := float64(ng.A) / float64(ng.B)\n\treturn math.Abs(x1-x) > math.Abs(x2-x)\n}\n\nfunc (ng *NG8) ingest(isN1 bool, t int64) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,\n\t\t\tng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,\n\t\t\tng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2\n\t}\n}\n\nfunc (ng *NG8) ingestInfinite(isN1 bool) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A2, ng.A, ng.B2, ng.B =\n\t\t\tng.A12, ng.A1,\n\t\t\tng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A1, ng.A, ng.B1, ng.B =\n\t\t\tng.A12, ng.A2,\n\t\t\tng.B12, ng.B2\n\t}\n}\n\nfunc (ng *NG8) egest(t int64) {\n\t\n\t\n\tng.A12, ng.A1, ng.A2, ng.A,\n\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\tng.B12, ng.B1, ng.B2, ng.B,\n\t\tng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t\n}\n\n\n\n\n\nfunc (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext1, next2 := N1(), N2()\n\t\tdone := false\n\t\tsinceEgest := 0\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tsinceEgest++\n\t\t\t\tif sinceEgest > limit {\n\t\t\t\t\tdone = true\n\t\t\t\t\treturn 0, false\n\t\t\t\t}\n\t\t\t\tisN1 := ng.ingestWhich()\n\t\t\t\tnext := next2\n\t\t\t\tif isN1 {\n\t\t\t\t\tnext = next1\n\t\t\t\t}\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(isN1, t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite(isN1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsinceEgest = 0\n\t\t\tt := ng.A / ng.B\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n"}
{"id": 49740, "name": "Lychrel numbers", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 49741, "name": "Lychrel numbers", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 49742, "name": "Base 16 numbers needing a to f", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n"}
{"id": 49743, "name": "Base 16 numbers needing a to f", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n"}
{"id": 49744, "name": "Erdös-Selfridge categorization of primes", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <primesieve.hpp>\n\nclass erdos_selfridge {\npublic:\n    explicit erdos_selfridge(int limit);\n    uint64_t get_prime(int index) const { return primes_[index].first; }\n    int get_category(int index);\n\nprivate:\n    std::vector<std::pair<uint64_t, int>> primes_;\n    size_t get_index(uint64_t prime) const;\n};\n\nerdos_selfridge::erdos_selfridge(int limit) {\n    primesieve::iterator iter;\n    for (int i = 0; i < limit; ++i)\n        primes_.emplace_back(iter.next_prime(), 0);\n}\n\nint erdos_selfridge::get_category(int index) {\n    auto& pair = primes_[index];\n    if (pair.second != 0)\n        return pair.second;\n    int max_category = 0;\n    uint64_t n = pair.first + 1;\n    for (int i = 0; n > 1; ++i) {\n        uint64_t p = primes_[i].first;\n        if (p * p > n)\n            break;\n        int count = 0;\n        for (; n % p == 0; ++count)\n            n /= p;\n        if (count != 0) {\n            int category = (p <= 3) ? 1 : 1 + get_category(i);\n            max_category = std::max(max_category, category);\n        }\n    }\n    if (n > 1) {\n        int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));\n        max_category = std::max(max_category, category);\n    }\n    pair.second = max_category;\n    return max_category;\n}\n\nsize_t erdos_selfridge::get_index(uint64_t prime) const {\n    auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,\n                               [](const std::pair<uint64_t, int>& p,\n                                  uint64_t n) { return p.first < n; });\n    assert(it != primes_.end());\n    assert(it->first == prime);\n    return std::distance(primes_.begin(), it);\n}\n\nauto get_primes_by_category(erdos_selfridge& es, int limit) {\n    std::map<int, std::vector<uint64_t>> primes_by_category;\n    for (int i = 0; i < limit; ++i) {\n        uint64_t prime = es.get_prime(i);\n        int category = es.get_category(i);\n        primes_by_category[category].push_back(prime);\n    }\n    return primes_by_category;\n}\n\nint main() {\n    const int limit1 = 200, limit2 = 1000000;\n\n    erdos_selfridge es(limit2);\n\n    std::cout << \"First 200 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit1)) {\n        std::cout << \"Category \" << p.first << \":\\n\";\n        for (size_t i = 0, n = p.second.size(); i != n; ++i) {\n            std::cout << std::setw(4) << p.second[i]\n                      << ((i + 1) % 15 == 0 ? '\\n' : ' ');\n        }\n        std::cout << \"\\n\\n\";\n    }\n\n    std::cout << \"First 1,000,000 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit2)) {\n        const auto& v = p.second;\n        std::cout << \"Category \" << std::setw(2) << p.first << \": \"\n                  << \"first = \" << std::setw(7) << v.front()\n                  << \"  last = \" << std::setw(8) << v.back()\n                  << \"  count = \" << v.size() << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nvar limit = int(math.Log(1e6) * 1e6 * 1.2) \nvar primes = rcu.Primes(limit)\n\nvar prevCats = make(map[int]int)\n\nfunc cat(p int) int {\n    if v, ok := prevCats[p]; ok {\n        return v\n    }\n    pf := rcu.PrimeFactors(p + 1)\n    all := true\n    for _, f := range pf {\n        if f != 2 && f != 3 {\n            all = false\n            break\n        }\n    }\n    if all {\n        return 1\n    }\n    if p > 2 {\n        len := len(pf)\n        for i := len - 1; i >= 1; i-- {\n            if pf[i-1] == pf[i] {\n                pf = append(pf[:i], pf[i+1:]...)\n            }\n        }\n    }\n    for c := 2; c <= 11; c++ {\n        all := true\n        for _, f := range pf {\n            if cat(f) >= c {\n                all = false\n                break\n            }\n        }\n        if all {\n            prevCats[p] = c\n            return c\n        }\n    }\n    return 12\n}\n\nfunc main() {\n    es := make([][]int, 12)\n    fmt.Println(\"First 200 primes:\\n\")\n    for _, p := range primes[0:200] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 6; c++ {\n        if len(es[c-1]) > 0 {\n            fmt.Println(\"Category\", c, \"\\b:\")\n            fmt.Println(es[c-1])\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"First million primes:\\n\")\n    for _, p := range primes[200:1e6] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 12; c++ {\n        e := es[c-1]\n        if len(e) > 0 {\n            format := \"Category %-2d: First = %7d  Last = %8d  Count = %6d\\n\"\n            fmt.Printf(format, c, e[0], e[len(e)-1], len(e))\n        }\n    }\n}\n"}
{"id": 49745, "name": "Range modifications", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <list>\n\nstruct range {\n    range(int lo, int hi) : low(lo), high(hi) {}\n    int low;\n    int high;\n};\n\nstd::ostream& operator<<(std::ostream& out, const range& r) {\n    return out << r.low << '-' << r.high;\n}\n\nclass ranges {\npublic:\n    ranges() {}\n    explicit ranges(std::initializer_list<range> init) : ranges_(init) {}\n    void add(int n);\n    void remove(int n);\n    bool empty() const { return ranges_.empty(); }\nprivate:\n    friend std::ostream& operator<<(std::ostream& out, const ranges& r);\n    std::list<range> ranges_;\n};\n\nvoid ranges::add(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n + 1 < i->low) {\n            ranges_.emplace(i, n, n);\n            return;\n        }\n        if (n > i->high + 1)\n            continue;\n        if (n + 1 == i->low)\n            i->low = n;\n        else if (n == i->high + 1)\n            i->high = n;\n        else\n            return;\n        if (i != ranges_.begin()) {\n            auto prev = std::prev(i);\n            if (prev->high + 1 == i->low) {\n                i->low = prev->low;\n                ranges_.erase(prev);\n            }\n        }\n        auto next = std::next(i);\n        if (next != ranges_.end() && next->low - 1 == i->high) {\n            i->high = next->high;\n            ranges_.erase(next);\n        }\n        return;\n    }\n    ranges_.emplace_back(n, n);\n}\n\nvoid ranges::remove(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n < i->low)\n            return;\n        if (n == i->low) {\n            if (++i->low > i->high)\n                ranges_.erase(i);\n            return;\n        }\n        if (n == i->high) {\n            if (--i->high < i->low)\n                ranges_.erase(i);\n            return;\n        }\n        if (n > i->low & n < i->high) {\n            int low = i->low;\n            i->low = n + 1;\n            ranges_.emplace(i, low, n - 1);\n            return;\n        }\n    }\n}\n\nstd::ostream& operator<<(std::ostream& out, const ranges& r) {\n    if (!r.empty()) {\n        auto i = r.ranges_.begin();\n        out << *i++;\n        for (; i != r.ranges_.end(); ++i)\n            out << ',' << *i;\n    }\n    return out;\n}\n\nvoid test_add(ranges& r, int n) {\n    r.add(n);\n    std::cout << \"       add \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test_remove(ranges& r, int n) {\n    r.remove(n);\n    std::cout << \"    remove \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test1() {\n    ranges r;\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 77);\n    test_add(r, 79);\n    test_add(r, 78);\n    test_remove(r, 77);\n    test_remove(r, 78);\n    test_remove(r, 79);\n}\n\nvoid test2() {\n    ranges r{{1,3}, {5,5}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 1);\n    test_remove(r, 4);\n    test_add(r, 7);\n    test_add(r, 8);\n    test_add(r, 6);\n    test_remove(r, 7);\n}\n\nvoid test3() {\n    ranges r{{1,5}, {10,25}, {27,30}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 26);\n    test_add(r, 9);\n    test_add(r, 7);\n    test_remove(r, 26);\n    test_remove(r, 9);\n    test_remove(r, 7);\n}\n\nint main() {\n    test1();\n    std::cout << '\\n';\n    test2();\n    std::cout << '\\n';\n    test3();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype rng struct{ from, to int }\n\ntype fn func(rngs *[]rng, n int)\n\nfunc (r rng) String() string { return fmt.Sprintf(\"%d-%d\", r.from, r.to) }\n\nfunc rangesAdd(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        rngs = append(rngs, rng{n, n})\n        return rngs\n    }\n    for i, r := range rngs {\n        if n < r.from-1 {\n            rngs = append(rngs, rng{})\n            copy(rngs[i+1:], rngs[i:])\n            rngs[i] = rng{n, n}\n            return rngs\n        } else if n == r.from-1 {\n            rngs[i] = rng{n, r.to}\n            return rngs\n        } else if n <= r.to {\n            return rngs\n        } else if n == r.to+1 {\n            rngs[i] = rng{r.from, n}\n            if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) {\n                rngs[i] = rng{r.from, rngs[i+1].to}\n                copy(rngs[i+1:], rngs[i+2:])\n                rngs[len(rngs)-1] = rng{}\n                rngs = rngs[:len(rngs)-1]\n            }\n            return rngs\n        } else if i == len(rngs)-1 {\n            rngs = append(rngs, rng{n, n})\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc rangesRemove(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        return rngs\n    }\n    for i, r := range rngs {\n        if n <= r.from-1 {\n            return rngs\n        } else if n == r.from && n == r.to {\n            copy(rngs[i:], rngs[i+1:])\n            rngs[len(rngs)-1] = rng{}\n            rngs = rngs[:len(rngs)-1]\n            return rngs\n        } else if n == r.from {\n            rngs[i] = rng{n + 1, r.to}\n            return rngs\n        } else if n < r.to {\n            rngs[i] = rng{r.from, n - 1}\n            rngs = append(rngs, rng{})\n            copy(rngs[i+2:], rngs[i+1:])\n            rngs[i+1] = rng{n + 1, r.to}\n            return rngs\n        } else if n == r.to {\n            rngs[i] = rng{r.from, n - 1}\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc standard(rngs []rng) string {\n    if len(rngs) == 0 {\n        return \"\"\n    }\n    var sb strings.Builder\n    for _, r := range rngs {\n        sb.WriteString(fmt.Sprintf(\"%s,\", r))\n    }\n    s := sb.String()\n    return s[:len(s)-1]\n}\n\nfunc main() {\n    const add = 0\n    const remove = 1\n    fns := []fn{\n        func(prngs *[]rng, n int) {\n            *prngs = rangesAdd(*prngs, n)\n            fmt.Printf(\"       add %2d => %s\\n\", n, standard(*prngs))\n        },\n        func(prngs *[]rng, n int) {\n            *prngs = rangesRemove(*prngs, n)\n            fmt.Printf(\"    remove %2d => %s\\n\", n, standard(*prngs))\n        },\n    }\n\n    var rngs []rng\n    ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}}\n    fmt.Printf(\"Start: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 3}, {5, 5}}\n    ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 5}, {10, 25}, {27, 30}}\n    ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n}\n"}
{"id": 49746, "name": "Juggler sequence", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n"}
{"id": 49747, "name": "Juggler sequence", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n"}
{"id": 49748, "name": "Sierpinski square curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n"}
{"id": 49749, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n"}
{"id": 49750, "name": "Powerful numbers", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n"}
{"id": 49751, "name": "Fixed length records", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nvoid reverse(std::istream& in, std::ostream& out) {\n    constexpr size_t record_length = 80;\n    char record[record_length];\n    while (in.read(record, record_length)) {\n        std::reverse(std::begin(record), std::end(record));\n        out.write(record, record_length);\n    }\n    out.flush();\n}\n\nint main(int argc, char** argv) {\n    std::ifstream in(\"infile.dat\", std::ios_base::binary);\n    if (!in) {\n        std::cerr << \"Cannot open input file\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ofstream out(\"outfile.dat\", std::ios_base::binary);\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        in.exceptions(std::ios_base::badbit);\n        out.exceptions(std::ios_base::badbit);\n        reverse(in, out);\n    } catch (const std::exception& ex) {\n        std::cerr << \"I/O error: \" << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc reverseBytes(bytes []byte) {\n    for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {\n        bytes[i], bytes[j] = bytes[j], bytes[i]\n    }\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    in, err := os.Open(\"infile.dat\")\n    check(err)\n    defer in.Close()\n\n    out, err := os.Create(\"outfile.dat\")\n    check(err)\n\n    record := make([]byte, 80)\n    empty := make([]byte, 80)\n    for {\n        n, err := in.Read(record)\n        if err != nil {\n            if n == 0 {\n                break \n            } else {\n                out.Close()\n                log.Fatal(err)\n            }\n        }\n        reverseBytes(record)\n        out.Write(record)\n        copy(record, empty)\n    }\n    out.Close()\n\n    \n    \n    cmd := exec.Command(\"dd\", \"if=outfile.dat\", \"cbs=80\", \"conv=unblock\")\n    bytes, err := cmd.Output()\n    check(err)\n    fmt.Println(string(bytes))\n}\n"}
{"id": 49752, "name": "Find words whose first and last three letters are equal", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        const size_t len = word.size();\n        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)\n            std::cout << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    count := 0\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {\n            count++\n            fmt.Printf(\"%d: %s\\n\", count, s)\n        }\n    }\n}\n"}
{"id": 49753, "name": "Giuga numbers", "C++": "#include <iostream>\n\n\nbool is_giuga(unsigned int n) {\n    unsigned int m = n / 2;\n    auto test_factor = [&m, n](unsigned int p) -> bool {\n        if (m % p != 0)\n            return true;\n        m /= p;\n        return m % p != 0 && (n / p - 1) % p == 0;\n    };\n    if (!test_factor(3) || !test_factor(5))\n        return false;\n    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n    for (unsigned int p = 7, i = 0; p * p <= m; ++i) {\n        if (!test_factor(p))\n            return false;\n        p += wheel[i & 7];\n    }\n    return m == 1 || (n / m - 1) % m == 0;\n}\n\nint main() {\n    std::cout << \"First 5 Giuga numbers:\\n\";\n    \n    for (unsigned int i = 0, n = 6; i < 5; n += 4) {\n        if (is_giuga(n)) {\n            std::cout << n << '\\n';\n            ++i;\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar factors []int\nvar inc = []int{4, 2, 4, 2, 4, 6, 2, 6}\n\n\n\nfunc primeFactors(n int) {\n    factors = factors[:0]\n    factors = append(factors, 2)\n    last := 2\n    n /= 2\n    for n%3 == 0 {\n        if last == 3 {\n            factors = factors[:0]\n            return\n        }\n        last = 3\n        factors = append(factors, 3)\n        n /= 3\n    }\n    for n%5 == 0 {\n        if last == 5 {\n            factors = factors[:0]\n            return\n        }\n        last = 5\n        factors = append(factors, 5)\n        n /= 5\n    }\n    for k, i := 7, 0; k*k <= n; {\n        if n%k == 0 {\n            if last == k {\n                factors = factors[:0]\n                return\n            }\n            last = k\n            factors = append(factors, k)\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        factors = append(factors, n)\n    }\n}\n\nfunc main() {\n    const limit = 5\n    var giuga []int\n    \n    for n := 6; len(giuga) < limit; n += 4 {\n        primeFactors(n)\n        \n        if len(factors) > 2 {\n            isGiuga := true\n            for _, f := range factors {\n                if (n/f-1)%f != 0 {\n                    isGiuga = false\n                    break\n                }\n            }\n            if isGiuga {\n                giuga = append(giuga, n)\n            }\n        }\n    }\n    fmt.Println(\"The first\", limit, \"Giuga numbers are:\")\n    fmt.Println(giuga)\n}\n"}
{"id": 49754, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 49755, "name": "Polynomial synthetic division", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 49756, "name": "Numbers whose count of divisors is prime", "C++": "#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n\nint divisor_count(int n) {\n    int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    for (int p = 3; p * p <= n; p += 2) {\n        int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nbool is_prime(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 (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(int argc, char** argv) {\n    int limit = 1000;\n    switch (argc) {\n    case 1:\n        break;\n    case 2:\n        limit = std::strtol(argv[1], nullptr, 10);\n        if (limit <= 0) {\n            std::cerr << \"Invalid limit\\n\";\n            return EXIT_FAILURE;\n        }\n        break;\n    default:\n        std::cerr << \"usage: \" << argv[0] << \" [limit]\\n\";\n        return EXIT_FAILURE;\n    }\n    int width = static_cast<int>(std::ceil(std::log10(limit)));\n    int count = 0;\n    for (int i = 1;; ++i) {\n        int n = i * i;\n        if (n >= limit)\n            break;\n        int divisors = divisor_count(n);\n        if (divisors != 2 && is_prime(divisors))\n            std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    for ; i*i <= n; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const limit = 1e5\n    var results []int\n    for i := 2; i * i < limit; i++ {\n        n := countDivisors(i * i)\n        if n > 2 && rcu.IsPrime(n) {\n            results = append(results, i * i)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Positive integers under %7s whose number of divisors is an odd prime:\\n\", climit)\n    under1000 := 0\n    for i, n := range results {\n        fmt.Printf(\"%7s\", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        if n < 1000 {\n            under1000++\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such integers (%d under 1,000).\\n\", len(results), under1000)\n}\n"}
{"id": 49757, "name": "Numbers whose count of divisors is prime", "C++": "#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n\nint divisor_count(int n) {\n    int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    for (int p = 3; p * p <= n; p += 2) {\n        int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nbool is_prime(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 (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(int argc, char** argv) {\n    int limit = 1000;\n    switch (argc) {\n    case 1:\n        break;\n    case 2:\n        limit = std::strtol(argv[1], nullptr, 10);\n        if (limit <= 0) {\n            std::cerr << \"Invalid limit\\n\";\n            return EXIT_FAILURE;\n        }\n        break;\n    default:\n        std::cerr << \"usage: \" << argv[0] << \" [limit]\\n\";\n        return EXIT_FAILURE;\n    }\n    int width = static_cast<int>(std::ceil(std::log10(limit)));\n    int count = 0;\n    for (int i = 1;; ++i) {\n        int n = i * i;\n        if (n >= limit)\n            break;\n        int divisors = divisor_count(n);\n        if (divisors != 2 && is_prime(divisors))\n            std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    for ; i*i <= n; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const limit = 1e5\n    var results []int\n    for i := 2; i * i < limit; i++ {\n        n := countDivisors(i * i)\n        if n > 2 && rcu.IsPrime(n) {\n            results = append(results, i * i)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Positive integers under %7s whose number of divisors is an odd prime:\\n\", climit)\n    under1000 := 0\n    for i, n := range results {\n        fmt.Printf(\"%7s\", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        if n < 1000 {\n            under1000++\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such integers (%d under 1,000).\\n\", len(results), under1000)\n}\n"}
{"id": 49758, "name": "Odd words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing word_list = std::vector<std::pair<std::string, std::string>>;\n\nvoid print_words(std::ostream& out, const word_list& words) {\n    int n = 1;\n    for (const auto& pair : words) {\n        out << std::right << std::setw(2) << n++ << \": \"\n            << std::left << std::setw(14) << pair.first\n            << pair.second << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    const int min_length = 5;\n    std::string line;\n    std::set<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            dictionary.insert(line);\n    }\n\n    word_list odd_words, even_words;\n\n    for (const std::string& word : dictionary) {\n        if (word.size() < min_length + 2*(min_length/2))\n            continue;\n        std::string odd_word, even_word;\n        for (auto w = word.begin(); w != word.end(); ++w) {\n            odd_word += *w;\n            if (++w == word.end())\n                break;\n            even_word += *w;\n        }\n\n        if (dictionary.find(odd_word) != dictionary.end())\n            odd_words.emplace_back(word, odd_word);\n\n        if (dictionary.find(even_word) != dictionary.end())\n            even_words.emplace_back(word, even_word);\n    }\n\n    std::cout << \"Odd words:\\n\";\n    print_words(std::cout, odd_words);\n\n    std::cout << \"\\nEven words:\\n\";\n    print_words(std::cout, even_words);\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    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n"}
{"id": 49759, "name": "Tree datastructures", "C++": "#include <iomanip>\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n#include <utility>\n#include <vector>\n\nclass nest_tree;\n\nbool operator==(const nest_tree&, const nest_tree&);\n\nclass nest_tree {\npublic:\n    explicit nest_tree(const std::string& name) : name_(name) {}\n    nest_tree& add_child(const std::string& name) {\n        children_.emplace_back(name);\n        return children_.back();\n    }\n    void print(std::ostream& out) const {\n        print(out, 0);\n    }\n    const std::string& name() const {\n        return name_;\n    }\n    const std::list<nest_tree>& children() const {\n        return children_;\n    }\n    bool equals(const nest_tree& n) const {\n        return name_ == n.name_ && children_ == n.children_;\n    }\nprivate:\n    void print(std::ostream& out, int level) const {\n        std::string indent(level * 4, ' ');\n        out << indent << name_ << '\\n';\n        for (const nest_tree& child : children_)\n            child.print(out, level + 1);\n    }\n    std::string name_;\n    std::list<nest_tree> children_;\n};\n\nbool operator==(const nest_tree& a, const nest_tree& b) {\n    return a.equals(b);\n}\n\nclass indent_tree {\npublic:\n    explicit indent_tree(const nest_tree& n) {\n        items_.emplace_back(0, n.name());\n        from_nest(n, 0);\n    }\n    void print(std::ostream& out) const {\n        for (const auto& item : items_)\n            std::cout << item.first << ' ' << item.second << '\\n';\n    }\n    nest_tree to_nest() const {\n        nest_tree n(items_[0].second);\n        to_nest_(n, 1, 0);\n        return n;\n    }\nprivate:\n    void from_nest(const nest_tree& n, int level) {\n        for (const nest_tree& child : n.children()) {\n            items_.emplace_back(level + 1, child.name());\n            from_nest(child, level + 1);\n        }\n    }\n    size_t to_nest_(nest_tree& n, size_t pos, int level) const {\n        while (pos < items_.size() && items_[pos].first == level + 1) {\n            nest_tree& child = n.add_child(items_[pos].second);\n            pos = to_nest_(child, pos + 1, level + 1);\n        }\n        return pos;\n    }\n    std::vector<std::pair<int, std::string>> items_;\n};\n\nint main() {\n    nest_tree n(\"RosettaCode\");\n    auto& child1 = n.add_child(\"rocks\");\n    auto& child2 = n.add_child(\"mocks\");\n    child1.add_child(\"code\");\n    child1.add_child(\"comparison\");\n    child1.add_child(\"wiki\");\n    child2.add_child(\"trolling\");\n    \n    std::cout << \"Initial nest format:\\n\";\n    n.print(std::cout);\n    \n    indent_tree i(n);\n    std::cout << \"\\nIndent format:\\n\";\n    i.print(std::cout);\n    \n    nest_tree n2(i.to_nest());\n    std::cout << \"\\nFinal nest format:\\n\";\n    n2.print(std::cout);\n\n    std::cout << \"\\nAre initial and final nest formats equal? \"\n        << std::boolalpha << n.equals(n2) << '\\n';\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n    if level == 0 {\n        fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n    }\n    fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\"  \", level), n.name)\n    for _, c := range n.children {\n        fmt.Fprintf(w, \"%s\", strings.Repeat(\"  \", level+1))\n        printNest(c, level+1, w)\n    }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n    fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n    for _, n := range iNodes {\n        fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n    }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n    *iNodes = append(*iNodes, iNode{level, n.name})\n    for _, c := range n.children {\n        toIndent(c, level+1, iNodes)\n    }\n}\n\nfunc main() {\n    n1 := nNode{\"RosettaCode\", nil}\n    n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n    n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n    n1.children = append(n1.children, n2, n3)\n\n    var sb strings.Builder\n    printNest(n1, 0, &sb)\n    s1 := sb.String()\n    fmt.Print(s1)\n\n    var iNodes []iNode\n    toIndent(n1, 0, &iNodes)\n    printIndent(iNodes, os.Stdout)\n\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    sb.Reset()\n    printNest(n, 0, &sb)\n    s2 := sb.String()\n    fmt.Print(s2)\n\n    fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}\n"}
{"id": 49760, "name": "Selectively replace multiple instances of a character within a string", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n"}
{"id": 49761, "name": "Selectively replace multiple instances of a character within a string", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n"}
{"id": 49762, "name": "Repunit primes", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n"}
{"id": 49763, "name": "Repunit primes", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n"}
{"id": 49764, "name": "Curzon numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 49765, "name": "Curzon numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 49766, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 49767, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 49768, "name": "Ramanujan's constant", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 49769, "name": "Respond to an unknown method call", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n"}
{"id": 49770, "name": "Word break problem", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n"}
{"id": 49771, "name": "Brilliant numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n"}
{"id": 49772, "name": "Brilliant numbers", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n"}
{"id": 49773, "name": "Word ladder", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n\nbool one_away(const std::string& s1, const std::string& s2) {\n    if (s1.size() != s2.size())\n        return false;\n    bool result = false;\n    for (size_t i = 0, n = s1.size(); i != n; ++i) {\n        if (s1[i] != s2[i]) {\n            if (result)\n                return false;\n            result = true;\n        }\n    }\n    return result;\n}\n\n\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n                 separator_type separator) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += separator;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\n\n\n\nbool word_ladder(const word_map& words, const std::string& from,\n                 const std::string& to) {\n    auto w = words.find(from.size());\n    if (w != words.end()) {\n        auto poss = w->second;\n        std::vector<std::vector<std::string>> queue{{from}};\n        while (!queue.empty()) {\n            auto curr = queue.front();\n            queue.erase(queue.begin());\n            for (auto i = poss.begin(); i != poss.end();) {\n                if (!one_away(*i, curr.back())) {\n                    ++i;\n                    continue;\n                }\n                if (to == *i) {\n                    curr.push_back(to);\n                    std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n                    return true;\n                }\n                std::vector<std::string> temp(curr);\n                temp.push_back(*i);\n                queue.push_back(std::move(temp));\n                i = poss.erase(i);\n            }\n        }\n    }\n    std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n    return false;\n}\n\nint main() {\n    word_map words;\n    std::ifstream in(\"unixdict.txt\");\n    if (!in) {\n        std::cerr << \"Cannot open file unixdict.txt.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    while (getline(in, word))\n        words[word.size()].push_back(word);\n    word_ladder(words, \"boy\", \"man\");\n    word_ladder(words, \"girl\", \"lady\");\n    word_ladder(words, \"john\", \"jane\");\n    word_ladder(words, \"child\", \"adult\");\n    word_ladder(words, \"cat\", \"dog\");\n    word_ladder(words, \"lead\", \"gold\");\n    word_ladder(words, \"white\", \"black\");\n    word_ladder(words, \"bubble\", \"tickle\");\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n"}
{"id": 49774, "name": "Equal prime and composite sums", "C++": "#include <primesieve.hpp>\n\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n\nclass composite_iterator {\npublic:\n    composite_iterator();\n    uint64_t next_composite();\n\nprivate:\n    uint64_t composite;\n    uint64_t prime;\n    primesieve::iterator pi;\n};\n\ncomposite_iterator::composite_iterator() {\n    composite = prime = pi.next_prime();\n    for (; composite == prime; ++composite)\n        prime = pi.next_prime();\n}\n\nuint64_t composite_iterator::next_composite() {\n    uint64_t result = composite;\n    while (++composite == prime)\n        prime = pi.next_prime();\n    return result;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    composite_iterator ci;\n    primesieve::iterator pi;\n    uint64_t prime_sum = pi.next_prime();\n    uint64_t composite_sum = ci.next_composite();\n    uint64_t prime_index = 1, composite_index = 1;\n    std::cout << \"Sum                   | Prime Index  | Composite Index\\n\";\n    std::cout << \"------------------------------------------------------\\n\";\n    for (int count = 0; count < 11;) {\n        if (prime_sum == composite_sum) {\n            std::cout << std::right << std::setw(21) << prime_sum << \" | \"\n                      << std::setw(12) << prime_index << \" | \" << std::setw(15)\n                      << composite_index << '\\n';\n            composite_sum += ci.next_composite();\n            prime_sum += pi.next_prime();\n            ++prime_index;\n            ++composite_index;\n            ++count;\n        } else if (prime_sum < composite_sum) {\n            prime_sum += pi.next_prime();\n            ++prime_index;\n        } else {\n            composite_sum += ci.next_composite();\n            ++composite_index;\n        }\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc ord(n int) string {\n    if n < 0 {\n        log.Fatal(\"Argument must be a non-negative integer.\")\n    }\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%sth\", rcu.Commatize(n))\n    }\n    m %= 10\n    suffix := \"th\"\n    if m == 1 {\n        suffix = \"st\"\n    } else if m == 2 {\n        suffix = \"nd\"\n    } else if m == 3 {\n        suffix = \"rd\"\n    }\n    return fmt.Sprintf(\"%s%s\", rcu.Commatize(n), suffix)\n}\n\nfunc main() {\n    limit := int(4 * 1e8)\n    c := rcu.PrimeSieve(limit-1, true)\n    var compSums []int\n    var primeSums []int\n    csum := 0\n    psum := 0\n    for i := 2; i < limit; i++ {\n        if c[i] {\n            csum += i\n            compSums = append(compSums, csum)\n        } else {\n            psum += i\n            primeSums = append(primeSums, psum)\n        }\n    }\n\n    for i := 0; i < len(primeSums); i++ {\n        ix := sort.SearchInts(compSums, primeSums[i])\n        if ix < len(compSums) && compSums[ix] == primeSums[i] {\n            cps := rcu.Commatize(primeSums[i])\n            fmt.Printf(\"%21s - %12s prime sum, %12s composite sum\\n\", cps, ord(i+1), ord(ix+1))\n        }\n    }\n}\n"}
{"id": 49775, "name": "Joystick position", "C++": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid clear() {\n\tfor(int n = 0;n < 10; n++) {\n\t\tprintf(\"\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\r\\n\\r\\n\\r\\n\");\n\t}\n}\n\n#define UP    \"00^00\\r\\n00|00\\r\\n00000\\r\\n\"\n#define DOWN  \"00000\\r\\n00|00\\r\\n00v00\\r\\n\"\n#define LEFT  \"00000\\r\\n<--00\\r\\n00000\\r\\n\"\n#define RIGHT \"00000\\r\\n00-->\\r\\n00000\\r\\n\"\n#define HOME  \"00000\\r\\n00+00\\r\\n00000\\r\\n\"\n\nint main() {\n\tclear();\n\tsystem(\"stty raw\");\n\n\tprintf(HOME);\n\tprintf(\"space to exit; wasd to move\\r\\n\");\n\tchar c = 1;\n\n\twhile(c) {\n\t\tc = getc(stdin);\n\t\tclear();\n\n\t\tswitch (c)\n\t\t{\n\t\t\tcase 'a':\n\t\t\t\tprintf(LEFT);\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tprintf(RIGHT);\n\t\t\t\tbreak;\n\t\t\tcase 'w':\n\t\t\t\tprintf(UP);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tprintf(DOWN);\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tc = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprintf(HOME);\n\t\t};\n\n\t\tprintf(\"space to exit; wasd key to move\\r\\n\");\n\t}\n\n\tsystem(\"stty cooked\");\n\tsystem(\"clear\"); \n\treturn 1;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"github.com/simulatedsimian/joystick\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc printAt(x, y int, s string) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)\n        x++\n    }\n}\n\nfunc readJoystick(js joystick.Joystick, hidden bool) {\n    jinfo, err := js.Read()\n    check(err)\n\n    w, h := termbox.Size()\n    tbcd := termbox.ColorDefault\n    termbox.Clear(tbcd, tbcd)\n    printAt(1, h-1, \"q - quit\")\n    if hidden {\n        printAt(11, h-1, \"s - show buttons:\")\n    } else {\n        bs := \"\"\n        printAt(11, h-1, \"h - hide buttons:\")\n        for button := 0; button < js.ButtonCount(); button++ {\n            if jinfo.Buttons&(1<<uint32(button)) != 0 {\n                \n                bs += fmt.Sprintf(\" %X\", button+1)\n            }\n        }\n        printAt(28, h-1, bs)\n    }\n\n    \n    x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)\n    y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)\n    printAt(x, y, \"+\") \n    termbox.Flush()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    \n    \n    jsid := 0\n    \n    if len(os.Args) > 1 {\n        i, err := strconv.Atoi(os.Args[1])\n        check(err)\n        jsid = i\n    }\n\n    js, jserr := joystick.Open(jsid)\n    check(jserr)\n \n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    ticker := time.NewTicker(time.Millisecond * 40)\n    hidden := false \n\n    for doQuit := false; !doQuit; {\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'q' {\n                    doQuit = true\n                } else if ev.Ch == 'h' {\n                    hidden = true\n                } else if ev.Ch == 's' {\n                    hidden = false\n                }\n            }\n            if ev.Type == termbox.EventResize {\n                termbox.Flush()\n            }\n        case <-ticker.C:\n            readJoystick(js, hidden)\n        }\n    }\n}\n"}
{"id": 49776, "name": "Earliest difference between prime gaps", "C++": "#include <iostream>\n#include <locale>\n#include <unordered_map>\n\n#include <primesieve.hpp>\n\nclass prime_gaps {\npublic:\n    prime_gaps() { last_prime_ = iterator_.next_prime(); }\n    uint64_t find_gap_start(uint64_t gap);\nprivate:\n    primesieve::iterator iterator_;\n    uint64_t last_prime_;\n    std::unordered_map<uint64_t, uint64_t> gap_starts_;\n};\n\nuint64_t prime_gaps::find_gap_start(uint64_t gap) {\n    auto i = gap_starts_.find(gap);\n    if (i != gap_starts_.end())\n        return i->second;\n    for (;;) {\n        uint64_t prev = last_prime_;\n        last_prime_ = iterator_.next_prime();\n        uint64_t diff = last_prime_ - prev;\n        gap_starts_.emplace(diff, prev);\n        if (gap == diff)\n            return prev;\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const uint64_t limit = 100000000000;\n    prime_gaps pg;\n    for (uint64_t pm = 10, gap1 = 2;;) {\n        uint64_t start1 = pg.find_gap_start(gap1);\n        uint64_t gap2 = gap1 + 2;\n        uint64_t start2 = pg.find_gap_start(gap2);\n        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;\n        if (diff > pm) {\n            std::cout << \"Earliest difference > \" << pm\n                      << \" between adjacent prime gap starting primes:\\n\"\n                      << \"Gap \" << gap1 << \" starts at \" << start1 << \", gap \"\n                      << gap2 << \" starts at \" << start2 << \", difference is \"\n                      << diff << \".\\n\\n\";\n            if (pm == limit)\n                break;\n            pm *= 10;\n        } else {\n            gap1 = gap2;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n"}
{"id": 49777, "name": "Latin Squares in reduced form", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n"}
{"id": 49778, "name": "Ormiston pairs", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <utility>\n\n#include <primesieve.hpp>\n\nclass ormiston_pair_generator {\npublic:\n    ormiston_pair_generator() { prime_ = pi_.next_prime(); }\n    std::pair<uint64_t, uint64_t> next_pair() {\n        for (;;) {\n            uint64_t prime = prime_;\n            auto digits = digits_;\n            prime_ = pi_.next_prime();\n            digits_ = get_digits(prime_);\n            if (digits_ == digits)\n                return std::make_pair(prime, prime_);\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    uint64_t prime_;\n    std::array<int, 10> digits_;\n};\n\nint main() {\n    ormiston_pair_generator generator;\n    int count = 0;\n    std::cout << \"First 30 Ormiston pairs:\\n\";\n    for (; count < 30; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        std::cout << '(' << std::setw(5) << p1 << \", \" << std::setw(5) << p2\n                  << ')' << ((count + 1) % 3 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        if (p1 > limit) {\n            std::cout << \"Number of Ormiston pairs < \" << limit << \": \" << count\n                      << '\\n';\n            limit *= 10;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e9\n    primes := rcu.Primes(limit)\n    var orm30 [][2]int\n    j := int(1e5)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-1; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        if (p2-p1)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 == key2 {\n            if count < 30 {\n                orm30 = append(orm30, [2]int{p1, p2})\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"First 30 Ormiston pairs:\")\n    for i := 0; i < 30; i++ {\n        fmt.Printf(\"%5v \", orm30[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e5)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston pairs before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n    }\n}\n"}
{"id": 49779, "name": "UPC", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 49780, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 49781, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 49782, "name": "Harmonic series", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\nusing integer = boost::multiprecision::mpz_int;\nusing rational = boost::rational<integer>;\n\nclass harmonic_generator {\npublic:\n    rational next() {\n        rational result = term_;\n        term_ += rational(1, ++n_);\n        return result;\n    }\n    void reset() {\n        n_ = 1;\n        term_ = 1;\n    }\nprivate:\n    integer n_ = 1;\n    rational term_ = 1;\n};\n\nint main() {\n    std::cout << \"First 20 harmonic numbers:\\n\";\n    harmonic_generator hgen;\n    for (int i = 1; i <= 20; ++i)\n        std::cout << std::setw(2) << i << \". \" << hgen.next() << '\\n';\n    \n    rational h;\n    for (int i = 1; i <= 80; ++i)\n        h = hgen.next();\n    std::cout << \"\\n100th harmonic number: \" << h << \"\\n\\n\";\n\n    int n = 1;\n    hgen.reset();\n    for (int i = 1; n <= 10; ++i) {\n        if (hgen.next() > n)\n            std::cout << \"Position of first term > \" << std::setw(2) << n++ << \": \" << i << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc harmonic(n int) *big.Rat {\n    sum := new(big.Rat)\n    for i := int64(1); i <= int64(n); i++ {\n        r := big.NewRat(1, i)\n        sum.Add(sum, r)\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The first 20 harmonic numbers and the 100th, expressed in rational form, are:\")\n    numbers := make([]int, 21)\n    for i := 1; i <= 20; i++ {\n        numbers[i-1] = i\n    }\n    numbers[20] = 100\n    for _, i := range numbers {\n        fmt.Printf(\"%3d : %s\\n\", i, harmonic(i))\n    }\n\n    fmt.Println(\"\\nThe first harmonic number to exceed the following integers is:\")\n    const limit = 10\n    for i, n, h := 1, 1, 0.0; i <= limit; n++ {\n        h += 1.0 / float64(n)\n        if h > float64(i) {\n            fmt.Printf(\"integer = %2d  -> n = %6d  ->  harmonic number = %9.6f (to 6dp)\\n\", i, n, h)\n            i++\n        }\n    }\n}\n"}
{"id": 49783, "name": "External sort", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n"}
{"id": 49784, "name": "External sort", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n"}
{"id": 49785, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n)", "C++": "\nclass matrixNG {\n  private:\n  virtual void consumeTerm(){}\n  virtual void consumeTerm(int n){}\n  virtual const bool needTerm(){}\n  protected: int cfn = 0, thisTerm;\n             bool haveTerm = false;\n  friend class NG;\n};\n\nclass NG_4 : public matrixNG {\n  private: int a1, a, b1, b, t;\n  const bool needTerm() {\n    if (b1==0 and b==0) return false;\n    if (b1==0 or b==0) return true; else thisTerm = a/b;\n    if (thisTerm==(int)(a1/b1)){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;\n      haveTerm=true; return false;\n    }\n    return true;\n  }\n  void consumeTerm(){a=a1; b=b1;}\n  void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}\n  public:\n  NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}\n};\n\nclass NG : public ContinuedFraction {\n  private:\n   matrixNG* ng;\n   ContinuedFraction* n[2];\n  public:\n  NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}\n  NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}\n  const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}\n  const bool moreTerms(){\n    while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();\n    return ng->haveTerm;\n  }\n};\n", "Go": "package cf\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG4 struct {\n\tA1, A int64\n\tB1, B int64\n}\n\nfunc (ng NG4) needsIngest() bool {\n\tif ng.isDone() {\n\t\tpanic(\"b₁==b==0\")\n\t}\n\treturn ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B\n}\n\nfunc (ng NG4) isDone() bool {\n\treturn ng.B1 == 0 && ng.B == 0\n}\n\nfunc (ng *NG4) ingest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.A+ng.A1*t, ng.A1,\n\t\tng.B+ng.B1*t, ng.B1\n}\n\nfunc (ng *NG4) ingestInfinite() {\n\t\n\t\n\tng.A, ng.B = ng.A1, ng.B1\n}\n\nfunc (ng *NG4) egest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.B1, ng.B,\n\t\tng.A1-ng.B1*t, ng.A-ng.B*t\n}\n\n\n\nfunc (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext := cf()\n\t\tdone := false\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite()\n\t\t\t\t}\n\t\t\t}\n\t\t\tt := ng.A1 / ng.B1\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n"}
{"id": 49786, "name": "Calkin-Wilf sequence", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n"}
{"id": 49787, "name": "Calkin-Wilf sequence", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n"}
{"id": 49788, "name": "Distribution of 0 digits in factorial series", "C++": "#include <array>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nauto init_zc() {\n    std::array<int, 1000> zc;\n    zc.fill(0);\n    zc[0] = 3;\n    for (int x = 1; x <= 9; ++x) {\n        zc[x] = 2;\n        zc[10 * x] = 2;\n        zc[100 * x] = 2;\n        for (int y = 10; y <= 90; y += 10) {\n            zc[y + x] = 1;\n            zc[10 * y + x] = 1;\n            zc[10 * (y + x)] = 1;\n        }\n    }\n    return zc;\n}\n\ntemplate <typename clock_type>\nauto elapsed(const std::chrono::time_point<clock_type>& t0) {\n    auto t1 = clock_type::now();\n    auto duration =\n        std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);\n    return duration.count();\n}\n\nint main() {\n    auto zc = init_zc();\n    auto t0 = std::chrono::high_resolution_clock::now();\n    int trail = 1, first = 0;\n    double total = 0;\n    std::vector<int> rfs{1};\n    std::cout << std::fixed << std::setprecision(10);\n    for (int f = 2; f <= 50000; ++f) {\n        int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();\n        for (int j = trail - 1; j < len || carry != 0; ++j) {\n            if (j < len)\n                carry += rfs[j] * f;\n            d999 = carry % 1000;\n            if (j < len)\n                rfs[j] = d999;\n            else\n                rfs.push_back(d999);\n            zeroes += zc[d999];\n            carry /= 1000;\n        }\n        while (rfs[trail - 1] == 0)\n            ++trail;\n        d999 = rfs.back();\n        d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;\n        zeroes -= d999;\n        int digits = rfs.size() * 3 - d999;\n        total += double(zeroes) / digits;\n        double ratio = total / f;\n        if (ratio >= 0.16)\n            first = 0;\n        else if (first == 0)\n            first = f;\n        if (f == 100 || f == 1000 || f == 10000) {\n            std::cout << \"Mean proportion of zero digits in factorials to \" << f\n                      << \" is \" << ratio << \". (\" << elapsed(t0) << \"ms)\\n\";\n        }\n    }\n    std::cout << \"The mean proportion dips permanently below 0.16 at \" << first\n              << \". (\" << elapsed(t0) << \"ms)\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nfunc main() {\n    fact  := big.NewInt(1)\n    sum   := 0.0\n    first := int64(0)\n    firstRatio := 0.0    \n    fmt.Println(\"The mean proportion of zero digits in factorials up to the following are:\")\n    for n := int64(1); n <= 50000; n++  {\n        fact.Mul(fact, big.NewInt(n))\n        bytes  := []byte(fact.String())\n        digits := len(bytes)\n        zeros  := 0\n        for _, b := range bytes {\n            if b == '0' {\n                zeros++\n            }\n        }\n        sum += float64(zeros)/float64(digits)\n        ratio := sum / float64(n)\n        if n == 100 || n == 1000 || n == 10000 {\n            fmt.Printf(\"%6s = %12.10f\\n\", rcu.Commatize(int(n)), ratio)\n        } \n        if first > 0 && ratio >= 0.16 {\n            first = 0\n            firstRatio = 0.0\n        } else if first == 0 && ratio < 0.16 {\n            first = n\n            firstRatio = ratio           \n        }\n    }\n    fmt.Printf(\"%6s = %12.10f\", rcu.Commatize(int(first)), firstRatio)\n    fmt.Println(\" (stays below 0.16 after this)\")\n    fmt.Printf(\"%6s = %12.10f\\n\", \"50,000\", sum / 50000)\n}\n"}
{"id": 49789, "name": "Closest-pair problem", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n"}
{"id": 49790, "name": "Address of a variable", "C++": "int i;\nvoid* address_of_i = &i;\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n"}
{"id": 49791, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 49792, "name": "Associative array_Creation", "C++": "#include <map>\n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 49793, "name": "Wilson primes of order n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\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\nint main() {\n    using big_int = mpz_class;\n    const int limit = 11000;\n    std::vector<big_int> f{1};\n    f.reserve(limit);\n    big_int factorial = 1;\n    for (int i = 1; i < limit; ++i) {\n        factorial *= i;\n        f.push_back(factorial);\n    }\n    std::vector<int> primes = generate_primes(limit);\n    std::cout << \" n | Wilson primes\\n--------------------\\n\";\n    for (int n = 1, s = -1; n <= 11; ++n, s = -s) {\n        std::cout << std::setw(2) << n << \" |\";\n        for (int p : primes) {\n            if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)\n                std::cout << ' ' << p;\n        }\n        std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n)\n\nfunc main() {\n    const LIMIT = 11000\n    primes := rcu.Primes(LIMIT)\n    facts := make([]*big.Int, LIMIT)\n    facts[0] = big.NewInt(1)\n    for i := int64(1); i < LIMIT; i++ {\n        facts[i] = new(big.Int)\n        facts[i].Mul(facts[i-1], big.NewInt(i))\n    }\n    sign := int64(1)\n    f := new(big.Int)\n    zero := new(big.Int)\n    fmt.Println(\" n:  Wilson primes\")\n    fmt.Println(\"--------------------\")\n    for n := 1; n < 12; n++ {\n        fmt.Printf(\"%2d:  \", n)\n        sign = -sign\n        for _, p := range primes {\n            if p < n {\n                continue\n            }\n            f.Mul(facts[n-1], facts[p-n])\n            f.Sub(f, big.NewInt(sign))\n            p2 := int64(p * p)\n            bp2 := big.NewInt(p2)\n            if f.Rem(f, bp2).Cmp(zero) == 0 {\n                fmt.Printf(\"%d \", p)\n            }\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 49794, "name": "Multi-base primes", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <primesieve.hpp>\n\nclass prime_sieve {\npublic:\n    explicit prime_sieve(uint64_t limit);\n    bool is_prime(uint64_t n) const {\n        return n == 2 || ((n & 1) == 1 && sieve[n >> 1]);\n    }\n\nprivate:\n    std::vector<bool> sieve;\n};\n\nprime_sieve::prime_sieve(uint64_t limit) : sieve((limit + 1) / 2, false) {\n    primesieve::iterator iter;\n    uint64_t prime = iter.next_prime(); \n    while ((prime = iter.next_prime()) <= limit) {\n        sieve[prime >> 1] = true;\n    }\n}\n\ntemplate <typename T> void print(std::ostream& out, const std::vector<T>& v) {\n    if (!v.empty()) {\n        out << '[';\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << \", \" << *i;\n        out << ']';\n    }\n}\n\nstd::string to_string(const std::vector<unsigned int>& v) {\n    static constexpr char digits[] =\n        \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (auto i : v)\n        str += digits[i];\n    return str;\n}\n\nbool increment(std::vector<unsigned int>& digits, unsigned int max_base) {\n    for (auto i = digits.rbegin(); i != digits.rend(); ++i) {\n        if (*i + 1 != max_base) {\n            ++*i;\n            return true;\n        }\n        *i = 0;\n    }\n    return false;\n}\n\nvoid multi_base_primes(unsigned int max_base, unsigned int max_length) {\n    prime_sieve sieve(static_cast<uint64_t>(std::pow(max_base, max_length)));\n    for (unsigned int length = 1; length <= max_length; ++length) {\n        std::cout << length\n                  << \"-character strings which are prime in most bases: \";\n        unsigned int most_bases = 0;\n        std::vector<\n            std::pair<std::vector<unsigned int>, std::vector<unsigned int>>>\n            max_strings;\n        std::vector<unsigned int> digits(length, 0);\n        digits[0] = 1;\n        std::vector<unsigned int> bases;\n        do {\n            auto max = std::max_element(digits.begin(), digits.end());\n            unsigned int min_base = 2;\n            if (max != digits.end())\n                min_base = std::max(min_base, *max + 1);\n            if (most_bases > max_base - min_base + 1)\n                continue;\n            bases.clear();\n            for (unsigned int b = min_base; b <= max_base; ++b) {\n                if (max_base - b + 1 + bases.size() < most_bases)\n                    break;\n                uint64_t n = 0;\n                for (auto d : digits)\n                    n = n * b + d;\n                if (sieve.is_prime(n))\n                    bases.push_back(b);\n            }\n            if (bases.size() > most_bases) {\n                most_bases = bases.size();\n                max_strings.clear();\n            }\n            if (bases.size() == most_bases)\n                max_strings.emplace_back(digits, bases);\n        } while (increment(digits, max_base));\n        std::cout << most_bases << '\\n';\n        for (const auto& m : max_strings) {\n            std::cout << to_string(m.first) << \" -> \";\n            print(std::cout, m.second);\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    unsigned int max_base = 36;\n    unsigned int max_length = 4;\n    for (int arg = 1; arg + 1 < argc; ++arg) {\n        if (strcmp(argv[arg], \"-max_base\") == 0)\n            max_base = strtoul(argv[++arg], nullptr, 10);\n        else if (strcmp(argv[arg], \"-max_length\") == 0)\n            max_length = strtoul(argv[++arg], nullptr, 10);\n    }\n    if (max_base > 62) {\n        std::cerr << \"Max base cannot be greater than 62.\\n\";\n        return EXIT_FAILURE;\n    }\n    if (max_base < 2) {\n        std::cerr << \"Max base cannot be less than 2.\\n\";\n        return EXIT_FAILURE;\n    }\n    multi_base_primes(max_base, max_length);\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nvar maxDepth = 6\nvar maxBase = 36\nvar c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)\nvar digits = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nvar maxStrings [][][]int\nvar mostBases = -1\n\nfunc maxSlice(a []int) int {\n    max := 0\n    for _, e := range a {\n        if e > max {\n            max = e\n        }\n    }\n    return max\n}\n\nfunc maxInt(a, b int) int {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nfunc process(indices []int) {\n    minBase := maxInt(2, maxSlice(indices)+1)\n    if maxBase - minBase + 1 < mostBases {\n        return  \n    }\n    var bases []int\n    for b := minBase; b <= maxBase; b++ {\n        n := 0\n        for _, i := range indices {\n            n = n*b + i\n        }\n        if !c[n] {\n            bases = append(bases, b)\n        }\n    }\n    count := len(bases)\n    if count > mostBases {\n        mostBases = count\n        indices2 := make([]int, len(indices))\n        copy(indices2, indices)\n        maxStrings = [][][]int{[][]int{indices2, bases}}\n    } else if count == mostBases {\n        indices2 := make([]int, len(indices))\n        copy(indices2, indices)\n        maxStrings = append(maxStrings, [][]int{indices2, bases})\n    }\n}\n\nfunc printResults() {\n    fmt.Printf(\"%d\\n\", len(maxStrings[0][1]))\n    for _, m := range maxStrings {\n        s := \"\"\n        for _, i := range m[0] {\n            s = s + string(digits[i])\n        }\n        fmt.Printf(\"%s -> %v\\n\", s, m[1])\n    }\n}\n\nfunc nestedFor(indices []int, length, level int) {\n    if level == len(indices) {\n        process(indices)\n    } else {\n        indices[level] = 0\n        if level == 0 {\n            indices[level] = 1\n        }\n        for indices[level] < length {\n            nestedFor(indices, length, level+1)\n            indices[level]++\n        }\n    }\n}\n\nfunc main() {\n    for depth := 1; depth <= maxDepth; depth++ {\n        fmt.Print(depth, \" character strings which are prime in most bases: \")\n        maxStrings = maxStrings[:0]\n        mostBases = -1\n        indices := make([]int, depth)\n        nestedFor(indices, maxBase, 0)\n        printResults()\n        fmt.Println()\n    }\n}\n"}
{"id": 49795, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n"}
{"id": 49796, "name": "Plasma effect", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n"}
{"id": 49797, "name": "Abelian sandpile model_Identity", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n"}
{"id": 49798, "name": "Abelian sandpile model_Identity", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n"}
{"id": 49799, "name": "Rhonda numbers", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint digit_product(int base, int n) {\n    int product = 1;\n    for (; n != 0; n /= base)\n        product *= n % base;\n    return product;\n}\n\nint prime_factor_sum(int n) {\n    int sum = 0;\n    for (; (n & 1) == 0; n >>= 1)\n        sum += 2;\n    for (int p = 3; p * p <= n; p += 2)\n        for (; n % p == 0; n /= p)\n            sum += p;\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nbool is_prime(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 (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\nbool is_rhonda(int base, int n) {\n    return digit_product(base, n) == base * prime_factor_sum(n);\n}\n\nstd::string to_string(int base, int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nint main() {\n    const int limit = 15;\n    for (int base = 2; base <= 36; ++base) {\n        if (is_prime(base))\n            continue;\n        std::cout << \"First \" << limit << \" Rhonda numbers to base \" << base\n                  << \":\\n\";\n        int numbers[limit];\n        for (int n = 1, count = 0; count < limit; ++n) {\n            if (is_rhonda(base, n))\n                numbers[count++] = n;\n        }\n        std::cout << \"In base 10:\";\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << numbers[i];\n        std::cout << \"\\nIn base \" << base << ':';\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << to_string(base, numbers[i]);\n        std::cout << \"\\n\\n\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc contains(a []int, n int) bool {\n    for _, e := range a {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    for b := 2; b <= 36; b++ {\n        if rcu.IsPrime(b) {\n            continue\n        }\n        count := 0\n        var rhonda []int\n        for n := 1; count < 15; n++ {\n            digits := rcu.Digits(n, b)\n            if !contains(digits, 0) {\n                var anyEven = false\n                for _, d := range digits {\n                    if d%2 == 0 {\n                        anyEven = true\n                        break\n                    }\n                }\n                if b != 10 || (contains(digits, 5) && anyEven) {\n                    calc1 := 1\n                    for _, d := range digits {\n                        calc1 *= d\n                    }\n                    calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))\n                    if calc1 == calc2 {\n                        rhonda = append(rhonda, n)\n                        count++\n                    }\n                }\n            }\n        }\n        if len(rhonda) > 0 {\n            fmt.Printf(\"\\nFirst 15 Rhonda numbers in base %d:\\n\", b)\n            rhonda2 := make([]string, len(rhonda))\n            counts2 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda2[i] = fmt.Sprintf(\"%d\", r)\n                counts2[i] = len(rhonda2[i])\n            }\n            rhonda3 := make([]string, len(rhonda))\n            counts3 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda3[i] = strconv.FormatInt(int64(r), b)\n                counts3[i] = len(rhonda3[i])\n            }\n            maxLen2 := rcu.MaxInts(counts2)\n            maxLen3 := rcu.MaxInts(counts3)\n            maxLen := maxLen2\n            if maxLen3 > maxLen {\n                maxLen = maxLen3\n            }\n            maxLen++\n            fmt.Printf(\"In base 10: %*s\\n\", maxLen, rhonda2)\n            fmt.Printf(\"In base %-2d: %*s\\n\", b, maxLen, rhonda3)\n        }\n    }\n}\n"}
{"id": 49800, "name": "Polymorphism", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 49801, "name": "Create an object_Native demonstration", "C++": "#include <iostream>\n#include <map>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nclass FixedMap : private T\n{\n    \n    \n    \n    \n    \n    T m_defaultValues;\n    \npublic:\n    FixedMap(T map)\n    : T(map), m_defaultValues(move(map)){}\n    \n    \n    using T::cbegin;\n    using T::cend;\n    using T::empty;\n    using T::find;\n    using T::size;\n\n    \n    using T::at;\n    using T::begin;\n    using T::end;\n    \n    \n    \n    auto& operator[](typename T::key_type&& key)\n    {\n        \n        return this->at(forward<typename T::key_type>(key));\n    }\n    \n    \n    \n    void erase(typename T::key_type&& key)\n    {\n        T::operator[](key) = m_defaultValues.at(key);\n    }\n\n    \n    void clear()\n    {\n        \n        T::operator=(m_defaultValues);\n    }\n    \n};\n\n\nauto PrintMap = [](const auto &map)\n{\n    for(auto &[key, value] : map)\n    {\n        cout << \"{\" << key << \" : \" << value << \"} \";\n    }\n    cout << \"\\n\\n\";\n};\n\nint main(void) \n{\n    \n    cout << \"Map intialized with values\\n\";\n    FixedMap<map<string, int>> fixedMap ({\n        {\"a\", 1},\n        {\"b\", 2}});\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values of the keys\\n\";\n    fixedMap[\"a\"] = 55;\n    fixedMap[\"b\"] = 56;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset the 'a' key\\n\";\n    fixedMap.erase(\"a\");\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values the again\\n\";\n    fixedMap[\"a\"] = 88;\n    fixedMap[\"b\"] = 99;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset all keys\\n\";\n    fixedMap.clear();\n    PrintMap(fixedMap);\n  \n    try\n    {\n        \n        cout << \"Try to add a new key\\n\";\n        fixedMap[\"newKey\"] = 99;\n    }\n    catch (exception &ex)\n    {\n        cout << \"error: \" << ex.what();\n    }\n}\n", "Go": "package romap\n\ntype Romap struct{ imap map[byte]int }\n\n\nfunc New(m map[byte]int) *Romap {\n    if m == nil {\n        return nil\n    }\n    return &Romap{m}\n}\n\n\nfunc (rom *Romap) Get(key byte) (int, bool) {\n    i, ok := rom.imap[key]\n    return i, ok\n}\n\n\nfunc (rom *Romap) Reset(key byte) {\n    _, ok := rom.imap[key]\n    if ok {\n        rom.imap[key] = 0 \n    }\n}\n"}
{"id": 49802, "name": "Find words which contain the most consonants", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n"}
{"id": 49803, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n"}
{"id": 49804, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n"}
{"id": 49805, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n"}
{"id": 49806, "name": "Prime words", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n"}
{"id": 49807, "name": "Numbers which are the cube roots of the product of their proper divisors", "C++": "#include <iomanip>\n#include <iostream>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\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    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"First 50 numbers which are the cube roots of the products of \"\n                 \"their proper divisors:\\n\";\n    for (unsigned int n = 1, count = 0; count < 50000; ++n) {\n        if (n == 1 || divisor_count(n) == 8) {\n            ++count;\n            if (count <= 50)\n                std::cout << std::setw(3) << n\n                          << (count % 10 == 0 ? '\\n' : ' ');\n            else if (count == 500 || count == 5000 || count == 50000)\n                std::cout << std::setw(6) << count << \"th: \" << n << '\\n';\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc divisorCount(n int) int {\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    count := 0\n    sqrt := int(math.Sqrt(float64(n)))\n    for i := 1; i <= sqrt; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    var numbers50 []int\n    count := 0\n    for n := 1; count < 50000; n++ {\n        dc := divisorCount(n)\n        if n == 1 || dc == 8 {\n            count++\n            if count <= 50 {\n                numbers50 = append(numbers50, n)\n                if count == 50 {\n                    rcu.PrintTable(numbers50, 10, 3, false)\n                }\n            } else if count == 500 {\n                fmt.Printf(\"\\n500th   : %s\", rcu.Commatize(n))\n            } else if count == 5000 {\n                fmt.Printf(\"\\n5,000th : %s\", rcu.Commatize(n))\n            } else if count == 50000 {\n                fmt.Printf(\"\\n50,000th: %s\\n\", rcu.Commatize(n))\n            }\n        }\n    }\n}\n"}
{"id": 49808, "name": "Ormiston triples", "C++": "#include <array>\n#include <iostream>\n\n#include <primesieve.hpp>\n\nclass ormiston_triple_generator {\npublic:\n    ormiston_triple_generator() {\n        for (int i = 0; i < 2; ++i) {\n            primes_[i] = pi_.next_prime();\n            digits_[i] = get_digits(primes_[i]);\n        }\n    }\n    std::array<uint64_t, 3> next_triple() {\n        for (;;) {\n            uint64_t prime = pi_.next_prime();\n            auto digits = get_digits(prime);\n            bool is_triple = digits == digits_[0] && digits == digits_[1];\n            uint64_t prime0 = primes_[0];\n            primes_[0] = primes_[1];\n            primes_[1] = prime;\n            digits_[0] = digits_[1];\n            digits_[1] = digits;\n            if (is_triple)\n                return {prime0, primes_[0], primes_[1]};\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    std::array<uint64_t, 2> primes_;\n    std::array<std::array<int, 10>, 2> digits_;\n};\n\nint main() {\n    ormiston_triple_generator generator;\n    int count = 0;\n    std::cout << \"Smallest members of first 25 Ormiston triples:\\n\";\n    for (; count < 25; ++count) {\n        auto primes = generator.next_triple();\n        std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {\n        auto primes = generator.next_triple();\n        if (primes[2] > limit) {\n            std::cout << \"Number of Ormiston triples < \" << limit << \": \"\n                      << count << '\\n';\n            limit *= 10;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e10\n    primes := rcu.Primes(limit)\n    var orm25 []int\n    j := int(1e9)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-2; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        p3 := primes[i+2]\n        if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 != key2 {\n            continue\n        }\n        key3 := 1\n        for _, dig := range rcu.Digits(p3, 10) {\n            key3 *= primes[dig]\n        }\n        if key2 == key3 {\n            if count < 25 {\n                orm25 = append(orm25, p1)\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"Smallest members of first 25 Ormiston triples:\")\n    for i := 0; i < 25; i++ {\n        fmt.Printf(\"%8v \", orm25[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e9)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston triples before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n        fmt.Println()\n    }\n}\n"}
{"id": 49809, "name": "Ormiston triples", "C++": "#include <array>\n#include <iostream>\n\n#include <primesieve.hpp>\n\nclass ormiston_triple_generator {\npublic:\n    ormiston_triple_generator() {\n        for (int i = 0; i < 2; ++i) {\n            primes_[i] = pi_.next_prime();\n            digits_[i] = get_digits(primes_[i]);\n        }\n    }\n    std::array<uint64_t, 3> next_triple() {\n        for (;;) {\n            uint64_t prime = pi_.next_prime();\n            auto digits = get_digits(prime);\n            bool is_triple = digits == digits_[0] && digits == digits_[1];\n            uint64_t prime0 = primes_[0];\n            primes_[0] = primes_[1];\n            primes_[1] = prime;\n            digits_[0] = digits_[1];\n            digits_[1] = digits;\n            if (is_triple)\n                return {prime0, primes_[0], primes_[1]};\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    std::array<uint64_t, 2> primes_;\n    std::array<std::array<int, 10>, 2> digits_;\n};\n\nint main() {\n    ormiston_triple_generator generator;\n    int count = 0;\n    std::cout << \"Smallest members of first 25 Ormiston triples:\\n\";\n    for (; count < 25; ++count) {\n        auto primes = generator.next_triple();\n        std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {\n        auto primes = generator.next_triple();\n        if (primes[2] > limit) {\n            std::cout << \"Number of Ormiston triples < \" << limit << \": \"\n                      << count << '\\n';\n            limit *= 10;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e10\n    primes := rcu.Primes(limit)\n    var orm25 []int\n    j := int(1e9)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-2; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        p3 := primes[i+2]\n        if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 != key2 {\n            continue\n        }\n        key3 := 1\n        for _, dig := range rcu.Digits(p3, 10) {\n            key3 *= primes[dig]\n        }\n        if key2 == key3 {\n            if count < 25 {\n                orm25 = append(orm25, p1)\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"Smallest members of first 25 Ormiston triples:\")\n    for i := 0; i < 25; i++ {\n        fmt.Printf(\"%8v \", orm25[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e9)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston triples before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n        fmt.Println()\n    }\n}\n"}
{"id": 49810, "name": "Elementary cellular automaton_Infinite length", "C++": "#include <iostream>\n#include <iomanip>\n#include <string>\n\nclass oo {\npublic:\n    void evolve( int l, int rule ) {\n        std::string    cells = \"O\";\n        std::cout << \" Rule #\" << rule << \":\\n\";\n        for( int x = 0; x < l; x++ ) {\n            addNoCells( cells );\n            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n            step( cells, rule );\n        }\n    }\nprivate:\n    void step( std::string& cells, int rule ) {\n        int bin;\n        std::string newCells;\n        for( size_t i = 0; i < cells.length() - 2; i++ ) {\n            bin = 0;\n            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n            }\n            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n        }\n        cells = newCells;\n    }\n    void addNoCells( std::string& s ) {\n        char l = s.at( 0 ) == 'O' ? '.' : 'O',\n             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n        s = l + s + r;\n        s = l + s + r;\n    }\n};\nint main( int argc, char* argv[] ) {\n    oo o;\n    o.evolve( 35, 90 );\n    std::cout << \"\\n\";\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc evolve(l, rule int) {\n    fmt.Printf(\" Rule #%d:\\n\", rule)\n    cells := \"O\"\n    for x := 0; x < l; x++ {\n        cells = addNoCells(cells)\n        width := 40 + (len(cells) >> 1)\n        fmt.Printf(\"%*s\\n\", width, cells)\n        cells = step(cells, rule)\n    }\n}\n\nfunc step(cells string, rule int) string {\n    newCells := new(strings.Builder)\n    for i := 0; i < len(cells)-2; i++ {\n        bin := 0\n        b := uint(2)\n        for n := i; n < i+3; n++ {\n            bin += btoi(cells[n] == 'O') << b\n            b >>= 1\n        }\n        a := '.'\n        if rule&(1<<uint(bin)) != 0 {\n            a = 'O'\n        }\n        newCells.WriteRune(a)\n    }\n    return newCells.String()\n}\n\nfunc addNoCells(cells string) string {\n    l, r := \"O\", \"O\"\n    if cells[0] == 'O' {\n        l = \".\"\n    }\n    if cells[len(cells)-1] == 'O' {\n        r = \".\"\n    }\n    cells = l + cells + r\n    cells = l + cells + r\n    return cells\n}\n\nfunc main() {\n    for _, r := range []int{90, 30} {\n        evolve(25, r)\n        fmt.Println()\n    }\n}\n"}
{"id": 49811, "name": "Elementary cellular automaton_Infinite length", "C++": "#include <iostream>\n#include <iomanip>\n#include <string>\n\nclass oo {\npublic:\n    void evolve( int l, int rule ) {\n        std::string    cells = \"O\";\n        std::cout << \" Rule #\" << rule << \":\\n\";\n        for( int x = 0; x < l; x++ ) {\n            addNoCells( cells );\n            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n            step( cells, rule );\n        }\n    }\nprivate:\n    void step( std::string& cells, int rule ) {\n        int bin;\n        std::string newCells;\n        for( size_t i = 0; i < cells.length() - 2; i++ ) {\n            bin = 0;\n            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n            }\n            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n        }\n        cells = newCells;\n    }\n    void addNoCells( std::string& s ) {\n        char l = s.at( 0 ) == 'O' ? '.' : 'O',\n             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n        s = l + s + r;\n        s = l + s + r;\n    }\n};\nint main( int argc, char* argv[] ) {\n    oo o;\n    o.evolve( 35, 90 );\n    std::cout << \"\\n\";\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc evolve(l, rule int) {\n    fmt.Printf(\" Rule #%d:\\n\", rule)\n    cells := \"O\"\n    for x := 0; x < l; x++ {\n        cells = addNoCells(cells)\n        width := 40 + (len(cells) >> 1)\n        fmt.Printf(\"%*s\\n\", width, cells)\n        cells = step(cells, rule)\n    }\n}\n\nfunc step(cells string, rule int) string {\n    newCells := new(strings.Builder)\n    for i := 0; i < len(cells)-2; i++ {\n        bin := 0\n        b := uint(2)\n        for n := i; n < i+3; n++ {\n            bin += btoi(cells[n] == 'O') << b\n            b >>= 1\n        }\n        a := '.'\n        if rule&(1<<uint(bin)) != 0 {\n            a = 'O'\n        }\n        newCells.WriteRune(a)\n    }\n    return newCells.String()\n}\n\nfunc addNoCells(cells string) string {\n    l, r := \"O\", \"O\"\n    if cells[0] == 'O' {\n        l = \".\"\n    }\n    if cells[len(cells)-1] == 'O' {\n        r = \".\"\n    }\n    cells = l + cells + r\n    cells = l + cells + r\n    return cells\n}\n\nfunc main() {\n    for _, r := range []int{90, 30} {\n        evolve(25, r)\n        fmt.Println()\n    }\n}\n"}
{"id": 49812, "name": "Execute CopyPasta Language", "C++": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n\n#include <stdlib.h>\n\nusing namespace std;\n\n\nvoid fatal_error(string errtext, char *argv[])\n{\n\tcout << \"%\" << errtext << endl;\n\tcout << \"usage: \" << argv[0] << \" [filename.cp]\" << endl;\n\texit(1);\n}\n\n\n\nstring& ltrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(0, str.find_first_not_of(chars));\n\treturn str;\n}\nstring& rtrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(str.find_last_not_of(chars) + 1);\n\treturn str;\n}\nstring& trim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\treturn ltrim(rtrim(str, chars), chars);\n}\n\nint main(int argc, char *argv[])\n{\n\t\n\tstring fname = \"\";\n\tstring source = \"\";\n\ttry\n\t{\n\t\tfname = argv[1];\n\t\tifstream t(fname);\n\n\t\tt.seekg(0, ios::end);\n\t\tsource.reserve(t.tellg());\n\t\tt.seekg(0, ios::beg);\n\n\t\tsource.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t}\n\tcatch(const exception& e)\n\t{\n\t\tfatal_error(\"error while trying to read from specified file\", argv);\n\t}\n\n\t\n\tstring clipboard = \"\";\n\n\t\n\tint loc = 0;\n\tstring remaining = source;\n\tstring line = \"\";\n\tstring command = \"\";\n\tstringstream ss;\n\twhile(remaining.find(\"\\n\") != string::npos)\n\t{\n\t\t\n\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\tcommand = trim(line);\n\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\n\t\ttry\n\t\t{\n\t\t\tif(line == \"Copy\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tclipboard += line;\n\t\t\t}\n\t\t\telse if(line == \"CopyFile\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tif(line == \"TheF*ckingCode\")\n\t\t\t\t\tclipboard += source;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring filetext = \"\";\n\t\t\t\t\tifstream t(line);\n\n\t\t\t\t\tt.seekg(0, ios::end);\n\t\t\t\t\tfiletext.reserve(t.tellg());\n\t\t\t\t\tt.seekg(0, ios::beg);\n\n\t\t\t\t\tfiletext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t\t\t\t\tclipboard += filetext;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Duplicate\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tint amount = stoi(line);\n\t\t\t\tstring origClipboard = clipboard;\n\t\t\t\tfor(int i = 0; i < amount - 1; i++) {\n\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Pasta!\")\n\t\t\t{\n\t\t\t\tcout << clipboard << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss << (loc + 1);\n\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encounter on line \" + ss.str(), argv);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception& e)\n\t\t{\n\t\t\tss << (loc + 1);\n\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + ss.str(), argv);\n\t\t}\n\n\t\t\n\t\tloc += 2;\n\t}\n\n\t\n\treturn 0;\n}\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n"}
{"id": 49813, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nvoid print_non_twin_prime_sums(const std::vector<bool>& sums) {\n    int count = 0;\n    for (size_t i = 2; i < sums.size(); i += 2) {\n        if (!sums[i]) {\n            ++count;\n            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nFound \" << count << '\\n';\n}\n\nint main() {\n    const int limit = 100001;\n\n    std::vector<bool> sieve = prime_sieve(limit + 2);\n    \n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))\n            sieve[i] = false;\n    }\n\n    std::vector<bool> twin_prime_sums(limit, false);\n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i]) {\n            for (size_t j = i; i + j < limit; ++j) {\n                if (sieve[j])\n                    twin_prime_sums[i + j] = true;\n            }\n        }\n    }\n\n    std::cout << \"Non twin prime sums:\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n\n    sieve[1] = true;\n    for (size_t i = 1; i + 1 < limit; ++i) {\n        if (sieve[i])\n            twin_prime_sums[i + 1] = true;\n    }\n\n    std::cout << \"\\nNon twin prime sums (including 1):\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst limit = 100000 \n\nfunc nonTwinSums(twins []int) []int {\n    sieve := make([]bool, limit+1)\n    for i := 0; i < len(twins); i++ {\n        for j := i; j < len(twins); j++ {\n            sum := twins[i] + twins[j]\n            if sum > limit {\n                break\n            }\n            sieve[sum] = true\n        }\n    }\n    var res []int\n    for i := 2; i < limit; i += 2 {\n        if !sieve[i] {\n            res = append(res, i)\n        }\n    }\n    return res\n}\n\nfunc main() {\n    primes := rcu.Primes(limit)[2:] \n    twins := []int{3}\n    for i := 0; i < len(primes)-1; i++ {\n        if primes[i+1]-primes[i] == 2 {\n            if twins[len(twins)-1] != primes[i] {\n                twins = append(twins, primes[i])\n            }\n            twins = append(twins, primes[i+1])\n        }\n    }\n    fmt.Println(\"Non twin prime sums:\")\n    ntps := nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n\n    fmt.Println(\"\\nNon twin prime sums (including 1):\")\n    twins = append([]int{1}, twins...)\n    ntps = nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n}\n"}
{"id": 49814, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nvoid print_non_twin_prime_sums(const std::vector<bool>& sums) {\n    int count = 0;\n    for (size_t i = 2; i < sums.size(); i += 2) {\n        if (!sums[i]) {\n            ++count;\n            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nFound \" << count << '\\n';\n}\n\nint main() {\n    const int limit = 100001;\n\n    std::vector<bool> sieve = prime_sieve(limit + 2);\n    \n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))\n            sieve[i] = false;\n    }\n\n    std::vector<bool> twin_prime_sums(limit, false);\n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i]) {\n            for (size_t j = i; i + j < limit; ++j) {\n                if (sieve[j])\n                    twin_prime_sums[i + j] = true;\n            }\n        }\n    }\n\n    std::cout << \"Non twin prime sums:\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n\n    sieve[1] = true;\n    for (size_t i = 1; i + 1 < limit; ++i) {\n        if (sieve[i])\n            twin_prime_sums[i + 1] = true;\n    }\n\n    std::cout << \"\\nNon twin prime sums (including 1):\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst limit = 100000 \n\nfunc nonTwinSums(twins []int) []int {\n    sieve := make([]bool, limit+1)\n    for i := 0; i < len(twins); i++ {\n        for j := i; j < len(twins); j++ {\n            sum := twins[i] + twins[j]\n            if sum > limit {\n                break\n            }\n            sieve[sum] = true\n        }\n    }\n    var res []int\n    for i := 2; i < limit; i += 2 {\n        if !sieve[i] {\n            res = append(res, i)\n        }\n    }\n    return res\n}\n\nfunc main() {\n    primes := rcu.Primes(limit)[2:] \n    twins := []int{3}\n    for i := 0; i < len(primes)-1; i++ {\n        if primes[i+1]-primes[i] == 2 {\n            if twins[len(twins)-1] != primes[i] {\n                twins = append(twins, primes[i])\n            }\n            twins = append(twins, primes[i+1])\n        }\n    }\n    fmt.Println(\"Non twin prime sums:\")\n    ntps := nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n\n    fmt.Println(\"\\nNon twin prime sums (including 1):\")\n    twins = append([]int{1}, twins...)\n    ntps = nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n}\n"}
{"id": 49815, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n"}
{"id": 49816, "name": "Monads_Writer monad", "C++": "#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct LoggingMonad\n{\n    double Value;\n    string Log;\n};\n\n\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n    auto result = f(monad.Value);\n    return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n\nauto MakeWriter = [](auto f, string message)\n{\n    return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n    \n    auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n    cout << result.Log << \"\\nResult: \" << result.Value;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n"}
{"id": 49817, "name": "Nested templated data", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"text/template\"\n)\n\nfunc main() {\n    const t = `[[[{{index .P 1}}, {{index .P 2}}],\n  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n  {{index .P 5}}]]\n`\n    type S struct {\n        P map[int]string\n    }\n\n    var s S\n    s.P = map[int]string{\n        0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n        4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n    }\n    tmpl := template.Must(template.New(\"\").Parse(t))\n    tmpl.Execute(os.Stdout, s)\n\n    var unused []int\n    for k, _ := range s.P {\n        if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n            unused = append(unused, k)\n        }\n    }\n    sort.Ints(unused)\n    fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}\n"}
{"id": 49818, "name": "Inner classes", "C++": "#include <iostream>\n#include <vector>\n\nclass Outer\n{\n    int m_privateField;\n    \npublic:\n    \n    Outer(int value) : m_privateField{value}{}\n    \n    \n    class Inner\n    {\n        int m_innerValue;\n        \n    public:\n        \n        Inner(int innerValue) : m_innerValue{innerValue}{}\n        \n        \n        int AddOuter(Outer outer) const\n        {\n            \n            return outer.m_privateField + m_innerValue;\n        }\n    };\n};\n\nint main()\n{\n    \n    \n    Outer::Inner inner{42};\n    \n    \n    Outer outer{1};  \n    auto sum = inner.AddOuter(outer);\n    std::cout << \"sum: \" << sum << \"\\n\";\n    \n    \n    std::vector<int> vec{1,2,3};\n    std::vector<int>::iterator itr = vec.begin();\n    std::cout << \"vec[0] = \" << *itr << \"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Outer struct {\n    field int\n    Inner struct {\n        field int\n    }\n}\n\nfunc (o *Outer) outerMethod() {\n    fmt.Println(\"Outer's field has a value of\", o.field)\n}\n\nfunc (o *Outer) innerMethod() {\n    fmt.Println(\"Inner's field has a value of\", o.Inner.field)\n}\n\nfunc main() {\n    o := &Outer{field: 43}\n    o.Inner.field = 42\n    o.innerMethod()\n    o.outerMethod()\n    \n    p := &Outer{\n        field: 45,\n        Inner: struct {\n            field int\n        }{\n            field: 44,\n        },\n    }\n    p.innerMethod()\n    p.outerMethod()\n}\n"}
{"id": 49819, "name": "Special pythagorean triplet", "C++": "#include <cmath>\n#include <concepts>\n#include <iostream>\n#include <numeric>\n#include <optional>\n#include <tuple>\n \nusing namespace std;\n\noptional<tuple<int, int ,int>> FindPerimeterTriplet(int perimeter)\n{\n    unsigned long long perimeterULL = perimeter;\n    auto max_M = (unsigned long long)sqrt(perimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n\n            \n            \n            \n            \n \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto primitive = a + b + c;\n\n            \n            auto factor = perimeterULL / primitive;\n            if(primitive * factor == perimeterULL)\n            {\n              \n              if(b<a) swap(a, b);\n              return tuple{a * factor, b * factor, c * factor};\n            }\n        }\n    }\n\n    \n    return nullopt;\n}\n \nint main()\n{\n  auto t1 = FindPerimeterTriplet(1000);\n  if(t1)\n  {\n    auto [a, b, c] = *t1;\n    cout << \"[\" << a << \", \" << b << \", \" << c << \"]\\n\";\n    cout << \"a * b * c = \" << a * b * c << \"\\n\";\n  }\n  else\n  {\n    cout << \"Perimeter not found\\n\";\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    start := time.Now()\n    for a := 3; ; a++ {\n        for b := a + 1; ; b++ {\n            c := 1000 - a - b\n            if c <= b {\n                break\n            }\n            if a*a+b*b == c*c {\n                fmt.Printf(\"a = %d, b = %d, c = %d\\n\", a, b, c)\n                fmt.Println(\"a + b + c =\", a+b+c)\n                fmt.Println(\"a * b * c =\", a*b*c)\n                fmt.Println(\"\\nTook\", time.Since(start))\n                return\n            }\n        }\n    }\n}\n"}
{"id": 49820, "name": "Mastermind", "C++": "#include <iostream>\n#include <algorithm>\n#include <ctime>\n#include <string>\n#include <vector>\n\ntypedef std::vector<char> vecChar;\n\nclass master {\npublic:\n    master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {\n        std::string color = \"ABCDEFGHIJKLMNOPQRST\";\n\n        if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;\n        if( !rpt && clr_count < code_len ) clr_count = code_len; \n        if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;\n        if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;\n        \n        codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;\n\n        for( size_t s = 0; s < colorsCnt; s++ ) {\n            colors.append( 1, color.at( s ) );\n        }\n    }\n    void play() {\n        bool win = false;\n        combo = getCombo();\n\n        while( guessCnt ) {\n            showBoard();\n            if( checkInput( getInput() ) ) {\n                win = true;\n                break;\n            }\n            guessCnt--;\n        }\n        if( win ) {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"Very well done!\\nYou found the code: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        } else {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"I am sorry, you couldn't make it!\\nThe code was: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        }\n    }\nprivate:\n    void showBoard() {\n        vecChar::iterator y;\n        for( int x = 0; x < guesses.size(); x++ ) {\n            std::cout << \"\\n--------------------------------\\n\";\n            std::cout << x + 1 << \": \";\n            for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            std::cout << \" :  \";\n            for( y = results[x].begin(); y != results[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            int z = codeLen - results[x].size();\n            if( z > 0 ) {\n                for( int x = 0; x < z; x++ ) std::cout << \"- \";\n            }\n        }\n        std::cout << \"\\n\\n\";\n    }\n    std::string getInput() {\n        std::string a;\n        while( true ) {\n            std::cout << \"Enter your guess (\" << colors << \"): \";\n            a = \"\"; std::cin >> a;\n            std::transform( a.begin(), a.end(), a.begin(), ::toupper );\n            if( a.length() > codeLen ) a.erase( codeLen );\n            bool r = true;\n            for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n                if( colors.find( *x ) == std::string::npos ) {\n                    r = false;\n                    break;\n                }\n            }\n            if( r ) break;\n        }\n        return a;\n    }\n    bool checkInput( std::string a ) {\n        vecChar g;\n        for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n            g.push_back( *x );\n        }\n        guesses.push_back( g );\n        \n        int black = 0, white = 0;\n        std::vector<bool> gmatch( codeLen, false );\n        std::vector<bool> cmatch( codeLen, false );\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if( a.at( i ) == combo.at( i ) ) {\n                gmatch[i] = true;\n                cmatch[i] = true;\n                black++;\n            }\n        }\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if (gmatch[i]) continue;\n            for( int j = 0; j < codeLen; j++ ) {\n                if (i == j || cmatch[j]) continue;\n                if( a.at( i ) == combo.at( j ) ) {\n                    cmatch[j] = true;\n                    white++;\n                    break;\n                }\n            }\n        }\n       \n        vecChar r;\n        for( int b = 0; b < black; b++ ) r.push_back( 'X' );\n        for( int w = 0; w < white; w++ ) r.push_back( 'O' );\n        results.push_back( r );\n\n        return ( black == codeLen );\n    }\n    std::string getCombo() {\n        std::string c, clr = colors;\n        int l, z;\n\n        for( size_t s = 0; s < codeLen; s++ ) {\n            z = rand() % ( int )clr.length();\n            c.append( 1, clr[z] );\n            if( !repeatClr ) clr.erase( z, 1 );\n        }\n        return c;\n    }\n\n    size_t codeLen, colorsCnt, guessCnt;\n    bool repeatClr;\n    std::vector<vecChar> guesses, results;\n    std::string colors, combo;\n};\n\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    master m( 4, 8, 12, false );\n    m.play();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n"}
{"id": 49821, "name": "Mastermind", "C++": "#include <iostream>\n#include <algorithm>\n#include <ctime>\n#include <string>\n#include <vector>\n\ntypedef std::vector<char> vecChar;\n\nclass master {\npublic:\n    master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {\n        std::string color = \"ABCDEFGHIJKLMNOPQRST\";\n\n        if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;\n        if( !rpt && clr_count < code_len ) clr_count = code_len; \n        if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;\n        if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;\n        \n        codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;\n\n        for( size_t s = 0; s < colorsCnt; s++ ) {\n            colors.append( 1, color.at( s ) );\n        }\n    }\n    void play() {\n        bool win = false;\n        combo = getCombo();\n\n        while( guessCnt ) {\n            showBoard();\n            if( checkInput( getInput() ) ) {\n                win = true;\n                break;\n            }\n            guessCnt--;\n        }\n        if( win ) {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"Very well done!\\nYou found the code: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        } else {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"I am sorry, you couldn't make it!\\nThe code was: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        }\n    }\nprivate:\n    void showBoard() {\n        vecChar::iterator y;\n        for( int x = 0; x < guesses.size(); x++ ) {\n            std::cout << \"\\n--------------------------------\\n\";\n            std::cout << x + 1 << \": \";\n            for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            std::cout << \" :  \";\n            for( y = results[x].begin(); y != results[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            int z = codeLen - results[x].size();\n            if( z > 0 ) {\n                for( int x = 0; x < z; x++ ) std::cout << \"- \";\n            }\n        }\n        std::cout << \"\\n\\n\";\n    }\n    std::string getInput() {\n        std::string a;\n        while( true ) {\n            std::cout << \"Enter your guess (\" << colors << \"): \";\n            a = \"\"; std::cin >> a;\n            std::transform( a.begin(), a.end(), a.begin(), ::toupper );\n            if( a.length() > codeLen ) a.erase( codeLen );\n            bool r = true;\n            for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n                if( colors.find( *x ) == std::string::npos ) {\n                    r = false;\n                    break;\n                }\n            }\n            if( r ) break;\n        }\n        return a;\n    }\n    bool checkInput( std::string a ) {\n        vecChar g;\n        for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n            g.push_back( *x );\n        }\n        guesses.push_back( g );\n        \n        int black = 0, white = 0;\n        std::vector<bool> gmatch( codeLen, false );\n        std::vector<bool> cmatch( codeLen, false );\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if( a.at( i ) == combo.at( i ) ) {\n                gmatch[i] = true;\n                cmatch[i] = true;\n                black++;\n            }\n        }\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if (gmatch[i]) continue;\n            for( int j = 0; j < codeLen; j++ ) {\n                if (i == j || cmatch[j]) continue;\n                if( a.at( i ) == combo.at( j ) ) {\n                    cmatch[j] = true;\n                    white++;\n                    break;\n                }\n            }\n        }\n       \n        vecChar r;\n        for( int b = 0; b < black; b++ ) r.push_back( 'X' );\n        for( int w = 0; w < white; w++ ) r.push_back( 'O' );\n        results.push_back( r );\n\n        return ( black == codeLen );\n    }\n    std::string getCombo() {\n        std::string c, clr = colors;\n        int l, z;\n\n        for( size_t s = 0; s < codeLen; s++ ) {\n            z = rand() % ( int )clr.length();\n            c.append( 1, clr[z] );\n            if( !repeatClr ) clr.erase( z, 1 );\n        }\n        return c;\n    }\n\n    size_t codeLen, colorsCnt, guessCnt;\n    bool repeatClr;\n    std::vector<vecChar> guesses, results;\n    std::string colors, combo;\n};\n\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    master m( 4, 8, 12, false );\n    m.play();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n"}
{"id": 49822, "name": "Untouchable numbers", "C++": "\n#include <functional>\n#include <bitset> \n#include <iostream>\n#include <cmath>\nusing namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;\nconst int maxUT{3000000}, dL{(int)log2(maxUT)};\nstruct uT{\n  bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};\n  void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}\n  Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}\n  Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}\n  Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}\n  void fL(Z3 n, int g){for(;;){\n    if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}\n    if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}\n  }\n  int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}\n  uT(const int n):mUT{n}{\n    N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();\n    N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);\n  }\n};\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i := 1 + k; i*i <= n; i += k {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n    }\n    return sum\n}\n\nfunc sieve(n int) []bool {\n    n++\n    s := make([]bool, n+1) \n    for i := 6; i <= n; i++ {\n        sd := sumDivisors(i)\n        if sd <= n {\n            s[sd] = true\n        }\n    }\n    return s\n}\n\nfunc primeSieve(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 main() {    \n    limit := 1000000\n    c := primeSieve(limit)\n    s := sieve(63 * limit)\n    untouchable := []int{2, 5}\n    for n := 6; n <= limit; n += 2 {\n        if !s[n] && c[n-1] && c[n-3] {\n            untouchable = append(untouchable, n)\n        }\n    }\n    fmt.Println(\"List of untouchable numbers <= 2,000:\")\n    count := 0\n    for i := 0; untouchable[i] <= 2000; i++ {\n        fmt.Printf(\"%6s\", commatize(untouchable[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        count++\n    }\n    fmt.Printf(\"\\n\\n%7s untouchable numbers were found  <=     2,000\\n\", commatize(count))\n    p := 10\n    count = 0\n    for _, n := range untouchable {\n        count++\n        if n > p {\n            cc := commatize(count - 1)\n            cp := commatize(p)\n            fmt.Printf(\"%7s untouchable numbers were found  <= %9s\\n\", cc, cp)\n            p = p * 10\n            if p == limit {\n                break\n            }\n        }\n    }\n    cu := commatize(len(untouchable))\n    cl := commatize(limit)\n    fmt.Printf(\"%7s untouchable numbers were found  <= %s\\n\", cu, cl)\n}\n"}
{"id": 49823, "name": "Untouchable numbers", "C++": "\n#include <functional>\n#include <bitset> \n#include <iostream>\n#include <cmath>\nusing namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;\nconst int maxUT{3000000}, dL{(int)log2(maxUT)};\nstruct uT{\n  bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};\n  void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}\n  Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}\n  Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}\n  Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}\n  void fL(Z3 n, int g){for(;;){\n    if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}\n    if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}\n  }\n  int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}\n  uT(const int n):mUT{n}{\n    N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();\n    N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);\n  }\n};\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i := 1 + k; i*i <= n; i += k {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n    }\n    return sum\n}\n\nfunc sieve(n int) []bool {\n    n++\n    s := make([]bool, n+1) \n    for i := 6; i <= n; i++ {\n        sd := sumDivisors(i)\n        if sd <= n {\n            s[sd] = true\n        }\n    }\n    return s\n}\n\nfunc primeSieve(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 main() {    \n    limit := 1000000\n    c := primeSieve(limit)\n    s := sieve(63 * limit)\n    untouchable := []int{2, 5}\n    for n := 6; n <= limit; n += 2 {\n        if !s[n] && c[n-1] && c[n-3] {\n            untouchable = append(untouchable, n)\n        }\n    }\n    fmt.Println(\"List of untouchable numbers <= 2,000:\")\n    count := 0\n    for i := 0; untouchable[i] <= 2000; i++ {\n        fmt.Printf(\"%6s\", commatize(untouchable[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        count++\n    }\n    fmt.Printf(\"\\n\\n%7s untouchable numbers were found  <=     2,000\\n\", commatize(count))\n    p := 10\n    count = 0\n    for _, n := range untouchable {\n        count++\n        if n > p {\n            cc := commatize(count - 1)\n            cp := commatize(p)\n            fmt.Printf(\"%7s untouchable numbers were found  <= %9s\\n\", cc, cp)\n            p = p * 10\n            if p == limit {\n                break\n            }\n        }\n    }\n    cu := commatize(len(untouchable))\n    cl := commatize(limit)\n    fmt.Printf(\"%7s untouchable numbers were found  <= %s\\n\", cu, cl)\n}\n"}
{"id": 49824, "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", "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": 49825, "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", "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": 49826, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 49827, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 49828, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 49829, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 49830, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 49831, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 49832, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 49833, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 49834, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 49835, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 49836, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 49837, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 49838, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 49839, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 49840, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 49841, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 49842, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(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": 49843, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(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": 49844, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 49845, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 49846, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\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": 49847, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\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": 49848, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 49849, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 49850, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 49851, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 49852, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 49853, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 49854, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 49855, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 49856, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 49857, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 49858, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\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": 49859, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\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": 49860, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\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": 49861, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\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": 49862, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\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": 49863, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\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": 49864, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\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": 49865, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\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": 49866, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\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": 49867, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\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": 49868, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\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": 49869, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\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": 49870, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\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": 49871, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\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": 49872, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\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": 49873, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\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": 49874, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\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": 49875, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\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": 49876, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\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": 49877, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\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": 49878, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 49879, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 49880, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 49881, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 49882, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\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": 49883, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\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": 49884, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\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": 49885, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\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": 49886, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Go": "var intStack []int\n"}
{"id": 49887, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Go": "var intStack []int\n"}
{"id": 49888, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 49889, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 49890, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $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    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": 49891, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $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    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": 49892, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\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": 49893, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\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": 49894, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\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": 49895, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\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": 49896, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\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    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": 49897, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\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    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": 49898, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\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": 49899, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\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": 49900, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\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": 49901, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\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": 49902, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\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": 49903, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\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": 49904, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 49905, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 49906, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 49907, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 49908, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\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": 49909, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\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": 49910, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 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": 49911, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 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": 49912, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\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": 49913, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\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": 49914, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\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": 49915, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\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": 49916, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\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": 49917, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\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": 49918, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\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": 49919, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\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": 49920, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\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": 49921, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\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": 49922, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\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": 49923, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\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": 49924, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\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": 49925, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\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": 49926, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\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": 49927, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\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": 49928, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 49929, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 49930, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 49931, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 49932, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 49933, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 49934, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 49935, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 49936, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 49937, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 49938, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 49939, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 49940, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 49941, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 49942, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 49943, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 49944, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 49945, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 49946, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 49947, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 49948, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 49949, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 49950, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 49951, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 49952, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n"}
{"id": 49953, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n"}
{"id": 49954, "name": "Include a file", "PHP": "include(\"file.php\")\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 49955, "name": "Include a file", "PHP": "include(\"file.php\")\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 49956, "name": "Include a file", "PHP": "include(\"file.php\")\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 49957, "name": "Include a file", "PHP": "include(\"file.php\")\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 49958, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n"}
{"id": 49959, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n"}
{"id": 49960, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n"}
{"id": 49961, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n"}
{"id": 49962, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 49963, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 49964, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 49965, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 49966, "name": "SOAP", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n"}
{"id": 49967, "name": "SOAP", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n"}
{"id": 49968, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49969, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49970, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49971, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 49972, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 49973, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 49974, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 49975, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 49976, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 49977, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 49978, "name": "Calendar - for _REAL_ programmers", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n"}
{"id": 49979, "name": "Calendar - for _REAL_ programmers", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n"}
{"id": 49980, "name": "Loops_Infinite", "PHP": "while(1)\n    echo \"SPAM\\n\";\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 49981, "name": "Loops_Infinite", "PHP": "while(1)\n    echo \"SPAM\\n\";\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 49982, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 49983, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 49984, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n"}
{"id": 49985, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n"}
{"id": 49986, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 49987, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 49988, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 49989, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 49990, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 49991, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 49992, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 49993, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 49994, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 49995, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 49996, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 49997, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 49998, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 49999, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 50000, "name": "Bitmap_Bézier curves_Cubic", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n"}
{"id": 50001, "name": "Bitmap_Bézier curves_Cubic", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n"}
{"id": 50002, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n"}
{"id": 50003, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n"}
{"id": 50004, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 50005, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 50006, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 50007, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 50008, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 50009, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 50010, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 50011, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 50012, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 50013, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 50014, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 50015, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 50016, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 50017, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 50018, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 50019, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 50020, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 50021, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 50022, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 50023, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 50024, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 50025, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 50026, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 50027, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 50028, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 50029, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 50030, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 50031, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 50032, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 50033, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 50034, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n"}
{"id": 50035, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n"}
{"id": 50036, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 50037, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 50038, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 50039, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 50040, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 50041, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 50042, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 50043, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 50044, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n"}
{"id": 50045, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n"}
{"id": 50046, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 50047, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 50048, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 50049, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 50050, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n"}
{"id": 50051, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n"}
{"id": 50052, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 50053, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 50054, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n"}
{"id": 50055, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n"}
{"id": 50056, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Go": "x := 3\n"}
{"id": 50057, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Go": "x := 3\n"}
{"id": 50058, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 50059, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 50060, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 50061, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 50062, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 50063, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 50064, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 50065, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 50066, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 50067, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 50068, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 50069, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 50070, "name": "OpenWebNet password", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n    start := true\n    num1 := uint32(0)\n    num2 := num1\n    i, _ := strconv.Atoi(password)\n    pwd := uint32(i)\n    for _, c := range nonce {\n        if c != '0' {\n            if start {\n                num2 = pwd\n            }\n            start = false\n        }\n        switch c {\n        case '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        case '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        case '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        case '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        case '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        case '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        case '7':\n            num3 := num2 & 0x0000FF00\n            num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n            num1 = num3 | num4\n            num2 = (num2 & 0xFF000000) >> 8\n        case '8':\n            num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n            num2 = (num2 & 0x00FF0000) >> 8\n        case '9':\n            num1 = ^num2\n        default:\n            num1 = num2\n        }\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if c != '0' && c != '9' {\n            num1 |= num2\n        }\n        num2 = num1\n    }\n    return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n    res := ownCalcPass(password, nonce)\n    m := fmt.Sprintf(\"%s  %s  %-10d  %-10d\", password, nonce, res, expected)\n    if res == expected {\n        fmt.Println(\"PASS\", m)\n    } else {\n        fmt.Println(\"FAIL\", m)\n    }\n}\n\nfunc main() {\n    testPasswordCalc(\"12345\", \"603356072\", 25280520)\n    testPasswordCalc(\"12345\", \"410501656\", 119537670)\n    testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}\n"}
{"id": 50071, "name": "OpenWebNet password", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n    start := true\n    num1 := uint32(0)\n    num2 := num1\n    i, _ := strconv.Atoi(password)\n    pwd := uint32(i)\n    for _, c := range nonce {\n        if c != '0' {\n            if start {\n                num2 = pwd\n            }\n            start = false\n        }\n        switch c {\n        case '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        case '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        case '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        case '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        case '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        case '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        case '7':\n            num3 := num2 & 0x0000FF00\n            num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n            num1 = num3 | num4\n            num2 = (num2 & 0xFF000000) >> 8\n        case '8':\n            num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n            num2 = (num2 & 0x00FF0000) >> 8\n        case '9':\n            num1 = ^num2\n        default:\n            num1 = num2\n        }\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if c != '0' && c != '9' {\n            num1 |= num2\n        }\n        num2 = num1\n    }\n    return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n    res := ownCalcPass(password, nonce)\n    m := fmt.Sprintf(\"%s  %s  %-10d  %-10d\", password, nonce, res, expected)\n    if res == expected {\n        fmt.Println(\"PASS\", m)\n    } else {\n        fmt.Println(\"FAIL\", m)\n    }\n}\n\nfunc main() {\n    testPasswordCalc(\"12345\", \"603356072\", 25280520)\n    testPasswordCalc(\"12345\", \"410501656\", 119537670)\n    testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}\n"}
{"id": 50072, "name": "Monads_Writer monad", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n"}
{"id": 50073, "name": "Monads_Writer monad", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n"}
{"id": 50074, "name": "Canny edge detector", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n", "Go": "package main\n\nimport (\n    ed \"github.com/Ernyoke/Imger/edgedetection\"\n    \"github.com/Ernyoke/Imger/imgio\"\n    \"log\"\n)\n\nfunc main() {\n    img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not read image\", err)\n    }\n\n    cny, err := ed.CannyRGBA(img, 15, 45, 5)\n    if err != nil {\n        log.Fatal(\"Could not perform Canny Edge detection\")\n    }\n\n    err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not write Canny image to disk\")\n    }\n}\n"}
{"id": 50075, "name": "Canny edge detector", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n", "Go": "package main\n\nimport (\n    ed \"github.com/Ernyoke/Imger/edgedetection\"\n    \"github.com/Ernyoke/Imger/imgio\"\n    \"log\"\n)\n\nfunc main() {\n    img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not read image\", err)\n    }\n\n    cny, err := ed.CannyRGBA(img, 15, 45, 5)\n    if err != nil {\n        log.Fatal(\"Could not perform Canny Edge detection\")\n    }\n\n    err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not write Canny image to disk\")\n    }\n}\n"}
{"id": 50076, "name": "Add a variable to a class instance at runtime", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n"}
{"id": 50077, "name": "Add a variable to a class instance at runtime", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n"}
{"id": 50078, "name": "Find URI in text", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 50079, "name": "Find URI in text", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 50080, "name": "Find URI in text", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 50081, "name": "Find URI in text", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 50082, "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", "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": 50083, "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", "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": 50084, "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", "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": 50085, "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", "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": 50086, "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", "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": 50087, "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", "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": 50088, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 50089, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 50090, "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", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 50091, "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", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\n"}
{"id": 50092, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 50093, "name": "Extensible prime generator", "Python": "islice(count(7), 0, None, 2)\n", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n"}
{"id": 50094, "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", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n"}
{"id": 50095, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 50096, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 50097, "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", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n"}
{"id": 50098, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 50099, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 50100, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 50101, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n"}
{"id": 50102, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 50103, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 50104, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 50105, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 50106, "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", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 50107, "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", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 50108, "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", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 50109, "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", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 50110, "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", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 50111, "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", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 50112, "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", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50113, "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", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 50114, "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", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n"}
{"id": 50115, "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", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 50116, "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", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 50117, "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", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 50118, "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", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 50119, "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", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 50120, "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", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 50121, "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", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 50122, "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", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 50123, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 50124, "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", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 50125, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 50126, "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", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 50127, "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", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 50128, "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", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 50129, "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", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n"}
{"id": 50130, "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", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n"}
{"id": 50131, "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", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 50132, "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", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 50133, "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", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50134, "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", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 50135, "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", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 50136, "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", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 50137, "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", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 50138, "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", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n"}
{"id": 50139, "name": "Write entire file", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 50140, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 50141, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 50142, "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", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 50143, "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", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 50144, "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", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 50145, "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", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 50146, "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", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 50147, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50148, "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", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50149, "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", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 50150, "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", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 50151, "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", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 50152, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 50153, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 50154, "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", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 50155, "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", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 50156, "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", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 50157, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 50158, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 50159, "name": "Image noise", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 50160, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 50161, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 50162, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 50163, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 50164, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 50165, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 50166, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 50167, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 50168, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 50169, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 50170, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 50171, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 50172, "name": "Water collected between towers", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50173, "name": "Square-free integers", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50174, "name": "Square-free integers", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50175, "name": "Jaro similarity", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n"}
{"id": 50176, "name": "Fairshare between two and more", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 50177, "name": "Fairshare between two and more", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 50178, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 50179, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n"}
{"id": 50180, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 50181, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 50182, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 50183, "name": "Biorhythms", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n"}
{"id": 50184, "name": "Biorhythms", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n"}
{"id": 50185, "name": "Table creation_Postal addresses", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n"}
{"id": 50186, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n"}
{"id": 50187, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n"}
{"id": 50188, "name": "Chat server", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50189, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 50190, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 50191, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 50192, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 50193, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 50194, "name": "Terminal control_Dimensions", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n"}
{"id": 50195, "name": "Terminal control_Dimensions", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n"}
{"id": 50196, "name": "Finite state machine", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n"}
{"id": 50197, "name": "Finite state machine", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n"}
{"id": 50198, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 50199, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 50200, "name": "Sierpinski pentagon", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n"}
{"id": 50201, "name": "Rep-string", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n"}
{"id": 50202, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n"}
{"id": 50203, "name": "GUI_Maximum window dimensions", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n"}
{"id": 50204, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 50205, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 50206, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 50207, "name": "Parse an IP Address", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n"}
{"id": 50208, "name": "Textonyms", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n"}
{"id": 50209, "name": "Range extraction", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n"}
{"id": 50210, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n"}
{"id": 50211, "name": "Zhang-Suen thinning algorithm", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n"}
{"id": 50212, "name": "Variable declaration reset", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n"}
{"id": 50213, "name": "Koch curve", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n"}
{"id": 50214, "name": "Draw a pixel", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n"}
{"id": 50215, "name": "Words from neighbour ones", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n"}
{"id": 50216, "name": "UTF-8 encode and decode", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n"}
{"id": 50217, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n"}
{"id": 50218, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 50219, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n"}
{"id": 50220, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n"}
{"id": 50221, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n"}
{"id": 50222, "name": "Death Star", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n"}
{"id": 50223, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "VB": "Public c As Variant\nPublic pi As Double\nDim arclists() As Variant\nPublic Enum circles_\n    xc = 0\n    yc\n    rc\nEnd Enum\nPublic Enum arclists_\n    rho\n    x_\n    y_\n    i_\nEnd Enum\nPublic Enum shoelace_axis\n    u = 0\n    v\nEnd Enum\nPrivate Sub give_a_list_of_circles()\n    c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _\n    Array(-1.4944608174, 1.2077959613, 1.1039549836), _\n    Array(0.6110294452, -0.6907087527, 0.9089162485), _\n    Array(0.3844862411, 0.2923344616, 0.2375743054), _\n    Array(-0.249589295, -0.3832854473, 1.0845181219), _\n    Array(1.7813504266, 1.6178237031, 0.8162655711), _\n    Array(-0.1985249206, -0.8343333301, 0.0538864941), _\n    Array(-1.7011985145, -0.1263820964, 0.4776976918), _\n    Array(-0.4319462812, 1.4104420482, 0.7886291537), _\n    Array(0.2178372997, -0.9499557344, 0.0357871187), _\n    Array(-0.6294854565, -1.3078893852, 0.7653357688), _\n    Array(1.7952608455, 0.6281269104, 0.2727652452), _\n    Array(1.4168575317, 1.0683357171, 1.1016025378), _\n    Array(1.4637371396, 0.9463877418, 1.1846214562), _\n    Array(-0.5263668798, 1.7315156631, 1.4428514068), _\n    Array(-1.2197352481, 0.9144146579, 1.0727263474), _\n    Array(-0.1389358881, 0.109280578, 0.7350208828), _\n    Array(1.5293954595, 0.0030278255, 1.2472867347), _\n    Array(-0.5258728625, 1.3782633069, 1.3495508831), _\n    Array(-0.1403562064, 0.2437382535, 1.3804956588), _\n    Array(0.8055826339, -0.0482092025, 0.3327165165), _\n    Array(-0.6311979224, 0.7184578971, 0.2491045282), _\n    Array(1.4685857879, -0.8347049536, 1.3670667538), _\n    Array(-0.6855727502, 1.6465021616, 1.0593087096), _\n    Array(0.0152957411, 0.0638919221, 0.9771215985))\n    pi = WorksheetFunction.pi()\nEnd Sub\nPrivate Function shoelace(s As Collection) As Double\n    \n    \n    \n    \n    \n    \n    Dim t As Double\n    If s.Count > 2 Then\n        s.Add s(1)\n        For i = 1 To s.Count - 1\n            t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v)\n        Next i\n    End If\n    shoelace = t / 2\nEnd Function\nPrivate Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _\n    f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer)\n    \n    \n    If acol.Count = 0 Then Exit Sub \n    Debug.Assert acol.Count Mod 2 = 0\n    Debug.Assert f0 <> f1\n    If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1\n    If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0\n    If f0 < f1 Then\n        \n        \n        \n        If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub \n        i = acol.Count + 1\n        start = 1\n        Do\n            i = i - 1\n        Loop Until f1 > acol(i)(rho)\n        If i Mod 2 = start Then\n            acol.Add Array(f1, u1, v1, j), after:=i\n        End If\n        i = 0\n        Do\n            i = i + 1\n        Loop Until f0 < acol(i)(rho)\n        If i Mod 2 = 1 - start Then\n            acol.Add Array(f0, u0, v0, j), before:=i\n            i = i + 1\n        End If\n        Do While acol(i)(rho) < f1\n            acol.Remove i\n            If i > acol.Count Then Exit Do\n        Loop\n    Else\n        start = 1\n        If f0 > acol(1)(rho) Then\n            i = acol.Count + 1\n            Do\n                i = i - 1\n            Loop While f0 < acol(i)(0)\n            If f0 = pi Then\n                acol.Add Array(f0, u0, v0, j), before:=i\n            Else\n                If i Mod 2 = start Then\n                    acol.Add Array(f0, u0, v0, j), after:=i\n                End If\n            End If\n        End If\n        If f1 <= acol(acol.Count)(rho) Then\n            i = 0\n            Do\n                i = i + 1\n            Loop While f1 > acol(i)(rho)\n            If f1 + pi < 5E-16 Then\n                acol.Add Array(f1, u1, v1, j), after:=i\n            Else\n                If i Mod 2 = 1 - start Then\n                    acol.Add Array(f1, u1, v1, j), before:=i\n                End If\n            End If\n        End If\n        Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1\n            acol.Remove acol.Count\n            If acol.Count = 0 Then Exit Do\n        Loop\n        If acol.Count > 0 Then\n            Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this)\n                acol.Remove 1\n                If acol.Count = 0 Then Exit Do\n            Loop\n        End If\n    End If\nEnd Sub\nPrivate Sub circle_cross()\n    ReDim arclists(LBound(c) To UBound(c))\n    Dim alpha As Double, beta As Double\n    Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double\n    Dim i As Integer, j As Integer\n    For i = LBound(c) To UBound(c)\n        Dim arccol As New Collection\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i)\n        arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1)\n        For j = LBound(c) To UBound(c)\n            If i <> j Then\n                x0 = c(i)(xc)\n                y0 = c(i)(yc)\n                r0 = c(i)(rc)\n                x1 = c(j)(xc)\n                y1 = c(j)(yc)\n                r1 = c(j)(rc)\n                d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2)\n                \n                If d >= r0 + r1 Or d <= Abs(r0 - r1) Then\n                    \n                Else\n                    a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d)\n                    h = Sqr(r0 ^ 2 - a ^ 2)\n                    x2 = x0 + a * (x1 - x0) / d\n                    y2 = y0 + a * (y1 - y0) / d\n                    x3 = x2 + h * (y1 - y0) / d\n                    y3 = y2 - h * (x1 - x0) / d\n                    alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0)\n                    x4 = x2 - h * (y1 - y0) / d\n                    y4 = y2 + h * (x1 - x0) / d\n                    beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0)\n                    \n                    \n                    \n                    \n                    arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j\n                End If\n            End If\n        Next j\n        Set arclists(i) = arccol\n        Set arccol = Nothing\n    Next i\nEnd Sub\nPrivate Sub make_path()\n    Dim pathcol As New Collection, arcsum As Double\n    i0 = UBound(arclists)\n    finished = False\n    Do While True\n        arcsum = 0\n        Do While arclists(i0).Count = 0\n            i0 = i0 - 1\n        Loop\n        j0 = arclists(i0).Count\n        next_i = i0\n        next_j = j0\n        Do While True\n            x = arclists(next_i)(next_j)(x_)\n            y = arclists(next_i)(next_j)(y_)\n            pathcol.Add Array(x, y)\n            prev_i = next_i\n            prev_j = next_j\n            If arclists(next_i)(next_j - 1)(i_) = next_i Then\n                \n                next_j = arclists(next_i).Count - 1\n                If next_j = 1 Then Exit Do \n            Else\n                next_j = next_j - 1\n            End If\n            \n            r = c(next_i)(rc)\n            a1 = arclists(next_i)(prev_j)(rho)\n            a2 = arclists(next_i)(next_j)(rho)\n            If a1 > a2 Then\n                alpha = a1 - a2\n            Else\n                alpha = 2 * pi - a2 + a1\n            End If\n            arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2\n            \n            next_i = arclists(next_i)(next_j)(i_)\n            next_j = arclists(next_i).Count\n            If next_j = 0 Then Exit Do \n            Do While arclists(next_i)(next_j)(i_) <> prev_i\n                \n                next_j = next_j - 1\n            Loop\n            If next_i = i0 And next_j = j0 Then\n                finished = True\n                Exit Do\n            End If\n        Loop\n        If finished Then Exit Do\n        i0 = i0 - 1\n        Set pathcol = Nothing\n    Loop\n    Debug.Print shoelace(pathcol) + arcsum\nEnd Sub\nPublic Sub total_circles()\n    give_a_list_of_circles\n    circle_cross\n    make_path\nEnd Sub\n"}
{"id": 50224, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "VB": "Public c As Variant\nPublic pi As Double\nDim arclists() As Variant\nPublic Enum circles_\n    xc = 0\n    yc\n    rc\nEnd Enum\nPublic Enum arclists_\n    rho\n    x_\n    y_\n    i_\nEnd Enum\nPublic Enum shoelace_axis\n    u = 0\n    v\nEnd Enum\nPrivate Sub give_a_list_of_circles()\n    c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _\n    Array(-1.4944608174, 1.2077959613, 1.1039549836), _\n    Array(0.6110294452, -0.6907087527, 0.9089162485), _\n    Array(0.3844862411, 0.2923344616, 0.2375743054), _\n    Array(-0.249589295, -0.3832854473, 1.0845181219), _\n    Array(1.7813504266, 1.6178237031, 0.8162655711), _\n    Array(-0.1985249206, -0.8343333301, 0.0538864941), _\n    Array(-1.7011985145, -0.1263820964, 0.4776976918), _\n    Array(-0.4319462812, 1.4104420482, 0.7886291537), _\n    Array(0.2178372997, -0.9499557344, 0.0357871187), _\n    Array(-0.6294854565, -1.3078893852, 0.7653357688), _\n    Array(1.7952608455, 0.6281269104, 0.2727652452), _\n    Array(1.4168575317, 1.0683357171, 1.1016025378), _\n    Array(1.4637371396, 0.9463877418, 1.1846214562), _\n    Array(-0.5263668798, 1.7315156631, 1.4428514068), _\n    Array(-1.2197352481, 0.9144146579, 1.0727263474), _\n    Array(-0.1389358881, 0.109280578, 0.7350208828), _\n    Array(1.5293954595, 0.0030278255, 1.2472867347), _\n    Array(-0.5258728625, 1.3782633069, 1.3495508831), _\n    Array(-0.1403562064, 0.2437382535, 1.3804956588), _\n    Array(0.8055826339, -0.0482092025, 0.3327165165), _\n    Array(-0.6311979224, 0.7184578971, 0.2491045282), _\n    Array(1.4685857879, -0.8347049536, 1.3670667538), _\n    Array(-0.6855727502, 1.6465021616, 1.0593087096), _\n    Array(0.0152957411, 0.0638919221, 0.9771215985))\n    pi = WorksheetFunction.pi()\nEnd Sub\nPrivate Function shoelace(s As Collection) As Double\n    \n    \n    \n    \n    \n    \n    Dim t As Double\n    If s.Count > 2 Then\n        s.Add s(1)\n        For i = 1 To s.Count - 1\n            t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v)\n        Next i\n    End If\n    shoelace = t / 2\nEnd Function\nPrivate Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _\n    f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer)\n    \n    \n    If acol.Count = 0 Then Exit Sub \n    Debug.Assert acol.Count Mod 2 = 0\n    Debug.Assert f0 <> f1\n    If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1\n    If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0\n    If f0 < f1 Then\n        \n        \n        \n        If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub \n        i = acol.Count + 1\n        start = 1\n        Do\n            i = i - 1\n        Loop Until f1 > acol(i)(rho)\n        If i Mod 2 = start Then\n            acol.Add Array(f1, u1, v1, j), after:=i\n        End If\n        i = 0\n        Do\n            i = i + 1\n        Loop Until f0 < acol(i)(rho)\n        If i Mod 2 = 1 - start Then\n            acol.Add Array(f0, u0, v0, j), before:=i\n            i = i + 1\n        End If\n        Do While acol(i)(rho) < f1\n            acol.Remove i\n            If i > acol.Count Then Exit Do\n        Loop\n    Else\n        start = 1\n        If f0 > acol(1)(rho) Then\n            i = acol.Count + 1\n            Do\n                i = i - 1\n            Loop While f0 < acol(i)(0)\n            If f0 = pi Then\n                acol.Add Array(f0, u0, v0, j), before:=i\n            Else\n                If i Mod 2 = start Then\n                    acol.Add Array(f0, u0, v0, j), after:=i\n                End If\n            End If\n        End If\n        If f1 <= acol(acol.Count)(rho) Then\n            i = 0\n            Do\n                i = i + 1\n            Loop While f1 > acol(i)(rho)\n            If f1 + pi < 5E-16 Then\n                acol.Add Array(f1, u1, v1, j), after:=i\n            Else\n                If i Mod 2 = 1 - start Then\n                    acol.Add Array(f1, u1, v1, j), before:=i\n                End If\n            End If\n        End If\n        Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1\n            acol.Remove acol.Count\n            If acol.Count = 0 Then Exit Do\n        Loop\n        If acol.Count > 0 Then\n            Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this)\n                acol.Remove 1\n                If acol.Count = 0 Then Exit Do\n            Loop\n        End If\n    End If\nEnd Sub\nPrivate Sub circle_cross()\n    ReDim arclists(LBound(c) To UBound(c))\n    Dim alpha As Double, beta As Double\n    Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double\n    Dim i As Integer, j As Integer\n    For i = LBound(c) To UBound(c)\n        Dim arccol As New Collection\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i)\n        arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1)\n        For j = LBound(c) To UBound(c)\n            If i <> j Then\n                x0 = c(i)(xc)\n                y0 = c(i)(yc)\n                r0 = c(i)(rc)\n                x1 = c(j)(xc)\n                y1 = c(j)(yc)\n                r1 = c(j)(rc)\n                d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2)\n                \n                If d >= r0 + r1 Or d <= Abs(r0 - r1) Then\n                    \n                Else\n                    a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d)\n                    h = Sqr(r0 ^ 2 - a ^ 2)\n                    x2 = x0 + a * (x1 - x0) / d\n                    y2 = y0 + a * (y1 - y0) / d\n                    x3 = x2 + h * (y1 - y0) / d\n                    y3 = y2 - h * (x1 - x0) / d\n                    alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0)\n                    x4 = x2 - h * (y1 - y0) / d\n                    y4 = y2 + h * (x1 - x0) / d\n                    beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0)\n                    \n                    \n                    \n                    \n                    arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j\n                End If\n            End If\n        Next j\n        Set arclists(i) = arccol\n        Set arccol = Nothing\n    Next i\nEnd Sub\nPrivate Sub make_path()\n    Dim pathcol As New Collection, arcsum As Double\n    i0 = UBound(arclists)\n    finished = False\n    Do While True\n        arcsum = 0\n        Do While arclists(i0).Count = 0\n            i0 = i0 - 1\n        Loop\n        j0 = arclists(i0).Count\n        next_i = i0\n        next_j = j0\n        Do While True\n            x = arclists(next_i)(next_j)(x_)\n            y = arclists(next_i)(next_j)(y_)\n            pathcol.Add Array(x, y)\n            prev_i = next_i\n            prev_j = next_j\n            If arclists(next_i)(next_j - 1)(i_) = next_i Then\n                \n                next_j = arclists(next_i).Count - 1\n                If next_j = 1 Then Exit Do \n            Else\n                next_j = next_j - 1\n            End If\n            \n            r = c(next_i)(rc)\n            a1 = arclists(next_i)(prev_j)(rho)\n            a2 = arclists(next_i)(next_j)(rho)\n            If a1 > a2 Then\n                alpha = a1 - a2\n            Else\n                alpha = 2 * pi - a2 + a1\n            End If\n            arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2\n            \n            next_i = arclists(next_i)(next_j)(i_)\n            next_j = arclists(next_i).Count\n            If next_j = 0 Then Exit Do \n            Do While arclists(next_i)(next_j)(i_) <> prev_i\n                \n                next_j = next_j - 1\n            Loop\n            If next_i = i0 And next_j = j0 Then\n                finished = True\n                Exit Do\n            End If\n        Loop\n        If finished Then Exit Do\n        i0 = i0 - 1\n        Set pathcol = Nothing\n    Loop\n    Debug.Print shoelace(pathcol) + arcsum\nEnd Sub\nPublic Sub total_circles()\n    give_a_list_of_circles\n    circle_cross\n    make_path\nEnd Sub\n"}
{"id": 50225, "name": "Verify distribution uniformity_Chi-squared test", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 50226, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50227, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 50228, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 50229, "name": "GUI component interaction", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 50230, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n"}
{"id": 50231, "name": "Spelling of ordinal numbers", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n"}
{"id": 50232, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 50233, "name": "Addition chains", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 50234, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n"}
{"id": 50235, "name": "Sparkline in unicode", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 50236, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 50237, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n"}
{"id": 50238, "name": "Own digits power sum", "Python": "\n\ndef isowndigitspowersum(integer):\n    \n    digits = [int(c) for c in str(integer)]\n    exponent = len(digits)\n    return sum(x ** exponent for x in digits) == integer\n\nprint(\"Own digits power sums for N = 3 to 9 inclusive:\")\nfor i in range(100, 1000000000):\n    if isowndigitspowersum(i):\n        print(i)\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\n\n\n\nModule OwnDigitsPowerSum\n\n    Public Sub Main\n\n        \n        Dim used(9) As Integer\n        Dim check(9) As Integer\n        Dim power(9, 9) As Long\n        For i As Integer = 0 To 9\n            check(i) = 0\n        Next i\n        For i As Integer = 1 To 9\n            power(1,  i) = i\n        Next i\n        For j As Integer =  2 To 9\n            For i As Integer = 1 To 9\n                power(j, i) = power(j - 1, i) * i\n            Next i\n        Next j\n        \n        \n        Dim lowestDigit(9) As Integer\n        lowestDigit(1) = -1\n        lowestDigit(2) = -1\n        Dim p10 As Long = 100\n        For i As Integer = 3 To 9\n            For p As Integer = 2 To 9\n                Dim np As Long = power(i, p) * i\n                If Not ( np < p10) Then Exit For\n                lowestDigit(i) = p\n            Next p\n            p10 *= 10\n        Next i\n        \n        Dim maxZeros(9, 9) As Integer\n        For i As Integer = 1 To 9\n            For j As Integer = 1 To 9\n                maxZeros(i, j) = 0\n            Next j\n        Next i\n        p10 = 1000\n        For w As Integer = 3 To 9\n            For d As Integer = lowestDigit(w) To 9\n                Dim nz As Integer = 9\n                Do\n                    If nz < 0 Then\n                        Exit Do\n                    Else\n                        Dim np As Long = power(w, d) * nz\n                        IF Not ( np > p10) Then Exit Do\n                    End If\n                    nz -= 1\n                Loop\n                maxZeros(w, d) = If(nz > w, 0, w - nz)\n            Next d\n            p10 *= 10\n        Next w\n        \n        \n        Dim numbers(100) As Long     \n        Dim nCount As Integer = 0    \n        Dim tryCount As Integer = 0  \n        Dim digits(9) As Integer     \n        For d As Integer = 1 To 9\n             digits(d) = 9\n        Next d\n        For d As Integer = 0 To 8\n            used(d) = 0\n        Next d\n        used(9) = 9\n        Dim width As Integer = 9     \n        Dim last As Integer = width  \n        p10 = 100000000              \n        Do While width > 2\n            tryCount += 1\n            Dim dps As Long = 0      \n            check(0) = used(0)\n            For i As Integer = 1 To 9\n                check(i) = used(i)\n                If used(i) <> 0 Then\n                    dps += used(i) * power(width, i)\n                End If\n            Next i\n            \n            Dim n As Long = dps\n            Do\n                check(CInt(n Mod 10)) -= 1 \n                n \\= 10\n            Loop Until n <= 0\n            Dim reduceWidth As Boolean = dps <= p10\n            If Not reduceWidth Then\n                \n                \n                \n                Dim zCount As Integer = 0\n                For i As Integer = 0 To 9\n                    If check(i) <> 0 Then Exit For\n                    zCount+= 1\n                Next i\n                If zCount = 10 Then\n                    nCount += 1\n                    numbers(nCount) = dps\n                End If\n                \n                used(digits(last)) -= 1\n                digits(last) -= 1\n                If digits(last) = 0 Then\n                    \n                    If used(0) >= maxZeros(width, digits(1)) Then\n                        \n                        digits(last) = -1\n                    End If\n                End If\n                If digits(last) >= 0 Then\n                    \n                    used(digits(last)) += 1\n                Else\n                    \n                    Dim prev As Integer = last\n                    Do\n                        prev -= 1\n                        If prev < 1 Then\n                            Exit Do\n                        Else\n                            used(digits(prev)) -= 1\n                            digits(prev) -= 1\n                            IF digits(prev) >= 0 Then Exit Do\n                        End If\n                    Loop\n                    If prev > 0 Then\n                        \n                        If prev = 1 Then\n                            If digits(1) <= lowestDigit(width) Then\n                               \n                               prev = 0\n                            End If\n                        End If\n                        If prev <> 0 Then\n                           \n                            used(digits(prev)) += 1\n                            For i As Integer = prev + 1 To width\n                                digits(i) = digits(prev)\n                                used(digits(prev)) += 1\n                            Next i\n                        End If\n                    End If\n                    If prev <= 0 Then\n                        \n                        reduceWidth = True\n                    End If\n                End If\n            End If\n            If reduceWidth Then\n                \n                last -= 1\n                width = last\n                If last > 0 Then\n                    \n                    For d As Integer = 1 To last\n                        digits(d) = 9\n                    Next d\n                    For d As Integer = last + 1 To 9\n                        digits(d) = -1\n                    Next d\n                    For d As Integer = 0 To 8\n                        used(d) = 0\n                    Next d\n                    used(9) = last\n                    p10 \\= 10\n                End If\n            End If\n        Loop\n        \n        Console.Out.WriteLine(\"Own digits power sums for N = 3 to 9 inclusive:\")\n        For i As Integer = nCount To 1 Step -1\n            Console.Out.WriteLine(numbers(i))\n        Next i\n        Console.Out.WriteLine(\"Considered \" & tryCount & \" digit combinations\")\n\n    End Sub\n\n\nEnd Module\n"}
{"id": 50239, "name": "Klarner-Rado sequence", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n"}
{"id": 50240, "name": "Klarner-Rado sequence", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n"}
{"id": 50241, "name": "Sorting algorithms_Pancake sort", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n"}
{"id": 50242, "name": "Chemical calculator", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50243, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n"}
{"id": 50244, "name": "Long stairs", "Python": "\n\nfrom numpy import mean\nfrom random import sample\n\ndef gen_long_stairs(start_step, start_length, climber_steps, add_steps):\n    secs, behind, total = 0, start_step, start_length\n    while True:\n        behind += climber_steps\n        behind += sum([behind > n for n in sample(range(total), add_steps)])\n        total += add_steps\n        secs += 1\n        yield (secs, behind, total)\n        \n\nls = gen_long_stairs(1, 100, 1, 5)\n\nprint(\"Seconds  Behind  Ahead\\n----------------------\")\nwhile True:\n    secs, pos, len = next(ls)\n    if 600 <= secs < 610:\n        print(secs, \"     \", pos, \"   \", len - pos)\n    elif secs == 610:\n        break\n\nprint(\"\\nTen thousand trials to top:\")\ntimes, heights = [], []\nfor trial in range(10_000):\n    trialstairs = gen_long_stairs(1, 100, 1, 5)\n    while True:\n        sec, step, height = next(trialstairs)\n        if step >= height:\n            times.append(sec)\n            heights.append(height)\n            break\n\nprint(\"Mean time:\", mean(times), \"secs. Mean height:\", mean(heights))\n", "VB": "Option Explicit\nRandomize Timer\n\nFunction pad(s,n) \n  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If \nEnd Function\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\nFunction Rounds(maxsecs,wiz,a)\n  Dim mystep,maxstep,toend,j,i,x,d \n  If IsArray(a) Then d=True: print \"seconds behind pending\"   \n  maxstep=100\n  For j=1 To maxsecs\n    For i=1 To wiz\n      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1\n      maxstep=maxstep+1  \n    Next \n    mystep=mystep+1 \n    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function\n    If d Then\n      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)\n    End If     \n  Next \n  Rounds=Array(maxsecs,maxstep)\nEnd Function\n\n\nDim n,r,a,sumt,sums,ntests,t,maxsecs\nntests=10000\nmaxsecs=7000\nt=timer\na=Array(600,609)\nFor n=1 To ntests\n  r=Rounds(maxsecs,5,a)\n  If r(0)<>maxsecs Then \n    sumt=sumt+r(0)\n    sums=sums+r(1)\n  End if  \n  a=\"\"\nNext  \n\nprint vbcrlf & \"Done \" & ntests & \" tests in \" & Timer-t & \" seconds\" \nprint \"escaped in \" & sumt/ntests  & \" seconds with \" & sums/ntests & \" stairs\"\n"}
{"id": 50245, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 50246, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 50247, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 50248, "name": "Zebra puzzle", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n"}
{"id": 50249, "name": "Rosetta Code_Find unimplemented tasks", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n"}
{"id": 50250, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 50251, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 50252, "name": "Practical numbers", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n"}
{"id": 50253, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n"}
{"id": 50254, "name": "Word search", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50255, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 50256, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 50257, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 50258, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 50259, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n"}
{"id": 50260, "name": "Zumkeller numbers", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n"}
{"id": 50261, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 50262, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 50263, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 50264, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 50265, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n"}
{"id": 50266, "name": "Geometric algebra", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n"}
{"id": 50267, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n"}
{"id": 50268, "name": "Define a primitive data type", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n"}
{"id": 50269, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n"}
{"id": 50270, "name": "Sierpinski square curve", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n"}
{"id": 50271, "name": "Find words whose first and last three letters are equal", "Python": "import urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>5 and word[:3].lower()==word[-3:].lower():\n        print(word)\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\nset d= createobject(\"Scripting.Dictionary\")\nfor each aa in a\n  x=trim(aa)\n  l=len(x)\n  if l>5 then\n   d.removeall\n   for i=1 to 3\n     m=mid(x,i,1)\n     if not d.exists(m) then d.add m,null\n   next\n   res=true\n   for i=l-2 to l\n     m=mid(x,i,1)\n     if not d.exists(m) then \n       res=false:exit for \n      else\n        d.remove(m)\n      end if        \n   next \n   if res then \n     wscript.stdout.write left(x & space(15),15)\n     if left(x,3)=right(x,3) then  wscript.stdout.write \"*\"\n     wscript.stdout.writeline\n    end if \n  end if\nnext\n"}
{"id": 50272, "name": "Word break problem", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50273, "name": "Latin Squares in reduced form", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50274, "name": "UPC", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n"}
{"id": 50275, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 50276, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 50277, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n"}
{"id": 50278, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n"}
{"id": 50279, "name": "Address of a variable", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n"}
{"id": 50280, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n"}
{"id": 50281, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 50282, "name": "Color wheel", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n"}
{"id": 50283, "name": "Rare numbers", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n", "VB": "Imports System.Console\nImports DT = System.DateTime\nImports Lsb = System.Collections.Generic.List(Of SByte)\nImports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte))\nImports UI = System.UInt64\n\nModule Module1\n    Const MxD As SByte = 15\n\n    Public Structure term\n        Public coeff As UI : Public a, b As SByte\n        Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer)\n            coeff = c : a = CSByte(a_) : b = CSByte(b_)\n        End Sub\n    End Structure\n\n    Dim nd, nd2, count As Integer, digs, cnd, di As Integer()\n    Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term))\n    Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst)\n    Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI\n\n    \n    Function ToDif() As UI\n        Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i)\n        Next : Return r\n    End Function\n\n    \n    Function ToSum() As UI\n        Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i)\n        Next : Return Dif + (r << 1)\n    End Function\n\n    \n    Function IsSquare(nmbr As UI) As Boolean\n        If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _\n            Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False\n    End Function\n\n    \n    Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb\n        Dim res As Lsb = New Lsb()\n        For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res\n    End Function\n\n    \n    Sub Fnpr(ByVal lev As Integer)\n        If lev = dis.Count Then\n            digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1)\n            Dim le As Integer = di.Length, i As Integer = 1\n            If odd Then le -= 1 : digs(nd >> 1) = di(le)\n            For Each d As SByte In di.Skip(1).Take(le - 1)\n                digs(ixs(i)(0)) = dmd(cnd(i))(d)(0)\n                digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next\n            If Not IsSquare(ToSum()) Then Return\n            res.Add(ToDif()) : count += 1\n            WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\", (DT.Now - st).TotalMilliseconds, count, res.Last())\n        Else\n            For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next\n        End If\n    End Sub\n\n    \n    Sub Fnmr(ByVal list As Lst, ByVal lev As Integer)\n        If lev = list.Count Then\n            Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2)\n                If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _\n                              Else Dif += t.coeff * CULng(cnd(i))\n                i += 1 : Next\n            If Dif <= 0 OrElse Not IsSquare(Dif) Then Return\n            dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)}\n            For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next\n            If odd Then dis.Add(il)\n            di = New Integer(dis.Count - 1) {} : Fnpr(0)\n        Else\n            For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next\n        End If\n    End Sub\n\n    Sub init()\n        Dim pow As UI = 1\n        \n        tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD)\n            Dim terms As List(Of term) = New List(Of term)()\n            pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1\n            Dim i1 As Integer = 0, i2 As Integer = r - 1\n            While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2))\n                p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While\n            tLst.Add(terms) : Next\n        \n        fml = New Dictionary(Of Integer, Lst)() From {\n            {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}},\n            {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}},\n            {4, New Lst() From {New Lsb() From {4, 0}}},\n            {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}}\n        \n        dmd = New Dictionary(Of Integer, Lst)()\n        For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i\n            While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _\n                Else dmd(d) = New Lst From {New Lsb From {i, j}}\n                j += 1 : d -= 1 : End While : Next\n        dl = Seq(-9, 9)    \n        zl = Seq(0, 0)     \n        el = Seq(-8, 8, 2) \n        ol = Seq(-9, 9, 2) \n        il = Seq(0, 9)\n        lists = New List(Of Lst)()\n        For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next\n    End Sub\n\n    Sub Main(ByVal args As String())\n        init() : res = New List(Of UI)() : st = DT.Now : count = 0\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Rare Numbers\")\n        nd = 2 : nd2 = 0 : odd = False : While nd <= MxD\n            digs = New Integer(nd - 1) {} : If nd = 4 Then\n                lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol)\n            ElseIf tLst(nd2).Count > lists(0).Count Then\n                For Each list As Lst In lists : list.Add(dl) : Next : End If\n            ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next\n            For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds)\n            nd += 1 : nd2 += 1 : odd = Not odd : End While\n        res.Sort() : WriteLine(vbLf & \"The {0} rare numbers with up to {1} digits are:\", res.Count, MxD)\n        count = 0 : For Each rare In res : count += 1 : WriteLine(\"{0,2}:{1,27:n0}\", count, rare) : Next\n        If System.Diagnostics.Debugger.IsAttached Then ReadKey()\n    End Sub\nEnd Module\n"}
{"id": 50284, "name": "Find words which contain the most consonants", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n"}
{"id": 50285, "name": "Find words which contain the most consonants", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n"}
{"id": 50286, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n"}
{"id": 50287, "name": "Primes with digits in nondecreasing order", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50288, "name": "Primes with digits in nondecreasing order", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50289, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50290, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n"}
{"id": 50291, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 50292, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 50293, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 50294, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50295, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50296, "name": "Commatizing numbers", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n"}
{"id": 50297, "name": "Arithmetic coding_As a generalized change of radix", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50298, "name": "Kosaraju", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n"}
{"id": 50299, "name": "Pentomino tiling", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n", "VB": "Module Module1\n\n    Dim symbols As Char() = \"XYPFTVNLUZWI█\".ToCharArray(),\n        nRows As Integer = 8, nCols As Integer = 8,\n        target As Integer = 12, blank As Integer = 12,\n        grid As Integer()() = New Integer(nRows - 1)() {},\n        placed As Boolean() = New Boolean(target - 1) {},\n        pens As List(Of List(Of Integer())), rand As Random,\n        seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}\n\n    Sub Main()\n        Unpack(seeds) : rand = New Random() : ShuffleShapes(2)\n        For r As Integer = 0 To nRows - 1\n            grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next\n        For i As Integer = 0 To 3\n            Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)\n            Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank\n        Next\n        If Solve(0, 0) Then\n            PrintResult()\n        Else\n            Console.WriteLine(\"no solution for this configuration:\") : PrintResult()\n        End If\n        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\n    Sub ShuffleShapes(count As Integer) \n        For i As Integer = 0 To count : For j = 0 To pens.Count - 1\n                Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j\n                Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp\n                Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch\n            Next : Next\n    End Sub\n\n    Sub PrintResult() \n        For Each r As Integer() In grid : For Each i As Integer In r\n                Console.Write(\"{0} \", If(i < 0, \".\", symbols(i)))\n            Next : Console.WriteLine() : Next\n    End Sub\n\n    \n    Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean\n        If numPlaced = target Then Return True\n        Dim row As Integer = pos \\ nCols, col As Integer = pos Mod nCols\n        If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)\n        For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then\n                For Each orientation As Integer() In pens(i)\n                    If Not TPO(orientation, row, col, i) Then Continue For\n                    placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True\n                    RmvO(orientation, row, col) : placed(i) = False\n                Next : End If : Next : Return False\n    End Function\n\n    \n    Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)\n        grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = -1 : Next\n    End Sub\n\n    \n    Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,\n                 ByVal sIdx As Integer) As Boolean\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)\n            If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse\n                grid(y)(x) <> -1 Then Return False\n        Next : grid(row)(col) = sIdx\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = sIdx\n        Next : Return True\n    End Function\n\n    \n    \n    \n    \n\n    Sub Unpack(sv As Integer()) \n        pens = New List(Of List(Of Integer())) : For Each item In sv\n            Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),\n                fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7\n                If i = 4 Then Mir(exi) Else Rot(exi)\n                fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))\n            Next : pens.Add(Gen) : Next\n    End Sub\n\n    \n    Function Expand(i As Integer) As List(Of Integer)\n        Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next\n    End Function\n\n    \n    Function ToP(p As List(Of Integer)) As Integer()\n        Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)\n            tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next\n        tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next\n        Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)\n            Dim adj = If((item And 7) > 4, 8, 0)\n            res.Add((adj + item) \\ 8) : res.Add((item And 7) - adj)\n        Next : Return res.ToArray()\n    End Function\n\n    \n    Function TheSame(a As Integer(), b As Integer()) As Boolean\n        For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False\n        Next : Return True\n    End Function\n\n    Sub Rot(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next\n    End Sub\n\n    Sub Mir(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next\n    End Sub\n\nEnd Module\n"}
{"id": 50300, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "VB": "Dim variable As datatype\nDim var1,var2,... As datatype\n"}
{"id": 50301, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n"}
{"id": 50302, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n"}
{"id": 50303, "name": "Check Machin-like formulas", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50304, "name": "Check Machin-like formulas", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50305, "name": "Solve triangle solitare puzzle", "Python": "\n\n\ndef DrawBoard(board):\n  peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n  for n in xrange(1,16):\n    peg[n] = '.'\n    if n in board:\n      peg[n] = \"%X\" % n\n  print \"     %s\" % peg[1]\n  print \"    %s %s\" % (peg[2],peg[3])\n  print \"   %s %s %s\" % (peg[4],peg[5],peg[6])\n  print \"  %s %s %s %s\" % (peg[7],peg[8],peg[9],peg[10])\n  print \" %s %s %s %s %s\" % (peg[11],peg[12],peg[13],peg[14],peg[15])\n\n\n\ndef RemovePeg(board,n):\n  board.remove(n)\n\n\ndef AddPeg(board,n):\n  board.append(n)\n\n\ndef IsPeg(board,n):\n  return n in board\n\n\n\nJumpMoves = { 1: [ (2,4),(3,6) ],  \n              2: [ (4,7),(5,9)  ],\n              3: [ (5,8),(6,10) ],\n              4: [ (2,1),(5,6),(7,11),(8,13) ],\n              5: [ (8,12),(9,14) ],\n              6: [ (3,1),(5,4),(9,13),(10,15) ],\n              7: [ (4,2),(8,9)  ],\n              8: [ (5,3),(9,10) ],\n              9: [ (5,2),(8,7)  ],\n             10: [ (9,8) ],\n             11: [ (12,13) ],\n             12: [ (8,5),(13,14) ],\n             13: [ (8,4),(9,6),(12,11),(14,15) ],\n             14: [ (9,5),(13,12)  ],\n             15: [ (10,6),(14,13) ]\n            }\n\nSolution = []\n\n\n\ndef Solve(board):\n  \n  if len(board) == 1:\n    return board \n  \n  for peg in xrange(1,16): \n    if IsPeg(board,peg):\n      movelist = JumpMoves[peg]\n      for over,land in movelist:\n        if IsPeg(board,over) and not IsPeg(board,land):\n          saveboard = board[:] \n          RemovePeg(board,peg)\n          RemovePeg(board,over)\n          AddPeg(board,land) \n\n          Solution.append((peg,over,land))\n\n          board = Solve(board)\n          if len(board) == 1:\n            return board\n        \n          board = saveboard[:] \n          del Solution[-1] \n  return board\n\n\n\n\ndef InitSolve(empty):\n  board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n  RemovePeg(board,empty_start)\n  Solve(board)\n\n\nempty_start = 1\nInitSolve(empty_start)\n\nboard = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nRemovePeg(board,empty_start)\nfor peg,over,land in Solution:\n  RemovePeg(board,peg)\n  RemovePeg(board,over)\n  AddPeg(board,land) \n  DrawBoard(board)\n  print \"Peg %X jumped over %X to land on %X\\n\" % (peg,over,land)\n", "VB": "Imports System, Microsoft.VisualBasic.DateAndTime\n\nPublic Module Module1\n    Const n As Integer = 5 \n    Dim Board As String \n    Dim Starting As Integer = 1 \n    Dim Target As Integer = 13 \n    Dim Moves As Integer() \n    Dim bi() As Integer \n    Dim ib() As Integer \n    Dim nl As Char = Convert.ToChar(10) \n\n    \n    Public Function Dou(s As String) As String\n        Dou = \"\" : Dim b As Boolean = True\n        For Each ch As Char In s\n            If b Then b = ch <> \" \"\n            If b Then Dou &= ch & \" \" Else Dou = \" \" & Dou\n        Next : Dou = Dou.TrimEnd()\n    End Function\n\n    \n    Public Function Fmt(s As String) As String\n        If s.Length < Board.Length Then Return s\n        Fmt = \"\" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &\n                If(i = n, s.Substring(Board.Length), \"\") & nl\n        Next\n    End Function\n\n    \n    Public Function Triangle(n As Integer) As Integer\n        Return (n * (n + 1)) / 2\n    End Function\n\n    \n    Public Function Init(s As String, pos As Integer) As String\n        Init = s : Mid(Init, pos, 1) = \"0\"\n    End Function\n\n    \n    Public Sub InitIndex()\n        ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0\n        For i As Integer = 0 To ib.Length - 1\n            If i = 0 Then\n                ib(i) = 0 : bi(j) = 0 : j += 1\n            Else\n                If Board(i - 1) = \"1\" Then ib(i) = j : bi(j) = i : j += 1\n            End If\n        Next\n    End Sub\n\n    \n    Public Function solve(brd As String, pegsLeft As Integer) As String\n        If pegsLeft = 1 Then \n            If Target = 0 Then Return \"Completed\" \n            If brd(bi(Target) - 1) = \"1\" Then Return \"Completed\" Else Return \"fail\"\n        End If\n        For i = 1 To Board.Length \n            If brd(i - 1) = \"1\" Then \n                For Each mj In Moves \n                    Dim over As Integer = i + mj \n                    Dim land As Integer = i + 2 * mj \n                    \n                    If land >= 1 AndAlso land <= brd.Length _\n                                AndAlso brd(land - 1) = \"0\" _\n                                AndAlso brd(over - 1) = \"1\" Then\n                        setPegs(brd, \"001\", i, over, land) \n                        \n                        Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)\n                        \n                        If Res.Length <> 4 Then _\n                            Return brd & info(i, over, land) & nl & Res\n                        setPegs(brd, \"110\", i, over, land) \n                    End If\n                Next\n            End If\n        Next\n        Return \"fail\"\n    End Function\n\n    \n    Function info(frm As Integer, over As Integer, dest As Integer) As String\n        Return \"  Peg from \" & ib(frm).ToString() & \" goes to \" & ib(dest).ToString() &\n            \", removing peg at \" & ib(over).ToString()\n    End Function\n\n    \n    Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)\n        Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)\n    End Sub\n\n    \n    Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)\n        x = Math.Max(Math.Min(x, hi), lo)\n    End Sub\n\n    Public Sub Main()\n        Dim t As Integer = Triangle(n) \n        LimitIt(Starting, 1, t) \n        LimitIt(Target, 0, t)\n        Dim stime As Date = Now() \n        Moves = {-n - 1, -n, -1, 1, n, n + 1} \n        Board = New String(\"1\", n * n) \n        For i As Integer = 0 To n - 2 \n            Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(\" \", n - 1 - i)\n        Next\n        InitIndex() \n        Dim B As String = Init(Board, bi(Starting)) \n        Console.WriteLine(Fmt(B & \"  Starting with peg removed from \" & Starting.ToString()))\n        Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)\n        Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & \" ms.\"\n        If res(0).Length = 4 Then\n            If Target = 0 Then\n                Console.WriteLine(\"Unable to find a solution with last peg left anywhere.\")\n            Else\n                Console.WriteLine(\"Unable to find a solution with last peg left at \" &\n                                  Target.ToString() & \".\")\n            End If\n            Console.WriteLine(\"Computation time: \" & ts)\n        Else\n            For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next\n            Console.WriteLine(\"Computation time to first found solution: \" & ts)\n        End If\n        If Diagnostics.Debugger.IsAttached Then Console.ReadLine()\n    End Sub\nEnd Module\n"}
{"id": 50306, "name": "Twelve statements", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n"}
{"id": 50307, "name": "Suffixation of decimal numbers", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n"}
{"id": 50308, "name": "Suffixation of decimal numbers", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n"}
{"id": 50309, "name": "Nested templated data", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n", "VB": "Public Sub test()\n    Dim t(2) As Variant\n    t(0) = [{1,2}]\n    t(1) = [{3,4,1}]\n    t(2) = 5\n    p = [{\"Payload#0\",\"Payload#1\",\"Payload#2\",\"Payload#3\",\"Payload#4\",\"Payload#5\",\"Payload#6\"}]\n    Dim q(6) As Boolean\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            For j = LBound(t(i)) To UBound(t(i))\n                q(t(i)(j)) = True\n                t(i)(j) = p(t(i)(j) + 1)\n            Next j\n        Else\n            q(t(i)) = True\n            t(i) = p(t(i) + 1)\n        End If\n    Next i\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            Debug.Print Join(t(i), \", \")\n        Else\n            Debug.Print t(i)\n        End If\n    Next i\n    For i = LBound(q) To UBound(q)\n        If Not q(i) Then Debug.Print p(i + 1); \" is not used\"\n    Next i\nEnd Sub\n"}
{"id": 50310, "name": "Solve hanging lantern problem", "Python": "def getLantern(arr):\n    res = 0\n    for i in range(0, n):\n        if arr[i] != 0:\n            arr[i] -= 1\n            res += getLantern(arr)\n            arr[i] += 1\n    if res == 0:\n        res = 1\n    return res\n\na = []\nn = int(input())\nfor i in range(0, n):\n    a.append(int(input()))\nprint(getLantern(a))\n", "VB": "Dim n As Integer, c As Integer\nDim a() As Integer\n\nPrivate Sub Command1_Click()\n    Dim res As Integer\n    If c < n Then Label3.Caption = \"Please input completely.\": Exit Sub\n    res = getLantern(a())\n    Label3.Caption = \"Result：\" + Str(res)\nEnd Sub\n\nPrivate Sub Text1_Change()\n    If Val(Text1.Text) <> 0 Then\n        n = Val(Text1.Text)\n        ReDim a(1 To n) As Integer\n    End If\nEnd Sub\n\n\nPrivate Sub Text2_KeyPress(KeyAscii As Integer)\n    If KeyAscii = Asc(vbCr) Then\n        If Val(Text2.Text) = 0 Then Exit Sub\n        c = c + 1\n        If c > n Then Exit Sub\n        a(c) = Val(Text2.Text)\n        List1.AddItem Str(a(c))\n        Text2.Text = \"\"\n    End If\nEnd Sub\n\nFunction getLantern(arr() As Integer) As Integer\n    Dim res As Integer, i As Integer\n    For i = 1 To n\n        If arr(i) <> 0 Then\n            arr(i) = arr(i) - 1\n            res = res + getLantern(arr())\n            arr(i) = arr(i) + 1\n        End If\n    Next i\n    If res = 0 Then res = 1\n    getLantern = res\nEnd Function\n"}
{"id": 50311, "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": 50312, "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", "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": 50313, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 50314, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 50315, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 50316, "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", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 50317, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 50318, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 50319, "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", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\n"}
{"id": 50320, "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", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n"}
{"id": 50321, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 50322, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 50323, "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", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n"}
{"id": 50324, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 50325, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 50326, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 50327, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 50328, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 50329, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 50330, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50331, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 50332, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 50333, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 50334, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 50335, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 50336, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 50337, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 50338, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 50339, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 50340, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 50341, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 50342, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50343, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 50344, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 50345, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 50346, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n"}
{"id": 50347, "name": "Write entire file", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 50348, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 50349, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 50350, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 50351, "name": "Roots of unity", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 50352, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50353, "name": "Pell's equation", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50354, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 50355, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 50356, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 50357, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 50358, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 50359, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 50360, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 50361, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 50362, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 50363, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 50364, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 50365, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 50366, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 50367, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 50368, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 50369, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 50370, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50371, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50372, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 50373, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 50374, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n"}
{"id": 50375, "name": "Chat server", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50376, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 50377, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 50378, "name": "Terminal control_Dimensions", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n"}
{"id": 50379, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 50380, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 50381, "name": "Literals_String", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n"}
{"id": 50382, "name": "GUI_Maximum window dimensions", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n"}
{"id": 50383, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 50384, "name": "Knapsack problem_Unbounded", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n"}
{"id": 50385, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n"}
{"id": 50386, "name": "Type detection", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n"}
{"id": 50387, "name": "Maximum triangle path sum", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n"}
{"id": 50388, "name": "UTF-8 encode and decode", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n"}
{"id": 50389, "name": "Magic squares of doubly even order", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n"}
{"id": 50390, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 50391, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n"}
{"id": 50392, "name": "XML validation", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n"}
{"id": 50393, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n"}
{"id": 50394, "name": "Brace expansion", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50395, "name": "GUI component interaction", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 50396, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n"}
{"id": 50397, "name": "Addition chains", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 50398, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n"}
{"id": 50399, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 50400, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 50401, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n"}
{"id": 50402, "name": "Chemical calculator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50403, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n"}
{"id": 50404, "name": "Zebra puzzle", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n"}
{"id": 50405, "name": "Zebra puzzle", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n"}
{"id": 50406, "name": "Rosetta Code_Find unimplemented tasks", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n"}
{"id": 50407, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 50408, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 50409, "name": "Practical numbers", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n"}
{"id": 50410, "name": "Literals_Floating point", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n"}
{"id": 50411, "name": "Literals_Floating point", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n"}
{"id": 50412, "name": "Word search", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50413, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 50414, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 50415, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 50416, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 50417, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n"}
{"id": 50418, "name": "Zumkeller numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n"}
{"id": 50419, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 50420, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 50421, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 50422, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 50423, "name": "Dijkstra's algorithm", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n"}
{"id": 50424, "name": "Geometric algebra", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n"}
{"id": 50425, "name": "Associative array_Iteration", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n"}
{"id": 50426, "name": "Define a primitive data type", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n"}
{"id": 50427, "name": "Hash join", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n"}
{"id": 50428, "name": "Latin Squares in reduced form", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50429, "name": "Latin Squares in reduced form", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50430, "name": "Closest-pair problem", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n"}
{"id": 50431, "name": "Address of a variable", "C#": "int i = 5;\nint* p = &i;\n", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n"}
{"id": 50432, "name": "Inheritance_Single", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n"}
{"id": 50433, "name": "Associative array_Creation", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 50434, "name": "Color wheel", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n"}
{"id": 50435, "name": "Rare numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nusing UI = System.UInt64;\nusing LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;\nusing Lst = System.Collections.Generic.List<sbyte>;\nusing DT = System.DateTime;\n\nclass Program {\n\n    const sbyte MxD = 19;\n\n    public struct term { public UI coeff; public sbyte a, b;\n        public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } }\n\n    static int[] digs;   static List<UI> res;   static sbyte count = 0;\n    static DT st; static List<List<term>> tLst; static List<LST> lists;\n    static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il;\n    static bool odd; static int nd, nd2; static LST ixs;\n    static int[] cnd, di; static LST dis; static UI Dif;\n\n    \n    static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++)\n            r = r * 10 + (uint)digs[i]; return r; }\n    \n    \n    static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--)\n            r = r * 10 + (uint)digs[i]; return Dif + (r << 1); }\n\n    \n    static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0)\n        { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; }\n\n    \n    static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst();\n        for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; }\n\n    \n    static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0];\n            digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1;\n            if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) {\n                digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; }\n            if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\",\n                (DT.Now - st).TotalMilliseconds, ++count, res.Last()); }\n        else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } }\n\n    \n    static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0;\n            foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]);\n                else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return;\n            dis = new LST { Seq(0, fml[cnd[0]].Count - 1) };\n            foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1));\n            if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0);\n        } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } }\n\n    static void init() { UI pow = 1;\n        \n        tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) {\n            List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1;\n            for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) {\n                terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; }\n            tLst.Add(terms); }\n        \n        fml = new Dictionary<int, LST> {\n            [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } },\n            [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } },\n            [4] = new LST { new Lst { 4, 0 } },\n            [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } };\n        \n        dmd = new Dictionary<int, LST>();\n        for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) {\n                if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j });\n                else dmd[d] = new LST { new Lst { i, j } }; }\n        dl = Seq(-9, 9);    \n        zl = Seq( 0, 0);    \n        el = Seq(-8, 8, 2); \n        ol = Seq(-9, 9, 2); \n        il = Seq( 0, 9); lists = new List<LST>();\n        foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); }\n\n    static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0;\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Unordered Rare Numbers\");\n        for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd];\n            if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); }\n            else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl);\n            ixs = new LST(); \n            foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b });\n            foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); }\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds); }\n        res.Sort();\n        WriteLine(\"\\nThe {0} rare numbers with up to {1} digits are:\", res.Count, MxD);\n        count = 0; foreach (var rare in res) WriteLine(\"{0,2}:{1,27:n0}\", ++count, rare);\n        if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }\n}\n", "VB": "Imports System.Console\nImports DT = System.DateTime\nImports Lsb = System.Collections.Generic.List(Of SByte)\nImports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte))\nImports UI = System.UInt64\n\nModule Module1\n    Const MxD As SByte = 15\n\n    Public Structure term\n        Public coeff As UI : Public a, b As SByte\n        Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer)\n            coeff = c : a = CSByte(a_) : b = CSByte(b_)\n        End Sub\n    End Structure\n\n    Dim nd, nd2, count As Integer, digs, cnd, di As Integer()\n    Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term))\n    Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst)\n    Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI\n\n    \n    Function ToDif() As UI\n        Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i)\n        Next : Return r\n    End Function\n\n    \n    Function ToSum() As UI\n        Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i)\n        Next : Return Dif + (r << 1)\n    End Function\n\n    \n    Function IsSquare(nmbr As UI) As Boolean\n        If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _\n            Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False\n    End Function\n\n    \n    Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb\n        Dim res As Lsb = New Lsb()\n        For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res\n    End Function\n\n    \n    Sub Fnpr(ByVal lev As Integer)\n        If lev = dis.Count Then\n            digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1)\n            Dim le As Integer = di.Length, i As Integer = 1\n            If odd Then le -= 1 : digs(nd >> 1) = di(le)\n            For Each d As SByte In di.Skip(1).Take(le - 1)\n                digs(ixs(i)(0)) = dmd(cnd(i))(d)(0)\n                digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next\n            If Not IsSquare(ToSum()) Then Return\n            res.Add(ToDif()) : count += 1\n            WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\", (DT.Now - st).TotalMilliseconds, count, res.Last())\n        Else\n            For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next\n        End If\n    End Sub\n\n    \n    Sub Fnmr(ByVal list As Lst, ByVal lev As Integer)\n        If lev = list.Count Then\n            Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2)\n                If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _\n                              Else Dif += t.coeff * CULng(cnd(i))\n                i += 1 : Next\n            If Dif <= 0 OrElse Not IsSquare(Dif) Then Return\n            dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)}\n            For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next\n            If odd Then dis.Add(il)\n            di = New Integer(dis.Count - 1) {} : Fnpr(0)\n        Else\n            For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next\n        End If\n    End Sub\n\n    Sub init()\n        Dim pow As UI = 1\n        \n        tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD)\n            Dim terms As List(Of term) = New List(Of term)()\n            pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1\n            Dim i1 As Integer = 0, i2 As Integer = r - 1\n            While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2))\n                p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While\n            tLst.Add(terms) : Next\n        \n        fml = New Dictionary(Of Integer, Lst)() From {\n            {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}},\n            {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}},\n            {4, New Lst() From {New Lsb() From {4, 0}}},\n            {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}}\n        \n        dmd = New Dictionary(Of Integer, Lst)()\n        For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i\n            While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _\n                Else dmd(d) = New Lst From {New Lsb From {i, j}}\n                j += 1 : d -= 1 : End While : Next\n        dl = Seq(-9, 9)    \n        zl = Seq(0, 0)     \n        el = Seq(-8, 8, 2) \n        ol = Seq(-9, 9, 2) \n        il = Seq(0, 9)\n        lists = New List(Of Lst)()\n        For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next\n    End Sub\n\n    Sub Main(ByVal args As String())\n        init() : res = New List(Of UI)() : st = DT.Now : count = 0\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Rare Numbers\")\n        nd = 2 : nd2 = 0 : odd = False : While nd <= MxD\n            digs = New Integer(nd - 1) {} : If nd = 4 Then\n                lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol)\n            ElseIf tLst(nd2).Count > lists(0).Count Then\n                For Each list As Lst In lists : list.Add(dl) : Next : End If\n            ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next\n            For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds)\n            nd += 1 : nd2 += 1 : odd = Not odd : End While\n        res.Sort() : WriteLine(vbLf & \"The {0} rare numbers with up to {1} digits are:\", res.Count, MxD)\n        count = 0 : For Each rare In res : count += 1 : WriteLine(\"{0,2}:{1,27:n0}\", count, rare) : Next\n        If System.Diagnostics.Debugger.IsAttached Then ReadKey()\n    End Sub\nEnd Module\n"}
{"id": 50436, "name": "Minesweeper game", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MineFieldModel\n{\n    public int RemainingMinesCount{\n        get{\n            var count = 0;\n            ForEachCell((i,j)=>{\n                if (Mines[i,j] && !Marked[i,j])\n                    count++;\n            });\n            return count;\n        }\n    }\n\n    public bool[,] Mines{get; private set;}\n    public bool[,] Opened{get;private set;}\n    public bool[,] Marked{get; private set;}\n    public int[,] Values{get;private set; }\n    public int Width{ get{return Mines.GetLength(1);} } \n    public int Height{ get{return Mines.GetLength(0);} }\n\n    public MineFieldModel(bool[,] mines)\n    {\n        this.Mines = mines;\n        this.Opened = new bool[Height, Width]; \n        this.Marked = new bool[Height, Width];\n        this.Values = CalculateValues();\n    }\n    \n    private int[,] CalculateValues()\n    {\n        int[,] values = new int[Height, Width];\n        ForEachCell((i,j) =>{\n            var value = 0;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (Mines[i1,j1])\n                    value++;\n            });\n            values[i,j] = value;\n        });\n        return values;\n    }\n\n    \n    public void ForEachCell(Action<int,int> action)\n    {\n        for (var i = 0; i < Height; i++)\n        for (var j = 0; j < Width; j++)\n            action(i,j);\n    }\n\n    \n    public void ForEachNeighbor(int i, int j, Action<int,int> action)\n    {\n        for (var i1 = i-1; i1 <= i+1; i1++)\n        for (var j1 = j-1; j1 <= j+1; j1++)               \n            if (InBounds(j1, i1) && !(i1==i && j1 ==j))\n                action(i1, j1);\n    }\n\n    private bool InBounds(int x, int y)\n    {\n        return y >= 0 && y < Height && x >=0 && x < Width;\n    }\n\n    public event Action Exploded = delegate{};\n    public event Action Win = delegate{};\n    public event Action Updated = delegate{};\n\n    public void OpenCell(int i, int j){\n        if(!Opened[i,j]){\n            if (Mines[i,j])\n                Exploded();\n            else{\n                OpenCellsStartingFrom(i,j);\n                Updated();\n                CheckForVictory();\n            }\n        }\n    }\n\n    void OpenCellsStartingFrom(int i, int j)\n    {\n            Opened[i,j] = true;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1])\n                    OpenCellsStartingFrom(i1, j1);\n            });\n    }\n    \n    void CheckForVictory(){\n        int notMarked = 0;\n        int wrongMarked = 0;\n        ForEachCell((i,j)=>{\n            if (Mines[i,j] && !Marked[i,j])\n                notMarked++;\n            if (!Mines[i,j] && Marked[i,j])\n                wrongMarked++;\n        }); \n        if (notMarked == 0 && wrongMarked == 0)\n            Win();\n    }\n\n    public void Mark(int i, int j){\n        if (!Opened[i,j])\n            Marked[i,j] = true;\n            Updated();\n            CheckForVictory();\n    }\n}\n\nclass MineFieldView: UserControl{\n    public const int CellSize = 40;\n\n    MineFieldModel _model;\n    public MineFieldModel Model{\n        get{ return _model; }\n        set\n        { \n            _model = value; \n            this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2);\n        }\n    }\n    \n    public MineFieldView(){\n        \n        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true);\n        this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);\n\n        this.MouseUp += (o,e)=>{\n            Point cellCoords = GetCell(e.Location);\n            if (Model != null)\n            {\n                if (e.Button == MouseButtons.Left)\n                    Model.OpenCell(cellCoords.Y, cellCoords.X);\n                else if (e.Button == MouseButtons.Right)\n                    Model.Mark(cellCoords.Y, cellCoords.X);\n            }\n        };\n    }\n\n    Point GetCell(Point coords)\n    {\n        var rgn = ClientRectangle;\n        var x = (coords.X - rgn.X)/CellSize;\n        var y = (coords.Y - rgn.Y)/CellSize;\n        return new Point(x,y);\n    }\n         \n    static readonly Brush MarkBrush = new SolidBrush(Color.Blue);\n    static readonly Brush ValueBrush = new SolidBrush(Color.Black);\n    static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control);\n    static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark);\n\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        var g = e.Graphics;\n        if (Model != null)\n        {\n            Model.ForEachCell((i,j)=>\n            {\n                var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize);\n                if (Model.Opened[i,j])\n                {\n                    g.FillRectangle(OpenBrush, bounds);\n                    if (Model.Values[i,j] > 0)\n                    {\n                        DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds);\n                    }\n                } \n                else \n                {\n                    g.FillRectangle(UnexploredBrush, bounds);\n                    if (Model.Marked[i,j])\n                    {\n                        DrawStringInCenter(g, \"?\", MarkBrush, bounds);\n                    }\n                    var outlineOffset = 1;\n                    var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset);\n                    g.DrawRectangle(Pens.Gray, outline);\n                }\n                g.DrawRectangle(Pens.Black, bounds);\n            });\n        }\n\n    }\n\n    static readonly StringFormat FormatCenter = new StringFormat\n                            {\n                                LineAlignment = StringAlignment.Center,\n                                Alignment=StringAlignment.Center\n                            };\n\n    void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds)\n    {\n        PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2);\n        g.DrawString(s, this.Font, brush, center, FormatCenter);\n    }\n\n}\n\nclass MineSweepForm: Form\n{\n\n    MineFieldModel CreateField(int width, int height)\n{\n        var field = new bool[height, width];\n        int mineCount = (int)(0.2 * height * width);\n        var rnd = new Random();\n        while(mineCount > 0)\n        {\n            var x = rnd.Next(width);\n            var y = rnd.Next(height);\n            if (!field[y,x])\n            {\n                field[y,x] = true;\n                mineCount--;\n            }\n        }\n        return new MineFieldModel(field);\n    }\n\n    public MineSweepForm()\n    {\n        var model = CreateField(6, 4);\n        var counter = new Label{ };\n        counter.Text = model.RemainingMinesCount.ToString();\n        var view = new MineFieldView\n                        { \n                            Model = model, BorderStyle = BorderStyle.FixedSingle,\n                        };\n        var stackPanel = new FlowLayoutPanel\n                        {\n                            Dock = DockStyle.Fill,\n                            FlowDirection = FlowDirection.TopDown,\n                            Controls = {counter, view}\n                        };\n        this.Controls.Add(stackPanel);\n        model.Updated += delegate{\n            view.Invalidate();\n            counter.Text = model.RemainingMinesCount.ToString();\n        };\n        model.Exploded += delegate {\n            MessageBox.Show(\"FAIL!\");\n            Close();\n        };\n        model.Win += delegate {\n            MessageBox.Show(\"WIN!\");\n            view.Enabled = false;\n        };\n\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Application.Run(new MineSweepForm());\n    }\n}\n", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n"}
{"id": 50437, "name": "Square root by hand", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n"}
{"id": 50438, "name": "Square root by hand", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n"}
{"id": 50439, "name": "Primes with digits in nondecreasing order", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50440, "name": "Primes with digits in nondecreasing order", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n"}
{"id": 50441, "name": "Reflection_List properties", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50442, "name": "Align columns", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n"}
{"id": 50443, "name": "Align columns", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n"}
{"id": 50444, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 50445, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 50446, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50447, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50448, "name": "Data Encryption Standard", "C#": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace DES {\n    class Program {\n        \n        static string ByteArrayToString(byte[] ba) {\n            return BitConverter.ToString(ba).Replace(\"-\", \"\");\n        }\n\n        \n        \n        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(messageBytes, 0, messageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] encryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n\n            return encryptedMessageBytes;\n        }\n\n        \n        \n        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] decryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);\n\n            return decryptedMessageBytes;\n        }\n\n        static void Main(string[] args) {\n            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };\n            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };\n\n            byte[] encStr = Encrypt(plainBytes, keyBytes);\n            Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr));\n\n            byte[] decBytes = Decrypt(encStr, keyBytes);\n            Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decBytes));\n        }\n    }\n}\n", "VB": "Imports System.IO\nImports System.Security.Cryptography\n\nModule Module1\n\n    \n    Function ByteArrayToString(ba As Byte()) As String\n        Return BitConverter.ToString(ba).Replace(\"-\", \"\")\n    End Function\n\n    \n    \n    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateEncryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(messageBytes, 0, messageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim encryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n\n        Return encryptedMessageBytes\n    End Function\n\n    \n    \n    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateDecryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim decryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)\n\n        Return decryptedMessageBytes\n    End Function\n\n    Sub Main()\n        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}\n        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}\n\n        Dim encStr = Encrypt(plainBytes, keyBytes)\n        Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr))\n\n        Dim decStr = Decrypt(encStr, keyBytes)\n        Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decStr))\n    End Sub\n\nEnd Module\n"}
{"id": 50449, "name": "Commatizing numbers", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n"}
{"id": 50450, "name": "Arithmetic coding_As a generalized change of radix", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 50451, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n"}
{"id": 50452, "name": "Twelve statements", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n"}
{"id": 50453, "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": 50454, "name": "Carmichael 3 strong pseudoprimes", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n"}
{"id": 50455, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n"}
{"id": 50456, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 50457, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 50458, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 50459, "name": "Conjugate transpose", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n"}
{"id": 50460, "name": "Conjugate transpose", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n"}
{"id": 50461, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 50462, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 50463, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n"}
{"id": 50464, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 50465, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 50466, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n"}
{"id": 50467, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 50468, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 50469, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 50470, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 50471, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 50472, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 50473, "name": "Fermat numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/jbarham/primegen\"\n    \"math\"\n    \"math/big\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst (\n    maxCurves = 10000\n    maxRnd    = 1 << 31\n    maxB1     = uint64(43 * 1e7)\n    maxB2     = uint64(2 * 1e10)\n)\n\nvar (\n    zero  = big.NewInt(0)\n    one   = big.NewInt(1)\n    two   = big.NewInt(2)\n    three = big.NewInt(3)\n    four  = big.NewInt(4)\n    five  = big.NewInt(5)\n)\n\n\nfunc pollardRho(n *big.Int) (*big.Int, error) {\n    \n    g := func(x, n *big.Int) *big.Int {\n        x2 := new(big.Int)\n        x2.Mul(x, x)\n        x2.Add(x2, one)\n        return x2.Mod(x2, n)\n    }\n    x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one)\n    t, z := new(big.Int), new(big.Int).Set(one)\n    count := 0\n    for {\n        x = g(x, n)\n        y = g(g(y, n), n)\n        t.Sub(x, y)\n        t.Abs(t)\n        t.Mod(t, n)\n        z.Mul(z, t)\n        count++\n        if count == 100 {\n            d.GCD(nil, nil, z, n)\n            if d.Cmp(one) != 0 {\n                break\n            }\n            z.Set(one)\n            count = 0\n        }\n    }\n    if d.Cmp(n) == 0 {\n        return nil, fmt.Errorf(\"Pollard's rho failure\")\n    }\n    return d, nil\n}\n\n\nfunc getPrimes(n uint64) []uint64 {\n    pg := primegen.New()\n    var primes []uint64\n    for {\n        prime := pg.Next()\n        if prime < n {\n            primes = append(primes, prime)\n        } else {\n            break\n        }\n    }\n    return primes\n}\n\n\nfunc computeBounds(n *big.Int) (uint64, uint64) {\n    le := len(n.String())\n    var b1, b2 uint64\n    switch {\n    case le <= 30:\n        b1, b2 = 2000, 147396\n    case le <= 40:\n        b1, b2 = 11000, 1873422\n    case le <= 50:\n        b1, b2 = 50000, 12746592\n    case le <= 60:\n        b1, b2 = 250000, 128992510\n    case le <= 70:\n        b1, b2 = 1000000, 1045563762\n    case le <= 80:\n        b1, b2 = 3000000, 5706890290\n    default:\n        b1, b2 = maxB1, maxB2\n    }\n    return b1, b2\n}\n\n\nfunc pointAdd(px, pz, qx, qz, rx, rz, n *big.Int) (*big.Int, *big.Int) {\n    t := new(big.Int).Sub(px, pz)\n    u := new(big.Int).Add(qx, qz)\n    u.Mul(t, u)\n    t.Add(px, pz)\n    v := new(big.Int).Sub(qx, qz)\n    v.Mul(t, v)\n    upv := new(big.Int).Add(u, v)\n    umv := new(big.Int).Sub(u, v)\n    x := new(big.Int).Mul(upv, upv)\n    x.Mul(x, rz)\n    if x.Cmp(n) >= 0 {\n        x.Mod(x, n)\n    }\n    z := new(big.Int).Mul(umv, umv)\n    z.Mul(z, rx)\n    if z.Cmp(n) >= 0 {\n        z.Mod(z, n)\n    }\n    return x, z\n}\n\n\nfunc pointDouble(px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {\n    u2 := new(big.Int).Add(px, pz)\n    u2.Mul(u2, u2)\n    v2 := new(big.Int).Sub(px, pz)\n    v2.Mul(v2, v2)\n    t := new(big.Int).Sub(u2, v2)\n    x := new(big.Int).Mul(u2, v2)\n    if x.Cmp(n) >= 0 {\n        x.Mod(x, n)\n    }\n    z := new(big.Int).Mul(a24, t)\n    z.Add(v2, z)\n    z.Mul(t, z)\n    if z.Cmp(n) >= 0 {\n        z.Mod(z, n)\n    }\n    return x, z\n}\n\n\nfunc scalarMultiply(k, px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {\n    sk := fmt.Sprintf(\"%b\", k)\n    lk := len(sk)\n    qx := new(big.Int).Set(px)\n    qz := new(big.Int).Set(pz)\n    rx, rz := pointDouble(px, pz, n, a24)\n    for i := 1; i < lk; i++ {\n        if sk[i] == '1' {\n            qx, qz = pointAdd(rx, rz, qx, qz, px, pz, n)\n            rx, rz = pointDouble(rx, rz, n, a24)\n\n        } else {\n            rx, rz = pointAdd(qx, qz, rx, rz, px, pz, n)\n            qx, qz = pointDouble(qx, qz, n, a24)\n        }\n    }\n    return qx, qz\n}\n\n\nfunc ecm(n *big.Int) (*big.Int, error) {\n    if n.Cmp(one) == 0 || n.ProbablyPrime(10) {\n        return n, nil\n    }\n    b1, b2 := computeBounds(n)\n    dd := uint64(math.Sqrt(float64(b2)))\n    beta := make([]*big.Int, dd+1)\n    for i := 0; i < len(beta); i++ {\n        beta[i] = new(big.Int)\n    }\n    s := make([]*big.Int, 2*dd+2)\n    for i := 0; i < len(s); i++ {\n        s[i] = new(big.Int)\n    }\n\n    \n    curves := 0\n    logB1 := math.Log(float64(b1))\n    primes := getPrimes(b2)\n    numPrimes := len(primes)\n    idxB1 := sort.Search(len(primes), func(i int) bool { return primes[i] >= b1 })\n\n    \n    k := big.NewInt(1)\n    for i := 0; i < idxB1; i++ {\n        p := primes[i]\n        bp := new(big.Int).SetUint64(p)\n        t := uint64(logB1 / math.Log(float64(p)))\n        bt := new(big.Int).SetUint64(t)\n        bt.Exp(bp, bt, nil)\n        k.Mul(k, bt)\n    }\n    g := big.NewInt(1)\n    for (g.Cmp(one) == 0 || g.Cmp(n) == 0) && curves <= maxCurves {\n        curves++\n        st := int64(6 + rand.Intn(maxRnd-5))\n        sigma := big.NewInt(st)\n\n        \n        u := new(big.Int).Mul(sigma, sigma)\n        u.Sub(u, five)\n        u.Mod(u, n)\n        v := new(big.Int).Mul(four, sigma)\n        v.Mod(v, n)\n        vmu := new(big.Int).Sub(v, u)\n        a := new(big.Int).Mul(vmu, vmu)\n        a.Mul(a, vmu)\n        t := new(big.Int).Mul(three, u)\n        t.Add(t, v)\n        a.Mul(a, t)\n        t.Mul(four, u)\n        t.Mul(t, u)\n        t.Mul(t, u)\n        t.Mul(t, v)\n        a.Quo(a, t)\n        a.Sub(a, two)\n        a.Mod(a, n)\n        a24 := new(big.Int).Add(a, two)\n        a24.Quo(a24, four)\n\n        \n        px := new(big.Int).Mul(u, u)\n        px.Mul(px, u)\n        t.Mul(v, v)\n        t.Mul(t, v)\n        px.Quo(px, t)\n        px.Mod(px, n)\n        pz := big.NewInt(1)\n        qx, qz := scalarMultiply(k, px, pz, n, a24)\n        g.GCD(nil, nil, n, qz)\n\n        \n        \n        if g.Cmp(one) != 0 && g.Cmp(n) != 0 {\n            return g, nil\n        }\n\n        \n        s[1], s[2] = pointDouble(qx, qz, n, a24)\n        s[3], s[4] = pointDouble(s[1], s[2], n, a24)\n        beta[1].Mul(s[1], s[2])\n        beta[1].Mod(beta[1], n)\n        beta[2].Mul(s[3], s[4])\n        beta[2].Mod(beta[2], n)\n        for d := uint64(3); d <= dd; d++ {\n            d2 := 2 * d\n            s[d2-1], s[d2] = pointAdd(s[d2-3], s[d2-2], s[1], s[2], s[d2-5], s[d2-4], n)\n            beta[d].Mul(s[d2-1], s[d2])\n            beta[d].Mod(beta[d], n)\n        }\n        g.SetUint64(1)\n        b := new(big.Int).SetUint64(b1 - 1)\n        rx, rz := scalarMultiply(b, qx, qz, n, a24)\n        t.Mul(two, new(big.Int).SetUint64(dd))\n        t.Sub(b, t)\n        tx, tz := scalarMultiply(t, qx, qz, n, a24)\n        q, step := idxB1, 2*dd\n        for r := b1 - 1; r < b2; r += step {\n            alpha := new(big.Int).Mul(rx, rz)\n            alpha.Mod(alpha, n)\n            limit := r + step\n            for q < numPrimes && primes[q] <= limit {\n                d := (primes[q] - r) / 2\n                t := new(big.Int).Sub(rx, s[2*d-1])\n                f := new(big.Int).Add(rz, s[2*d])\n                f.Mul(t, f)\n                f.Sub(f, alpha)\n                f.Add(f, beta[d])\n                g.Mul(g, f)\n                g.Mod(g, n)\n                q++\n            }\n            trx := new(big.Int).Set(rx)\n            trz := new(big.Int).Set(rz)\n            rx, rz = pointAdd(rx, rz, s[2*dd-1], s[2*dd], tx, tz, n)\n            tx.Set(trx)\n            tz.Set(trz)\n        }\n        g.GCD(nil, nil, n, g)\n    }\n\n    \n    if curves > maxCurves {\n        return zero, fmt.Errorf(\"maximum curves exceeded before a factor was found\")\n    }\n    return g, nil\n}\n\n\nfunc primeFactors(n *big.Int) ([]*big.Int, error) {\n    var res []*big.Int\n    if n.ProbablyPrime(10) {\n        return append(res, n), nil\n    }\n    le := len(n.String())\n    var factor1 *big.Int\n    var err error\n    if le > 20 && le <= 60 {\n        factor1, err = ecm(n)\n    } else {\n        factor1, err = pollardRho(n)\n    }\n    if err != nil {\n        return nil, err\n    }\n    if !factor1.ProbablyPrime(10) {\n        return nil, fmt.Errorf(\"first factor is not prime\")\n    }\n    factor2 := new(big.Int)\n    factor2.Quo(n, factor1)\n    if !factor2.ProbablyPrime(10) {\n        return nil, fmt.Errorf(\"%d (second factor is not prime)\", factor1)\n    }\n    return append(res, factor1, factor2), nil\n}\n\nfunc fermatNumbers(n int) (res []*big.Int) {\n    f := new(big.Int).SetUint64(3) \n    for i := 0; i < n; i++ {\n        t := new(big.Int).Set(f)\n        res = append(res, t)\n        f.Sub(f, one)\n        f.Mul(f, f)\n        f.Add(f, one)\n    }\n    return res\n}\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n    fns := fermatNumbers(10)\n    fmt.Println(\"First 10 Fermat numbers:\")\n    for i, f := range fns {\n        fmt.Printf(\"F%c = %d\\n\", 0x2080+i, f)\n    }\n\n    fmt.Println(\"\\nFactors of first 10 Fermat numbers:\")\n    for i, f := range fns {\n        fmt.Printf(\"F%c = \", 0x2080+i)\n        factors, err := primeFactors(f)\n        if err != nil {\n            fmt.Println(err)\n            continue\n        }\n        for _, factor := range factors {\n            fmt.Printf(\"%d \", factor)\n        }\n        if len(factors) == 1 {\n            fmt.Println(\"- prime\")\n        } else {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nTook %s\\n\", time.Since(start))\n}\n", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n"}
{"id": 50474, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 50475, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 50476, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 50477, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n"}
{"id": 50478, "name": "Descending primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n"}
{"id": 50479, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"}
{"id": 50480, "name": "Jaro similarity", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50481, "name": "Sum and product puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n"}
{"id": 50482, "name": "Fairshare between two and more", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n"}
{"id": 50483, "name": "Two bullet roulette", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n    t := cylinder[5]\n    for i := 4; i >= 0; i-- {\n        cylinder[i+1] = cylinder[i]\n    }\n    cylinder[0] = t\n}\n\nfunc unload() {\n    for i := 0; i < 6; i++ {\n        cylinder[i] = false\n    }\n}\n\nfunc load() {\n    for cylinder[0] {\n        rshift()\n    }\n    cylinder[0] = true\n    rshift()\n}\n\nfunc spin() {\n    var lim = 1 + rand.Intn(6)\n    for i := 1; i < lim; i++ {\n        rshift()\n    }\n}\n\nfunc fire() bool {\n    shot := cylinder[0]\n    rshift()\n    return shot\n}\n\nfunc method(s string) int {\n    unload()\n    for _, c := range s {\n        switch c {\n        case 'L':\n            load()\n        case 'S':\n            spin()\n        case 'F':\n            if fire() {\n                return 1\n            }\n        }\n    }\n    return 0\n}\n\nfunc mstring(s string) string {\n    var l []string\n    for _, c := range s {\n        switch c {\n        case 'L':\n            l = append(l, \"load\")\n        case 'S':\n            l = append(l, \"spin\")\n        case 'F':\n            l = append(l, \"fire\")\n        }\n    }\n    return strings.Join(l, \", \")\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := 100000\n    for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n        sum := 0\n        for t := 1; t <= tests; t++ {\n            sum += method(m)\n        }\n        pc := float64(sum) * 100 / float64(tests)\n        fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n    }\n}\n", "Python": "\nimport numpy as np\n\nclass Revolver:\n    \n\n    def __init__(self):\n        \n        self.cylinder = np.array([False] * 6)\n\n    def unload(self):\n        \n        self.cylinder[:] = False\n\n    def load(self):\n        \n        while self.cylinder[1]:\n            self.cylinder[:] = np.roll(self.cylinder, 1)\n        self.cylinder[1] = True\n\n    def spin(self):\n        \n        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n    def fire(self):\n        \n        shot = self.cylinder[0]\n        self.cylinder[:] = np.roll(self.cylinder, 1)\n        return shot\n\n    def LSLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LSLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n    def LLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n\nif __name__ == '__main__':\n\n    REV = Revolver()\n    TESTCOUNT = 100000\n    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n                           ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n        print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\n"}
{"id": 50484, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 50485, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 50486, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 50487, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 50488, "name": "Sequence_ nth number with exactly n divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 50489, "name": "Sequence_ smallest number with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 50490, "name": "Pancake numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n"}
{"id": 50491, "name": "Generate random chess position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n"}
{"id": 50492, "name": "Esthetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n"}
{"id": 50493, "name": "Topswops", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n"}
{"id": 50494, "name": "Old Russian measure of length", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n"}
{"id": 50495, "name": "Rate counter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n"}
{"id": 50496, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n"}
{"id": 50497, "name": "Padovan sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n", "Python": "from math import floor\nfrom collections import deque\nfrom typing import Dict, Generator\n\n\ndef padovan_r() -> Generator[int, None, None]:\n    last = deque([1, 1, 1], 4)\n    while True:\n        last.append(last[-2] + last[-3])\n        yield last.popleft()\n\n_p, _s = 1.324717957244746025960908854, 1.0453567932525329623\n\ndef padovan_f(n: int) -> int:\n    return floor(_p**(n-1) / _s + .5)\n\ndef padovan_l(start: str='A',\n             rules: Dict[str, str]=dict(A='B', B='C', C='AB')\n             ) -> Generator[str, None, None]:\n    axiom = start\n    while True:\n        yield axiom\n        axiom = ''.join(rules[ch] for ch in axiom)\n\n\nif __name__ == \"__main__\":\n    from itertools import islice\n\n    print(\"The first twenty terms of the sequence.\")\n    print(str([padovan_f(n) for n in range(20)])[1:-1])\n\n    r_generator = padovan_r()\n    if all(next(r_generator) == padovan_f(n) for n in range(64)):\n        print(\"\\nThe recurrence and floor based algorithms match to n=63 .\")\n    else:\n        print(\"\\nThe recurrence and floor based algorithms DIFFER!\")\n\n    print(\"\\nThe first 10 L-system string-lengths and strings\")\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    print('\\n'.join(f\"  {len(string):3} {repr(string)}\"\n                    for string in islice(l_generator, 10)))\n\n    r_generator = padovan_r()\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)\n           for n in range(32)):\n        print(\"\\nThe L-system, recurrence and floor based algorithms match to n=31 .\")\n    else:\n        print(\"\\nThe L-system, recurrence and floor based algorithms DIFFER!\")\n"}
{"id": 50498, "name": "Pythagoras tree", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n"}
{"id": 50499, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 50500, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 50501, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 50502, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"}
{"id": 50503, "name": "Biorhythms", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"}
{"id": 50504, "name": "Biorhythms", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"}
{"id": 50505, "name": "Table creation_Postal addresses", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n"}
{"id": 50506, "name": "Sine wave", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os/exec\"\n)\n\nfunc main() {\n    synthType := \"sine\"\n    duration := \"5\"\n    frequency := \"440\"\n    cmd := exec.Command(\"play\", \"-n\", \"synth\", duration, synthType, frequency)\n    err := cmd.Run()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "\n\nimport os\nfrom math import pi, sin\n\n\nau_header = bytearray(\n            [46, 115, 110, 100,   \n              0,   0,   0,  24,   \n            255, 255, 255, 255,   \n              0,   0,   0,   3,   \n              0,   0, 172,  68,   \n              0,   0,   0,   1])  \n\ndef f(x, freq):\n    \"Compute sine wave as 16-bit integer\"\n    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536\n\ndef play_sine(freq=440, duration=5, oname=\"pysine.au\"):\n    \"Play a sine wave for `duration` seconds\"\n    out = open(oname, 'wb')\n    out.write(au_header)\n    v = [f(x, freq) for x in range(duration * 44100 + 1)]\n    s = []\n    for i in v:\n        s.append(i >> 8)\n        s.append(i % 256)\n    out.write(bytearray(s))\n    out.close()\n    os.system(\"vlc \" + oname)   \n\nplay_sine()\n"}
{"id": 50507, "name": "Compiler_code generator", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 50508, "name": "Compiler_code generator", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 50509, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "Python": "import one \n\n\n\n"}
{"id": 50510, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "Python": "import one \n\n\n\n"}
{"id": 50511, "name": "Stern-Brocot sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 50512, "name": "Numeric error propagation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n"}
{"id": 50513, "name": "Soundex", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 50514, "name": "List rooted trees", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n"}
{"id": 50515, "name": "Documentation", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n"}
{"id": 50516, "name": "Table creation", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n"}
{"id": 50517, "name": "Table creation", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n"}
{"id": 50518, "name": "Problem of Apollonius", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n"}
{"id": 50519, "name": "Append numbers at same position in strings", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n"}
{"id": 50520, "name": "Append numbers at same position in strings", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n"}
{"id": 50521, "name": "Longest common suffix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50522, "name": "Chat server", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n"}
{"id": 50523, "name": "Idiomatically determine all the lowercase and uppercase letters", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n"}
{"id": 50524, "name": "Sum of elements below main diagonal of matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n"}
{"id": 50525, "name": "Retrieve and search chat history", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc get(url string) (res string, err error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n\nfunc grep(needle string, haystack string) (res []string) {\n\tfor _, line := range strings.Split(haystack, \"\\n\") {\n\t\tif strings.Contains(line, needle) {\n\t\t\tres = append(res, line)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc genUrl(i int, loc *time.Location) string {\n\tdate := time.Now().In(loc).AddDate(0, 0, i)\n\treturn date.Format(\"http:\n}\n\nfunc main() {\n\tneedle := os.Args[1]\n\tback := -10\n\tserverLoc, err := time.LoadLocation(\"Europe/Berlin\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor i := back; i <= 0; i++ {\n\t\turl := genUrl(i, serverLoc)\n\t\tcontents, err := get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfound := grep(needle, contents)\n\t\tif len(found) > 0 {\n\t\t\tfmt.Printf(\"%v\\n------\\n\", url)\n\t\t\tfor _, line := range found {\n\t\t\t\tfmt.Printf(\"%v\\n\", line)\n\t\t\t}\n\t\t\tfmt.Printf(\"------\\n\\n\")\n\t\t}\n\t}\n}\n", "Python": "\nimport datetime\nimport re\nimport urllib.request\nimport sys\n\ndef get(url):\n    with urllib.request.urlopen(url) as response:\n       html = response.read().decode('utf-8')\n    if re.match(r'<!Doctype HTML[\\s\\S]*<Title>URL Not Found</Title>', html):\n        return None\n    return html\n\ndef main():\n    template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'\n    today = datetime.datetime.utcnow()\n    back = 10\n    needle = sys.argv[1]\n    \n    \n    \n    for i in range(-back, 2):\n        day = today + datetime.timedelta(days=i)\n        url = day.strftime(template)\n        haystack = get(url)\n        if haystack:\n            mentions = [x for x in haystack.split('\\n') if needle in x]\n            if mentions:\n                print('{}\\n------\\n{}\\n------\\n'\n                          .format(url, '\\n'.join(mentions)))\n\nmain()\n"}
{"id": 50526, "name": "Rosetta Code_Rank languages by number of users", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n"}
{"id": 50527, "name": "Rosetta Code_Rank languages by number of users", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n"}
{"id": 50528, "name": "Multiline shebang", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n", "Python": "\n\"exec\" \"python\" \"$0\"\n\nprint \"Hello World\"\n"}
{"id": 50529, "name": "Multiline shebang", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n", "Python": "\n\"exec\" \"python\" \"$0\"\n\nprint \"Hello World\"\n"}
{"id": 50530, "name": "Terminal control_Unicode output", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n"}
{"id": 50531, "name": "Terminal control_Unicode output", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n"}
{"id": 50532, "name": "Find adjacent primes which differ by a square integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n"}
{"id": 50533, "name": "Find adjacent primes which differ by a square integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n"}
{"id": 50534, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 50535, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 50536, "name": "Video display modes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n"}
{"id": 50537, "name": "Video display modes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n"}
{"id": 50538, "name": "Keyboard input_Flush the keyboard buffer", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    _, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    gc.FlushInput()\n}\n", "Python": "def flush_input():\n    try:\n        import msvcrt\n        while msvcrt.kbhit():\n            msvcrt.getch()\n    except ImportError:\n        import sys, termios\n        termios.tcflush(sys.stdin, termios.TCIOFLUSH)\n"}
{"id": 50539, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 50540, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 50541, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n"}
{"id": 50542, "name": "FASTA format", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n"}
{"id": 50543, "name": "Cousin 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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50544, "name": "Cousin 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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50545, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 50546, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 50547, "name": "Check input device is a terminal", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n"}
{"id": 50548, "name": "Check input device is a terminal", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n"}
{"id": 50549, "name": "Window creation_X11", "Go": "package main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"github.com/jezek/xgb\"\n    \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n    \n    X, err := xgb.NewConn()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    points := []xproto.Point{\n        {10, 10},\n        {10, 20},\n        {20, 10},\n        {20, 20}};\n\n    polyline := []xproto.Point{\n        {50, 10},\n        { 5, 20},     \n        {25,-20},\n        {10, 10}};\n\n    segments := []xproto.Segment{\n        {100, 10, 140, 30},\n        {110, 25, 130, 60}};\n\n    rectangles := []xproto.Rectangle{\n        { 10, 50, 40, 20},\n        { 80, 50, 10, 40}};\n\n    arcs := []xproto.Arc{\n        {10, 100, 60, 40, 0, 90 << 6},\n        {90, 100, 55, 40, 0, 270 << 6}};\n\n    setup := xproto.Setup(X)\n    \n    screen := setup.DefaultScreen(X)\n\n    \n    foreground, _ := xproto.NewGcontextId(X)\n    mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n    values := []uint32{screen.BlackPixel, 0}\n    xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n    \n    win, _ := xproto.NewWindowId(X)\n    winDrawable := xproto.Drawable(win)\n\n    \n    mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n    values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n    xproto.CreateWindow(X,                  \n            screen.RootDepth,               \n            win,                            \n            screen.Root,                    \n            0, 0,                           \n            150, 150,                       \n            10,                             \n            xproto.WindowClassInputOutput,  \n            screen.RootVisual,              \n            mask, values)                   \n\n    \n    xproto.MapWindow(X, win)\n\n    for {\n        evt, err := X.WaitForEvent()\n        switch evt.(type) {\n            case xproto.ExposeEvent:\n                \n                xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n                \n                xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n                \n                xproto.PolySegment(X, winDrawable, foreground, segments)\n\n                \n                xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n                \n                xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n            default:\n                \n        }\n\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    return\n}\n", "Python": "from Xlib import X, display\n\nclass Window:\n    def __init__(self, display, msg):\n        self.display = display\n        self.msg = msg\n        \n        self.screen = self.display.screen()\n        self.window = self.screen.root.create_window(\n            10, 10, 100, 100, 1,\n            self.screen.root_depth,\n            background_pixel=self.screen.white_pixel,\n            event_mask=X.ExposureMask | X.KeyPressMask,\n            )\n        self.gc = self.window.create_gc(\n            foreground = self.screen.black_pixel,\n            background = self.screen.white_pixel,\n            )\n\n        self.window.map()\n\n    def loop(self):\n        while True:\n            e = self.display.next_event()\n                \n            if e.type == X.Expose:\n                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n                self.window.draw_text(self.gc, 10, 50, self.msg)\n            elif e.type == X.KeyPress:\n                raise SystemExit\n\n                \nif __name__ == \"__main__\":\n    Window(display.Display(), \"Hello, World!\").loop()\n"}
{"id": 50550, "name": "Elementary cellular automaton_Random number generator", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n", "Python": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n    cells = '1' + '0' * (lencells - 1)\n    gen = eca(cells, 30)\n    while True:\n        yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n    print([b for i,b in zip(range(10), rule30bytes())])\n"}
{"id": 50551, "name": "Terminal control_Dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n"}
{"id": 50552, "name": "Finite state machine", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n"}
{"id": 50553, "name": "Vibrating rectangles", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n"}
{"id": 50554, "name": "Vibrating rectangles", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n"}
{"id": 50555, "name": "Last list item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}\n    for len(a) > 1 {\n        sort.Ints(a)\n        fmt.Println(\"Sorted list:\", a)\n        sum := a[0] + a[1]\n        fmt.Printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum)\n        a = append(a, sum)\n        a = a[2:]\n    }\n    fmt.Println(\"Last item is\", a[0], \"\\b.\")\n}\n", "Python": "\n\ndef add_least_reduce(lis):\n    \n    while len(lis) > 1:\n        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))\n        print('Interim list:', lis)\n    return lis\n\nLIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]\n\nprint(LIST, ' ==> ', add_least_reduce(LIST.copy()))\n"}
{"id": 50556, "name": "Minimum numbers of three lists", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 98, 53}\n    numbers := [5]int{}\n    for n := 0; n < 5; n++ {\n        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])\n    }\n    fmt.Println(numbers)\n}\n", "Python": "numbers1 = [5,45,23,21,67]\nnumbers2 = [43,22,78,46,38]\nnumbers3 = [9,98,12,98,53]\n\nnumbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]\n\nprint(numbers)\n"}
{"id": 50557, "name": "Minimum numbers of three lists", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 98, 53}\n    numbers := [5]int{}\n    for n := 0; n < 5; n++ {\n        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])\n    }\n    fmt.Println(numbers)\n}\n", "Python": "numbers1 = [5,45,23,21,67]\nnumbers2 = [43,22,78,46,38]\nnumbers3 = [9,98,12,98,53]\n\nnumbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]\n\nprint(numbers)\n"}
{"id": 50558, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 50559, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 50560, "name": "Pseudo-random numbers_PCG32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 50561, "name": "Deconvolution_1D", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    h := []float64{-8, -9, -3, -1, -6, 7}\n    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n        96, 31, 55, 36, 29, -43, -7}\n    fmt.Println(h)\n    fmt.Println(deconv(g, f))\n    fmt.Println(f)\n    fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n    h := make([]float64, len(g)-len(f)+1)\n    for n := range h {\n        h[n] = g[n]\n        var lower int\n        if n >= len(f) {\n            lower = n - len(f) + 1\n        }\n        for i := lower; i < n; i++ {\n            h[n] -= h[i] * f[n-i]\n        }\n        h[n] /= f[0]\n    }\n    return h\n}\n", "Python": "def ToReducedRowEchelonForm( M ):\n    if not M: return\n    lead = 0\n    rowCount = len(M)\n    columnCount = len(M[0])\n    for r in range(rowCount):\n        if lead >= columnCount:\n            return\n        i = r\n        while M[i][lead] == 0:\n            i += 1\n            if i == rowCount:\n                i = r\n                lead += 1\n                if columnCount == lead:\n                    return\n        M[i],M[r] = M[r],M[i]\n        lv = M[r][lead]\n        M[r] = [ mrx / lv for mrx in M[r]]\n        for i in range(rowCount):\n            if i != r:\n                lv = M[i][lead]\n                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n        lead += 1\n    return M\n \ndef pmtx(mtx):\n    print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n \ndef convolve(f, h):\n    g = [0] * (len(f) + len(h) - 1)\n    for hindex, hval in enumerate(h):\n        for findex, fval in enumerate(f):\n            g[hindex + findex] += fval * hval\n    return g\n\ndef deconvolve(g, f):\n    lenh = len(g) - len(f) + 1\n    mtx = [[0 for x in range(lenh+1)] for y in g]\n    for hindex in range(lenh):\n        for findex, fval in enumerate(f):\n            gindex = hindex + findex\n            mtx[gindex][hindex] = fval\n    for gindex, gval in enumerate(g):        \n        mtx[gindex][lenh] = gval\n    ToReducedRowEchelonForm( mtx )\n    return [mtx[i][lenh] for i in range(lenh)]  \n\nif __name__ == '__main__':\n    h = [-8,-9,-3,-1,-6,7]\n    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n    assert convolve(f,h) == g\n    assert deconvolve(g, f) == h\n"}
{"id": 50562, "name": "Bitmap_PPM conversion through a pipe", "Go": "package main\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    b := raster.NewBitmap(400, 300)\n    \n    b.FillRgb(0xc08040)\n    for i := 0; i < 2000; i++ {\n        b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)\n    }\n    for x := 0; x < 400; x++ {\n        for y := 240; y < 245; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for y := 260; y < 265; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n    for y := 0; y < 300; y++ {\n        for x := 80; x < 85; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for x := 95; x < 100; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n\n    \n    c := exec.Command(\"cjpeg\", \"-outfile\", \"pipeout.jpg\")\n    pipe, err := c.StdinPipe()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = c.Start()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = b.WritePpmTo(pipe)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = pipe.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "\n\nfrom PIL import Image\n\nim = Image.open(\"boxes_1.ppm\")\nim.save(\"boxes_1.jpg\")\n"}
{"id": 50563, "name": "Bitcoin_public point to address", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n"}
{"id": 50564, "name": "Bitcoin_public point to address", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n"}
{"id": 50565, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 50566, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n"}
{"id": 50567, "name": "Disarium numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n"}
{"id": 50568, "name": "Disarium numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n"}
{"id": 50569, "name": "Sierpinski pentagon", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n"}
{"id": 50570, "name": "Bitmap_Histogram", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 50571, "name": "Bitmap_Histogram", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 50572, "name": "Padovan n-step number sequences", "Go": "package main\n\nimport \"fmt\"\n\nfunc padovanN(n, t int) []int {\n    if n < 2 || t < 3 {\n        ones := make([]int, t)\n        for i := 0; i < t; i++ {\n            ones[i] = 1\n        }\n        return ones\n    }\n    p := padovanN(n-1, t)\n    for i := n + 1; i < t; i++ {\n        p[i] = 0\n        for j := i - 2; j >= i-n-1; j-- {\n            p[i] += p[j]\n        }\n    }\n    return p\n}\n\nfunc main() {\n    t := 15\n    fmt.Println(\"First\", t, \"terms of the Padovan n-step number sequences:\")\n    for n := 2; n <= 8; n++ {\n        fmt.Printf(\"%d: %3d\\n\", n, padovanN(n, t))\n    }\n}\n", "Python": "def pad_like(max_n=8, t=15):\n    \n    start = [[], [1, 1, 1]]     \n    for n in range(2, max_n+1):\n        this = start[n-1][:n+1]     \n        while len(this) < t:\n            this.append(sum(this[i] for i in range(-2, -n - 2, -1)))\n        start.append(this)\n    return start[2:]\n\ndef pr(p):\n    print(.strip())\n    for n, seq in enumerate(p, 2):\n        print(f\"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\\n|-\")\n    print('|}')\n\nif __name__ == '__main__':\n    p = pad_like()\n    pr(p)\n"}
{"id": 50573, "name": "Mutex", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n"}
{"id": 50574, "name": "Mutex", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n"}
{"id": 50575, "name": "Metronome", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 \n\tvar bpb = 4    \n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}\n", "Python": "\nimport time\n\ndef main(bpm = 72, bpb = 4):\n    sleep = 60.0 / bpm\n    counter = 0\n    while True:\n        counter += 1\n        if counter % bpb:\n            print 'tick'\n        else:\n            print 'TICK'\n        time.sleep(sleep)\n        \n\n\nmain()\n"}
{"id": 50576, "name": "Native shebang", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n"}
{"id": 50577, "name": "Native shebang", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n"}
{"id": 50578, "name": "EKG sequence convergence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n    for _, j := range a {\n        if j == b {\n            return true\n        }\n    }\n    return false\n}\n\nfunc gcd(a, b int) int {\n    for a != b {\n        if a > b {\n            a -= b\n        } else {\n            b -= a\n        }\n    }\n    return a\n}\n\nfunc areSame(s, t []int) bool {\n    le := len(s)\n    if le != len(t) {\n        return false\n    }\n    sort.Ints(s)\n    sort.Ints(t)\n    for i := 0; i < le; i++ {\n        if s[i] != t[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100\n    starts := [5]int{2, 5, 7, 9, 10}\n    var ekg [5][limit]int\n\n    for s, start := range starts {\n        ekg[s][0] = 1\n        ekg[s][1] = start\n        for n := 2; n < limit; n++ {\n            for i := 2; ; i++ {\n                \n                \n                if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n                    ekg[s][n] = i\n                    break\n                }\n            }\n        }\n        fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n    }   \n\n    \n    for i := 2; i < limit; i++ {\n        if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n            fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n            return\n        }\n    }\n    fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}\n", "Python": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n    \n    c = count(start + 1)\n    last, so_far = start, list(range(2, start))\n    yield 1, []\n    yield last, []\n    while True:\n        for index, sf in enumerate(so_far):\n            if gcd(last, sf) > 1:\n                last = so_far.pop(index)\n                yield last, so_far[::]\n                break\n        else:\n            so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n    \"Returns the convergence point or zero if not found within the limit\"\n    ekg = [EKG_gen(n) for n in ekgs]\n    for e in ekg:\n        next(e)    \n    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),\n                                  zip(*ekg))))\n\nif __name__ == '__main__':\n    for start in 2, 5, 7, 9, 10:\n        print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n    print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")\n"}
{"id": 50579, "name": "Rep-string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n"}
{"id": 50580, "name": "Terminal control_Preserve screen", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"\\033[?1049h\\033[H\")\n    fmt.Println(\"Alternate screen buffer\\n\")\n    s := \"s\"\n    for i := 5; i > 0; i-- {\n        if i == 1 {\n            s = \"\"\n        }\n        fmt.Printf(\"\\rgoing back in %d second%s...\", i, s)\n        time.Sleep(time.Second)\n    }\n    fmt.Print(\"\\033[?1049l\")\n}\n", "Python": "\n\nimport time\n\nprint \"\\033[?1049h\\033[H\"\nprint \"Alternate buffer!\"\n\nfor i in xrange(5, 0, -1):\n    print \"Going back in:\", i\n    time.sleep(1)\n\nprint \"\\033[?1049l\"\n"}
{"id": 50581, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 50582, "name": "Changeable words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n"}
{"id": 50583, "name": "Window management", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n"}
{"id": 50584, "name": "Window management", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n"}
{"id": 50585, "name": "Monads_List monad", "Go": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n    return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n    return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = v + 1\n    }\n    return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = 2 * v\n    }\n    return unit(lst2)\n}\n\nfunc main() {\n    ml1 := unit([]int{3, 4, 5})\n    ml2 := ml1.bind(increment).bind(double)\n    fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}\n", "Python": "\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n    @classmethod\n    def unit(cls, value: Iterable[T]) -> MList[T]:\n        return cls(value)\n\n    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return MList(chain.from_iterable(map(func, self)))\n\n    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return self.bind(func)\n\n\nif __name__ == \"__main__\":\n    \n    print(\n        MList([1, 99, 4])\n        .bind(lambda val: MList([val + 1]))\n        .bind(lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList([1, 99, 4])\n        >> (lambda val: MList([val + 1]))\n        >> (lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList(range(1, 6)).bind(\n            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n        )\n    )\n\n    \n    print(\n        MList(range(1, 26)).bind(\n            lambda x: MList(range(x + 1, 26)).bind(\n                lambda y: MList(range(y + 1, 26)).bind(\n                    lambda z: MList([(x, y, z)])\n                    if x * x + y * y == z * z\n                    else MList([])\n                )\n            )\n        )\n    )\n"}
{"id": 50586, "name": "Find squares n where n+1 is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n"}
{"id": 50587, "name": "Find squares n where n+1 is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n"}
{"id": 50588, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n"}
{"id": 50589, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n"}
{"id": 50590, "name": "Mayan numerals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst (\n    ul = \"╔\"\n    uc = \"╦\"\n    ur = \"╗\"\n    ll = \"╚\"\n    lc = \"╩\"\n    lr = \"╝\"\n    hb = \"═\"\n    vb = \"║\"\n)\n\nvar mayan = [5]string{\n    \"    \",\n    \" ∙  \",\n    \" ∙∙ \",\n    \"∙∙∙ \",\n    \"∙∙∙∙\",\n}\n\nconst (\n    m0 = \" Θ  \"\n    m5 = \"────\"\n)\n\nfunc dec2vig(n uint64) []uint64 {\n    vig := strconv.FormatUint(n, 20)\n    res := make([]uint64, len(vig))\n    for i, d := range vig {\n        res[i], _ = strconv.ParseUint(string(d), 20, 64)\n    }\n    return res\n}\n\nfunc vig2quin(n uint64) [4]string {\n    if n >= 20 {\n        panic(\"Cant't convert a number >= 20\")\n    }\n    res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}\n    if n == 0 {\n        res[3] = m0\n        return res\n    }\n    fives := n / 5\n    rem := n % 5\n    res[3-fives] = mayan[rem]\n    for i := 3; i > 3-int(fives); i-- {\n        res[i] = m5\n    }\n    return res\n}\n\nfunc draw(mayans [][4]string) {\n    lm := len(mayans)\n    fmt.Print(ul)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(uc)\n        } else {\n            fmt.Println(ur)\n        }\n    }\n    for i := 1; i < 5; i++ {\n        fmt.Print(vb)\n        for j := 0; j < lm; j++ {\n            fmt.Print(mayans[j][i-1])\n            fmt.Print(vb)\n        }\n        fmt.Println()\n    }\n    fmt.Print(ll)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(lc)\n        } else {\n            fmt.Println(lr)\n        }\n    }\n}\n\nfunc main() {\n    numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}\n    for _, n := range numbers {\n        fmt.Printf(\"Converting %d to Mayan:\\n\", n)\n        vigs := dec2vig(n)\n        lv := len(vigs)\n        mayans := make([][4]string, lv)\n        for i, vig := range vigs {\n            mayans[i] = vig2quin(vig)\n        }\n        draw(mayans)\n        fmt.Println()\n    }\n}\n", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50591, "name": "Special factorials", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc sf(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    sfact := big.NewInt(1)\n    fact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        sfact.Mul(sfact, fact)\n    }\n    return sfact\n}\n\nfunc H(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    hfact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        bi := big.NewInt(int64(i))\n        hfact.Mul(hfact, bi.Exp(bi, bi, nil))\n    }\n    return hfact\n}\n\nfunc af(n int) *big.Int {\n    if n < 1 {\n        return new(big.Int)\n    }\n    afact := new(big.Int)\n    fact := big.NewInt(1)\n    sign := new(big.Int)\n    if n%2 == 0 {\n        sign.SetInt64(-1)\n    } else {\n        sign.SetInt64(1)\n    }\n    t := new(big.Int)\n    for i := 1; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        afact.Add(afact, t.Mul(fact, sign))\n        sign.Neg(sign)\n    }\n    return afact\n}\n\nfunc ef(n int) *big.Int {\n    if n < 1 {\n        return big.NewInt(1)\n    }\n    t := big.NewInt(int64(n))\n    return t.Exp(t, ef(n-1), nil)\n}\n\nfunc rf(n *big.Int) int {\n    i := 0\n    fact := big.NewInt(1)\n    for {\n        if fact.Cmp(n) == 0 {\n            return i\n        }\n        if fact.Cmp(n) > 0 {\n            return -1\n        }\n        i++\n        fact.Mul(fact, big.NewInt(int64(i)))\n    }\n}\n\nfunc main() {\n    fmt.Println(\"First 10 superfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sf(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 hyperfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(H(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 alternating factorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Print(af(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 exponential factorials:\")\n    for i := 0; i <= 4; i++ {\n        fmt.Print(ef(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nThe number of digits in 5$ is\", len(ef(5).String()))\n\n    fmt.Println(\"\\nReverse factorials:\")\n    facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}\n    for _, fact := range facts {\n        bfact := big.NewInt(fact)\n        rfact := rf(bfact)\n        srfact := fmt.Sprintf(\"%d\", rfact)\n        if rfact == -1 {\n            srfact = \"none\"\n        }\n        fmt.Printf(\"%4s <- rf(%d)\\n\", srfact, fact)\n    }\n}\n", "Python": "\n\nfrom math import prod\n\ndef superFactorial(n):\n    return prod([prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef hyperFactorial(n):\n    return prod([i**i for i in range(1,n+1)])\n\ndef alternatingFactorial(n):\n    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef exponentialFactorial(n):\n    if n in [0,1]:\n        return 1\n    else:\n        return n**exponentialFactorial(n-1)\n        \ndef inverseFactorial(n):\n    i = 1\n    while True:\n        if n == prod(range(1,i)):\n            return i-1\n        elif n < prod(range(1,i)):\n            return \"undefined\"\n        i+=1\n\nprint(\"Superfactorials for [0,9] :\")\nprint({\"sf(\" + str(i) + \") \" : superFactorial(i) for i in range(0,10)})\n\nprint(\"\\nHyperfactorials for [0,9] :\")\nprint({\"H(\" + str(i) + \") \"  : hyperFactorial(i) for i in range(0,10)})\n\nprint(\"\\nAlternating factorials for [0,9] :\")\nprint({\"af(\" + str(i) + \") \" : alternatingFactorial(i) for i in range(0,10)})\n\nprint(\"\\nExponential factorials for [0,4] :\")\nprint({str(i) + \"$ \" : exponentialFactorial(i) for i in range(0,5)})\n\nprint(\"\\nDigits in 5$ : \" , len(str(exponentialFactorial(5))))\n\nfactorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n\nprint(\"\\nInverse factorials for \" , factorialSet)\nprint({\"rf(\" + str(i) + \") \":inverseFactorial(i) for i in factorialSet})\n\nprint(\"\\nrf(119) : \" + inverseFactorial(119))\n"}
{"id": 50592, "name": "Special neighbor primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n"}
{"id": 50593, "name": "Special neighbor primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n"}
{"id": 50594, "name": "Ramsey's theorem", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n", "Python": "range17 = range(17)\na = [['0'] * 17 for i in range17]\nidx = [0] * 4\n\n\ndef find_group(mark, min_n, max_n, depth=1):\n    if (depth == 4):\n        prefix = \"\" if (mark == '1') else \"un\"\n        print(\"Fail, found totally {}connected group:\".format(prefix))\n        for i in range(4):\n            print(idx[i])\n        return True\n\n    for i in range(min_n, max_n):\n        n = 0\n        while (n < depth):\n            if (a[idx[n]][i] != mark):\n                break\n            n += 1\n\n        if (n == depth):\n            idx[n] = i\n            if (find_group(mark, 1, max_n, depth + 1)):\n                return True\n\n    return False\n\n\nif __name__ == '__main__':\n    for i in range17:\n        a[i][i] = '-'\n    for k in range(4):\n        for i in range17:\n            j = (i + pow(2, k)) % 17\n            a[i][j] = a[j][i] = '1'\n\n    \n    \n\n    for row in a:\n        print(' '.join(row))\n\n    for i in range17:\n        idx[0] = i\n        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):\n            print(\"no good\")\n            exit()\n\n    print(\"all good\")\n"}
{"id": 50595, "name": "GUI_Maximum window dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n"}
{"id": 50596, "name": "Terminal control_Inverse video", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    tput(\"rev\")\n    fmt.Print(\"Rosetta\")\n    tput(\"sgr0\")\n    fmt.Println(\" Code\")\n}\n\nfunc tput(arg string) error {\n    cmd := exec.Command(\"tput\", arg)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n", "Python": "\n\nprint \"\\033[7mReversed\\033[m Normal\"\n"}
{"id": 50597, "name": "Four is magic", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n"}
{"id": 50598, "name": "Getting the number of decimals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n"}
{"id": 50599, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 50600, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 50601, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 50602, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n"}
{"id": 50603, "name": "Minimum number of cells after, before, above and below NxN squares", "Go": "package main\n\nimport \"fmt\"\n\nfunc printMinCells(n int) {\n    fmt.Printf(\"Minimum number of cells after, before, above and below %d x %d square:\\n\", n, n)\n    p := 1\n    if n > 20 {\n        p = 2\n    }\n    for r := 0; r < n; r++ {\n        cells := make([]int, n)\n        for c := 0; c < n; c++ {\n            nums := []int{n - r - 1, r, c, n - c - 1}\n            min := n\n            for _, num := range nums {\n                if num < min {\n                    min = num\n                }\n            }\n            cells[c] = min\n        }\n        fmt.Printf(\"%*d \\n\", p, cells)\n    }\n}\n\nfunc main() {\n    for _, n := range []int{23, 10, 9, 2, 1} {\n        printMinCells(n)\n        fmt.Println()\n    }\n}\n", "Python": "def min_cells_matrix(siz):\n    return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]\n\ndef display_matrix(mat):\n    siz = len(mat)\n    spaces = 2 if siz < 20 else 3 if siz < 200 else 4\n    print(f\"\\nMinimum number of cells after, before, above and below {siz} x {siz} square:\")\n    for row in range(siz):\n        print(\"\".join([f\"{n:{spaces}}\" for n in mat[row]]))\n\ndef test_min_mat():\n    for siz in [23, 10, 9, 2, 1]:\n        display_matrix(min_cells_matrix(siz))\n\nif __name__ == \"__main__\":\n    test_min_mat()\n"}
{"id": 50604, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 50605, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 50606, "name": "Parse an IP Address", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n"}
{"id": 50607, "name": "Matrix digital rain", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n"}
{"id": 50608, "name": "Matrix digital rain", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n"}
{"id": 50609, "name": "Mind boggling card trick", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n"}
{"id": 50610, "name": "Mind boggling card trick", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n"}
{"id": 50611, "name": "Textonyms", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n"}
{"id": 50612, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 50613, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 50614, "name": "Teacup rim text", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50615, "name": "Increasing gaps between consecutive Niven numbers", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n"}
{"id": 50616, "name": "Print debugging statement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n"}
{"id": 50617, "name": "Find prime n such that reversed n is also prime", "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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n"}
{"id": 50618, "name": "Find prime n such that reversed n is also prime", "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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n"}
{"id": 50619, "name": "Find prime n such that reversed n is also prime", "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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n"}
{"id": 50620, "name": "Superellipse", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n"}
{"id": 50621, "name": "Permutations_Rank of a permutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n"}
{"id": 50622, "name": "Permutations_Rank of a permutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n"}
{"id": 50623, "name": "Banker's algorithm", "Go": "package bank\n\nimport (\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n    \"sort\"\n    \"sync\"\n)\n\ntype PID string\ntype RID string\ntype RMap map[RID]int\n\n\nfunc (m RMap) String() string {\n    rs := make([]string, len(m))\n    i := 0\n    for r := range m {\n        rs[i] = string(r)\n        i++\n    }\n    sort.Strings(rs)\n    var b bytes.Buffer\n    b.WriteString(\"{\")\n    for _, r := range rs {\n        fmt.Fprintf(&b, \"%q: %d, \", r, m[RID(r)])\n    }\n    bb := b.Bytes()\n    if len(bb) > 1 {\n        bb[len(bb)-2] = '}'\n    }\n    return string(bb)\n}\n\ntype Bank struct {\n    available  RMap\n    max        map[PID]RMap\n    allocation map[PID]RMap\n    sync.Mutex\n}\n\nfunc (b *Bank) need(p PID, r RID) int {\n    return b.max[p][r] - b.allocation[p][r]\n}\n\nfunc New(available RMap) (b *Bank, err error) {\n    for r, a := range available {\n        if a < 0 {\n            return nil, fmt.Errorf(\"negative resource %s: %d\", r, a)\n        }\n    }\n    return &Bank{\n        available:  available,\n        max:        map[PID]RMap{},\n        allocation: map[PID]RMap{},\n    }, nil\n}\n\nfunc (b *Bank) NewProcess(p PID, max RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[p]; ok {\n        return fmt.Errorf(\"process %s already registered\", p)\n    }\n    for r, m := range max {\n        switch a, ok := b.available[r]; {\n        case !ok:\n            return fmt.Errorf(\"resource %s unknown\", r)\n        case m > a:\n            return fmt.Errorf(\"resource %s: process %s max %d > available %d\",\n                r, p, m, a)\n        }\n    }\n    b.max[p] = max\n    b.allocation[p] = RMap{}\n    return\n}\n\nfunc (b *Bank) Request(pid PID, change RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[pid]; !ok {\n        return fmt.Errorf(\"process %s unknown\", pid)\n    }\n    for r, c := range change {\n        if c < 0 {\n            return errors.New(\"decrease not allowed\")\n        }\n        if _, ok := b.available[r]; !ok {\n            return fmt.Errorf(\"resource %s unknown\", r)\n        }\n        if c > b.need(pid, r) {\n            return errors.New(\"increase exceeds declared max\")\n        }\n    }\n    \n    \n    for r, c := range change {\n        b.allocation[pid][r] += c \n    }\n    defer func() {\n        if err != nil { \n            for r, c := range change {\n                b.allocation[pid][r] -= c \n            }\n        }\n    }()\n    \n    \n    cash := RMap{}\n    for r, a := range b.available {\n        cash[r] = a\n    }\n    perm := make([]PID, len(b.allocation))\n    i := 1\n    for pr, a := range b.allocation {\n        if pr == pid {\n            perm[0] = pr\n        } else {\n            perm[i] = pr\n            i++\n        }\n        for r, a := range a {\n            cash[r] -= a\n        }\n    }\n    ret := RMap{}  \n    m := len(perm) \n    for {\n        \n        h := 0\n    h:\n        for ; ; h++ {\n            if h == m {\n                \n                return errors.New(\"request would make deadlock possible\")\n            }\n            for r := range b.available {\n                if b.need(perm[h], r) > cash[r]+ret[r] {\n                    \n                    continue h\n                }\n            }\n            \n            log.Println(\" \", perm[h], \"could terminate\")\n            \n            break\n        }\n        if h == 0 { \n            \n            \n            return nil\n        }\n        for r, a := range b.allocation[perm[h]] {\n            ret[r] += a\n        }\n        m--\n        perm[h] = perm[m]\n    }\n}\n", "Python": "def main():\n    resources = int(input(\"Cantidad de recursos: \"))\n    processes = int(input(\"Cantidad de procesos: \"))\n    max_resources = [int(i) for i in input(\"Recursos máximos: \").split()]\n\n    print(\"\\n-- recursos asignados para cada proceso  --\")\n    currently_allocated = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    print(\"\\n--- recursos máximos para cada proceso  ---\")\n    max_need = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    allocated = [0] * resources\n    for i in range(processes):\n        for j in range(resources):\n            allocated[j] += currently_allocated[i][j]\n    print(f\"\\nRecursos totales asignados  : {allocated}\")\n\n    available = [max_resources[i] - allocated[i] for i in range(resources)]\n    print(f\"Recursos totales disponibles: {available}\\n\")\n\n    running = [True] * processes\n    count = processes\n    while count != 0:\n        safe = False\n        for i in range(processes):\n            if running[i]:\n                executing = True\n                for j in range(resources):\n                    if max_need[i][j] - currently_allocated[i][j] > available[j]:\n                        executing = False\n                        break\n                if executing:\n                    print(f\"proceso {i + 1} ejecutándose\")\n                    running[i] = False\n                    count -= 1\n                    safe = True\n                    for j in range(resources):\n                        available[j] += currently_allocated[i][j]\n                    break\n        if not safe:\n            print(\"El proceso está en un estado inseguro.\")\n            break\n\n        print(f\"El proceso está en un estado seguro.\\nRecursos disponibles: {available}\\n\")\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50624, "name": "Range extraction", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n"}
{"id": 50625, "name": "Machine code", "Go": "package main\n\nimport \"fmt\"\n\n\nimport \"C\"\n\nfunc main() {\n    code := []byte{\n        0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,\n        0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,\n        0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,\n        0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,\n    }\n    le := len(code)\n    buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,\n        C.MAP_PRIVATE|C.MAP_ANON, -1, 0)\n    codePtr := C.CBytes(code)\n    C.memcpy(buf, codePtr, C.size_t(le))\n    var a, b byte = 7, 12\n    fmt.Printf(\"%d + %d = \", a, b)\n    C.runMachineCode(buf, C.byte(a), C.byte(b))\n    C.munmap(buf, C.size_t(le))\n    C.free(codePtr)\n}\n", "Python": "import ctypes\nimport os\nfrom ctypes import c_ubyte, c_int\n\ncode = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])\n\ncode_size = len(code)\n\nif (os.name == 'posix'):\n    import mmap\n    executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)\n    \n    executable_map.write(code)\n    \n    \n    func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))\nelif (os.name == 'nt'):\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    PAGE_EXECUTE_READWRITE = 0x40  \n    MEM_COMMIT = 0x1000\n    executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)\n    if (executable_buffer_address == 0):\n        print('Warning: Failed to enable code execution, call will likely cause a protection fault.')\n        func_address = ctypes.addressof(code_buffer)\n    else:\n        ctypes.memmove(executable_buffer_address, code_buffer, code_size)\n        func_address = executable_buffer_address\nelse:\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    func_address = ctypes.addressof(code_buffer)\n\nprototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) \nfunc = prototype(func_address)                        \nres = func(7,12)\nprint(res)\n"}
{"id": 50626, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 50627, "name": "Zhang-Suen thinning algorithm", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n"}
{"id": 50628, "name": "Median filter", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"raster\"\n)\n\nvar g0, g1 *raster.Grmap\nvar ko [][]int\nvar kc []uint16\nvar mid int\n\nfunc init() {\n    \n    ko = [][]int{\n        {-1, -1}, {0, -1}, {1, -1},\n        {-1,  0}, {0,  0}, {1,  0},\n        {-1,  1}, {0,  1}, {1,  1}}\n    kc = make([]uint16, len(ko))\n    mid = len(ko) / 2\n}\n\nfunc main() {\n    \n    \n    \n    \n    \n    b, err := raster.ReadPpmFile(\"Lenna50.ppm\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    g0 = b.Grmap()\n    w, h := g0.Extent()\n    g1 = raster.NewGrmap(w, h)\n    for y := 0; y < h; y++ {\n        for x := 0; x < w; x++ {\n            g1.SetPx(x, y, median(x, y))\n        }\n    }\n    \n    \n    err = g1.Bitmap().WritePpmFile(\"median.ppm\")\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc median(x, y int) uint16 {\n    var n int\n    \n    \n    \n    for _, o := range ko {\n        \n        c, ok := g0.GetPx(x+o[0], y+o[1])\n        if !ok {\n            continue\n        }\n        \n        var i int\n        for ; i < n; i++ {\n            if c < kc[i] {\n                for j := n; j > i; j-- {\n                    kc[j] = kc[j-1]\n                }\n                break\n            }\n        }\n        kc[i] = c\n        n++\n    }\n    \n    switch {\n    case n == len(kc): \n        return kc[mid]\n    case n%2 == 1: \n        return kc[n/2]\n    }\n    \n    m := n / 2\n    return (kc[m-1] + kc[m]) / 2\n}\n", "Python": "import Image, ImageFilter\nim = Image.open('image.ppm')\n\nmedian = im.filter(ImageFilter.MedianFilter(3))\nmedian.save('image2.ppm')\n"}
{"id": 50629, "name": "Median filter", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"raster\"\n)\n\nvar g0, g1 *raster.Grmap\nvar ko [][]int\nvar kc []uint16\nvar mid int\n\nfunc init() {\n    \n    ko = [][]int{\n        {-1, -1}, {0, -1}, {1, -1},\n        {-1,  0}, {0,  0}, {1,  0},\n        {-1,  1}, {0,  1}, {1,  1}}\n    kc = make([]uint16, len(ko))\n    mid = len(ko) / 2\n}\n\nfunc main() {\n    \n    \n    \n    \n    \n    b, err := raster.ReadPpmFile(\"Lenna50.ppm\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    g0 = b.Grmap()\n    w, h := g0.Extent()\n    g1 = raster.NewGrmap(w, h)\n    for y := 0; y < h; y++ {\n        for x := 0; x < w; x++ {\n            g1.SetPx(x, y, median(x, y))\n        }\n    }\n    \n    \n    err = g1.Bitmap().WritePpmFile(\"median.ppm\")\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc median(x, y int) uint16 {\n    var n int\n    \n    \n    \n    for _, o := range ko {\n        \n        c, ok := g0.GetPx(x+o[0], y+o[1])\n        if !ok {\n            continue\n        }\n        \n        var i int\n        for ; i < n; i++ {\n            if c < kc[i] {\n                for j := n; j > i; j-- {\n                    kc[j] = kc[j-1]\n                }\n                break\n            }\n        }\n        kc[i] = c\n        n++\n    }\n    \n    switch {\n    case n == len(kc): \n        return kc[mid]\n    case n%2 == 1: \n        return kc[n/2]\n    }\n    \n    m := n / 2\n    return (kc[m-1] + kc[m]) / 2\n}\n", "Python": "import Image, ImageFilter\nim = Image.open('image.ppm')\n\nmedian = im.filter(ImageFilter.MedianFilter(3))\nmedian.save('image2.ppm')\n"}
{"id": 50630, "name": "Run as a daemon or service", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n"}
{"id": 50631, "name": "Run as a daemon or service", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n"}
{"id": 50632, "name": "Coprime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n"}
{"id": 50633, "name": "Coprime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n"}
{"id": 50634, "name": "Variable declaration reset", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n"}
{"id": 50635, "name": "SOAP", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n"}
{"id": 50636, "name": "Pragmatic directives", "Go": "\n", "Python": "Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> import __future__\n>>> __future__.all_feature_names\n['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']\n>>>\n"}
{"id": 50637, "name": "Find first and last set bit of a long integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 50638, "name": "Find first and last set bit of a long integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n"}
{"id": 50639, "name": "Numbers with equal rises and falls", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n"}
{"id": 50640, "name": "Terminal control_Cursor movement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc main() {\n    tput(\"clear\") \n    tput(\"cup\", \"6\", \"3\") \n    time.Sleep(1 * time.Second)\n    tput(\"cub1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuf1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuu1\") \n    time.Sleep(1 * time.Second)\n    \n    tput(\"cud\", \"1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cr\") \n    time.Sleep(1 * time.Second)\n    \n    var h, w int\n    cmd := exec.Command(\"stty\", \"size\")\n    cmd.Stdin = os.Stdin\n    d, _ := cmd.Output()\n    fmt.Sscan(string(d), &h, &w)\n    \n    tput(\"hpa\", strconv.Itoa(w-1))\n    time.Sleep(2 * time.Second)\n    \n    tput(\"home\")\n    time.Sleep(2 * time.Second)\n    \n    tput(\"cup\", strconv.Itoa(h-1), strconv.Itoa(w-1))\n    time.Sleep(3 * time.Second)\n}\n\nfunc tput(args ...string) error {\n    cmd := exec.Command(\"tput\", args...)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n"}
{"id": 50641, "name": "Summation of primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    sum := 0\n    for _, p := range rcu.Primes(2e6 - 1) {\n        sum += p\n    }\n    fmt.Printf(\"The sum of all primes below 2 million is %s.\\n\", rcu.Commatize(sum))\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    suma = 2\n    n = 1\n    for i in range(3, 2000000, 2):\n        if isPrime(i):\n            suma += i\n            n+=1 \n    print(suma)\n"}
{"id": 50642, "name": "Koch curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n"}
{"id": 50643, "name": "Draw pixel 2", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 640, 480)\n    img := image.NewRGBA(rect)\n\n    \n    blue := color.RGBA{0, 0, 255, 255}\n    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)\n\n    \n    yellow := color.RGBA{255, 255, 0, 255}\n    width := img.Bounds().Dx()\n    height := img.Bounds().Dy()\n    rand.Seed(time.Now().UnixNano())\n    x := rand.Intn(width)\n    y := rand.Intn(height)\n    img.Set(x, y, yellow)\n\n    \n    cmap := map[color.Color]string{blue: \"blue\", yellow: \"yellow\"}\n    for i := 0; i < width; i++ {\n        for j := 0; j < height; j++ {\n            c := img.At(i, j)\n            if cmap[c] == \"yellow\" {\n                fmt.Printf(\"The color of the pixel at (%d, %d) is yellow\\n\", i, j)\n            }\n        }\n    }\n}\n", "Python": "import Tkinter,random\ndef draw_pixel_2 ( sizex=640,sizey=480 ):\n    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )\n    root = Tkinter.Tk()\n    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )\n    can.create_rectangle( pos*2,outline='yellow' )\n    can.pack()\n    root.title('press ESCAPE to quit')\n    root.bind('<Escape>',lambda e : root.quit())\n    root.mainloop()\n\ndraw_pixel_2()\n"}
{"id": 50644, "name": "Count how many vowels and consonants occur in a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n"}
{"id": 50645, "name": "Count how many vowels and consonants occur in a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n"}
{"id": 50646, "name": "Compiler_syntax analyzer", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n"}
{"id": 50647, "name": "Compiler_syntax analyzer", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n"}
{"id": 50648, "name": "Draw a pixel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n"}
{"id": 50649, "name": "Numbers whose binary and ternary digit sums are prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50650, "name": "Numbers whose binary and ternary digit sums are prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50651, "name": "Words from neighbour ones", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n"}
{"id": 50652, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var res []int\n    for n := 1; n < 1000; n++ {\n        digits := rcu.Digits(n, 10)\n        var all = true\n        for _, d := range digits {\n            if d == 0 || n%d != 0 {\n                all = false\n                break\n            }\n        }\n        if all {\n            prod := 1\n            for _, d := range digits {\n                prod *= d\n            }\n            if prod > 0 && n%prod != 0 {\n                res = append(res, n)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 1000 divisible by their digits, but not by the product thereof:\")\n    for i, n := range res {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such numbers found\\n\", len(res))\n}\n", "Python": "\n\nfrom functools import reduce\nfrom operator import mul\n\n\n\ndef p(n):\n    \n    digits = [int(c) for c in str(n)]\n    return not 0 in digits and (\n        0 != (n % reduce(mul, digits, 1))\n    ) and all(0 == n % d for d in digits)\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1000)\n        if p(n)\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matching numbers:\\n')\n    print('\\n'.join(\n        ' '.join(cell.rjust(w, ' ') for cell in row)\n        for row in chunksOf(10)(xs)\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50653, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 50654, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 50655, "name": "Magic squares of singly even order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n"}
{"id": 50656, "name": "Generate Chess960 starting position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n"}
{"id": 50657, "name": "Generate Chess960 starting position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n"}
{"id": 50658, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 50659, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 50660, "name": "Perlin noise", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n    X := int(math.Floor(x)) & 255\n    Y := int(math.Floor(y)) & 255\n    Z := int(math.Floor(z)) & 255\n    x -= math.Floor(x)\n    y -= math.Floor(y)\n    z -= math.Floor(z)\n    u := fade(x)\n    v := fade(y)\n    w := fade(z)\n    A := p[X] + Y\n    AA := p[A] + Z\n    AB := p[A+1] + Z\n    B := p[X+1] + Y\n    BA := p[B] + Z\n    BB := p[B+1] + Z\n    return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n        grad(p[BA], x-1, y, z)),\n        lerp(u, grad(p[AB], x, y-1, z),\n            grad(p[BB], x-1, y-1, z))),\n        lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n            grad(p[BA+1], x-1, y, z-1)),\n            lerp(u, grad(p[AB+1], x, y-1, z-1),\n                grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n    \n    \n    \n    switch hash & 15 {\n    case 0, 12:\n        return x + y\n    case 1, 14:\n        return y - x\n    case 2:\n        return x - y\n    case 3:\n        return -x - y\n    case 4:\n        return x + z\n    case 5:\n        return z - x\n    case 6:\n        return x - z\n    case 7:\n        return -x - z\n    case 8:\n        return y + z\n    case 9, 13:\n        return z - y\n    case 10:\n        return y - z\n    }\n    \n    return -y - z\n}\n\nvar permutation = []int{\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n    140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n    247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n    57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n    74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n    60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n    65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n    200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n    52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n    207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n    119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n    129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n    218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n    81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n    184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n    222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)\n", "Python": "import math\n\ndef perlin_noise(x, y, z):\n    X = math.floor(x) & 255                  \n    Y = math.floor(y) & 255                  \n    Z = math.floor(z) & 255\n    x -= math.floor(x)                                \n    y -= math.floor(y)                                \n    z -= math.floor(z)\n    u = fade(x)                                \n    v = fade(y)                                \n    w = fade(z)\n    A = p[X  ]+Y; AA = p[A]+Z; AB = p[A+1]+Z      \n    B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z      \n \n    return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                   grad(p[BA  ], x-1, y  , z   )), \n                           lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                   grad(p[BB  ], x-1, y-1, z   ))),\n                   lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                   grad(p[BA+1], x-1, y  , z-1 )), \n                           lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                   grad(p[BB+1], x-1, y-1, z-1 ))))\n                                   \ndef fade(t): \n    return t ** 3 * (t * (t * 6 - 15) + 10)\n    \ndef lerp(t, a, b):\n    return a + t * (b - a)\n    \ndef grad(hash, x, y, z):\n    h = hash & 15                      \n    u = x if h<8 else y                \n    v = y if h<4 else (x if h in (12, 14) else z)\n    return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n    p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n    print(\"%1.17f\" % perlin_noise(3.14, 42, 7))\n"}
{"id": 50661, "name": "File size distribution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc commatize(n int64) 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 fileSizeDistribution(root string) {\n    var sizes [12]int\n    files := 0\n    directories := 0\n    totalSize := int64(0)\n    walkFunc := func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        files++\n        if info.IsDir() {\n            directories++\n        }\n        size := info.Size()\n        if size == 0 {\n            sizes[0]++\n            return nil\n        }\n        totalSize += size\n        logSize := math.Log10(float64(size))\n        index := int(math.Floor(logSize))\n        sizes[index+1]++\n        return nil\n    }\n    err := filepath.Walk(root, walkFunc)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n    for i := 0; i < len(sizes); i++ {\n        if i == 0 {\n            fmt.Print(\"  \")\n        } else {\n            fmt.Print(\"+ \")\n        }\n        fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n    }\n    fmt.Println(\"                                  -----\")\n    fmt.Printf(\"= Total number of files         : %5d\\n\", files)\n    fmt.Printf(\"  including directories         : %5d\\n\", directories)\n    c := commatize(totalSize)\n    fmt.Println(\"\\n  Total size of files           :\", c, \"bytes\")\n}\n\nfunc main() {\n    fileSizeDistribution(\"./\")\n}\n", "Python": "import sys, os\nfrom collections import Counter\n\ndef dodir(path):\n    global h\n\n    for name in os.listdir(path):\n        p = os.path.join(path, name)\n\n        if os.path.islink(p):\n            pass\n        elif os.path.isfile(p):\n            h[os.stat(p).st_size] += 1\n        elif os.path.isdir(p):\n            dodir(p)\n        else:\n            pass\n\ndef main(arg):\n    global h\n    h = Counter()\n    for dir in arg:\n        dodir(dir)\n\n    s = n = 0\n    for k, v in sorted(h.items()):\n        print(\"Size %d -> %d file(s)\" % (k, v))\n        n += v\n        s += k * v\n    print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])\n"}
{"id": 50662, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 50663, "name": "Rendezvous", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n    \"sync\"\n)\n\nvar hdText = `Humpty Dumpty sat on a wall.\nHumpty Dumpty had a great fall.\nAll the king's horses and all the king's men,\nCouldn't put Humpty together again.`\n\nvar mgText = `Old Mother Goose,\nWhen she wanted to wander,\nWould ride through the air,\nOn a very fine gander.\nJack's mother came in,\nAnd caught the goose soon,\nAnd mounting its back,\nFlew up to the moon.`\n\nfunc main() {\n    reservePrinter := startMonitor(newPrinter(5), nil)\n    mainPrinter := startMonitor(newPrinter(5), reservePrinter)\n    var busy sync.WaitGroup\n    busy.Add(2)\n    go writer(mainPrinter, \"hd\", hdText, &busy)\n    go writer(mainPrinter, \"mg\", mgText, &busy)\n    busy.Wait()\n}\n\n\n\n\ntype printer func(string) error\n\n\n\n\n\nfunc newPrinter(ink int) printer {\n    return func(line string) error {\n        if ink == 0 {\n            return eOutOfInk\n        }\n        for _, c := range line {\n            fmt.Printf(\"%c\", c)\n        }\n        fmt.Println()\n        ink--\n        return nil\n    }\n}\n\nvar eOutOfInk = errors.New(\"out of ink\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype rSync struct {\n    call     chan string\n    response chan error\n}\n\n\n\n\n\n\nfunc (r *rSync) print(data string) error {\n    r.call <- data      \n    return <-r.response \n}\n\n\n\n\nfunc monitor(hardPrint printer, entry, reserve *rSync) {\n    for {\n        \n        \n        data := <-entry.call\n        \n        \n        \n\n        \n        switch err := hardPrint(data); {\n\n        \n        case err == nil:\n            entry.response <- nil \n\n        case err == eOutOfInk && reserve != nil:\n            \n            \n            \n            \n            entry.response <- reserve.print(data)\n\n        default:\n            entry.response <- err \n        }\n        \n    }\n}\n\n\n\n\n\n\nfunc startMonitor(p printer, reservePrinter *rSync) *rSync {\n    entry := &rSync{make(chan string), make(chan error)}\n    go monitor(p, entry, reservePrinter)\n    return entry\n}\n\n\n\n\n\n\nfunc writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {\n    for _, line := range strings.Split(text, \"\\n\") {\n        if err := printMonitor.print(line); err != nil {\n            fmt.Printf(\"**** writer task %q terminated: %v ****\\n\", id, err)\n            break\n        }\n    }\n    busy.Done()\n}\n", "Python": "\nfrom __future__ import annotations\n\nimport asyncio\nimport sys\n\nfrom typing import Optional\nfrom typing import TextIO\n\n\nclass OutOfInkError(Exception):\n    \n\n\nclass Printer:\n    def __init__(self, name: str, backup: Optional[Printer]):\n        self.name = name\n        self.backup = backup\n\n        self.ink_level: int = 5\n        self.output_stream: TextIO = sys.stdout\n\n    async def print(self, msg):\n        if self.ink_level <= 0:\n            if self.backup:\n                await self.backup.print(msg)\n            else:\n                raise OutOfInkError(self.name)\n        else:\n            self.ink_level -= 1\n            self.output_stream.write(f\"({self.name}): {msg}\\n\")\n\n\nasync def main():\n    reserve = Printer(\"reserve\", None)\n    main = Printer(\"main\", reserve)\n\n    humpty_lines = [\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men,\",\n        \"Couldn't put Humpty together again.\",\n    ]\n\n    goose_lines = [\n        \"Old Mother Goose,\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air,\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n    ]\n\n    async def print_humpty():\n        for line in humpty_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Humpty Dumpty out of ink!\")\n                break\n\n    async def print_goose():\n        for line in goose_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Mother Goose out of ink!\")\n                break\n\n    await asyncio.gather(print_goose(), print_humpty())\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main(), debug=True)\n"}
{"id": 50664, "name": "Rendezvous", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n    \"sync\"\n)\n\nvar hdText = `Humpty Dumpty sat on a wall.\nHumpty Dumpty had a great fall.\nAll the king's horses and all the king's men,\nCouldn't put Humpty together again.`\n\nvar mgText = `Old Mother Goose,\nWhen she wanted to wander,\nWould ride through the air,\nOn a very fine gander.\nJack's mother came in,\nAnd caught the goose soon,\nAnd mounting its back,\nFlew up to the moon.`\n\nfunc main() {\n    reservePrinter := startMonitor(newPrinter(5), nil)\n    mainPrinter := startMonitor(newPrinter(5), reservePrinter)\n    var busy sync.WaitGroup\n    busy.Add(2)\n    go writer(mainPrinter, \"hd\", hdText, &busy)\n    go writer(mainPrinter, \"mg\", mgText, &busy)\n    busy.Wait()\n}\n\n\n\n\ntype printer func(string) error\n\n\n\n\n\nfunc newPrinter(ink int) printer {\n    return func(line string) error {\n        if ink == 0 {\n            return eOutOfInk\n        }\n        for _, c := range line {\n            fmt.Printf(\"%c\", c)\n        }\n        fmt.Println()\n        ink--\n        return nil\n    }\n}\n\nvar eOutOfInk = errors.New(\"out of ink\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype rSync struct {\n    call     chan string\n    response chan error\n}\n\n\n\n\n\n\nfunc (r *rSync) print(data string) error {\n    r.call <- data      \n    return <-r.response \n}\n\n\n\n\nfunc monitor(hardPrint printer, entry, reserve *rSync) {\n    for {\n        \n        \n        data := <-entry.call\n        \n        \n        \n\n        \n        switch err := hardPrint(data); {\n\n        \n        case err == nil:\n            entry.response <- nil \n\n        case err == eOutOfInk && reserve != nil:\n            \n            \n            \n            \n            entry.response <- reserve.print(data)\n\n        default:\n            entry.response <- err \n        }\n        \n    }\n}\n\n\n\n\n\n\nfunc startMonitor(p printer, reservePrinter *rSync) *rSync {\n    entry := &rSync{make(chan string), make(chan error)}\n    go monitor(p, entry, reservePrinter)\n    return entry\n}\n\n\n\n\n\n\nfunc writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {\n    for _, line := range strings.Split(text, \"\\n\") {\n        if err := printMonitor.print(line); err != nil {\n            fmt.Printf(\"**** writer task %q terminated: %v ****\\n\", id, err)\n            break\n        }\n    }\n    busy.Done()\n}\n", "Python": "\nfrom __future__ import annotations\n\nimport asyncio\nimport sys\n\nfrom typing import Optional\nfrom typing import TextIO\n\n\nclass OutOfInkError(Exception):\n    \n\n\nclass Printer:\n    def __init__(self, name: str, backup: Optional[Printer]):\n        self.name = name\n        self.backup = backup\n\n        self.ink_level: int = 5\n        self.output_stream: TextIO = sys.stdout\n\n    async def print(self, msg):\n        if self.ink_level <= 0:\n            if self.backup:\n                await self.backup.print(msg)\n            else:\n                raise OutOfInkError(self.name)\n        else:\n            self.ink_level -= 1\n            self.output_stream.write(f\"({self.name}): {msg}\\n\")\n\n\nasync def main():\n    reserve = Printer(\"reserve\", None)\n    main = Printer(\"main\", reserve)\n\n    humpty_lines = [\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men,\",\n        \"Couldn't put Humpty together again.\",\n    ]\n\n    goose_lines = [\n        \"Old Mother Goose,\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air,\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n    ]\n\n    async def print_humpty():\n        for line in humpty_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Humpty Dumpty out of ink!\")\n                break\n\n    async def print_goose():\n        for line in goose_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Mother Goose out of ink!\")\n                break\n\n    await asyncio.gather(print_goose(), print_humpty())\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main(), debug=True)\n"}
{"id": 50665, "name": "First class environments", "Go": "package main\n\nimport \"fmt\"\n\nconst jobs = 12\n\ntype environment struct{ seq, cnt int }\n\nvar (\n    env      [jobs]environment\n    seq, cnt *int\n)\n\nfunc hail() {\n    fmt.Printf(\"% 4d\", *seq)\n    if *seq == 1 {\n        return\n    }\n    (*cnt)++\n    if *seq&1 != 0 {\n        *seq = 3*(*seq) + 1\n    } else {\n        *seq /= 2\n    }\n}\n\nfunc switchTo(id int) {\n    seq = &env[id].seq\n    cnt = &env[id].cnt\n}\n\nfunc main() {\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        env[i].seq = i + 1\n    }\n\nagain:\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        hail()\n    }\n    fmt.Println()\n\n    for j := 0; j < jobs; j++ {\n        switchTo(j)\n        if *seq != 1 {\n            goto again\n        }\n    }\n    fmt.Println()\n\n    fmt.Println(\"COUNTS:\")\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        fmt.Printf(\"% 4d\", *cnt)\n    }\n    fmt.Println()\n}\n", "Python": "environments = [{'cnt':0, 'seq':i+1} for i in range(12)]\n\ncode = \n\nwhile any(env['seq'] > 1 for env in environments):\n    for env in environments:\n        exec(code, globals(), env)\n    print()\n\nprint('Counts')\nfor env in environments:\n    print('% 4d' % env['cnt'], end='')\nprint()\n"}
{"id": 50666, "name": "UTF-8 encode and decode", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n"}
{"id": 50667, "name": "UTF-8 encode and decode", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n"}
{"id": 50668, "name": "Xiaolin Wu's line algorithm", "Go": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n    return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n    return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n    return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n    return 1 - fpart(x)\n}\n\n\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n    \n    dx := x2 - x1\n    dy := y2 - y1\n    ax := dx\n    if ax < 0 {\n        ax = -ax\n    }\n    ay := dy\n    if ay < 0 {\n        ay = -ay\n    }\n    \n    var plot func(int, int, float64)\n    if ax < ay {\n        x1, y1 = y1, x1\n        x2, y2 = y2, x2\n        dx, dy = dy, dx\n        plot = func(x, y int, c float64) {\n            g.SetPx(y, x, uint16(c*math.MaxUint16))\n        }\n    } else {\n        plot = func(x, y int, c float64) {\n            g.SetPx(x, y, uint16(c*math.MaxUint16))\n        }\n    }\n    if x2 < x1 {\n        x1, x2 = x2, x1\n        y1, y2 = y2, y1\n    }\n    gradient := dy / dx\n\n    \n    xend := round(x1)\n    yend := y1 + gradient*(xend-x1)\n    xgap := rfpart(x1 + .5)\n    xpxl1 := int(xend) \n    ypxl1 := int(ipart(yend))\n    plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n    intery := yend + gradient \n\n    \n    xend = round(x2)\n    yend = y2 + gradient*(xend-x2)\n    xgap = fpart(x2 + 0.5)\n    xpxl2 := int(xend) \n    ypxl2 := int(ipart(yend))\n    plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n    \n    for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n        plot(x, int(ipart(intery)), rfpart(intery))\n        plot(x, int(ipart(intery))+1, fpart(intery))\n        intery = intery + gradient\n    }\n}\n", "Python": "\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n    return x - int(x)\n\ndef _rfpart(x):\n    return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n    \n    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n    c = compose_color(img.getpixel(xy), color)\n    img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n    \n    x1, y1 = p1\n    x2, y2 = p2\n    dx, dy = x2-x1, y2-y1\n    steep = abs(dx) < abs(dy)\n    p = lambda px, py: ((px,py), (py,px))[steep]\n\n    if steep:\n        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n    if x2 < x1:\n        x1, x2, y1, y2 = x2, x1, y2, y1\n\n    grad = dy/dx\n    intery = y1 + _rfpart(x1) * grad\n    def draw_endpoint(pt):\n        x, y = pt\n        xend = round(x)\n        yend = y + grad * (xend - x)\n        xgap = _rfpart(x + 0.5)\n        px, py = int(xend), int(yend)\n        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n        return px\n\n    xstart = draw_endpoint(p(*p1)) + 1\n    xend = draw_endpoint(p(*p2))\n\n    for x in range(xstart, xend):\n        y = int(intery)\n        putpixel(img, p(x, y), color, _rfpart(intery))\n        putpixel(img, p(x, y+1), color, _fpart(intery))\n        intery += grad\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print 'usage: python xiaolinwu.py [output-file]'\n        sys.exit(-1)\n\n    blue = (0, 0, 255)\n    yellow = (255, 255, 0)\n    img = Image.new(\"RGB\", (500,500), blue)\n    for a in range(10, 431, 60):\n        draw_line(img, (10, 10), (490, a), yellow)\n        draw_line(img, (10, 10), (a, 490), yellow)\n    draw_line(img, (10, 10), (490, 490), yellow)\n    filename = sys.argv[1]\n    img.save(filename)\n    print 'image saved to', filename\n"}
{"id": 50669, "name": "Keyboard macros", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"unsafe\"\n\nfunc main() {\n    d := C.XOpenDisplay(nil)\n    f7, f6 := C.CString(\"F7\"), C.CString(\"F6\")\n    defer C.free(unsafe.Pointer(f7))\n    defer C.free(unsafe.Pointer(f6))\n\n    if d != nil {\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),\n            C.Mod1Mask, \n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),\n            C.Mod1Mask,\n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n\n        var event C.XEvent\n        for {\n            C.XNextEvent(d, &event)\n            if C.getXEvent_type(event) == C.KeyPress {\n                xkeyEvent := C.getXEvent_xkey(event)\n                s := C.XLookupKeysym(&xkeyEvent, 0)\n                if s == C.XK_F7 {\n                    fmt.Println(\"something's happened\")\n                } else if s == C.XK_F6 {\n                    break\n                }\n            }\n        }\n\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n    } else {\n        fmt.Println(\"XOpenDisplay did not succeed\")\n    }\n}\n", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n"}
{"id": 50670, "name": "McNuggets problem", "Go": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n    sv := make([]bool, limit+1) \n    for s := 0; s <= limit; s += 6 {\n        for n := s; n <= limit; n += 9 {\n            for t := n; t <= limit; t += 20 {\n                sv[t] = true\n            }\n        }\n    }\n    for i := limit; i >= 0; i-- {\n        if !sv[i] {\n            fmt.Println(\"Maximum non-McNuggets number is\", i)\n            return\n        }\n    }\n}\n\nfunc main() {\n    mcnugget(100)\n}\n", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n"}
{"id": 50671, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 50672, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 50673, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 50674, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n"}
{"id": 50675, "name": "Pseudo-random numbers_Xorshift star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n"}
{"id": 50676, "name": "Four is the number of letters in the ...", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n"}
{"id": 50677, "name": "ASCII art diagram converter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n"}
{"id": 50678, "name": "Levenshtein distance_Alignment", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"github.com/biogo/biogo/align\"\n    ab \"github.com/biogo/biogo/alphabet\"\n    \"github.com/biogo/biogo/feat\"\n    \"github.com/biogo/biogo/seq/linear\"\n)\n\nfunc main() {\n    \n    \n    lc := ab.Must(ab.NewAlphabet(\"-abcdefghijklmnopqrstuvwxyz\",\n        feat.Undefined, '-', 0, true))\n    \n    \n    \n    \n    nw := make(align.NW, lc.Len())\n    for i := range nw {\n        r := make([]int, lc.Len())\n        nw[i] = r\n        for j := range r {\n            if j != i {\n                r[j] = -1\n            }\n        }\n    }\n    \n    a := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"rosettacode\"))}\n    a.Alpha = lc\n    b := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"raisethysword\"))}\n    b.Alpha = lc\n    \n    aln, err := nw.Align(a, b)\n    \n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fa := align.Format(a, b, aln, '-')\n    fmt.Printf(\"%s\\n%s\\n\", fa[0], fa[1])\n    aa := fmt.Sprint(fa[0])\n    ba := fmt.Sprint(fa[1])\n    ma := make([]byte, len(aa))\n    for i := range ma {\n        if aa[i] == ba[i] {\n            ma[i] = ' '\n        } else {\n            ma[i] = '|'\n        }\n    }\n    fmt.Println(string(ma))\n}\n", "Python": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n    result = \"\"\n    pos, removed = 0, 0\n    for x in ndiff(str1, str2):\n        if pos<len(str1) and str1[pos] == x[2]:\n          pos += 1\n          result += x[2]\n          if x[0] == \"-\":\n              removed += 1\n          continue\n        else:\n          if removed > 0:\n            removed -=1\n          else:\n            result += \"-\"\n    print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")\n"}
{"id": 50679, "name": "Compare sorting algorithms' performance", "Go": "package main\n\nimport (\n    \"log\"\n    \"math/rand\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/gonum/plot\"\n    \"github.com/gonum/plot/plotter\"\n    \"github.com/gonum/plot/plotutil\"\n    \"github.com/gonum/plot/vg\"\n)\n\n\n\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\nfunc insertionsort(a []int) {\n    for i := 1; i < len(a); i++ {\n        value := a[i]\n        j := i - 1\n        for j >= 0 && a[j] > value {\n            a[j+1] = a[j]\n            j = j - 1\n        }\n        a[j+1] = value\n    }\n}\n\nfunc quicksort(a []int) {\n    var pex func(int, int)\n    pex = func(lower, upper int) {\n        for {\n            switch upper - lower {\n            case -1, 0:\n                return\n            case 1:\n                if a[upper] < a[lower] {\n                    a[upper], a[lower] = a[lower], a[upper]\n                }\n                return\n            }\n            bx := (upper + lower) / 2\n            b := a[bx]\n            lp := lower\n            up := upper\n        outer:\n            for {\n                for lp < upper && !(b < a[lp]) {\n                    lp++\n                }\n                for {\n                    if lp > up {\n                        break outer\n                    }\n                    if a[up] < b {\n                        break\n                    }\n                    up--\n                }\n                a[lp], a[up] = a[up], a[lp]\n                lp++\n                up--\n            }\n            if bx < lp {\n                if bx < lp-1 {\n                    a[bx], a[lp-1] = a[lp-1], b\n                }\n                up = lp - 2\n            } else {\n                if bx > lp {\n                    a[bx], a[lp] = a[lp], b\n                }\n                up = lp - 1\n                lp++\n            }\n            if up-lower < upper-lp {\n                pex(lower, up)\n                lower = lp\n            } else {\n                pex(lp, upper)\n                upper = up\n            }\n        }\n    }\n    pex(0, len(a)-1)\n}\n\n\n\nfunc ones(n int) []int {\n    s := make([]int, n)\n    for i := range s {\n        s[i] = 1\n    }\n    return s\n}\n\nfunc ascending(n int) []int {\n    s := make([]int, n)\n    v := 1\n    for i := 0; i < n; {\n        if rand.Intn(3) == 0 {\n            s[i] = v\n            i++\n        }\n        v++\n    }\n    return s\n}\n\nfunc shuffled(n int) []int {\n    return rand.Perm(n)\n}\n\n\n\n\n\n\nconst (\n    nPts = 7    \n    inc  = 1000 \n)\n\nvar (\n    p        *plot.Plot\n    sortName = []string{\"Bubble sort\", \"Insertion sort\", \"Quicksort\"}\n    sortFunc = []func([]int){bubblesort, insertionsort, quicksort}\n    dataName = []string{\"Ones\", \"Ascending\", \"Shuffled\"}\n    dataFunc = []func(int) []int{ones, ascending, shuffled}\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    var err error\n    p, err = plot.New()\n    if err != nil {\n        log.Fatal(err)\n    }\n    p.X.Label.Text = \"Data size\"\n    p.Y.Label.Text = \"microseconds\"\n    p.Y.Scale = plot.LogScale{}\n    p.Y.Tick.Marker = plot.LogTicks{}\n    p.Y.Min = .5 \n\n    for dx, name := range dataName {\n        s, err := plotter.NewScatter(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        s.Shape = plotutil.DefaultGlyphShapes[dx]\n        p.Legend.Add(name, s)\n    }\n    for sx, name := range sortName {\n        l, err := plotter.NewLine(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        l.Color = plotutil.DarkColors[sx]\n        p.Legend.Add(name, l)\n    }\n    for sx := range sortFunc {\n        bench(sx, 0, 1) \n        bench(sx, 1, 5) \n        bench(sx, 2, 5) \n    }\n\n    if err := p.Save(5*vg.Inch, 5*vg.Inch, \"comp.png\"); err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc bench(sx, dx, rep int) {\n    log.Println(\"bench\", sortName[sx], dataName[dx], \"x\", rep)\n    pts := make(plotter.XYs, nPts)\n    sf := sortFunc[sx]\n    for i := range pts {\n        x := (i + 1) * inc\n        \n        \n        \n        s0 := dataFunc[dx](x) \n        s := make([]int, x)   \n        var tSort int64\n        for j := 0; j < rep; j++ {\n            tSort += testing.Benchmark(func(b *testing.B) {\n                for i := 0; i < b.N; i++ {\n                    copy(s, s0)\n                    sf(s)\n                }\n            }).NsPerOp()\n        }\n        tSort /= int64(rep)\n        log.Println(x, \"items\", tSort, \"ns\") \n        pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001}\n    }\n    pl, ps, err := plotter.NewLinePoints(pts) \n    if err != nil {\n        log.Fatal(err)\n    }\n    pl.Color = plotutil.DarkColors[sx]\n    ps.Color = plotutil.DarkColors[sx]\n    ps.Shape = plotutil.DefaultGlyphShapes[dx]\n    p.Add(pl, ps)\n}\n", "Python": "def builtinsort(x):\n    x.sort()\n\ndef partition(seq, pivot):\n   low, middle, up = [], [], []\n   for x in seq:\n       if x < pivot:\n           low.append(x)\n       elif x == pivot:\n           middle.append(x)\n       else:\n           up.append(x)\n   return low, middle, up\nimport random\ndef qsortranpart(seq):\n   size = len(seq)\n   if size < 2: return seq\n   low, middle, up = partition(seq, random.choice(seq))\n   return qsortranpart(low) + middle + qsortranpart(up)\n"}
{"id": 50680, "name": "Same fringe", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 50681, "name": "Same fringe", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 50682, "name": "Parse command-line arguments", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n"}
{"id": 50683, "name": "Parse command-line arguments", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n"}
{"id": 50684, "name": "Parse command-line arguments", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n"}
{"id": 50685, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n"}
{"id": 50686, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n"}
{"id": 50687, "name": "Simulate input_Keyboard", "Go": "package main\n\nimport (\n    \"github.com/micmonay/keybd_event\"\n    \"log\"\n    \"runtime\"\n    \"time\"\n)\n\nfunc main() {\n    kb, err := keybd_event.NewKeyBonding()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    if runtime.GOOS == \"linux\" {\n        time.Sleep(2 * time.Second)\n    }\n\n    \n    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)\n\n    \n    err = kb.Launching()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "import autopy\nautopy.key.type_string(\"Hello, world!\") \nautopy.key.type_string(\"Hello, world!\", wpm=60) \nautopy.key.tap(autopy.key.Code.RETURN)\nautopy.key.tap(autopy.key.Code.F1)\nautopy.key.tap(autopy.key.Code.LEFT_ARROW)\n"}
{"id": 50688, "name": "Peaceful chess queen armies", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n"}
{"id": 50689, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "Python": "while 1:\n   print \"SPAM\"\n"}
{"id": 50690, "name": "Metaprogramming", "Go": "package main\n\nimport \"fmt\"\n\ntype person struct{\n    name string\n    age int\n}\n\nfunc copy(p person) person {\n    return person{p.name, p.age}\n}\n\nfunc main() {\n    p := person{\"Dave\", 40}\n    fmt.Println(p)\n    q := copy(p)\n    fmt.Println(q)\n     \n}\n", "Python": "from macropy.core.macros import *\nfrom macropy.core.quotes import macros, q, ast, u\n\nmacros = Macros()\n\n@macros.expr\ndef expand(tree, **kw):\n    addition = 10\n    return q[lambda x: x * ast[tree] + u[addition]]\n"}
{"id": 50691, "name": "Numbers with same digit set in base 10 and base 16", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n", "Python": "col = 0\nfor i in range(100000):\n    if set(str(i)) == set(hex(i)[2:]):\n        col += 1\n        print(\"{:7}\".format(i), end='\\n'[:col % 10 == 0])\nprint()\n"}
{"id": 50692, "name": "Largest prime factor", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestPrimeFactor(n uint64) uint64 {\n    if n < 2 {\n        return 1\n    }\n    inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}\n    max := uint64(1)\n    for n%2 == 0 {\n        max = 2\n        n /= 2\n    }\n    for n%3 == 0 {\n        max = 3\n        n /= 3\n    }\n    for n%5 == 0 {\n        max = 5\n        n /= 5\n    }\n    k := uint64(7)\n    i := 0\n    for k*k <= n {\n        if n%k == 0 {\n            max = k\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        return n\n    }\n    return max\n}\n\nfunc main() {\n    n := uint64(600851475143)\n    fmt.Println(\"The largest prime factor of\", n, \"is\", largestPrimeFactor(n), \"\\b.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    n = 600851475143\n    j = 3\n    while not isPrime(n):\n        if n % j == 0:\n            n /= j\n        j += 2\n    print(n);\n"}
{"id": 50693, "name": "Largest proper divisor of n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            return n / i\n        }\n    }\n    return 1\n}\n\nfunc main() {\n    fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n    fmt.Print(\" 1  \")\n    for n := 2; n <= 100; n++ {\n        if n%2 == 0 {\n            fmt.Printf(\"%2d  \", n/2)\n        } else {\n            fmt.Printf(\"%2d  \", largestProperDivisor(n))\n        }\n        if n%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def lpd(n):\n    for i in range(n-1,0,-1):\n        if n%i==0: return i\n    return 1\n\nfor i in range(1,101):\n    print(\"{:3}\".format(lpd(i)), end=i%10==0 and '\\n' or '')\n"}
{"id": 50694, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 50695, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 50696, "name": "Active Directory_Search for a user", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n"}
{"id": 50697, "name": "Singular value decomposition", "Go": "<package main\n\nimport (\n    \"fmt\"\n    \"gonum.org/v1/gonum/mat\"\n    \"log\"\n)\n\nfunc matPrint(m mat.Matrix) {\n    fa := mat.Formatted(m, mat.Prefix(\"\"), mat.Squeeze())\n    fmt.Printf(\"%13.10f\\n\", fa)\n}\n\nfunc main() {\n    var svd mat.SVD\n    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})\n    ok := svd.Factorize(a, mat.SVDFull)\n    if !ok {\n        log.Fatal(\"Something went wrong!\")\n    }\n    u := mat.NewDense(2, 2, nil)\n    svd.UTo(u)\n    fmt.Println(\"U:\")\n    matPrint(u)\n    values := svd.Values(nil)\n    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})\n    fmt.Println(\"\\nΣ:\")\n    matPrint(sigma)\n    vt := mat.NewDense(2, 2, nil)\n    svd.VTo(vt)\n    fmt.Println(\"\\nVT:\")\n    matPrint(vt)\n}\n", "Python": "from numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n"}
{"id": 50698, "name": "Sum of first n cubes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n"}
{"id": 50699, "name": "Test integerness", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n"}
{"id": 50700, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 50701, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 50702, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 50703, "name": "Death Star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n"}
{"id": 50704, "name": "Death Star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n"}
{"id": 50705, "name": "Lucky and even lucky numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n    for i := 0; i < luckySize; i++ {\n        luckyOdd[i] = i*2 + 1\n        luckyEven[i] = i*2 + 2\n    }\n}\n\nfunc filterLuckyOdd() {\n    for n := 2; n < len(luckyOdd); n++ {\n        m := luckyOdd[n-1]\n        end := (len(luckyOdd)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyOdd[j:], luckyOdd[j+1:])\n            luckyOdd = luckyOdd[:len(luckyOdd)-1]\n        }\n    }\n}\n\nfunc filterLuckyEven() {\n    for n := 2; n < len(luckyEven); n++ {\n        m := luckyEven[n-1]\n        end := (len(luckyEven)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyEven[j:], luckyEven[j+1:])\n            luckyEven = luckyEven[:len(luckyEven)-1]\n        }\n    }\n}\n\nfunc printSingle(j int, odd bool) error {\n    if odd {\n        if j >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n    } else {\n        if j >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n    }\n    return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n    if odd {\n        if k >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyOdd[j-1 : k])\n    } else {\n        if k >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyEven[j-1 : k])\n    }\n    return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n    var r []int\n    if odd {\n        max := luckyOdd[len(luckyOdd)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyOdd {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    } else {\n        max := luckyEven[len(luckyEven)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyEven {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    }\n    return nil\n}\n\nfunc main() {\n    nargs := len(os.Args)\n    if nargs < 2 || nargs > 4 {\n        log.Fatal(\"there must be between 1 and 3 command line arguments\")\n    }\n    filterLuckyOdd()\n    filterLuckyEven()\n    j, err := strconv.Atoi(os.Args[1])\n    if err != nil || j < 1 {\n        log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n    }\n    if nargs == 2 {\n        if err := printSingle(j, true); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    if nargs == 3 {\n        k, err := strconv.Atoi(os.Args[2])\n        if err != nil {\n            log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n        }\n        if k >= 0 {\n            if j > k {\n                log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n            }\n            if err := printRange(j, k, true); err != nil {\n                log.Fatal(err)\n            }\n        } else {\n            l := -k\n            if j > l {\n                log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n            }\n            if err := printBetween(j, l, true); err != nil {\n                log.Fatal(err)\n            }\n        }\n        return\n    }\n\n    var odd bool\n    switch lucky := strings.ToLower(os.Args[3]); lucky {\n    case \"lucky\":\n        odd = true\n    case \"evenlucky\":\n        odd = false\n    default:\n        log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n    }\n    if os.Args[2] == \",\" {\n        if err := printSingle(j, odd); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    k, err := strconv.Atoi(os.Args[2])\n    if err != nil {\n        log.Fatal(\"second argument must be an integer or a comma\")\n    }\n    if k >= 0 {\n        if j > k {\n            log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n        }\n        if err := printRange(j, k, odd); err != nil {\n            log.Fatal(err)\n        }\n    } else {\n        l := -k\n        if j > l {\n            log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n        }\n        if err := printBetween(j, l, odd); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n"}
{"id": 50706, "name": "Simple database", "Go": "package main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n    \"unicode\"\n)\n\n\n\ntype Item struct {\n    Stamp time.Time\n    Name  string\n    Tags  []string `json:\",omitempty\"`\n    Notes string   `json:\",omitempty\"`\n}\n\n\nfunc (i *Item) String() string {\n    s := i.Stamp.Format(time.ANSIC) + \"\\n  Name:  \" + i.Name\n    if len(i.Tags) > 0 {\n        s = fmt.Sprintf(\"%s\\n  Tags:  %v\", s, i.Tags)\n    }\n    if i.Notes > \"\" {\n        s += \"\\n  Notes: \" + i.Notes\n    }\n    return s\n}\n\n\ntype db []*Item\n\n\nfunc (d db) Len() int           { return len(d) }\nfunc (d db) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }\nfunc (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) }\n\n\nconst fn = \"sdb.json\"\n\nfunc main() {\n    if len(os.Args) == 1 {\n        latest()\n        return\n    }\n    switch os.Args[1] {\n    case \"add\":\n        add()\n    case \"latest\":\n        latest()\n    case \"tags\":\n        tags()\n    case \"all\":\n        all()\n    case \"help\":\n        help()\n    default:\n        usage(\"unrecognized command\")\n    }\n}\n\nfunc usage(err string) {\n    if err > \"\" {\n        fmt.Println(err)\n    }\n    fmt.Println(`usage:  sdb [command] [data]\n    where command is one of add, latest, tags, all, or help.`)\n}\n\nfunc help() {\n    usage(\"\")\n    fmt.Println(`\nCommands must be in lower case.\nIf no command is specified, the default command is latest.\n\nLatest prints the latest item.\nAll prints all items in chronological order.\nTags prints the lastest item for each tag.\nHelp prints this message.\n\nAdd adds data as a new record.  The format is,\n\n  name [tags] [notes]\n\nName is the name of the item and is required for the add command.\n\nTags are optional.  A tag is a single word.\nA single tag can be specified without enclosing brackets.\nMultiple tags can be specified by enclosing them in square brackets.\n\nText remaining after tags is taken as notes.  Notes do not have to be\nenclosed in quotes or brackets.  The brackets above are only showing\nthat notes are optional.\n\nQuotes may be useful however--as recognized by your operating system shell\nor command line--to allow entry of arbitrary text.  In particular, quotes\nor escape characters may be needed to prevent the shell from trying to\ninterpret brackets or other special characters.\n\nExamples:\nsdb add Bookends                        \nsdb add Bookends rock my favorite       \nsdb add Bookends [rock folk]            \nsdb add Bookends [] \"Simon & Garfunkel\" \nsdb add \"Simon&Garfunkel [artist]\"      \n    \nAs shown in the last example, if you use features of your shell to pass\nall data as a single string, the item name and tags will still be identified\nby separating whitespace.\n    \nThe database is stored in JSON format in the file \"sdb.json\"\n`)  \n}\n\n\nfunc load() (db, bool) {\n    d, f, ok := open()\n    if ok {\n        f.Close()\n        if len(d) == 0 {\n            fmt.Println(\"no items\")\n            ok = false\n        }\n    }\n    return d, ok\n}\n\n\nfunc open() (d db, f *os.File, ok bool) {\n    var err error\n    f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)\n    if err != nil {\n        fmt.Println(\"cant open??\")\n        fmt.Println(err)\n        return\n    }\n    jd := json.NewDecoder(f)\n    err = jd.Decode(&d)\n    \n    if err != nil && err != io.EOF {\n        fmt.Println(err)\n        f.Close()\n        return\n    }\n    ok = true\n    return\n}\n\n\nfunc latest() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    fmt.Println(d[len(d)-1])\n}\n\n\nfunc all() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    for _, i := range d {\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(i)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n\n\nfunc tags() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    \n    \n    \n    latest := make(map[string]*Item)\n    for _, item := range d {\n        for _, tag := range item.Tags {\n            li, ok := latest[tag]\n            if !ok || item.Stamp.After(li.Stamp) {\n                latest[tag] = item\n            }\n        }\n    }\n    \n    \n    type itemTags struct {\n        item *Item\n        tags []string\n    }\n    inv := make(map[*Item][]string)\n    for tag, item := range latest {\n        inv[item] = append(inv[item], tag)\n    }\n    \n    li := make(db, len(inv))\n    i := 0\n    for item := range inv {\n        li[i] = item\n        i++\n    }\n    sort.Sort(li)\n    \n    for _, item := range li {\n        tags := inv[item]\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(\"Latest item with tags\", tags)\n        fmt.Println(item)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n    \n\nfunc add() { \n    if len(os.Args) < 3 {\n        usage(\"add command requires data\")\n        return\n    } else if len(os.Args) == 3 {\n        add1()\n    } else {\n        add4()\n    }\n}   \n\n\nfunc add1() {\n    data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace)\n    if data == \"\" {\n        \n        usage(\"invalid name\")\n        return \n    }\n    sep := strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(data, nil, \"\")\n        return\n    }\n    name := data[:sep]\n    data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace)\n    if data == \"\" {\n        \n        addItem(name, nil, \"\")\n        return\n    }\n    if data[0] == '[' {\n        sep = strings.Index(data, \"]\")\n        if sep < 0 {\n            \n            addItem(name, strings.Fields(data[1:]), \"\")\n        } else {\n            \n            addItem(name, strings.Fields(data[1:sep]),\n                strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n        }\n        return\n    }\n    sep = strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(name, []string{data}, \"\")\n    } else {\n        \n        addItem(name, []string{data[:sep]},\n            strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n    }\n}\n\n\nfunc add4() {\n    name := os.Args[2]\n    tag1 := os.Args[3]\n    if tag1[0] != '[' {\n        \n        addItem(name, []string{tag1}, strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    if tag1[len(tag1)-1] == ']' {\n        \n        addItem(name, strings.Fields(tag1[1:len(tag1)-1]),\n            strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    \n    var tags []string\n    if tag1 > \"[\" {\n        tags = []string{tag1[1:]}\n    }\n    for x, tag := range os.Args[4:] {\n        if tag[len(tag)-1] != ']' {\n            tags = append(tags, tag)\n        } else {\n            \n            if tag > \"]\" {\n                tags = append(tags, tag[:len(tag)-1])\n            }\n            addItem(name, tags, strings.Join(os.Args[5+x:], \" \"))\n            return\n        }\n    }\n    \n    addItem(name, tags, \"\")\n}\n\n\nfunc addItem(name string, tags []string, notes string) {\n    db, f, ok := open()\n    if !ok {\n        return\n    }\n    defer f.Close()\n    \n    db = append(db, &Item{time.Now(), name, tags, notes})\n    sort.Sort(db)\n    js, err := json.MarshalIndent(db, \"\", \"  \")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if _, err = f.Seek(0, 0); err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Truncate(0)\n    if _, err = f.Write(js); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n"}
{"id": 50707, "name": "Total circles area", "Go": "package main\n\nimport (\n        \"flag\"\n        \"fmt\"\n        \"math\"\n        \"runtime\"\n        \"sort\"\n)\n\n\n\n\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n        \n        return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n        return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n        return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n        nw := c.ContainsPt(r.NW())\n        ne := c.ContainsPt(r.NE())\n        sw := c.ContainsPt(r.SW())\n        se := c.ContainsPt(r.SE())\n        return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64)  { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64)  { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64          { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n        return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n        return r.X1 <= x && x < r.X2 &&\n                r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { \n        return r.ContainsPt(c.North()) ||\n                r.ContainsPt(c.South()) ||\n                r.ContainsPt(c.West()) ||\n                r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n        return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n        Δx, Δy := x2-x1, y2-y1\n        return (Δx * Δx) + (Δy * Δy)\n}\n\ntype CircleSet []Circle\n\n\nfunc (s CircleSet) Len() int           { return len(s) }\nfunc (s CircleSet) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n        s := *sp\n        sort.Sort(s)\n        for i := 0; i < len(s); i++ {\n                for j := i + 1; j < len(s); {\n                        if s[i].ContainsC(s[j]) {\n                                s[j], s[len(s)-1] = s[len(s)-1], s[j]\n                                s = s[:len(s)-1]\n                        } else {\n                                j++\n                        }\n                }\n        }\n        *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n        x1 := s[0].X - s[0].R\n        x2 := s[0].X + s[0].R\n        y1 := s[0].Y - s[0].R\n        y2 := s[0].Y + s[0].R\n        for _, c := range s[1:] {\n                x1 = math.Min(x1, c.X-c.R)\n                x2 = math.Max(x2, c.X+c.R)\n                y1 = math.Min(y1, c.Y-c.R)\n                y2 = math.Max(y2, c.Y+c.R)\n        }\n        return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(ε float64) (min, max float64) {\n        sort.Sort(s)\n        stop := make(chan bool)\n        inside := make(chan Rect)\n        outside := make(chan Rect)\n        unknown := make(chan Rect, 5e7) \n\n        for i := 0; i < nWorkers; i++ {\n                go s.worker(stop, unknown, inside, outside)\n        }\n        r := s.Bounds()\n        max = r.Area()\n        unknown <- r\n        for max-min > ε {\n                select {\n                case r = <-inside:\n                        min += r.Area()\n                case r = <-outside:\n                        max -= r.Area()\n                }\n        }\n        close(stop)\n        return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n        for {\n                select {\n                case <-stop:\n                        return\n                case r := <-unk:\n                        inside, outside := s.CategorizeR(r)\n                        switch {\n                        case inside:\n                                in <- r\n                        case outside:\n                                out <- r\n                        default:\n                                \n                                midX, midY := r.Centre()\n                                unk <- Rect{r.X1, r.Y1, midX, midY}\n                                unk <- Rect{midX, r.Y1, r.X2, midY}\n                                unk <- Rect{r.X1, midY, midX, r.Y2}\n                                unk <- Rect{midX, midY, r.X2, r.Y2}\n                        }\n                }\n        }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n        anyCorner := false\n        for _, c := range s {\n                full, corner := c.ContainsR(r)\n                if full {\n                        return true, false \n                }\n                anyCorner = anyCorner || corner\n        }\n        if anyCorner {\n                return false, false \n        }\n        for _, c := range s {\n                if r.ContainsPC(c) {\n                        return false, false \n                }\n        }\n        return false, true \n}\n\nfunc main() {\n        flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n        maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n        flag.Parse()\n\n        if *maxproc > 0 {\n                runtime.GOMAXPROCS(*maxproc)\n        } else {\n                *maxproc = runtime.GOMAXPROCS(0)\n        }\n\n        circles := CircleSet{\n                NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n                NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n                NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n                NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n                NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n                NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n                NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n                NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n                NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n                NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n                NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n                NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n                NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n                NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n                NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n                NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n                NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n                NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n                NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n                NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n                NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n                NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n                NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n                NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n                NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n        }\n        fmt.Println(\"Starting with\", len(circles), \"circles.\")\n        circles.RemoveContainedC()\n        fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n        fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n        const ε = 0.0001\n        min, max := circles.UnionArea(ε)\n        avg := (min + max) / 2.0\n        rng := max - min\n        fmt.Printf(\"Area = %v±%v\\n\", avg, rng)\n        fmt.Printf(\"Area ≈ %.*f\\n\", 5, avg)\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 50708, "name": "Total circles area", "Go": "package main\n\nimport (\n        \"flag\"\n        \"fmt\"\n        \"math\"\n        \"runtime\"\n        \"sort\"\n)\n\n\n\n\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n        \n        return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n        return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n        return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n        nw := c.ContainsPt(r.NW())\n        ne := c.ContainsPt(r.NE())\n        sw := c.ContainsPt(r.SW())\n        se := c.ContainsPt(r.SE())\n        return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64)  { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64)  { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64          { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n        return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n        return r.X1 <= x && x < r.X2 &&\n                r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { \n        return r.ContainsPt(c.North()) ||\n                r.ContainsPt(c.South()) ||\n                r.ContainsPt(c.West()) ||\n                r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n        return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n        Δx, Δy := x2-x1, y2-y1\n        return (Δx * Δx) + (Δy * Δy)\n}\n\ntype CircleSet []Circle\n\n\nfunc (s CircleSet) Len() int           { return len(s) }\nfunc (s CircleSet) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n        s := *sp\n        sort.Sort(s)\n        for i := 0; i < len(s); i++ {\n                for j := i + 1; j < len(s); {\n                        if s[i].ContainsC(s[j]) {\n                                s[j], s[len(s)-1] = s[len(s)-1], s[j]\n                                s = s[:len(s)-1]\n                        } else {\n                                j++\n                        }\n                }\n        }\n        *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n        x1 := s[0].X - s[0].R\n        x2 := s[0].X + s[0].R\n        y1 := s[0].Y - s[0].R\n        y2 := s[0].Y + s[0].R\n        for _, c := range s[1:] {\n                x1 = math.Min(x1, c.X-c.R)\n                x2 = math.Max(x2, c.X+c.R)\n                y1 = math.Min(y1, c.Y-c.R)\n                y2 = math.Max(y2, c.Y+c.R)\n        }\n        return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(ε float64) (min, max float64) {\n        sort.Sort(s)\n        stop := make(chan bool)\n        inside := make(chan Rect)\n        outside := make(chan Rect)\n        unknown := make(chan Rect, 5e7) \n\n        for i := 0; i < nWorkers; i++ {\n                go s.worker(stop, unknown, inside, outside)\n        }\n        r := s.Bounds()\n        max = r.Area()\n        unknown <- r\n        for max-min > ε {\n                select {\n                case r = <-inside:\n                        min += r.Area()\n                case r = <-outside:\n                        max -= r.Area()\n                }\n        }\n        close(stop)\n        return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n        for {\n                select {\n                case <-stop:\n                        return\n                case r := <-unk:\n                        inside, outside := s.CategorizeR(r)\n                        switch {\n                        case inside:\n                                in <- r\n                        case outside:\n                                out <- r\n                        default:\n                                \n                                midX, midY := r.Centre()\n                                unk <- Rect{r.X1, r.Y1, midX, midY}\n                                unk <- Rect{midX, r.Y1, r.X2, midY}\n                                unk <- Rect{r.X1, midY, midX, r.Y2}\n                                unk <- Rect{midX, midY, r.X2, r.Y2}\n                        }\n                }\n        }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n        anyCorner := false\n        for _, c := range s {\n                full, corner := c.ContainsR(r)\n                if full {\n                        return true, false \n                }\n                anyCorner = anyCorner || corner\n        }\n        if anyCorner {\n                return false, false \n        }\n        for _, c := range s {\n                if r.ContainsPC(c) {\n                        return false, false \n                }\n        }\n        return false, true \n}\n\nfunc main() {\n        flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n        maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n        flag.Parse()\n\n        if *maxproc > 0 {\n                runtime.GOMAXPROCS(*maxproc)\n        } else {\n                *maxproc = runtime.GOMAXPROCS(0)\n        }\n\n        circles := CircleSet{\n                NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n                NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n                NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n                NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n                NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n                NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n                NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n                NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n                NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n                NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n                NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n                NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n                NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n                NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n                NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n                NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n                NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n                NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n                NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n                NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n                NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n                NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n                NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n                NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n                NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n        }\n        fmt.Println(\"Starting with\", len(circles), \"circles.\")\n        circles.RemoveContainedC()\n        fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n        fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n        const ε = 0.0001\n        min, max := circles.UnionArea(ε)\n        avg := (min + max) / 2.0\n        rng := max - min\n        fmt.Printf(\"Area = %v±%v\\n\", avg, rng)\n        fmt.Printf(\"Area ≈ %.*f\\n\", 5, avg)\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 50709, "name": "Total circles area", "Go": "package main\n\nimport (\n        \"flag\"\n        \"fmt\"\n        \"math\"\n        \"runtime\"\n        \"sort\"\n)\n\n\n\n\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n        \n        return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n        return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n        return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n        nw := c.ContainsPt(r.NW())\n        ne := c.ContainsPt(r.NE())\n        sw := c.ContainsPt(r.SW())\n        se := c.ContainsPt(r.SE())\n        return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64)  { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64)  { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64          { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n        return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n        return r.X1 <= x && x < r.X2 &&\n                r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { \n        return r.ContainsPt(c.North()) ||\n                r.ContainsPt(c.South()) ||\n                r.ContainsPt(c.West()) ||\n                r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n        return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n        Δx, Δy := x2-x1, y2-y1\n        return (Δx * Δx) + (Δy * Δy)\n}\n\ntype CircleSet []Circle\n\n\nfunc (s CircleSet) Len() int           { return len(s) }\nfunc (s CircleSet) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n        s := *sp\n        sort.Sort(s)\n        for i := 0; i < len(s); i++ {\n                for j := i + 1; j < len(s); {\n                        if s[i].ContainsC(s[j]) {\n                                s[j], s[len(s)-1] = s[len(s)-1], s[j]\n                                s = s[:len(s)-1]\n                        } else {\n                                j++\n                        }\n                }\n        }\n        *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n        x1 := s[0].X - s[0].R\n        x2 := s[0].X + s[0].R\n        y1 := s[0].Y - s[0].R\n        y2 := s[0].Y + s[0].R\n        for _, c := range s[1:] {\n                x1 = math.Min(x1, c.X-c.R)\n                x2 = math.Max(x2, c.X+c.R)\n                y1 = math.Min(y1, c.Y-c.R)\n                y2 = math.Max(y2, c.Y+c.R)\n        }\n        return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(ε float64) (min, max float64) {\n        sort.Sort(s)\n        stop := make(chan bool)\n        inside := make(chan Rect)\n        outside := make(chan Rect)\n        unknown := make(chan Rect, 5e7) \n\n        for i := 0; i < nWorkers; i++ {\n                go s.worker(stop, unknown, inside, outside)\n        }\n        r := s.Bounds()\n        max = r.Area()\n        unknown <- r\n        for max-min > ε {\n                select {\n                case r = <-inside:\n                        min += r.Area()\n                case r = <-outside:\n                        max -= r.Area()\n                }\n        }\n        close(stop)\n        return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n        for {\n                select {\n                case <-stop:\n                        return\n                case r := <-unk:\n                        inside, outside := s.CategorizeR(r)\n                        switch {\n                        case inside:\n                                in <- r\n                        case outside:\n                                out <- r\n                        default:\n                                \n                                midX, midY := r.Centre()\n                                unk <- Rect{r.X1, r.Y1, midX, midY}\n                                unk <- Rect{midX, r.Y1, r.X2, midY}\n                                unk <- Rect{r.X1, midY, midX, r.Y2}\n                                unk <- Rect{midX, midY, r.X2, r.Y2}\n                        }\n                }\n        }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n        anyCorner := false\n        for _, c := range s {\n                full, corner := c.ContainsR(r)\n                if full {\n                        return true, false \n                }\n                anyCorner = anyCorner || corner\n        }\n        if anyCorner {\n                return false, false \n        }\n        for _, c := range s {\n                if r.ContainsPC(c) {\n                        return false, false \n                }\n        }\n        return false, true \n}\n\nfunc main() {\n        flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n        maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n        flag.Parse()\n\n        if *maxproc > 0 {\n                runtime.GOMAXPROCS(*maxproc)\n        } else {\n                *maxproc = runtime.GOMAXPROCS(0)\n        }\n\n        circles := CircleSet{\n                NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n                NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n                NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n                NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n                NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n                NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n                NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n                NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n                NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n                NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n                NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n                NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n                NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n                NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n                NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n                NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n                NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n                NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n                NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n                NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n                NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n                NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n                NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n                NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n                NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n        }\n        fmt.Println(\"Starting with\", len(circles), \"circles.\")\n        circles.RemoveContainedC()\n        fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n        fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n        const ε = 0.0001\n        min, max := circles.UnionArea(ε)\n        avg := (min + max) / 2.0\n        rng := max - min\n        fmt.Printf(\"Area = %v±%v\\n\", avg, rng)\n        fmt.Printf(\"Area ≈ %.*f\\n\", 5, avg)\n}\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 50710, "name": "Hough transform", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "from math import hypot, pi, cos, sin\nfrom PIL import Image\n\n\ndef hough(im, ntx=460, mry=360):\n    \"Calculate Hough transform.\"\n    pim = im.load()\n    nimx, mimy = im.size\n    mry = int(mry/2)*2          \n    him = Image.new(\"L\", (ntx, mry), 255)\n    phim = him.load()\n\n    rmax = hypot(nimx, mimy)\n    dr = rmax / (mry/2)\n    dth = pi / ntx\n\n    for jx in xrange(nimx):\n        for iy in xrange(mimy):\n            col = pim[jx, iy]\n            if col == 255: continue\n            for jtx in xrange(ntx):\n                th = dth * jtx\n                r = jx*cos(th) + iy*sin(th)\n                iry = mry/2 + int(r/dr+0.5)\n                phim[jtx, iry] -= 1\n    return him\n\n\ndef test():\n    \"Test Hough transform with pentagon.\"\n    im = Image.open(\"pentagon.png\").convert(\"L\")\n    him = hough(im)\n    him.save(\"ho5.bmp\")\n\n\nif __name__ == \"__main__\": test()\n"}
{"id": 50711, "name": "Verify distribution uniformity_Chi-squared test", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n"}
{"id": 50712, "name": "Welch's t-test", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 50713, "name": "Welch's t-test", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n"}
{"id": 50714, "name": "Topological sort_Extracted top item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n"}
{"id": 50715, "name": "Topological sort_Extracted top item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n"}
{"id": 50716, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 50717, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 50718, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 50719, "name": "Superpermutation minimisation", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n"}
{"id": 50720, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n"}
{"id": 50721, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 50722, "name": "Summarize and say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n"}
{"id": 50723, "name": "Summarize and say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n"}
{"id": 50724, "name": "Spelling of ordinal numbers", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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"}
{"id": 50725, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 50726, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 50727, "name": "Addition chains", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n"}
{"id": 50728, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 50729, "name": "Sparkline in unicode", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n"}
{"id": 50730, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 50731, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 50732, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 50733, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n"}
{"id": 50734, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 50735, "name": "Simulate input_Mouse", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n", "Python": "import ctypes\n\ndef click():\n    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    \n    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    \n\nclick()\n"}
{"id": 50736, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 50737, "name": "Sunflower fractal", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n"}
{"id": 50738, "name": "Vogel's approximation method", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n"}
{"id": 50739, "name": "Air mass", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    RE  = 6371000 \n    DD  = 0.001   \n    FIN = 1e7     \n)\n\n\nfunc rho(a float64) float64 { return math.Exp(-a / 8500) }\n\n\nfunc radians(degrees float64) float64 { return degrees * math.Pi / 180 }\n\n\n\n\nfunc height(a, z, d float64) float64 {\n    aa := RE + a\n    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))\n    return hh - RE\n}\n\n\nfunc columnDensity(a, z float64) float64 {\n    sum := 0.0\n    d := 0.0\n    for d < FIN {\n        delta := math.Max(DD, DD*d) \n        sum += rho(height(a, z, d+0.5*delta)) * delta\n        d += delta\n    }\n    return sum\n}\n\nfunc airmass(a, z float64) float64 {\n    return columnDensity(a, z) / columnDensity(a, 0)\n}\n\nfunc main() {\n    fmt.Println(\"Angle     0 m              13700 m\")\n    fmt.Println(\"------------------------------------\")\n    for z := 0; z <= 90; z += 5 {\n        fz := float64(z)\n        fmt.Printf(\"%2d      %11.8f      %11.8f\\n\", z, airmass(0, fz), airmass(13700, fz))\n    }\n}\n", "Python": "\n\nfrom math import sqrt, cos, exp\n\nDEG = 0.017453292519943295769236907684886127134  \nRE = 6371000                                     \ndd = 0.001      \nFIN = 10000000  \n \ndef rho(a):\n    \n    return exp(-a / 8500.0)\n \ndef height(a, z, d):\n     \n    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE\n \ndef column_density(a, z):\n    \n    dsum, d = 0.0, 0.0\n    while d < FIN:\n        delta = max(dd, (dd)*d)  \n        dsum += rho(height(a, z, d + 0.5 * delta)) * delta\n        d += delta\n    return dsum\n\ndef airmass(a, z):\n    return column_density(a, z) / column_density(a, 0)\n\nprint('Angle           0 m          13700 m\\n', '-' * 36)\nfor z in range(0, 91, 5):\n    print(f\"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}\")\n"}
{"id": 50740, "name": "Formal power series", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype fps interface {\n    extract(int) float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc one() fps {\n    return &oneFps{}\n}\n\nfunc add(s1, s2 fps) fps {\n    return &sum{s1: s1, s2: s2}\n}\n\nfunc sub(s1, s2 fps) fps {\n    return &diff{s1: s1, s2: s2}\n}\n\nfunc mul(s1, s2 fps) fps {\n    return &prod{s1: s1, s2: s2}\n}\n\nfunc div(s1, s2 fps) fps {\n    return &quo{s1: s1, s2: s2}\n}\n\nfunc differentiate(s1 fps) fps {\n    return &deriv{s1: s1}\n}\n\nfunc integrate(s1 fps) fps {\n    return &integ{s1: s1}\n}\n\n\n\n\n\n\n\nfunc sinCos() (fps, fps) {\n    sin := &integ{}\n    cos := sub(one(), integrate(sin))\n    sin.s1 = cos\n    return sin, cos\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype oneFps struct{}\n\n\n\nfunc (*oneFps) extract(n int) float64 {\n    if n == 0 {\n        return 1\n    }\n    return 0\n}\n\n\n\ntype sum struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *sum) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\n\n\n\n\ntype diff struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *diff) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\ntype prod struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *prod) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 0; k <= i; k++ {\n            c += s.s1.extract(k) * s.s1.extract(n-k)\n        }\n        s.s = append(s.s, c)\n    }\n    return s.s[n]\n}\n\n\n\ntype quo struct {\n    s1, s2 fps\n    inv    float64   \n    c      []float64 \n    s      []float64\n}\n\n\n\n\nfunc (s *quo) extract(n int) float64 {\n    switch {\n    case len(s.s) > 0:\n    case !math.IsInf(s.inv, 1):\n        a0 := s.s2.extract(0)\n        s.inv = 1 / a0\n        if a0 != 0 {\n            break\n        }\n        fallthrough\n    default:\n        return math.NaN()\n    }\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 1; k <= i; k++ {\n            c += s.s2.extract(k) * s.c[n-k]\n        }\n        c = s.s1.extract(i) - c*s.inv\n        s.c = append(s.c, c)\n        s.s = append(s.s, c*s.inv)\n    }\n    return s.s[n]\n}\n\n\n\n\ntype deriv struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *deriv) extract(n int) float64 {\n    for i := len(s.s); i <= n; {\n        i++\n        s.s = append(s.s, float64(i)*s.s1.extract(i))\n    }\n    return s.s[n]\n}\n\ntype integ struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *integ) extract(n int) float64 {\n    if n == 0 {\n        return 0 \n    }\n    \n    for i := len(s.s) + 1; i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i-1)/float64(i))\n    }\n    return s.s[n-1]\n}\n\n\nfunc main() {\n    \n    partialSeries := func(f fps) (s string) {\n        for i := 0; i < 6; i++ {\n            s = fmt.Sprintf(\"%s %8.5f \", s, f.extract(i))\n        }\n        return\n    }\n    sin, cos := sinCos()\n    fmt.Println(\"sin:\", partialSeries(sin))\n    fmt.Println(\"cos:\", partialSeries(cos))\n}\n", "Python": "\n\nfrom itertools import islice\nfrom fractions import Fraction\nfrom functools import reduce\ntry:\n    from itertools import izip as zip \nexcept:\n    pass\n\ndef head(n):\n    \n    return lambda seq: islice(seq, n)\n\ndef pipe(gen, *cmds):\n    \n    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)\n\ndef sinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    zero = 0\n    yield zero\n    while True:\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\n        sign = -sign\n        n +=1\n        fac *= n\n        yield zero\ndef cosinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    yield Fraction(1,fac)\n    zero = 0\n    while True:\n        n +=1\n        fac *= n\n        yield zero\n        sign = -sign\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\ndef pluspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield sum(elements)\ndef minuspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield elements[0] - sum(elements[1:])\ndef mulpower(fgen,ggen):\n    'From: http://en.wikipedia.org/wiki/Power_series\n    a,b = [],[]\n    for f,g in zip(fgen, ggen):\n        a.append(f)\n        b.append(g)\n        yield sum(f*g for f,g in zip(a, reversed(b)))\ndef constpower(n):\n    yield n\n    while True:\n        yield 0\ndef diffpower(gen):\n    'differentiatiate power series'\n    next(gen)\n    for n, an in enumerate(gen, start=1):\n        yield an*n\ndef intgpower(k=0):\n    'integrate power series with constant k'\n    def _intgpower(gen):\n        yield k\n        for n, an in enumerate(gen, start=1):\n            yield an * Fraction(1,n)\n    return _intgpower\n\n\nprint(\"cosine\")\nc = list(pipe(cosinepower(), head(10)))\nprint(c)\nprint(\"sine\")\ns = list(pipe(sinepower(), head(10)))\nprint(s)\n\nintegc = list(pipe(cosinepower(),intgpower(0), head(10)))\n\nintegs1 = list(minuspower(pipe(constpower(1), head(10)),\n                          pipe(sinepower(),intgpower(0), head(10))))\n\nassert s == integc, \"The integral of cos should be sin\"\nassert c == integs1, \"1 minus the integral of sin should be cos\"\n"}
{"id": 50741, "name": "Formal power series", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype fps interface {\n    extract(int) float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc one() fps {\n    return &oneFps{}\n}\n\nfunc add(s1, s2 fps) fps {\n    return &sum{s1: s1, s2: s2}\n}\n\nfunc sub(s1, s2 fps) fps {\n    return &diff{s1: s1, s2: s2}\n}\n\nfunc mul(s1, s2 fps) fps {\n    return &prod{s1: s1, s2: s2}\n}\n\nfunc div(s1, s2 fps) fps {\n    return &quo{s1: s1, s2: s2}\n}\n\nfunc differentiate(s1 fps) fps {\n    return &deriv{s1: s1}\n}\n\nfunc integrate(s1 fps) fps {\n    return &integ{s1: s1}\n}\n\n\n\n\n\n\n\nfunc sinCos() (fps, fps) {\n    sin := &integ{}\n    cos := sub(one(), integrate(sin))\n    sin.s1 = cos\n    return sin, cos\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype oneFps struct{}\n\n\n\nfunc (*oneFps) extract(n int) float64 {\n    if n == 0 {\n        return 1\n    }\n    return 0\n}\n\n\n\ntype sum struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *sum) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\n\n\n\n\ntype diff struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *diff) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\ntype prod struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *prod) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 0; k <= i; k++ {\n            c += s.s1.extract(k) * s.s1.extract(n-k)\n        }\n        s.s = append(s.s, c)\n    }\n    return s.s[n]\n}\n\n\n\ntype quo struct {\n    s1, s2 fps\n    inv    float64   \n    c      []float64 \n    s      []float64\n}\n\n\n\n\nfunc (s *quo) extract(n int) float64 {\n    switch {\n    case len(s.s) > 0:\n    case !math.IsInf(s.inv, 1):\n        a0 := s.s2.extract(0)\n        s.inv = 1 / a0\n        if a0 != 0 {\n            break\n        }\n        fallthrough\n    default:\n        return math.NaN()\n    }\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 1; k <= i; k++ {\n            c += s.s2.extract(k) * s.c[n-k]\n        }\n        c = s.s1.extract(i) - c*s.inv\n        s.c = append(s.c, c)\n        s.s = append(s.s, c*s.inv)\n    }\n    return s.s[n]\n}\n\n\n\n\ntype deriv struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *deriv) extract(n int) float64 {\n    for i := len(s.s); i <= n; {\n        i++\n        s.s = append(s.s, float64(i)*s.s1.extract(i))\n    }\n    return s.s[n]\n}\n\ntype integ struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *integ) extract(n int) float64 {\n    if n == 0 {\n        return 0 \n    }\n    \n    for i := len(s.s) + 1; i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i-1)/float64(i))\n    }\n    return s.s[n-1]\n}\n\n\nfunc main() {\n    \n    partialSeries := func(f fps) (s string) {\n        for i := 0; i < 6; i++ {\n            s = fmt.Sprintf(\"%s %8.5f \", s, f.extract(i))\n        }\n        return\n    }\n    sin, cos := sinCos()\n    fmt.Println(\"sin:\", partialSeries(sin))\n    fmt.Println(\"cos:\", partialSeries(cos))\n}\n", "Python": "\n\nfrom itertools import islice\nfrom fractions import Fraction\nfrom functools import reduce\ntry:\n    from itertools import izip as zip \nexcept:\n    pass\n\ndef head(n):\n    \n    return lambda seq: islice(seq, n)\n\ndef pipe(gen, *cmds):\n    \n    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)\n\ndef sinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    zero = 0\n    yield zero\n    while True:\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\n        sign = -sign\n        n +=1\n        fac *= n\n        yield zero\ndef cosinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    yield Fraction(1,fac)\n    zero = 0\n    while True:\n        n +=1\n        fac *= n\n        yield zero\n        sign = -sign\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\ndef pluspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield sum(elements)\ndef minuspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield elements[0] - sum(elements[1:])\ndef mulpower(fgen,ggen):\n    'From: http://en.wikipedia.org/wiki/Power_series\n    a,b = [],[]\n    for f,g in zip(fgen, ggen):\n        a.append(f)\n        b.append(g)\n        yield sum(f*g for f,g in zip(a, reversed(b)))\ndef constpower(n):\n    yield n\n    while True:\n        yield 0\ndef diffpower(gen):\n    'differentiatiate power series'\n    next(gen)\n    for n, an in enumerate(gen, start=1):\n        yield an*n\ndef intgpower(k=0):\n    'integrate power series with constant k'\n    def _intgpower(gen):\n        yield k\n        for n, an in enumerate(gen, start=1):\n            yield an * Fraction(1,n)\n    return _intgpower\n\n\nprint(\"cosine\")\nc = list(pipe(cosinepower(), head(10)))\nprint(c)\nprint(\"sine\")\ns = list(pipe(sinepower(), head(10)))\nprint(s)\n\nintegc = list(pipe(cosinepower(),intgpower(0), head(10)))\n\nintegs1 = list(minuspower(pipe(constpower(1), head(10)),\n                          pipe(sinepower(),intgpower(0), head(10))))\n\nassert s == integc, \"The integral of cos should be sin\"\nassert c == integs1, \"1 minus the integral of sin should be cos\"\n"}
{"id": 50742, "name": "Own digits power sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n    fmt.Println(\"Own digits power sums for N = 3 to 9 inclusive:\")\n    for n := 3; n < 10; n++ {\n        for d := 2; d < 10; d++ {\n            powers[d] *= d\n        }\n        i := int(math.Pow(10, float64(n-1)))\n        max := i * 10\n        lastDigit := 0\n        sum := 0\n        var digits []int\n        for i < max {\n            if lastDigit == 0 {\n                digits = rcu.Digits(i, 10)\n                sum = 0\n                for _, d := range digits {\n                    sum += powers[d]\n                }\n            } else if lastDigit == 1 {\n                sum++\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1]\n            }\n            if sum == i {\n                fmt.Println(i)\n                if lastDigit == 0 {\n                    fmt.Println(i + 1)\n                }\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if sum > i {\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if lastDigit < 9 {\n                i++\n                lastDigit++\n            } else {\n                i++\n                lastDigit = 0\n            }\n        }\n    }\n}\n", "Python": "\n\ndef isowndigitspowersum(integer):\n    \n    digits = [int(c) for c in str(integer)]\n    exponent = len(digits)\n    return sum(x ** exponent for x in digits) == integer\n\nprint(\"Own digits power sums for N = 3 to 9 inclusive:\")\nfor i in range(100, 1000000000):\n    if isowndigitspowersum(i):\n        print(i)\n"}
{"id": 50743, "name": "Compiler_virtual machine interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\nvar codeMap = map[string]code{\n    \"fetch\": fetch,\n    \"store\": store,\n    \"push\":  push,\n    \"add\":   add,\n    \"sub\":   sub,\n    \"mul\":   mul,\n    \"div\":   div,\n    \"mod\":   mod,\n    \"lt\":    lt,\n    \"gt\":    gt,\n    \"le\":    le,\n    \"ge\":    ge,\n    \"eq\":    eq,\n    \"ne\":    ne,\n    \"and\":   and,\n    \"or\":    or,\n    \"neg\":   neg,\n    \"not\":   not,\n    \"jmp\":   jmp,\n    \"jz\":    jz,\n    \"prtc\":  prtc,\n    \"prts\":  prts,\n    \"prti\":  prti,\n    \"halt\":  halt,\n}\n\nvar (\n    err        error\n    scanner    *bufio.Scanner\n    object     []code\n    stringPool []string\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int32 {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int32) bool {\n    if i != 0 {\n        return true\n    }\n    return false\n}\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\n\nfunc runVM(dataSize int) {\n    stack := make([]int32, dataSize+1)\n    pc := int32(0)\n    for {\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, stack[x])\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            ln := len(stack)\n            stack[x] = stack[ln-1]\n            stack = stack[:ln-1]\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, x)\n            pc += 4\n        case add:\n            ln := len(stack)\n            stack[ln-2] += stack[ln-1]\n            stack = stack[:ln-1]\n        case sub:\n            ln := len(stack)\n            stack[ln-2] -= stack[ln-1]\n            stack = stack[:ln-1]\n        case mul:\n            ln := len(stack)\n            stack[ln-2] *= stack[ln-1]\n            stack = stack[:ln-1]\n        case div:\n            ln := len(stack)\n            stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))\n            stack = stack[:ln-1]\n        case mod:\n            ln := len(stack)\n            stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))\n            stack = stack[:ln-1]\n        case lt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])\n            stack = stack[:ln-1]\n        case gt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])\n            stack = stack[:ln-1]\n        case le:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])\n            stack = stack[:ln-1]\n        case ge:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])\n            stack = stack[:ln-1]\n        case eq:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])\n            stack = stack[:ln-1]\n        case ne:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])\n            stack = stack[:ln-1]\n        case and:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case or:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case neg:\n            ln := len(stack)\n            stack[ln-1] = -stack[ln-1]\n        case not:\n            ln := len(stack)\n            stack[ln-1] = btoi(!itob(stack[ln-1]))\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            pc += x\n        case jz:\n            ln := len(stack)\n            v := stack[ln-1]\n            stack = stack[:ln-1]\n            if v != 0 {\n                pc += 4\n            } else {\n                x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n                pc += x\n            }\n        case prtc:\n            ln := len(stack)\n            fmt.Printf(\"%c\", stack[ln-1])\n            stack = stack[:ln-1]\n        case prts:\n            ln := len(stack)\n            fmt.Printf(\"%s\", stringPool[stack[ln-1]])\n            stack = stack[:ln-1]\n        case prti:\n            ln := len(stack)\n            fmt.Printf(\"%d\", stack[ln-1])\n            stack = stack[:ln-1]\n        case halt:\n            return\n        default:\n            reportError(fmt.Sprintf(\"Unknown opcode %d\\n\", op))\n        }\n    }\n}\n\nfunc translate(s string) string {\n    var d strings.Builder\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    return d.String()\n}\n\nfunc loadCode() int {\n    var dataSize int\n    firstLine := true\n    for scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        if len(line) == 0 {\n            if firstLine {\n                reportError(\"empty line\")\n            } else {\n                break\n            }\n        }\n        lineList := strings.Fields(line)\n        if firstLine {\n            dataSize, err = strconv.Atoi(lineList[1])\n            check(err)\n            nStrings, err := strconv.Atoi(lineList[3])\n            check(err)\n            for i := 0; i < nStrings; i++ {\n                scanner.Scan()\n                s := strings.Trim(scanner.Text(), \"\\\"\\n\")\n                stringPool = append(stringPool, translate(s))\n            }\n            firstLine = false\n            continue\n        }\n        offset, err := strconv.Atoi(lineList[0])\n        check(err)\n        instr := lineList[1]\n        opCode, ok := codeMap[instr]\n        if !ok {\n            reportError(fmt.Sprintf(\"Unknown instruction %s at %d\", instr, opCode))\n        }\n        emitByte(opCode)\n        switch opCode {\n        case jmp, jz:\n            p, err := strconv.Atoi(lineList[3])\n            check(err)\n            emitWord(p - offset - 1)\n        case push:\n            value, err := strconv.Atoi(lineList[2])\n            check(err)\n            emitWord(value)\n        case fetch, store:\n            value, err := strconv.Atoi(strings.Trim(lineList[2], \"[]\"))\n            check(err)\n            emitWord(value)\n        }\n    }\n    check(scanner.Err())\n    return dataSize\n}\n\nfunc main() {\n    codeGen, err := os.Open(\"codegen.txt\")\n    check(err)\n    defer codeGen.Close()\n    scanner = bufio.NewScanner(codeGen)\n    runVM(loadCode())\n}\n", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n"}
{"id": 50744, "name": "Compiler_virtual machine interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\nvar codeMap = map[string]code{\n    \"fetch\": fetch,\n    \"store\": store,\n    \"push\":  push,\n    \"add\":   add,\n    \"sub\":   sub,\n    \"mul\":   mul,\n    \"div\":   div,\n    \"mod\":   mod,\n    \"lt\":    lt,\n    \"gt\":    gt,\n    \"le\":    le,\n    \"ge\":    ge,\n    \"eq\":    eq,\n    \"ne\":    ne,\n    \"and\":   and,\n    \"or\":    or,\n    \"neg\":   neg,\n    \"not\":   not,\n    \"jmp\":   jmp,\n    \"jz\":    jz,\n    \"prtc\":  prtc,\n    \"prts\":  prts,\n    \"prti\":  prti,\n    \"halt\":  halt,\n}\n\nvar (\n    err        error\n    scanner    *bufio.Scanner\n    object     []code\n    stringPool []string\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int32 {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int32) bool {\n    if i != 0 {\n        return true\n    }\n    return false\n}\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\n\nfunc runVM(dataSize int) {\n    stack := make([]int32, dataSize+1)\n    pc := int32(0)\n    for {\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, stack[x])\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            ln := len(stack)\n            stack[x] = stack[ln-1]\n            stack = stack[:ln-1]\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, x)\n            pc += 4\n        case add:\n            ln := len(stack)\n            stack[ln-2] += stack[ln-1]\n            stack = stack[:ln-1]\n        case sub:\n            ln := len(stack)\n            stack[ln-2] -= stack[ln-1]\n            stack = stack[:ln-1]\n        case mul:\n            ln := len(stack)\n            stack[ln-2] *= stack[ln-1]\n            stack = stack[:ln-1]\n        case div:\n            ln := len(stack)\n            stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))\n            stack = stack[:ln-1]\n        case mod:\n            ln := len(stack)\n            stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))\n            stack = stack[:ln-1]\n        case lt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])\n            stack = stack[:ln-1]\n        case gt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])\n            stack = stack[:ln-1]\n        case le:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])\n            stack = stack[:ln-1]\n        case ge:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])\n            stack = stack[:ln-1]\n        case eq:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])\n            stack = stack[:ln-1]\n        case ne:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])\n            stack = stack[:ln-1]\n        case and:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case or:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case neg:\n            ln := len(stack)\n            stack[ln-1] = -stack[ln-1]\n        case not:\n            ln := len(stack)\n            stack[ln-1] = btoi(!itob(stack[ln-1]))\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            pc += x\n        case jz:\n            ln := len(stack)\n            v := stack[ln-1]\n            stack = stack[:ln-1]\n            if v != 0 {\n                pc += 4\n            } else {\n                x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n                pc += x\n            }\n        case prtc:\n            ln := len(stack)\n            fmt.Printf(\"%c\", stack[ln-1])\n            stack = stack[:ln-1]\n        case prts:\n            ln := len(stack)\n            fmt.Printf(\"%s\", stringPool[stack[ln-1]])\n            stack = stack[:ln-1]\n        case prti:\n            ln := len(stack)\n            fmt.Printf(\"%d\", stack[ln-1])\n            stack = stack[:ln-1]\n        case halt:\n            return\n        default:\n            reportError(fmt.Sprintf(\"Unknown opcode %d\\n\", op))\n        }\n    }\n}\n\nfunc translate(s string) string {\n    var d strings.Builder\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    return d.String()\n}\n\nfunc loadCode() int {\n    var dataSize int\n    firstLine := true\n    for scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        if len(line) == 0 {\n            if firstLine {\n                reportError(\"empty line\")\n            } else {\n                break\n            }\n        }\n        lineList := strings.Fields(line)\n        if firstLine {\n            dataSize, err = strconv.Atoi(lineList[1])\n            check(err)\n            nStrings, err := strconv.Atoi(lineList[3])\n            check(err)\n            for i := 0; i < nStrings; i++ {\n                scanner.Scan()\n                s := strings.Trim(scanner.Text(), \"\\\"\\n\")\n                stringPool = append(stringPool, translate(s))\n            }\n            firstLine = false\n            continue\n        }\n        offset, err := strconv.Atoi(lineList[0])\n        check(err)\n        instr := lineList[1]\n        opCode, ok := codeMap[instr]\n        if !ok {\n            reportError(fmt.Sprintf(\"Unknown instruction %s at %d\", instr, opCode))\n        }\n        emitByte(opCode)\n        switch opCode {\n        case jmp, jz:\n            p, err := strconv.Atoi(lineList[3])\n            check(err)\n            emitWord(p - offset - 1)\n        case push:\n            value, err := strconv.Atoi(lineList[2])\n            check(err)\n            emitWord(value)\n        case fetch, store:\n            value, err := strconv.Atoi(strings.Trim(lineList[2], \"[]\"))\n            check(err)\n            emitWord(value)\n        }\n    }\n    check(scanner.Err())\n    return dataSize\n}\n\nfunc main() {\n    codeGen, err := os.Open(\"codegen.txt\")\n    check(err)\n    defer codeGen.Close()\n    scanner = bufio.NewScanner(codeGen)\n    runVM(loadCode())\n}\n", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n"}
{"id": 50745, "name": "Bitmap_Bézier curves_Cubic", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n"}
{"id": 50746, "name": "Sorting algorithms_Pancake sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n"}
{"id": 50747, "name": "Largest five adjacent number", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"rcu\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var sb strings.Builder\n    for i := 0; i < 1000; i++ {\n        sb.WriteByte(byte(rand.Intn(10) + 48))\n    }\n    number := sb.String()\n    for i := 99999; i >= 0; i-- {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The largest  number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            break\n        }\n    }\n    for i := 0; i <= 99999; i++ {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The smallest number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            return\n        }\n    }\n}\n", "Python": "\n\nfrom random import seed,randint\nfrom datetime import datetime\n\nseed(str(datetime.now()))\n\nlargeNum = [randint(1,9)]\n\nfor i in range(1,1000):\n    largeNum.append(randint(0,9))\n\nmaxNum,minNum = 0,99999\n\nfor i in range(0,994):\n    num = int(\"\".join(map(str,largeNum[i:i+5])))\n    if num > maxNum:\n        maxNum = num\n    elif num < minNum:\n        minNum = num\n\nprint(\"Largest 5-adjacent number found \", maxNum)\nprint(\"Smallest 5-adjacent number found \", minNum)\n"}
{"id": 50748, "name": "Sum of square and cube digits of an integer are primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    for i := 1; i < 100; i++ {\n        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {\n            continue\n        }\n        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {\n            fmt.Printf(\"%d \", i)\n        }\n    }\n    fmt.Println()\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef digSum(n, b):\n    s = 0\n    while n:\n        s += (n % b)\n        n = n // b\n    return s\n\nif __name__ == '__main__':\n    for n in range(11, 99):\n        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):\n            print(n, end = \"  \")\n"}
{"id": 50749, "name": "The sieve of Sundaram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nfunc sos(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        p := 2*i + 3\n        s := (p*p - 3) / 2\n        for j := s; j < k; j += p {\n            marked[j] = true\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\n\nfunc soe(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        if !marked[i] {\n            p := 2*i + 3\n            s := (p*p - 3) / 2\n            for j := s; j < k; j += p {\n                marked[j] = true\n            }\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\nfunc main() {\n    const limit = int(16e6) \n    start := time.Now()\n    primes := sos(limit)\n    elapsed := int(time.Since(start).Milliseconds())\n    climit := rcu.Commatize(limit)\n    celapsed := rcu.Commatize(elapsed)\n    million := rcu.Commatize(1e6)\n    millionth := rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"Using the Sieve of Sundaram generated primes up to %s in %s ms.\\n\\n\", climit, celapsed)\n    fmt.Println(\"First 100 odd primes generated by the Sieve of Sundaram:\")\n    for i, p := range primes[0:100] {\n        fmt.Printf(\"%3d \", p)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThe %s Sundaram prime is %s\\n\", million, millionth)\n\n    start = time.Now()\n    primes = soe(limit)\n    elapsed = int(time.Since(start).Milliseconds())\n    celapsed = rcu.Commatize(elapsed)\n    millionth = rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"\\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\\n\", celapsed)\n    fmt.Printf(\"\\nAs a check, the %s Sundaram prime would again have been %s\\n\", million, millionth)\n}\n", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n"}
{"id": 50750, "name": "Chemical calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n"}
{"id": 50751, "name": "Active Directory_Connect", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 50752, "name": "Exactly three adjacent 3 in lists", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    lists := [][]int{\n        {9, 3, 3, 3, 2, 1, 7, 8, 5},\n        {5, 2, 9, 3, 3, 7, 8, 4, 1},\n        {1, 4, 3, 6, 7, 3, 8, 3, 2},\n        {1, 2, 3, 4, 5, 6, 7, 8, 9},\n        {4, 6, 8, 7, 2, 3, 3, 3, 1},\n        {3, 3, 3, 1, 2, 4, 5, 1, 3},\n        {0, 3, 3, 3, 3, 7, 2, 2, 6},\n        {3, 3, 3, 3, 3, 4, 4, 4, 4},\n    }\n    for d := 1; d <= 4; d++ {\n        fmt.Printf(\"Exactly %d adjacent %d's:\\n\", d, d)\n        for _, list := range lists {\n            var indices []int\n            for i, e := range list {\n                if e == d {\n                    indices = append(indices, i)\n                }\n            }\n            adjacent := false\n            if len(indices) == d {\n                adjacent = true\n                for i := 1; i < len(indices); i++ {\n                    if indices[i]-indices[i-1] != 1 {\n                        adjacent = false\n                        break\n                    }\n                }\n            }\n            fmt.Printf(\"%v -> %t\\n\", list, adjacent)\n        }\n        fmt.Println()\n    }\n}\n", "Python": "\n\nfrom itertools import dropwhile, takewhile\n\n\n\ndef nnPeers(n):\n    \n    def p(x):\n        return n == x\n\n    def go(xs):\n        fromFirstMatch = list(dropwhile(\n            lambda v: not p(v),\n            xs\n        ))\n        ns = list(takewhile(p, fromFirstMatch))\n        rest = fromFirstMatch[len(ns):]\n\n        return p(len(ns)) and (\n            not any(p(x) for x in rest)\n        )\n\n    return go\n\n\n\n\ndef main():\n    \n    print(\n        '\\n'.join([\n            f'{xs} -> {nnPeers(3)(xs)}' for xs in [\n                [9, 3, 3, 3, 2, 1, 7, 8, 5],\n                [5, 2, 9, 3, 3, 7, 8, 4, 1],\n                [1, 4, 3, 6, 7, 3, 8, 3, 2],\n                [1, 2, 3, 4, 5, 6, 7, 8, 9],\n                [4, 6, 8, 7, 2, 3, 3, 3, 1]\n            ]\n        ])\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50753, "name": "Permutations by swapping", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n"}
{"id": 50754, "name": "Minimum multiple of m where digital sum equals m", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50755, "name": "Pythagorean quadruples", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 50756, "name": "Verhoeff algorithm", "Go": "package main\n\nimport \"fmt\"\n\nvar d = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},\n    {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},\n    {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},\n    {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},\n    {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n}\n\nvar inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}\n\nvar p = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},\n    {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},\n    {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},\n    {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n}\n\nfunc verhoeff(s string, validate, table bool) interface{} {\n    if table {\n        t := \"Check digit\"\n        if validate {\n            t = \"Validation\"\n        }\n        fmt.Printf(\"%s calculations for '%s':\\n\\n\", t, s)\n        fmt.Println(\" i  nᵢ  p[i,nᵢ]  c\")\n        fmt.Println(\"------------------\")\n    }\n    if !validate {\n        s = s + \"0\"\n    }\n    c := 0\n    le := len(s) - 1\n    for i := le; i >= 0; i-- {\n        ni := int(s[i] - 48)\n        pi := p[(le-i)%8][ni]\n        c = d[c][pi]\n        if table {\n            fmt.Printf(\"%2d  %d      %d     %d\\n\", le-i, ni, pi, c)\n        }\n    }\n    if table && !validate {\n        fmt.Printf(\"\\ninv[%d] = %d\\n\", c, inv[c])\n    }\n    if !validate {\n        return inv[c]\n    }\n    return c == 0\n}\n\nfunc main() {\n    ss := []string{\"236\", \"12345\", \"123456789012\"}\n    ts := []bool{true, true, false, true}\n    for i, s := range ss {\n        c := verhoeff(s, false, ts[i]).(int)\n        fmt.Printf(\"\\nThe check digit for '%s' is '%d'\\n\\n\", s, c)\n        for _, sc := range []string{s + string(c+48), s + \"9\"} {\n            v := verhoeff(sc, true, ts[i]).(bool)\n            ans := \"correct\"\n            if !v {\n                ans = \"incorrect\"\n            }\n            fmt.Printf(\"\\nThe validation for '%s' is %s\\n\\n\", sc, ans)\n        }\n    }\n}\n", "Python": "MULTIPLICATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),\n    (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),\n    (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),\n    (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),\n    (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),\n    (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),\n    (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),\n    (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),\n    (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),\n]\n\nINV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)\n\nPERMUTATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),\n    (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),\n    (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),\n    (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),\n    (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),\n    (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),\n    (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),\n]\n\ndef verhoeffchecksum(n, validate=True, terse=True, verbose=False):\n    \n    if verbose:\n        print(f\"\\n{'Validation' if validate else 'Check digit'}\",\\\n            f\"calculations for {n}:\\n\\n i  nᵢ  p[i,nᵢ]   c\\n------------------\")\n    \n    c, dig = 0, list(str(n if validate else 10 * n))\n    for i, ni in enumerate(dig[::-1]):\n        p = PERMUTATION_TABLE[i % 8][int(ni)]\n        c = MULTIPLICATION_TABLE[c][p]\n        if verbose:\n            print(f\"{i:2}  {ni}      {p}    {c}\")\n\n    if verbose and not validate:\n        print(f\"\\ninv({c}) = {INV[c]}\")\n    if not terse:\n        print(f\"\\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}.\"\\\n              if validate else f\"\\nThe check digit for '{n}' is {INV[c]}.\")\n    return c == 0 if validate else INV[c]\n\nif __name__ == '__main__':\n\n    for n, va, t, ve in [\n        (236, False, False, True), (2363, True, False, True), (2369, True, False, True),\n        (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),\n        (123456789012, False, False, False), (1234567890120, True, False, False),\n        (1234567890129, True, False, False)]:\n        verhoeffchecksum(n, va, t, ve)\n"}
{"id": 50757, "name": "Steady squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc contains(list []int, s int) bool {\n    for _, e := range list {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"Steady squares under 10,000:\")\n    finalDigits := []int{1, 5, 6}\n    for i := 1; i < 10000; i++ {\n        if !contains(finalDigits, i%10) {\n            continue\n        }\n        sq := i * i\n        sqs := strconv.Itoa(sq)\n        is := strconv.Itoa(i)\n        if strings.HasSuffix(sqs, is) {\n            fmt.Printf(\"%5s -> %10s\\n\", rcu.Commatize(i), rcu.Commatize(sq))\n        }\n    }\n}\n", "Python": "print(\"working...\")\nprint(\"Steady squares under 10.000 are:\")\nlimit = 10000\n\nfor n in range(1,limit):\n    nstr = str(n)\n    nlen = len(nstr)\n    square = str(pow(n,2))\n    rn = square[-nlen:]\n    if nstr == rn:\n       print(str(n) + \" \" + str(square))\n\nprint(\"done...\")\n"}
{"id": 50758, "name": "Numbers in base 10 that are palindromic in bases 2, 4, and 16", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc reverse(s string) string {\n    chars := []rune(s)\n    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n        chars[i], chars[j] = chars[j], chars[i]\n    }\n    return string(chars)\n}\n\nfunc main() {\n    fmt.Println(\"Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:\")\n    var numbers []int\n    for i := int64(0); i < 25000; i++ {\n        b2 := strconv.FormatInt(i, 2)\n        if b2 == reverse(b2) {\n            b4 := strconv.FormatInt(i, 4)\n            if b4 == reverse(b4) {\n                b16 := strconv.FormatInt(i, 16)\n                if b16 == reverse(b16) {\n                    numbers = append(numbers, int(i))\n                }\n            }\n        }\n    }\n    for i, n := range numbers {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(numbers), \"such numbers.\")\n}\n", "Python": "def reverse(n, base):\n    r = 0\n    while n > 0:\n        r = r*base + n%base\n        n = n//base\n    return r\n    \ndef palindrome(n, base):\n    return n == reverse(n, base)\n    \ncnt = 0\nfor i in range(25000):\n    if all(palindrome(i, base) for base in (2,4,16)):\n        cnt += 1\n        print(\"{:5}\".format(i), end=\" \\n\"[cnt % 12 == 0])\n\nprint()\n"}
{"id": 50759, "name": "Long stairs", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    totalSecs := 0\n    totalSteps := 0\n    fmt.Println(\"Seconds    steps behind    steps ahead\")\n    fmt.Println(\"-------    ------------    -----------\")\n    for trial := 1; trial < 10000; trial++ {\n        sbeh := 0\n        slen := 100\n        secs := 0\n        for sbeh < slen {\n            sbeh++\n            for wiz := 1; wiz < 6; wiz++ {\n                if rand.Intn(slen) < sbeh {\n                    sbeh++\n                }\n                slen++\n            }\n            secs++\n            if trial == 1 && secs > 599 && secs < 610 {\n                fmt.Printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh)\n            }\n        }\n        totalSecs += secs\n        totalSteps += slen\n    }\n    fmt.Println(\"\\nAverage secs taken:\", float64(totalSecs)/10000)\n    fmt.Println(\"Average final length of staircase:\", float64(totalSteps)/10000)\n}\n", "Python": "\n\nfrom numpy import mean\nfrom random import sample\n\ndef gen_long_stairs(start_step, start_length, climber_steps, add_steps):\n    secs, behind, total = 0, start_step, start_length\n    while True:\n        behind += climber_steps\n        behind += sum([behind > n for n in sample(range(total), add_steps)])\n        total += add_steps\n        secs += 1\n        yield (secs, behind, total)\n        \n\nls = gen_long_stairs(1, 100, 1, 5)\n\nprint(\"Seconds  Behind  Ahead\\n----------------------\")\nwhile True:\n    secs, pos, len = next(ls)\n    if 600 <= secs < 610:\n        print(secs, \"     \", pos, \"   \", len - pos)\n    elif secs == 610:\n        break\n\nprint(\"\\nTen thousand trials to top:\")\ntimes, heights = [], []\nfor trial in range(10_000):\n    trialstairs = gen_long_stairs(1, 100, 1, 5)\n    while True:\n        sec, step, height = next(trialstairs)\n        if step >= height:\n            times.append(sec)\n            heights.append(height)\n            break\n\nprint(\"Mean time:\", mean(times), \"secs. Mean height:\", mean(heights))\n"}
{"id": 50760, "name": "Terminal control_Positional read", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i < 80*25; i++ {\n        fmt.Print(\"A\")  \n    }\n    fmt.Println()\n    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)\n    info := C.CONSOLE_SCREEN_BUFFER_INFO{}\n    pos := C.COORD{}\n    C.GetConsoleScreenBufferInfo(conOut, &info)\n    pos.X = info.srWindow.Left + 3 \n    pos.Y = info.srWindow.Top + 6  \n    var c C.wchar_t\n    var le C.ulong\n    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)\n    if ret == 0 || le <= 0 {\n        fmt.Println(\"Something went wrong!\")\n        return\n    }\n    fmt.Printf(\"The character at column 3, row 6 is '%c'\\n\", c) \n}\n", "Python": "import curses\nfrom random import randint\n\n\n\nstdscr = curses.initscr()\nfor rows in range(10):\n    line = ''.join([chr(randint(41, 90)) for i in range(10)])\n    stdscr.addstr(line + '\\n')\n\n\nicol = 3 - 1\nirow = 6 - 1\nch = stdscr.instr(irow, icol, 1).decode(encoding=\"utf-8\")\n\n\nstdscr.move(irow, icol + 10)\nstdscr.addstr('Character at column 3, row 6 = ' + ch + '\\n')\nstdscr.getch()\n\ncurses.endwin()\n"}
{"id": 50761, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 50762, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 50763, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 50764, "name": "Image convolution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/jpeg\"\n    \"math\"\n    \"os\"\n)\n\n\n\nfunc kf3(k *[9]float64, src, dst *image.Gray) {\n    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {\n        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {\n            var sum float64\n            var i int\n            for yo := y - 1; yo <= y+1; yo++ {\n                for xo := x - 1; xo <= x+1; xo++ {\n                    if (image.Point{xo, yo}).In(src.Rect) {\n                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)\n                    } else {\n                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)\n                    }\n                    i++\n                }\n            }\n            dst.SetGray(x, y,\n                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})\n        }\n    }\n}\n\nvar blur = [9]float64{\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9}\n\n\n\nfunc blurY(src *image.YCbCr) *image.YCbCr {\n    dst := *src\n\n    \n    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {\n        return &dst\n    }\n\n    \n    srcGray := image.Gray{src.Y, src.YStride, src.Rect}\n    dstGray := srcGray\n    dstGray.Pix = make([]uint8, len(src.Y))\n    kf3(&blur, &srcGray, &dstGray) \n\n    \n    dst.Y = dstGray.Pix                   \n    dst.Cb = append([]uint8{}, src.Cb...) \n    dst.Cr = append([]uint8{}, src.Cr...)\n    return &dst\n}\n\nfunc main() {\n    \n    \n    f, err := os.Open(\"Lenna100.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    img, err := jpeg.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n    y, ok := img.(*image.YCbCr)\n    if !ok {\n        fmt.Println(\"expected color jpeg\")\n        return\n    }\n    f, err = os.Create(\"blur.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "\nfrom PIL import Image, ImageFilter\n\nif __name__==\"__main__\":\n\tim = Image.open(\"test.jpg\")\n\n\tkernelValues = [-2,-1,0,-1,1,1,0,1,2] \n\tkernel = ImageFilter.Kernel((3,3), kernelValues)\n\n\tim2 = im.filter(kernel)\n\n\tim2.show()\n"}
{"id": 50765, "name": "Deconvolution_2D+", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\nfunc fft(buf []complex128, n int) {\n    out := make([]complex128, n)\n    copy(out, buf)\n    fft2(buf, out, n, 1)\n}\n\nfunc fft2(buf, out []complex128, n, step int) {\n    if step < n {\n        fft2(out, buf, n, step*2)\n        fft2(out[step:], buf[step:], n, step*2)\n        for j := 0; j < n; j += 2 * step {\n            fj, fn := float64(j), float64(n)\n            t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step]\n            buf[j/2] = out[j] + t\n            buf[(j+n)/2] = out[j] - t\n        }\n    }\n}\n\n\nfunc padTwo(g []float64, le int, ns *int) []complex128 {\n    n := 1\n    if *ns != 0 {\n        n = *ns\n    } else {\n        for n < le {\n            n *= 2\n        }\n    }\n    buf := make([]complex128, n)\n    for i := 0; i < le; i++ {\n        buf[i] = complex(g[i], 0)\n    }\n    *ns = n\n    return buf\n}\n\nfunc deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) {\n    ns := 0\n    g2 := padTwo(g, lg, &ns)\n    f2 := padTwo(f, lf, &ns)\n    fft(g2, ns)\n    fft(f2, ns)\n    h := make([]complex128, ns)\n    for i := 0; i < ns; i++ {\n        h[i] = g2[i] / f2[i]\n    }\n    fft(h, ns)\n    for i := 0; i < ns; i++ {\n        if math.Abs(real(h[i])) < 1e-10 {\n            h[i] = 0\n        }\n    }\n    for i := 0; i > lf-lg-rowLe; i-- {\n        out[-i] = real(h[(i+ns)%ns] / 32)\n    }\n}\n\nfunc unpack2(m [][]float64, rows, le, toLe int) []float64 {\n    buf := make([]float64, rows*toLe)\n    for i := 0; i < rows; i++ {\n        for j := 0; j < le; j++ {\n            buf[i*toLe+j] = m[i][j]\n        }\n    }\n    return buf\n}\n\nfunc pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) {\n    for i := 0; i < rows; i++ {\n        for j := 0; j < toLe; j++ {\n            out[i][j] = buf[i*fromLe+j] / 4\n        }\n    }\n}\n\nfunc deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) {\n    g2 := unpack2(g, rowG, colG, colG)\n    f2 := unpack2(f, rowF, colF, colG)\n    ff := make([]float64, (rowG-rowF+1)*colG)\n    deconv(g2, rowG*colG, f2, rowF*colG, ff, colG)\n    pack2(ff, rowG-rowF+1, colG, colG-colF+1, out)\n}\n\nfunc unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 {\n    buf := make([]float64, x*toY*toZ)\n    for i := 0; i < x; i++ {\n        for j := 0; j < y; j++ {\n            for k := 0; k < z; k++ {\n                buf[(i*toY+j)*toZ+k] = m[i][j][k]\n            }\n        }\n    }\n    return buf\n}\n\nfunc pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) {\n    for i := 0; i < x; i++ {\n        for j := 0; j < toY; j++ {\n            for k := 0; k < toZ; k++ {\n                out[i][j][k] = buf[(i*y+j)*z+k] / 4\n            }\n        }\n    }\n}\n\nfunc deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) {\n    g2 := unpack3(g, gx, gy, gz, gy, gz)\n    f2 := unpack3(f, fx, fy, fz, gy, gz)\n    ff := make([]float64, (gx-fx+1)*gy*gz)\n    deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)\n    pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)\n}\n\nfunc main() {\n    f := [][][]float64{\n        {{-9, 5, -8}, {3, 5, 1}},\n        {{-1, -7, 2}, {-5, -6, 6}},\n        {{8, 5, 8}, {-2, -6, -4}},\n    }\n    fx, fy, fz := len(f), len(f[0]), len(f[0][0])\n\n    g := [][][]float64{\n        {{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73},\n            {-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}},\n        {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64},\n            {87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}},\n        {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144},\n            {-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}},\n        {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8},\n            {-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12},\n        },\n    }\n    gx, gy, gz := len(g), len(g[0]), len(g[0][0])\n\n    h := [][][]float64{\n        {{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}},\n        {{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}},\n    }\n    hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1\n\n    h2 := make([][][]float64, hx)\n    for i := 0; i < hx; i++ {\n        h2[i] = make([][]float64, hy)\n        for j := 0; j < hy; j++ {\n            h2[i][j] = make([]float64, hz)\n        }\n    }\n    deconv3(g, gx, gy, gz, f, fx, fy, fz, h2)\n    fmt.Println(\"deconv3(g, f):\\n\")\n    for i := 0; i < hx; i++ {\n        for j := 0; j < hy; j++ {\n            for k := 0; k < hz; k++ {\n                fmt.Printf(\"% .10g  \", h2[i][j][k])\n            }\n            fmt.Println()\n        }\n        if i < hx-1 {\n            fmt.Println()\n        }\n    }\n\n    kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1\n    f2 := make([][][]float64, kx)\n    for i := 0; i < kx; i++ {\n        f2[i] = make([][]float64, ky)\n        for j := 0; j < ky; j++ {\n            f2[i][j] = make([]float64, kz)\n        }\n    }\n    deconv3(g, gx, gy, gz, h, hx, hy, hz, f2)\n    fmt.Println(\"\\ndeconv(g, h):\\n\")\n    for i := 0; i < kx; i++ {\n        for j := 0; j < ky; j++ {\n            for k := 0; k < kz; k++ {\n                fmt.Printf(\"% .10g  \", f2[i][j][k])\n            }\n            fmt.Println()\n        }\n        if i < kx-1 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "\n\nimport numpy\nimport pprint\n\nh =  [\n      [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], \n      [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf =  [\n      [[-9, 5, -8], [3, 5, 1]], \n      [[-1, -7, 2], [-5, -6, 6]], \n      [[8, 5, 8],[-2, -6, -4]]]\ng =  [\n      [\n         [54, 42, 53, -42, 85, -72], \n         [45, -170, 94, -36, 48, 73], \n         [-39, 65, -112, -16, -78, -72], \n         [6, -11, -6, 62, 49, 8]], \n      [\n         [-57, 49, -23, 52, -135, 66], \n         [-23, 127, -58, -5, -118, 64], \n         [87, -16, 121, 23, -41, -12], \n         [-19, 29, 35, -148, -11, 45]], \n      [\n         [-55, -147, -146, -31, 55, 60], \n         [-88, -45, -28, 46, -26, -144], \n         [-12, -107, -34, 150, 249, 66], \n         [11, -15, -34, 27, -78, -50]], \n      [\n         [56, 67, 108, 4, 2, -48], \n         [58, 67, 89, 32, 32, -8], \n         [-42, -31, -103, -30, -23, -8],\n         [6, 4, -26, -10, 26, 12]]]\n      \ndef trim_zero_empty(x):\n    \n    \n    if len(x) > 0:\n        if type(x[0]) != numpy.ndarray:\n            \n            return list(numpy.trim_zeros(x))\n        else:\n            \n            new_x = []\n            for l in x:\n               tl = trim_zero_empty(l)\n               if len(tl) > 0:\n                   new_x.append(tl)\n            return new_x\n    else:\n        \n        return x\n       \ndef deconv(a, b):\n    \n    \n    \n\n    ffta = numpy.fft.fftn(a)\n    \n    \n    \n    \n    ashape = numpy.shape(a)\n    \n    \n    \n\n    fftb = numpy.fft.fftn(b,ashape)\n    \n    \n\n    fftquotient = ffta / fftb\n    \n    \n    \n\n    c = numpy.fft.ifftn(fftquotient)\n    \n    \n    \n\n    trimmedc = numpy.around(numpy.real(c),decimals=6)\n    \n    \n    \n    \n    cleanc = trim_zero_empty(trimmedc)\n                \n    return cleanc\n    \nprint(\"deconv(g,h)=\")\n\npprint.pprint(deconv(g,h))\n\nprint(\" \")\n\nprint(\"deconv(g,f)=\")\n\npprint.pprint(deconv(g,f))\n"}
{"id": 50766, "name": "Dice game probabilities", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n"}
{"id": 50767, "name": "Zebra puzzle", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"log\"\n        \"strings\"\n)\n\n\n\ntype HouseSet [5]*House\ntype House struct {\n        n Nationality\n        c Colour\n        a Animal\n        d Drink\n        s Smoke\n}\ntype Nationality int8\ntype Colour int8\ntype Animal int8\ntype Drink int8\ntype Smoke int8\n\n\n\nconst (\n        English Nationality = iota\n        Swede\n        Dane\n        Norwegian\n        German\n)\nconst (\n        Red Colour = iota\n        Green\n        White\n        Yellow\n        Blue\n)\nconst (\n        Dog Animal = iota\n        Birds\n        Cats\n        Horse\n        Zebra\n)\nconst (\n        Tea Drink = iota\n        Coffee\n        Milk\n        Beer\n        Water\n)\nconst (\n        PallMall Smoke = iota\n        Dunhill\n        Blend\n        BlueMaster\n        Prince\n)\n\n\n\nvar nationalities = [...]string{\"English\", \"Swede\", \"Dane\", \"Norwegian\", \"German\"}\nvar colours = [...]string{\"red\", \"green\", \"white\", \"yellow\", \"blue\"}\nvar animals = [...]string{\"dog\", \"birds\", \"cats\", \"horse\", \"zebra\"}\nvar drinks = [...]string{\"tea\", \"coffee\", \"milk\", \"beer\", \"water\"}\nvar smokes = [...]string{\"Pall Mall\", \"Dunhill\", \"Blend\", \"Blue Master\", \"Prince\"}\n\nfunc (n Nationality) String() string { return nationalities[n] }\nfunc (c Colour) String() string      { return colours[c] }\nfunc (a Animal) String() string      { return animals[a] }\nfunc (d Drink) String() string       { return drinks[d] }\nfunc (s Smoke) String() string       { return smokes[s] }\nfunc (h House) String() string {\n        return fmt.Sprintf(\"%-9s  %-6s  %-5s  %-6s  %s\", h.n, h.c, h.a, h.d, h.s)\n}\nfunc (hs HouseSet) String() string {\n        lines := make([]string, 0, len(hs))\n        for i, h := range hs {\n                s := fmt.Sprintf(\"%d  %s\", i, h)\n                lines = append(lines, s)\n        }\n        return strings.Join(lines, \"\\n\")\n}\n\n\n\nfunc simpleBruteForce() (int, HouseSet) {\n        var v []House\n        for n := range nationalities {\n                for c := range colours {\n                        for a := range animals {\n                                for d := range drinks {\n                                        for s := range smokes {\n                                                h := House{\n                                                        n: Nationality(n),\n                                                        c: Colour(c),\n                                                        a: Animal(a),\n                                                        d: Drink(d),\n                                                        s: Smoke(s),\n                                                }\n                                                if !h.Valid() {\n                                                        continue\n                                                }\n                                                v = append(v, h)\n                                        }\n                                }\n                        }\n                }\n        }\n        n := len(v)\n        log.Println(\"Generated\", n, \"valid houses\")\n\n        combos := 0\n        first := 0\n        valid := 0\n        var validSet HouseSet\n        for a := 0; a < n; a++ {\n                if v[a].n != Norwegian { \n                        continue\n                }\n                for b := 0; b < n; b++ {\n                        if b == a {\n                                continue\n                        }\n                        if v[b].anyDups(&v[a]) {\n                                continue\n                        }\n                        for c := 0; c < n; c++ {\n                                if c == b || c == a {\n                                        continue\n                                }\n                                if v[c].d != Milk { \n                                        continue\n                                }\n                                if v[c].anyDups(&v[b], &v[a]) {\n                                        continue\n                                }\n                                for d := 0; d < n; d++ {\n                                        if d == c || d == b || d == a {\n                                                continue\n                                        }\n                                        if v[d].anyDups(&v[c], &v[b], &v[a]) {\n                                                continue\n                                        }\n                                        for e := 0; e < n; e++ {\n                                                if e == d || e == c || e == b || e == a {\n                                                        continue\n                                                }\n                                                if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {\n                                                        continue\n                                                }\n                                                combos++\n                                                set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}\n                                                if set.Valid() {\n                                                        valid++\n                                                        if valid == 1 {\n                                                                first = combos\n                                                        }\n                                                        validSet = set\n                                                        \n                                                }\n                                        }\n                                }\n                        }\n                }\n        }\n        log.Println(\"Tested\", first, \"different combinations of valid houses before finding solution\")\n        log.Println(\"Tested\", combos, \"different combinations of valid houses in total\")\n        return valid, validSet\n}\n\n\nfunc (h *House) anyDups(list ...*House) bool {\n        for _, b := range list {\n                if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {\n                        return true\n                }\n        }\n        return false\n}\n\nfunc (h *House) Valid() bool {\n        \n        if h.n == English && h.c != Red || h.n != English && h.c == Red {\n                return false\n        }\n        \n        if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {\n                return false\n        }\n        \n        if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {\n                return false\n        }\n        \n        if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {\n                return false\n        }\n        \n        if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {\n                return false\n        }\n        \n        if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {\n                return false\n        }\n        \n        if h.a == Cats && h.s == Blend {\n                return false\n        }\n        \n        if h.a == Horse && h.s == Dunhill {\n                return false\n        }\n        \n        if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {\n                return false\n        }\n        \n        if h.n == German && h.s != Prince || h.n != German && h.s == Prince {\n                return false\n        }\n        \n        if h.n == Norwegian && h.c == Blue {\n                return false\n        }\n        \n        if h.d == Water && h.s == Blend {\n                return false\n        }\n        return true\n}\n\nfunc (hs *HouseSet) Valid() bool {\n        ni := make(map[Nationality]int, 5)\n        ci := make(map[Colour]int, 5)\n        ai := make(map[Animal]int, 5)\n        di := make(map[Drink]int, 5)\n        si := make(map[Smoke]int, 5)\n        for i, h := range hs {\n                ni[h.n] = i\n                ci[h.c] = i\n                ai[h.a] = i\n                di[h.d] = i\n                si[h.s] = i\n        }\n        \n        if ci[Green]+1 != ci[White] {\n                return false\n        }\n        \n        if dist(ai[Cats], si[Blend]) != 1 {\n                return false\n        }\n        \n        if dist(ai[Horse], si[Dunhill]) != 1 {\n                return false\n        }\n        \n        if dist(ni[Norwegian], ci[Blue]) != 1 {\n                return false\n        }\n        \n        if dist(di[Water], si[Blend]) != 1 {\n                return false\n        }\n\n        \n        if hs[2].d != Milk {\n                return false\n        }\n        \n        if hs[0].n != Norwegian {\n                return false\n        }\n        return true\n}\n\nfunc dist(a, b int) int {\n        if a > b {\n                return a - b\n        }\n        return b - a\n}\n\nfunc main() {\n        log.SetFlags(0)\n        n, sol := simpleBruteForce()\n        fmt.Println(n, \"solution found\")\n        fmt.Println(sol)\n}\n", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n"}
{"id": 50768, "name": "Rosetta Code_Find unimplemented tasks", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n"}
{"id": 50769, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n"}
{"id": 50770, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n"}
{"id": 50771, "name": "Sokoban", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n"}
{"id": 50772, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 50773, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 50774, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 50775, "name": "Practical numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n"}
{"id": 50776, "name": "Consecutive primes with ascending or descending differences", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n    pd := 0\n    longSeqs := [][]int{{2}}\n    currSeq := []int{2}\n    for i := 1; i < len(primes); i++ {\n        d := primes[i] - primes[i-1]\n        if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n            if len(currSeq) > len(longSeqs[0]) {\n                longSeqs = [][]int{currSeq}\n            } else if len(currSeq) == len(longSeqs[0]) {\n                longSeqs = append(longSeqs, currSeq)\n            }\n            currSeq = []int{primes[i-1], primes[i]}\n        } else {\n            currSeq = append(currSeq, primes[i])\n        }\n        pd = d\n    }\n    if len(currSeq) > len(longSeqs[0]) {\n        longSeqs = [][]int{currSeq}\n    } else if len(currSeq) == len(longSeqs[0]) {\n        longSeqs = append(longSeqs, currSeq)\n    }\n    fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n    for _, ls := range longSeqs {\n        var diffs []int\n        for i := 1; i < len(ls); i++ {\n            diffs = append(diffs, ls[i]-ls[i-1])\n        }\n        for i := 0; i < len(ls)-1; i++ {\n            fmt.Print(ls[i], \" (\", diffs[i], \") \")\n        }\n        fmt.Println(ls[len(ls)-1])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    fmt.Println(\"For primes < 1 million:\\n\")\n    for _, dir := range []string{\"ascending\", \"descending\"} {\n        longestSeq(dir)\n    }\n}\n", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n"}
{"id": 50777, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 50778, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 50779, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50780, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50781, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 50782, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 50783, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 50784, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 50785, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 50786, "name": "Word search", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n"}
{"id": 50787, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 50788, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 50789, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 50790, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 50791, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 50792, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50793, "name": "Zumkeller numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n"}
{"id": 50794, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 50795, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 50796, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 50797, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 50798, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 50799, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 50800, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 50801, "name": "Geometric algebra", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n"}
{"id": 50802, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 50803, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 50804, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 50805, "name": "Define a primitive data type", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n"}
{"id": 50806, "name": "Arithmetic derivative", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc D(n float64) float64 {\n    if n < 0 {\n        return -D(-n)\n    }\n    if n < 2 {\n        return 0\n    }\n    var f []int\n    if n < 1e19 {\n        f = rcu.PrimeFactors(int(n))\n    } else {\n        g := int(n / 100)\n        f = rcu.PrimeFactors(g)\n        f = append(f, []int{2, 2, 5, 5}...)\n    }\n    c := len(f)\n    if c == 1 {\n        return 1\n    }\n    if c == 2 {\n        return float64(f[0] + f[1])\n    }\n    d := n / float64(f[0])\n    return D(d)*float64(f[0]) + d\n}\n\nfunc main() {\n    ad := make([]int, 200)\n    for n := -99; n < 101; n++ {\n        ad[n+99] = int(D(float64(n)))\n    }\n    rcu.PrintTable(ad, 10, 4, false)\n    fmt.Println()\n    pow := 1.0\n    for m := 1; m < 21; m++ {\n        pow *= 10\n        fmt.Printf(\"D(10^%-2d) / 7 = %.0f\\n\", m, D(pow)/7)\n    }\n}\n", "Python": "from sympy.ntheory import factorint\n\ndef D(n):\n    if n < 0:\n        return -D(-n)\n    elif n < 2:\n        return 0\n    else:\n        fdict = factorint(n)\n        if len(fdict) == 1 and 1 in fdict: \n            return 1\n        return sum([n * e // p for p, e in fdict.items()])\n\nfor n in range(-99, 101):\n    print('{:5}'.format(D(n)), end='\\n' if n % 10 == 0 else '')\n\nprint()\nfor m in range(1, 21):\n    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))\n"}
{"id": 50807, "name": "Permutations with some identical elements", "Go": "package main\n\nimport \"fmt\"\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 createSlice(nums []int, charSet string) []byte {\n    var chars []byte\n    for i := 0; i < len(nums); i++ {\n        for j := 0; j < nums[i]; j++ {\n            chars = append(chars, charSet[i])\n        }\n    }\n    return chars\n}\n\nfunc main() {\n    var res, res2, res3 []string\n    nums := []int{2, 1}\n    s := createSlice(nums, \"12\")\n    findPerms(s, 0, len(s), &res)\n    fmt.Println(res)\n    fmt.Println()\n\n    nums = []int{2, 3, 1}\n    s = createSlice(nums, \"123\")\n    findPerms(s, 0, len(s), &res2)\n    fmt.Println(res2)\n    fmt.Println()\n\n    s = createSlice(nums, \"ABC\")\n    findPerms(s, 0, len(s), &res3)\n    fmt.Println(res3)\n}\n", "Python": "\n\nfrom itertools import permutations\n\nnumList = [2,3,1]\n\nbaseList = []\n\nfor i in numList:\n    for j in range(0,i):\n        baseList.append(i)\n\nstringDict = {'A':2,'B':3,'C':1}\n\nbaseString=\"\"\n\nfor i in stringDict:\n    for j in range(0,stringDict[i]):\n        baseString+=i\n\nprint(\"Permutations for \" + str(baseList) + \" : \")\n[print(i) for i in set(permutations(baseList))]\n\nprint(\"Permutations for \" + baseString + \" : \")\n[print(i) for i in set(permutations(baseString))]\n"}
{"id": 50808, "name": "Penrose tiling", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\ntype tiletype int\n\nconst (\n    kite tiletype = iota\n    dart\n)\n\ntype tile struct {\n    tt          tiletype\n    x, y        float64\n    angle, size float64\n}\n\nvar gr = (1 + math.Sqrt(5)) / 2 \n\nconst theta = math.Pi / 5 \n\nfunc setupPrototiles(w, h int) []tile {\n    var proto []tile\n    \n    for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {\n        ww := float64(w / 2)\n        hh := float64(h / 2)\n        proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})\n    }\n    return proto\n}\n\nfunc distinctTiles(tls []tile) []tile {\n    tileset := make(map[tile]bool)\n    for _, tl := range tls {\n        tileset[tl] = true\n    }\n    distinct := make([]tile, len(tileset))\n    for tl, _ := range tileset {\n        distinct = append(distinct, tl)\n    }\n    return distinct\n}\n\nfunc deflateTiles(tls []tile, gen int) []tile {\n    if gen <= 0 {\n        return tls\n    }\n    var next []tile\n    for _, tl := range tls {\n        x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr\n        var nx, ny float64\n        if tl.tt == dart {\n            next = append(next, tile{kite, x, y, a + 5*theta, size})\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                nx = x + math.Cos(a-4*theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-4*theta*sign)*gr*tl.size\n                next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})\n            }\n        } else {\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                next = append(next, tile{dart, x, y, a - 4*theta*sign, size})\n                nx = x + math.Cos(a-theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-theta*sign)*gr*tl.size\n                next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})\n            }\n        }\n    }\n    \n    tls = distinctTiles(next)\n    return deflateTiles(tls, gen-1)\n}\n\nfunc drawTiles(dc *gg.Context, tls []tile) {\n    dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}\n    for _, tl := range tls {\n        angle := tl.angle - theta\n        dc.MoveTo(tl.x, tl.y)\n        ord := tl.tt\n        for i := 0; i < 3; i++ {\n            x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)\n            y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)\n            dc.LineTo(x, y)\n            angle += theta\n        }\n        dc.ClosePath()\n        if ord == kite {\n            dc.SetHexColor(\"FFA500\") \n        } else {\n            dc.SetHexColor(\"FFFF00\") \n        }\n        dc.FillPreserve()\n        dc.SetHexColor(\"A9A9A9\") \n        dc.SetLineWidth(1)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    w, h := 700, 450\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    tiles := deflateTiles(setupPrototiles(w, h), 5)\n    drawTiles(dc, tiles)\n    dc.SavePNG(\"penrose_tiling.png\")\n}\n", "Python": "def penrose(depth):\n    print(\t<g id=\"A{d+1}\" transform=\"translate(100, 0) scale(0.6180339887498949)\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n\t<g id=\"B{d+1}\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\t<g id=\"G\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n  </defs>\n  <g transform=\"scale(2, 2)\">\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n  </g>\n</svg>''')\n\npenrose(6)\n"}
{"id": 50809, "name": "Sphenic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = 1000000\n    limit2 := int(math.Cbrt(limit)) \n    primes := rcu.Primes(limit / 6)\n    pc := len(primes)\n    var sphenic []int\n    fmt.Println(\"Sphenic numbers less than 1,000:\")\n    for i := 0; i < pc-2; i++ {\n        if primes[i] > limit2 {\n            break\n        }\n        for j := i + 1; j < pc-1; j++ {\n            prod := primes[i] * primes[j]\n            if prod+primes[j+1] >= limit {\n                break\n            }\n            for k := j + 1; k < pc; k++ {\n                res := prod * primes[k]\n                if res >= limit {\n                    break\n                }\n                sphenic = append(sphenic, res)\n            }\n        }\n    }\n    sort.Ints(sphenic)\n    ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })\n    rcu.PrintTable(sphenic[:ix], 15, 3, false)\n    fmt.Println(\"\\nSphenic triplets less than 10,000:\")\n    var triplets [][3]int\n    for i := 0; i < len(sphenic)-2; i++ {\n        s := sphenic[i]\n        if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {\n            triplets = append(triplets, [3]int{s, s + 1, s + 2})\n        }\n    }\n    ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })\n    for i := 0; i < ix; i++ {\n        fmt.Printf(\"%4d \", triplets[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThere are %s sphenic numbers less than 1,000,000.\\n\", rcu.Commatize(len(sphenic)))\n    fmt.Printf(\"There are %s sphenic triplets less than 1,000,000.\\n\", rcu.Commatize(len(triplets)))\n    s := sphenic[199999]\n    pf := rcu.PrimeFactors(s)\n    fmt.Printf(\"The 200,000th sphenic number is %s (%d*%d*%d).\\n\", rcu.Commatize(s), pf[0], pf[1], pf[2])\n    fmt.Printf(\"The 5,000th sphenic triplet is %v.\\n.\", triplets[4999])\n}\n", "Python": "\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n    d = factorint(i)\n    if len(d) == 3 and sum(d.values()) == 3:\n        sphenics1m.append(i)\n        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n            sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n    if n < 1000:\n        print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n    else:\n        break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n    if n < 10_000:\n        print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else '  ')\n    else:\n        break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n      'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n"}
{"id": 50810, "name": "Tree from nesting levels", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n"}
{"id": 50811, "name": "Tree from nesting levels", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n"}
{"id": 50812, "name": "Find duplicate files", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"crypto/md5\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"path/filepath\"\n    \"sort\"\n    \"time\"\n)\n\ntype fileData struct {\n    filePath string\n    info     os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc checksum(filePath string) hash {\n    bytes, err := ioutil.ReadFile(filePath)\n    check(err)\n    return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n    var dups [][2]fileData\n    m := make(map[hash]fileData)\n    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        if !info.IsDir() && info.Size() >= minSize {\n            h := checksum(path)\n            fd, ok := m[h]\n            fd2 := fileData{path, info}\n            if !ok {\n                m[h] = fd2\n            } else {\n                dups = append(dups, [2]fileData{fd, fd2})\n            }\n        }\n        return nil\n    })\n    check(werr)\n    return dups\n}\n\nfunc main() {\n    dups := findDuplicates(\".\", 1)\n    fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n    fmt.Println(\"File name                 Size      Date last modified\")\n    fmt.Println(\"==========================================================\")\n    sort.Slice(dups, func(i, j int) bool {\n        return dups[i][0].info.Size() > dups[j][0].info.Size() \n    })\n    for _, dup := range dups {\n        for i := 0; i < 2; i++ {\n            d := dup[i]\n            fmt.Printf(\"%-20s  %8d    %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n        }\n        fmt.Println()\n    }\n}\n", "Python": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n    knownFiles = {}\n\n    \n    for root, dirs, files in os.walk(pth):\n        for fina in files:\n            fullFina = os.path.join(root, fina)\n            isSymLink = os.path.islink(fullFina)\n            if isSymLink:\n                continue \n            si = os.path.getsize(fullFina)\n            if si < minSize:\n                continue\n            if si not in knownFiles:\n                knownFiles[si] = {}\n            h = hashlib.new(hashName)\n            h.update(open(fullFina, \"rb\").read())\n            hashed = h.digest()\n            if hashed in knownFiles[si]:\n                fileRec = knownFiles[si][hashed]\n                fileRec.append(fullFina)\n            else:\n                knownFiles[si][hashed] = [fullFina]\n\n    \n    sizeList = list(knownFiles.keys())\n    sizeList.sort(reverse=True)\n    for si in sizeList:\n        filesAtThisSize = knownFiles[si]\n        for hashVal in filesAtThisSize:\n            if len(filesAtThisSize[hashVal]) < 2:\n                continue\n            fullFinaLi = filesAtThisSize[hashVal]\n            print (\"=======Duplicate=======\")\n            for fullFina in fullFinaLi:\n                st = os.stat(fullFina)\n                isHardLink = st.st_nlink > 1 \n                infoStr = []\n                if isHardLink:\n                    infoStr.append(\"(Hard linked)\")\n                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n                print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n"}
{"id": 50813, "name": "Sylvester's sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    two := big.NewInt(2)\n    next := new(big.Int)\n    sylvester := []*big.Int{two}\n    prod := new(big.Int).Set(two)\n    count := 1\n    for count < 10 {\n        next.Add(prod, one)\n        sylvester = append(sylvester, new(big.Int).Set(next))\n        count++\n        prod.Mul(prod, next)\n    }\n    fmt.Println(\"The first 10 terms in the Sylvester sequence are:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sylvester[i])\n    }\n\n    sumRecip := new(big.Rat)\n    for _, s := range sylvester {\n        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))\n    }\n    fmt.Println(\"\\nThe sum of their reciprocals as a rational number is:\")\n    fmt.Println(sumRecip)\n    fmt.Println(\"\\nThe sum of their reciprocals as a decimal number (to 211 places) is:\")\n    fmt.Println(sumRecip.FloatString(211))\n}\n", "Python": "\n\nfrom functools import reduce\nfrom itertools import count, islice\n\n\n\ndef sylvester():\n    \n    def go(n):\n        return 1 + reduce(\n            lambda a, x: a * go(x),\n            range(0, n),\n            1\n        ) if 0 != n else 2\n\n    return map(go, count(0))\n\n\n\n\ndef main():\n    \n\n    print(\"First 10 terms of OEIS A000058:\")\n    xs = list(islice(sylvester(), 10))\n    print('\\n'.join([\n        str(x) for x in xs\n    ]))\n\n    print(\"\\nSum of the reciprocals of the first 10 terms:\")\n    print(\n        reduce(lambda a, x: a + 1 / x, xs, 0)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50814, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 50815, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 50816, "name": "Order disjoint list items", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype indexSort struct {\n\tval sort.Interface\n\tind []int\n}\n\nfunc (s indexSort) Len() int           { return len(s.ind) }\nfunc (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }\nfunc (s indexSort) Swap(i, j int) {\n\ts.val.Swap(s.ind[i], s.ind[j])\n\ts.ind[i], s.ind[j] = s.ind[j], s.ind[i]\n}\n\nfunc disjointSliceSort(m, n []string) []string {\n\ts := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}\n\tused := make(map[int]bool)\n\tfor _, nw := range n {\n\t\tfor i, mw := range m {\n\t\t\tif used[i] || mw != nw {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tused[i] = true\n\t\t\ts.ind = append(s.ind, i)\n\t\t\tbreak\n\t\t}\n\t}\n\tsort.Sort(s)\n\treturn s.val.(sort.StringSlice)\n}\n\nfunc disjointStringSort(m, n string) string {\n\treturn strings.Join(\n\t\tdisjointSliceSort(strings.Fields(m), strings.Fields(n)), \" \")\n}\n\nfunc main() {\n\tfor _, data := range []struct{ m, n string }{\n\t\t{\"the cat sat on the mat\", \"mat cat\"},\n\t\t{\"the cat sat on the mat\", \"cat mat\"},\n\t\t{\"A B C A B C A B C\", \"C A C A\"},\n\t\t{\"A B C A B D A B E\", \"E A D A\"},\n\t\t{\"A B\", \"B\"},\n\t\t{\"A B\", \"B A\"},\n\t\t{\"A B B A\", \"B A\"},\n\t} {\n\t\tmp := disjointStringSort(data.m, data.n)\n\t\tfmt.Printf(\"%s → %s » %s\\n\", data.m, data.n, mp)\n\t}\n\n}\n", "Python": "from __future__ import print_function\n\ndef order_disjoint_list_items(data, items):\n    \n    itemindices = []\n    for item in set(items):\n        itemcount = items.count(item)\n        \n        lastindex = [-1]\n        for i in range(itemcount):\n            lastindex.append(data.index(item, lastindex[-1] + 1))\n        itemindices += lastindex[1:]\n    itemindices.sort()\n    for index, item in zip(itemindices, items):\n        data[index] = item\n\nif __name__ == '__main__':\n    tostring = ' '.join\n    for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),\n                         (str.split('the cat sat on the mat'), str.split('cat mat')),\n                         (list('ABCABCABC'), list('CACA')),\n                         (list('ABCABDABE'), list('EADA')),\n                         (list('AB'), list('B')),\n                         (list('AB'), list('BA')),\n                         (list('ABBA'), list('BA')),\n                         (list(''), list('')),\n                         (list('A'), list('A')),\n                         (list('AB'), list('')),\n                         (list('ABBA'), list('AB')),\n                         (list('ABAB'), list('AB')),\n                         (list('ABAB'), list('BABA')),\n                         (list('ABCCBA'), list('ACAC')),\n                         (list('ABCCBA'), list('CACA')),\n                       ]:\n        print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')\n        order_disjoint_list_items(data, items)\n        print(\"-> M' %r\" % tostring(data))\n"}
{"id": 50817, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 50818, "name": "Achilles numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n"}
{"id": 50819, "name": "Achilles numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n"}
{"id": 50820, "name": "Odd squarefree semiprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n"}
{"id": 50821, "name": "Odd squarefree semiprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n"}
{"id": 50822, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n"}
{"id": 50823, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n"}
{"id": 50824, "name": "Most frequent k chars distance", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n"}
{"id": 50825, "name": "Most frequent k chars distance", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n"}
{"id": 50826, "name": "Palindromic primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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": 50827, "name": "Palindromic primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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": 50828, "name": "Find words which contains all the vowels", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Words which contain all 5 vowels once in\", wordList, \"\\b:\\n\")\n    for _, word := range words {\n        ca, ce, ci, co, cu := 0, 0, 0, 0, 0\n        for _, r := range word {\n            switch r {\n            case 'a':\n                ca++\n            case 'e':\n                ce++\n            case 'i':\n                ci++\n            case 'o':\n                co++\n            case 'u':\n                cu++\n            }\n        }\n        if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {\n            count++\n            fmt.Printf(\"%2d: %s\\n\", count, word)\n        }\n    }\n}\n", "Python": "import urllib.request\nfrom collections import Counter\n\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>10:\n        frequency = Counter(word.lower())\n        if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:\n            print(word)\n"}
{"id": 50829, "name": "Tropical algebra overloading", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar MinusInf = math.Inf(-1)\n\ntype MaxTropical struct{ r float64 }\n\nfunc newMaxTropical(r float64) MaxTropical {\n    if math.IsInf(r, 1) || math.IsNaN(r) {\n        log.Fatal(\"Argument must be a real number or negative infinity.\")\n    }\n    return MaxTropical{r}\n}\n\nfunc (t MaxTropical) eq(other MaxTropical) bool {\n    return t.r == other.r\n}\n\n\nfunc (t MaxTropical) add(other MaxTropical) MaxTropical {\n    if t.r == MinusInf {\n        return other\n    }\n    if other.r == MinusInf {\n        return t\n    }\n    return newMaxTropical(math.Max(t.r, other.r))\n}\n\n\nfunc (t MaxTropical) mul(other MaxTropical) MaxTropical {\n    if t.r == 0 {\n        return other\n    }\n    if other.r == 0 {\n        return t\n    }\n    return newMaxTropical(t.r + other.r)\n}\n\n\nfunc (t MaxTropical) pow(e int) MaxTropical {\n    if e < 1 {\n        log.Fatal(\"Exponent must be a positive integer.\")\n    }\n    if e == 1 {\n        return t\n    }\n    p := t\n    for i := 2; i <= e; i++ {\n        p = p.mul(t)\n    }\n    return p\n}\n\nfunc (t MaxTropical) String() string {\n    return fmt.Sprintf(\"%g\", t.r)\n}\n\nfunc main() {\n    \n    data := [][]float64{\n        {2, -2, 1},\n        {-0.001, MinusInf, 0},\n        {0, MinusInf, 1},\n        {1.5, -1, 0},\n        {-0.5, 0, 1},\n    }\n    for _, d := range data {\n        a := newMaxTropical(d[0])\n        b := newMaxTropical(d[1])\n        if d[2] == 0 {\n            fmt.Printf(\"%s ⊕ %s = %s\\n\", a, b, a.add(b))\n        } else {\n            fmt.Printf(\"%s ⊗ %s = %s\\n\", a, b, a.mul(b))\n        }\n    }\n\n    c := newMaxTropical(5)\n    fmt.Printf(\"%s ^ 7 = %s\\n\", c, c.pow(7))\n\n    d := newMaxTropical(8)\n    e := newMaxTropical(7)\n    f := c.mul(d.add(e))\n    g := c.mul(d).add(c.mul(e))\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) = %s\\n\", c, d, e, f)\n    fmt.Printf(\"%s ⊗ %s ⊕ %s ⊗ %s = %s\\n\", c, d, c, e, g)\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\\n\", c, d, e, c, d, c, e, f.eq(g))\n}\n", "Python": "from numpy import Inf\n\nclass MaxTropical:\n    \n    def __init__(self, x=0):\n        self.x = x\n\n    def __str__(self):\n        return str(self.x)\n\n    def __add__(self, other):\n        return MaxTropical(max(self.x, other.x))\n\n    def __mul__(self, other):\n        return MaxTropical(self.x + other.x)\n\n    def __pow__(self, other):\n        assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n        return MaxTropical(self.x * other.x)\n\n    def __eq__(self, other):\n        return self.x == other.x\n\n\nif __name__ == \"__main__\":\n    a = MaxTropical(-2)\n    b = MaxTropical(-1)\n    c = MaxTropical(-0.5)\n    d = MaxTropical(-0.001)\n    e = MaxTropical(0)\n    f = MaxTropical(0.5)\n    g = MaxTropical(1)\n    h = MaxTropical(1.5)\n    i = MaxTropical(2)\n    j = MaxTropical(5)\n    k = MaxTropical(7)\n    l = MaxTropical(8)\n    m = MaxTropical(-Inf)\n\n    print(\"2 * -2 == \", i * a)\n    print(\"-0.001 + -Inf == \", d + m)\n    print(\"0 * -Inf == \", e * m)\n    print(\"1.5 + -1 == \", h + b)\n    print(\"-0.5 * 0 == \", c * e)\n    print(\"5**7 == \", j**k)\n    print(\"5 * (8 + 7)) == \", j * (l + k))\n    print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n    print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n"}
{"id": 50830, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n"}
{"id": 50831, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n"}
{"id": 50832, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 50833, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 50834, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n"}
{"id": 50835, "name": "Base 16 numbers needing a to f", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50836, "name": "Base 16 numbers needing a to f", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50837, "name": "Range modifications", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype rng struct{ from, to int }\n\ntype fn func(rngs *[]rng, n int)\n\nfunc (r rng) String() string { return fmt.Sprintf(\"%d-%d\", r.from, r.to) }\n\nfunc rangesAdd(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        rngs = append(rngs, rng{n, n})\n        return rngs\n    }\n    for i, r := range rngs {\n        if n < r.from-1 {\n            rngs = append(rngs, rng{})\n            copy(rngs[i+1:], rngs[i:])\n            rngs[i] = rng{n, n}\n            return rngs\n        } else if n == r.from-1 {\n            rngs[i] = rng{n, r.to}\n            return rngs\n        } else if n <= r.to {\n            return rngs\n        } else if n == r.to+1 {\n            rngs[i] = rng{r.from, n}\n            if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) {\n                rngs[i] = rng{r.from, rngs[i+1].to}\n                copy(rngs[i+1:], rngs[i+2:])\n                rngs[len(rngs)-1] = rng{}\n                rngs = rngs[:len(rngs)-1]\n            }\n            return rngs\n        } else if i == len(rngs)-1 {\n            rngs = append(rngs, rng{n, n})\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc rangesRemove(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        return rngs\n    }\n    for i, r := range rngs {\n        if n <= r.from-1 {\n            return rngs\n        } else if n == r.from && n == r.to {\n            copy(rngs[i:], rngs[i+1:])\n            rngs[len(rngs)-1] = rng{}\n            rngs = rngs[:len(rngs)-1]\n            return rngs\n        } else if n == r.from {\n            rngs[i] = rng{n + 1, r.to}\n            return rngs\n        } else if n < r.to {\n            rngs[i] = rng{r.from, n - 1}\n            rngs = append(rngs, rng{})\n            copy(rngs[i+2:], rngs[i+1:])\n            rngs[i+1] = rng{n + 1, r.to}\n            return rngs\n        } else if n == r.to {\n            rngs[i] = rng{r.from, n - 1}\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc standard(rngs []rng) string {\n    if len(rngs) == 0 {\n        return \"\"\n    }\n    var sb strings.Builder\n    for _, r := range rngs {\n        sb.WriteString(fmt.Sprintf(\"%s,\", r))\n    }\n    s := sb.String()\n    return s[:len(s)-1]\n}\n\nfunc main() {\n    const add = 0\n    const remove = 1\n    fns := []fn{\n        func(prngs *[]rng, n int) {\n            *prngs = rangesAdd(*prngs, n)\n            fmt.Printf(\"       add %2d => %s\\n\", n, standard(*prngs))\n        },\n        func(prngs *[]rng, n int) {\n            *prngs = rangesRemove(*prngs, n)\n            fmt.Printf(\"    remove %2d => %s\\n\", n, standard(*prngs))\n        },\n    }\n\n    var rngs []rng\n    ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}}\n    fmt.Printf(\"Start: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 3}, {5, 5}}\n    ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 5}, {10, 25}, {27, 30}}\n    ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n}\n", "Python": "class Sequence():\n    \n    def __init__(self, sequence_string):\n        self.ranges = self.to_ranges(sequence_string)\n        assert self.ranges == sorted(self.ranges), \"Sequence order error\"\n        \n    def to_ranges(self, txt):\n        return [[int(x) for x in r.strip().split('-')]\n                for r in txt.strip().split(',') if r]\n    \n    def remove(self, rem):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= rem <= r[1]:\n                if r[0] == rem:     \n                    if r[1] > rem:\n                        r[0] += 1\n                    else:\n                        del ranges[i]\n                elif r[1] == rem:   \n                    if r[0] < rem:\n                        r[1] -= 1\n                    else:\n                        del ranges[i]\n                else:               \n                    r[1], splitrange = rem - 1, [rem + 1, r[1]]\n                    ranges.insert(i + 1, splitrange)\n                break\n            if r[0] > rem:  \n                break\n        return self\n            \n    def add(self, add):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= add <= r[1]:     \n                break\n            elif r[0] - 1 == add:      \n                r[0] = add\n                break\n            elif r[1] + 1 == add:      \n                r[1] = add\n                break\n            elif r[0] > add:      \n                ranges.insert(i, [add, add])\n                break\n        else:\n            ranges.append([add, add])\n            return self\n        return self.consolidate()\n    \n    def consolidate(self):\n        \"Combine overlapping ranges\"\n        ranges = self.ranges\n        for this, that in zip(ranges, ranges[1:]):\n            if this[1] + 1 >= that[0]:  \n                if this[1] >= that[1]:  \n                    this[:], that[:] = [], this\n                else:   \n                    this[:], that[:] = [], [this[0], that[1]]\n        ranges[:] = [r for r in ranges if r]\n        return self\n    def __repr__(self):\n        rr = self.ranges\n        return \",\".join(f\"{r[0]}-{r[1]}\" for r in rr)\n\ndef demo(opp_txt):\n    by_line = opp_txt.strip().split('\\n')\n    start = by_line.pop(0)\n    ex = Sequence(start.strip().split()[-1][1:-1])    \n    lines = [line.strip().split() for line in by_line]\n    opps = [((ex.add if word[0] == \"add\" else ex.remove), int(word[1]))\n            for word in lines]\n    print(f\"Start: \\\"{ex}\\\"\")\n    for op, val in opps:\n        print(f\"    {op.__name__:>6} {val:2} => {op(val)}\")\n    print()\n                    \nif __name__ == '__main__':\n    demo()\n    demo()\n    demo()\n"}
{"id": 50838, "name": "Juggler sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n"}
{"id": 50839, "name": "Juggler sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n"}
{"id": 50840, "name": "Sierpinski square curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n"}
{"id": 50841, "name": "Powerful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 50842, "name": "Powerful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n"}
{"id": 50843, "name": "Fixed length records", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc reverseBytes(bytes []byte) {\n    for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {\n        bytes[i], bytes[j] = bytes[j], bytes[i]\n    }\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    in, err := os.Open(\"infile.dat\")\n    check(err)\n    defer in.Close()\n\n    out, err := os.Create(\"outfile.dat\")\n    check(err)\n\n    record := make([]byte, 80)\n    empty := make([]byte, 80)\n    for {\n        n, err := in.Read(record)\n        if err != nil {\n            if n == 0 {\n                break \n            } else {\n                out.Close()\n                log.Fatal(err)\n            }\n        }\n        reverseBytes(record)\n        out.Write(record)\n        copy(record, empty)\n    }\n    out.Close()\n\n    \n    \n    cmd := exec.Command(\"dd\", \"if=outfile.dat\", \"cbs=80\", \"conv=unblock\")\n    bytes, err := cmd.Output()\n    check(err)\n    fmt.Println(string(bytes))\n}\n", "Python": "infile = open('infile.dat', 'rb')\noutfile = open('outfile.dat', 'wb')\n\nwhile True:\n    onerecord = infile.read(80)\n    if len(onerecord) < 80:\n        break\n    onerecordreversed = bytes(reversed(onerecord))\n    outfile.write(onerecordreversed)\n\ninfile.close()\noutfile.close()\n"}
{"id": 50844, "name": "Find words whose first and last three letters are equal", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    count := 0\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {\n            count++\n            fmt.Printf(\"%d: %s\\n\", count, s)\n        }\n    }\n}\n", "Python": "import urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>5 and word[:3].lower()==word[-3:].lower():\n        print(word)\n"}
{"id": 50845, "name": "Giuga numbers", "Go": "package main\n\nimport \"fmt\"\n\nvar factors []int\nvar inc = []int{4, 2, 4, 2, 4, 6, 2, 6}\n\n\n\nfunc primeFactors(n int) {\n    factors = factors[:0]\n    factors = append(factors, 2)\n    last := 2\n    n /= 2\n    for n%3 == 0 {\n        if last == 3 {\n            factors = factors[:0]\n            return\n        }\n        last = 3\n        factors = append(factors, 3)\n        n /= 3\n    }\n    for n%5 == 0 {\n        if last == 5 {\n            factors = factors[:0]\n            return\n        }\n        last = 5\n        factors = append(factors, 5)\n        n /= 5\n    }\n    for k, i := 7, 0; k*k <= n; {\n        if n%k == 0 {\n            if last == k {\n                factors = factors[:0]\n                return\n            }\n            last = k\n            factors = append(factors, k)\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        factors = append(factors, n)\n    }\n}\n\nfunc main() {\n    const limit = 5\n    var giuga []int\n    \n    for n := 6; len(giuga) < limit; n += 4 {\n        primeFactors(n)\n        \n        if len(factors) > 2 {\n            isGiuga := true\n            for _, f := range factors {\n                if (n/f-1)%f != 0 {\n                    isGiuga = false\n                    break\n                }\n            }\n            if isGiuga {\n                giuga = append(giuga, n)\n            }\n        }\n    }\n    fmt.Println(\"The first\", limit, \"Giuga numbers are:\")\n    fmt.Println(giuga)\n}\n", "Python": "\n\nfrom math import sqrt\n\ndef isGiuga(m):\n    n = m\n    f = 2\n    l = sqrt(n)\n    while True:\n        if n % f == 0:\n            if ((m / f) - 1) % f != 0:\n                return False\n            n /= f\n            if f > n:\n                return True\n        else:\n            f += 1\n            if f > l:\n                return False\n\n\nif __name__ == '__main__':\n    n = 3\n    c = 0\n    print(\"The first 4 Giuga numbers are: \")\n    while c < 4:\n        if isGiuga(n):\n            c += 1\n            print(n)\n        n += 1\n"}
{"id": 50846, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 50847, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 50848, "name": "Odd words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n"}
{"id": 50849, "name": "Odd words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n"}
{"id": 50850, "name": "Tree datastructures", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n    if level == 0 {\n        fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n    }\n    fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\"  \", level), n.name)\n    for _, c := range n.children {\n        fmt.Fprintf(w, \"%s\", strings.Repeat(\"  \", level+1))\n        printNest(c, level+1, w)\n    }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n    fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n    for _, n := range iNodes {\n        fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n    }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n    *iNodes = append(*iNodes, iNode{level, n.name})\n    for _, c := range n.children {\n        toIndent(c, level+1, iNodes)\n    }\n}\n\nfunc main() {\n    n1 := nNode{\"RosettaCode\", nil}\n    n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n    n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n    n1.children = append(n1.children, n2, n3)\n\n    var sb strings.Builder\n    printNest(n1, 0, &sb)\n    s1 := sb.String()\n    fmt.Print(s1)\n\n    var iNodes []iNode\n    toIndent(n1, 0, &iNodes)\n    printIndent(iNodes, os.Stdout)\n\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    sb.Reset()\n    printNest(n, 0, &sb)\n    s2 := sb.String()\n    fmt.Print(s2)\n\n    fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}\n", "Python": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n    if flat is None:\n        flat = []\n    if node:\n        flat.append((depth, node[0]))\n    for child in node[1]:\n        to_indent(child, depth + 1, flat)\n    return flat\n\ndef to_nest(lst, depth=0, level=None):\n    if level is None:\n        level = []\n    while lst:\n        d, name = lst[0]\n        if d == depth:\n            children = []\n            level.append((name, children))\n            lst.pop(0)\n        elif d > depth:  \n            to_nest(lst, d, children)\n        elif d < depth:  \n            return\n    return level[0] if level else None\n                    \nif __name__ == '__main__':\n    print('Start Nest format:')\n    nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n                            ('mocks', [('trolling', [])])])\n    pp(nest, width=25)\n\n    print('\\n... To Indent format:')\n    as_ind = to_indent(nest)\n    pp(as_ind, width=25)\n\n    print('\\n... To Nest format:')\n    as_nest = to_nest(as_ind)\n    pp(as_nest, width=25)\n\n    if nest != as_nest:\n        print(\"Whoops round-trip issues\")\n"}
{"id": 50851, "name": "Tree datastructures", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n    if level == 0 {\n        fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n    }\n    fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\"  \", level), n.name)\n    for _, c := range n.children {\n        fmt.Fprintf(w, \"%s\", strings.Repeat(\"  \", level+1))\n        printNest(c, level+1, w)\n    }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n    fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n    for _, n := range iNodes {\n        fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n    }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n    *iNodes = append(*iNodes, iNode{level, n.name})\n    for _, c := range n.children {\n        toIndent(c, level+1, iNodes)\n    }\n}\n\nfunc main() {\n    n1 := nNode{\"RosettaCode\", nil}\n    n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n    n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n    n1.children = append(n1.children, n2, n3)\n\n    var sb strings.Builder\n    printNest(n1, 0, &sb)\n    s1 := sb.String()\n    fmt.Print(s1)\n\n    var iNodes []iNode\n    toIndent(n1, 0, &iNodes)\n    printIndent(iNodes, os.Stdout)\n\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    sb.Reset()\n    printNest(n, 0, &sb)\n    s2 := sb.String()\n    fmt.Print(s2)\n\n    fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}\n", "Python": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n    if flat is None:\n        flat = []\n    if node:\n        flat.append((depth, node[0]))\n    for child in node[1]:\n        to_indent(child, depth + 1, flat)\n    return flat\n\ndef to_nest(lst, depth=0, level=None):\n    if level is None:\n        level = []\n    while lst:\n        d, name = lst[0]\n        if d == depth:\n            children = []\n            level.append((name, children))\n            lst.pop(0)\n        elif d > depth:  \n            to_nest(lst, d, children)\n        elif d < depth:  \n            return\n    return level[0] if level else None\n                    \nif __name__ == '__main__':\n    print('Start Nest format:')\n    nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n                            ('mocks', [('trolling', [])])])\n    pp(nest, width=25)\n\n    print('\\n... To Indent format:')\n    as_ind = to_indent(nest)\n    pp(as_ind, width=25)\n\n    print('\\n... To Nest format:')\n    as_nest = to_nest(as_ind)\n    pp(as_nest, width=25)\n\n    if nest != as_nest:\n        print(\"Whoops round-trip issues\")\n"}
{"id": 50852, "name": "Selectively replace multiple instances of a character within a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n"}
{"id": 50853, "name": "Selectively replace multiple instances of a character within a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n"}
{"id": 50854, "name": "Repunit primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n"}
{"id": 50855, "name": "Repunit primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n"}
{"id": 50856, "name": "Curzon numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n"}
{"id": 50857, "name": "Curzon numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n"}
{"id": 50858, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 50859, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 50860, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n"}
{"id": 50861, "name": "Respond to an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n"}
{"id": 50862, "name": "Word break problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50863, "name": "Brilliant numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n"}
{"id": 50864, "name": "Brilliant numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n"}
{"id": 50865, "name": "Word ladder", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n"}
{"id": 50866, "name": "Joystick position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"github.com/simulatedsimian/joystick\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc printAt(x, y int, s string) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)\n        x++\n    }\n}\n\nfunc readJoystick(js joystick.Joystick, hidden bool) {\n    jinfo, err := js.Read()\n    check(err)\n\n    w, h := termbox.Size()\n    tbcd := termbox.ColorDefault\n    termbox.Clear(tbcd, tbcd)\n    printAt(1, h-1, \"q - quit\")\n    if hidden {\n        printAt(11, h-1, \"s - show buttons:\")\n    } else {\n        bs := \"\"\n        printAt(11, h-1, \"h - hide buttons:\")\n        for button := 0; button < js.ButtonCount(); button++ {\n            if jinfo.Buttons&(1<<uint32(button)) != 0 {\n                \n                bs += fmt.Sprintf(\" %X\", button+1)\n            }\n        }\n        printAt(28, h-1, bs)\n    }\n\n    \n    x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)\n    y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)\n    printAt(x, y, \"+\") \n    termbox.Flush()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    \n    \n    jsid := 0\n    \n    if len(os.Args) > 1 {\n        i, err := strconv.Atoi(os.Args[1])\n        check(err)\n        jsid = i\n    }\n\n    js, jserr := joystick.Open(jsid)\n    check(jserr)\n \n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    ticker := time.NewTicker(time.Millisecond * 40)\n    hidden := false \n\n    for doQuit := false; !doQuit; {\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'q' {\n                    doQuit = true\n                } else if ev.Ch == 'h' {\n                    hidden = true\n                } else if ev.Ch == 's' {\n                    hidden = false\n                }\n            }\n            if ev.Type == termbox.EventResize {\n                termbox.Flush()\n            }\n        case <-ticker.C:\n            readJoystick(js, hidden)\n        }\n    }\n}\n", "Python": "import sys\nimport pygame\n\npygame.init()\n\n\nclk = pygame.time.Clock()\n\n\nif pygame.joystick.get_count() == 0:\n    raise IOError(\"No joystick detected\")\njoy = pygame.joystick.Joystick(0)\njoy.init()\n\n\nsize = width, height = 600, 600\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Joystick Tester\")\n\n\nframeRect = pygame.Rect((45, 45), (510, 510))\n\n\ncrosshair = pygame.surface.Surface((10, 10))\ncrosshair.fill(pygame.Color(\"magenta\"))\npygame.draw.circle(crosshair, pygame.Color(\"blue\"), (5,5), 5, 0)\ncrosshair.set_colorkey(pygame.Color(\"magenta\"), pygame.RLEACCEL)\ncrosshair = crosshair.convert()\n\n\nwriter = pygame.font.Font(pygame.font.get_default_font(), 15)\nbuttons = {}\nfor b in range(joy.get_numbuttons()):\n    buttons[b] = [\n        writer.render(\n            hex(b)[2:].upper(),\n            1,\n            pygame.Color(\"red\"),\n            pygame.Color(\"black\")\n        ).convert(),\n        \n        \n        ((15*b)+45, 560)\n    ]\n\nwhile True:\n    \n    pygame.event.pump()\n    for events in pygame.event.get():\n        if events.type == pygame.QUIT:\n            pygame.quit()\n            sys.exit()\n\n    \n    screen.fill(pygame.Color(\"black\"))\n\n    \n    x = joy.get_axis(0)\n    y = joy.get_axis(1)\n\n    \n    \n    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))\n    pygame.draw.rect(screen, pygame.Color(\"red\"), frameRect, 1)\n\n    \n    for b in range(joy.get_numbuttons()):\n        if joy.get_button(b):\n            screen.blit(buttons[b][0], buttons[b][1])\n\n    \n    pygame.display.flip()\n    clk.tick(40) \n"}
{"id": 50867, "name": "Earliest difference between prime gaps", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n", "Python": "\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n    if pri[i] - pri[i - 1] not in gapstarts:\n        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n    while GAP1 not in gapstarts:\n        GAP1 += 2\n    start1 = gapstarts[GAP1]\n    GAP2 = GAP1 + 2\n    if GAP2 not in gapstarts:\n        GAP1 = GAP2 + 2\n        continue\n    start2 = gapstarts[GAP2]\n    diff = abs(start2 - start1)\n    if diff > PM:\n        print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n        print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n        if PM == LIMIT:\n            break\n        PM *= 10\n    else:\n        GAP1 = GAP2\n"}
{"id": 50868, "name": "Latin Squares in reduced form", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n"}
{"id": 50869, "name": "Ormiston pairs", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e9\n    primes := rcu.Primes(limit)\n    var orm30 [][2]int\n    j := int(1e5)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-1; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        if (p2-p1)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 == key2 {\n            if count < 30 {\n                orm30 = append(orm30, [2]int{p1, p2})\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"First 30 Ormiston pairs:\")\n    for i := 0; i < 30; i++ {\n        fmt.Printf(\"%5v \", orm30[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e5)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston pairs before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n    }\n}\n", "Python": "\n\nfrom sympy import primerange\n\n\nPRIMES1M = list(primerange(1, 1_000_000))\nASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M]\nORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M))\n             if ASBASE10SORT[i - 1] == ASBASE10SORT[i]]\n\nprint('First 30 Ormiston pairs:')\nfor (i, o) in enumerate(ORMISTONS):\n    if i < 30:\n        print(f'({o[0] : 6} {o[1] : 6} )',\n              end='\\n' if (i + 1) % 5 == 0 else '  ')\n    else:\n        break\n\nprint(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')\n"}
{"id": 50870, "name": "UPC", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 50871, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 50872, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 50873, "name": "Harmonic series", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc harmonic(n int) *big.Rat {\n    sum := new(big.Rat)\n    for i := int64(1); i <= int64(n); i++ {\n        r := big.NewRat(1, i)\n        sum.Add(sum, r)\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The first 20 harmonic numbers and the 100th, expressed in rational form, are:\")\n    numbers := make([]int, 21)\n    for i := 1; i <= 20; i++ {\n        numbers[i-1] = i\n    }\n    numbers[20] = 100\n    for _, i := range numbers {\n        fmt.Printf(\"%3d : %s\\n\", i, harmonic(i))\n    }\n\n    fmt.Println(\"\\nThe first harmonic number to exceed the following integers is:\")\n    const limit = 10\n    for i, n, h := 1, 1, 0.0; i <= limit; n++ {\n        h += 1.0 / float64(n)\n        if h > float64(i) {\n            fmt.Printf(\"integer = %2d  -> n = %6d  ->  harmonic number = %9.6f (to 6dp)\\n\", i, n, h)\n            i++\n        }\n    }\n}\n", "Python": "from  fractions import Fraction\n\ndef harmonic_series():\n    n, h = Fraction(1), Fraction(1)\n    while True:\n        yield h\n        h += 1 / (n + 1)\n        n += 1\n\nif __name__ == '__main__':\n    from itertools import islice\n    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):\n        print(n, '/', d)\n"}
{"id": 50874, "name": "External sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n"}
{"id": 50875, "name": "External sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n"}
{"id": 50876, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n)", "Go": "package cf\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG4 struct {\n\tA1, A int64\n\tB1, B int64\n}\n\nfunc (ng NG4) needsIngest() bool {\n\tif ng.isDone() {\n\t\tpanic(\"b₁==b==0\")\n\t}\n\treturn ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B\n}\n\nfunc (ng NG4) isDone() bool {\n\treturn ng.B1 == 0 && ng.B == 0\n}\n\nfunc (ng *NG4) ingest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.A+ng.A1*t, ng.A1,\n\t\tng.B+ng.B1*t, ng.B1\n}\n\nfunc (ng *NG4) ingestInfinite() {\n\t\n\t\n\tng.A, ng.B = ng.A1, ng.B1\n}\n\nfunc (ng *NG4) egest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.B1, ng.B,\n\t\tng.A1-ng.B1*t, ng.A-ng.B*t\n}\n\n\n\nfunc (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext := cf()\n\t\tdone := false\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite()\n\t\t\t\t}\n\t\t\t}\n\t\t\tt := ng.A1 / ng.B1\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n", "Python": "class NG:\n  def __init__(self, a1, a, b1, b):\n    self.a1, self.a, self.b1, self.b = a1, a, b1, b\n\n  def ingress(self, n):\n    self.a, self.a1 = self.a1, self.a + self.a1 * n\n    self.b, self.b1 = self.b1, self.b + self.b1 * n\n\n  @property\n  def needterm(self):\n    return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1\n\n  @property\n  def egress(self):\n    n = self.a // self.b\n    self.a,  self.b  = self.b,  self.a  - self.b  * n\n    self.a1, self.b1 = self.b1, self.a1 - self.b1 * n\n    return n\n\n  @property\n  def egress_done(self):\n    if self.needterm: self.a, self.b = self.a1, self.b1\n    return self.egress\n\n  @property\n  def done(self):\n    return self.b == 0 and self.b1 == 0\n"}
{"id": 50877, "name": "Calkin-Wilf sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n"}
{"id": 50878, "name": "Calkin-Wilf sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n"}
{"id": 50879, "name": "Distribution of 0 digits in factorial series", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nfunc main() {\n    fact  := big.NewInt(1)\n    sum   := 0.0\n    first := int64(0)\n    firstRatio := 0.0    \n    fmt.Println(\"The mean proportion of zero digits in factorials up to the following are:\")\n    for n := int64(1); n <= 50000; n++  {\n        fact.Mul(fact, big.NewInt(n))\n        bytes  := []byte(fact.String())\n        digits := len(bytes)\n        zeros  := 0\n        for _, b := range bytes {\n            if b == '0' {\n                zeros++\n            }\n        }\n        sum += float64(zeros)/float64(digits)\n        ratio := sum / float64(n)\n        if n == 100 || n == 1000 || n == 10000 {\n            fmt.Printf(\"%6s = %12.10f\\n\", rcu.Commatize(int(n)), ratio)\n        } \n        if first > 0 && ratio >= 0.16 {\n            first = 0\n            firstRatio = 0.0\n        } else if first == 0 && ratio < 0.16 {\n            first = n\n            firstRatio = ratio           \n        }\n    }\n    fmt.Printf(\"%6s = %12.10f\", rcu.Commatize(int(first)), firstRatio)\n    fmt.Println(\" (stays below 0.16 after this)\")\n    fmt.Printf(\"%6s = %12.10f\\n\", \"50,000\", sum / 50000)\n}\n", "Python": "def facpropzeros(N, verbose = True):\n    proportions = [0.0] * N\n    fac, psum = 1, 0.0\n    for i in range(N):\n        fac *= i + 1\n        d = list(str(fac))\n        psum += sum(map(lambda x: x == '0', d)) / len(d)\n        proportions[i] = psum / (i + 1)\n\n    if verbose:\n        print(\"The mean proportion of 0 in factorials from 1 to {} is {}.\".format(N, psum / N))\n\n    return proportions\n\n\nfor n in [100, 1000, 10000]:\n    facpropzeros(n)\n\nprops = facpropzeros(47500, False)\nn = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))\n\nprint(\"The mean proportion dips permanently below 0.16 at {}.\".format(n + 2))\n"}
{"id": 50880, "name": "Closest-pair problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 50881, "name": "Address of a variable", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n"}
{"id": 50882, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 50883, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 50884, "name": "Color wheel", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n"}
{"id": 50885, "name": "Plasma effect", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n"}
{"id": 50886, "name": "Abelian sandpile model_Identity", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n"}
{"id": 50887, "name": "Abelian sandpile model_Identity", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n"}
{"id": 50888, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 50889, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 50890, "name": "Create an object_Native demonstration", "Go": "package romap\n\ntype Romap struct{ imap map[byte]int }\n\n\nfunc New(m map[byte]int) *Romap {\n    if m == nil {\n        return nil\n    }\n    return &Romap{m}\n}\n\n\nfunc (rom *Romap) Get(key byte) (int, bool) {\n    i, ok := rom.imap[key]\n    return i, ok\n}\n\n\nfunc (rom *Romap) Reset(key byte) {\n    _, ok := rom.imap[key]\n    if ok {\n        rom.imap[key] = 0 \n    }\n}\n", "Python": "from collections import UserDict\nimport copy\n\nclass Dict(UserDict):\n    \n    def __init__(self, dict=None, **kwargs):\n        self.__init = True\n        super().__init__(dict, **kwargs)\n        self.default = copy.deepcopy(self.data)\n        self.__init = False\n    \n    def __delitem__(self, key):\n        if key in self.default:\n            self.data[key] = self.default[key]\n        else:\n            raise NotImplementedError\n\n    def __setitem__(self, key, item):\n        if self.__init:\n            super().__setitem__(key, item)\n        elif key in self.data:\n            self.data[key] = item\n        else:\n            raise KeyError\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, super().__repr__())\n    \n    def fromkeys(cls, iterable, value=None):\n        if self.__init:\n            super().fromkeys(cls, iterable, value)\n        else:\n            for key in iterable:\n                if key in self.data:\n                    self.data[key] = value\n                else:\n                    raise KeyError\n\n    def clear(self):\n        self.data.update(copy.deepcopy(self.default))\n\n    def pop(self, key, default=None):\n        raise NotImplementedError\n\n    def popitem(self):\n        raise NotImplementedError\n\n    def update(self, E, **F):\n        if self.__init:\n            super().update(E, **F)\n        else:\n            haskeys = False\n            try:\n                keys = E.keys()\n                haskeys = Ture\n            except AttributeError:\n                pass\n            if haskeys:\n                for key in keys:\n                    self[key] = E[key]\n            else:\n                for key, val in E:\n                    self[key] = val\n            for key in F:\n                self[key] = F[key]\n\n    def setdefault(self, key, default=None):\n        if key not in self.data:\n            raise KeyError\n        else:\n            return super().setdefault(key, default)\n"}
{"id": 50891, "name": "Rare numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n    \"time\"\n)\n\ntype term struct {\n    coeff    uint64\n    ix1, ix2 int8\n}\n\nconst maxDigits = 19\n\nfunc toUint64(digits []int8, reverse bool) uint64 {\n    sum := uint64(0)\n    if !reverse {\n        for i := 0; i < len(digits); i++ {\n            sum = sum*10 + uint64(digits[i])\n        }\n    } else {\n        for i := len(digits) - 1; i >= 0; i-- {\n            sum = sum*10 + uint64(digits[i])\n        }\n    }\n    return sum\n}\n\nfunc isSquare(n uint64) bool {\n    if 0x202021202030213&(1<<(n&63)) != 0 {\n        root := uint64(math.Sqrt(float64(n)))\n        return root*root == n\n    }\n    return false\n}\n\nfunc seq(from, to, step int8) []int8 {\n    var res []int8\n    for i := from; i <= to; i += step {\n        res = append(res, i)\n    }\n    return res\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    pow := uint64(1)\n    fmt.Println(\"Aggregate timings to process all numbers up to:\")\n    \n    allTerms := make([][]term, maxDigits-1)\n    for r := 2; r <= maxDigits; r++ {\n        var terms []term\n        pow *= 10\n        pow1, pow2 := pow, uint64(1)\n        for i1, i2 := int8(0), int8(r-1); i1 < i2; i1, i2 = i1+1, i2-1 {\n            terms = append(terms, term{pow1 - pow2, i1, i2})\n            pow1 /= 10\n            pow2 *= 10\n        }\n        allTerms[r-2] = terms\n    }\n    \n    fml := map[int8][][]int8{\n        0: {{2, 2}, {8, 8}},\n        1: {{6, 5}, {8, 7}},\n        4: {{4, 0}},\n        6: {{6, 0}, {8, 2}},\n    }\n    \n    dmd := make(map[int8][][]int8)\n    for i := int8(0); i < 100; i++ {\n        a := []int8{i / 10, i % 10}\n        d := a[0] - a[1]\n        dmd[d] = append(dmd[d], a)\n    }\n    fl := []int8{0, 1, 4, 6}\n    dl := seq(-9, 9, 1) \n    zl := []int8{0}     \n    el := seq(-8, 8, 2) \n    ol := seq(-9, 9, 2) \n    il := seq(0, 9, 1)\n    var rares []uint64\n    lists := make([][][]int8, 4)\n    for i, f := range fl {\n        lists[i] = [][]int8{{f}}\n    }\n    var digits []int8\n    count := 0\n\n    \n    \n    var fnpr func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int)\n    fnpr = func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) {\n        if level == len(dis) {\n            digits[indices[0][0]] = fml[cand[0]][di[0]][0]\n            digits[indices[0][1]] = fml[cand[0]][di[0]][1]\n            le := len(di)\n            if nd%2 == 1 {\n                le--\n                digits[nd/2] = di[le]\n            }\n            for i, d := range di[1:le] {\n                digits[indices[i+1][0]] = dmd[cand[i+1]][d][0]\n                digits[indices[i+1][1]] = dmd[cand[i+1]][d][1]\n            }\n            r := toUint64(digits, true)\n            npr := nmr + 2*r\n            if !isSquare(npr) {\n                return\n            }\n            count++\n            fmt.Printf(\"     R/N %2d:\", count)\n            ms := uint64(time.Since(start).Milliseconds())\n            fmt.Printf(\"  %9s ms\", commatize(ms))\n            n := toUint64(digits, false)\n            fmt.Printf(\"  (%s)\\n\", commatize(n))\n            rares = append(rares, n)\n        } else {\n            for _, num := range dis[level] {\n                di[level] = num\n                fnpr(cand, di, dis, indices, nmr, nd, level+1)\n            }\n        }\n    }\n\n    \n    var fnmr func(cand []int8, list [][]int8, indices [][2]int8, nd, level int)\n    fnmr = func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) {\n        if level == len(list) {\n            var nmr, nmr2 uint64\n            for i, t := range allTerms[nd-2] {\n                if cand[i] >= 0 {\n                    nmr += t.coeff * uint64(cand[i])\n                } else {\n                    nmr2 += t.coeff * uint64(-cand[i])\n                    if nmr >= nmr2 {\n                        nmr -= nmr2\n                        nmr2 = 0\n                    } else {\n                        nmr2 -= nmr\n                        nmr = 0\n                    }\n                }\n            }\n            if nmr2 >= nmr {\n                return\n            }\n            nmr -= nmr2\n            if !isSquare(nmr) {\n                return\n            }\n            var dis [][]int8\n            dis = append(dis, seq(0, int8(len(fml[cand[0]]))-1, 1))\n            for i := 1; i < len(cand); i++ {\n                dis = append(dis, seq(0, int8(len(dmd[cand[i]]))-1, 1))\n            }\n            if nd%2 == 1 {\n                dis = append(dis, il)\n            }\n            di := make([]int8, len(dis))\n            fnpr(cand, di, dis, indices, nmr, nd, 0)\n        } else {\n            for _, num := range list[level] {\n                cand[level] = num\n                fnmr(cand, list, indices, nd, level+1)\n            }\n        }\n    }\n\n    for nd := 2; nd <= maxDigits; nd++ {\n        digits = make([]int8, nd)\n        if nd == 4 {\n            lists[0] = append(lists[0], zl)\n            lists[1] = append(lists[1], ol)\n            lists[2] = append(lists[2], el)\n            lists[3] = append(lists[3], ol)\n        } else if len(allTerms[nd-2]) > len(lists[0]) {\n            for i := 0; i < 4; i++ {\n                lists[i] = append(lists[i], dl)\n            }\n        }\n        var indices [][2]int8\n        for _, t := range allTerms[nd-2] {\n            indices = append(indices, [2]int8{t.ix1, t.ix2})\n        }\n        for _, list := range lists {\n            cand := make([]int8, len(list))\n            fnmr(cand, list, indices, nd, 0)\n        }\n        ms := uint64(time.Since(start).Milliseconds())\n        fmt.Printf(\"  %2d digits:  %9s ms\\n\", nd, commatize(ms))\n    }\n\n    sort.Slice(rares, func(i, j int) bool { return rares[i] < rares[j] })\n    fmt.Printf(\"\\nThe rare numbers with up to %d digits are:\\n\", maxDigits)\n    for i, rare := range rares {\n        fmt.Printf(\"  %2d:  %25s\\n\", i+1, commatize(rare))\n    }\n}\n", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n"}
{"id": 50892, "name": "Find words which contain the most consonants", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n"}
{"id": 50893, "name": "Find words which contain the most consonants", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n"}
{"id": 50894, "name": "Prime words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n"}
{"id": 50895, "name": "Prime words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n"}
{"id": 50896, "name": "Numbers which are the cube roots of the product of their proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc divisorCount(n int) int {\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    count := 0\n    sqrt := int(math.Sqrt(float64(n)))\n    for i := 1; i <= sqrt; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    var numbers50 []int\n    count := 0\n    for n := 1; count < 50000; n++ {\n        dc := divisorCount(n)\n        if n == 1 || dc == 8 {\n            count++\n            if count <= 50 {\n                numbers50 = append(numbers50, n)\n                if count == 50 {\n                    rcu.PrintTable(numbers50, 10, 3, false)\n                }\n            } else if count == 500 {\n                fmt.Printf(\"\\n500th   : %s\", rcu.Commatize(n))\n            } else if count == 5000 {\n                fmt.Printf(\"\\n5,000th : %s\", rcu.Commatize(n))\n            } else if count == 50000 {\n                fmt.Printf(\"\\n50,000th: %s\\n\", rcu.Commatize(n))\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n    if num * num * num == divprod:\n        FOUND += 1\n        if FOUND <= 50:\n            print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n        if FOUND == 500:\n            print(f'\\nFive hundreth: {num:,}')\n        if FOUND == 5000:\n            print(f'\\nFive thousandth: {num:,}')\n        if FOUND == 50000:\n            print(f'\\nFifty thousandth: {num:,}')\n            break\n"}
{"id": 50897, "name": "Numbers which are the cube roots of the product of their proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc divisorCount(n int) int {\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    count := 0\n    sqrt := int(math.Sqrt(float64(n)))\n    for i := 1; i <= sqrt; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    var numbers50 []int\n    count := 0\n    for n := 1; count < 50000; n++ {\n        dc := divisorCount(n)\n        if n == 1 || dc == 8 {\n            count++\n            if count <= 50 {\n                numbers50 = append(numbers50, n)\n                if count == 50 {\n                    rcu.PrintTable(numbers50, 10, 3, false)\n                }\n            } else if count == 500 {\n                fmt.Printf(\"\\n500th   : %s\", rcu.Commatize(n))\n            } else if count == 5000 {\n                fmt.Printf(\"\\n5,000th : %s\", rcu.Commatize(n))\n            } else if count == 50000 {\n                fmt.Printf(\"\\n50,000th: %s\\n\", rcu.Commatize(n))\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n    if num * num * num == divprod:\n        FOUND += 1\n        if FOUND <= 50:\n            print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n        if FOUND == 500:\n            print(f'\\nFive hundreth: {num:,}')\n        if FOUND == 5000:\n            print(f'\\nFive thousandth: {num:,}')\n        if FOUND == 50000:\n            print(f'\\nFifty thousandth: {num:,}')\n            break\n"}
{"id": 50898, "name": "Ormiston triples", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e10\n    primes := rcu.Primes(limit)\n    var orm25 []int\n    j := int(1e9)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-2; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        p3 := primes[i+2]\n        if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 != key2 {\n            continue\n        }\n        key3 := 1\n        for _, dig := range rcu.Digits(p3, 10) {\n            key3 *= primes[dig]\n        }\n        if key2 == key3 {\n            if count < 25 {\n                orm25 = append(orm25, p1)\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"Smallest members of first 25 Ormiston triples:\")\n    for i := 0; i < 25; i++ {\n        fmt.Printf(\"%8v \", orm25[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e9)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston triples before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n        fmt.Println()\n    }\n}\n", "Python": "import textwrap\n\nfrom itertools import pairwise\nfrom typing import Iterator\nfrom typing import List\n\nimport primesieve\n\n\ndef primes() -> Iterator[int]:\n    it = primesieve.Iterator()\n    while True:\n        yield it.next_prime()\n\n\ndef triplewise(iterable):\n    for (a, _), (b, c) in pairwise(pairwise(iterable)):\n        yield a, b, c\n\n\ndef is_anagram(a: int, b: int, c: int) -> bool:\n    return sorted(str(a)) == sorted(str(b)) == sorted(str(c))\n\n\ndef up_to_one_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 1_000_000_000:\n            break\n    return count\n\n\ndef up_to_ten_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 10_000_000_000:\n            break\n    return count\n\n\ndef first_25() -> List[int]:\n    rv: List[int] = []\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            rv.append(triple[0])\n            if len(rv) >= 25:\n                break\n    return rv\n\n\nif __name__ == \"__main__\":\n    print(\"Smallest members of first 25 Ormiston triples:\")\n    print(textwrap.fill(\" \".join(str(i) for i in first_25())), \"\\n\")\n    print(up_to_one_billion(), \"Ormiston triples before 1,000,000,000\")\n    print(up_to_ten_billion(), \"Ormiston triples before 10,000,000,000\")\n"}
{"id": 50899, "name": "Minesweeper game", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\ntype cell struct {\n    isMine  bool\n    display byte \n}\n\nconst lMargin = 4\n\nvar (\n    grid        [][]cell\n    mineCount   int\n    minesMarked int\n    isGameOver  bool\n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc makeGrid(n, m int) {\n    if n <= 0 || m <= 0 {\n        panic(\"Grid dimensions must be positive.\")\n    }\n    grid = make([][]cell, n)\n    for i := 0; i < n; i++ {\n        grid[i] = make([]cell, m)\n        for j := 0; j < m; j++ {\n            grid[i][j].display = '.'\n        }\n    }\n    min := int(math.Round(float64(n*m) * 0.1)) \n    max := int(math.Round(float64(n*m) * 0.2)) \n    mineCount = min + rand.Intn(max-min+1)\n    rm := mineCount\n    for rm > 0 {\n        x, y := rand.Intn(n), rand.Intn(m)\n        if !grid[x][y].isMine {\n            rm--\n            grid[x][y].isMine = true\n        }\n    }\n    minesMarked = 0\n    isGameOver = false\n}\n\nfunc displayGrid(isEndOfGame bool) {\n    if !isEndOfGame {\n        fmt.Println(\"Grid has\", mineCount, \"mine(s),\", minesMarked, \"mine(s) marked.\")\n    }\n    margin := strings.Repeat(\" \", lMargin)\n    fmt.Print(margin, \" \")\n    for i := 1; i <= len(grid); i++ {\n        fmt.Print(i)\n    }\n    fmt.Println()\n    fmt.Println(margin, strings.Repeat(\"-\", len(grid)))\n    for y := 0; y < len(grid[0]); y++ {\n        fmt.Printf(\"%*d:\", lMargin, y+1)\n        for x := 0; x < len(grid); x++ {\n            fmt.Printf(\"%c\", grid[x][y].display)\n        }\n        fmt.Println()\n    }\n}\n\nfunc endGame(msg string) {\n    isGameOver = true\n    fmt.Println(msg)\n    ans := \"\"\n    for ans != \"y\" && ans != \"n\" {\n        fmt.Print(\"Another game (y/n)? : \")\n        scanner.Scan()\n        ans = strings.ToLower(scanner.Text())\n    }\n    if scanner.Err() != nil || ans == \"n\" {\n        return\n    }\n    makeGrid(6, 4)\n    displayGrid(false)\n}\n\nfunc resign() {\n    found := 0\n    for y := 0; y < len(grid[0]); y++ {\n        for x := 0; x < len(grid); x++ {\n            if grid[x][y].isMine {\n                if grid[x][y].display == '?' {\n                    grid[x][y].display = 'Y'\n                    found++\n                } else if grid[x][y].display != 'x' {\n                    grid[x][y].display = 'N'\n                }\n            }\n        }\n    }\n    displayGrid(true)\n    msg := fmt.Sprint(\"You found \", found, \" out of \", mineCount, \" mine(s).\")\n    endGame(msg)\n}\n\nfunc usage() {\n    fmt.Println(\"h or ? - this help,\")\n    fmt.Println(\"c x y  - clear cell (x,y),\")\n    fmt.Println(\"m x y  - marks (toggles) cell (x,y),\")\n    fmt.Println(\"n      - start a new game,\")\n    fmt.Println(\"q      - quit/resign the game,\")\n    fmt.Println(\"where x is the (horizontal) column number and y is the (vertical) row number.\\n\")\n}\n\nfunc markCell(x, y int) {\n    if grid[x][y].display == '?' {\n        minesMarked--\n        grid[x][y].display = '.'\n    } else if grid[x][y].display == '.' {\n        minesMarked++\n        grid[x][y].display = '?'\n    }\n}\n\nfunc countAdjMines(x, y int) int {\n    count := 0\n    for j := y - 1; j <= y+1; j++ {\n        if j >= 0 && j < len(grid[0]) {\n            for i := x - 1; i <= x+1; i++ {\n                if i >= 0 && i < len(grid) {\n                    if grid[i][j].isMine {\n                        count++\n                    }\n                }\n            }\n        }\n    }\n    return count\n}\n\nfunc clearCell(x, y int) bool {\n    if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {\n        if grid[x][y].display == '.' {\n            if !grid[x][y].isMine {\n                count := countAdjMines(x, y)\n                if count > 0 {\n                    grid[x][y].display = string(48 + count)[0]\n                } else {\n                    grid[x][y].display = ' '\n                    clearCell(x+1, y)\n                    clearCell(x+1, y+1)\n                    clearCell(x, y+1)\n                    clearCell(x-1, y+1)\n                    clearCell(x-1, y)\n                    clearCell(x-1, y-1)\n                    clearCell(x, y-1)\n                    clearCell(x+1, y-1)\n                }\n            } else {\n                grid[x][y].display = 'x'\n                fmt.Println(\"Kaboom! You lost!\")\n                return false\n            }\n        }\n    }\n    return true\n}\n\nfunc testForWin() bool {\n    isCleared := false\n    if minesMarked == mineCount {\n        isCleared = true\n        for x := 0; x < len(grid); x++ {\n            for y := 0; y < len(grid[0]); y++ {\n                if grid[x][y].display == '.' {\n                    isCleared = false\n                }\n            }\n        }\n    }\n    if isCleared {\n        fmt.Println(\"You won!\")\n    }\n    return isCleared\n}\n\nfunc splitAction(action string) (int, int, bool) {\n    fields := strings.Fields(action)\n    if len(fields) != 3 {\n        return 0, 0, false\n    }\n    x, err := strconv.Atoi(fields[1])\n    if err != nil || x < 1 || x > len(grid) {\n        return 0, 0, false\n    }\n    y, err := strconv.Atoi(fields[2])\n    if err != nil || y < 1 || y > len(grid[0]) {\n        return 0, 0, false\n    }\n    return x, y, true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    usage()\n    makeGrid(6, 4)\n    displayGrid(false)\n    for !isGameOver {\n        fmt.Print(\"\\n>\")\n        scanner.Scan()\n        action := strings.ToLower(scanner.Text())\n        if scanner.Err() != nil || len(action) == 0 {\n            continue\n        }\n        switch action[0] {\n        case 'h', '?':\n            usage()\n        case 'n':\n            makeGrid(6, 4)\n            displayGrid(false)\n        case 'c':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            if clearCell(x-1, y-1) {\n                displayGrid(false)\n                if testForWin() {\n                    resign()\n                }\n            } else {\n                resign()\n            }\n        case 'm':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            markCell(x-1, y-1)\n            displayGrid(false)\n            if testForWin() {\n                resign()\n            }\n        case 'q':\n            resign()\n        }\n    }\n}\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 50900, "name": "Elementary cellular automaton_Infinite length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc evolve(l, rule int) {\n    fmt.Printf(\" Rule #%d:\\n\", rule)\n    cells := \"O\"\n    for x := 0; x < l; x++ {\n        cells = addNoCells(cells)\n        width := 40 + (len(cells) >> 1)\n        fmt.Printf(\"%*s\\n\", width, cells)\n        cells = step(cells, rule)\n    }\n}\n\nfunc step(cells string, rule int) string {\n    newCells := new(strings.Builder)\n    for i := 0; i < len(cells)-2; i++ {\n        bin := 0\n        b := uint(2)\n        for n := i; n < i+3; n++ {\n            bin += btoi(cells[n] == 'O') << b\n            b >>= 1\n        }\n        a := '.'\n        if rule&(1<<uint(bin)) != 0 {\n            a = 'O'\n        }\n        newCells.WriteRune(a)\n    }\n    return newCells.String()\n}\n\nfunc addNoCells(cells string) string {\n    l, r := \"O\", \"O\"\n    if cells[0] == 'O' {\n        l = \".\"\n    }\n    if cells[len(cells)-1] == 'O' {\n        r = \".\"\n    }\n    cells = l + cells + r\n    cells = l + cells + r\n    return cells\n}\n\nfunc main() {\n    for _, r := range []int{90, 30} {\n        evolve(25, r)\n        fmt.Println()\n    }\n}\n", "Python": "def _notcell(c):\n    return '0' if c == '1' else '1'\n\ndef eca_infinite(cells, rule):\n    lencells = len(cells)\n    rulebits = '{0:08b}'.format(rule)\n    neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n    c = cells\n    while True:\n        yield c\n        c = _notcell(c[0])*2 + c + _notcell(c[-1])*2    \n\n        c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))\n        \n\nif __name__ == '__main__':\n    lines = 25\n    for rule in (90, 30):\n        print('\\nRule: %i' % rule)\n        for i, c in zip(range(lines), eca_infinite('1', rule)):\n            print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '\n"}
{"id": 50901, "name": "Execute CopyPasta Language", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n"}
{"id": 50902, "name": "Execute CopyPasta Language", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n"}
{"id": 50903, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst limit = 100000 \n\nfunc nonTwinSums(twins []int) []int {\n    sieve := make([]bool, limit+1)\n    for i := 0; i < len(twins); i++ {\n        for j := i; j < len(twins); j++ {\n            sum := twins[i] + twins[j]\n            if sum > limit {\n                break\n            }\n            sieve[sum] = true\n        }\n    }\n    var res []int\n    for i := 2; i < limit; i += 2 {\n        if !sieve[i] {\n            res = append(res, i)\n        }\n    }\n    return res\n}\n\nfunc main() {\n    primes := rcu.Primes(limit)[2:] \n    twins := []int{3}\n    for i := 0; i < len(primes)-1; i++ {\n        if primes[i+1]-primes[i] == 2 {\n            if twins[len(twins)-1] != primes[i] {\n                twins = append(twins, primes[i])\n            }\n            twins = append(twins, primes[i+1])\n        }\n    }\n    fmt.Println(\"Non twin prime sums:\")\n    ntps := nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n\n    fmt.Println(\"\\nNon twin prime sums (including 1):\")\n    twins = append([]int{1}, twins...)\n    ntps = nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n}\n", "Python": "\n\nfrom sympy import sieve\n\n\ndef nonpairsums(include1=False, limit=20_000):\n    \n    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)\n            for i in range(limit+2)]\n    if include1:\n        tpri[1] = True\n    twinsums = [False] * (limit * 2)\n    for i in range(limit):\n        for j in range(limit-i+1):\n            if tpri[i] and tpri[j]:\n                twinsums[i + j] = True\n\n    return [i for i in range(2, limit+1, 2) if not twinsums[i]]\n\n\nprint('Non twin prime sums:')\nfor k, p in enumerate(nonpairsums()):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n\nprint('\\n\\nNon twin prime sums (including 1):')\nfor k, p in enumerate(nonpairsums(include1=True)):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n"}
{"id": 50904, "name": "Primes with digits in nondecreasing order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50905, "name": "Primes with digits in nondecreasing order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50906, "name": "Reflection_List properties", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 50907, "name": "Minimal steps down to 1", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n    divs, subs []int\n    mins       [][]string\n)\n\n\nfunc minsteps(n int) {\n    if n == 1 {\n        mins[1] = []string{}\n        return\n    }\n    min := limit\n    var p, q int\n    var op byte\n    for _, div := range divs {\n        if n%div == 0 {\n            d := n / div\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, div, '/'\n            }\n        }\n    }\n    for _, sub := range subs {\n        if d := n - sub; d >= 1 {\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, sub, '-'\n            }\n        }\n    }\n    mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n    mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n    for r := 0; r < 2; r++ {\n        divs = []int{2, 3}\n        if r == 0 {\n            subs = []int{1}\n        } else {\n            subs = []int{2}\n        }\n        mins = make([][]string, limit+1)\n        fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n        fmt.Println(\"  Minimum number of steps to diminish the following numbers down to 1 is:\")\n        for i := 1; i <= limit; i++ {\n            minsteps(i)\n            if i <= 10 {\n                steps := len(mins[i])\n                plural := \"s\"\n                if steps == 1 {\n                    plural = \" \"\n                }\n                fmt.Printf(\"    %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n            }\n        }\n        for _, lim := range []int{2000, 20000, 50000} {\n            max := 0\n            for _, min := range mins[0 : lim+1] {\n                m := len(min)\n                if m > max {\n                    max = m\n                }\n            }\n            var maxs []int\n            for i, min := range mins[0 : lim+1] {\n                if len(min) == max {\n                    maxs = append(maxs, i)\n                }\n            }\n            nums := len(maxs)\n            verb, verb2, plural := \"are\", \"have\", \"s\"\n            if nums == 1 {\n                verb, verb2, plural = \"is\", \"has\", \"\"\n            }\n            fmt.Printf(\"  There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n            fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n            fmt.Println(\"   \", maxs)\n        }\n        fmt.Println()\n    }\n}\n", "Python": "from functools import lru_cache\n\n\n\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n    \"Recursive, memoised minimised steps to 1\"\n\n    def __init__(self, divs=DIVS, subs=SUBS):\n        self.divs, self.subs = divs, subs\n\n    @lru_cache(maxsize=None)\n    def _minrec(self, n):\n        \"Recursive, memoised\"\n        if n == 1:\n            return 0, ['=1']\n        possibles = {}\n        for d in self.divs:\n            if n % d == 0:\n                possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n        for s in self.subs:\n            if n > s:\n                possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n        thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n        ret = 1 + count, [thiskind] + otherkinds\n        return ret\n\n    def __call__(self, n):\n        \"Recursive, memoised\"\n        ans = self._minrec(n)[1][:-1]\n        return len(ans), ans\n\n\nif __name__ == '__main__':\n    for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n        minrec = Minrec(DIVS, SUBS)\n        print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n        print('  Possible divisors:  ', DIVS)\n        print('  Possible decrements:', SUBS)\n        for n in range(1, 11):\n            steps, how = minrec(n)\n            print(f'    minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n        upto = 2000\n        print(f'\\n    Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n        stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n        mx = stepn[-1][0]\n        ans = [x[1] for x in stepn if x[0] == mx]\n        print('      Taking', mx, f'steps is/are the {len(ans)} numbers:',\n              ', '.join(str(n) for n in sorted(ans)))\n        \n        print()\n"}
{"id": 50908, "name": "Align columns", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 50909, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 50910, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 50911, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 50912, "name": "Idoneal numbers", "Go": "package main\n\nimport \"rcu\"\n\nfunc isIdoneal(n int) bool {\n    for a := 1; a < n; a++ {\n        for b := a + 1; b < n; b++ {\n            if a*b+a+b > n {\n                break\n            }\n            for c := b + 1; c < n; c++ {\n                sum := a*b + b*c + a*c\n                if sum == n {\n                    return false\n                }\n                if sum > n {\n                    break\n                }\n            }\n        }\n    }\n    return true\n}\n\nfunc main() {\n    var idoneals []int\n    for n := 1; n <= 1850; n++ {\n        if isIdoneal(n) {\n            idoneals = append(idoneals, n)\n        }\n    }\n    rcu.PrintTable(idoneals, 13, 4, false)\n}\n", "Python": "\n\n\ndef is_idoneal(num):\n    \n    for a in range(1, num):\n        for b in range(a + 1, num):\n            if a * b + a + b > num:\n                break\n            for c in range(b + 1, num):\n                sum3 = a * b + b * c + a * c\n                if sum3 == num:\n                    return False\n                if sum3 > num:\n                    break\n    return True\n\n\nrow = 0\nfor n in range(1, 2000):\n    if is_idoneal(n):\n        row += 1\n        print(f'{n:5}', end='\\n' if row % 13 == 0 else '')\n"}
{"id": 50913, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 50914, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 50915, "name": "Dynamic variable names", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n"}
{"id": 50916, "name": "Data Encryption Standard", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n", "Python": "\n\n\n\nIP = (\n    58, 50, 42, 34, 26, 18, 10, 2,\n    60, 52, 44, 36, 28, 20, 12, 4,\n    62, 54, 46, 38, 30, 22, 14, 6,\n    64, 56, 48, 40, 32, 24, 16, 8,\n    57, 49, 41, 33, 25, 17, 9,  1,\n    59, 51, 43, 35, 27, 19, 11, 3,\n    61, 53, 45, 37, 29, 21, 13, 5,\n    63, 55, 47, 39, 31, 23, 15, 7\n)\nIP_INV = (\n    40,  8, 48, 16, 56, 24, 64, 32,\n    39,  7, 47, 15, 55, 23, 63, 31,\n    38,  6, 46, 14, 54, 22, 62, 30,\n    37,  5, 45, 13, 53, 21, 61, 29,\n    36,  4, 44, 12, 52, 20, 60, 28,\n    35,  3, 43, 11, 51, 19, 59, 27,\n    34,  2, 42, 10, 50, 18, 58, 26,\n    33,  1, 41,  9, 49, 17, 57, 25\n)\nPC1 = (\n    57, 49, 41, 33, 25, 17, 9,\n    1,  58, 50, 42, 34, 26, 18,\n    10, 2,  59, 51, 43, 35, 27,\n    19, 11, 3,  60, 52, 44, 36,\n    63, 55, 47, 39, 31, 23, 15,\n    7,  62, 54, 46, 38, 30, 22,\n    14, 6,  61, 53, 45, 37, 29,\n    21, 13, 5,  28, 20, 12, 4\n)\nPC2 = (\n    14, 17, 11, 24, 1,  5,\n    3,  28, 15, 6,  21, 10,\n    23, 19, 12, 4,  26, 8,\n    16, 7,  27, 20, 13, 2,\n    41, 52, 31, 37, 47, 55,\n    30, 40, 51, 45, 33, 48,\n    44, 49, 39, 56, 34, 53,\n    46, 42, 50, 36, 29, 32\n)\n\nE  = (\n    32, 1,  2,  3,  4,  5,\n    4,  5,  6,  7,  8,  9,\n    8,  9,  10, 11, 12, 13,\n    12, 13, 14, 15, 16, 17,\n    16, 17, 18, 19, 20, 21,\n    20, 21, 22, 23, 24, 25,\n    24, 25, 26, 27, 28, 29,\n    28, 29, 30, 31, 32, 1\n)\n\nSboxes = {\n    0: (\n        14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7,\n        0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8,\n        4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0,\n        15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13\n    ),\n    1: (\n        15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10,\n        3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5,\n        0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15,\n        13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9 \n    ),\n    2: (\n        10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8,\n        13,  7,  0,  9,  3,  4,  6, 10,  2,  8,  5, 14, 12, 11, 15,  1,\n        13,  6,  4,  9,  8, 15,  3,  0, 11,  1,  2, 12,  5, 10, 14,  7,\n        1, 10, 13,  0,  6,  9,  8,  7,  4, 15, 14,  3, 11,  5,  2, 12 \n    ),\n    3: (\n        7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15,\n        13,  8, 11,  5,  6, 15,  0,  3,  4,  7,  2, 12,  1, 10, 14,  9,\n        10,  6,  9,  0, 12, 11,  7, 13, 15,  1,  3, 14,  5,  2,  8,  4,\n        3, 15,  0,  6, 10,  1, 13,  8,  9,  4,  5, 11, 12,  7,  2, 14\n    ),\n    4: (\n        2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9,\n        14, 11,  2, 12,  4,  7, 13,  1,  5,  0, 15, 10,  3,  9,  8,  6,\n        4,  2,  1, 11, 10, 13,  7,  8, 15,  9, 12,  5,  6,  3,  0, 14,\n        11,  8, 12,  7,  1, 14,  2, 13,  6, 15,  0,  9, 10,  4,  5,  3\n    ),\n    5: (\n        12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11,\n        10, 15,  4,  2,  7, 12,  9,  5,  6,  1, 13, 14,  0, 11,  3,  8,\n        9, 14, 15,  5,  2,  8, 12,  3,  7,  0,  4, 10,  1, 13, 11,  6,\n        4,  3,  2, 12,  9,  5, 15, 10, 11, 14,  1,  7,  6,  0,  8, 13\n    ),\n    6: (\n        4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1,\n        13,  0, 11,  7,  4,  9,  1, 10, 14,  3,  5, 12,  2, 15,  8,  6,\n        1,  4, 11, 13, 12,  3,  7, 14, 10, 15,  6,  8,  0,  5,  9,  2,\n        6, 11, 13,  8,  1,  4, 10,  7,  9,  5,  0, 15, 14,  2,  3, 12\n    ),\n    7: (\n        13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7,\n        1, 15, 13,  8, 10,  3,  7,  4, 12,  5,  6, 11,  0, 14,  9,  2,\n        7, 11,  4,  1,  9, 12, 14,  2,  0,  6, 10, 13, 15,  3,  5,  8,\n        2,  1, 14,  7,  4, 10,  8, 13, 15, 12,  9,  0,  3,  5,  6, 11\n    )\n}\n\nP = (\n    16,  7, 20, 21,\n    29, 12, 28, 17,\n    1, 15, 23, 26,\n    5, 18, 31, 10,\n    2,  8, 24, 14,\n    32, 27,  3,  9,\n    19, 13, 30,  6,\n    22, 11, 4,  25\n)\n    \ndef encrypt(msg, key, decrypt=False):\n    \n    assert isinstance(msg, int) and isinstance(key, int)\n    assert not msg.bit_length() > 64\n    assert not key.bit_length() > 64\n\n    \n    key = permutation_by_table(key, 64, PC1) \n\n    \n    \n    C0 = key >> 28\n    D0 = key & (2**28-1)\n    round_keys = generate_round_keys(C0, D0) \n\n    msg_block = permutation_by_table(msg, 64, IP)\n    L0 = msg_block >> 32\n    R0 = msg_block & (2**32-1)\n\n    \n    L_last = L0\n    R_last = R0\n    for i in range(1,17):\n        if decrypt: \n            i = 17-i\n        L_round = R_last\n        R_round = L_last ^ round_function(R_last, round_keys[i])\n        L_last = L_round\n        R_last = R_round\n\n    \n    cipher_block = (R_round<<32) + L_round\n\n    \n    cipher_block = permutation_by_table(cipher_block, 64, IP_INV)\n\n    return cipher_block\n\ndef round_function(Ri, Ki):\n    \n    Ri = permutation_by_table(Ri, 32, E)\n\n    \n    Ri ^= Ki\n\n    \n    Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)]\n\n    \n    for i, block in enumerate(Ri_blocks):\n        \n        row = ((0b100000 & block) >> 4) + (0b1 & block)\n        col = (0b011110 & block) >> 1\n        \n        Ri_blocks[i] = Sboxes[i][16*row+col]\n\n    \n    Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0))\n    Ri = 0\n    for block, lshift_val in Ri_blocks:\n        Ri += (block << lshift_val)\n\n    \n    Ri = permutation_by_table(Ri, 32, P)\n\n    return Ri\n\ndef permutation_by_table(block, block_len, table):\n    \n    block_str = bin(block)[2:].zfill(block_len)\n    perm = []\n    for pos in range(len(table)):\n        perm.append(block_str[table[pos]-1])\n    return int(''.join(perm), 2)\n\ndef generate_round_keys(C0, D0):\n    \n\n    round_keys = dict.fromkeys(range(0,17))\n    lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1)\n\n    \n    lrot = lambda val, r_bits, max_bits: \\\n    (val << r_bits%max_bits) & (2**max_bits-1) | \\\n    ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))\n\n    \n    C0 = lrot(C0, 0, 28)\n    D0 = lrot(D0, 0, 28)\n    round_keys[0] = (C0, D0)\n\n    \n    for i, rot_val in enumerate(lrot_values):\n        i+=1\n        Ci = lrot(round_keys[i-1][0], rot_val, 28)\n        Di = lrot(round_keys[i-1][1], rot_val, 28)\n        round_keys[i] = (Ci, Di)\n\n    \n    \n    \n    del round_keys[0]\n\n    \n    for i, (Ci, Di) in round_keys.items():\n        Ki = (Ci << 28) + Di\n        round_keys[i] = permutation_by_table(Ki, 56, PC2) \n\n    return round_keys\n\nk = 0x0e329232ea6d0d73 \nk2 = 0x133457799BBCDFF1\nm = 0x8787878787878787\nm2 = 0x0123456789ABCDEF\n\ndef prove(key, msg):\n    print('key:       {:x}'.format(key))\n    print('message:   {:x}'.format(msg))\n    cipher_text = encrypt(msg, key)\n    print('encrypted: {:x}'.format(cipher_text))\n    plain_text = encrypt(cipher_text, key, decrypt=True)\n    print('decrypted: {:x}'.format(plain_text))\n\nprove(k, m)\nprint('----------')\nprove(k2, m2)\n"}
{"id": 50917, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n"}
{"id": 50918, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n"}
{"id": 50919, "name": "Largest palindrome product", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(n uint64) uint64 {\n    r := uint64(0)\n    for n > 0 {\n        r = n%10 + r*10\n        n /= 10\n    }\n    return r\n}\n\nfunc main() {\n    pow := uint64(10)\nnextN:\n    for n := 2; n < 10; n++ {\n        low := pow * 9\n        pow *= 10\n        high := pow - 1\n        fmt.Printf(\"Largest palindromic product of two %d-digit integers: \", n)\n        for i := high; i >= low; i-- {\n            j := reverse(i)\n            p := i*pow + j\n            \n            for k := high; k > low; k -= 2 {\n                if k % 10 == 5 {\n                    continue\n                }\n                l := p / k\n                if l > high {\n                    break\n                }\n                if p%k == 0 {\n                    fmt.Printf(\"%d x %d = %d\\n\", k, l, p)\n                    continue nextN\n                }\n            }\n        }\n    }\n}\n", "Python": "\n\nT=[set([(0, 0)])]\n\ndef double(it):\n    for a, b in it:\n        yield a, b\n        yield b, a\n\ndef tails(n):\n    \n    if len(T)<=n:\n        l = set()\n        for i in range(10):\n            for j in range(i, 10):\n                I = i*10**(n-1)\n                J = j*10**(n-1)\n                it = tails(n-1)\n                if I!=J: it = double(it)\n                for t1, t2 in it:\n                    if ((I+t1)*(J+t2)+1)%10**n == 0:\n                        l.add((I+t1, J+t2))\n        T.append(l)\n    return T[n]\n\ndef largestPalindrome(n):\n    \n    m, tail = 0, n // 2\n    head = n - tail\n    up = 10**head\n    for L in range(1, 9*10**(head-1)+1):\n        \n        m = 0\n        sol = None\n        for i in range(1, L + 1):\n            lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)\n            hi = int(up - (up - L)**2 / (up - i))\n            for j in range(lo, hi + 1):\n                I = (up-i) * 10**tail\n                J = (up-j) * 10**tail\n                it = tails(tail)\n                if I!=J: it = double(it)\n                    for t1, t2 in it:\n                        val = (I + t1)*(J + t2)\n                        s = str(val)\n                        if s == s[::-1] and val>m:\n                            sol = (I + t1, J + t2)\n                            m = val\n\n        if m:\n            print(\"{:2d}\\t{:4d}\".format(n, m % 1337), sol, sol[0] * sol[1])\n            return m % 1337\n    return 0\n\nif __name__ == \"__main__\":\n    for k in range(1, 14):\n        largestPalindrome(k)\n"}
{"id": 50920, "name": "Commatizing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n"}
{"id": 50921, "name": "Commatizing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n"}
{"id": 50922, "name": "Arithmetic coding_As a generalized change of radix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n"}
{"id": 50923, "name": "Arithmetic coding_As a generalized change of radix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n"}
{"id": 50924, "name": "Kosaraju", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n"}
{"id": 50925, "name": "Reflection_List methods", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n"}
{"id": 50926, "name": "Pentomino tiling", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar F = [][]int{\n    {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},\n    {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},\n    {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},\n}\n\nvar I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}\n\nvar L = [][]int{\n    {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},\n}\n\nvar N = [][]int{\n    {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},\n}\n\nvar P = [][]int{\n    {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},\n}\n\nvar T = [][]int{\n    {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},\n}\n\nvar U = [][]int{\n    {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},\n}\n\nvar V = [][]int{\n    {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},\n}\n\nvar W = [][]int{\n    {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},\n}\n\nvar X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}\n\nvar Y = [][]int{\n    {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},\n}\n\nvar Z = [][]int{\n    {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},\n}\n\nvar shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}\n\nvar symbols = []byte(\"FILNPTUVWXYZ-\")\n\nconst (\n    nRows = 8\n    nCols = 8\n    blank = 12\n)\n\nvar grid [nRows][nCols]int\nvar placed [12]bool\n\nfunc tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {\n    for i := 0; i < len(o); i += 2 {\n        x := c + o[i+1]\n        y := r + o[i]\n        if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {\n            return false\n        }\n    }\n    grid[r][c] = shapeIndex\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = shapeIndex\n    }\n    return true\n}\n\nfunc removeOrientation(o []int, r, c int) {\n    grid[r][c] = -1\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = -1\n    }\n}\n\nfunc solve(pos, numPlaced int) bool {\n    if numPlaced == len(shapes) {\n        return true\n    }\n    row := pos / nCols\n    col := pos % nCols\n    if grid[row][col] != -1 {\n        return solve(pos+1, numPlaced)\n    }\n\n    for i := range shapes {\n        if !placed[i] {\n            for _, orientation := range shapes[i] {\n                if !tryPlaceOrientation(orientation, row, col, i) {\n                    continue\n                }\n                placed[i] = true\n                if solve(pos+1, numPlaced+1) {\n                    return true\n                }\n                removeOrientation(orientation, row, col)\n                placed[i] = false\n            }\n        }\n    }\n    return false\n}\n\nfunc shuffleShapes() {\n    rand.Shuffle(len(shapes), func(i, j int) {\n        shapes[i], shapes[j] = shapes[j], shapes[i]\n        symbols[i], symbols[j] = symbols[j], symbols[i]\n    })\n}\n\nfunc printResult() {\n    for _, r := range grid {\n        for _, i := range r {\n            fmt.Printf(\"%c \", symbols[i])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    shuffleShapes()\n    for r := 0; r < nRows; r++ {\n        for i := range grid[r] {\n            grid[r][i] = -1\n        }\n    }\n    for i := 0; i < 4; i++ {\n        var randRow, randCol int\n        for {\n            randRow = rand.Intn(nRows)\n            randCol = rand.Intn(nCols)\n            if grid[randRow][randCol] != blank {\n                break\n            }\n        }\n        grid[randRow][randCol] = blank\n    }\n    if solve(0, 0) {\n        printResult()\n    } else {\n        fmt.Println(\"No solution\")\n    }\n}\n", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n"}
{"id": 50927, "name": "Send an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n"}
{"id": 50928, "name": "Variables", "Go": "x := 3\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 50929, "name": "Particle swarm optimization", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype ff = func([]float64) float64\n\ntype parameters struct{ omega, phip, phig float64 }\n\ntype state struct {\n    iter       int\n    gbpos      []float64\n    gbval      float64\n    min        []float64\n    max        []float64\n    params     parameters\n    pos        [][]float64\n    vel        [][]float64\n    bpos       [][]float64\n    bval       []float64\n    nParticles int\n    nDims      int\n}\n\nfunc (s state) report(testfunc string) {\n    fmt.Println(\"Test Function        :\", testfunc)\n    fmt.Println(\"Iterations           :\", s.iter)\n    fmt.Println(\"Global Best Position :\", s.gbpos)\n    fmt.Println(\"Global Best Value    :\", s.gbval)\n}\n\nfunc psoInit(min, max []float64, params parameters, nParticles int) *state {\n    nDims := len(min)\n    pos := make([][]float64, nParticles)\n    vel := make([][]float64, nParticles)\n    bpos := make([][]float64, nParticles)\n    bval := make([]float64, nParticles)\n    for i := 0; i < nParticles; i++ {\n        pos[i] = min\n        vel[i] = make([]float64, nDims)\n        bpos[i] = min\n        bval[i] = math.Inf(1)\n    }\n    iter := 0\n    gbpos := make([]float64, nDims)\n    for i := 0; i < nDims; i++ {\n        gbpos[i] = math.Inf(1)\n    }\n    gbval := math.Inf(1)\n    return &state{iter, gbpos, gbval, min, max, params,\n        pos, vel, bpos, bval, nParticles, nDims}\n}\n\nfunc pso(fn ff, y *state) *state {\n    p := y.params\n    v := make([]float64, y.nParticles)\n    bpos := make([][]float64, y.nParticles)\n    bval := make([]float64, y.nParticles)\n    gbpos := make([]float64, y.nDims)\n    gbval := math.Inf(1)\n    for j := 0; j < y.nParticles; j++ {\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j] {\n            bpos[j] = y.pos[j]\n            bval[j] = v[j]\n        } else {\n            bpos[j] = y.bpos[j]\n            bval[j] = y.bval[j]\n        }\n        if bval[j] < gbval {\n            gbval = bval[j]\n            gbpos = bpos[j]\n        }\n    }\n    rg := rand.Float64()\n    pos := make([][]float64, y.nParticles)\n    vel := make([][]float64, y.nParticles)\n    for j := 0; j < y.nParticles; j++ {\n        pos[j] = make([]float64, y.nDims)\n        vel[j] = make([]float64, y.nDims)\n        \n        rp := rand.Float64()\n        ok := true\n        for z := 0; z < y.nDims; z++ {\n            pos[j][z] = 0\n            vel[j][z] = 0\n        }\n        for k := 0; k < y.nDims; k++ {\n            vel[j][k] = p.omega*y.vel[j][k] +\n                p.phip*rp*(bpos[j][k]-y.pos[j][k]) +\n                p.phig*rg*(gbpos[k]-y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]\n        }\n        if !ok {\n            for k := 0; k < y.nDims; k++ {\n                pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64()\n            }\n        }\n    }\n    iter := 1 + y.iter\n    return &state{iter, gbpos, gbval, y.min, y.max, y.params,\n        pos, vel, bpos, bval, y.nParticles, y.nDims}\n}\n\nfunc iterate(fn ff, n int, y *state) *state {\n    r := y\n    for i := 0; i < n; i++ {\n        r = pso(fn, r)\n    }\n    return r\n}\n\nfunc mccormick(x []float64) float64 {\n    a, b := x[0], x[1]\n    return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a\n}\n\nfunc michalewicz(x []float64) float64 {\n    m := 10.0\n    sum := 0.0\n    for i := 1; i <= len(x); i++ {\n        j := x[i-1]\n        k := math.Sin(float64(i) * j * j / math.Pi)\n        sum += math.Sin(j) * math.Pow(k, 2*m)\n    }\n    return -sum\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    st := psoInit(\n        []float64{-1.5, -3.0},\n        []float64{4.0, 4.0},\n        parameters{0.0, 0.6, 0.3},\n        100,\n    )\n    st = iterate(mccormick, 40, st)\n    st.report(\"McCormick\")\n    fmt.Println(\"f(-.54719, -1.54719) :\", mccormick([]float64{-.54719, -1.54719}))\n    fmt.Println()\n    st = psoInit(\n        []float64{0.0, 0.0},\n        []float64{math.Pi, math.Pi},\n        parameters{0.3, 0.3, 0.3},\n        1000,\n    )\n    st = iterate(michalewicz, 30, st)\n    st.report(\"Michalewicz (2D)\")\n    fmt.Println(\"f(2.20, 1.57)        :\", michalewicz([]float64{2.2, 1.57}))\n", "Python": "import math\nimport random\n\nINFINITY = 1 << 127\nMAX_INT = 1 << 31\n\nclass Parameters:\n    def __init__(self, omega, phip, phig):\n        self.omega = omega\n        self.phip = phip\n        self.phig = phig\n\nclass State:\n    def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):\n        self.iter = iter\n        self.gbpos = gbpos\n        self.gbval = gbval\n        self.min = min\n        self.max = max\n        self.parameters = parameters\n        self.pos = pos\n        self.vel = vel\n        self.bpos = bpos\n        self.bval = bval\n        self.nParticles = nParticles\n        self.nDims = nDims\n\n    def report(self, testfunc):\n        print \"Test Function :\", testfunc\n        print \"Iterations    :\", self.iter\n        print \"Global Best Position :\", self.gbpos\n        print \"Global Best Value    : %.16f\" % self.gbval\n\ndef uniform01():\n    v = random.random()\n    assert 0.0 <= v and v < 1.0\n    return v\n\ndef psoInit(min, max, parameters, nParticles):\n    nDims = len(min)\n    pos = [min[:]] * nParticles\n    vel = [[0.0] * nDims] * nParticles\n    bpos = [min[:]] * nParticles\n    bval = [INFINITY] * nParticles\n    iter = 0\n    gbpos = [INFINITY] * nDims\n    gbval = INFINITY\n    return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n\ndef pso(fn, y):\n    p = y.parameters\n    v = [0.0] * (y.nParticles)\n    bpos = [y.min[:]] * (y.nParticles)\n    bval = [0.0] * (y.nParticles)\n    gbpos = [0.0] * (y.nDims)\n    gbval = INFINITY\n    for j in xrange(0, y.nParticles):\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j]:\n            bpos[j] = y.pos[j][:]\n            bval[j] = v[j]\n        else:\n            bpos[j] = y.bpos[j][:]\n            bval[j] = y.bval[j]\n        if bval[j] < gbval:\n            gbval = bval[j]\n            gbpos = bpos[j][:]\n    rg = uniform01()\n    pos = [[None] * (y.nDims)] * (y.nParticles)\n    vel = [[None] * (y.nDims)] * (y.nParticles)\n    for j in xrange(0, y.nParticles):\n        \n        rp = uniform01()\n        ok = True\n        vel[j] = [0.0] * (len(vel[j]))\n        pos[j] = [0.0] * (len(pos[j]))\n        for k in xrange(0, y.nDims):\n            vel[j][k] = p.omega * y.vel[j][k] \\\n                      + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \\\n                      + p.phig * rg * (gbpos[k] - y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]\n        if not ok:\n            for k in xrange(0, y.nDims):\n                pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()\n    iter = 1 + y.iter\n    return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n\ndef iterate(fn, n, y):\n    r = y\n    old = y\n    if n == MAX_INT:\n        while True:\n            r = pso(fn, r)\n            if r == old:\n                break\n            old = r\n    else:\n        for _ in xrange(0, n):\n            r = pso(fn, r)\n    return r\n\ndef mccormick(x):\n    (a, b) = x\n    return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a\n\ndef michalewicz(x):\n    m = 10\n    d = len(x)\n    sum = 0.0\n    for i in xrange(1, d):\n        j = x[i - 1]\n        k = math.sin(i * j * j / math.pi)\n        sum += math.sin(j) * k ** (2.0 * m)\n    return -sum\n\ndef main():\n    state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)\n    state = iterate(mccormick, 40, state)\n    state.report(\"McCormick\")\n    print \"f(-.54719, -1.54719) : %.16f\" % (mccormick([-.54719, -1.54719]))\n\n    print\n\n    state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)\n    state = iterate(michalewicz, 30, state)\n    state.report(\"Michalewicz (2D)\")\n    print \"f(2.20, 1.57)        : %.16f\" % (michalewicz([2.2, 1.57]))\n\nmain()\n"}
{"id": 50930, "name": "Interactive programming (repl)", "Go": "package main\n\nimport \"fmt\"\n\nfunc f(s1, s2, sep string) string {\n\treturn s1 + sep + sep + s2\n}\n\nfunc main() {\n\tfmt.Println(f(\"Rosetta\", \"Code\", \":\"))\n}\n", "Python": "python\nPython 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(string1, string2, separator):\n\treturn separator.join([string1, '', string2])\n\n>>> f('Rosetta', 'Code', ':')\n'Rosetta::Code'\n>>>\n"}
{"id": 50931, "name": "Interactive programming (repl)", "Go": "package main\n\nimport \"fmt\"\n\nfunc f(s1, s2, sep string) string {\n\treturn s1 + sep + sep + s2\n}\n\nfunc main() {\n\tfmt.Println(f(\"Rosetta\", \"Code\", \":\"))\n}\n", "Python": "python\nPython 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(string1, string2, separator):\n\treturn separator.join([string1, '', string2])\n\n>>> f('Rosetta', 'Code', ':')\n'Rosetta::Code'\n>>>\n"}
{"id": 50932, "name": "Index finite lists of positive integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc rank(l []uint) (r big.Int) {\n    for _, n := range l {\n        r.Lsh(&r, n+1)\n        r.SetBit(&r, int(n), 1)\n    }\n    return\n}\n\nfunc unrank(n big.Int) (l []uint) {\n    m := new(big.Int).Set(&n)\n    for a := m.BitLen(); a > 0; {\n        m.SetBit(m, a-1, 0)\n        b := m.BitLen()\n        l = append(l, uint(a-b-1))\n        a = b\n    }\n    return\n}\n\nfunc main() {\n    var b big.Int\n    for i := 0; i <= 10; i++ {\n        b.SetInt64(int64(i))\n        u := unrank(b)\n        r := rank(u)\n        fmt.Println(i, u, &r)\n    }\n    b.SetString(\"12345678901234567890\", 10)\n    u := unrank(b)\n    r := rank(u)\n    fmt.Printf(\"\\n%v\\n%d\\n%d\\n\", &b, u, &r)\n}\n", "Python": "def rank(x): return int('a'.join(map(str, [1] + x)), 11)\n\ndef unrank(n):\n\ts = ''\n\twhile n: s,n = \"0123456789a\"[n%11] + s, n//11\n\treturn map(int, s.split('a'))[1:]\n\nl = [1, 2, 3, 10, 100, 987654321]\nprint l\nn = rank(l)\nprint n\nl = unrank(n)\nprint l\n"}
{"id": 50933, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 50934, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 50935, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 50936, "name": "Reverse the gender of a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n"}
{"id": 50937, "name": "Reverse the gender of a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n"}
{"id": 50938, "name": "Audio alarm", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    number := 0\n    for number < 1 {\n        fmt.Print(\"Enter number of seconds delay > 0 : \")\n        scanner.Scan()\n        input := scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n        number, _ = strconv.Atoi(input)\n    }\n\n    filename := \"\"\n    for filename == \"\" {\n        fmt.Print(\"Enter name of .mp3 file to play (without extension) : \")\n        scanner.Scan()\n        filename = scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n    }\n\n    cls := \"\\033[2J\\033[0;0H\" \n    fmt.Printf(\"%sAlarm will sound in %d seconds...\", cls, number)\n    time.Sleep(time.Duration(number) * time.Second)\n    fmt.Printf(cls)\n    cmd := exec.Command(\"play\", filename+\".mp3\")\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "import time\nimport os\n\nseconds = input(\"Enter a number of seconds: \")\nsound = input(\"Enter an mp3 filename: \")\n\ntime.sleep(float(seconds))\nos.startfile(sound + \".mp3\")\n"}
{"id": 50939, "name": "Decimal floating point number to binary", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n"}
{"id": 50940, "name": "Decimal floating point number to binary", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n"}
{"id": 50941, "name": "Decimal floating point number to binary", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n"}
{"id": 50942, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 50943, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 50944, "name": "Check Machin-like formulas", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n"}
{"id": 50945, "name": "Check Machin-like formulas", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n"}
{"id": 50946, "name": "MD5_Implementation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"bytes\"\n    \"encoding/binary\"\n)\n\ntype testCase struct {\n    hashCode string\n    string\n}\n\nvar testCases = []testCase{\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\nfunc main() {\n    for _, tc := range testCases {\n        fmt.Printf(\"%s\\n%x\\n\\n\", tc.hashCode, md5(tc.string))\n    }\n}\n\nvar shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}\nvar table [64]uint32\n\nfunc init() {\n    for i := range table {\n        table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))\n    }\n}\n\nfunc md5(s string) (r [16]byte) {\n    padded := bytes.NewBuffer([]byte(s))\n    padded.WriteByte(0x80)\n    for padded.Len() % 64 != 56 {\n        padded.WriteByte(0)\n    }\n    messageLenBits := uint64(len(s)) * 8\n    binary.Write(padded, binary.LittleEndian, messageLenBits)\n\n    var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476\n    var buffer [16]uint32\n    for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { \n        a1, b1, c1, d1 := a, b, c, d\n        for j := 0; j < 64; j++ {\n            var f uint32\n            bufferIndex := j\n            round := j >> 4\n            switch round {\n            case 0:\n                f = (b1 & c1) | (^b1 & d1)\n            case 1:\n                f = (b1 & d1) | (c1 & ^d1)\n                bufferIndex = (bufferIndex*5 + 1) & 0x0F\n            case 2:\n                f = b1 ^ c1 ^ d1\n                bufferIndex = (bufferIndex*3 + 5) & 0x0F\n            case 3:\n                f = c1 ^ (b1 | ^d1)\n                bufferIndex = (bufferIndex * 7) & 0x0F\n            }\n            sa := shift[(round<<2)|(j&3)]\n            a1 += f + buffer[bufferIndex] + table[j]\n            a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1\n        }\n        a, b, c, d = a+a1, b+b1, c+c1, d+d1\n    }\n\n    binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})\n    return\n}\n", "Python": "import math\n\nrotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\nconstants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]\n\ninit_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]\n\nfunctions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \\\n            16*[lambda b, c, d: (d & b) | (~d & c)] + \\\n            16*[lambda b, c, d: b ^ c ^ d] + \\\n            16*[lambda b, c, d: c ^ (b | ~d)]\n\nindex_functions = 16*[lambda i: i] + \\\n                  16*[lambda i: (5*i + 1)%16] + \\\n                  16*[lambda i: (3*i + 5)%16] + \\\n                  16*[lambda i: (7*i)%16]\n\ndef left_rotate(x, amount):\n    x &= 0xFFFFFFFF\n    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF\n\ndef md5(message):\n\n    message = bytearray(message) \n    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff\n    message.append(0x80)\n    while len(message)%64 != 56:\n        message.append(0)\n    message += orig_len_in_bits.to_bytes(8, byteorder='little')\n\n    hash_pieces = init_values[:]\n\n    for chunk_ofst in range(0, len(message), 64):\n        a, b, c, d = hash_pieces\n        chunk = message[chunk_ofst:chunk_ofst+64]\n        for i in range(64):\n            f = functions[i](b, c, d)\n            g = index_functions[i](i)\n            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')\n            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF\n            a, b, c, d = d, new_b, b, c\n        for i, val in enumerate([a, b, c, d]):\n            hash_pieces[i] += val\n            hash_pieces[i] &= 0xFFFFFFFF\n    \n    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))\n        \ndef md5_to_hex(digest):\n    raw = digest.to_bytes(16, byteorder='little')\n    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))\n\nif __name__=='__main__':\n    demo = [b\"\", b\"a\", b\"abc\", b\"message digest\", b\"abcdefghijklmnopqrstuvwxyz\",\n            b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n            b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"]\n    for message in demo:\n        print(md5_to_hex(md5(message)),' <= \"',message.decode('ascii'),'\"', sep='')\n"}
{"id": 50947, "name": "K-means++ clustering", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype r2 struct {\n    x, y float64\n}\n\ntype r2c struct {\n    r2\n    c int \n}\n\n\nfunc kmpp(k int, data []r2c) {\n    kMeans(data, kmppSeeds(k, data))\n}\n\n\n\nfunc kmppSeeds(k int, data []r2c) []r2 {\n    s := make([]r2, k)\n    s[0] = data[rand.Intn(len(data))].r2\n    d2 := make([]float64, len(data))\n    for i := 1; i < k; i++ {\n        var sum float64\n        for j, p := range data {\n            _, dMin := nearest(p, s[:i])\n            d2[j] = dMin * dMin\n            sum += d2[j]\n        }\n        target := rand.Float64() * sum\n        j := 0\n        for sum = d2[0]; sum < target; sum += d2[j] {\n            j++\n        }\n        s[i] = data[j].r2\n    }\n    return s\n}\n\n\n\n\nfunc nearest(p r2c, mean []r2) (int, float64) {\n    iMin := 0\n    dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y)\n    for i := 1; i < len(mean); i++ {\n        d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y)\n        if d < dMin {\n            dMin = d\n            iMin = i\n        }\n    }\n    return iMin, dMin\n}\n\n\nfunc kMeans(data []r2c, mean []r2) {\n    \n    for i, p := range data {\n        cMin, _ := nearest(p, mean)\n        data[i].c = cMin\n    }\n    mLen := make([]int, len(mean))\n    for {\n        \n        for i := range mean {\n            mean[i] = r2{}\n            mLen[i] = 0\n        }\n        for _, p := range data {\n            mean[p.c].x += p.x\n            mean[p.c].y += p.y\n            mLen[p.c]++\n        }\n        for i := range mean {\n            inv := 1 / float64(mLen[i])\n            mean[i].x *= inv\n            mean[i].y *= inv\n        }\n        \n        var changes int\n        for i, p := range data {\n            if cMin, _ := nearest(p, mean); cMin != p.c {\n                changes++\n                data[i].c = cMin\n            }\n        }\n        if changes == 0 {\n            return\n        }\n    }\n}\n\n\ntype ecParam struct {\n    k          int\n    nPoints    int\n    xBox, yBox int\n    stdv       int\n}\n\n\nfunc main() {\n    ec := &ecParam{6, 30000, 300, 200, 30}\n    \n    origin, data := genECData(ec)\n    vis(ec, data, \"origin\")\n    fmt.Println(\"Data set origins:\")\n    fmt.Println(\"    x      y\")\n    for _, o := range origin {\n        fmt.Printf(\"%5.1f  %5.1f\\n\", o.x, o.y)\n    }\n\n    kmpp(ec.k, data)\n    \n    fmt.Println(\n        \"\\nCluster centroids, mean distance from centroid, number of points:\")\n    fmt.Println(\"    x      y  distance  points\")\n    cent := make([]r2, ec.k)\n    cLen := make([]int, ec.k)\n    inv := make([]float64, ec.k)\n    for _, p := range data {\n        cent[p.c].x += p.x \n        cent[p.c].y += p.y \n        cLen[p.c]++\n    }\n    for i, iLen := range cLen {\n        inv[i] = 1 / float64(iLen)\n        cent[i].x *= inv[i]\n        cent[i].y *= inv[i]\n    }\n    dist := make([]float64, ec.k)\n    for _, p := range data {\n        dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y)\n    }\n    for i, iLen := range cLen {\n        fmt.Printf(\"%5.1f  %5.1f  %8.1f  %6d\\n\",\n            cent[i].x, cent[i].y, dist[i]*inv[i], iLen)\n    }\n    vis(ec, data, \"clusters\")\n}\n\n\n\n\n\n\n\nfunc genECData(ec *ecParam) (orig []r2, data []r2c) {\n    rand.Seed(time.Now().UnixNano())\n    orig = make([]r2, ec.k)\n    data = make([]r2c, ec.nPoints)\n    for i, n := 0, 0; i < ec.k; i++ {\n        x := rand.Float64() * float64(ec.xBox)\n        y := rand.Float64() * float64(ec.yBox)\n        orig[i] = r2{x, y}\n        for j := ec.nPoints / ec.k; j > 0; j-- {\n            data[n].x = rand.NormFloat64()*float64(ec.stdv) + x\n            data[n].y = rand.NormFloat64()*float64(ec.stdv) + y\n            data[n].c = i\n            n++\n        }\n    }\n    return\n}\n\n\nfunc vis(ec *ecParam, data []r2c, fn string) {\n    colors := make([]color.NRGBA, ec.k)\n    for i := range colors {\n        i3 := i * 3\n        third := i3 / ec.k\n        frac := uint8((i3 % ec.k) * 255 / ec.k)\n        switch third {\n        case 0:\n            colors[i] = color.NRGBA{frac, 255 - frac, 0, 255}\n        case 1:\n            colors[i] = color.NRGBA{0, frac, 255 - frac, 255}\n        case 2:\n            colors[i] = color.NRGBA{255 - frac, 0, frac, 255}\n        }\n    }\n    bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv)\n    im := image.NewNRGBA(bounds)\n    draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    fMinX := float64(bounds.Min.X)\n    fMaxX := float64(bounds.Max.X)\n    fMinY := float64(bounds.Min.Y)\n    fMaxY := float64(bounds.Max.Y)\n    for _, p := range data {\n        imx := math.Floor(p.x)\n        imy := math.Floor(float64(ec.yBox) - p.y)\n        if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY {\n            im.SetNRGBA(int(imx), int(imy), colors[p.c])\n        }\n    }\n    f, err := os.Create(fn + \".png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = png.Encode(f, im)\n    if err != nil {\n        fmt.Println(err)\n    }\n    err = f.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "from math import pi, sin, cos\nfrom collections import namedtuple\nfrom random import random, choice\nfrom copy import copy\n\ntry:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\n\nFLOAT_MAX = 1e100\n\n\nclass Point:\n    __slots__ = [\"x\", \"y\", \"group\"]\n    def __init__(self, x=0.0, y=0.0, group=0):\n        self.x, self.y, self.group = x, y, group\n\n\ndef generate_points(npoints, radius):\n    points = [Point() for _ in xrange(npoints)]\n\n    \n    for p in points:\n        r = random() * radius\n        ang = random() * 2 * pi\n        p.x = r * cos(ang)\n        p.y = r * sin(ang)\n\n    return points\n\n\ndef nearest_cluster_center(point, cluster_centers):\n    \n    def sqr_distance_2D(a, b):\n        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2\n\n    min_index = point.group\n    min_dist = FLOAT_MAX\n\n    for i, cc in enumerate(cluster_centers):\n        d = sqr_distance_2D(cc, point)\n        if min_dist > d:\n            min_dist = d\n            min_index = i\n\n    return (min_index, min_dist)\n\n\ndef kpp(points, cluster_centers):\n    cluster_centers[0] = copy(choice(points))\n    d = [0.0 for _ in xrange(len(points))]\n\n    for i in xrange(1, len(cluster_centers)):\n        sum = 0\n        for j, p in enumerate(points):\n            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]\n            sum += d[j]\n\n        sum *= random()\n\n        for j, di in enumerate(d):\n            sum -= di\n            if sum > 0:\n                continue\n            cluster_centers[i] = copy(points[j])\n            break\n\n    for p in points:\n        p.group = nearest_cluster_center(p, cluster_centers)[0]\n\n\ndef lloyd(points, nclusters):\n    cluster_centers = [Point() for _ in xrange(nclusters)]\n\n    \n    kpp(points, cluster_centers)\n\n    lenpts10 = len(points) >> 10\n\n    changed = 0\n    while True:\n        \n        for cc in cluster_centers:\n            cc.x = 0\n            cc.y = 0\n            cc.group = 0\n\n        for p in points:\n            cluster_centers[p.group].group += 1\n            cluster_centers[p.group].x += p.x\n            cluster_centers[p.group].y += p.y\n\n        for cc in cluster_centers:\n            cc.x /= cc.group\n            cc.y /= cc.group\n\n        \n        changed = 0\n        for p in points:\n            min_i = nearest_cluster_center(p, cluster_centers)[0]\n            if min_i != p.group:\n                changed += 1\n                p.group = min_i\n\n        \n        if changed <= lenpts10:\n            break\n\n    for i, cc in enumerate(cluster_centers):\n        cc.group = i\n\n    return cluster_centers\n\n\ndef print_eps(points, cluster_centers, W=400, H=400):\n    Color = namedtuple(\"Color\", \"r g b\");\n\n    colors = []\n    for i in xrange(len(cluster_centers)):\n        colors.append(Color((3 * (i + 1) % 11) / 11.0,\n                            (7 * i % 11) / 11.0,\n                            (9 * i % 11) / 11.0))\n\n    max_x = max_y = -FLOAT_MAX\n    min_x = min_y = FLOAT_MAX\n\n    for p in points:\n        if max_x < p.x: max_x = p.x\n        if min_x > p.x: min_x = p.x\n        if max_y < p.y: max_y = p.y\n        if min_y > p.y: min_y = p.y\n\n    scale = min(W / (max_x - min_x),\n                H / (max_y - min_y))\n    cx = (max_x + min_x) / 2\n    cy = (max_y + min_y) / 2\n\n    print \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: -5 -5 %d %d\" % (W + 10, H + 10)\n\n    print (\"/l {rlineto} def /m {rmoveto} def\\n\" +\n           \"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\\n\" +\n           \"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath \" +\n           \"   gsave 1 setgray fill grestore gsave 3 setlinewidth\" +\n           \" 1 setgray stroke grestore 0 setgray stroke }def\")\n\n    for i, cc in enumerate(cluster_centers):\n        print (\"%g %g %g setrgbcolor\" %\n               (colors[i].r, colors[i].g, colors[i].b))\n\n        for p in points:\n            if p.group != i:\n                continue\n            print (\"%.3f %.3f c\" % ((p.x - cx) * scale + W / 2,\n                                    (p.y - cy) * scale + H / 2))\n\n        print (\"\\n0 setgray %g %g s\" % ((cc.x - cx) * scale + W / 2,\n                                        (cc.y - cy) * scale + H / 2))\n\n    print \"\\n%%%%EOF\"\n\n\ndef main():\n    npoints = 30000\n    k = 7 \n\n    points = generate_points(npoints, 10)\n    cluster_centers = lloyd(points, k)\n    print_eps(points, cluster_centers)\n\n\nmain()\n"}
{"id": 50948, "name": "Maze solving", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\" \n    \"math/rand\"\n    \"time\"\n)\n\ntype maze struct { \n    c2 [][]byte \n    h2 [][]byte \n    v2 [][]byte \n}\n\nfunc newMaze(rows, cols int) *maze {\n    c := make([]byte, rows*cols)              \n    h := bytes.Repeat([]byte{'-'}, rows*cols) \n    v := bytes.Repeat([]byte{'|'}, rows*cols) \n    c2 := make([][]byte, rows)                \n    h2 := make([][]byte, rows)                \n    v2 := make([][]byte, rows)                \n    for i := range h2 {\n        c2[i] = c[i*cols : (i+1)*cols]\n        h2[i] = h[i*cols : (i+1)*cols]\n        v2[i] = v[i*cols : (i+1)*cols]\n    }\n    return &maze{c2, h2, v2}\n}   \n    \nfunc (m *maze) String() string {\n    hWall := []byte(\"+---\")\n    hOpen := []byte(\"+   \")\n    vWall := []byte(\"|   \")\n    vOpen := []byte(\"    \")\n    rightCorner := []byte(\"+\\n\")\n    rightWall := []byte(\"|\\n\")\n    var b []byte\n    for r, hw := range m.h2 {\n        for _, h := range hw {\n            if h == '-' || r == 0 {\n                b = append(b, hWall...)\n            } else {\n                b = append(b, hOpen...)\n                if h != '-' && h != 0 {\n                    b[len(b)-2] = h\n                }\n            }\n        }\n        b = append(b, rightCorner...)\n        for c, vw := range m.v2[r] {\n            if vw == '|' || c == 0 {\n                b = append(b, vWall...)\n            } else {\n                b = append(b, vOpen...)\n                if vw != '|' && vw != 0 {\n                    b[len(b)-4] = vw\n                }\n            }\n            if m.c2[r][c] != 0 {\n                b[len(b)-2] = m.c2[r][c]\n            }\n        }\n        b = append(b, rightWall...)\n    }\n    for _ = range m.h2[0] {\n        b = append(b, hWall...)\n    }\n    b = append(b, rightCorner...)\n    return string(b)\n}\n\nfunc (m *maze) gen() {\n    m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))\n}\n\nconst (\n    up = iota\n    dn\n    rt\n    lf\n)\n\nfunc (m *maze) g2(r, c int) {\n    m.c2[r][c] = ' '\n    for _, dir := range rand.Perm(4) {\n        switch dir {\n        case up:\n            if r > 0 && m.c2[r-1][c] == 0 {\n                m.h2[r][c] = 0\n                m.g2(r-1, c)\n            }\n        case lf:\n            if c > 0 && m.c2[r][c-1] == 0 {\n                m.v2[r][c] = 0\n                m.g2(r, c-1)\n            }\n        case dn:\n            if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {\n                m.h2[r+1][c] = 0\n                m.g2(r+1, c)\n            }\n        case rt:\n            if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {\n                m.v2[r][c+1] = 0\n                m.g2(r, c+1)\n            } \n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const height = 4\n    const width = 7\n    m := newMaze(height, width)\n    m.gen() \n    m.solve(\n        rand.Intn(height), rand.Intn(width),\n        rand.Intn(height), rand.Intn(width))\n    fmt.Print(m)\n}   \n    \nfunc (m *maze) solve(ra, ca, rz, cz int) {\n    var rSolve func(ra, ca, dir int) bool\n    rSolve = func(r, c, dir int) bool {\n        if r == rz && c == cz {\n            m.c2[r][c] = 'F'\n            return true\n        }\n        if dir != dn && m.h2[r][c] == 0 {\n            if rSolve(r-1, c, up) {\n                m.c2[r][c] = '^'\n                m.h2[r][c] = '^'\n                return true\n            }\n        }\n        if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 {\n            if rSolve(r+1, c, dn) {\n                m.c2[r][c] = 'v'\n                m.h2[r+1][c] = 'v'\n                return true\n            }\n        }\n        if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 {\n            if rSolve(r, c+1, rt) {\n                m.c2[r][c] = '>'\n                m.v2[r][c+1] = '>'\n                return true\n            }\n        }\n        if dir != rt && m.v2[r][c] == 0 {\n            if rSolve(r, c-1, lf) {\n                m.c2[r][c] = '<'\n                m.v2[r][c] = '<'\n                return true\n            }\n        }\n        return false\n    }\n    rSolve(ra, ca, -1)\n    m.c2[ra][ca] = 'S'\n}\n", "Python": "\n\ndef Dijkstra(Graph, source):\n    \n    \n    infinity = float('infinity')\n    n = len(graph)\n    dist = [infinity]*n   \n    previous = [infinity]*n \n    dist[source] = 0        \n    Q = list(range(n)) \n    while Q:           \n        u = min(Q, key=lambda n:dist[n])                 \n        Q.remove(u)\n        if dist[u] == infinity:\n            break \n        for v in range(n):               \n            if Graph[u][v] and (v in Q): \n                alt = dist[u] + Graph[u][v]\n                if alt < dist[v]:       \n                    dist[v] = alt\n                    previous[v] = u\n    return dist,previous\n\ndef display_solution(predecessor):\n    cell = len(predecessor)-1\n    while cell:\n        print(cell,end='<')\n        cell = predecessor[cell]\n    print(0)\n"}
{"id": 50949, "name": "Generate random numbers without repeating a value", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\nfunc generate(from, to int64) {\n    if to < from || from < 0 {\n        log.Fatal(\"Invalid range.\")\n    }\n    span := to - from + 1\n    generated := make([]bool, span) \n    count := span\n    for count > 0 {\n        n := from + rand.Int63n(span) \n        if !generated[n-from] {\n            generated[n-from] = true\n            fmt.Printf(\"%2d \", n)\n            count--\n        }\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    \n    for i := 1; i <= 5; i++ {\n        generate(1, 20)\n    }\n}\n", "Python": "import random\n\nprint(random.sample(range(1, 21), 20))\n"}
{"id": 50950, "name": "Solve triangle solitare puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype solution struct{ peg, over, land int }\n\ntype move struct{ from, to int }\n\nvar emptyStart = 1\n\nvar board [16]bool\n\nvar jumpMoves = [16][]move{\n    {},\n    {{2, 4}, {3, 6}},\n    {{4, 7}, {5, 9}},\n    {{5, 8}, {6, 10}},\n    {{2, 1}, {5, 6}, {7, 11}, {8, 13}},\n    {{8, 12}, {9, 14}},\n    {{3, 1}, {5, 4}, {9, 13}, {10, 15}},\n    {{4, 2}, {8, 9}},\n    {{5, 3}, {9, 10}},\n    {{5, 2}, {8, 7}},\n    {{9, 8}},\n    {{12, 13}},\n    {{8, 5}, {13, 14}},\n    {{8, 4}, {9, 6}, {12, 11}, {14, 15}},\n    {{9, 5}, {13, 12}},\n    {{10, 6}, {14, 13}},\n}\n\nvar solutions []solution\n\nfunc initBoard() {\n    for i := 1; i < 16; i++ {\n        board[i] = true\n    }\n    board[emptyStart] = false\n}\n\nfunc (sol solution) split() (int, int, int) {\n    return sol.peg, sol.over, sol.land\n}\n\nfunc (mv move) split() (int, int) {\n    return mv.from, mv.to\n}\n\nfunc drawBoard() {\n    var pegs [16]byte\n    for i := 1; i < 16; i++ {\n        if board[i] {\n            pegs[i] = fmt.Sprintf(\"%X\", i)[0]\n        } else {\n            pegs[i] = '-'\n        }\n    }\n    fmt.Printf(\"       %c\\n\", pegs[1])\n    fmt.Printf(\"      %c %c\\n\", pegs[2], pegs[3])\n    fmt.Printf(\"     %c %c %c\\n\", pegs[4], pegs[5], pegs[6])\n    fmt.Printf(\"    %c %c %c %c\\n\", pegs[7], pegs[8], pegs[9], pegs[10])\n    fmt.Printf(\"   %c %c %c %c %c\\n\", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n}\n\nfunc solved() bool {\n    count := 0\n    for _, b := range board {\n        if b {\n            count++\n        }\n    }\n    return count == 1 \n}\n\nfunc solve() {\n    if solved() {\n        return\n    }\n    for peg := 1; peg < 16; peg++ {\n        if board[peg] {\n            for _, mv := range jumpMoves[peg] {\n                over, land := mv.split()\n                if board[over] && !board[land] {\n                    saveBoard := board\n                    board[peg] = false\n                    board[over] = false\n                    board[land] = true\n                    solutions = append(solutions, solution{peg, over, land})\n                    solve()\n                    if solved() {\n                        return \n                    }\n                    board = saveBoard\n                    solutions = solutions[:len(solutions)-1]\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    initBoard()\n    solve()\n    initBoard()\n    drawBoard()\n    fmt.Printf(\"Starting with peg %X removed\\n\\n\", emptyStart)\n    for _, solution := range solutions {\n        peg, over, land := solution.split()\n        board[peg] = false\n        board[over] = false\n        board[land] = true\n        drawBoard()\n        fmt.Printf(\"Peg %X jumped over %X to land on %X\\n\\n\", peg, over, land)\n    }\n}\n", "Python": "\n\n\ndef DrawBoard(board):\n  peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n  for n in xrange(1,16):\n    peg[n] = '.'\n    if n in board:\n      peg[n] = \"%X\" % n\n  print \"     %s\" % peg[1]\n  print \"    %s %s\" % (peg[2],peg[3])\n  print \"   %s %s %s\" % (peg[4],peg[5],peg[6])\n  print \"  %s %s %s %s\" % (peg[7],peg[8],peg[9],peg[10])\n  print \" %s %s %s %s %s\" % (peg[11],peg[12],peg[13],peg[14],peg[15])\n\n\n\ndef RemovePeg(board,n):\n  board.remove(n)\n\n\ndef AddPeg(board,n):\n  board.append(n)\n\n\ndef IsPeg(board,n):\n  return n in board\n\n\n\nJumpMoves = { 1: [ (2,4),(3,6) ],  \n              2: [ (4,7),(5,9)  ],\n              3: [ (5,8),(6,10) ],\n              4: [ (2,1),(5,6),(7,11),(8,13) ],\n              5: [ (8,12),(9,14) ],\n              6: [ (3,1),(5,4),(9,13),(10,15) ],\n              7: [ (4,2),(8,9)  ],\n              8: [ (5,3),(9,10) ],\n              9: [ (5,2),(8,7)  ],\n             10: [ (9,8) ],\n             11: [ (12,13) ],\n             12: [ (8,5),(13,14) ],\n             13: [ (8,4),(9,6),(12,11),(14,15) ],\n             14: [ (9,5),(13,12)  ],\n             15: [ (10,6),(14,13) ]\n            }\n\nSolution = []\n\n\n\ndef Solve(board):\n  \n  if len(board) == 1:\n    return board \n  \n  for peg in xrange(1,16): \n    if IsPeg(board,peg):\n      movelist = JumpMoves[peg]\n      for over,land in movelist:\n        if IsPeg(board,over) and not IsPeg(board,land):\n          saveboard = board[:] \n          RemovePeg(board,peg)\n          RemovePeg(board,over)\n          AddPeg(board,land) \n\n          Solution.append((peg,over,land))\n\n          board = Solve(board)\n          if len(board) == 1:\n            return board\n        \n          board = saveboard[:] \n          del Solution[-1] \n  return board\n\n\n\n\ndef InitSolve(empty):\n  board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n  RemovePeg(board,empty_start)\n  Solve(board)\n\n\nempty_start = 1\nInitSolve(empty_start)\n\nboard = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nRemovePeg(board,empty_start)\nfor peg,over,land in Solution:\n  RemovePeg(board,peg)\n  RemovePeg(board,over)\n  AddPeg(board,land) \n  DrawBoard(board)\n  print \"Peg %X jumped over %X to land on %X\\n\" % (peg,over,land)\n"}
{"id": 50951, "name": "Non-transitive dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n    found := make([]bool, 256)\n    for i := 1; i <= 4; i++ {\n        for j := 1; j <= 4; j++ {\n            for k := 1; k <= 4; k++ {\n                for l := 1; l <= 4; l++ {\n                    c := [4]int{i, j, k, l}\n                    sort.Ints(c[:])\n                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n                    if !found[key] {\n                        found[key] = true\n                        res = append(res, c)\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc cmp(x, y [4]int) int {\n    xw := 0\n    yw := 0\n    for i := 0; i < 4; i++ {\n        for j := 0; j < 4; j++ {\n            if x[i] > y[j] {\n                xw++\n            } else if y[j] > x[i] {\n                yw++\n            }\n        }\n    }\n    if xw < yw {\n        return -1\n    } else if xw > yw {\n        return 1\n    }\n    return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n    var c = len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                first := cmp(cs[i], cs[j])\n                if first == -1 {\n                    second := cmp(cs[j], cs[k])\n                    if second == -1 {\n                        third := cmp(cs[i], cs[k])\n                        if third == 1 {\n                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n    c := len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                for l := 0; l < c; l++ {\n                    first := cmp(cs[i], cs[j])\n                    if first == -1 {\n                        second := cmp(cs[j], cs[k])\n                        if second == -1 {\n                            third := cmp(cs[k], cs[l])\n                            if third == -1 {\n                                fourth := cmp(cs[i], cs[l])\n                                if fourth == 1 {\n                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc main() {\n    combs := fourFaceCombs()\n    fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n    it3 := findIntransitive3(combs)\n    fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n    for _, a := range it3 {\n        fmt.Println(a)\n    }\n    it4 := findIntransitive4(combs)\n    fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n    for _, a := range it4 {\n        fmt.Println(a)\n    }\n}\n", "Python": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n    dice = list(cmbr(faces, n))\n \n    succ = [set(j for j, b in enumerate(dice)\n                    if sum((x>y) - (x<y) for x in a for y in b) > 0)\n                for a in dice]\n \n    def loops(seq):\n        s = succ[seq[-1]]\n\n        if len(seq) == m:\n            if seq[0] in s: yield seq\n            return\n\n        for d in (x for x in s if x > seq[0] and not x in seq):\n            yield from loops(seq + (d,))\n \n    yield from (tuple(''.join(dice[s]) for s in x)\n                    for i, v in enumerate(succ)\n                    for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n    print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n    t, t0 = time(), t\n    print(f'\\ttime: {t - t0:.4f} seconds\\n')\n"}
{"id": 50952, "name": "Non-transitive dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n    found := make([]bool, 256)\n    for i := 1; i <= 4; i++ {\n        for j := 1; j <= 4; j++ {\n            for k := 1; k <= 4; k++ {\n                for l := 1; l <= 4; l++ {\n                    c := [4]int{i, j, k, l}\n                    sort.Ints(c[:])\n                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n                    if !found[key] {\n                        found[key] = true\n                        res = append(res, c)\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc cmp(x, y [4]int) int {\n    xw := 0\n    yw := 0\n    for i := 0; i < 4; i++ {\n        for j := 0; j < 4; j++ {\n            if x[i] > y[j] {\n                xw++\n            } else if y[j] > x[i] {\n                yw++\n            }\n        }\n    }\n    if xw < yw {\n        return -1\n    } else if xw > yw {\n        return 1\n    }\n    return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n    var c = len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                first := cmp(cs[i], cs[j])\n                if first == -1 {\n                    second := cmp(cs[j], cs[k])\n                    if second == -1 {\n                        third := cmp(cs[i], cs[k])\n                        if third == 1 {\n                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n    c := len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                for l := 0; l < c; l++ {\n                    first := cmp(cs[i], cs[j])\n                    if first == -1 {\n                        second := cmp(cs[j], cs[k])\n                        if second == -1 {\n                            third := cmp(cs[k], cs[l])\n                            if third == -1 {\n                                fourth := cmp(cs[i], cs[l])\n                                if fourth == 1 {\n                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc main() {\n    combs := fourFaceCombs()\n    fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n    it3 := findIntransitive3(combs)\n    fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n    for _, a := range it3 {\n        fmt.Println(a)\n    }\n    it4 := findIntransitive4(combs)\n    fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n    for _, a := range it4 {\n        fmt.Println(a)\n    }\n}\n", "Python": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n    dice = list(cmbr(faces, n))\n \n    succ = [set(j for j, b in enumerate(dice)\n                    if sum((x>y) - (x<y) for x in a for y in b) > 0)\n                for a in dice]\n \n    def loops(seq):\n        s = succ[seq[-1]]\n\n        if len(seq) == m:\n            if seq[0] in s: yield seq\n            return\n\n        for d in (x for x in s if x > seq[0] and not x in seq):\n            yield from loops(seq + (d,))\n \n    yield from (tuple(''.join(dice[s]) for s in x)\n                    for i, v in enumerate(succ)\n                    for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n    print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n    t, t0 = time(), t\n    print(f'\\ttime: {t - t0:.4f} seconds\\n')\n"}
{"id": 50953, "name": "History variables", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"sync\"\n    \"time\"\n)\n\n\ntype history struct {\n    timestamp tsFunc\n    hs        []hset\n}\n\n\ntype tsFunc func() time.Time\n\n\ntype hset struct {\n    int           \n    t   time.Time \n}\n\n\nfunc newHistory(ts tsFunc) history {\n    return history{ts, []hset{{t: ts()}}}\n}   \n    \n\nfunc (h history) int() int {\n    return h.hs[len(h.hs)-1].int\n}\n    \n\nfunc (h *history) set(x int) time.Time {\n    t := h.timestamp()\n    h.hs = append(h.hs, hset{x, t})\n    return t\n}\n\n\nfunc (h history) dump() {\n    for _, hs := range h.hs {\n        fmt.Println(hs.t.Format(time.StampNano), hs.int)\n    }\n}   \n    \n\n\nfunc (h history) recall(t time.Time) (int,  bool) {\n    i := sort.Search(len(h.hs), func(i int) bool {\n        return h.hs[i].t.After(t)\n    })\n    if i > 0 {\n        return h.hs[i-1].int, true\n    }\n    return 0, false\n}\n\n\n\n\n\nfunc newTimestamper() tsFunc {\n    var last time.Time\n    return func() time.Time {\n        if t := time.Now(); t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n        }\n        return last\n    }\n}\n\n\n\nfunc newProtectedTimestamper() tsFunc {\n    var last time.Time\n    var m sync.Mutex\n    return func() (t time.Time) {\n        t = time.Now()\n        m.Lock() \n        if t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n            t = last\n        }\n        m.Unlock()\n        return\n    }\n}\n\nfunc main() {\n    \n    ts := newTimestamper()\n    \n    h := newHistory(ts)\n    \n    ref := []time.Time{h.set(3), h.set(1), h.set(4)}\n    \n    fmt.Println(\"History of variable h:\")\n    h.dump() \n    \n    \n    fmt.Println(\"Recalling values:\")\n    for _, t := range ref {\n        rv, _ := h.recall(t)\n        fmt.Println(rv)\n    }\n}\n", "Python": "import sys\n\nHIST = {}\n\ndef trace(frame, event, arg):\n    for name,val in frame.f_locals.items():\n        if name not in HIST:\n            HIST[name] = []\n        else:\n            if HIST[name][-1] is val:\n                continue\n        HIST[name].append(val)\n    return trace\n\ndef undo(name):\n    HIST[name].pop(-1)\n    return HIST[name][-1]\n\ndef main():\n    a = 10\n    a = 20\n\n    for i in range(5):\n        c = i\n\n    print \"c:\", c, \"-> undo x3 ->\",\n    c = undo('c')\n    c = undo('c')\n    c = undo('c')\n    print c\n    print 'HIST:', HIST\n\nsys.settrace(trace)\nmain()\n"}
{"id": 50954, "name": "Perceptron", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst c = 0.00001\n\nfunc linear(x float64) float64 {\n    return x*0.7 + 40\n}\n\ntype trainer struct {\n    inputs []float64\n    answer int\n}\n\nfunc newTrainer(x, y float64, a int) *trainer {\n    return &trainer{[]float64{x, y, 1}, a}\n}\n\ntype perceptron struct {\n    weights  []float64\n    training []*trainer\n}\n\nfunc newPerceptron(n, w, h int) *perceptron {\n    weights := make([]float64, n)\n    for i := 0; i < n; i++ {\n        weights[i] = rand.Float64()*2 - 1\n    }\n\n    training := make([]*trainer, 2000)\n    for i := 0; i < 2000; i++ {\n        x := rand.Float64() * float64(w)\n        y := rand.Float64() * float64(h)\n        answer := 1\n        if y < linear(x) {\n            answer = -1\n        }\n        training[i] = newTrainer(x, y, answer)\n    }\n    return &perceptron{weights, training}\n}\n\nfunc (p *perceptron) feedForward(inputs []float64) int {\n    if len(inputs) != len(p.weights) {\n        panic(\"weights and input length mismatch, program terminated\")\n    }\n    sum := 0.0\n    for i, w := range p.weights {\n        sum += inputs[i] * w\n    }\n    if sum > 0 {\n        return 1\n    }\n    return -1\n}\n\nfunc (p *perceptron) train(inputs []float64, desired int) {\n    guess := p.feedForward(inputs)\n    err := float64(desired - guess)\n    for i := range p.weights {\n        p.weights[i] += c * err * inputs[i]\n    }\n}\n\nfunc (p *perceptron) draw(dc *gg.Context, iterations int) {\n    le := len(p.training)\n    for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le {\n        p.train(p.training[count].inputs, p.training[count].answer)\n    }\n    x := float64(dc.Width())\n    y := linear(x)\n    dc.SetLineWidth(2)\n    dc.SetRGB255(0, 0, 0) \n    dc.DrawLine(0, linear(0), x, y)\n    dc.Stroke()\n    dc.SetLineWidth(1)\n    for i := 0; i < le; i++ {\n        guess := p.feedForward(p.training[i].inputs)\n        x := p.training[i].inputs[0] - 4\n        y := p.training[i].inputs[1] - 4\n        if guess > 0 {\n            dc.SetRGB(0, 0, 1) \n        } else {\n            dc.SetRGB(1, 0, 0) \n        }\n        dc.DrawCircle(x, y, 8)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    w, h := 640, 360\n    perc := newPerceptron(3, w, h)\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    perc.draw(dc, 2000)\n    dc.SavePNG(\"perceptron.png\")\n}\n", "Python": "import random\n\nTRAINING_LENGTH = 2000\n\nclass Perceptron:\n    \n    def __init__(self,n):\n        self.c = .01\n        self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)]\n\n    def feed_forward(self, inputs):\n        vars = []\n        for i in range(len(inputs)):\n            vars.append(inputs[i] * self.weights[i])\n        return self.activate(sum(vars))\n\n    def activate(self, value):\n        return 1 if value > 0 else -1\n\n    def train(self, inputs, desired):\n        guess = self.feed_forward(inputs)\n        error = desired - guess\n        for i in range(len(inputs)):\n            self.weights[i] += self.c * error * inputs[i]\n        \nclass Trainer():\n    \n    def __init__(self, x, y, a):\n        self.inputs = [x, y, 1]\n        self.answer = a\n\ndef F(x):\n    return 2 * x + 1\n\nif __name__ == \"__main__\":\n    ptron = Perceptron(3)\n    training = []\n    for i in range(TRAINING_LENGTH):\n        x = random.uniform(-10,10)\n        y = random.uniform(-10,10)\n        answer = 1\n        if y < F(x): answer = -1\n        training.append(Trainer(x,y,answer))\n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Untrained')\n    for row in result:\n        print(''.join(v for v in row))\n\n    for t in training:\n        ptron.train(t.inputs, t.answer)\n    \n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Trained')\n    for row in result:\n        print(''.join(v for v in row))\n"}
{"id": 50955, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "Python": ">>> exec \n10\n"}
{"id": 50956, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "Python": ">>> exec \n10\n"}
{"id": 50957, "name": "Pisano period", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(a, b uint) uint {\n    if b == 0 {\n        return a\n    }\n    return gcd(b, a%b)\n}\n\nfunc lcm(a, b uint) uint {\n    return a / gcd(a, b) * b\n}\n\nfunc ipow(x, p uint) uint {\n    prod := uint(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\n\nfunc getPrimes(n uint) []uint {\n    var primes []uint\n    for i := uint(2); i <= n; i++ {\n        div := n / i\n        mod := n % i\n        for mod == 0 {\n            primes = append(primes, i)\n            n = div\n            div = n / i\n            mod = n % i\n        }\n    }\n    return primes\n}\n\n\nfunc isPrime(n uint) 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 := uint(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\n\nfunc pisanoPeriod(m uint) uint {\n    var p, c uint = 0, 1\n    for i := uint(0); i < m*m; i++ {\n        p, c = c, (p+c)%m\n        if p == 0 && c == 1 {\n            return i + 1\n        }\n    }\n    return 1\n}\n\n\nfunc pisanoPrime(p uint, k uint) uint {\n    if !isPrime(p) || k == 0 {\n        return 0 \n    }\n    return ipow(p, k-1) * pisanoPeriod(p)\n}\n\n\nfunc pisano(m uint) uint {\n    primes := getPrimes(m)\n    primePowers := make(map[uint]uint)\n    for _, p := range primes {\n        primePowers[p]++\n    }\n    var pps []uint\n    for k, v := range primePowers {\n        pps = append(pps, pisanoPrime(k, v))\n    }\n    if len(pps) == 0 {\n        return 1\n    }\n    if len(pps) == 1 {\n        return pps[0]\n    }    \n    f := pps[0]\n    for i := 1; i < len(pps); i++ {\n        f = lcm(f, pps[i])\n    }\n    return f\n}\n\nfunc main() {\n    for p := uint(2); p < 15; p++ {\n        pp := pisanoPrime(p, 2)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%2d: 2) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    for p := uint(2); p < 180; p++ {\n        pp := pisanoPrime(p, 1)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%3d: 1) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    fmt.Println(\"pisano(n) for integers 'n' from 1 to 180 are:\")\n    for n := uint(1); n <= 180; n++ {\n        fmt.Printf(\"%3d \", pisano(n))\n        if n != 1 && n%15 == 0 {\n            fmt.Println()\n        }\n    }    \n    fmt.Println()\n}\n", "Python": "from sympy import isprime, lcm, factorint, primerange\nfrom functools import reduce\n\n\ndef pisano1(m):\n    \"Simple definition\"\n    if m < 2:\n        return 1\n    lastn, n = 0, 1\n    for i in range(m ** 2):\n        lastn, n = n, (lastn + n) % m\n        if lastn == 0 and n == 1:\n            return i + 1\n    return 1\n\ndef pisanoprime(p, k):\n    \"Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1\"\n    assert isprime(p) and k > 0\n    return p ** (k - 1) * pisano1(p)\n\ndef pisano_mult(m, n):\n    \"pisano(m*n) where m and n assumed coprime integers\"\n    return lcm(pisano1(m), pisano1(n))\n\ndef pisano2(m):\n    \"Uses prime factorization of m\"\n    return reduce(lcm, (pisanoprime(prime, mult)\n                        for prime, mult in factorint(m).items()), 1)\n\n\nif __name__ == '__main__':\n    for n in range(1, 181):\n        assert pisano1(n) == pisano2(n), \"Wall-Sun-Sun prime exists??!!\"\n    print(\"\\nPisano period (p, 2) for primes less than 50\\n \",\n          [pisanoprime(prime, 2) for prime in primerange(1, 50)])\n    print(\"\\nPisano period (p, 1) for primes less than 180\\n \",\n          [pisanoprime(prime, 1) for prime in primerange(1, 180)])\n    print(\"\\nPisano period (p) for integers 1 to 180\")\n    for i in range(1, 181):\n        print(\" %3d\" % pisano2(i), end=\"\" if i % 10 else \"\\n\")\n"}
{"id": 50958, "name": "Railway circuit", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    right    = 1\n    left     = -1\n    straight = 0\n)\n\nfunc normalize(tracks []int) string {\n    size := len(tracks)\n    a := make([]byte, size)\n    for i := 0; i < size; i++ {\n        a[i] = \"abc\"[tracks[i]+1]\n    }\n\n    \n\n    norm := string(a)\n    for i := 0; i < size; i++ {\n        s := string(a)\n        if s < norm {\n            norm = s\n        }\n        tmp := a[0]\n        copy(a, a[1:])\n        a[size-1] = tmp\n    }\n    return norm\n}\n\nfunc fullCircleStraight(tracks []int, nStraight int) bool {\n    if nStraight == 0 {\n        return true\n    }\n\n    \n    count := 0\n    for _, track := range tracks {\n        if track == straight {\n            count++\n        }\n    }\n    if count != nStraight {\n        return false\n    }\n\n    \n    var straightTracks [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == straight {\n            straightTracks[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if straightTracks[i] != straightTracks[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if straightTracks[i] != straightTracks[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc fullCircleRight(tracks []int) bool {\n    \n    sum := 0\n    for _, track := range tracks {\n        sum += track * 30\n    }\n    if sum%360 != 0 {\n        return false\n    }\n\n    \n    var rTurns [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == right {\n            rTurns[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if rTurns[i] != rTurns[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if rTurns[i] != rTurns[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc circuits(nCurved, nStraight int) {\n    solutions := make(map[string][]int)\n    gen := getPermutationsGen(nCurved, nStraight)\n    for gen.hasNext() {\n        tracks := gen.next()\n        if !fullCircleStraight(tracks, nStraight) {\n            continue\n        }\n        if !fullCircleRight(tracks) {\n            continue\n        }\n        tracks2 := make([]int, len(tracks))\n        copy(tracks2, tracks)\n        solutions[normalize(tracks)] = tracks2\n    }\n    report(solutions, nCurved, nStraight)\n}\n\nfunc getPermutationsGen(nCurved, nStraight int) PermutationsGen {\n    if (nCurved+nStraight-12)%4 != 0 {\n        panic(\"input must be 12 + k * 4\")\n    }\n    var trackTypes []int\n    switch nStraight {\n    case 0:\n        trackTypes = []int{right, left}\n    case 12:\n        trackTypes = []int{right, straight}\n    default:\n        trackTypes = []int{right, left, straight}\n    }\n    return NewPermutationsGen(nCurved+nStraight, trackTypes)\n}\n\nfunc report(sol map[string][]int, numC, numS int) {\n    size := len(sol)\n    fmt.Printf(\"\\n%d solution(s) for C%d,%d \\n\", size, numC, numS)\n    if numC <= 20 {\n        for _, tracks := range sol {\n            for _, track := range tracks {\n                fmt.Printf(\"%2d \", track)\n            }\n            fmt.Println()\n        }\n    }\n}\n\n\ntype PermutationsGen struct {\n    NumPositions int\n    choices      []int\n    indices      []int\n    sequence     []int\n    carry        int\n}\n\nfunc NewPermutationsGen(numPositions int, choices []int) PermutationsGen {\n    indices := make([]int, numPositions)\n    sequence := make([]int, numPositions)\n    carry := 0\n    return PermutationsGen{numPositions, choices, indices, sequence, carry}\n}\n\nfunc (p *PermutationsGen) next() []int {\n    p.carry = 1\n\n    \n    for i := 1; i < len(p.indices) && p.carry > 0; i++ {\n        p.indices[i] += p.carry\n        p.carry = 0\n        if p.indices[i] == len(p.choices) {\n            p.carry = 1\n            p.indices[i] = 0\n        }\n    }\n    for j := 0; j < len(p.indices); j++ {\n        p.sequence[j] = p.choices[p.indices[j]]\n    }\n    return p.sequence\n}\n\nfunc (p *PermutationsGen) hasNext() bool {\n    return p.carry != 1\n}\n\nfunc main() {\n    for n := 12; n <= 28; n += 4 {\n        circuits(n, 0)\n    }\n    circuits(12, 4)\n}\n", "Python": "from itertools import count, islice\nimport numpy as np\nfrom numpy import sin, cos, pi\n\n\nANGDIV = 12\nANG = 2*pi/ANGDIV\n\ndef draw_all(sols):\n    import matplotlib.pyplot as plt\n\n    def draw_track(ax, s):\n        turn, xend, yend = 0, [0], [0]\n\n        for d in s:\n            x0, y0 = xend[-1], yend[-1]\n            a = turn*ANG\n            cs, sn = cos(a), sin(a)\n            ang = a + d*pi/2\n            cx, cy = x0 + cos(ang), y0 + sin(ang)\n\n            da = np.linspace(ang, ang + d*ANG, 10)\n            xs = cx - cos(da)\n            ys = cy - sin(da)\n            ax.plot(xs, ys, 'green' if d == -1 else 'orange')\n\n            xend.append(xs[-1])\n            yend.append(ys[-1])\n            turn += d\n\n        ax.plot(xend, yend, 'k.', markersize=1)\n        ax.set_aspect(1)\n\n    ls = len(sols)\n    if ls == 0: return\n\n    w, h = min((abs(w*2 - h*3) + w*h - ls, w, h)\n        for w, h in ((w, (ls + w - 1)//w)\n            for w in range(1, ls + 1)))[1:]\n\n    fig, ax = plt.subplots(h, w, squeeze=False)\n    for a in ax.ravel(): a.set_axis_off()\n\n    for i, s in enumerate(sols):\n        draw_track(ax[i//w, i%w], s)\n\n    plt.show()\n\n\ndef match_up(this, that, equal_lr, seen):\n    if not this or not that: return\n\n    n = len(this[0][-1])\n    n2 = n*2\n\n    l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0\n\n    def record(m):\n        for _ in range(n2):\n            seen[m] = True\n            m = (m&1) << (n2 - 1) | (m >> 1)\n\n        if equal_lr:\n            m ^= (1<<n2) - 1\n            for _ in range(n2):\n                seen[m] = True\n                m = (m&1) << (n2 - 1) | (m >> 1)\n\n    l_n, r_n = len(this), len(that)\n    tol = 1e-3\n\n    while l_lo < l_n:\n        while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol:\n            l_hi += 1\n\n        while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol:\n            r_lo += 1\n\n        r_hi = r_lo\n        while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol:\n            r_hi += 1\n\n        for a in this[l_lo:l_hi]:\n            m_left = a[-2]<<n\n            for b in that[r_lo:r_hi]:\n                if (m := m_left | b[-2]) not in seen:\n                    if np.abs(a[1] + b[2]) < tol:\n                        record(m)\n                        record(int(f'{m:b}'[::-1], base=2))\n                        yield(a[-1] + b[-1])\n\n        l_lo, r_lo = l_hi, r_hi\n\ndef track_combo(left, right):\n    n = (left + right)//2\n    n1 = left + right - n\n\n    alphas = np.exp(1j*ANG*np.arange(ANGDIV))\n    def half_track(m, n):\n        turns = tuple(1 - 2*(m>>i & 1) for i in range(n))\n        rcnt = np.cumsum(turns)%ANGDIV\n        asum = np.sum(alphas[rcnt])\n        want = asum/alphas[rcnt[-1]]\n        return np.abs(asum), asum, want, m, turns\n\n    res = [[] for _ in range(right + 1)]\n    for i in range(1<<n):\n        b = i.bit_count()\n        if b <= right:\n            res[b].append(half_track(i, n))\n\n    for v in res: v.sort()\n    if n1 == n:\n        return res, res\n\n    res1 = [[] for _ in range(right + 1)]\n    for i in range(1<<n1):\n        b = i.bit_count()\n        if b <= right:\n            res1[b].append(half_track(i, n1))\n\n    for v in res: v.sort()\n    return res, res1\n\ndef railway(n):\n    seen = {}\n\n    for l in range(n//2, n + 1):\n        r = n - l\n        if not l >= r: continue\n\n        if (l - r)%ANGDIV == 0:\n            res_l, res_r = track_combo(l, r)\n\n            for i, this in enumerate(res_l):\n                if 2*i < r: continue\n                that = res_r[r - i]\n                for s in match_up(this, that, l == r, seen):\n                    yield s\n\nsols = []\nfor i, s in enumerate(railway(30)):\n    \n    print(i + 1, s)\n    sols.append(s)\n\ndraw_all(sols[:40])\n"}
{"id": 50959, "name": "Free polyominoes enumeration", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype point struct{ x, y int }\ntype polyomino []point\ntype pointset map[point]bool\n\nfunc (p point) rotate90() point  { return point{p.y, -p.x} }\nfunc (p point) rotate180() point { return point{-p.x, -p.y} }\nfunc (p point) rotate270() point { return point{-p.y, p.x} }\nfunc (p point) reflect() point   { return point{-p.x, p.y} }\n\nfunc (p point) String() string { return fmt.Sprintf(\"(%d, %d)\", p.x, p.y) }\n\n\nfunc (p point) contiguous() polyomino {\n    return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y},\n        point{p.x, p.y - 1}, point{p.x, p.y + 1}}\n}\n\n\nfunc (po polyomino) minima() (int, int) {\n    minx := po[0].x\n    miny := po[0].y\n    for i := 1; i < len(po); i++ {\n        if po[i].x < minx {\n            minx = po[i].x\n        }\n        if po[i].y < miny {\n            miny = po[i].y\n        }\n    }\n    return minx, miny\n}\n\nfunc (po polyomino) translateToOrigin() polyomino {\n    minx, miny := po.minima()\n    res := make(polyomino, len(po))\n    for i, p := range po {\n        res[i] = point{p.x - minx, p.y - miny}\n    }\n    sort.Slice(res, func(i, j int) bool {\n        return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y)\n    })\n    return res\n}\n\n\nfunc (po polyomino) rotationsAndReflections() []polyomino {\n    rr := make([]polyomino, 8)\n    for i := 0; i < 8; i++ {\n        rr[i] = make(polyomino, len(po))\n    }\n    copy(rr[0], po)\n    for j := 0; j < len(po); j++ {\n        rr[1][j] = po[j].rotate90()\n        rr[2][j] = po[j].rotate180()\n        rr[3][j] = po[j].rotate270()\n        rr[4][j] = po[j].reflect()\n        rr[5][j] = po[j].rotate90().reflect()\n        rr[6][j] = po[j].rotate180().reflect()\n        rr[7][j] = po[j].rotate270().reflect()\n    }\n    return rr\n}\n\nfunc (po polyomino) canonical() polyomino {\n    rr := po.rotationsAndReflections()\n    minr := rr[0].translateToOrigin()\n    mins := minr.String()\n    for i := 1; i < 8; i++ {\n        r := rr[i].translateToOrigin()\n        s := r.String()\n        if s < mins {\n            minr = r\n            mins = s\n        }\n    }\n    return minr\n}\n\nfunc (po polyomino) String() string {\n    return fmt.Sprintf(\"%v\", []point(po))\n}\n\nfunc (po polyomino) toPointset() pointset {\n    pset := make(pointset, len(po))\n    for _, p := range po {\n        pset[p] = true\n    }\n    return pset\n}\n\n\nfunc (po polyomino) newPoints() polyomino {\n    pset := po.toPointset()\n    m := make(pointset) \n    for _, p := range po {\n        pts := p.contiguous()\n        for _, pt := range pts {\n            if !pset[pt] {\n                m[pt] = true \n            }\n        }\n    }\n    poly := make(polyomino, 0, len(m))\n    for k := range m {\n        poly = append(poly, k)\n    }\n    return poly\n}\n\nfunc (po polyomino) newPolys() []polyomino {\n    pts := po.newPoints()\n    res := make([]polyomino, len(pts))\n    for i, pt := range pts {\n        poly := make(polyomino, len(po))\n        copy(poly, po)\n        poly = append(poly, pt)\n        res[i] = poly.canonical()\n    }\n    return res\n}\n\nvar monomino = polyomino{point{0, 0}}\nvar monominoes = []polyomino{monomino}\n\n\nfunc rank(n int) []polyomino {\n    switch {\n    case n < 0:\n        panic(\"n cannot be negative. Program terminated.\")\n    case n == 0:\n        return []polyomino{}\n    case n == 1:\n        return monominoes\n    default:\n        r := rank(n - 1)\n        m := make(map[string]bool)\n        var polys []polyomino\n        for _, po := range r {\n            for _, po2 := range po.newPolys() {\n                if s := po2.String(); !m[s] {\n                    polys = append(polys, po2)\n                    m[s] = true\n                }\n            }\n        }\n        sort.Slice(polys, func(i, j int) bool {\n            return polys[i].String() < polys[j].String()\n        })\n        return polys\n    }\n}\n\nfunc main() {\n    const n = 5\n    fmt.Printf(\"All free polyominoes of rank %d:\\n\\n\", n)\n    for _, poly := range rank(n) {\n        for _, pt := range poly {\n            fmt.Printf(\"%s \", pt)\n        }\n        fmt.Println()\n    }\n    const k = 10\n    fmt.Printf(\"\\nNumber of free polyominoes of ranks 1 to %d:\\n\", k)\n    for i := 1; i <= k; i++ {\n        fmt.Printf(\"%d \", len(rank(i)))\n    }\n    fmt.Println()\n}\n", "Python": "from itertools import imap, imap, groupby, chain, imap\nfrom operator import itemgetter\nfrom sys import argv\nfrom array import array\n\ndef concat_map(func, it):\n    return list(chain.from_iterable(imap(func, it)))\n\ndef minima(poly):\n    \n    return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))\n\ndef translate_to_origin(poly):\n    (minx, miny) = minima(poly)\n    return [(x - minx, y - miny) for (x, y) in poly]\n\nrotate90   = lambda (x, y): ( y, -x)\nrotate180  = lambda (x, y): (-x, -y)\nrotate270  = lambda (x, y): (-y,  x)\nreflect    = lambda (x, y): (-x,  y)\n\ndef rotations_and_reflections(poly):\n    \n    return (poly,\n            map(rotate90, poly),\n            map(rotate180, poly),\n            map(rotate270, poly),\n            map(reflect, poly),\n            [reflect(rotate90(pt)) for pt in poly],\n            [reflect(rotate180(pt)) for pt in poly],\n            [reflect(rotate270(pt)) for pt in poly])\n\ndef canonical(poly):\n    return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly))\n\ndef unique(lst):\n    lst.sort()\n    return map(next, imap(itemgetter(1), groupby(lst)))\n\n\ncontiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]\n\ndef new_points(poly):\n    \n    return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly])\n\ndef new_polys(poly):\n    return unique([canonical(poly + [pt]) for pt in new_points(poly)])\n\nmonomino = [(0, 0)]\nmonominoes = [monomino]\n\ndef rank(n):\n    \n    assert n >= 0\n    if n == 0: return []\n    if n == 1: return monominoes\n    return unique(concat_map(new_polys, rank(n - 1)))\n\ndef text_representation(poly):\n    \n    min_pt = minima(poly)\n    max_pt = (max(p[0] for p in poly), max(p[1] for p in poly))\n    table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1)\n             for _ in xrange(max_pt[0] - min_pt[0] + 1)]\n    for pt in poly:\n        table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = '\n    return \"\\n\".join(row.tostring() for row in table)\n\ndef main():\n    print [len(rank(n)) for n in xrange(1, 11)]\n\n    n = int(argv[1]) if (len(argv) == 2) else 5\n    print \"\\nAll free polyominoes of rank %d:\" % n\n\n    for poly in rank(n):\n        print text_representation(poly), \"\\n\"\n\nmain()\n"}
{"id": 50960, "name": "Use a REST API", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar key string\n\nfunc init() {\n\t\n\t\n\tconst keyFile = \"api_key.txt\"\n\tf, err := os.Open(keyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkeydata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkey = strings.TrimSpace(string(keydata))\n}\n\ntype EventResponse struct {\n\tResults []Result\n\t\n}\n\ntype Result struct {\n\tID          string\n\tStatus      string\n\tName        string\n\tEventURL    string `json:\"event_url\"`\n\tDescription string\n\tTime        EventTime\n\t\n}\n\n\n\ntype EventTime struct{ time.Time }\n\nfunc (et *EventTime) UnmarshalJSON(data []byte) error {\n\tvar msec int64\n\tif err := json.Unmarshal(data, &msec); err != nil {\n\t\treturn err\n\t}\n\tet.Time = time.Unix(0, msec*int64(time.Millisecond))\n\treturn nil\n}\n\nfunc (et EventTime) MarshalJSON() ([]byte, error) {\n\tmsec := et.UnixNano() / int64(time.Millisecond)\n\treturn json.Marshal(msec)\n}\n\n\nfunc (r *Result) String() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintln(&b, \"ID:\", r.ID)\n\tfmt.Fprintln(&b, \"URL:\", r.EventURL)\n\tfmt.Fprintln(&b, \"Time:\", r.Time.Format(time.UnixDate))\n\td := r.Description\n\tconst limit = 65\n\tif len(d) > limit {\n\t\td = d[:limit-1] + \"…\"\n\t}\n\tfmt.Fprintln(&b, \"Description:\", d)\n\treturn b.String()\n}\n\nfunc main() {\n\tv := url.Values{\n\t\t\n\t\t\n\t\t\"topic\": []string{\"photo\"},\n\t\t\"time\":  []string{\",1w\"},\n\t\t\"key\":   []string{key},\n\t}\n\tu := url.URL{\n\t\tScheme:   \"http\",\n\t\tHost:     \"api.meetup.com\",\n\t\tPath:     \"2/open_events.json\",\n\t\tRawQuery: v.Encode(),\n\t}\n\t\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Println(\"HTTP Status:\", resp.Status)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\n\tvar buf bytes.Buffer\n\tif err = json.Indent(&buf, body, \"\", \"  \"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\n\n\tvar evresp EventResponse\n\tjson.Unmarshal(body, &evresp)\n\t\n\n\tfmt.Println(\"Got\", len(evresp.Results), \"events\")\n\tif len(evresp.Results) > 0 {\n\t\tfmt.Println(\"First event:\\n\", &evresp.Results[0])\n\t}\n}\n", "Python": "\nimport requests\nimport json\n\ncity = None\ntopic = None\n\ndef getEvent(url_path, key) :\n    responseString = \"\"\n    \n    params = {'city':city, 'key':key,'topic':topic}\n    r = requests.get(url_path, params = params)    \n    print(r.url)    \n    responseString = r.text\n    return responseString\n\n\ndef getApiKey(key_path):\n    key = \"\"\n    f = open(key_path, 'r')\n    key = f.read()\n    return key\n\n\ndef submitEvent(url_path,params):\n    r = requests.post(url_path, data=json.dumps(params))        \n    print(r.text+\" : Event Submitted\")\n"}
{"id": 50961, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n"}
{"id": 50962, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n"}
{"id": 50963, "name": "Deming's funnel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n"}
{"id": 50964, "name": "Deming's funnel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n"}
{"id": 50965, "name": "Rosetta Code_Fix code tags", "Go": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"log\"\nimport \"os\"\nimport \"regexp\"\nimport \"strings\"\n\nfunc main() {\n\terr := fix()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc fix() (err error) {\n\tbuf, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, err := Lang(string(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(out)\n\treturn nil\n}\n\nfunc Lang(in string) (out string, err error) {\n\treg := regexp.MustCompile(\"<[^>]+>\")\n\tout = reg.ReplaceAllStringFunc(in, repl)\n\treturn out, nil\n}\n\nfunc repl(in string) (out string) {\n\tif in == \"</code>\" {\n\t\t\n\t\treturn \"</\"+\"lang>\"\n\t}\n\n\t\n\tmid := in[1 : len(in)-1]\n\n\t\n\tvar langs = []string{\n\t\t\"abap\", \"actionscript\", \"actionscript3\", \"ada\", \"apache\", \"applescript\",\n\t\t\"apt_sources\", \"asm\", \"asp\", \"autoit\", \"avisynth\", \"bash\", \"basic4gl\",\n\t\t\"bf\", \"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\", \"cfm\",\n\t\t\"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\", \"d\", \"delphi\",\n\t\t\"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\", \"fortran\", \"freebasic\",\n\t\t\"genero\", \"gettext\", \"glsl\", \"gml\", \"gnuplot\", \"go\", \"groovy\", \"haskell\",\n\t\t\"hq9plus\", \"html4strict\", \"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\",\n\t\t\"java5\", \"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\", \"m68k\",\n\t\t\"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\", \"mysql\", \"nsis\",\n\t\t\"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\", \"oracle11\", \"oracle8\", \"pascal\",\n\t\t\"per\", \"perl\", \"php\", \"php-brief\", \"pic16\", \"pixelbender\", \"plsql\",\n\t\t\"povray\", \"powershell\", \"progress\", \"prolog\", \"providex\", \"python\",\n\t\t\"qbasic\", \"rails\", \"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\",\n\t\t\"scilab\", \"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\", \"verilog\",\n\t\t\"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\", \"whitespace\", \"winbatch\",\n\t\t\"xml\", \"xorg_conf\", \"xpp\", \"z80\",\n\t}\n\tfor _, lang := range langs {\n\t\tif mid == lang {\n\t\t\t\n\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"/\") {\n\t\t\tif mid[len(\"/\"):] == lang {\n\t\t\t\t\n\t\t\t\treturn \"</\"+\"lang>\"\n\t\t\t}\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"code \") {\n\t\t\tif mid[len(\"code \"):] == lang {\n\t\t\t\t\n\t\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn in\n}\n", "Python": "\n\nfrom re import sub\n\ntesttexts = [\n,\n    ,\n    ]\n\nfor txt in testtexts:\n    text2 = sub(r'<lang\\s+\\\"?([\\w\\d\\s]+)\\\"?\\s?>', r'<syntaxhighlight lang=\\1>', txt)\n    text2 = sub(r'<lang\\s*>', r'<syntaxhighlight lang=text>', text2)\n    text2 = sub(r'</lang\\s*>', r'\n"}
{"id": 50966, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50967, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50968, "name": "OpenWebNet password", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n    start := true\n    num1 := uint32(0)\n    num2 := num1\n    i, _ := strconv.Atoi(password)\n    pwd := uint32(i)\n    for _, c := range nonce {\n        if c != '0' {\n            if start {\n                num2 = pwd\n            }\n            start = false\n        }\n        switch c {\n        case '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        case '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        case '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        case '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        case '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        case '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        case '7':\n            num3 := num2 & 0x0000FF00\n            num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n            num1 = num3 | num4\n            num2 = (num2 & 0xFF000000) >> 8\n        case '8':\n            num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n            num2 = (num2 & 0x00FF0000) >> 8\n        case '9':\n            num1 = ^num2\n        default:\n            num1 = num2\n        }\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if c != '0' && c != '9' {\n            num1 |= num2\n        }\n        num2 = num1\n    }\n    return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n    res := ownCalcPass(password, nonce)\n    m := fmt.Sprintf(\"%s  %s  %-10d  %-10d\", password, nonce, res, expected)\n    if res == expected {\n        fmt.Println(\"PASS\", m)\n    } else {\n        fmt.Println(\"FAIL\", m)\n    }\n}\n\nfunc main() {\n    testPasswordCalc(\"12345\", \"603356072\", 25280520)\n    testPasswordCalc(\"12345\", \"410501656\", 119537670)\n    testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}\n", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n"}
{"id": 50969, "name": "ADFGVX cipher", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n)\n\nvar adfgvx = \"ADFGVX\"\nvar alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\nfunc distinct(bs []byte) []byte {\n    var u []byte\n    for _, b := range bs {\n        if !bytes.Contains(u, []byte{b}) {\n            u = append(u, b)\n        }\n    }\n    return u\n}\n\nfunc allAsciiAlphaNum(word []byte) bool {\n    for _, b := range word {\n        if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc orderKey(key string) []int {\n    temp := make([][2]byte, len(key))\n    for i := 0; i < len(key); i++ {\n        temp[i] = [2]byte{key[i], byte(i)}\n    }\n    sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] })\n    res := make([]int, len(key))\n    for i := 0; i < len(key); i++ {\n        res[i] = int(temp[i][1])\n    }\n    return res\n}\n\nfunc createPolybius() []string {\n    temp := []byte(alphabet)\n    rand.Shuffle(36, func(i, j int) {\n        temp[i], temp[j] = temp[j], temp[i]\n    })\n    alphabet = string(temp)\n    fmt.Println(\"6 x 6 Polybius square:\\n\")\n    fmt.Println(\"  | A D F G V X\")\n    fmt.Println(\"---------------\")\n    p := make([]string, 6)\n    for i := 0; i < 6; i++ {\n        fmt.Printf(\"%c | \", adfgvx[i])\n        p[i] = alphabet[6*i : 6*(i+1)]\n        for _, c := range p[i] {\n            fmt.Printf(\"%c \", c)\n        }\n        fmt.Println()\n    }\n    return p\n}\n\nfunc createKey(n int) string {\n    if n < 7 || n > 12 {\n        log.Fatal(\"Key should be within 7 and 12 letters long.\")\n    }\n    bs, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Split(bs, []byte{'\\n'})\n    var candidates [][]byte\n    for _, word := range words {\n        if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) {\n            candidates = append(candidates, word)\n        }\n    }\n    k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))]))\n    fmt.Println(\"\\nThe key is\", k)\n    return k\n}\n\nfunc encrypt(polybius []string, key, plainText string) string {\n    temp := \"\"\nouter:\n    for _, ch := range []byte(plainText) {\n        for r := 0; r <= 5; r++ {\n            for c := 0; c <= 5; c++ {\n                if polybius[r][c] == ch {\n                    temp += fmt.Sprintf(\"%c%c\", adfgvx[r], adfgvx[c])\n                    continue outer\n                }\n            }\n        }\n    }\n    colLen := len(temp) / len(key)\n    \n    if len(temp)%len(key) > 0 {\n        colLen++\n    }\n    table := make([][]string, colLen)\n    for i := 0; i < colLen; i++ {\n        table[i] = make([]string, len(key))\n    }\n    for i := 0; i < len(temp); i++ {\n        table[i/len(key)][i%len(key)] = string(temp[i])\n    }\n    order := orderKey(key)\n    cols := make([][]string, len(key))\n    for i := 0; i < len(key); i++ {\n        cols[i] = make([]string, colLen)\n        for j := 0; j < colLen; j++ {\n            cols[i][j] = table[j][order[i]]\n        }\n    }\n    res := make([]string, len(cols))\n    for i := 0; i < len(cols); i++ {\n        res[i] = strings.Join(cols[i], \"\")\n    }\n    return strings.Join(res, \" \")\n}\n\nfunc decrypt(polybius []string, key, cipherText string) string {\n    colStrs := strings.Split(cipherText, \" \")\n    \n    maxColLen := 0\n    for _, s := range colStrs {\n        if len(s) > maxColLen {\n            maxColLen = len(s)\n        }\n    }\n    cols := make([][]string, len(colStrs))\n    for i, s := range colStrs {\n        var ls []string\n        for _, c := range s {\n            ls = append(ls, string(c))\n        }\n        if len(s) < maxColLen {\n            cols[i] = make([]string, maxColLen)\n            copy(cols[i], ls)\n        } else {\n            cols[i] = ls\n        }\n    }\n    table := make([][]string, maxColLen)\n    order := orderKey(key)\n    for i := 0; i < maxColLen; i++ {\n        table[i] = make([]string, len(key))\n        for j := 0; j < len(key); j++ {\n            table[i][order[j]] = cols[j][i]\n        }\n    }\n    temp := \"\"\n    for i := 0; i < len(table); i++ {\n        temp += strings.Join(table[i], \"\")\n    }\n    plainText := \"\"\n    for i := 0; i < len(temp); i += 2 {\n        r := strings.IndexByte(adfgvx, temp[i])\n        c := strings.IndexByte(adfgvx, temp[i+1])\n        plainText = plainText + string(polybius[r][c])\n    }\n    return plainText\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    plainText := \"ATTACKAT1200AM\"\n    polybius := createPolybius()\n    key := createKey(9)\n    fmt.Println(\"\\nPlaintext :\", plainText)\n    cipherText := encrypt(polybius, key, plainText)\n    fmt.Println(\"\\nEncrypted :\", cipherText)\n    plainText2 := decrypt(polybius, key, cipherText)\n    fmt.Println(\"\\nDecrypted :\", plainText2)\n}\n", "Python": "\n\nfrom random import shuffle, choice\nfrom itertools import product, accumulate\nfrom numpy import floor, sqrt\n\nclass ADFGVX:\n    \n    def __init__(self, spoly, k, alph='ADFGVX'):\n        self.polybius = list(spoly.upper())\n        self.pdim = int(floor(sqrt(len(self.polybius))))\n        self.key = list(k.upper())\n        self.keylen = len(self.key)\n        self.alphabet = list(alph)\n        pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)]\n        self.encode = dict(zip(self.polybius, pairs))\n        self.decode = dict((v, k) for (k, v) in self.encode.items())\n\n    def encrypt(self, msg):\n        \n        chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius]))\n        colvecs = [(lett, chars[i:len(chars):self.keylen]) \\\n            for (i, lett) in enumerate(self.key)]\n        colvecs.sort(key=lambda x: x[0])\n        return ''.join([''.join(a[1]) for a in colvecs])\n\n    def decrypt(self, cod):\n        \n        chars = [c for c in cod if c in self.alphabet]\n        sortedkey = sorted(self.key)\n        order = [self.key.index(ch) for ch in sortedkey]\n        originalorder = [sortedkey.index(ch) for ch in self.key]\n        base, extra = divmod(len(chars), self.keylen)\n        strides = [base + (1 if extra > i else 0) for i in order]    \n        starts = list(accumulate(strides[:-1], lambda x, y: x + y))  \n        starts = [0] + starts                                        \n        ends = [starts[i] + strides[i] for i in range(self.keylen)]  \n        cols = [chars[starts[i]:ends[i]] for i in originalorder]     \n        pairs = []                                                   \n        for i in range((len(chars) - 1) // self.keylen + 1):\n            for j in range(self.keylen):\n                if i * self.keylen + j < len(chars):\n                    pairs.append(cols[j][i])\n\n        return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)])\n\n\nif __name__ == '__main__':\n    PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')\n    shuffle(PCHARS)\n    POLYBIUS = ''.join(PCHARS)\n    with open('unixdict.txt') as fh:\n        WORDS = [w for w in (fh.read()).split() \\\n            if len(w) == 9 and len(w) == len(set(list(w)))]\n        KEY = choice(WORDS)\n\n    SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM'\n    print(f'Polybius: {POLYBIUS}, key: {KEY}')\n    print('Message: ', MESSAGE)\n    ENCODED = SECRET.encrypt(MESSAGE)\n    DECODED = SECRET.decrypt(ENCODED)\n    print('Encoded: ', ENCODED)\n    print('Decoded: ', DECODED)\n"}
{"id": 50970, "name": "ADFGVX cipher", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n)\n\nvar adfgvx = \"ADFGVX\"\nvar alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\nfunc distinct(bs []byte) []byte {\n    var u []byte\n    for _, b := range bs {\n        if !bytes.Contains(u, []byte{b}) {\n            u = append(u, b)\n        }\n    }\n    return u\n}\n\nfunc allAsciiAlphaNum(word []byte) bool {\n    for _, b := range word {\n        if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc orderKey(key string) []int {\n    temp := make([][2]byte, len(key))\n    for i := 0; i < len(key); i++ {\n        temp[i] = [2]byte{key[i], byte(i)}\n    }\n    sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] })\n    res := make([]int, len(key))\n    for i := 0; i < len(key); i++ {\n        res[i] = int(temp[i][1])\n    }\n    return res\n}\n\nfunc createPolybius() []string {\n    temp := []byte(alphabet)\n    rand.Shuffle(36, func(i, j int) {\n        temp[i], temp[j] = temp[j], temp[i]\n    })\n    alphabet = string(temp)\n    fmt.Println(\"6 x 6 Polybius square:\\n\")\n    fmt.Println(\"  | A D F G V X\")\n    fmt.Println(\"---------------\")\n    p := make([]string, 6)\n    for i := 0; i < 6; i++ {\n        fmt.Printf(\"%c | \", adfgvx[i])\n        p[i] = alphabet[6*i : 6*(i+1)]\n        for _, c := range p[i] {\n            fmt.Printf(\"%c \", c)\n        }\n        fmt.Println()\n    }\n    return p\n}\n\nfunc createKey(n int) string {\n    if n < 7 || n > 12 {\n        log.Fatal(\"Key should be within 7 and 12 letters long.\")\n    }\n    bs, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Split(bs, []byte{'\\n'})\n    var candidates [][]byte\n    for _, word := range words {\n        if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) {\n            candidates = append(candidates, word)\n        }\n    }\n    k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))]))\n    fmt.Println(\"\\nThe key is\", k)\n    return k\n}\n\nfunc encrypt(polybius []string, key, plainText string) string {\n    temp := \"\"\nouter:\n    for _, ch := range []byte(plainText) {\n        for r := 0; r <= 5; r++ {\n            for c := 0; c <= 5; c++ {\n                if polybius[r][c] == ch {\n                    temp += fmt.Sprintf(\"%c%c\", adfgvx[r], adfgvx[c])\n                    continue outer\n                }\n            }\n        }\n    }\n    colLen := len(temp) / len(key)\n    \n    if len(temp)%len(key) > 0 {\n        colLen++\n    }\n    table := make([][]string, colLen)\n    for i := 0; i < colLen; i++ {\n        table[i] = make([]string, len(key))\n    }\n    for i := 0; i < len(temp); i++ {\n        table[i/len(key)][i%len(key)] = string(temp[i])\n    }\n    order := orderKey(key)\n    cols := make([][]string, len(key))\n    for i := 0; i < len(key); i++ {\n        cols[i] = make([]string, colLen)\n        for j := 0; j < colLen; j++ {\n            cols[i][j] = table[j][order[i]]\n        }\n    }\n    res := make([]string, len(cols))\n    for i := 0; i < len(cols); i++ {\n        res[i] = strings.Join(cols[i], \"\")\n    }\n    return strings.Join(res, \" \")\n}\n\nfunc decrypt(polybius []string, key, cipherText string) string {\n    colStrs := strings.Split(cipherText, \" \")\n    \n    maxColLen := 0\n    for _, s := range colStrs {\n        if len(s) > maxColLen {\n            maxColLen = len(s)\n        }\n    }\n    cols := make([][]string, len(colStrs))\n    for i, s := range colStrs {\n        var ls []string\n        for _, c := range s {\n            ls = append(ls, string(c))\n        }\n        if len(s) < maxColLen {\n            cols[i] = make([]string, maxColLen)\n            copy(cols[i], ls)\n        } else {\n            cols[i] = ls\n        }\n    }\n    table := make([][]string, maxColLen)\n    order := orderKey(key)\n    for i := 0; i < maxColLen; i++ {\n        table[i] = make([]string, len(key))\n        for j := 0; j < len(key); j++ {\n            table[i][order[j]] = cols[j][i]\n        }\n    }\n    temp := \"\"\n    for i := 0; i < len(table); i++ {\n        temp += strings.Join(table[i], \"\")\n    }\n    plainText := \"\"\n    for i := 0; i < len(temp); i += 2 {\n        r := strings.IndexByte(adfgvx, temp[i])\n        c := strings.IndexByte(adfgvx, temp[i+1])\n        plainText = plainText + string(polybius[r][c])\n    }\n    return plainText\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    plainText := \"ATTACKAT1200AM\"\n    polybius := createPolybius()\n    key := createKey(9)\n    fmt.Println(\"\\nPlaintext :\", plainText)\n    cipherText := encrypt(polybius, key, plainText)\n    fmt.Println(\"\\nEncrypted :\", cipherText)\n    plainText2 := decrypt(polybius, key, cipherText)\n    fmt.Println(\"\\nDecrypted :\", plainText2)\n}\n", "Python": "\n\nfrom random import shuffle, choice\nfrom itertools import product, accumulate\nfrom numpy import floor, sqrt\n\nclass ADFGVX:\n    \n    def __init__(self, spoly, k, alph='ADFGVX'):\n        self.polybius = list(spoly.upper())\n        self.pdim = int(floor(sqrt(len(self.polybius))))\n        self.key = list(k.upper())\n        self.keylen = len(self.key)\n        self.alphabet = list(alph)\n        pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)]\n        self.encode = dict(zip(self.polybius, pairs))\n        self.decode = dict((v, k) for (k, v) in self.encode.items())\n\n    def encrypt(self, msg):\n        \n        chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius]))\n        colvecs = [(lett, chars[i:len(chars):self.keylen]) \\\n            for (i, lett) in enumerate(self.key)]\n        colvecs.sort(key=lambda x: x[0])\n        return ''.join([''.join(a[1]) for a in colvecs])\n\n    def decrypt(self, cod):\n        \n        chars = [c for c in cod if c in self.alphabet]\n        sortedkey = sorted(self.key)\n        order = [self.key.index(ch) for ch in sortedkey]\n        originalorder = [sortedkey.index(ch) for ch in self.key]\n        base, extra = divmod(len(chars), self.keylen)\n        strides = [base + (1 if extra > i else 0) for i in order]    \n        starts = list(accumulate(strides[:-1], lambda x, y: x + y))  \n        starts = [0] + starts                                        \n        ends = [starts[i] + strides[i] for i in range(self.keylen)]  \n        cols = [chars[starts[i]:ends[i]] for i in originalorder]     \n        pairs = []                                                   \n        for i in range((len(chars) - 1) // self.keylen + 1):\n            for j in range(self.keylen):\n                if i * self.keylen + j < len(chars):\n                    pairs.append(cols[j][i])\n\n        return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)])\n\n\nif __name__ == '__main__':\n    PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')\n    shuffle(PCHARS)\n    POLYBIUS = ''.join(PCHARS)\n    with open('unixdict.txt') as fh:\n        WORDS = [w for w in (fh.read()).split() \\\n            if len(w) == 9 and len(w) == len(set(list(w)))]\n        KEY = choice(WORDS)\n\n    SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM'\n    print(f'Polybius: {POLYBIUS}, key: {KEY}')\n    print('Message: ', MESSAGE)\n    ENCODED = SECRET.encrypt(MESSAGE)\n    DECODED = SECRET.decrypt(ENCODED)\n    print('Encoded: ', ENCODED)\n    print('Decoded: ', DECODED)\n"}
{"id": 50971, "name": "Exponentiation with infix operators in (or operating on) the base", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype float float64\n\nfunc (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }\n\nfunc main() {\n    ops := []string{\"-x.p(e)\", \"-(x).p(e)\", \"(-x).p(e)\", \"-(x.p(e))\"}\n    for _, x := range []float{float(-5), float(5)} {\n        for _, e := range []float{float(2), float(3)} {\n            fmt.Printf(\"x = %2.0f e = %0.0f | \", x, e)\n            fmt.Printf(\"%s = %4.0f | \", ops[0], -x.p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[1], -(x).p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[2], (-x).p(e))\n            fmt.Printf(\"%s = %4.0f\\n\", ops[3], -(x.p(e)))\n        }\n    }\n}\n", "Python": "from itertools import product\n\nxx = '-5 +5'.split()\npp = '2 3'.split()\ntexts = '-x**p -(x)**p (-x)**p -(x**p)'.split()\n\nprint('Integer variable exponentiation')\nfor x, p in product(xx, pp):\n    print(f'  x,p = {x:2},{p}; ', end=' ')\n    x, p = int(x), int(p)\n    print('; '.join(f\"{t} =={eval(t):4}\" for t in texts))\n\nprint('\\nBonus integer literal exponentiation')\nX, P = 'xp'\nxx.insert(0, ' 5')\ntexts.insert(0, 'x**p')\nfor x, p in product(xx, pp):\n    texts2 = [t.replace(X, x).replace(P, p) for t in texts]\n    print(' ', '; '.join(f\"{t2} =={eval(t2):4}\" for t2 in texts2))\n"}
{"id": 50972, "name": "Exponentiation with infix operators in (or operating on) the base", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype float float64\n\nfunc (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }\n\nfunc main() {\n    ops := []string{\"-x.p(e)\", \"-(x).p(e)\", \"(-x).p(e)\", \"-(x.p(e))\"}\n    for _, x := range []float{float(-5), float(5)} {\n        for _, e := range []float{float(2), float(3)} {\n            fmt.Printf(\"x = %2.0f e = %0.0f | \", x, e)\n            fmt.Printf(\"%s = %4.0f | \", ops[0], -x.p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[1], -(x).p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[2], (-x).p(e))\n            fmt.Printf(\"%s = %4.0f\\n\", ops[3], -(x.p(e)))\n        }\n    }\n}\n", "Python": "from itertools import product\n\nxx = '-5 +5'.split()\npp = '2 3'.split()\ntexts = '-x**p -(x)**p (-x)**p -(x**p)'.split()\n\nprint('Integer variable exponentiation')\nfor x, p in product(xx, pp):\n    print(f'  x,p = {x:2},{p}; ', end=' ')\n    x, p = int(x), int(p)\n    print('; '.join(f\"{t} =={eval(t):4}\" for t in texts))\n\nprint('\\nBonus integer literal exponentiation')\nX, P = 'xp'\nxx.insert(0, ' 5')\ntexts.insert(0, 'x**p')\nfor x, p in product(xx, pp):\n    texts2 = [t.replace(X, x).replace(P, p) for t in texts]\n    print(' ', '; '.join(f\"{t2} =={eval(t2):4}\" for t2 in texts2))\n"}
{"id": 50973, "name": "Separate the house number from the street name", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc isDigit(b byte) bool {\n    return '0' <= b && b <= '9'\n}\n\nfunc separateHouseNumber(address string) (street string, house string) {\n    length := len(address)\n    fields := strings.Fields(address)\n    size := len(fields)\n    last := fields[size-1]\n    penult := fields[size-2]\n    if isDigit(last[0]) {\n        isdig := isDigit(penult[0])\n        if size > 2 && isdig && !strings.HasPrefix(penult, \"194\") {\n            house = fmt.Sprintf(\"%s %s\", penult, last)\n        } else {\n            house = last\n        }\n    } else if size > 2 {\n        house = fmt.Sprintf(\"%s %s\", penult, last)\n    }\n    street = strings.TrimRight(address[:length-len(house)], \" \")\n    return\n}\n\nfunc main() {\n    addresses := [...]string{\n        \"Plataanstraat 5\",\n        \"Straat 12\",\n        \"Straat 12 II\",\n        \"Dr. J. Straat   12\",\n        \"Dr. J. Straat 12 a\",\n        \"Dr. J. Straat 12-14\",\n        \"Laan 1940 - 1945 37\",\n        \"Plein 1940 2\",\n        \"1213-laan 11\",\n        \"16 april 1944 Pad 1\",\n        \"1e Kruisweg 36\",\n        \"Laan 1940-'45 66\",\n        \"Laan '40-'45\",\n        \"Langeloërduinen 3 46\",\n        \"Marienwaerdt 2e Dreef 2\",\n        \"Provincialeweg N205 1\",\n        \"Rivium 2e Straat 59.\",\n        \"Nieuwe gracht 20rd\",\n        \"Nieuwe gracht 20rd 2\",\n        \"Nieuwe gracht 20zw /2\",\n        \"Nieuwe gracht 20zw/3\",\n        \"Nieuwe gracht 20 zw/4\",\n        \"Bahnhofstr. 4\",\n        \"Wertstr. 10\",\n        \"Lindenhof 1\",\n        \"Nordesch 20\",\n        \"Weilstr. 6\",\n        \"Harthauer Weg 2\",\n        \"Mainaustr. 49\",\n        \"August-Horch-Str. 3\",\n        \"Marktplatz 31\",\n        \"Schmidener Weg 3\",\n        \"Karl-Weysser-Str. 6\",\n    }\n    fmt.Println(\"Street                   House Number\")\n    fmt.Println(\"---------------------    ------------\")\n    for _, address := range addresses {\n        street, house := separateHouseNumber(address)\n        if house == \"\" {\n            house = \"(none)\"\n        }\n        fmt.Printf(\"%-22s   %s\\n\", street, house)\n    }\n}\n", "Python": "Plataanstraat 5           split as (Plataanstraat, 5)\nStraat 12                 split as (Straat, 12)\nStraat 12 II              split as (Straat, 12 II)\nDr. J. Straat   12        split as (Dr. J. Straat  , 12)\nDr. J. Straat 12 a        split as (Dr. J. Straat, 12 a)\nDr. J. Straat 12-14       split as (Dr. J. Straat, 12-14)\nLaan 1940 – 1945 37       split as (Laan 1940 – 1945, 37)\nPlein 1940 2              split as (Plein 1940, 2)\n1213-laan 11              split as (1213-laan, 11)\n16 april 1944 Pad 1       split as (16 april 1944 Pad, 1)\n1e Kruisweg 36            split as (1e Kruisweg, 36)\nLaan 1940-’45 66          split as (Laan 1940-’45, 66)\nLaan ’40-’45              split as (Laan ’40-’45,)\nLangeloërduinen 3 46      split as (Langeloërduinen, 3 46)\nMarienwaerdt 2e Dreef 2   split as (Marienwaerdt 2e Dreef, 2)\nProvincialeweg N205 1     split as (Provincialeweg N205, 1)\nRivium 2e Straat 59.      split as (Rivium 2e Straat, 59.)\nNieuwe gracht 20rd        split as (Nieuwe gracht, 20rd)\nNieuwe gracht 20rd 2      split as (Nieuwe gracht, 20rd 2)\nNieuwe gracht 20zw /2     split as (Nieuwe gracht, 20zw /2)\nNieuwe gracht 20zw/3      split as (Nieuwe gracht, 20zw/3)\nNieuwe gracht 20 zw/4     split as (Nieuwe gracht, 20 zw/4)\nBahnhofstr. 4             split as (Bahnhofstr., 4)\nWertstr. 10               split as (Wertstr., 10)\nLindenhof 1               split as (Lindenhof, 1)\nNordesch 20               split as (Nordesch, 20)\nWeilstr. 6                split as (Weilstr., 6)\nHarthauer Weg 2           split as (Harthauer Weg, 2)\nMainaustr. 49             split as (Mainaustr., 49)\nAugust-Horch-Str. 3       split as (August-Horch-Str., 3)\nMarktplatz 31             split as (Marktplatz, 31)\nSchmidener Weg 3          split as (Schmidener Weg, 3)\nKarl-Weysser-Str. 6       split as (Karl-Weysser-Str., 6)''')\n"}
{"id": 50974, "name": "Display an outline as a nested table", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc makeIndent(outline string, tab int) []iNode {\n    lines := strings.Split(outline, \"\\n\")\n    iNodes := make([]iNode, len(lines))\n    for i, line := range lines {\n        line2 := strings.TrimLeft(line, \" \")\n        le, le2 := len(line), len(line2)\n        level := (le - le2) / tab\n        iNodes[i] = iNode{level, line2}\n    }\n    return iNodes\n}\n\nfunc toMarkup(n nNode, cols []string, depth int) string {\n    var span int\n\n    var colSpan func(nn nNode)\n    colSpan = func(nn nNode) {\n        for i, c := range nn.children {\n            if i > 0 {\n                span++\n            }\n            colSpan(c)\n        }\n    }\n\n    for _, c := range n.children {\n        span = 1\n        colSpan(c)\n    }\n    var lines []string\n    lines = append(lines, `{| class=\"wikitable\" style=\"text-align: center;\"`)\n    const l1, l2 = \"|-\", \"|  |\"\n    lines = append(lines, l1)\n    span = 1\n    colSpan(n)\n    s := fmt.Sprintf(`| style=\"background: %s \" colSpan=%d | %s`, cols[0], span, n.name)\n    lines = append(lines, s, l1)\n\n    var nestedFor func(nn nNode, level, maxLevel, col int)\n    nestedFor = func(nn nNode, level, maxLevel, col int) {\n        if level == 1 && maxLevel > level {\n            for i, c := range nn.children {\n                nestedFor(c, 2, maxLevel, i)\n            }\n        } else if level < maxLevel {\n            for _, c := range nn.children {\n                nestedFor(c, level+1, maxLevel, col)\n            }\n        } else {\n            if len(nn.children) > 0 {\n                for i, c := range nn.children {\n                    span = 1\n                    colSpan(c)\n                    cn := col + 1\n                    if maxLevel == 1 {\n                        cn = i + 1\n                    }\n                    s := fmt.Sprintf(`| style=\"background: %s \" colspan=%d | %s`, cols[cn], span, c.name)\n                    lines = append(lines, s)\n                }\n            } else {\n                lines = append(lines, l2)\n            }\n        }\n    }\n    for maxLevel := 1; maxLevel < depth; maxLevel++ {\n        nestedFor(n, 1, maxLevel, 0)\n        if maxLevel < depth-1 {\n            lines = append(lines, l1)\n        }\n    }\n    lines = append(lines, \"|}\")\n    return strings.Join(lines, \"\\n\")\n}\n\nfunc main() {\n    const outline = `Display an outline as a nested table.\n    Parse the outline to a tree,\n        measuring the indent of each line,\n        translating the indentation to a nested structure,\n        and padding the tree to even depth.\n    count the leaves descending from each node,\n        defining the width of a leaf as 1,\n        and the width of a parent node as a sum.\n            (The sum of the widths of its children) \n    and write out a table with 'colspan' values\n        either as a wiki table,\n        or as HTML.`\n    const (\n        yellow = \"#ffffe6;\"\n        orange = \"#ffebd2;\"\n        green  = \"#f0fff0;\"\n        blue   = \"#e6ffff;\"\n        pink   = \"#ffeeff;\"\n    )\n    cols := []string{yellow, orange, green, blue, pink}\n    iNodes := makeIndent(outline, 4)\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    fmt.Println(toMarkup(n, cols, 4))\n\n    fmt.Println(\"\\n\")\n    const outline2 = `Display an outline as a nested table.\n    Parse the outline to a tree,\n        measuring the indent of each line,\n        translating the indentation to a nested structure,\n        and padding the tree to even depth.\n    count the leaves descending from each node,\n        defining the width of a leaf as 1,\n        and the width of a parent node as a sum.\n            (The sum of the widths of its children)\n            Propagating the sums upward as necessary. \n    and write out a table with 'colspan' values\n        either as a wiki table,\n        or as HTML.\n    Optionally add color to the nodes.`\n    cols2 := []string{blue, yellow, orange, green, pink}\n    var n2 nNode\n    iNodes2 := makeIndent(outline2, 4)\n    toNest(iNodes2, 0, 0, &n2)\n    fmt.Println(toMarkup(n2, cols2, 4))\n}\n", "Python": "\n\nimport itertools\nimport re\nimport sys\n\nfrom collections import deque\nfrom typing import NamedTuple\n\n\nRE_OUTLINE = re.compile(r\"^((?: |\\t)*)(.+)$\", re.M)\n\nCOLORS = itertools.cycle(\n    [\n        \"\n        \"\n        \"\n        \"\n        \"\n    ]\n)\n\n\nclass Node:\n    def __init__(self, indent, value, parent, children=None):\n        self.indent = indent\n        self.value = value\n        self.parent = parent\n        self.children = children or []\n\n        self.color = None\n\n    def depth(self):\n        if self.parent:\n            return self.parent.depth() + 1\n        return -1\n\n    def height(self):\n        \n        if not self.children:\n            return 0\n        return max(child.height() for child in self.children) + 1\n\n    def colspan(self):\n        if self.leaf:\n            return 1\n        return sum(child.colspan() for child in self.children)\n\n    @property\n    def leaf(self):\n        return not bool(self.children)\n\n    def __iter__(self):\n        \n        q = deque()\n        q.append(self)\n        while q:\n            node = q.popleft()\n            yield node\n            q.extend(node.children)\n\n\nclass Token(NamedTuple):\n    indent: int\n    value: str\n\n\ndef tokenize(outline):\n    \n    for match in RE_OUTLINE.finditer(outline):\n        indent, value = match.groups()\n        yield Token(len(indent), value)\n\n\ndef parse(outline):\n    \n    \n    tokens = list(tokenize(outline))\n\n    \n    temp_root = Node(-1, \"\", None)\n    _parse(tokens, 0, temp_root)\n\n    \n    root = temp_root.children[0]\n    pad_tree(root, root.height())\n\n    return root\n\n\ndef _parse(tokens, index, node):\n    \n    \n    if index >= len(tokens):\n        return\n\n    token = tokens[index]\n\n    if token.indent == node.indent:\n        \n        current = Node(token.indent, token.value, node.parent)\n        node.parent.children.append(current)\n        _parse(tokens, index + 1, current)\n\n    elif token.indent > node.indent:\n        \n        current = Node(token.indent, token.value, node)\n        node.children.append(current)\n        _parse(tokens, index + 1, current)\n\n    elif token.indent < node.indent:\n        \n        _parse(tokens, index, node.parent)\n\n\ndef pad_tree(node, height):\n    \n    if node.leaf and node.depth() < height:\n        pad_node = Node(node.indent + 1, \"\", node)\n        node.children.append(pad_node)\n\n    for child in node.children:\n        pad_tree(child, height)\n\n\ndef color_tree(node):\n    \n    if not node.value:\n        node.color = \"\n    elif node.depth() <= 1:\n        node.color = next(COLORS)\n    else:\n        node.color = node.parent.color\n\n    for child in node.children:\n        color_tree(child)\n\n\ndef table_data(node):\n    \n    indent = \"    \"\n\n    if node.colspan() > 1:\n        colspan = f'colspan=\"{node.colspan()}\"'\n    else:\n        colspan = \"\"\n\n    if node.color:\n        style = f'style=\"background-color: {node.color};\"'\n    else:\n        style = \"\"\n\n    attrs = \" \".join([colspan, style])\n    return f\"{indent}<td{attrs}>{node.value}</td>\"\n\n\ndef html_table(tree):\n    \n    \n    table_cols = tree.colspan()\n\n    \n    row_cols = 0\n\n    \n    buf = [\"<table style='text-align: center;'>\"]\n\n    \n    for node in tree:\n        if row_cols == 0:\n            buf.append(\"  <tr>\")\n\n        buf.append(table_data(node))\n        row_cols += node.colspan()\n\n        if row_cols == table_cols:\n            buf.append(\"  </tr>\")\n            row_cols = 0\n\n    buf.append(\"</table>\")\n    return \"\\n\".join(buf)\n\n\ndef wiki_table_data(node):\n    \n    if not node.value:\n        return \"|  |\"\n\n    if node.colspan() > 1:\n        colspan = f\"colspan={node.colspan()}\"\n    else:\n        colspan = \"\"\n\n    if node.color:\n        style = f'style=\"background: {node.color};\"'\n    else:\n        style = \"\"\n\n    attrs = \" \".join([colspan, style])\n    return f\"| {attrs} | {node.value}\"\n\n\ndef wiki_table(tree):\n    \n    \n    table_cols = tree.colspan()\n\n    \n    row_cols = 0\n\n    \n    buf = ['{| class=\"wikitable\" style=\"text-align: center;\"']\n\n    for node in tree:\n        if row_cols == 0:\n            buf.append(\"|-\")\n\n        buf.append(wiki_table_data(node))\n        row_cols += node.colspan()\n\n        if row_cols == table_cols:\n            row_cols = 0\n\n    buf.append(\"|}\")\n    return \"\\n\".join(buf)\n\n\ndef example(table_format=\"wiki\"):\n    \n\n    outline = (\n        \"Display an outline as a nested table.\\n\"\n        \"    Parse the outline to a tree,\\n\"\n        \"        measuring the indent of each line,\\n\"\n        \"        translating the indentation to a nested structure,\\n\"\n        \"        and padding the tree to even depth.\\n\"\n        \"    count the leaves descending from each node,\\n\"\n        \"        defining the width of a leaf as 1,\\n\"\n        \"        and the width of a parent node as a sum.\\n\"\n        \"            (The sum of the widths of its children)\\n\"\n        \"    and write out a table with 'colspan' values\\n\"\n        \"        either as a wiki table,\\n\"\n        \"        or as HTML.\"\n    )\n\n    tree = parse(outline)\n    color_tree(tree)\n\n    if table_format == \"wiki\":\n        print(wiki_table(tree))\n    else:\n        print(html_table(tree))\n\n\nif __name__ == \"__main__\":\n    args = sys.argv[1:]\n\n    if len(args) == 1:\n        table_format = args[0]\n    else:\n        table_format = \"wiki\"\n\n    example(table_format)\n"}
{"id": 50975, "name": "Common list elements", "Go": "package main\n\nimport \"fmt\"\n\nfunc indexOf(l []int, n int) int {\n    for i := 0; i < len(l); i++ {\n        if l[i] == n {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc common2(l1, l2 []int) []int {\n    \n    c1, c2 := len(l1), len(l2)\n    shortest, longest := l1, l2\n    if c1 > c2 {\n        shortest, longest = l2, l1\n    }\n    longest2 := make([]int, len(longest))\n    copy(longest2, longest) \n    var res []int\n    for _, e := range shortest {\n        ix := indexOf(longest2, e)\n        if ix >= 0 {\n            res = append(res, e)\n            longest2 = append(longest2[:ix], longest2[ix+1:]...)\n        }\n    }\n    return res\n}\n\nfunc commonN(ll [][]int) []int {\n    n := len(ll)\n    if n == 0 {\n        return []int{}\n    }\n    if n == 1 {\n        return ll[0]\n    }\n    res := common2(ll[0], ll[1])\n    if n == 2 {\n        return res\n    }\n    for _, l := range ll[2:] {\n        res = common2(res, l)\n    }\n    return res\n}\n\nfunc main() {\n    lls := [][][]int{\n        {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}},\n        {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}},\n    }\n    for _, ll := range lls {\n        fmt.Println(\"Intersection of\", ll, \"is:\")\n        fmt.Println(commonN(ll))\n        fmt.Println()\n    }\n}\n", "Python": "\n\ndef common_list_elements(*lists):\n    return list(set.intersection(*(set(list_) for list_ in lists)))\n\n\nif __name__ == \"__main__\":\n    test_cases = [\n        ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),\n        ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),\n    ]\n\n    for case in test_cases:\n        result = common_list_elements(*case)\n        print(f\"Intersection of {case} is {result}\")\n"}
{"id": 50976, "name": "Common list elements", "Go": "package main\n\nimport \"fmt\"\n\nfunc indexOf(l []int, n int) int {\n    for i := 0; i < len(l); i++ {\n        if l[i] == n {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc common2(l1, l2 []int) []int {\n    \n    c1, c2 := len(l1), len(l2)\n    shortest, longest := l1, l2\n    if c1 > c2 {\n        shortest, longest = l2, l1\n    }\n    longest2 := make([]int, len(longest))\n    copy(longest2, longest) \n    var res []int\n    for _, e := range shortest {\n        ix := indexOf(longest2, e)\n        if ix >= 0 {\n            res = append(res, e)\n            longest2 = append(longest2[:ix], longest2[ix+1:]...)\n        }\n    }\n    return res\n}\n\nfunc commonN(ll [][]int) []int {\n    n := len(ll)\n    if n == 0 {\n        return []int{}\n    }\n    if n == 1 {\n        return ll[0]\n    }\n    res := common2(ll[0], ll[1])\n    if n == 2 {\n        return res\n    }\n    for _, l := range ll[2:] {\n        res = common2(res, l)\n    }\n    return res\n}\n\nfunc main() {\n    lls := [][][]int{\n        {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}},\n        {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}},\n    }\n    for _, ll := range lls {\n        fmt.Println(\"Intersection of\", ll, \"is:\")\n        fmt.Println(commonN(ll))\n        fmt.Println()\n    }\n}\n", "Python": "\n\ndef common_list_elements(*lists):\n    return list(set.intersection(*(set(list_) for list_ in lists)))\n\n\nif __name__ == \"__main__\":\n    test_cases = [\n        ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),\n        ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),\n    ]\n\n    for case in test_cases:\n        result = common_list_elements(*case)\n        print(f\"Intersection of {case} is {result}\")\n"}
{"id": 50977, "name": "Monads_Writer monad", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n"}
{"id": 50978, "name": "N-queens minimum and knights and bishops", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n    \"time\"\n)\n\nvar board [][]bool\nvar diag1, diag2 [][]int\nvar diag1Lookup, diag2Lookup []bool\nvar n, minCount int\nvar layout string\n\nfunc isAttacked(piece string, row, col int) bool {\n    if piece == \"Q\" {\n        for i := 0; i < n; i++ {\n            if board[i][col] || board[row][i] {\n                return true\n            }\n        }\n        if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] {\n            return true\n        }\n    } else if piece == \"B\" {\n        if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] {\n            return true\n        }\n    } else { \n        if board[row][col] {\n            return true\n        }\n        if row+2 < n && col-1 >= 0 && board[row+2][col-1] {\n            return true\n        }\n        if row-2 >= 0 && col-1 >= 0 && board[row-2][col-1] {\n            return true\n        }\n        if row+2 < n && col+1 < n && board[row+2][col+1] {\n            return true\n        }\n        if row-2 >= 0 && col+1 < n && board[row-2][col+1] {\n            return true\n        }\n        if row+1 < n && col+2 < n && board[row+1][col+2] {\n            return true\n        }\n        if row-1 >= 0 && col+2 < n && board[row-1][col+2] {\n            return true\n        }\n        if row+1 < n && col-2 >= 0 && board[row+1][col-2] {\n            return true\n        }\n        if row-1 >= 0 && col-2 >= 0 && board[row-1][col-2] {\n            return true\n        }\n    }\n    return false\n}\n\nfunc abs(i int) int {\n    if i < 0 {\n        i = -i\n    }\n    return i\n}\n\nfunc attacks(piece string, row, col, trow, tcol int) bool {\n    if piece == \"Q\" {\n        return row == trow || col == tcol || abs(row-trow) == abs(col-tcol)\n    } else if piece == \"B\" {\n        return abs(row-trow) == abs(col-tcol)\n    } else { \n        rd := abs(trow - row)\n        cd := abs(tcol - col)\n        return (rd == 1 && cd == 2) || (rd == 2 && cd == 1)\n    }\n}\n\nfunc storeLayout(piece string) {\n    var sb strings.Builder\n    for _, row := range board {\n        for _, cell := range row {\n            if cell {\n                sb.WriteString(piece + \" \")\n            } else {\n                sb.WriteString(\". \")\n            }\n        }\n        sb.WriteString(\"\\n\")\n    }\n    layout = sb.String()\n}\n\nfunc placePiece(piece string, countSoFar, maxCount int) {\n    if countSoFar >= minCount {\n        return\n    }\n    allAttacked := true\n    ti := 0\n    tj := 0\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            if !isAttacked(piece, i, j) {\n                allAttacked = false\n                ti = i\n                tj = j\n                break\n            }\n        }\n        if !allAttacked {\n            break\n        }\n    }\n    if allAttacked {\n        minCount = countSoFar\n        storeLayout(piece)\n        return\n    }\n    if countSoFar <= maxCount {\n        si := ti\n        sj := tj\n        if piece == \"K\" {\n            si = si - 2\n            sj = sj - 2\n            if si < 0 {\n                si = 0\n            }\n            if sj < 0 {\n                sj = 0\n            } \n        }\n        for i := si; i < n; i++ {\n            for j := sj; j < n; j++ {\n                if !isAttacked(piece, i, j) {\n                    if (i == ti && j == tj) || attacks(piece, i, j, ti, tj) {\n                        board[i][j] = true\n                        if piece != \"K\" {\n                            diag1Lookup[diag1[i][j]] = true\n                            diag2Lookup[diag2[i][j]] = true\n                        }\n                        placePiece(piece, countSoFar+1, maxCount)\n                        board[i][j] = false\n                        if piece != \"K\" {\n                            diag1Lookup[diag1[i][j]] = false\n                            diag2Lookup[diag2[i][j]] = false\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    start := time.Now()\n    pieces := []string{\"Q\", \"B\", \"K\"}\n    limits := map[string]int{\"Q\": 10, \"B\": 10, \"K\": 10}\n    names := map[string]string{\"Q\": \"Queens\", \"B\": \"Bishops\", \"K\": \"Knights\"}\n    for _, piece := range pieces {\n        fmt.Println(names[piece])\n        fmt.Println(\"=======\\n\")\n\n        for n = 1; ; n++ {\n            board = make([][]bool, n)\n            for i := 0; i < n; i++ {\n                board[i] = make([]bool, n)\n            }\n            if piece != \"K\" {\n                diag1 = make([][]int, n)\n                for i := 0; i < n; i++ {\n                    diag1[i] = make([]int, n)\n                    for j := 0; j < n; j++ {\n                        diag1[i][j] = i + j\n                    }\n                }\n                diag2 = make([][]int, n)\n                for i := 0; i < n; i++ {\n                    diag2[i] = make([]int, n)\n                    for j := 0; j < n; j++ {\n                        diag2[i][j] = i - j + n - 1\n                    }\n                }\n                diag1Lookup = make([]bool, 2*n-1)\n                diag2Lookup = make([]bool, 2*n-1)\n            }\n            minCount = math.MaxInt32\n            layout = \"\"\n            for maxCount := 1; maxCount <= n*n; maxCount++ {\n                placePiece(piece, 0, maxCount)\n                if minCount <= n*n {\n                    break\n                }\n            }\n            fmt.Printf(\"%2d x %-2d : %d\\n\", n, n, minCount)\n            if n == limits[piece] {\n                fmt.Printf(\"\\n%s on a %d x %d board:\\n\", names[piece], n, n)\n                fmt.Println(\"\\n\" + layout)\n                break\n            }\n        }\n    }\n    elapsed := time.Now().Sub(start)\n    fmt.Printf(\"Took %s\\n\", elapsed)\n}\n", "Python": "\n\nfrom mip import Model, BINARY, xsum, minimize\n\ndef n_queens_min(N):\n    \n    if N < 4:\n        brd = [[0 for i in range(N)] for j in range(N)]\n        brd[0 if N < 2 else 1][0 if N < 2 else 1] = 1\n        return 1, brd\n\n    model = Model()\n    board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)]\n    for k in range(N):\n        model += xsum(board[k][j] for j in range(N)) <= 1\n        model += xsum(board[i][k] for i in range(N)) <= 1\n\n    for k in range(1, 2 * N - 2):\n        model += xsum(board[k - j][j] for j in range(max(0, k - N + 1), min(k + 1, N))) <= 1\n\n    for k in range(2 - N, N - 1):\n        model += xsum(board[k + j][j] for j in range(max(0, -k), min(N - k, N))) <= 1\n\n    for i in range(N):\n        for j in range(N):\n            model += xsum([xsum(board[i][k] for k in range(N)),\n               xsum(board[k][j] for k in range(N)),\n               xsum(board[i + k][j + k] for k in range(-N, N)\n                  if 0 <= i + k < N and 0 <= j + k < N),\n               xsum(board[i - k][j + k] for k in range(-N, N)\n                  if 0 <= i - k < N and 0 <= j + k < N)]) >= 1\n\n    model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N)))\n    model.optimize()\n    return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)]\n\n\ndef n_bishops_min(N):\n    \n    model = Model()\n    board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)]\n\n    for i in range(N):\n        for j in range(N):\n            model += xsum([\n               xsum(board[i + k][j + k] for k in range(-N, N)\n                  if 0 <= i + k < N and 0 <= j + k < N),\n               xsum(board[i - k][j + k] for k in range(-N, N)\n                  if 0 <= i - k < N and 0 <= j + k < N)]) >= 1\n\n    model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N)))\n    model.optimize()\n    return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)]\n\ndef n_knights_min(N):\n    \n    if N < 2:\n        return 1, \"N\"\n\n    knightdeltas = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n    model = Model()\n    \n    board = [[model.add_var(var_type=BINARY) for j in range(N + 4)] for i in range(N + 4)]\n    for i in range(N + 4):\n        model += xsum(board[i][j] for j in [0, 1, N + 2, N + 3]) == 0\n    for j in range(N + 4):\n        model += xsum(board[i][j] for i in [0, 1, N + 2, N + 3]) == 0\n\n    for i in range(2, N + 2):\n        for j in range(2, N + 2):\n            model += xsum([board[i][j]] + [board[i + d[0]][j + d[1]]\n               for d in knightdeltas]) >= 1\n            model += xsum([board[i + d[0]][j + d[1]]\n               for d in knightdeltas] + [100 * board[i][j]]) <= 100\n\n    model.objective = minimize(xsum(board[i][j] for i in range(2, N + 2) for j in range(2, N + 2)))\n    model.optimize()\n    minresult = model.objective_value\n    return minresult, [[board[i][j].x for i in range(2, N + 2)] for j in range(2, N + 2)]\n\n\nif __name__ == '__main__':\n    examples, pieces, chars = [[], [], []], [\"Queens\", \"Bishops\", \"Knights\"], ['Q', 'B', 'N']\n    print(\"   Squares    Queens   Bishops   Knights\")\n    for nrows in range(1, 11):\n        print(str(nrows * nrows).rjust(10), end='')\n        minval, examples[0] = n_queens_min(nrows)\n        print(str(int(minval)).rjust(10), end='')\n        minval, examples[1] = n_bishops_min(nrows)\n        print(str(int(minval)).rjust(10), end='')\n        minval, examples[2] = n_knights_min(nrows)\n        print(str(int(minval)).rjust(10))\n        if nrows == 10:\n            print(\"\\nExamples for N = 10:\")\n            for idx, piece in enumerate(chars):\n                print(f\"\\n{pieces[idx]}:\")\n                for row in examples[idx]:\n                    for sqr in row:\n                        print(chars[idx] if sqr == 1 else '.', '', end = '')\n                    print()\n                print()\n"}
{"id": 50979, "name": "Wordle comparison", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc wordle(answer, guess string) []int {\n    n := len(guess)\n    if n != len(answer) {\n        log.Fatal(\"The words must be of the same length.\")\n    }\n    answerBytes := []byte(answer)\n    result := make([]int, n) \n    for i := 0; i < n; i++ {\n        if guess[i] == answerBytes[i] {\n            answerBytes[i] = '\\000'\n            result[i] = 2\n        }\n    }\n    for i := 0; i < n; i++ {\n        ix := bytes.IndexByte(answerBytes, guess[i])\n        if ix >= 0 {\n            answerBytes[ix] = '\\000'\n            result[i] = 1\n        }\n    }\n    return result\n}\n\nfunc main() {\n    colors := []string{\"grey\", \"yellow\", \"green\"}\n    pairs := [][]string{\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"},\n    }\n    for _, pair := range pairs {\n        res := wordle(pair[0], pair[1])\n        res2 := make([]string, len(res))\n        for i := 0; i < len(res); i++ {\n            res2[i] = colors[res[i]]\n        }\n        fmt.Printf(\"%s v %s => %v => %v\\n\", pair[0], pair[1], res, res2)\n    }\n}\n", "Python": "\n\nfrom functools import reduce\nfrom operator import add\n\n\n\ndef wordleScore(target, guess):\n    \n    return mapAccumL(amber)(\n        *first(charCounts)(\n            mapAccumL(green)(\n                [], zip(target, guess)\n            )\n        )\n    )[1]\n\n\n\ndef green(residue, tg):\n    \n    t, g = tg\n    return (residue, (g, 2)) if t == g else (\n        [t] + residue, (g, 0)\n    )\n\n\n\ndef amber(tally, cn):\n    \n    c, n = cn\n    return (tally, 2) if 2 == n else (\n        adjust(\n            lambda x: x - 1,\n            c, tally\n        ),\n        1\n    ) if 0 < tally.get(c, 0) else (tally, 0)\n\n\n\n\ndef main():\n    \n    print(' -> '.join(['Target', 'Guess', 'Scores']))\n    print()\n    print(\n        '\\n'.join([\n            wordleReport(*tg) for tg in [\n                (\"ALLOW\", \"LOLLY\"),\n                (\"CHANT\", \"LATTE\"),\n                (\"ROBIN\", \"ALERT\"),\n                (\"ROBIN\", \"SONIC\"),\n                (\"ROBIN\", \"ROBIN\"),\n                (\"BULLY\", \"LOLLY\"),\n                (\"ADAPT\", \"SÅLÅD\"),\n                (\"Ukraine\", \"Ukraíne\"),\n                (\"BBAAB\", \"BBBBBAA\"),\n                (\"BBAABBB\", \"AABBBAA\")\n            ]\n        ])\n    )\n\n\n\ndef wordleReport(target, guess):\n    \n    scoreName = {2: 'green', 1: 'amber', 0: 'gray'}\n\n    if 5 != len(target):\n        return f'{target}: Expected 5 character target.'\n    elif 5 != len(guess):\n        return f'{guess}: Expected 5 character guess.'\n    else:\n        scores = wordleScore(target, guess)\n        return ' -> '.join([\n            target, guess, repr(scores),\n            ' '.join([\n                scoreName[n] for n in scores\n            ])\n        ])\n\n\n\n\n\ndef adjust(f, k, dct):\n    \n    return dict(\n        dct,\n        **{k: f(dct[k]) if k in dct else None}\n    )\n\n\n\ndef charCounts(s):\n    \n    return reduce(\n        lambda a, c: insertWith(add)(c)(1)(a),\n        list(s),\n        {}\n    )\n\n\n\ndef first(f):\n    \n    return lambda xy: (f(xy[0]), xy[1])\n\n\n\n\ndef insertWith(f):\n    \n    return lambda k: lambda x: lambda dct: dict(\n        dct,\n        **{k: f(dct[k], x) if k in dct else x}\n    )\n\n\n\n\ndef mapAccumL(f):\n    \n    def nxt(a, x):\n        return second(lambda v: a[1] + [v])(\n            f(a[0], x)\n        )\n    return lambda acc, xs: reduce(\n        nxt, xs, (acc, [])\n    )\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 50980, "name": "Largest product in a grid", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strings\"\n)\n\nvar grid = [][]int {\n    { 8,  2, 22, 97, 38, 15,  0, 40,  0, 75,  4,  5,  7, 78, 52, 12, 50, 77, 91,  8},\n    {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48,  4, 56, 62,  0},\n    {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30,  3, 49, 13, 36, 65},\n    {52, 70, 95, 23,  4, 60, 11, 42, 69, 24, 68, 56,  1, 32, 56, 71, 37,  2, 36, 91},\n    {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},\n    {24, 47, 32, 60, 99,  3, 45,  2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},\n    {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},\n    {67, 26, 20, 68,  2, 62, 12, 20, 95, 63, 94, 39, 63,  8, 40, 91, 66, 49, 94, 21},\n    {24, 55, 58,  5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},\n    {21, 36, 23,  9, 75,  0, 76, 44, 20, 45, 35, 14,  0, 61, 33, 97, 34, 31, 33, 95},\n    {78, 17, 53, 28, 22, 75, 31, 67, 15, 94,  3, 80,  4, 62, 16, 14,  9, 53, 56, 92},\n    {16, 39,  5, 42, 96, 35, 31, 47, 55, 58, 88, 24,  0, 17, 54, 24, 36, 29, 85, 57},\n    {86, 56,  0, 48, 35, 71, 89,  7,  5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},\n    {19, 80, 81, 68,  5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77,  4, 89, 55, 40},\n    { 4, 52,  8, 83, 97, 35, 99, 16,  7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},\n    {88, 36, 68, 87, 57, 62, 20, 72,  3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},\n    { 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18,  8, 46, 29, 32, 40, 62, 76, 36},\n    {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74,  4, 36, 16},\n    {20, 73, 35, 29, 78, 31, 90,  1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57,  5, 54},\n    { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52,  1, 89, 19, 67, 48},\n}\n\nfunc main() {\n    maxProd, maxR1, maxR2, maxC1, maxC2 := 0, 0, 0, 0, 0\n    var maxNums [4]int\n    h, w := len(grid), len(grid[0])\n\n    \n    for r := 0; r < h; r++ {\n        for c := 0; c < w-4; c++ {\n            prod := 1\n            for i := c; i < c+4; i++ {\n                prod *= grid[r][i]\n            }\n            if prod > maxProd {\n                maxProd = prod\n                for n := 0; n < 4; n++ {\n                    maxNums[n] = grid[r][c+n]\n                }\n                maxR1, maxR2 = r, r\n                maxC1, maxC2 = c, c+3\n            }\n        }\n    }\n\n    \n    for c := 0; c < w; c++ {\n        for r := 0; r < h-4; r++ {\n            prod := 1\n            for i := r; i < r+4; i++ {\n                prod *= grid[i][c]\n            }\n            if prod > maxProd {\n                maxProd = prod\n                for n := 0; n < 4; n++ {\n                    maxNums[n] = grid[r+n][c]\n                }\n                maxR1, maxR2 = r, r+3\n                maxC1, maxC2 = c, c\n            }\n        }\n    }\n\n    fmt.Println(\"The greatest product of four adjacent numbers in the same direction (down or right) in the grid is:\")\n    var maxNumStrs [4]string\n    for i := 0; i < 4; i++ {\n        maxNumStrs[i] = fmt.Sprintf(\"%d\", maxNums[i])\n    }\n    fmt.Printf(\"  %s = %s\\n\", strings.Join(maxNumStrs[:], \" x \"), rcu.Commatize(maxProd))\n    fmt.Print(\"  at indices (one based): \")\n    for r := maxR1; r <= maxR2; r++ {\n        for c := maxC1; c <= maxC2; c++ {\n            fmt.Printf(\"(%d, %d) \", r+1, c+1)\n        }\n    }\n    fmt.Println()\n}\n", "Python": "\n\nfrom math import prod\n\ndef maxproduct(mat, length):\n    \n    nrow, ncol = len(mat), len(mat[0])\n    maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0]\n    for row in range(nrow):\n        for col in range(ncol):\n            row2, col2 = row + length, col + length\n            if row < nrow - length:\n                array = [r[col] for r in mat[row:row2]]\n                pro = prod(array)\n                if pro > maxprod:\n                    maxprod, maxrow, maxcol, arr = pro, [row, row2], col, array\n            if col < ncol - length:\n                pro = prod(mat[row][col:col2])\n                if pro > maxprod:\n                    maxprod, maxrow, maxcol, arr = pro, row, [col, col2], mat[row][col:col2]\n\n    print(f\"The max {length}-product is {maxprod}, product of {arr} at row {maxrow}, col {maxcol}.\")\n\nMATRIX = [\n    [ 8,  2, 22, 97, 38, 15,  0, 40,  0, 75,  4,  5,  7, 78, 52, 12, 50, 77, 91,  8],\n    [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48,  4, 56, 62,  0],\n    [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30,  3, 49, 13, 36, 65],\n    [52, 70, 95, 23,  4, 60, 11, 42, 69, 24, 68, 56,  1, 32, 56, 71, 37,  2, 36, 91],\n    [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],\n    [24, 47, 32, 60, 99,  3, 45,  2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],\n    [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],\n    [67, 26, 20, 68,  2, 62, 12, 20, 95, 63, 94, 39, 63,  8, 40, 91, 66, 49, 94, 21],\n    [24, 55, 58,  5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],\n    [21, 36, 23,  9, 75,  0, 76, 44, 20, 45, 35, 14,  0, 61, 33, 97, 34, 31, 33, 95],\n    [78, 17, 53, 28, 22, 75, 31, 67, 15, 94,  3, 80,  4, 62, 16, 14,  9, 53, 56, 92],\n    [16, 39,  5, 42, 96, 35, 31, 47, 55, 58, 88, 24,  0, 17, 54, 24, 36, 29, 85, 57],\n    [86, 56,  0, 48, 35, 71, 89,  7,  5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],\n    [19, 80, 81, 68,  5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77,  4, 89, 55, 40],\n    [ 4, 52,  8, 83, 97, 35, 99, 16,  7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],\n    [88, 36, 68, 87, 57, 62, 20, 72,  3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],\n    [ 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18,  8, 46, 29, 32, 40, 62, 76, 36],\n    [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74,  4, 36, 16],\n    [20, 73, 35, 29, 78, 31, 90,  1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57,  5, 54],\n    [ 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52,  1, 89, 19, 67, 48]\n]\n\nfor n in range(2, 6):\n    maxproduct(MATRIX, n)\n"}
{"id": 50981, "name": "Neighbour primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(504)\n    var nprimes []int\n    fmt.Println(\"Neighbour primes < 500:\")\n    for i := 0; i < len(primes)-1; i++ {\n        p := primes[i]*primes[i+1] + 2\n        if rcu.IsPrime(p) {\n            nprimes = append(nprimes, primes[i])\n        }\n    }\n    rcu.PrintTable(nprimes, 10, 3, false)\n    fmt.Println(\"\\nFound\", len(nprimes), \"such primes.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    print(\"p        q       pq+2\")\n    print(\"-----------------------\")\n    for p in range(2, 499):\n        if not isPrime(p):\n            continue\n        q = p + 1\n        while not isPrime(q):\n            q += 1\n        if not isPrime(2 + p*q):\n            continue \n        print(p, \"\\t\", q, \"\\t\", 2+p*q)\n"}
{"id": 50982, "name": "Neighbour primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(504)\n    var nprimes []int\n    fmt.Println(\"Neighbour primes < 500:\")\n    for i := 0; i < len(primes)-1; i++ {\n        p := primes[i]*primes[i+1] + 2\n        if rcu.IsPrime(p) {\n            nprimes = append(nprimes, primes[i])\n        }\n    }\n    rcu.PrintTable(nprimes, 10, 3, false)\n    fmt.Println(\"\\nFound\", len(nprimes), \"such primes.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    print(\"p        q       pq+2\")\n    print(\"-----------------------\")\n    for p in range(2, 499):\n        if not isPrime(p):\n            continue\n        q = p + 1\n        while not isPrime(q):\n            q += 1\n        if not isPrime(2 + p*q):\n            continue \n        print(p, \"\\t\", q, \"\\t\", 2+p*q)\n"}
{"id": 50983, "name": "Resistance calculator", "Go": "package main\n\nimport \"fmt\"\n\ntype Resistor struct {\n    symbol              rune\n    resistance, voltage float64\n    a, b                *Resistor\n}\n\nfunc (r *Resistor) res() float64 {\n    switch r.symbol {\n    case '+':\n        return r.a.res() + r.b.res()\n    case '*':\n        return 1 / (1/r.a.res() + 1/r.b.res())\n    default:\n        return r.resistance\n    }\n}\n\nfunc (r *Resistor) setVoltage(voltage float64) {\n    switch r.symbol {\n    case '+':\n        ra := r.a.res()\n        rb := r.b.res()\n        r.a.setVoltage(ra / (ra + rb) * voltage)\n        r.b.setVoltage(rb / (ra + rb) * voltage)\n    case '*':\n        r.a.setVoltage(voltage)\n        r.b.setVoltage(voltage)\n    }\n    r.voltage = voltage\n}\n\nfunc (r *Resistor) current() float64 {\n    return r.voltage / r.res()\n}\n\nfunc (r *Resistor) effect() float64 {\n    return r.current() * r.voltage\n}\n\nfunc (r *Resistor) report(level string) {\n    fmt.Printf(\"%8.3f %8.3f %8.3f %8.3f  %s%c\\n\", r.res(), r.voltage, r.current(), r.effect(), level, r.symbol)\n    if r.a != nil {\n        r.a.report(level + \"| \")\n    }\n    if r.b != nil {\n        r.b.report(level + \"| \")\n    }\n}\n\nfunc (r *Resistor) add(other *Resistor) *Resistor {\n    return &Resistor{'+', 0, 0, r, other}\n}\n\nfunc (r *Resistor) mul(other *Resistor) *Resistor {\n    return &Resistor{'*', 0, 0, r, other}\n}\n\nfunc main() {\n    var r [10]*Resistor\n    resistances := []float64{6, 8, 4, 8, 4, 6, 8, 10, 6, 2}\n    for i := 0; i < 10; i++ {\n        r[i] = &Resistor{'r', resistances[i], 0, nil, nil}\n    }\n    node := r[7].add(r[9]).mul(r[8]).add(r[6]).mul(r[5]).add(r[4]).mul(r[3]).add(r[2]).mul(r[1]).add(r[0])\n    node.setVoltage(18)\n    fmt.Println(\"     Ohm     Volt   Ampere     Watt  Network tree\")\n    node.report(\"\")\n}\n", "Python": "import strutils, strformat\n\ntype\n  Node = ref object\n    kind: char  \n    resistance: float\n    voltage: float\n    a: Node\n    b: Node\n\nproc res(node: Node): float =\n  if node.kind == '+': return node.a.res + node.b.res\n  if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res)\n  node.resistance\n\nproc current(node: Node): float = node.voltage / node.res\nproc effect (node: Node): float = node.current * node.voltage\n\nproc report(node: Node, level: string = \"\") =\n  echo fmt\"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f}  {level}{node.kind}\"\n  if node.kind in \"+*\":\n    node.a.report level & \"| \"\n    node.b.report level & \"| \"\n\nproc setVoltage(node: Node, voltage: float) =\n  node.voltage = voltage\n  if node.kind == '+':\n    let ra = node.a.res\n    let rb = node.b.res\n    node.a.setVoltage ra / (ra+rb) * voltage\n    node.b.setVoltage rb / (ra+rb) * voltage\n  if node.kind == '*':\n    node.a.setVoltage voltage\n    node.b.setVoltage voltage\n\nproc build(tokens: seq[string]): Node =\n  var stack: seq[Node]\n  for token in tokens:\n    stack.add if token == \"+\": Node(kind: '+', a: stack.pop, b: stack.pop)\n              elif token == \"*\": Node(kind: '*', a: stack.pop, b: stack.pop)\n              else: Node(kind: 'r', resistance: parseFloat(token))\n  stack.pop\n\nproc calculate(voltage: float, tokens: seq[string]): Node =\n  echo \"\"\n  echo \"     Ohm     Volt   Ampere     Watt  Network tree\"\n  let node = build tokens\n  node.setVoltage voltage\n  node.report\n  node\n"}
{"id": 50984, "name": "Upside-down numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc genUpsideDown(limit int) chan int {\n    ch := make(chan int)\n    wrappings := [][2]int{\n        {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5},\n        {6, 4}, {7, 3}, {8, 2}, {9, 1},\n    }\n    evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91}\n    odds := []int{5}\n    oddIndex := 0\n    evenIndex := 0\n    ndigits := 1\n    pow := 100\n    count := 0\n    go func() {\n        for count < limit {\n            if ndigits%2 == 1 {\n                if len(odds) > oddIndex {\n                    ch <- odds[oddIndex]\n                    count++\n                    oddIndex++\n                } else {\n                    \n                    var nextOdds []int\n                    for _, w := range wrappings {\n                        for _, i := range odds {\n                            nextOdds = append(nextOdds, w[0]*pow+i*10+w[1])\n                        }\n                    }\n                    odds = nextOdds\n                    ndigits++\n                    pow *= 10\n                    oddIndex = 0\n                }\n            } else {\n                if len(evens) > evenIndex {\n                    ch <- evens[evenIndex]\n                    count++\n                    evenIndex++\n                } else {\n                    \n                    var nextEvens []int\n                    for _, w := range wrappings {\n                        for _, i := range evens {\n                            nextEvens = append(nextEvens, w[0]*pow+i*10+w[1])\n                        }\n                    }\n                    evens = nextEvens\n                    ndigits++\n                    pow *= 10\n                    evenIndex = 0\n                }\n            }\n        }\n        close(ch)\n    }()\n    return ch\n}\n\nfunc main() {\n    const limit = 50_000_000\n    count := 0\n    var ud50s []int\n    pow := 50\n    for n := range genUpsideDown(limit) {\n        count++\n        if count < 50 {\n            ud50s = append(ud50s, n)\n        } else if count == 50 {\n            ud50s = append(ud50s, n)\n            fmt.Println(\"First 50 upside down numbers:\")\n            rcu.PrintTable(ud50s, 10, 5, true)\n            fmt.Println()\n            pow = 500\n        } else if count == pow {\n            fmt.Printf(\"%sth : %s\\n\", rcu.Commatize(pow), rcu.Commatize(n))\n            pow *= 10\n        }\n    }\n}\n", "Python": "\n\n\ndef gen_upside_down_number():\n    \n    wrappings = [[1, 9], [2, 8], [3, 7], [4, 6],\n                 [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]]\n    evens = [19, 28, 37, 46, 55, 64, 73, 82, 91]\n    odds = [5]\n    odd_index, even_index = 0, 0\n    ndigits = 1\n    while True:\n        if ndigits % 2 == 1:\n            if len(odds) > odd_index:\n                yield odds[odd_index]\n                odd_index += 1\n            else:\n                \n                odds = sorted([hi * 10**(ndigits + 1) + 10 *\n                              i + lo for i in odds for hi, lo in wrappings])\n                ndigits += 1\n                odd_index = 0\n        else:\n            if len(evens) > even_index:\n                yield evens[even_index]\n                even_index += 1\n            else:\n                \n                evens = sorted([hi * 10**(ndigits + 1) + 10 *\n                               i + lo for i in evens for hi, lo in wrappings])\n                ndigits += 1\n                even_index = 0\n\n\nprint('First fifty upside-downs:')\nfor (udcount, udnumber) in enumerate(gen_upside_down_number()):\n    if udcount < 50:\n        print(f'{udnumber : 5}', end='\\n' if (udcount + 1) % 10 == 0 else '')\n    elif udcount == 499:\n        print(f'\\nFive hundredth: {udnumber: ,}')\n    elif udcount == 4999:\n        print(f'\\nFive thousandth: {udnumber: ,}')\n    elif udcount == 49_999:\n        print(f'\\nFifty thousandth: {udnumber: ,}')\n    elif udcount == 499_999:\n        print(f'\\nFive hundred thousandth: {udnumber: ,}')\n    elif udcount == 4_999_999:\n        print(f'\\nFive millionth: {udnumber: ,}')\n        break\n"}
{"id": 50985, "name": "Minkowski question-mark function", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst MAXITER = 151\n\nfunc minkowski(x float64) float64 {\n    if x > 1 || x < 0 {\n        return math.Floor(x) + minkowski(x-math.Floor(x))\n    }\n    p := uint64(x)\n    q := uint64(1)\n    r := p + 1\n    s := uint64(1)\n    d := 1.0\n    y := float64(p)\n    for {\n        d = d / 2\n        if y+d == y {\n            break\n        }\n        m := p + r\n        if m < 0 || p < 0 {\n            break\n        }\n        n := q + s\n        if n < 0 {\n            break\n        }\n        if x < float64(m)/float64(n) {\n            r = m\n            s = n\n        } else {\n            y = y + d\n            p = m\n            q = n\n        }\n    }\n    return y + d\n}\n\nfunc minkowskiInv(x float64) float64 {\n    if x > 1 || x < 0 {\n        return math.Floor(x) + minkowskiInv(x-math.Floor(x))\n    }\n    if x == 1 || x == 0 {\n        return x\n    }\n    contFrac := []uint32{0}\n    curr := uint32(0)\n    count := uint32(1)\n    i := 0\n    for {\n        x *= 2\n        if curr == 0 {\n            if x < 1 {\n                count++\n            } else {\n                i++\n                t := contFrac\n                contFrac = make([]uint32, i+1)\n                copy(contFrac, t)\n                contFrac[i-1] = count\n                count = 1\n                curr = 1\n                x--\n            }\n        } else {\n            if x > 1 {\n                count++\n                x--\n            } else {\n                i++\n                t := contFrac\n                contFrac = make([]uint32, i+1)\n                copy(contFrac, t)\n                contFrac[i-1] = count\n                count = 1\n                curr = 0\n            }\n        }\n        if x == math.Floor(x) {\n            contFrac[i] = count\n            break\n        }\n        if i == MAXITER {\n            break\n        }\n    }\n    ret := 1.0 / float64(contFrac[i])\n    for j := i - 1; j >= 0; j-- {\n        ret = float64(contFrac[j]) + 1.0/ret\n    }\n    return 1.0 / ret\n}\n\nfunc main() {\n    fmt.Printf(\"%19.16f %19.16f\\n\", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0)\n    fmt.Printf(\"%19.16f %19.16f\\n\", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6)\n    fmt.Printf(\"%19.16f %19.16f\\n\", minkowski(minkowskiInv(0.718281828)),\n        minkowskiInv(minkowski(0.1213141516171819)))\n}\n", "Python": "    print(\n        \"{:19.16f} {:19.16f}\".format(\n            minkowski(minkowski_inv(4.04145188432738056)),\n            minkowski_inv(minkowski(4.04145188432738056)),\n        )\n    )\n"}
{"id": 50986, "name": "Canny edge detector", "Go": "package main\n\nimport (\n    ed \"github.com/Ernyoke/Imger/edgedetection\"\n    \"github.com/Ernyoke/Imger/imgio\"\n    \"log\"\n)\n\nfunc main() {\n    img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not read image\", err)\n    }\n\n    cny, err := ed.CannyRGBA(img, 15, 45, 5)\n    if err != nil {\n        log.Fatal(\"Could not perform Canny Edge detection\")\n    }\n\n    err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not write Canny image to disk\")\n    }\n}\n", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n"}
{"id": 50987, "name": "War card game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar suits = []string{\"♣\", \"♦\", \"♥\", \"♠\"}\nvar faces = []string{\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"}\nvar cards = make([]string, 52)\nvar ranks = make([]int, 52)\n\nfunc init() {\n    for i := 0; i < 52; i++ {\n        cards[i] = fmt.Sprintf(\"%s%s\", faces[i%13], suits[i/13])\n        ranks[i] = i % 13\n    }\n}\n\nfunc war() {\n    deck := make([]int, 52)\n    for i := 0; i < 52; i++ {\n        deck[i] = i\n    }\n    rand.Shuffle(52, func(i, j int) {\n        deck[i], deck[j] = deck[j], deck[i]\n    })\n    hand1 := make([]int, 26, 52)\n    hand2 := make([]int, 26, 52)\n    for i := 0; i < 26; i++ {\n        hand1[25-i] = deck[2*i]\n        hand2[25-i] = deck[2*i+1]\n    }\n    for len(hand1) > 0 && len(hand2) > 0 {\n        card1 := hand1[0]\n        copy(hand1[0:], hand1[1:])\n        hand1[len(hand1)-1] = 0\n        hand1 = hand1[0 : len(hand1)-1]\n        card2 := hand2[0]\n        copy(hand2[0:], hand2[1:])\n        hand2[len(hand2)-1] = 0\n        hand2 = hand2[0 : len(hand2)-1]\n        played1 := []int{card1}\n        played2 := []int{card2}\n        numPlayed := 2\n        for {\n            fmt.Printf(\"%s\\t%s\\t\", cards[card1], cards[card2])\n            if ranks[card1] > ranks[card2] {\n                hand1 = append(hand1, played1...)\n                hand1 = append(hand1, played2...)\n                fmt.Printf(\"Player 1 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand1))\n                break\n            } else if ranks[card1] < ranks[card2] {\n                hand2 = append(hand2, played2...)\n                hand2 = append(hand2, played1...)\n                fmt.Printf(\"Player 2 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand2))\n                break\n            } else {\n                fmt.Println(\"War!\")\n                if len(hand1) < 2 {\n                    fmt.Println(\"Player 1 has insufficient cards left.\")\n                    hand2 = append(hand2, played2...)\n                    hand2 = append(hand2, played1...)\n                    hand2 = append(hand2, hand1...)\n                    hand1 = hand1[0:0]\n                    break\n                }\n                if len(hand2) < 2 {\n                    fmt.Println(\"Player 2 has insufficient cards left.\")\n                    hand1 = append(hand1, played1...)\n                    hand1 = append(hand1, played2...)\n                    hand1 = append(hand1, hand2...)\n                    hand2 = hand2[0:0]\n                    break\n                }\n                fdCard1 := hand1[0] \n                card1 = hand1[1]    \n                copy(hand1[0:], hand1[2:])\n                hand1[len(hand1)-1] = 0\n                hand1[len(hand1)-2] = 0\n                hand1 = hand1[0 : len(hand1)-2]\n                played1 = append(played1, fdCard1, card1)\n                fdCard2 := hand2[0] \n                card2 = hand2[1]    \n                copy(hand2[0:], hand2[2:])\n                hand2[len(hand2)-1] = 0\n                hand2[len(hand2)-2] = 0\n                hand2 = hand2[0 : len(hand2)-2]\n                played2 = append(played2, fdCard2, card2)\n                numPlayed += 4\n                fmt.Println(\"? \\t? \\tFace down cards.\")\n            }\n        }\n    }\n    if len(hand1) == 52 {\n        fmt.Println(\"Player 1 wins the game!\")\n    } else {\n        fmt.Println(\"Player 2 wins the game!\")\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    war()\n}\n", "Python": "\n\nfrom numpy.random import shuffle\n\nSUITS = ['♣', '♦', '♥', '♠']\nFACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nDECK = [f + s for f in FACES for s in SUITS]\nCARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))\n\n\nclass WarCardGame:\n    \n    def __init__(self):\n        deck = DECK.copy()\n        shuffle(deck)\n        self.deck1, self.deck2 = deck[:26], deck[26:]\n        self.pending = []\n\n    def turn(self):\n        \n        if len(self.deck1) == 0 or len(self.deck2) == 0:\n            return self.gameover()\n\n        card1, card2 = self.deck1.pop(0), self.deck2.pop(0)\n        rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]\n        print(\"{:10}{:10}\".format(card1, card2), end='')\n        if rank1 > rank2:\n            print('Player 1 takes the cards.')\n            self.deck1.extend([card1, card2])\n            self.deck1.extend(self.pending)\n            self.pending = []\n        elif rank1 < rank2:\n            print('Player 2 takes the cards.')\n            self.deck2.extend([card2, card1])\n            self.deck2.extend(self.pending)\n            self.pending = []\n        else:  \n            print('Tie!')\n            if len(self.deck1) == 0 or len(self.deck2) == 0:\n                return self.gameover()\n\n            card3, card4 = self.deck1.pop(0), self.deck2.pop(0)\n            self.pending.extend([card1, card2, card3, card4])\n            print(\"{:10}{:10}\".format(\"?\", \"?\"), 'Cards are face down.', sep='')\n            return self.turn()\n\n        return True\n\n    def gameover(self):\n        \n        if len(self.deck2) == 0:\n            if len(self.deck1) == 0:\n                print('\\nGame ends as a tie.')\n            else:\n                print('\\nPlayer 1 wins the game.')\n        else:\n            print('\\nPlayer 2 wins the game.')\n\n        return False\n\n\nif __name__ == '__main__':\n    WG = WarCardGame()\n    while WG.turn():\n        continue\n"}
{"id": 50988, "name": "War card game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar suits = []string{\"♣\", \"♦\", \"♥\", \"♠\"}\nvar faces = []string{\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"}\nvar cards = make([]string, 52)\nvar ranks = make([]int, 52)\n\nfunc init() {\n    for i := 0; i < 52; i++ {\n        cards[i] = fmt.Sprintf(\"%s%s\", faces[i%13], suits[i/13])\n        ranks[i] = i % 13\n    }\n}\n\nfunc war() {\n    deck := make([]int, 52)\n    for i := 0; i < 52; i++ {\n        deck[i] = i\n    }\n    rand.Shuffle(52, func(i, j int) {\n        deck[i], deck[j] = deck[j], deck[i]\n    })\n    hand1 := make([]int, 26, 52)\n    hand2 := make([]int, 26, 52)\n    for i := 0; i < 26; i++ {\n        hand1[25-i] = deck[2*i]\n        hand2[25-i] = deck[2*i+1]\n    }\n    for len(hand1) > 0 && len(hand2) > 0 {\n        card1 := hand1[0]\n        copy(hand1[0:], hand1[1:])\n        hand1[len(hand1)-1] = 0\n        hand1 = hand1[0 : len(hand1)-1]\n        card2 := hand2[0]\n        copy(hand2[0:], hand2[1:])\n        hand2[len(hand2)-1] = 0\n        hand2 = hand2[0 : len(hand2)-1]\n        played1 := []int{card1}\n        played2 := []int{card2}\n        numPlayed := 2\n        for {\n            fmt.Printf(\"%s\\t%s\\t\", cards[card1], cards[card2])\n            if ranks[card1] > ranks[card2] {\n                hand1 = append(hand1, played1...)\n                hand1 = append(hand1, played2...)\n                fmt.Printf(\"Player 1 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand1))\n                break\n            } else if ranks[card1] < ranks[card2] {\n                hand2 = append(hand2, played2...)\n                hand2 = append(hand2, played1...)\n                fmt.Printf(\"Player 2 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand2))\n                break\n            } else {\n                fmt.Println(\"War!\")\n                if len(hand1) < 2 {\n                    fmt.Println(\"Player 1 has insufficient cards left.\")\n                    hand2 = append(hand2, played2...)\n                    hand2 = append(hand2, played1...)\n                    hand2 = append(hand2, hand1...)\n                    hand1 = hand1[0:0]\n                    break\n                }\n                if len(hand2) < 2 {\n                    fmt.Println(\"Player 2 has insufficient cards left.\")\n                    hand1 = append(hand1, played1...)\n                    hand1 = append(hand1, played2...)\n                    hand1 = append(hand1, hand2...)\n                    hand2 = hand2[0:0]\n                    break\n                }\n                fdCard1 := hand1[0] \n                card1 = hand1[1]    \n                copy(hand1[0:], hand1[2:])\n                hand1[len(hand1)-1] = 0\n                hand1[len(hand1)-2] = 0\n                hand1 = hand1[0 : len(hand1)-2]\n                played1 = append(played1, fdCard1, card1)\n                fdCard2 := hand2[0] \n                card2 = hand2[1]    \n                copy(hand2[0:], hand2[2:])\n                hand2[len(hand2)-1] = 0\n                hand2[len(hand2)-2] = 0\n                hand2 = hand2[0 : len(hand2)-2]\n                played2 = append(played2, fdCard2, card2)\n                numPlayed += 4\n                fmt.Println(\"? \\t? \\tFace down cards.\")\n            }\n        }\n    }\n    if len(hand1) == 52 {\n        fmt.Println(\"Player 1 wins the game!\")\n    } else {\n        fmt.Println(\"Player 2 wins the game!\")\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    war()\n}\n", "Python": "\n\nfrom numpy.random import shuffle\n\nSUITS = ['♣', '♦', '♥', '♠']\nFACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nDECK = [f + s for f in FACES for s in SUITS]\nCARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))\n\n\nclass WarCardGame:\n    \n    def __init__(self):\n        deck = DECK.copy()\n        shuffle(deck)\n        self.deck1, self.deck2 = deck[:26], deck[26:]\n        self.pending = []\n\n    def turn(self):\n        \n        if len(self.deck1) == 0 or len(self.deck2) == 0:\n            return self.gameover()\n\n        card1, card2 = self.deck1.pop(0), self.deck2.pop(0)\n        rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]\n        print(\"{:10}{:10}\".format(card1, card2), end='')\n        if rank1 > rank2:\n            print('Player 1 takes the cards.')\n            self.deck1.extend([card1, card2])\n            self.deck1.extend(self.pending)\n            self.pending = []\n        elif rank1 < rank2:\n            print('Player 2 takes the cards.')\n            self.deck2.extend([card2, card1])\n            self.deck2.extend(self.pending)\n            self.pending = []\n        else:  \n            print('Tie!')\n            if len(self.deck1) == 0 or len(self.deck2) == 0:\n                return self.gameover()\n\n            card3, card4 = self.deck1.pop(0), self.deck2.pop(0)\n            self.pending.extend([card1, card2, card3, card4])\n            print(\"{:10}{:10}\".format(\"?\", \"?\"), 'Cards are face down.', sep='')\n            return self.turn()\n\n        return True\n\n    def gameover(self):\n        \n        if len(self.deck2) == 0:\n            if len(self.deck1) == 0:\n                print('\\nGame ends as a tie.')\n            else:\n                print('\\nPlayer 1 wins the game.')\n        else:\n            print('\\nPlayer 2 wins the game.')\n\n        return False\n\n\nif __name__ == '__main__':\n    WG = WarCardGame()\n    while WG.turn():\n        continue\n"}
{"id": 50989, "name": "Color quantization", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    f, err := os.Open(\"Quantum_frog.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    img, err := png.Decode(f)\n    if ec := f.Close(); err != nil {\n        log.Fatal(err)\n    } else if ec != nil {\n        log.Fatal(ec)\n    }\n    fq, err := os.Create(\"frog16.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = png.Encode(fq, quant(img, 16)); err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc quant(img image.Image, nq int) image.Image {\n    qz := newQuantizer(img, nq) \n    qz.cluster()                \n    return qz.Paletted()        \n}\n\n\ntype quantizer struct {\n    img image.Image \n    cs  []cluster   \n    px  []point     \n    ch  chValues    \n    eq  []point     \n}\n\ntype cluster struct {\n    px       []point \n    widestCh int     \n    chRange  uint32  \n}\n\ntype point struct{ x, y int }\ntype chValues []uint32\ntype queue []*cluster\n\nconst (\n    rx = iota\n    gx\n    bx\n)\n\nfunc newQuantizer(img image.Image, nq int) *quantizer {\n    b := img.Bounds()\n    npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)\n    \n    qz := &quantizer{\n        img: img,\n        ch:  make(chValues, npx),\n        cs:  make([]cluster, nq),\n    }\n    \n    c := &qz.cs[0]\n    px := make([]point, npx)\n    c.px = px\n    i := 0\n    for y := b.Min.Y; y < b.Max.Y; y++ {\n        for x := b.Min.X; x < b.Max.X; x++ {\n            px[i].x = x\n            px[i].y = y\n            i++\n        }\n    }\n    return qz\n}\n\nfunc (qz *quantizer) cluster() {\n    \n    \n    \n    \n    \n    pq := new(queue)\n    \n    c := &qz.cs[0]\n    for i := 1; ; {\n        qz.setColorRange(c)\n        \n        \n        if c.chRange > 0 {\n            heap.Push(pq, c) \n        }\n        \n        \n        if len(*pq) == 0 {\n            qz.cs = qz.cs[:i]\n            break\n        }\n        s := heap.Pop(pq).(*cluster) \n        c = &qz.cs[i]                \n        i++\n        m := qz.Median(s)\n        qz.Split(s, c, m) \n        \n        if i == len(qz.cs) {\n            break\n        }\n        qz.setColorRange(s)\n        if s.chRange > 0 {\n            heap.Push(pq, s) \n        }\n    }\n}\n    \nfunc (q *quantizer) setColorRange(c *cluster) {\n    \n    var maxR, maxG, maxB uint32\n    minR := uint32(math.MaxUint32)\n    minG := uint32(math.MaxUint32)\n    minB := uint32(math.MaxUint32) \n    for _, p := range c.px {\n        r, g, b, _ := q.img.At(p.x, p.y).RGBA()\n        if r < minR { \n            minR = r\n        }\n        if r > maxR {\n            maxR = r\n        }\n        if g < minG {\n            minG = g \n        }\n        if g > maxG {\n            maxG = g\n        }\n        if b < minB {\n            minB = b\n        }\n        if b > maxB {\n            maxB = b\n        }\n    }\n    \n    s := gx\n    min := minG\n    max := maxG\n    if maxR-minR > max-min {\n        s = rx\n        min = minR\n        max = maxR\n    }\n    if maxB-minB > max-min {\n        s = bx\n        min = minB\n        max = maxB\n    }\n    c.widestCh = s\n    c.chRange = max - min \n}\n\nfunc (q *quantizer) Median(c *cluster) uint32 {\n    px := c.px\n    ch := q.ch[:len(px)]\n    \n    switch c.widestCh {\n    case rx:\n        for i, p := range c.px {\n            ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case gx:\n        for i, p := range c.px {\n            _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case bx:\n        for i, p := range c.px {\n            _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA()\n        }\n    }\n    \n    sort.Sort(ch)\n    half := len(ch) / 2\n    m := ch[half]\n    if len(ch)%2 == 0 {\n        m = (m + ch[half-1]) / 2\n    }\n    return m\n}\n\nfunc (q *quantizer) Split(s, c *cluster, m uint32) {\n    px := s.px\n    var v uint32\n    i := 0\n    lt := 0\n    gt := len(px) - 1\n    eq := q.eq[:0] \n    for i <= gt {\n        \n        r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA()\n        switch s.widestCh {\n        case rx:\n            v = r\n        case gx:\n            v = g\n        case bx:\n            v = b\n        } \n        \n        switch {\n        case v < m:\n            px[lt] = px[i]\n            lt++\n            i++\n        case v > m:\n            px[gt], px[i] = px[i], px[gt]\n            gt--\n        default:\n            eq = append(eq, px[i])\n            i++\n        }\n    }\n    \n    if len(eq) > 0 {\n        copy(px[lt:], eq) \n        \n        \n        \n        if len(px)-i < lt {\n            i = lt\n        }\n        q.eq = eq \n    }\n    \n    s.px = px[:i]\n    c.px = px[i:]\n}   \n    \nfunc (qz *quantizer) Paletted() *image.Paletted {\n    cp := make(color.Palette, len(qz.cs))\n    pi := image.NewPaletted(qz.img.Bounds(), cp)\n    for i := range qz.cs {\n        px := qz.cs[i].px\n        \n        var rsum, gsum, bsum int64\n        for _, p := range px {\n            r, g, b, _ := qz.img.At(p.x, p.y).RGBA()\n            rsum += int64(r)\n            gsum += int64(g)\n            bsum += int64(b)\n        } \n        n64 := int64(len(px))\n        cp[i] = color.NRGBA64{\n            uint16(rsum / n64),\n            uint16(gsum / n64),\n            uint16(bsum / n64),\n            0xffff,\n        }\n        \n        for _, p := range px {\n            pi.SetColorIndex(p.x, p.y, uint8(i))\n        }\n    }\n    return pi\n}\n\n\nfunc (c chValues) Len() int           { return len(c) }\nfunc (c chValues) Less(i, j int) bool { return c[i] < c[j] }\nfunc (c chValues) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\n\n\nfunc (q queue) Len() int { return len(q) }\n\n\nfunc (q queue) Less(i, j int) bool {\n    return len(q[j].px) < len(q[i].px)\n}\n\nfunc (q queue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n}\nfunc (pq *queue) Push(x interface{}) {\n    c := x.(*cluster)\n    *pq = append(*pq, c)\n}\nfunc (pq *queue) Pop() interface{} {\n    q := *pq\n    n := len(q) - 1\n    c := q[n]\n    *pq = q[:n]\n    return c\n}\n", "Python": "from PIL import Image\n\nif __name__==\"__main__\":\n\tim = Image.open(\"frog.png\")\n\tim2 = im.quantize(16)\n\tim2.show()\n"}
{"id": 50990, "name": "Modified random distribution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n    for {\n        r1 := rand.Float64()\n        r2 := rand.Float64()\n        if r2 < modifier(r1) {\n            return r1\n        }\n    }\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    rand.Seed(time.Now().UnixNano())\n    modifier := func(x float64) float64 {\n        if x < 0.5 {\n            return 2 * (0.5 - x)\n        }\n        return 2 * (x - 0.5)\n    }\n    const (\n        N              = 100000\n        NUM_BINS       = 20\n        HIST_CHAR      = \"■\"\n        HIST_CHAR_SIZE = 125\n    )\n    bins := make([]int, NUM_BINS) \n    binSize := 1.0 / NUM_BINS\n    for i := 0; i < N; i++ {\n        rn := rng(modifier)\n        bn := int(math.Floor(rn / binSize))\n        bins[bn]++\n    }\n\n    fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n    fmt.Println(\"    Range           Number of samples within that range\")\n    for i := 0; i < NUM_BINS; i++ {\n        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n        fi := float64(i)\n        fmt.Printf(\"%4.2f ..< %4.2f  %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n    }\n}\n", "Python": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n    \n    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n                                 n: int) -> List[float]:\n    \n    d: List[float] = []\n    while len(d) < n:\n        r1 = prob = random.random()\n        if random.random() < modifier(prob):\n            d.append(r1)\n    return d\n\n\nif __name__ == '__main__':\n    from collections import Counter\n\n    data = modified_random_distribution(modifier, 50_000)\n    bins = 15\n    counts = Counter(d // (1 / bins) for d in data)\n    \n    mx = max(counts.values())\n    print(\"   BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n    last: Optional[float] = None\n    for b, count in sorted(counts.items()):\n        delta = 'N/A' if last is None else str(count - last)\n        print(f\"  {b / bins:5.2f},  {count:4},  {delta:>4}: \"\n              f\"{'\n        last = count\n"}
{"id": 50991, "name": "Modified random distribution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n    for {\n        r1 := rand.Float64()\n        r2 := rand.Float64()\n        if r2 < modifier(r1) {\n            return r1\n        }\n    }\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    rand.Seed(time.Now().UnixNano())\n    modifier := func(x float64) float64 {\n        if x < 0.5 {\n            return 2 * (0.5 - x)\n        }\n        return 2 * (x - 0.5)\n    }\n    const (\n        N              = 100000\n        NUM_BINS       = 20\n        HIST_CHAR      = \"■\"\n        HIST_CHAR_SIZE = 125\n    )\n    bins := make([]int, NUM_BINS) \n    binSize := 1.0 / NUM_BINS\n    for i := 0; i < N; i++ {\n        rn := rng(modifier)\n        bn := int(math.Floor(rn / binSize))\n        bins[bn]++\n    }\n\n    fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n    fmt.Println(\"    Range           Number of samples within that range\")\n    for i := 0; i < NUM_BINS; i++ {\n        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n        fi := float64(i)\n        fmt.Printf(\"%4.2f ..< %4.2f  %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n    }\n}\n", "Python": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n    \n    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n                                 n: int) -> List[float]:\n    \n    d: List[float] = []\n    while len(d) < n:\n        r1 = prob = random.random()\n        if random.random() < modifier(prob):\n            d.append(r1)\n    return d\n\n\nif __name__ == '__main__':\n    from collections import Counter\n\n    data = modified_random_distribution(modifier, 50_000)\n    bins = 15\n    counts = Counter(d // (1 / bins) for d in data)\n    \n    mx = max(counts.values())\n    print(\"   BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n    last: Optional[float] = None\n    for b, count in sorted(counts.items()):\n        delta = 'N/A' if last is None else str(count - last)\n        print(f\"  {b / bins:5.2f},  {count:4},  {delta:>4}: \"\n              f\"{'\n        last = count\n"}
{"id": 50992, "name": "Modified random distribution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n    for {\n        r1 := rand.Float64()\n        r2 := rand.Float64()\n        if r2 < modifier(r1) {\n            return r1\n        }\n    }\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    rand.Seed(time.Now().UnixNano())\n    modifier := func(x float64) float64 {\n        if x < 0.5 {\n            return 2 * (0.5 - x)\n        }\n        return 2 * (x - 0.5)\n    }\n    const (\n        N              = 100000\n        NUM_BINS       = 20\n        HIST_CHAR      = \"■\"\n        HIST_CHAR_SIZE = 125\n    )\n    bins := make([]int, NUM_BINS) \n    binSize := 1.0 / NUM_BINS\n    for i := 0; i < N; i++ {\n        rn := rng(modifier)\n        bn := int(math.Floor(rn / binSize))\n        bins[bn]++\n    }\n\n    fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n    fmt.Println(\"    Range           Number of samples within that range\")\n    for i := 0; i < NUM_BINS; i++ {\n        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n        fi := float64(i)\n        fmt.Printf(\"%4.2f ..< %4.2f  %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n    }\n}\n", "Python": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n    \n    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n                                 n: int) -> List[float]:\n    \n    d: List[float] = []\n    while len(d) < n:\n        r1 = prob = random.random()\n        if random.random() < modifier(prob):\n            d.append(r1)\n    return d\n\n\nif __name__ == '__main__':\n    from collections import Counter\n\n    data = modified_random_distribution(modifier, 50_000)\n    bins = 15\n    counts = Counter(d // (1 / bins) for d in data)\n    \n    mx = max(counts.values())\n    print(\"   BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n    last: Optional[float] = None\n    for b, count in sorted(counts.items()):\n        delta = 'N/A' if last is None else str(count - last)\n        print(f\"  {b / bins:5.2f},  {count:4},  {delta:>4}: \"\n              f\"{'\n        last = count\n"}
{"id": 50993, "name": "Collect and sort square numbers in ascending order from three lists", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc main() {\n    lists := [][]int{\n        {3, 4, 34, 25, 9, 12, 36, 56, 36},\n        {2, 8, 81, 169, 34, 55, 76, 49, 7},\n        {75, 121, 75, 144, 35, 16, 46, 35},\n    }\n    var squares []int\n    for _, list := range lists {\n        for _, e := range list {\n            if isSquare(e) {\n                squares = append(squares, e)\n            }\n        }\n    }\n    sort.Ints(squares)\n    fmt.Println(squares)\n}\n", "Python": "import math\n\nprint(\"working...\")\nlist = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)]\nSquares = []\n\ndef issquare(x):\n\tfor p in range(x):\n\t\tif x == p*p:\n\t\t\treturn 1\nfor n in range(3):\n\tfor m in range(len(list[n])):\n\t\tif issquare(list[n][m]):\n\t\t\tSquares.append(list[n][m])\n\nSquares.sort()\nprint(Squares)\nprint(\"done...\")\n"}
{"id": 50994, "name": "Collect and sort square numbers in ascending order from three lists", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc main() {\n    lists := [][]int{\n        {3, 4, 34, 25, 9, 12, 36, 56, 36},\n        {2, 8, 81, 169, 34, 55, 76, 49, 7},\n        {75, 121, 75, 144, 35, 16, 46, 35},\n    }\n    var squares []int\n    for _, list := range lists {\n        for _, e := range list {\n            if isSquare(e) {\n                squares = append(squares, e)\n            }\n        }\n    }\n    sort.Ints(squares)\n    fmt.Println(squares)\n}\n", "Python": "import math\n\nprint(\"working...\")\nlist = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)]\nSquares = []\n\ndef issquare(x):\n\tfor p in range(x):\n\t\tif x == p*p:\n\t\t\treturn 1\nfor n in range(3):\n\tfor m in range(len(list[n])):\n\t\tif issquare(list[n][m]):\n\t\t\tSquares.append(list[n][m])\n\nSquares.sort()\nprint(Squares)\nprint(\"done...\")\n"}
{"id": 50995, "name": "Suffixation of decimal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n"}
{"id": 50996, "name": "Suffixation of decimal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n"}
{"id": 50997, "name": "Longest palindromic substrings", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc reverse(s string) string {\n    var r = []rune(s)\n    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc longestPalSubstring(s string) []string {\n    var le = len(s)\n    if le <= 1 {\n        return []string{s}\n    }\n    targetLen := le\n    var longest []string\n    i := 0\n    for {\n        j := i + targetLen - 1\n        if j < le {\n            ss := s[i : j+1]\n            if reverse(ss) == ss {\n                longest = append(longest, ss)\n            }\n            i++\n        } else {\n            if len(longest) > 0 {\n                return longest\n            }\n            i = 0\n            targetLen--\n        }\n    }\n    return longest\n}\n\nfunc distinct(sa []string) []string {\n    sort.Strings(sa)\n    duplicated := make([]bool, len(sa))\n    for i := 1; i < len(sa); i++ {\n        if sa[i] == sa[i-1] {\n            duplicated[i] = true\n        }\n    }\n    var res []string\n    for i := 0; i < len(sa); i++ {\n        if !duplicated[i] {\n            res = append(res, sa[i])\n        }\n    }\n    return res\n}\n\nfunc main() {\n    strings := []string{\"babaccd\", \"rotator\", \"reverse\", \"forever\", \"several\", \"palindrome\", \"abaracadaraba\"}\n    fmt.Println(\"The palindromic substrings having the longest length are:\")\n    for _, s := range strings {\n        longest := distinct(longestPalSubstring(s))\n        fmt.Printf(\"  %-13s Length %d -> %v\\n\", s, len(longest[0]), longest)\n    }\n}\n", "Python": "\n\n\n\ndef longestPalindromes(s):\n    \n    k = s.lower()\n    palindromes = [\n        palExpansion(k)(ab) for ab\n        in palindromicNuclei(k)\n    ]\n    maxLength = max([\n        len(x) for x in palindromes\n    ]) if palindromes else 1\n    return (\n        [\n            x for x in palindromes if maxLength == len(x)\n        ] if palindromes else list(s),\n        maxLength\n    ) if s else ([], 0)\n\n\n\ndef palindromicNuclei(s):\n    \n    cs = list(s)\n    return [\n        \n        (i, 1 + i) for (i, (a, b))\n        in enumerate(zip(cs, cs[1:]))\n        if a == b\n    ] + [\n        \n        (i, 2 + i) for (i, (a, b, c))\n        in enumerate(zip(cs, cs[1:], cs[2:]))\n        if a == c\n    ]\n\n\n\ndef palExpansion(s):\n    \n    iEnd = len(s) - 1\n\n    def limit(ij):\n        i, j = ij\n        return 0 == i or iEnd == j or s[i-1] != s[j+1]\n\n    def expansion(ij):\n        i, j = ij\n        return (i - 1, 1 + j)\n\n    def go(ij):\n        ab = until(limit)(expansion)(ij)\n        return s[ab[0]:ab[1] + 1]\n    return go\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(repr)(\n            longestPalindromes\n        )([\n            'three old rotators',\n            'never reverse',\n            'stable was I ere I saw elbatrosses',\n            'abracadabra',\n            'drome',\n            'the abbatial palace',\n            ''\n        ])\n    )\n\n\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\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\nif __name__ == '__main__':\n    main()\n"}
{"id": 50998, "name": "Hunt the Wumpus", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar cave = map[int][3]int{\n    1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11},\n    6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16},\n    11: {5, 12, 17}, 12: {6, 11, 18}, 13: {7, 14, 18}, 14: {8, 13, 19},\n    15: {9, 16, 17}, 16: {10, 15, 19}, 17: {11, 20, 15}, 18: {12, 13, 20},\n    19: {14, 16, 20}, 20: {17, 18, 19},\n}\n\nvar player, wumpus, bat1, bat2, pit1, pit2 int\n\nvar arrows = 5\n\nfunc isEmpty(r int) bool {\n    if r != player && r != wumpus && r != bat1 && r != bat2 && r != pit1 && r != pit2 {\n        return true\n    }\n    return false\n}\n\nfunc sense(adj [3]int) {\n    bat := false\n    pit := false\n    for _, ar := range adj {\n        if ar == wumpus {\n            fmt.Println(\"You smell something terrible nearby.\")\n        }\n        switch ar {\n        case bat1, bat2:\n            if !bat {\n                fmt.Println(\"You hear a rustling.\")\n                bat = true\n            }\n        case pit1, pit2:\n            if !pit {\n                fmt.Println(\"You feel a cold wind blowing from a nearby cavern.\")\n                pit = true\n            }\n        }\n    }\n    fmt.Println()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc plural(n int) string {\n    if n != 1 {\n        return \"s\"\n    }\n    return \"\"\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    player = 1\n    wumpus = rand.Intn(19) + 2 \n    bat1 = rand.Intn(19) + 2\n    for {\n        bat2 = rand.Intn(19) + 2\n        if bat2 != bat1 {\n            break\n        }\n    }\n    for {\n        pit1 = rand.Intn(19) + 2\n        if pit1 != bat1 && pit1 != bat2 {\n            break\n        }\n    }\n    for {\n        pit2 = rand.Intn(19) + 2\n        if pit2 != bat1 && pit2 != bat2 && pit2 != pit1 {\n            break\n        }\n    }\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        fmt.Printf(\"\\nYou are in room %d with %d arrow%s left\\n\", player, arrows, plural(arrows))\n        adj := cave[player]\n        fmt.Printf(\"The adjacent rooms are %v\\n\", adj)\n        sense(adj)\n        var room int\n        for {\n            fmt.Print(\"Choose an adjacent room : \")\n            scanner.Scan()\n            room, _ = strconv.Atoi(scanner.Text())\n            if room != adj[0] && room != adj[1] && room != adj[2] {\n                fmt.Println(\"Invalid response, try again\")\n            } else {\n                break\n            }\n        }\n        check(scanner.Err())\n        var action byte\n        for {\n            fmt.Print(\"Walk or shoot w/s : \")\n            scanner.Scan()\n            reply := strings.ToLower(scanner.Text())\n            if len(reply) != 1 || (len(reply) == 1 && reply[0] != 'w' && reply[0] != 's') {\n                fmt.Println(\"Invalid response, try again\")\n            } else {\n                action = reply[0]\n                break\n            }\n        }\n        check(scanner.Err())\n        if action == 'w' {\n            player = room\n            switch player {\n            case wumpus:\n                fmt.Println(\"You have been eaten by the Wumpus and lost the game!\")\n                return\n            case pit1, pit2:\n                fmt.Println(\"You have fallen down a bottomless pit and lost the game!\")\n                return\n            case bat1, bat2:\n                for {\n                    room = rand.Intn(19) + 2\n                    if isEmpty(room) {\n                        fmt.Println(\"A bat has transported you to a random empty room\")\n                        player = room\n                        break\n                    }\n                }\n            }\n        } else {\n            if room == wumpus {\n                fmt.Println(\"You have killed the Wumpus and won the game!!\")\n                return\n            } else {\n                chance := rand.Intn(4) \n                if chance > 0 {        \n                    wumpus = cave[wumpus][rand.Intn(3)]\n                    if player == wumpus {\n                        fmt.Println(\"You have been eaten by the Wumpus and lost the game!\")\n                        return\n                    }\n                }\n            }\n            arrows--\n            if arrows == 0 {\n                fmt.Println(\"You have run out of arrows and lost the game!\")\n                return\n            }\n        }\n    }\n}\n", "Python": "import random\n\nclass WumpusGame(object):\n\n\n\tdef __init__(self, edges=[]):\n\t\t\n\t\t\n\t\tif edges:\n\t\t\tcave = {}\n\t\t\tN = max([edges[i][0] for i in range(len(edges))])\n\t\t\tfor i in range(N):\n\t\t\t\texits = [edge[1] for edge in edges if edge[0] == i]\n\t\t\t\tcave[i] = exits\n\n\t\t\n\t\telse:\n\t\t\tcave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1,9,10], 5:[2,9,11],\n\t\t\t\t6: [2,7,12], 7: [3,6,13], 8: [3,10,14], 9: [4,5,15], 10: [4,8,16], \n\t\t\t\t11: [5,12,17], 12: [6,11,18], 13: [7,14,18], 14: [8,13,19], \n\t\t\t\t15: [9,16,17], 16: [10,15,19], 17: [11,20,15], 18: [12,13,20], \n\t\t\t\t19: [14,16,20], 20: [17,18,19]}\n\n\t\tself.cave = cave\n\n\t\tself.threats = {}\n\n\t\tself.arrows = 5\n\n\t\tself.arrow_travel_distance = 5\t\t\n\t\t\t\t\t\t\t\t\t\t\t\n\t\tself.player_pos = -1\n\n\n\t\n\n\n\tdef get_safe_rooms(self):\n\t\t\n\t\treturn list(set(self.cave.keys()).difference(self.threats.keys()))\n\n\n\tdef populate_cave(self):\n\t\t\n\t\tfor threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']:\n\t\t\tpos = random.choice(self.get_safe_rooms())\n\t\t\tself.threats[pos] = threat\n\t\tself.player_pos = random.choice(self.get_safe_rooms())\n\n\n\tdef breadth_first_search(self, source, target, max_depth=5):\n\t\t\n\t\t\n\t\tgraph = self.cave\n\t\tdepth = 0\n\n\t\tdef search(stack, visited, target, depth):\n\t\t\tif stack == []:\t\t\t\t\t\n\t\t\t\treturn False, -1\n\t\t\tif target in stack:\n\t\t\t\treturn True, depth\n\t\t\tvisited = visited + stack\n\t\t\tstack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited))\n\t\t\tdepth += 1\n\t\t\tif depth > max_depth:\t\t\t\n\t\t\t\treturn False, depth\n\t\t\telse:\t\t\t\t\t\t\t\n\t\t\t\treturn search(stack, visited, target, depth)\n\n\t\treturn search([source], [], target, depth)\n\n\n\t\n\n\n\tdef print_warning(self, threat):\n\t\t\n\t\tif threat == 'bat':\n\t\t\tprint(\"You hear a rustling.\")\n\t\telif threat == 'pit':\n\t\t\tprint(\"You feel a cold wind blowing from a nearby cavern.\")\n\t\telif threat == 'wumpus':\n\t\t\tprint(\"You smell something terrible nearby.\")\n\n\n\tdef get_players_input(self):\n\t\t\n\t\twhile 1:\t\t\t\t\t\t\t\t\n\n\t\t\tinpt = input(\"Shoot or move (S-M)? \")\n\t\t\ttry:\t\t\t\t\t\t\t\t\n\t\t\t\tmode = str(inpt).lower()\n\t\t\t\tassert mode in ['s', 'm', 'q']\n\t\t\t\tbreak\n\t\t\texcept (ValueError, AssertionError):\n\t\t\t\tprint(\"This is not a valid action: pick 'S' to shoot and 'M' to move.\")\n\n\t\tif mode == 'q':\t\t\t\t\t\t\t\n\t\t\treturn 'q', 0\n\n\t\twhile 1:\t\t\t\t\t\t\t\t\n\n\t\t\tinpt = input(\"Where to? \")\n\t\t\ttry:\t\t\t\t\t\t\t\t\n\t\t\t\ttarget = int(inpt)\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"This is not even a real number.\")\n\t\t\t\tcontinue\t\t\t\t\t\t\n\n\t\t\tif mode == 'm':\n\t\t\t\ttry:\t\t\t\t\t\t\t\n\t\t\t\t\tassert target in self.cave[self.player_pos]\n\t\t\t\t\tbreak\n\t\t\t\texcept AssertionError:\n\t\t\t\t\tprint(\"You cannot walk that far. Please use one of the tunnels.\")\n\n\t\t\telif mode == 's':\n\t\t\t\ttry:\t\t\t\t\t\t\t\n\t\t\t\t\tbfs = self.breadth_first_search(self.player_pos, target)\n\t\t\t\t\tassert bfs[0] == True\n\t\t\t\t\tbreak\n\t\t\t\texcept AssertionError:\n\t\t\t\t\tif bfs[1] == -1: \t\t\t\n\t\t\t\t\t\tprint(\"There is no room with this number in the cave. Your arrow travels randomly.\")\n\t\t\t\t\t\ttarget = random.choice(self.cave.keys())\n\t\t\t\t\tif bfs[1] > self.arrow_travel_distance:\t\t\t\t\n\t\t\t\t\t\tprint(\"Arrows aren't that croocked.\")\n\n\t\treturn mode, target\n\n\n\t\n\n\n\tdef enter_room(self, room_number):\n\t\t\t\n\t\tprint(\"Entering room {}...\".format(room_number))\n\t\t\n\t\tif self.threats.get(room_number) == 'bat':\n\t\t\t\n\t\t\tprint(\"You encounter a bat, it transports you to a random empty room.\")\n\t\t\tnew_pos = random.choice(self.get_safe_rooms())\n\t\t\treturn self.enter_room(new_pos)\n\t\telif self.threats.get(room_number) == 'wumpus':\n\t\t\tprint(\"Wumpus eats you.\")\n\t\t\treturn -1\n\t\telif self.threats.get(room_number) == 'pit':\n\t\t\tprint(\"You fall into a pit.\")\n\t\t\treturn -1\n\n\t\t\n\t\tfor i in self.cave[room_number]:\n\t\t\tself.print_warning(self.threats.get(i))\n\n\t\t\n\t\treturn room_number\n\n\n\tdef shoot_room(self, room_number):\n\t\t\n\t\tprint(\"Shooting an arrow into room {}...\".format(room_number))\n\t\t\n\t\tself.arrows -= 1\n\t\tthreat = self.threats.get(room_number)\n\t\tif threat in ['bat', 'wumpus']:\n\t\t\tdel self.threats[room_number]\t\t\n\t\t\tif threat == 'wumpus':\n\t\t\t\tprint(\"Hurra, you killed the wumpus!\")\n\t\t\t\treturn -1\n\t\t\telif threat == 'bat':\n\t\t\t\tprint(\"You killed a bat.\")\n\t\telif threat in ['pit', None]:\n\t\t\tprint(\"This arrow is lost.\")\n\t\t\n\t\t\n\t\tif self.arrows < 1:\t\t\n\t\t\tprint(\"Your quiver is empty.\")\n\t\t\treturn -1\n\n\t\t\n\t\tif random.random() < 0.75:\n\t\t\t\n\t\t\tfor room_number, threat in self.threats.items():\n\t\t\t\tif threat == 'wumpus':\n\t\t\t\t\twumpus_pos = room_number\t\t\t\t\t\n\t\t\tnew_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys())))\n\t\t\tdel self.threats[room_number]\n\t\t\tself.threats[new_pos] = 'wumpus'\t\t\t\n\t\t\tif new_pos == self.player_pos: \n\t\t\t\tprint(\"Wumpus enters your room and eats you!\")\n\t\t\t\treturn -1\n\n\t\treturn self.player_pos\n\n\t\t\n\tdef gameloop(self):\n\n\t\tprint(\"HUNT THE WUMPUS\")\n\t\tprint(\"===============\")\n\t\tprint()\n\t\tself.populate_cave()\n\t\tself.enter_room(self.player_pos)\n\n\t\twhile 1:\n\n\t\t\t\n\t\t\t\n\t\t\t\n\n\t\t\tprint(\"You are in room {}.\".format(self.player_pos), end=\" \")\n\t\t\tprint(\"Tunnels lead to:  {0}  {1}  {2}\".format(*self.cave[self.player_pos]))\n\t\t\t\n\t\t\t\n\t\t\tinpt = self.get_players_input()\t\t\n\t\t\tprint()\t\t\t\t\t\t\t\t\n\t\t\tif inpt[0] == 'm':\t\t\t\t\t\n\t\t\t\ttarget = inpt[1] \n\t\t\t\tself.player_pos = self.enter_room(target)\n\t\t\telif inpt[0] == 's':\t\t\t\t\n\t\t\t\ttarget = inpt[1]\n\t\t\t\tself.player_pos = self.shoot_room(target)\n\t\t\telif inpt[0] == 'q':\t\t\t\t\n\t\t\t\tself.player_pos = -1\n\n\t\t\tif self.player_pos == -1:\t\t\t\n\t\t\t\tbreak\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\tprint()\n\t\tprint(\"Game over!\")\t\n\t\t\n\nif __name__ == '__main__':\t\t\t\t\t\t\n\t\n\t\n\t\n\t\n\n\t\n\n\tWG = WumpusGame()\n\tWG.gameloop()\n"}
{"id": 50999, "name": "Reverse the order of lines in a text file while preserving the contents of each line", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"runtime\"\n)\n\nfunc main() {\n    fileName1 := \"rodgers.txt\"\n    fileName2 := \"rodgers_reversed.txt\"\n    lineBreak := \"\\n\"\n    if runtime.GOOS == \"windows\" {\n        lineBreak = \"\\r\\n\"\n    }\n    \n    b, err := ioutil.ReadFile(fileName1)\n    if err != nil {\n        log.Fatal(err)\n    }\n    lines := bytes.Split(b, []byte(lineBreak))\n    \n    if len(lines[len(lines)-1]) == 0 {\n        lines = lines[:len(lines)-1]\n    }\n\n    \n    for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {\n        lines[i], lines[j] = lines[j], lines[i]\n    }\n    b = bytes.Join(lines, []byte(lineBreak))\n    if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil {\n        log.Fatal(err)\n    }\n    \n    b, err = ioutil.ReadFile(fileName2)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(b))\n}\n", "Python": "\n\nimport sys\n\nif len(sys.argv)!=2:\n    print(\"Usage : python \" + sys.argv[0] + \" <filename>\")\n    exit()\n\ndataFile = open(sys.argv[1],\"r\")\n\nfileData = dataFile.read().split('\\n')\n\ndataFile.close()\n\n[print(i) for i in fileData[::-1]]\n"}
{"id": 51000, "name": "Hourglass puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc minimum(a []int) int {\n    min := a[0]\n    for i := 1; i < len(a); i++ {\n        if a[i] < min {\n            min = a[i]\n        }\n    }\n    return min\n}\n\nfunc sum(a []int) int {\n    s := 0\n    for _, i := range a {\n        s = s + i\n    }\n    return s\n}\n\nfunc hourglassFlipper(hourglasses []int, target int) (int, []int) {\n    flippers := make([]int, len(hourglasses))\n    copy(flippers, hourglasses)\n    var series []int\n    for iter := 0; iter < 10000; iter++ {\n        n := minimum(flippers)\n        series = append(series, n)\n        for i := 0; i < len(flippers); i++ {\n            flippers[i] -= n\n        }\n        for i, flipper := range flippers {\n            if flipper == 0 {\n                flippers[i] = hourglasses[i]\n            }\n        }\n        for start := len(series) - 1; start >= 0; start-- {\n            if sum(series[start:]) == target {\n                return start, series\n            }\n        }\n    }\n    log.Fatal(\"Unable to find an answer within 10,000 iterations.\")\n    return 0, nil\n}\n\nfunc main() {\n    fmt.Print(\"Flip an hourglass every time it runs out of grains, \")\n    fmt.Println(\"and note the interval in time.\")\n    hgs := [][]int{{4, 7}, {5, 7, 31}}\n    ts := []int{9, 36}\n    for i := 0; i < len(hgs); i++ {\n        start, series := hourglassFlipper(hgs[i], ts[i])\n        end := len(series) - 1\n        fmt.Println(\"\\nSeries:\", series)\n        fmt.Printf(\"Use hourglasses from indices %d to %d (inclusive) to sum \", start, end)\n        fmt.Println(ts[i], \"using\", hgs[i])\n    }\n}\n", "Python": "def hourglass_puzzle():\n    t4 = 0\n    while t4 < 10_000:\n        t7_left = 7 - t4 % 7\n        if t7_left == 9 - 4:\n            break\n        t4 += 4\n    else:\n        print('Not found')\n        return \n    print(f)\n \nhourglass_puzzle()\n"}
{"id": 51001, "name": "Hourglass puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc minimum(a []int) int {\n    min := a[0]\n    for i := 1; i < len(a); i++ {\n        if a[i] < min {\n            min = a[i]\n        }\n    }\n    return min\n}\n\nfunc sum(a []int) int {\n    s := 0\n    for _, i := range a {\n        s = s + i\n    }\n    return s\n}\n\nfunc hourglassFlipper(hourglasses []int, target int) (int, []int) {\n    flippers := make([]int, len(hourglasses))\n    copy(flippers, hourglasses)\n    var series []int\n    for iter := 0; iter < 10000; iter++ {\n        n := minimum(flippers)\n        series = append(series, n)\n        for i := 0; i < len(flippers); i++ {\n            flippers[i] -= n\n        }\n        for i, flipper := range flippers {\n            if flipper == 0 {\n                flippers[i] = hourglasses[i]\n            }\n        }\n        for start := len(series) - 1; start >= 0; start-- {\n            if sum(series[start:]) == target {\n                return start, series\n            }\n        }\n    }\n    log.Fatal(\"Unable to find an answer within 10,000 iterations.\")\n    return 0, nil\n}\n\nfunc main() {\n    fmt.Print(\"Flip an hourglass every time it runs out of grains, \")\n    fmt.Println(\"and note the interval in time.\")\n    hgs := [][]int{{4, 7}, {5, 7, 31}}\n    ts := []int{9, 36}\n    for i := 0; i < len(hgs); i++ {\n        start, series := hourglassFlipper(hgs[i], ts[i])\n        end := len(series) - 1\n        fmt.Println(\"\\nSeries:\", series)\n        fmt.Printf(\"Use hourglasses from indices %d to %d (inclusive) to sum \", start, end)\n        fmt.Println(ts[i], \"using\", hgs[i])\n    }\n}\n", "Python": "def hourglass_puzzle():\n    t4 = 0\n    while t4 < 10_000:\n        t7_left = 7 - t4 % 7\n        if t7_left == 9 - 4:\n            break\n        t4 += 4\n    else:\n        print('Not found')\n        return \n    print(f)\n \nhourglass_puzzle()\n"}
{"id": 51002, "name": "Unique characters in each string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    strings := []string{\"1a3c52debeffd\", \"2b6178c97a938stf\", \"3ycxdb1fgxa2yz\"}\n    u := make(map[rune]int)\n    for _, s := range strings {\n        m := make(map[rune]int)\n        for _, c := range s {\n            m[c]++\n        }\n        for k, v := range m {\n            if v == 1 {\n                u[k]++\n            }\n        }\n    }\n    var chars []rune\n    for k, v := range u {\n        if v == 3 {\n            chars = append(chars, k)\n        }\n    }\n    sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] })\n    fmt.Println(string(chars))\n}\n", "Python": "LIST = [\"1a3c52debeffd\", \"2b6178c97a938stf\", \"3ycxdb1fgxa2yz\"]\n\nprint(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))\n"}
{"id": 51003, "name": "Fibonacci heap", "Go": "package fib\n\nimport \"fmt\"\n\ntype Value interface {\n    LT(Value) bool\n}\n\ntype Node struct {\n    value      Value\n    parent     *Node\n    child      *Node\n    prev, next *Node\n    rank       int\n    mark       bool\n}\n\nfunc (n Node) Value() Value { return n.value }\n\ntype Heap struct{ *Node }\n\n\nfunc MakeHeap() *Heap { return &Heap{} }\n\n\nfunc (h *Heap) Insert(v Value) *Node {\n    x := &Node{value: v}\n    if h.Node == nil {\n        x.next = x\n        x.prev = x\n        h.Node = x\n    } else {\n        meld1(h.Node, x)\n        if x.value.LT(h.value) {\n            h.Node = x\n        }\n    }\n    return x\n}\n\nfunc meld1(list, single *Node) {\n    list.prev.next = single\n    single.prev = list.prev\n    single.next = list\n    list.prev = single\n}\n\n\nfunc (h *Heap) Union(h2 *Heap) {\n    switch {\n    case h.Node == nil:\n        *h = *h2\n    case h2.Node != nil:\n        meld2(h.Node, h2.Node)\n        if h2.value.LT(h.value) {\n            *h = *h2\n        }\n    }\n    h2.Node = nil\n}\n\nfunc meld2(a, b *Node) {\n    a.prev.next = b\n    b.prev.next = a\n    a.prev, b.prev = b.prev, a.prev\n}\n\n\nfunc (h Heap) Minimum() (min Value, ok bool) {\n    if h.Node == nil {\n        return\n    }\n    return h.value, true\n}\n\n\nfunc (h *Heap) ExtractMin() (min Value, ok bool) {\n    if h.Node == nil {\n        return\n    }\n    min = h.value\n    roots := map[int]*Node{}\n    add := func(r *Node) {\n        r.prev = r\n        r.next = r\n        for {\n            x, ok := roots[r.rank]\n            if !ok {\n               break\n            }\n            delete(roots, r.rank)\n            if x.value.LT(r.value) {\n                r, x = x, r\n            }\n            x.parent = r\n            x.mark = false\n            if r.child == nil {\n                x.next = x\n                x.prev = x\n                r.child = x\n            } else {\n                meld1(r.child, x)\n            }\n            r.rank++\n        }\n        roots[r.rank] = r\n    }\n    for r := h.next; r != h.Node; {\n        n := r.next\n        add(r)\n        r = n\n    }\n    if c := h.child; c != nil {\n        c.parent = nil\n        r := c.next\n        add(c)\n        for r != c {\n            n := r.next\n            r.parent = nil\n            add(r)\n            r = n\n        }\n    }\n    if len(roots) == 0 {\n        h.Node = nil\n        return min, true\n    }\n    var mv *Node\n    var d int\n    for d, mv = range roots {\n        break\n    }\n    delete(roots, d)\n    mv.next = mv\n    mv.prev = mv\n    for _, r := range roots {\n        r.prev = mv\n        r.next = mv.next\n        mv.next.prev = r\n        mv.next = r\n        if r.value.LT(mv.value) {\n            mv = r\n        }\n    }\n    h.Node = mv\n    return min, true\n}\n\n\nfunc (h *Heap) DecreaseKey(n *Node, v Value) error {\n    if n.value.LT(v) {\n        return fmt.Errorf(\"DecreaseKey new value greater than existing value\")\n    }\n    n.value = v\n    if n == h.Node {\n        return nil\n    }\n    p := n.parent\n    if p == nil {\n        if v.LT(h.value) {\n            h.Node = n\n        }\n        return nil\n    }\n    h.cutAndMeld(n)\n    return nil\n}\n\nfunc (h Heap) cut(x *Node) {\n    p := x.parent\n    p.rank--\n    if p.rank == 0 {\n        p.child = nil\n    } else {\n        p.child = x.next\n        x.prev.next = x.next\n        x.next.prev = x.prev\n    }\n    if p.parent == nil {\n        return\n    }\n    if !p.mark {\n        p.mark = true\n        return\n    }\n    h.cutAndMeld(p)\n}\n\nfunc (h Heap) cutAndMeld(x *Node) {\n    h.cut(x)\n    x.parent = nil\n    meld1(h.Node, x)\n}\n\n\nfunc (h *Heap) Delete(n *Node) {\n    p := n.parent\n    if p == nil {\n        if n == h.Node {\n            h.ExtractMin()\n            return\n        }\n        n.prev.next = n.next\n        n.next.prev = n.prev\n    } else {\n        h.cut(n)\n    }\n    c := n.child\n    if c == nil {\n        return\n    }\n    for {\n        c.parent = nil\n        c = c.next\n        if c == n.child {\n            break\n        }\n    }\n    meld2(h.Node, c)\n}\n\n\nfunc (h Heap) Vis() {\n    if h.Node == nil {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(*Node, string)\n    f = func(n *Node, pre string) {\n        pc := \"│ \"\n        for x := n; ; x = x.next {\n            if x.next != n {\n                fmt.Print(pre, \"├─\")\n            } else {\n                fmt.Print(pre, \"└─\")\n                pc = \"  \"\n            }\n            if x.child == nil {\n                fmt.Println(\"╴\", x.value)\n            } else {\n                fmt.Println(\"┐\", x.value)\n                f(x.child, pre+pc)\n            }\n            if x.next == n {\n                break\n            }\n        }\n    }\n    f(h.Node, \"\")\n}\n", "Python": "class FibonacciHeap:\n    \n    \n    class Node:\n        def __init__(self, data):\n            self.data = data\n            self.parent = self.child = self.left = self.right = None\n            self.degree = 0\n            self.mark = False\n            \n    \n    def iterate(self, head):\n        node = stop = head\n        flag = False\n        while True:\n            if node == stop and flag is True:\n                break\n            elif node == stop:\n                flag = True\n            yield node\n            node = node.right\n    \n    \n    root_list, min_node = None, None\n    \n    \n    total_nodes = 0\n    \n    \n    def find_min(self):\n        return self.min_node\n         \n    \n    \n    def extract_min(self):\n        z = self.min_node\n        if z is not None:\n            if z.child is not None:\n                \n                children = [x for x in self.iterate(z.child)]\n                for i in xrange(0, len(children)):\n                    self.merge_with_root_list(children[i])\n                    children[i].parent = None\n            self.remove_from_root_list(z)\n            \n            if z == z.right:\n                self.min_node = self.root_list = None\n            else:\n                self.min_node = z.right\n                self.consolidate()\n            self.total_nodes -= 1\n        return z\n                    \n    \n    def insert(self, data):\n        n = self.Node(data)\n        n.left = n.right = n\n        self.merge_with_root_list(n)\n        if self.min_node is None or n.data < self.min_node.data:\n            self.min_node = n\n        self.total_nodes += 1\n        \n    \n    def decrease_key(self, x, k):\n        if k > x.data:\n            return None\n        x.data = k\n        y = x.parent\n        if y is not None and x.data < y.data:\n            self.cut(x, y)\n            self.cascading_cut(y)\n        if x.data < self.min_node.data:\n            self.min_node = x\n            \n    \n    \n    \n    def merge(self, h2):\n        H = FibonacciHeap()\n        H.root_list, H.min_node = self.root_list, self.min_node\n        \n        last = h2.root_list.left\n        h2.root_list.left = H.root_list.left\n        H.root_list.left.right = h2.root_list\n        H.root_list.left = last\n        H.root_list.left.right = H.root_list\n        \n        if h2.min_node.data < H.min_node.data:\n            H.min_node = h2.min_node\n        \n        H.total_nodes = self.total_nodes + h2.total_nodes\n        return H\n        \n    \n    \n    def cut(self, x, y):\n        self.remove_from_child_list(y, x)\n        y.degree -= 1\n        self.merge_with_root_list(x)\n        x.parent = None\n        x.mark = False\n    \n    \n    def cascading_cut(self, y):\n        z = y.parent\n        if z is not None:\n            if y.mark is False:\n                y.mark = True\n            else:\n                self.cut(y, z)\n                self.cascading_cut(z)\n    \n    \n    \n    def consolidate(self):\n        A = [None] * self.total_nodes\n        nodes = [w for w in self.iterate(self.root_list)]\n        for w in xrange(0, len(nodes)):\n            x = nodes[w]\n            d = x.degree\n            while A[d] != None:\n                y = A[d] \n                if x.data > y.data:\n                    temp = x\n                    x, y = y, temp\n                self.heap_link(y, x)\n                A[d] = None\n                d += 1\n            A[d] = x\n        \n        \n        \n        for i in xrange(0, len(A)):\n            if A[i] is not None:\n                if A[i].data < self.min_node.data:\n                    self.min_node = A[i]\n        \n    \n    \n    def heap_link(self, y, x):\n        self.remove_from_root_list(y)\n        y.left = y.right = y\n        self.merge_with_child_list(x, y)\n        x.degree += 1\n        y.parent = x\n        y.mark = False\n        \n    \n    def merge_with_root_list(self, node):\n        if self.root_list is None:\n            self.root_list = node\n        else:\n            node.right = self.root_list.right\n            node.left = self.root_list\n            self.root_list.right.left = node\n            self.root_list.right = node\n            \n    \n    def merge_with_child_list(self, parent, node):\n        if parent.child is None:\n            parent.child = node\n        else:\n            node.right = parent.child.right\n            node.left = parent.child\n            parent.child.right.left = node\n            parent.child.right = node\n            \n    \n    def remove_from_root_list(self, node):\n        if node == self.root_list:\n            self.root_list = node.right\n        node.left.right = node.right\n        node.right.left = node.left\n        \n    \n    def remove_from_child_list(self, parent, node):\n        if parent.child == parent.child.right:\n            parent.child = None\n        elif parent.child == node:\n            parent.child = node.right\n            node.right.parent = parent\n        node.left.right = node.right\n        node.right.left = node.left\n"}
{"id": 51004, "name": "Mayan calendar", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar sacred = strings.Fields(\"Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw\")\n\nvar civil = strings.Fields(\"Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’\")\n\nvar (\n    date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC)\n    date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC)\n)\n\nfunc tzolkin(date time.Time) (int, string) {\n    diff := int(date.Sub(date1).Hours()) / 24\n    rem := diff % 13\n    if rem < 0 {\n        rem = 13 + rem\n    }\n    var num int\n    if rem <= 9 {\n        num = rem + 4\n    } else {\n        num = rem - 9\n    }\n    rem = diff % 20\n    if rem <= 0 {\n        rem = 20 + rem\n    }\n    return num, sacred[rem-1]\n}\n\nfunc haab(date time.Time) (string, string) {\n    diff := int(date.Sub(date2).Hours()) / 24\n    rem := diff % 365\n    if rem < 0 {\n        rem = 365 + rem\n    }\n    month := civil[(rem+1)/20]\n    last := 20\n    if month == \"Wayeb’\" {\n        last = 5\n    }\n    d := rem%20 + 1\n    if d < last {\n        return strconv.Itoa(d), month\n    }\n    return \"Chum\", month\n}\n\nfunc longCount(date time.Time) string {\n    diff := int(date.Sub(date1).Hours()) / 24\n    diff += 13 * 400 * 360\n    baktun := diff / (400 * 360)\n    diff %= 400 * 360\n    katun := diff / (20 * 360)\n    diff %= 20 * 360\n    tun := diff / 360\n    diff %= 360\n    winal := diff / 20\n    kin := diff % 20\n    return fmt.Sprintf(\"%d.%d.%d.%d.%d\", baktun, katun, tun, winal, kin)    \n}\n\nfunc lord(date time.Time) string {\n    diff := int(date.Sub(date1).Hours()) / 24\n    rem := diff % 9\n    if rem <= 0 {\n        rem = 9 + rem\n    }\n    return fmt.Sprintf(\"G%d\", rem)\n}\n\nfunc main() {\n    const shortForm = \"2006-01-02\"\n    dates := []string{\n        \"2004-06-19\",\n        \"2012-12-18\",\n        \"2012-12-21\",\n        \"2019-01-19\",\n        \"2019-03-27\",\n        \"2020-02-29\",\n        \"2020-03-01\",\n        \"2071-05-16\",\n    }\n    fmt.Println(\" Gregorian   Tzolk’in        Haab’              Long           Lord of\")\n    fmt.Println(\"   Date       # Name       Day Month            Count         the Night\")\n    fmt.Println(\"----------   --------    -------------        --------------  ---------\")\n    for _, dt := range dates {\n        date, _ := time.Parse(shortForm, dt)\n        n, s := tzolkin(date)\n        d, m := haab(date)\n        lc := longCount(date)\n        l := lord(date)\n        fmt.Printf(\"%s   %2d %-8s %4s %-9s       %-14s     %s\\n\", dt, n, s, d, m, lc, l)\n    }\n}\n", "Python": "import datetime\n\n\ndef g2m(date, gtm_correlation=True):\n    \n\n    \n\n    correlation = 584283 if gtm_correlation else 584285\n\n    long_count_days = [144000, 7200, 360, 20, 1]\n\n    tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen',\n                      'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw']  \n\n    haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak',\n                   'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’']  \n\n    gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal()\n    julian_days = gregorian_days + 1721425\n\n    \n\n    long_date = list()\n    remainder = julian_days - correlation\n\n    for days in long_count_days:\n\n        result, remainder = divmod(remainder, days)\n        long_date.append(int(result))\n\n    long_date = '.'.join(['{:02d}'.format(d) for d in long_date])\n\n    \n\n    tzolkin_month = (julian_days + 16) % 20\n    tzolkin_day = ((julian_days + 5) % 13) + 1\n\n    haab_month = int(((julian_days + 65) % 365) / 20)\n    haab_day = ((julian_days + 65) % 365) % 20\n    haab_day = haab_day if haab_day else 'Chum'\n\n    lord_number = (julian_days - correlation) % 9\n    lord_number = lord_number if lord_number else 9\n\n    round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}'\n\n    return long_date, round_date\n\nif __name__ == '__main__':\n\n    dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01']\n\n    for date in dates:\n\n        long, round = g2m(date)\n        print(date, long, round)\n"}
{"id": 51005, "name": "Smallest numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    var res []int64\n    for n := 0; n <= 50; n++ {\n        ns := strconv.Itoa(n)\n        k := int64(1)\n        for {\n            bk := big.NewInt(k)\n            s := bk.Exp(bk, bk, nil).String()\n            if strings.Contains(s, ns) {\n                res = append(res, k)\n                break\n            }\n            k++\n        }\n    }\n    fmt.Println(\"The smallest positive integers K where K ^ K contains N (0..50) are:\")\n    for i, n := range res {\n        fmt.Printf(\"%2d \", n)\n        if (i+1)%17 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "\n\nimport sys\n\nif len(sys.argv)!=2:\n    print(\"Usage : python \" + sys.argv[0] + \" <whole number>\")\n    exit()\n\nnumLimit = int(sys.argv[1])\n\nresultSet = {}\n\nbase = 1\n\nwhile len(resultSet)!=numLimit:\n    result = base**base\n\n    for i in range(0,numLimit):\n        if str(i) in str(result) and i not in resultSet:\n            resultSet[i] = base\n\n    base+=1\n\n[print(resultSet[i], end=' ') for i in sorted(resultSet)]\n"}
{"id": 51006, "name": "Safe and Sophie Germain primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var sgp []int\n    p := 2\n    count := 0\n    for count < 50 {\n        if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) {\n            sgp = append(sgp, p)\n            count++\n        }\n        if p != 2 {\n            p = p + 2\n        } else {\n            p = 3\n        }\n    }\n    fmt.Println(\"The first 50 Sophie Germain primes are:\")\n    for i := 0; i < len(sgp); i++ {\n        fmt.Printf(\"%5s \", rcu.Commatize(sgp[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "print(\"working...\")\nrow = 0\nlimit = 1500\nSophie = []\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\nfor n in range(2,limit):\n\tp = 2*n + 1\n\tif isPrime(n) and isPrime(p):\n\t\tSophie.append(n)\n\nprint(\"Found \",end = \"\")\nprint(len(Sophie),end = \"\")\nprint(\" Safe and Sophie primes.\")\n\nprint(Sophie)\nprint(\"done...\")\n"}
{"id": 51007, "name": "Safe and Sophie Germain primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var sgp []int\n    p := 2\n    count := 0\n    for count < 50 {\n        if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) {\n            sgp = append(sgp, p)\n            count++\n        }\n        if p != 2 {\n            p = p + 2\n        } else {\n            p = 3\n        }\n    }\n    fmt.Println(\"The first 50 Sophie Germain primes are:\")\n    for i := 0; i < len(sgp); i++ {\n        fmt.Printf(\"%5s \", rcu.Commatize(sgp[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "print(\"working...\")\nrow = 0\nlimit = 1500\nSophie = []\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\nfor n in range(2,limit):\n\tp = 2*n + 1\n\tif isPrime(n) and isPrime(p):\n\t\tSophie.append(n)\n\nprint(\"Found \",end = \"\")\nprint(len(Sophie),end = \"\")\nprint(\" Safe and Sophie primes.\")\n\nprint(Sophie)\nprint(\"done...\")\n"}
{"id": 51008, "name": "Checksumcolor", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"log\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n)\n\ntype Color struct{ r, g, b int }\n\ntype ColorEx struct {\n    color Color\n    code  string\n}\n\nvar colors = []ColorEx{\n    {Color{15, 0, 0}, \"31\"},\n    {Color{0, 15, 0}, \"32\"},\n    {Color{15, 15, 0}, \"33\"},\n    {Color{0, 0, 15}, \"34\"},\n    {Color{15, 0, 15}, \"35\"},\n    {Color{0, 15, 15}, \"36\"},\n}\n\nfunc squareDist(c1, c2 Color) int {\n    xd := c2.r - c1.r\n    yd := c2.g - c1.g\n    zd := c2.b - c1.b\n    return xd*xd + yd*yd + zd*zd\n}\n\nfunc printColor(s string) {\n    n := len(s)\n    k := 0\n    for i := 0; i < n/3; i++ {\n        j := i * 3\n        c1 := s[j]\n        c2 := s[j+1]\n        c3 := s[j+2]\n        k = j + 3\n        r, err := strconv.ParseInt(fmt.Sprintf(\"0x%c\", c1), 0, 64)\n        check(err)\n        g, err := strconv.ParseInt(fmt.Sprintf(\"0x%c\", c2), 0, 64)\n        check(err)\n        b, err := strconv.ParseInt(fmt.Sprintf(\"0x%c\", c3), 0, 64)\n        check(err)\n        rgb := Color{int(r), int(g), int(b)}\n        m := 676\n        colorCode := \"\"\n        for _, cex := range colors {\n            sqd := squareDist(cex.color, rgb)\n            if sqd < m {\n                colorCode = cex.code\n                m = sqd\n            }\n        }\n        fmt.Printf(\"\\033[%s;1m%c%c%c\\033[00m\", colorCode, c1, c2, c3)\n    }\n    for j := k; j < n; j++ {\n        c := s[j]\n        fmt.Printf(\"\\033[0;1m%c\\033[00m\", c)\n    }\n}\n\nvar (\n    r       = regexp.MustCompile(\"^([A-Fa-f0-9]+)([ \\t]+.+)$\")\n    scanner = bufio.NewScanner(os.Stdin)\n    err     error\n)\n\nfunc colorChecksum() {\n    for scanner.Scan() {\n        line := scanner.Text()\n        if r.MatchString(line) {\n            submatches := r.FindStringSubmatch(line)\n            s1 := submatches[1]\n            s2 := submatches[2]\n            printColor(s1)\n            fmt.Println(s2)\n        } else {\n            fmt.Println(line)\n        }\n    }\n    check(scanner.Err())\n}\n\nfunc cat() {\n    for scanner.Scan() {\n        line := scanner.Text()\n        fmt.Println(line)\n    }\n    check(scanner.Err())\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdout.Fd())) {\n        colorChecksum()\n    } else {\n        cat()\n    }\n}\n", "Python": "\n\n\nfrom __future__ import unicode_literals\n\nimport argparse\nimport fileinput\nimport os\nimport sys\n\nfrom functools import partial\nfrom itertools import count\nfrom itertools import takewhile\n\n\nANSI_RESET = \"\\u001b[0m\"\n\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nYELLOW = (255, 255, 0)\nBLUE = (0, 0, 255)\nMAGENTA = (255, 0, 255)\nCYAN = (0, 255, 255)\n\nANSI_PALETTE = {\n    RED: \"\\u001b[31m\",\n    GREEN: \"\\u001b[32m\",\n    YELLOW: \"\\u001b[33m\",\n    BLUE: \"\\u001b[34m\",\n    MAGENTA: \"\\u001b[35m\",\n    CYAN: \"\\u001b[36m\",\n}\n\n\n\n_8BIT_PALETTE = {\n    (0xAF, 0x00, 0x00): \"\\u001b[38;5;124m\",\n    (0xAF, 0x00, 0x5F): \"\\u001b[38;5;125m\",\n    (0xAF, 0x00, 0x87): \"\\u001b[38;5;126m\",\n    (0xAF, 0x00, 0xAF): \"\\u001b[38;5;127m\",\n    (0xAF, 0x00, 0xD7): \"\\u001b[38;5;128m\",\n    (0xAF, 0x00, 0xFF): \"\\u001b[38;5;129m\",\n    (0xAF, 0x5F, 0x00): \"\\u001b[38;5;130m\",\n    (0xAF, 0x5F, 0x5F): \"\\u001b[38;5;131m\",\n    (0xAF, 0x5F, 0x87): \"\\u001b[38;5;132m\",\n    (0xAF, 0x5F, 0xAF): \"\\u001b[38;5;133m\",\n    (0xAF, 0x5F, 0xD7): \"\\u001b[38;5;134m\",\n    (0xAF, 0x5F, 0xFF): \"\\u001b[38;5;135m\",\n    (0xAF, 0x87, 0x00): \"\\u001b[38;5;136m\",\n    (0xAF, 0x87, 0x5F): \"\\u001b[38;5;137m\",\n    (0xAF, 0x87, 0x87): \"\\u001b[38;5;138m\",\n    (0xAF, 0x87, 0xAF): \"\\u001b[38;5;139m\",\n    (0xAF, 0x87, 0xD7): \"\\u001b[38;5;140m\",\n    (0xAF, 0x87, 0xFF): \"\\u001b[38;5;141m\",\n    (0xAF, 0xAF, 0x00): \"\\u001b[38;5;142m\",\n    (0xAF, 0xAF, 0x5F): \"\\u001b[38;5;143m\",\n    (0xAF, 0xAF, 0x87): \"\\u001b[38;5;144m\",\n    (0xAF, 0xAF, 0xAF): \"\\u001b[38;5;145m\",\n    (0xAF, 0xAF, 0xD7): \"\\u001b[38;5;146m\",\n    (0xAF, 0xAF, 0xFF): \"\\u001b[38;5;147m\",\n    (0xAF, 0xD7, 0x00): \"\\u001b[38;5;148m\",\n    (0xAF, 0xD7, 0x5F): \"\\u001b[38;5;149m\",\n    (0xAF, 0xD7, 0x87): \"\\u001b[38;5;150m\",\n    (0xAF, 0xD7, 0xAF): \"\\u001b[38;5;151m\",\n    (0xAF, 0xD7, 0xD7): \"\\u001b[38;5;152m\",\n    (0xAF, 0xD7, 0xFF): \"\\u001b[38;5;153m\",\n    (0xAF, 0xFF, 0x00): \"\\u001b[38;5;154m\",\n    (0xAF, 0xFF, 0x5F): \"\\u001b[38;5;155m\",\n    (0xAF, 0xFF, 0x87): \"\\u001b[38;5;156m\",\n    (0xAF, 0xFF, 0xAF): \"\\u001b[38;5;157m\",\n    (0xAF, 0xFF, 0xD7): \"\\u001b[38;5;158m\",\n    (0xAF, 0xFF, 0xFF): \"\\u001b[38;5;159m\",\n}\n\n\ndef error(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(os.linesep)\n    sys.exit(1)\n\n\ndef rgb(group):\n    \n    nibbles_per_channel = len(group) // 3\n    max_val = 16 ** nibbles_per_channel - 1\n    nibbles = chunked(group, nibbles_per_channel)\n\n    \n    return tuple((int(n, 16) * 255) // max_val for n in nibbles)\n\n\ndef distance(color, other):\n    \n    return sum((o - s) ** 2 for s, o in zip(color, other))\n\n\ndef chunked(seq, n):\n    \n    return takewhile(len, (seq[i : i + n] for i in count(0, n)))\n\n\ndef escape(group, palette):\n    \n    key = partial(distance, other=rgb(group.ljust(3, \"0\")))\n    ansi_color = min(palette, key=key)\n    return \"\".join([palette[ansi_color], group, ANSI_RESET])\n\n\ndef colorize(line, group_size=3, palette=ANSI_PALETTE):\n    \n    checksum, filename = line.split(None, 1)\n    escaped = [escape(group, palette) for group in chunked(checksum, group_size)]\n    sys.stdout.write(\"  \".join([\"\".join(escaped), filename]))\n\n\ndef html_colorize(checksum, group_size=3, palette=ANSI_PALETTE):\n    \n\n    def span(group):\n        key = partial(distance, other=rgb(group.ljust(3, \"0\")))\n        ansi_color = min(palette, key=key)\n        int_val = int.from_bytes(ansi_color, byteorder=\"big\")\n        hex_val = hex(int_val)[2:].rjust(6, \"0\")\n        return '<span style=\"color:\n\n    checksum, filename = line.split(None, 1)\n    escaped = [span(group) for group in chunked(checksum, group_size)]\n    sys.stdout.write(\"  \".join([\"\".join(escaped), filename]))\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description=\"Color checksum.\")\n\n    parser.add_argument(\n        \"-n\",\n        type=int,\n        default=3,\n        help=\"Color the checksum in groups of size N. Defaults to 3.\",\n    )\n\n    parser.add_argument(\n        \"-e\",\n        \"--extended-palette\",\n        action=\"store_true\",\n        help=\"Use the extended 8-bit palette. Defaults to False.\",\n    )\n\n    parser.add_argument(\n        \"--html\",\n        action=\"store_true\",\n        help=\"Output checksum groups wrapped with 'span' tags instead of ANSI escape sequences.\",\n    )\n\n    parser.add_argument(\"files\", nargs=\"*\", default=\"-\", metavar=\"FILE\")\n\n    args = parser.parse_args()\n\n    if sys.stdout.isatty():\n\n        palette = ANSI_PALETTE\n        if args.extended_palette:\n            palette = _8BIT_PALETTE\n\n        colorize_func = colorize\n        if args.html:\n            colorize_func = html_colorize\n\n        for line in fileinput.input(files=args.files):\n            colorize_func(line, group_size=args.n, palette=palette)\n    else:\n        \n        for line in fileinput.input(files=args.files):\n            sys.stdout.write(line)\n"}
{"id": 51009, "name": "URL shortener", "Go": "\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"net/http\"\n    \"time\"\n)\n\nconst (\n    chars = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    host  = \"localhost:8000\"\n)\n\ntype database map[string]string\n\ntype shortener struct {\n    Long string `json:\"long\"`\n}\n\nfunc (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n    switch req.Method {\n    case http.MethodPost: \n        body, err := ioutil.ReadAll(req.Body)\n        if err != nil {\n            w.WriteHeader(http.StatusBadRequest) \n            return\n        }\n        var sh shortener\n        err = json.Unmarshal(body, &sh)\n        if err != nil {\n            w.WriteHeader(http.StatusUnprocessableEntity) \n            return\n        }\n        short := generateKey(8)\n        db[short] = sh.Long\n        fmt.Fprintf(w, \"The shortened URL: http:\n    case http.MethodGet: \n        path := req.URL.Path[1:]\n        if v, ok := db[path]; ok {\n            http.Redirect(w, req, v, http.StatusFound) \n        } else {\n            w.WriteHeader(http.StatusNotFound) \n            fmt.Fprintf(w, \"No such shortened url: http:\n        }\n    default:\n        w.WriteHeader(http.StatusNotFound) \n        fmt.Fprintf(w, \"Unsupprted method: %s\\n\", req.Method)\n    }\n}\n\nfunc generateKey(size int) string {\n    key := make([]byte, size)\n    le := len(chars)\n    for i := 0; i < size; i++ {\n        key[i] = chars[rand.Intn(le)]\n    }\n    return string(key)\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    db := make(database)\n    log.Fatal(http.ListenAndServe(host, db))\n}\n", "Python": "\n\nimport sqlite3\nimport string\nimport random\n\nfrom http import HTTPStatus\n\nfrom flask import Flask\nfrom flask import Blueprint\nfrom flask import abort\nfrom flask import current_app\nfrom flask import g\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import request\nfrom flask import url_for\n\n\nCHARS = frozenset(string.ascii_letters + string.digits)\nMIN_URL_SIZE = 8\nRANDOM_ATTEMPTS = 3\n\n\ndef create_app(*, db=None, server_name=None) -> Flask:\n    app = Flask(__name__)\n    app.config.from_mapping(\n        DATABASE=db or \"shorten.sqlite\",\n        SERVER_NAME=server_name,\n    )\n\n    with app.app_context():\n        init_db()\n\n    app.teardown_appcontext(close_db)\n    app.register_blueprint(shortener)\n\n    return app\n\n\ndef get_db():\n    if \"db\" not in g:\n        g.db = sqlite3.connect(current_app.config[\"DATABASE\"])\n        g.db.row_factory = sqlite3.Row\n\n    return g.db\n\n\ndef close_db(_):\n    db = g.pop(\"db\", None)\n\n    if db is not None:\n        db.close()\n\n\ndef init_db():\n    db = get_db()\n\n    with db:\n        db.execute(\n            \"CREATE TABLE IF NOT EXISTS shorten (\"\n            \"url TEXT PRIMARY KEY, \"\n            \"short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)\"\n        )\n\n\nshortener = Blueprint(\"shorten\", \"short\")\n\n\ndef random_short(size=MIN_URL_SIZE):\n    \n    return \"\".join(random.sample(CHARS, size))\n\n\n@shortener.errorhandler(HTTPStatus.NOT_FOUND)\ndef short_url_not_found(_):\n    return \"short url not found\", HTTPStatus.NOT_FOUND\n\n\n@shortener.route(\"/<path:key>\", methods=(\"GET\",))\ndef short(key):\n    db = get_db()\n\n    cursor = db.execute(\"SELECT url FROM shorten WHERE short = ?\", (key,))\n    row = cursor.fetchone()\n\n    if row is None:\n        abort(HTTPStatus.NOT_FOUND)\n\n    \n    return redirect(row[\"url\"], code=HTTPStatus.FOUND)\n\n\nclass URLExistsError(Exception):\n    \n\n\nclass ShortCollisionError(Exception):\n    \n\n\ndef _insert_short(long_url, short):\n    \n    db = get_db()\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE url = ?\", (long_url,)).fetchone()\n        is not None\n    ):\n        raise URLExistsError(long_url)\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE short = ?\", (short,)).fetchone()\n        is not None\n    ):\n        raise ShortCollisionError(short)\n\n    with db:\n        db.execute(\"INSERT INTO shorten VALUES (?, ?)\", (long_url, short))\n\n\ndef make_short(long_url):\n    \n    size = MIN_URL_SIZE\n    attempts = 1\n    short = random_short(size=size)\n\n    while True:\n        try:\n            _insert_short(long_url, short)\n        except ShortCollisionError:\n            \n            if not attempts % RANDOM_ATTEMPTS:\n                size += 1\n\n            attempts += 1\n            short = random_short(size=size)\n        else:\n            break\n\n    return short\n\n\n@shortener.route(\"/\", methods=(\"POST\",))\ndef shorten():\n    data = request.get_json()\n\n    if data is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    long_url = data.get(\"long\")\n\n    if long_url is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    db = get_db()\n\n    \n    cursor = db.execute(\"SELECT short FROM shorten WHERE url = ?\", (long_url,))\n    row = cursor.fetchone()\n\n    if row is not None:\n        short_url = url_for(\"shorten.short\", _external=True, key=row[\"short\"])\n        status_code = HTTPStatus.OK\n    else:\n        short_url = url_for(\"shorten.short\", _external=True, key=make_short(long_url))\n        status_code = HTTPStatus.CREATED\n\n    mimetype = request.accept_mimetypes.best_match(\n        matches=[\"text/plain\", \"application/json\"], default=\"text/plain\"\n    )\n\n    if mimetype == \"application/json\":\n        return jsonify(long=long_url, short=short_url), status_code\n    else:\n        return short_url, status_code\n\n\nif __name__ == \"__main__\":\n    \n    app = create_app()\n    app.env = \"development\"\n    app.run(debug=True)\n"}
{"id": 51010, "name": "URL shortener", "Go": "\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"net/http\"\n    \"time\"\n)\n\nconst (\n    chars = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    host  = \"localhost:8000\"\n)\n\ntype database map[string]string\n\ntype shortener struct {\n    Long string `json:\"long\"`\n}\n\nfunc (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n    switch req.Method {\n    case http.MethodPost: \n        body, err := ioutil.ReadAll(req.Body)\n        if err != nil {\n            w.WriteHeader(http.StatusBadRequest) \n            return\n        }\n        var sh shortener\n        err = json.Unmarshal(body, &sh)\n        if err != nil {\n            w.WriteHeader(http.StatusUnprocessableEntity) \n            return\n        }\n        short := generateKey(8)\n        db[short] = sh.Long\n        fmt.Fprintf(w, \"The shortened URL: http:\n    case http.MethodGet: \n        path := req.URL.Path[1:]\n        if v, ok := db[path]; ok {\n            http.Redirect(w, req, v, http.StatusFound) \n        } else {\n            w.WriteHeader(http.StatusNotFound) \n            fmt.Fprintf(w, \"No such shortened url: http:\n        }\n    default:\n        w.WriteHeader(http.StatusNotFound) \n        fmt.Fprintf(w, \"Unsupprted method: %s\\n\", req.Method)\n    }\n}\n\nfunc generateKey(size int) string {\n    key := make([]byte, size)\n    le := len(chars)\n    for i := 0; i < size; i++ {\n        key[i] = chars[rand.Intn(le)]\n    }\n    return string(key)\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    db := make(database)\n    log.Fatal(http.ListenAndServe(host, db))\n}\n", "Python": "\n\nimport sqlite3\nimport string\nimport random\n\nfrom http import HTTPStatus\n\nfrom flask import Flask\nfrom flask import Blueprint\nfrom flask import abort\nfrom flask import current_app\nfrom flask import g\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import request\nfrom flask import url_for\n\n\nCHARS = frozenset(string.ascii_letters + string.digits)\nMIN_URL_SIZE = 8\nRANDOM_ATTEMPTS = 3\n\n\ndef create_app(*, db=None, server_name=None) -> Flask:\n    app = Flask(__name__)\n    app.config.from_mapping(\n        DATABASE=db or \"shorten.sqlite\",\n        SERVER_NAME=server_name,\n    )\n\n    with app.app_context():\n        init_db()\n\n    app.teardown_appcontext(close_db)\n    app.register_blueprint(shortener)\n\n    return app\n\n\ndef get_db():\n    if \"db\" not in g:\n        g.db = sqlite3.connect(current_app.config[\"DATABASE\"])\n        g.db.row_factory = sqlite3.Row\n\n    return g.db\n\n\ndef close_db(_):\n    db = g.pop(\"db\", None)\n\n    if db is not None:\n        db.close()\n\n\ndef init_db():\n    db = get_db()\n\n    with db:\n        db.execute(\n            \"CREATE TABLE IF NOT EXISTS shorten (\"\n            \"url TEXT PRIMARY KEY, \"\n            \"short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)\"\n        )\n\n\nshortener = Blueprint(\"shorten\", \"short\")\n\n\ndef random_short(size=MIN_URL_SIZE):\n    \n    return \"\".join(random.sample(CHARS, size))\n\n\n@shortener.errorhandler(HTTPStatus.NOT_FOUND)\ndef short_url_not_found(_):\n    return \"short url not found\", HTTPStatus.NOT_FOUND\n\n\n@shortener.route(\"/<path:key>\", methods=(\"GET\",))\ndef short(key):\n    db = get_db()\n\n    cursor = db.execute(\"SELECT url FROM shorten WHERE short = ?\", (key,))\n    row = cursor.fetchone()\n\n    if row is None:\n        abort(HTTPStatus.NOT_FOUND)\n\n    \n    return redirect(row[\"url\"], code=HTTPStatus.FOUND)\n\n\nclass URLExistsError(Exception):\n    \n\n\nclass ShortCollisionError(Exception):\n    \n\n\ndef _insert_short(long_url, short):\n    \n    db = get_db()\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE url = ?\", (long_url,)).fetchone()\n        is not None\n    ):\n        raise URLExistsError(long_url)\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE short = ?\", (short,)).fetchone()\n        is not None\n    ):\n        raise ShortCollisionError(short)\n\n    with db:\n        db.execute(\"INSERT INTO shorten VALUES (?, ?)\", (long_url, short))\n\n\ndef make_short(long_url):\n    \n    size = MIN_URL_SIZE\n    attempts = 1\n    short = random_short(size=size)\n\n    while True:\n        try:\n            _insert_short(long_url, short)\n        except ShortCollisionError:\n            \n            if not attempts % RANDOM_ATTEMPTS:\n                size += 1\n\n            attempts += 1\n            short = random_short(size=size)\n        else:\n            break\n\n    return short\n\n\n@shortener.route(\"/\", methods=(\"POST\",))\ndef shorten():\n    data = request.get_json()\n\n    if data is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    long_url = data.get(\"long\")\n\n    if long_url is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    db = get_db()\n\n    \n    cursor = db.execute(\"SELECT short FROM shorten WHERE url = ?\", (long_url,))\n    row = cursor.fetchone()\n\n    if row is not None:\n        short_url = url_for(\"shorten.short\", _external=True, key=row[\"short\"])\n        status_code = HTTPStatus.OK\n    else:\n        short_url = url_for(\"shorten.short\", _external=True, key=make_short(long_url))\n        status_code = HTTPStatus.CREATED\n\n    mimetype = request.accept_mimetypes.best_match(\n        matches=[\"text/plain\", \"application/json\"], default=\"text/plain\"\n    )\n\n    if mimetype == \"application/json\":\n        return jsonify(long=long_url, short=short_url), status_code\n    else:\n        return short_url, status_code\n\n\nif __name__ == \"__main__\":\n    \n    app = create_app()\n    app.env = \"development\"\n    app.run(debug=True)\n"}
{"id": 51011, "name": "Hexapawn", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\nconst (\n\tRows = 3\n\tCols = 3\n)\n\nvar vlog *log.Logger\n\nfunc main() {\n\tverbose := flag.Bool(\"v\", false, \"verbose\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tlogOutput := ioutil.Discard\n\tif *verbose {\n\t\tlogOutput = os.Stderr\n\t}\n\tvlog = log.New(logOutput, \"hexapawn: \", 0)\n\n\trand.Seed(time.Now().UnixNano())\n\twins := make(map[spot]int, 2)\n\tfor {\n\t\th := New()\n\t\tvar s herGameState\n\t\tfor c := false; h[stateIdx] == empty; c = !c {\n\t\t\tif c {\n\t\t\t\th = s.Move(h)\n\t\t\t} else {\n\t\t\t\th = h.HumanMove()\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Board:\\n%v is a win for %v\\n\", h, h[stateIdx])\n\t\ts.Result(h[stateIdx])\n\t\twins[h[stateIdx]]++\n\t\tfmt.Printf(\"Wins: Black=%d, White=%d\\n\", wins[black], wins[white])\n\t\tfmt.Println()\n\t}\n}\n\nfunc (h Hexapawn) HumanMove() Hexapawn {\n\tfmt.Print(\"Board:\\n\", h, \"\\n\")\n\tvar from, to int\n\tfor {\n\t\tfmt.Print(\"Your move: \")\n\t\t_, err := fmt.Scanln(&from, &to)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err == io.EOF {\n\t\t\t\tos.Exit(0) \n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err := h.doMove(white, from-1, to-1); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\treturn h\n\t}\n}\n\nvar herNextMove = make(map[Hexapawn][]move)\n\ntype herGameState struct {\n\t\n\th Hexapawn\n\ti int\n}\n\nfunc (s *herGameState) Move(h Hexapawn) Hexapawn {\n\tknown := false\n\tmoves := herNextMove[h]\n\tif moves == nil { \n\t\tmoves = possibleMoves(black, h)\n\t\therNextMove[h] = moves\n\t} else if len(moves) == 0 {\n\t\t\n\t\tvlog.Println(\"no good moves left to black, picking a random looser\")\n\t\tknown = true\n\t\tmoves = possibleMoves(black, h)\n\t}\n\tvlog.Println(\"considering\", moves)\n\ti := rand.Intn(len(moves))\n\tif !known {\n\t\ts.h = h\n\t\ts.i = i\n\t}\n\tfmt.Println(\"Computer moves\", moves[i])\n\tif err := h.doMove(black, moves[i].from, moves[i].to); err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}\n\nfunc (s herGameState) Result(winner spot) {\n\tif winner == black {\n\t\treturn \n\t}\n\t\n\tmoves := herNextMove[s.h]\n\tvlog.Printf(\"Training:\\n%v will no longer do %v\\n\", s.h, moves[s.i])\n\therNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...)\n\tvlog.Println(\"will instead do one of:\", herNextMove[s.h])\n}\n\ntype move struct{ from, to int }\n\nfunc (m move) String() string { return fmt.Sprintf(\"%d→%d\", m.from+1, m.to+1) }\n\nvar cachedMoves = []map[Hexapawn][]move{\n\tblack: make(map[Hexapawn][]move),\n\twhite: make(map[Hexapawn][]move),\n}\n\nfunc possibleMoves(s spot, h Hexapawn) []move {\n\tm := cachedMoves[s][h]\n\tif m != nil {\n\t\treturn m\n\t}\n\t\n\t\n\t\n\tm = make([]move, 0)\n\tfor from := 0; from < Rows*Cols; from++ {\n\t\tfor to := 0; to < Rows*Cols; to++ {\n\t\t\tif err := h.checkMove(s, from, to); err == nil {\n\t\t\t\tm = append(m, move{from, to})\n\t\t\t}\n\t\t}\n\t}\n\tcachedMoves[s][h] = m\n\tvlog.Printf(\"caclulated possible moves for %v\\n%v as %v\\n\", s, h, m)\n\treturn m\n}\n\nfunc (h *Hexapawn) doMove(p spot, from, to int) error {\n\tif err := h.checkMove(p, from, to); err != nil {\n\t\treturn err\n\t}\n\th[from] = empty\n\th[to] = p\n\tif (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) {\n\t\th[stateIdx] = p\n\t} else if len(possibleMoves(p.Other(), *h)) == 0 {\n\t\th[stateIdx] = p\n\t}\n\treturn nil\n}\n\nfunc (h *Hexapawn) checkMove(p spot, from, to int) error {\n\tif h[from] != p {\n\t\treturn fmt.Errorf(\"No %v located at spot %v\", p, from+1)\n\t}\n\tif h[to] == p {\n\t\treturn fmt.Errorf(\"%v already occupies spot %v\", p, to+1)\n\t}\n\tΔr := from/Rows - to/Rows\n\tif (p == white && Δr != -1) || (p == black && Δr != 1) {\n\t\treturn errors.New(\"must move forward one row\")\n\t}\n\tΔc := from%Rows - to%Rows\n\tcapture := h[to] != empty\n\tif (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) {\n\t\treturn errors.New(\"ilegal move\")\n\t}\n\treturn nil\n}\n\ntype Hexapawn [Rows*Cols + 1]spot\n\nfunc New() Hexapawn {\n\t\n\treturn Hexapawn{\n\t\twhite, white, white,\n\t\tempty, empty, empty,\n\t\tblack, black, black,\n\t}\n}\n\nfunc idx(r, c int) int { return r*Cols + c }\n\n\nconst stateIdx = Rows * Cols\n\nfunc (h Hexapawn) String() string {\n\tvar b bytes.Buffer\n\tfor r := Rows - 1; r >= 0; r-- {\n\t\tfor c := 0; c < Cols; c++ {\n\t\t\tb.WriteByte(h[idx(r, c)].Byte())\n\t\t}\n\t\tb.WriteByte('\\n')\n\t}\n\t\n\treturn string(b.Next(Rows*(Cols+1) - 1))\n}\n\ntype spot uint8\n\nconst (\n\tempty spot = iota\n\tblack\n\twhite\n)\n\nfunc (s spot) String() string {\n\tswitch s {\n\tcase black:\n\t\treturn \"Black\"\n\tcase white:\n\t\treturn \"White\"\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Byte() byte {\n\tswitch s {\n\tcase empty:\n\t\treturn '.'\n\tcase black:\n\t\treturn 'B'\n\tcase white:\n\t\treturn 'W'\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Other() spot {\n\tif s == black {\n\t\treturn white\n\t}\n\treturn black\n}\n", "Python": "\nimport sys\n\nblack_pawn = \" \\u265f  \"\nwhite_pawn = \" \\u2659  \"\nempty_square = \"    \"\n\n\ndef draw_board(board_data):\n    \n    bg_black = \"\\u001b[48;5;237m\"\n    \n    bg_white = \"\\u001b[48;5;245m\"\n\n    clear_to_eol = \"\\u001b[0m\\u001b[K\\n\"\n\n    board = [\"1 \", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol,\n             \"2 \", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol,\n             \"3 \", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol,\n             \"   A   B   C\\n\"];\n\n    sys.stdout.write(\"\".join(board))\n\ndef get_movement_direction(colour):\n    direction = -1\n    if colour == black_pawn:\n        direction = 1\n    elif colour == white_pawn:\n        direction = -1\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\n    return direction\n\ndef get_other_colour(colour):\n    if colour == black_pawn:\n        return white_pawn\n    elif colour == white_pawn:\n        return black_pawn\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\ndef get_allowed_moves(board_data, row, col):\n    if board_data[row][col] == empty_square:\n        return set()\n\n    colour = board_data[row][col]\n    other_colour = get_other_colour(colour)\n    direction = get_movement_direction(colour)\n\n    if (row + direction < 0 or row + direction > 2):\n        return set()\n\n    allowed_moves = set()\n    if board_data[row + direction][col] == empty_square:\n        allowed_moves.add('f')\n    if col > 0 and board_data[row + direction][col - 1] == other_colour:\n        allowed_moves.add('dl')\n    if col < 2 and board_data[row + direction][col + 1] == other_colour:\n        allowed_moves.add('dr')\n\n    return allowed_moves\n\ndef get_human_move(board_data, colour):\n    \n    direction = get_movement_direction(colour)\n\n    while True:\n        piece_posn = input(f'What {colour} do you want to move? ')\n        valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2),\n                        'a2': (1,0), 'b2': (1,1), 'c2': (1,2),\n                        'a3': (2,0), 'b3': (2,1), 'c3': (2,2)}\n        if piece_posn not in valid_inputs:\n            print(\"LOL that's not a valid position! Try again.\")\n            continue\n\n        (row, col) = valid_inputs[piece_posn]\n        piece = board_data[row][col]\n        if piece == empty_square:\n            print(\"What are you trying to pull, there's no piece in that space!\")\n            continue\n\n        if piece != colour:\n            print(\"LOL that's not your piece, try again!\")\n            continue\n\n        allowed_moves = get_allowed_moves(board_data, row, col)\n\n        if len(allowed_moves) == 0:\n            print('LOL nice try. That piece has no valid moves.')\n            continue\n\n        move = list(allowed_moves)[0]\n        if len(allowed_moves) > 1:\n            move = input(f'What move do you want to make ({\",\".join(list(allowed_moves))})? ')\n            if move not in allowed_moves:\n                print('LOL that move is not allowed. Try again.')\n                continue\n\n        if move == 'f':\n            board_data[row + direction][col] = board_data[row][col]\n        elif move == 'dl':\n            board_data[row + direction][col - 1] = board_data[row][col]\n        elif move == 'dr':\n            board_data[row + direction][col + 1] = board_data[row][col]\n\n        board_data[row][col] = empty_square\n        return board_data\n\n\ndef is_game_over(board_data):\n    if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn:\n        return white_pawn\n\n    if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn:\n        return black_pawn\n\n    white_count = 0\n    black_count = 0\n    black_allowed_moves = []\n    white_allowed_moves = []\n    for i in range(3):\n        for j in range(3):\n            moves = get_allowed_moves(board_data, i, j)\n\n            if board_data[i][j] == white_pawn:\n                white_count += 1\n                if len(moves) > 0:\n                    white_allowed_moves.append((i,j,moves))\n            if board_data[i][j] == black_pawn:\n                black_count += 1\n                if len(moves) > 0:\n                    black_allowed_moves.append((i,j,moves))\n\n    if white_count == 0 or len(white_allowed_moves) == 0:\n        return black_pawn\n    if black_count == 0 or len(black_allowed_moves) == 0:\n        return white_pawn\n\n    return \"LOL NOPE\"\n\ndef play_game(black_move, white_move):\n\n    board_data = [[black_pawn, black_pawn, black_pawn],\n                  [empty_square, empty_square, empty_square],\n                  [white_pawn, white_pawn, white_pawn]]\n\n    last_player = black_pawn\n    next_player = white_pawn\n    while is_game_over(board_data) == \"LOL NOPE\":\n        draw_board(board_data)\n\n        if (next_player == black_pawn):\n            board_data = black_move(board_data, next_player)\n        else:\n            board_data = white_move(board_data, next_player)\n\n        temp = last_player\n        last_player = next_player\n        next_player = temp\n\n    winner = is_game_over(board_data)\n    print(f'Congratulations {winner}!')\n\nplay_game(get_human_move, get_human_move)\n"}
{"id": 51012, "name": "Hexapawn", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\nconst (\n\tRows = 3\n\tCols = 3\n)\n\nvar vlog *log.Logger\n\nfunc main() {\n\tverbose := flag.Bool(\"v\", false, \"verbose\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tlogOutput := ioutil.Discard\n\tif *verbose {\n\t\tlogOutput = os.Stderr\n\t}\n\tvlog = log.New(logOutput, \"hexapawn: \", 0)\n\n\trand.Seed(time.Now().UnixNano())\n\twins := make(map[spot]int, 2)\n\tfor {\n\t\th := New()\n\t\tvar s herGameState\n\t\tfor c := false; h[stateIdx] == empty; c = !c {\n\t\t\tif c {\n\t\t\t\th = s.Move(h)\n\t\t\t} else {\n\t\t\t\th = h.HumanMove()\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Board:\\n%v is a win for %v\\n\", h, h[stateIdx])\n\t\ts.Result(h[stateIdx])\n\t\twins[h[stateIdx]]++\n\t\tfmt.Printf(\"Wins: Black=%d, White=%d\\n\", wins[black], wins[white])\n\t\tfmt.Println()\n\t}\n}\n\nfunc (h Hexapawn) HumanMove() Hexapawn {\n\tfmt.Print(\"Board:\\n\", h, \"\\n\")\n\tvar from, to int\n\tfor {\n\t\tfmt.Print(\"Your move: \")\n\t\t_, err := fmt.Scanln(&from, &to)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err == io.EOF {\n\t\t\t\tos.Exit(0) \n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err := h.doMove(white, from-1, to-1); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\treturn h\n\t}\n}\n\nvar herNextMove = make(map[Hexapawn][]move)\n\ntype herGameState struct {\n\t\n\th Hexapawn\n\ti int\n}\n\nfunc (s *herGameState) Move(h Hexapawn) Hexapawn {\n\tknown := false\n\tmoves := herNextMove[h]\n\tif moves == nil { \n\t\tmoves = possibleMoves(black, h)\n\t\therNextMove[h] = moves\n\t} else if len(moves) == 0 {\n\t\t\n\t\tvlog.Println(\"no good moves left to black, picking a random looser\")\n\t\tknown = true\n\t\tmoves = possibleMoves(black, h)\n\t}\n\tvlog.Println(\"considering\", moves)\n\ti := rand.Intn(len(moves))\n\tif !known {\n\t\ts.h = h\n\t\ts.i = i\n\t}\n\tfmt.Println(\"Computer moves\", moves[i])\n\tif err := h.doMove(black, moves[i].from, moves[i].to); err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}\n\nfunc (s herGameState) Result(winner spot) {\n\tif winner == black {\n\t\treturn \n\t}\n\t\n\tmoves := herNextMove[s.h]\n\tvlog.Printf(\"Training:\\n%v will no longer do %v\\n\", s.h, moves[s.i])\n\therNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...)\n\tvlog.Println(\"will instead do one of:\", herNextMove[s.h])\n}\n\ntype move struct{ from, to int }\n\nfunc (m move) String() string { return fmt.Sprintf(\"%d→%d\", m.from+1, m.to+1) }\n\nvar cachedMoves = []map[Hexapawn][]move{\n\tblack: make(map[Hexapawn][]move),\n\twhite: make(map[Hexapawn][]move),\n}\n\nfunc possibleMoves(s spot, h Hexapawn) []move {\n\tm := cachedMoves[s][h]\n\tif m != nil {\n\t\treturn m\n\t}\n\t\n\t\n\t\n\tm = make([]move, 0)\n\tfor from := 0; from < Rows*Cols; from++ {\n\t\tfor to := 0; to < Rows*Cols; to++ {\n\t\t\tif err := h.checkMove(s, from, to); err == nil {\n\t\t\t\tm = append(m, move{from, to})\n\t\t\t}\n\t\t}\n\t}\n\tcachedMoves[s][h] = m\n\tvlog.Printf(\"caclulated possible moves for %v\\n%v as %v\\n\", s, h, m)\n\treturn m\n}\n\nfunc (h *Hexapawn) doMove(p spot, from, to int) error {\n\tif err := h.checkMove(p, from, to); err != nil {\n\t\treturn err\n\t}\n\th[from] = empty\n\th[to] = p\n\tif (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) {\n\t\th[stateIdx] = p\n\t} else if len(possibleMoves(p.Other(), *h)) == 0 {\n\t\th[stateIdx] = p\n\t}\n\treturn nil\n}\n\nfunc (h *Hexapawn) checkMove(p spot, from, to int) error {\n\tif h[from] != p {\n\t\treturn fmt.Errorf(\"No %v located at spot %v\", p, from+1)\n\t}\n\tif h[to] == p {\n\t\treturn fmt.Errorf(\"%v already occupies spot %v\", p, to+1)\n\t}\n\tΔr := from/Rows - to/Rows\n\tif (p == white && Δr != -1) || (p == black && Δr != 1) {\n\t\treturn errors.New(\"must move forward one row\")\n\t}\n\tΔc := from%Rows - to%Rows\n\tcapture := h[to] != empty\n\tif (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) {\n\t\treturn errors.New(\"ilegal move\")\n\t}\n\treturn nil\n}\n\ntype Hexapawn [Rows*Cols + 1]spot\n\nfunc New() Hexapawn {\n\t\n\treturn Hexapawn{\n\t\twhite, white, white,\n\t\tempty, empty, empty,\n\t\tblack, black, black,\n\t}\n}\n\nfunc idx(r, c int) int { return r*Cols + c }\n\n\nconst stateIdx = Rows * Cols\n\nfunc (h Hexapawn) String() string {\n\tvar b bytes.Buffer\n\tfor r := Rows - 1; r >= 0; r-- {\n\t\tfor c := 0; c < Cols; c++ {\n\t\t\tb.WriteByte(h[idx(r, c)].Byte())\n\t\t}\n\t\tb.WriteByte('\\n')\n\t}\n\t\n\treturn string(b.Next(Rows*(Cols+1) - 1))\n}\n\ntype spot uint8\n\nconst (\n\tempty spot = iota\n\tblack\n\twhite\n)\n\nfunc (s spot) String() string {\n\tswitch s {\n\tcase black:\n\t\treturn \"Black\"\n\tcase white:\n\t\treturn \"White\"\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Byte() byte {\n\tswitch s {\n\tcase empty:\n\t\treturn '.'\n\tcase black:\n\t\treturn 'B'\n\tcase white:\n\t\treturn 'W'\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Other() spot {\n\tif s == black {\n\t\treturn white\n\t}\n\treturn black\n}\n", "Python": "\nimport sys\n\nblack_pawn = \" \\u265f  \"\nwhite_pawn = \" \\u2659  \"\nempty_square = \"    \"\n\n\ndef draw_board(board_data):\n    \n    bg_black = \"\\u001b[48;5;237m\"\n    \n    bg_white = \"\\u001b[48;5;245m\"\n\n    clear_to_eol = \"\\u001b[0m\\u001b[K\\n\"\n\n    board = [\"1 \", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol,\n             \"2 \", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol,\n             \"3 \", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol,\n             \"   A   B   C\\n\"];\n\n    sys.stdout.write(\"\".join(board))\n\ndef get_movement_direction(colour):\n    direction = -1\n    if colour == black_pawn:\n        direction = 1\n    elif colour == white_pawn:\n        direction = -1\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\n    return direction\n\ndef get_other_colour(colour):\n    if colour == black_pawn:\n        return white_pawn\n    elif colour == white_pawn:\n        return black_pawn\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\ndef get_allowed_moves(board_data, row, col):\n    if board_data[row][col] == empty_square:\n        return set()\n\n    colour = board_data[row][col]\n    other_colour = get_other_colour(colour)\n    direction = get_movement_direction(colour)\n\n    if (row + direction < 0 or row + direction > 2):\n        return set()\n\n    allowed_moves = set()\n    if board_data[row + direction][col] == empty_square:\n        allowed_moves.add('f')\n    if col > 0 and board_data[row + direction][col - 1] == other_colour:\n        allowed_moves.add('dl')\n    if col < 2 and board_data[row + direction][col + 1] == other_colour:\n        allowed_moves.add('dr')\n\n    return allowed_moves\n\ndef get_human_move(board_data, colour):\n    \n    direction = get_movement_direction(colour)\n\n    while True:\n        piece_posn = input(f'What {colour} do you want to move? ')\n        valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2),\n                        'a2': (1,0), 'b2': (1,1), 'c2': (1,2),\n                        'a3': (2,0), 'b3': (2,1), 'c3': (2,2)}\n        if piece_posn not in valid_inputs:\n            print(\"LOL that's not a valid position! Try again.\")\n            continue\n\n        (row, col) = valid_inputs[piece_posn]\n        piece = board_data[row][col]\n        if piece == empty_square:\n            print(\"What are you trying to pull, there's no piece in that space!\")\n            continue\n\n        if piece != colour:\n            print(\"LOL that's not your piece, try again!\")\n            continue\n\n        allowed_moves = get_allowed_moves(board_data, row, col)\n\n        if len(allowed_moves) == 0:\n            print('LOL nice try. That piece has no valid moves.')\n            continue\n\n        move = list(allowed_moves)[0]\n        if len(allowed_moves) > 1:\n            move = input(f'What move do you want to make ({\",\".join(list(allowed_moves))})? ')\n            if move not in allowed_moves:\n                print('LOL that move is not allowed. Try again.')\n                continue\n\n        if move == 'f':\n            board_data[row + direction][col] = board_data[row][col]\n        elif move == 'dl':\n            board_data[row + direction][col - 1] = board_data[row][col]\n        elif move == 'dr':\n            board_data[row + direction][col + 1] = board_data[row][col]\n\n        board_data[row][col] = empty_square\n        return board_data\n\n\ndef is_game_over(board_data):\n    if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn:\n        return white_pawn\n\n    if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn:\n        return black_pawn\n\n    white_count = 0\n    black_count = 0\n    black_allowed_moves = []\n    white_allowed_moves = []\n    for i in range(3):\n        for j in range(3):\n            moves = get_allowed_moves(board_data, i, j)\n\n            if board_data[i][j] == white_pawn:\n                white_count += 1\n                if len(moves) > 0:\n                    white_allowed_moves.append((i,j,moves))\n            if board_data[i][j] == black_pawn:\n                black_count += 1\n                if len(moves) > 0:\n                    black_allowed_moves.append((i,j,moves))\n\n    if white_count == 0 or len(white_allowed_moves) == 0:\n        return black_pawn\n    if black_count == 0 or len(black_allowed_moves) == 0:\n        return white_pawn\n\n    return \"LOL NOPE\"\n\ndef play_game(black_move, white_move):\n\n    board_data = [[black_pawn, black_pawn, black_pawn],\n                  [empty_square, empty_square, empty_square],\n                  [white_pawn, white_pawn, white_pawn]]\n\n    last_player = black_pawn\n    next_player = white_pawn\n    while is_game_over(board_data) == \"LOL NOPE\":\n        draw_board(board_data)\n\n        if (next_player == black_pawn):\n            board_data = black_move(board_data, next_player)\n        else:\n            board_data = white_move(board_data, next_player)\n\n        temp = last_player\n        last_player = next_player\n        next_player = temp\n\n    winner = is_game_over(board_data)\n    print(f'Congratulations {winner}!')\n\nplay_game(get_human_move, get_human_move)\n"}
{"id": 51013, "name": "Graph colouring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype graph struct {\n    nn  int     \n    st  int     \n    nbr [][]int \n}\n\ntype nodeval struct {\n    n int \n    v int \n}\n\nfunc contains(s []int, n int) bool {\n    for _, e := range s {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc newGraph(nn, st int) graph {\n    nbr := make([][]int, nn)\n    return graph{nn, st, nbr}\n}\n\n\nfunc (g graph) addEdge(n1, n2 int) {\n    n1, n2 = n1-g.st, n2-g.st \n    g.nbr[n1] = append(g.nbr[n1], n2)\n    if n1 != n2 {\n        g.nbr[n2] = append(g.nbr[n2], n1)\n    }\n}\n\n\nfunc (g graph) greedyColoring() []int {\n    \n    cols := make([]int, g.nn) \n    for i := 1; i < g.nn; i++ {\n        cols[i] = -1 \n    }\n    \n    available := make([]bool, g.nn) \n    \n    for i := 1; i < g.nn; i++ {\n        \n        for _, j := range g.nbr[i] {\n            if cols[j] != -1 {\n                available[cols[j]] = true\n            }\n        }\n        \n        c := 0\n        for ; c < g.nn; c++ {\n            if !available[c] {\n                break\n            }\n        }\n        cols[i] = c \n        \n        \n        for _, j := range g.nbr[i] {\n            if cols[j] != -1 {\n                available[cols[j]] = false\n            }\n        }\n    }\n    return cols\n}\n\n\nfunc (g graph) wpColoring() []int {\n    \n    nvs := make([]nodeval, g.nn)\n    for i := 0; i < g.nn; i++ {\n        v := len(g.nbr[i])\n        if v == 1 && g.nbr[i][0] == i { \n            v = 0\n        }\n        nvs[i] = nodeval{i, v}\n    }\n    \n    sort.Slice(nvs, func(i, j int) bool {\n        return nvs[i].v > nvs[j].v\n    })\n    \n    cols := make([]int, g.nn)\n    for i := range cols {\n        cols[i] = -1 \n    }\n    currCol := 0 \n    for f := 0; f < g.nn-1; f++ {\n        h := nvs[f].n\n        if cols[h] != -1 { \n            continue\n        }\n        cols[h] = currCol\n        \n        \n    outer:\n        for i := f + 1; i < g.nn; i++ {\n            j := nvs[i].n\n            if cols[j] != -1 { \n                continue\n            }\n            for k := f; k < i; k++ {\n                l := nvs[k].n\n                if cols[l] == -1 { \n                    continue\n                }\n                if contains(g.nbr[j], l) {\n                    continue outer \n                }\n            }\n            cols[j] = currCol\n        }\n        currCol++\n    }\n    return cols\n}\n\nfunc main() {\n    fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring}\n    titles := []string{\"'Greedy'\", \"Welsh-Powell\"}\n    nns := []int{4, 8, 8, 8}\n    starts := []int{0, 1, 1, 1}\n    edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}}\n    edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8},\n        {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}}\n    edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8},\n        {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}}\n    edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8},\n        {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}}\n    for j, fn := range fns {\n        fmt.Println(\"Using the\", titles[j], \"algorithm:\\n\")\n        for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} {\n            fmt.Println(\"  Example\", i+1)\n            g := newGraph(nns[i], starts[i])\n            for _, e := range edges {\n                g.addEdge(e[0], e[1])\n            }\n            cols := fn(g)\n            ecount := 0 \n            for _, e := range edges {\n                if e[0] != e[1] {\n                    fmt.Printf(\"    Edge  %d-%d -> Color %d, %d\\n\", e[0], e[1],\n                        cols[e[0]-g.st], cols[e[1]-g.st])\n                    ecount++\n                } else {\n                    fmt.Printf(\"    Node  %d   -> Color %d\\n\", e[0], cols[e[0]-g.st])\n                }\n            }\n            maxCol := 0 \n            for _, col := range cols {\n                if col > maxCol {\n                    maxCol = col\n                }\n            }\n            fmt.Println(\"    Number of nodes  :\", nns[i])\n            fmt.Println(\"    Number of edges  :\", ecount)\n            fmt.Println(\"    Number of colors :\", maxCol+1)\n            fmt.Println()\n        }\n    }\n}\n", "Python": "import re\nfrom collections import defaultdict\nfrom itertools import count\n\n\nconnection_re = r\n\nclass Graph:\n\n    def __init__(self, name, connections):\n        self.name = name\n        self.connections = connections\n        g = self.graph = defaultdict(list)  \n\n        matches = re.finditer(connection_re, connections,\n                              re.MULTILINE | re.VERBOSE)\n        for match in matches:\n            n1, n2, n = match.groups()\n            if n:\n                g[n] += []\n            else:\n                g[n1].append(n2)    \n                g[n2].append(n1)\n\n    def greedy_colour(self, order=None):\n        \"Greedy colourisation algo.\"\n        if order is None:\n            order = self.graph      \n        colour = self.colour = {}\n        neighbours = self.graph\n        for node in order:\n            used_neighbour_colours = (colour[nbr] for nbr in neighbours[node]\n                                      if nbr in colour)\n            colour[node] = first_avail_int(used_neighbour_colours)\n        self.pp_colours()\n        return colour\n\n    def pp_colours(self):\n        print(f\"\\n{self.name}\")\n        c = self.colour\n        e = canonical_edges = set()\n        for n1, neighbours in sorted(self.graph.items()):\n            if neighbours:\n                for n2 in neighbours:\n                    edge = tuple(sorted([n1, n2]))\n                    if edge not in canonical_edges:\n                        print(f\"       {n1}-{n2}: Colour: {c[n1]}, {c[n2]}\")\n                        canonical_edges.add(edge)\n            else:\n                print(f\"         {n1}: Colour: {c[n1]}\")\n        lc = len(set(c.values()))\n        print(f\"    \n\n\ndef first_avail_int(data):\n    \"return lowest int 0... not in data\"\n    d = set(data)\n    for i in count():\n        if i not in d:\n            return i\n\n\nif __name__ == '__main__':\n    for name, connections in [\n            ('Ex1', \"0-1 1-2 2-0 3\"),\n            ('Ex2', \"1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\"),\n            ('Ex3', \"1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\"),\n            ('Ex4', \"1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\"),\n            ]:\n        g = Graph(name, connections)\n        g.greedy_colour()\n"}
{"id": 51014, "name": "Sort primes from list to a list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103}\n    var primes []int\n    for _, e := range list {\n        if rcu.IsPrime(e) {\n            primes = append(primes, e)\n        }\n    }\n    sort.Ints(primes)\n    fmt.Println(primes)\n}\n", "Python": "print(\"working...\")\nprint(\"Primes are:\")\n\ndef isprime(m):\n    for i in range(2,int(m**0.5)+1):\n        if m%i==0:\n            return False\n    return True\n\nPrimes = [2,43,81,122,63,13,7,95,103]\nTemp = []\n\nfor n in range(len(Primes)):\n\tif isprime(Primes[n]):\n\t\tTemp.append(Primes[n])\n\nTemp.sort()\nprint(Temp)\nprint(\"done...\")\n"}
{"id": 51015, "name": "Count the coins_0-1", "Go": "package main\n\nimport \"fmt\"\n\nvar cnt = 0  \nvar cnt2 = 0 \nvar wdth = 0 \n\nfunc factorial(n int) int {\n    prod := 1\n    for i := 2; i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc count(want int, used []int, sum int, have, uindices, rindices []int) {\n    if sum == want {\n        cnt++\n        cnt2 += factorial(len(used))\n        if cnt < 11 {\n            uindicesStr := fmt.Sprintf(\"%v\", uindices)\n            fmt.Printf(\"  indices %*s => used %v\\n\", wdth, uindicesStr, used)\n        }\n    } else if sum < want && len(have) != 0 {\n        thisCoin := have[0]\n        index := rindices[0]\n        rest := have[1:]\n        rindices := rindices[1:]\n        count(want, append(used, thisCoin), sum+thisCoin, rest,\n            append(uindices, index), rindices)\n        count(want, used, sum, rest, uindices, rindices)\n    }\n}\n\nfunc countCoins(want int, coins []int, width int) {\n    fmt.Printf(\"Sum %d from coins %v\\n\", want, coins)\n    cnt = 0\n    cnt2 = 0\n    wdth = -width\n    rindices := make([]int, len(coins))\n    for i := range rindices {\n        rindices[i] = i\n    }\n    count(want, []int{}, 0, coins, []int{}, rindices)\n    if cnt > 10 {\n        fmt.Println(\"  .......\")\n        fmt.Println(\"  (only the first 10 ways generated are shown)\")\n    }\n    fmt.Println(\"Number of ways - order unimportant :\", cnt, \"(as above)\")\n    fmt.Println(\"Number of ways - order important   :\", cnt2, \"(all perms of above indices)\\n\")\n}\n\nfunc main() {\n    countCoins(6, []int{1, 2, 3, 4, 5}, 7)\n    countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9)\n    countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20)\n}\n", "Python": "from itertools import product, compress\n\nfact = lambda n: n and n*fact(n - 1) or 1\ncombo_count = lambda total, coins, perm:\\\n                    sum(perm and fact(len(x)) or 1\n                        for x in (list(compress(coins, c))\n                                  for c in product(*([(0, 1)]*len(coins))))\n                        if sum(x) == total)\n\ncases = [(6,  [1, 2, 3, 4, 5]),\n         (6,  [1, 1, 2, 3, 3, 4, 5]),\n         (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])]\n\nfor perm in [False, True]:\n    print(f'Order matters: {perm}')\n    for s, c in cases:\n        print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}')\n    print()\n"}
{"id": 51016, "name": "Count the coins_0-1", "Go": "package main\n\nimport \"fmt\"\n\nvar cnt = 0  \nvar cnt2 = 0 \nvar wdth = 0 \n\nfunc factorial(n int) int {\n    prod := 1\n    for i := 2; i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc count(want int, used []int, sum int, have, uindices, rindices []int) {\n    if sum == want {\n        cnt++\n        cnt2 += factorial(len(used))\n        if cnt < 11 {\n            uindicesStr := fmt.Sprintf(\"%v\", uindices)\n            fmt.Printf(\"  indices %*s => used %v\\n\", wdth, uindicesStr, used)\n        }\n    } else if sum < want && len(have) != 0 {\n        thisCoin := have[0]\n        index := rindices[0]\n        rest := have[1:]\n        rindices := rindices[1:]\n        count(want, append(used, thisCoin), sum+thisCoin, rest,\n            append(uindices, index), rindices)\n        count(want, used, sum, rest, uindices, rindices)\n    }\n}\n\nfunc countCoins(want int, coins []int, width int) {\n    fmt.Printf(\"Sum %d from coins %v\\n\", want, coins)\n    cnt = 0\n    cnt2 = 0\n    wdth = -width\n    rindices := make([]int, len(coins))\n    for i := range rindices {\n        rindices[i] = i\n    }\n    count(want, []int{}, 0, coins, []int{}, rindices)\n    if cnt > 10 {\n        fmt.Println(\"  .......\")\n        fmt.Println(\"  (only the first 10 ways generated are shown)\")\n    }\n    fmt.Println(\"Number of ways - order unimportant :\", cnt, \"(as above)\")\n    fmt.Println(\"Number of ways - order important   :\", cnt2, \"(all perms of above indices)\\n\")\n}\n\nfunc main() {\n    countCoins(6, []int{1, 2, 3, 4, 5}, 7)\n    countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9)\n    countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20)\n}\n", "Python": "from itertools import product, compress\n\nfact = lambda n: n and n*fact(n - 1) or 1\ncombo_count = lambda total, coins, perm:\\\n                    sum(perm and fact(len(x)) or 1\n                        for x in (list(compress(coins, c))\n                                  for c in product(*([(0, 1)]*len(coins))))\n                        if sum(x) == total)\n\ncases = [(6,  [1, 2, 3, 4, 5]),\n         (6,  [1, 1, 2, 3, 3, 4, 5]),\n         (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])]\n\nfor perm in [False, True]:\n    print(f'Order matters: {perm}')\n    for s, c in cases:\n        print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}')\n    print()\n"}
{"id": 51017, "name": "Numerical and alphabetical suffixes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype minmult struct {\n    min  int\n    mult float64\n}\n\nvar abbrevs = map[string]minmult{\n    \"PAIRs\": {4, 2}, \"SCOres\": {3, 20}, \"DOZens\": {3, 12},\n    \"GRoss\": {2, 144}, \"GREATGRoss\": {7, 1728}, \"GOOGOLs\": {6, 1e100},\n}\n\nvar metric = map[string]float64{\n    \"K\": 1e3, \"M\": 1e6, \"G\": 1e9, \"T\": 1e12, \"P\": 1e15, \"E\": 1e18,\n    \"Z\": 1e21, \"Y\": 1e24, \"X\": 1e27, \"W\": 1e30, \"V\": 1e33, \"U\": 1e36,\n}\n\nvar binary = map[string]float64{\n    \"Ki\": b(10), \"Mi\": b(20), \"Gi\": b(30), \"Ti\": b(40), \"Pi\": b(50), \"Ei\": b(60),\n    \"Zi\": b(70), \"Yi\": b(80), \"Xi\": b(90), \"Wi\": b(100), \"Vi\": b(110), \"Ui\": b(120),\n}\n\nfunc b(e float64) float64 {\n    return math.Pow(2, e)\n}\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc fact(num string, d int) int {\n    prod := 1\n    n, _ := strconv.Atoi(num)\n    for i := n; i > 0; i -= d {\n        prod *= i\n    }\n    return prod\n}\n\nfunc parse(number string) *big.Float {\n    bf := new(big.Float).SetPrec(500)\n    t1 := new(big.Float).SetPrec(500)\n    t2 := new(big.Float).SetPrec(500)\n    \n    var i int\n    for i = len(number) - 1; i >= 0; i-- {\n        if '0' <= number[i] && number[i] <= '9' {\n            break\n        }\n    }\n    num := number[:i+1]\n    num = strings.Replace(num, \",\", \"\", -1) \n    suf := strings.ToUpper(number[i+1:])\n    if suf == \"\" {\n        bf.SetString(num)\n        return bf\n    }\n    if suf[0] == '!' {\n        prod := fact(num, len(suf))\n        bf.SetInt64(int64(prod))\n        return bf\n    }\n    for k, v := range abbrevs {\n        kk := strings.ToUpper(k)\n        if strings.HasPrefix(kk, suf) && len(suf) >= v.min {\n            t1.SetString(num)\n            if k != \"GOOGOLs\" {\n                t2.SetFloat64(v.mult)\n            } else {\n                t2 = googol() \n            }\n            bf.Mul(t1, t2)\n            return bf\n        }\n    }\n    bf.SetString(num)\n    for k, v := range metric {\n        for j := 0; j < len(suf); j++ {\n            if k == suf[j:j+1] {\n                if j < len(suf)-1 && suf[j+1] == 'I' {\n                    t1.SetFloat64(binary[k+\"i\"])\n                    bf.Mul(bf, t1)\n                    j++\n                } else {\n                    t1.SetFloat64(v)\n                    bf.Mul(bf, t1)\n                }\n            }\n        }\n    }\n    return bf\n}\n\nfunc commatize(s string) string {\n    if len(s) == 0 {\n        return \"\"\n    }\n    neg := s[0] == '-'\n    if neg {\n        s = s[1:]\n    }\n    frac := \"\"\n    if ix := strings.Index(s, \".\"); ix >= 0 {\n        frac = s[ix:]\n        s = s[:ix]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if !neg {\n        return s + frac\n    }\n    return \"-\" + s + frac\n}\n\nfunc process(numbers []string) {\n    fmt.Print(\"numbers =  \")\n    for _, number := range numbers {\n        fmt.Printf(\"%s  \", number)\n    }\n    fmt.Print(\"\\nresults =  \")\n    for _, number := range numbers {\n        res := parse(number)\n        t := res.Text('g', 50)\n        fmt.Printf(\"%s  \", commatize(t))\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    numbers := []string{\"2greatGRo\", \"24Gros\", \"288Doz\", \"1,728pairs\", \"172.8SCOre\"}\n    process(numbers)\n\n    numbers = []string{\"1,567\", \"+1.567k\", \"0.1567e-2m\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kK\", \"25.123m\", \"2.5123e-00002G\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kiKI\", \"25.123Mi\", \"2.5123e-00002Gi\", \"+.25123E-7Ei\"}\n    process(numbers)\n\n    numbers = []string{\"-.25123e-34Vikki\", \"2e-77gooGols\"}\n    process(numbers)\n\n    numbers = []string{\"9!\", \"9!!\", \"9!!!\", \"9!!!!\", \"9!!!!!\", \"9!!!!!!\",\n        \"9!!!!!!!\", \"9!!!!!!!!\", \"9!!!!!!!!!\"}\n    process(numbers)\n}\n", "Python": "from functools import reduce\nfrom operator import mul\nfrom decimal import *\n\ngetcontext().prec = MAX_PREC\n\ndef expand(num):\n    suffixes = [\n        \n        ('greatgross', 7, 12, 3),\n        ('gross', 2, 12, 2),\n        ('dozens', 3, 12, 1),\n        ('pairs', 4, 2, 1),\n        ('scores', 3, 20, 1),\n        ('googols', 6, 10, 100),\n        ('ki', 2, 2, 10),\n        ('mi', 2, 2, 20),\n        ('gi', 2, 2, 30),\n        ('ti', 2, 2, 40),\n        ('pi', 2, 2, 50),\n        ('ei', 2, 2, 60),\n        ('zi', 2, 2, 70),\n        ('yi', 2, 2, 80),\n        ('xi', 2, 2, 90),\n        ('wi', 2, 2, 100),\n        ('vi', 2, 2, 110),\n        ('ui', 2, 2, 120),\n        ('k', 1, 10, 3),\n        ('m', 1, 10, 6),\n        ('g', 1, 10, 9),\n        ('t', 1, 10, 12),\n        ('p', 1, 10, 15),\n        ('e', 1, 10, 18),\n        ('z', 1, 10, 21),\n        ('y', 1, 10, 24),\n        ('x', 1, 10, 27),\n        ('w', 1, 10, 30)\n    ]\n\n    num = num.replace(',', '').strip().lower()\n\n    if num[-1].isdigit():\n        return float(num)\n\n    for i, char in enumerate(reversed(num)):\n        if char.isdigit():\n            input_suffix = num[-i:]\n            num = Decimal(num[:-i])\n            break\n\n    if input_suffix[0] == '!':\n        return reduce(mul, range(int(num), 0, -len(input_suffix)))\n\n    while len(input_suffix) > 0:\n        for suffix, min_abbrev, base, power in suffixes:\n            if input_suffix[:min_abbrev] == suffix[:min_abbrev]:\n                for i in range(min_abbrev, len(input_suffix) + 1):\n                    if input_suffix[:i+1] != suffix[:i+1]:\n                        num *= base ** power\n                        input_suffix = input_suffix[i:]\n                        break\n                break\n\n    return num\n\n\ntest = \"2greatGRo   24Gros  288Doz  1,728pairs  172.8SCOre\\n\\\n        1,567      +1.567k    0.1567e-2m\\n\\\n        25.123kK    25.123m   2.5123e-00002G\\n\\\n        25.123kiKI  25.123Mi  2.5123e-00002Gi  +.25123E-7Ei\\n\\\n        -.25123e-34Vikki      2e-77gooGols\\n\\\n        9!   9!!   9!!!   9!!!!   9!!!!!   9!!!!!!   9!!!!!!!   9!!!!!!!!   9!!!!!!!!!\"\n\nfor test_line in test.split(\"\\n\"):\n    test_cases = test_line.split()\n    print(\"Input:\", ' '.join(test_cases))\n    print(\"Output:\", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))\n"}
{"id": 51018, "name": "Numerical and alphabetical suffixes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype minmult struct {\n    min  int\n    mult float64\n}\n\nvar abbrevs = map[string]minmult{\n    \"PAIRs\": {4, 2}, \"SCOres\": {3, 20}, \"DOZens\": {3, 12},\n    \"GRoss\": {2, 144}, \"GREATGRoss\": {7, 1728}, \"GOOGOLs\": {6, 1e100},\n}\n\nvar metric = map[string]float64{\n    \"K\": 1e3, \"M\": 1e6, \"G\": 1e9, \"T\": 1e12, \"P\": 1e15, \"E\": 1e18,\n    \"Z\": 1e21, \"Y\": 1e24, \"X\": 1e27, \"W\": 1e30, \"V\": 1e33, \"U\": 1e36,\n}\n\nvar binary = map[string]float64{\n    \"Ki\": b(10), \"Mi\": b(20), \"Gi\": b(30), \"Ti\": b(40), \"Pi\": b(50), \"Ei\": b(60),\n    \"Zi\": b(70), \"Yi\": b(80), \"Xi\": b(90), \"Wi\": b(100), \"Vi\": b(110), \"Ui\": b(120),\n}\n\nfunc b(e float64) float64 {\n    return math.Pow(2, e)\n}\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc fact(num string, d int) int {\n    prod := 1\n    n, _ := strconv.Atoi(num)\n    for i := n; i > 0; i -= d {\n        prod *= i\n    }\n    return prod\n}\n\nfunc parse(number string) *big.Float {\n    bf := new(big.Float).SetPrec(500)\n    t1 := new(big.Float).SetPrec(500)\n    t2 := new(big.Float).SetPrec(500)\n    \n    var i int\n    for i = len(number) - 1; i >= 0; i-- {\n        if '0' <= number[i] && number[i] <= '9' {\n            break\n        }\n    }\n    num := number[:i+1]\n    num = strings.Replace(num, \",\", \"\", -1) \n    suf := strings.ToUpper(number[i+1:])\n    if suf == \"\" {\n        bf.SetString(num)\n        return bf\n    }\n    if suf[0] == '!' {\n        prod := fact(num, len(suf))\n        bf.SetInt64(int64(prod))\n        return bf\n    }\n    for k, v := range abbrevs {\n        kk := strings.ToUpper(k)\n        if strings.HasPrefix(kk, suf) && len(suf) >= v.min {\n            t1.SetString(num)\n            if k != \"GOOGOLs\" {\n                t2.SetFloat64(v.mult)\n            } else {\n                t2 = googol() \n            }\n            bf.Mul(t1, t2)\n            return bf\n        }\n    }\n    bf.SetString(num)\n    for k, v := range metric {\n        for j := 0; j < len(suf); j++ {\n            if k == suf[j:j+1] {\n                if j < len(suf)-1 && suf[j+1] == 'I' {\n                    t1.SetFloat64(binary[k+\"i\"])\n                    bf.Mul(bf, t1)\n                    j++\n                } else {\n                    t1.SetFloat64(v)\n                    bf.Mul(bf, t1)\n                }\n            }\n        }\n    }\n    return bf\n}\n\nfunc commatize(s string) string {\n    if len(s) == 0 {\n        return \"\"\n    }\n    neg := s[0] == '-'\n    if neg {\n        s = s[1:]\n    }\n    frac := \"\"\n    if ix := strings.Index(s, \".\"); ix >= 0 {\n        frac = s[ix:]\n        s = s[:ix]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if !neg {\n        return s + frac\n    }\n    return \"-\" + s + frac\n}\n\nfunc process(numbers []string) {\n    fmt.Print(\"numbers =  \")\n    for _, number := range numbers {\n        fmt.Printf(\"%s  \", number)\n    }\n    fmt.Print(\"\\nresults =  \")\n    for _, number := range numbers {\n        res := parse(number)\n        t := res.Text('g', 50)\n        fmt.Printf(\"%s  \", commatize(t))\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    numbers := []string{\"2greatGRo\", \"24Gros\", \"288Doz\", \"1,728pairs\", \"172.8SCOre\"}\n    process(numbers)\n\n    numbers = []string{\"1,567\", \"+1.567k\", \"0.1567e-2m\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kK\", \"25.123m\", \"2.5123e-00002G\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kiKI\", \"25.123Mi\", \"2.5123e-00002Gi\", \"+.25123E-7Ei\"}\n    process(numbers)\n\n    numbers = []string{\"-.25123e-34Vikki\", \"2e-77gooGols\"}\n    process(numbers)\n\n    numbers = []string{\"9!\", \"9!!\", \"9!!!\", \"9!!!!\", \"9!!!!!\", \"9!!!!!!\",\n        \"9!!!!!!!\", \"9!!!!!!!!\", \"9!!!!!!!!!\"}\n    process(numbers)\n}\n", "Python": "from functools import reduce\nfrom operator import mul\nfrom decimal import *\n\ngetcontext().prec = MAX_PREC\n\ndef expand(num):\n    suffixes = [\n        \n        ('greatgross', 7, 12, 3),\n        ('gross', 2, 12, 2),\n        ('dozens', 3, 12, 1),\n        ('pairs', 4, 2, 1),\n        ('scores', 3, 20, 1),\n        ('googols', 6, 10, 100),\n        ('ki', 2, 2, 10),\n        ('mi', 2, 2, 20),\n        ('gi', 2, 2, 30),\n        ('ti', 2, 2, 40),\n        ('pi', 2, 2, 50),\n        ('ei', 2, 2, 60),\n        ('zi', 2, 2, 70),\n        ('yi', 2, 2, 80),\n        ('xi', 2, 2, 90),\n        ('wi', 2, 2, 100),\n        ('vi', 2, 2, 110),\n        ('ui', 2, 2, 120),\n        ('k', 1, 10, 3),\n        ('m', 1, 10, 6),\n        ('g', 1, 10, 9),\n        ('t', 1, 10, 12),\n        ('p', 1, 10, 15),\n        ('e', 1, 10, 18),\n        ('z', 1, 10, 21),\n        ('y', 1, 10, 24),\n        ('x', 1, 10, 27),\n        ('w', 1, 10, 30)\n    ]\n\n    num = num.replace(',', '').strip().lower()\n\n    if num[-1].isdigit():\n        return float(num)\n\n    for i, char in enumerate(reversed(num)):\n        if char.isdigit():\n            input_suffix = num[-i:]\n            num = Decimal(num[:-i])\n            break\n\n    if input_suffix[0] == '!':\n        return reduce(mul, range(int(num), 0, -len(input_suffix)))\n\n    while len(input_suffix) > 0:\n        for suffix, min_abbrev, base, power in suffixes:\n            if input_suffix[:min_abbrev] == suffix[:min_abbrev]:\n                for i in range(min_abbrev, len(input_suffix) + 1):\n                    if input_suffix[:i+1] != suffix[:i+1]:\n                        num *= base ** power\n                        input_suffix = input_suffix[i:]\n                        break\n                break\n\n    return num\n\n\ntest = \"2greatGRo   24Gros  288Doz  1,728pairs  172.8SCOre\\n\\\n        1,567      +1.567k    0.1567e-2m\\n\\\n        25.123kK    25.123m   2.5123e-00002G\\n\\\n        25.123kiKI  25.123Mi  2.5123e-00002Gi  +.25123E-7Ei\\n\\\n        -.25123e-34Vikki      2e-77gooGols\\n\\\n        9!   9!!   9!!!   9!!!!   9!!!!!   9!!!!!!   9!!!!!!!   9!!!!!!!!   9!!!!!!!!!\"\n\nfor test_line in test.split(\"\\n\"):\n    test_cases = test_line.split()\n    print(\"Input:\", ' '.join(test_cases))\n    print(\"Output:\", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))\n"}
{"id": 51019, "name": "Factorial base numbers indexing permutations of a collection", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\nfunc genFactBaseNums(size int, countOnly bool) ([][]int, int) {\n    var results [][]int\n    count := 0\n    for n := 0; ; n++ {\n        radix := 2\n        var res []int = nil\n        if !countOnly { \n            res = make([]int, size)\n        }\n        k := n\n        for k > 0 {\n            div := k / radix\n            rem := k % radix\n            if !countOnly {\n                if radix <= size+1 {\n                    res[size-radix+1] = rem\n                }\n            }\n            k = div\n            radix++\n        }\n        if radix > size+2 {\n            break\n        }\n        count++\n        if !countOnly {\n            results = append(results, res)\n        }\n    }\n    return results, count\n}\n\nfunc mapToPerms(factNums [][]int) [][]int {\n    var perms [][]int\n    psize := len(factNums[0]) + 1\n    start := make([]int, psize)\n    for i := 0; i < psize; i++ {\n        start[i] = i\n    }\n    for _, fn := range factNums {\n        perm := make([]int, psize)\n        copy(perm, start)\n        for m := 0; m < len(fn); m++ {\n            g := fn[m]\n            if g == 0 {\n                continue\n            }\n            first := m\n            last := m + g\n            for i := 1; i <= g; i++ {\n                temp := perm[first]\n                for j := first + 1; j <= last; j++ {\n                    perm[j-1] = perm[j]\n                }\n                perm[last] = temp\n            }\n        }\n        perms = append(perms, perm)\n    }\n    return perms\n}\n\nfunc join(is []int, sep string) string {\n    ss := make([]string, len(is))\n    for i := 0; i < len(is); i++ {\n        ss[i] = strconv.Itoa(is[i])\n    }\n    return strings.Join(ss, sep)\n}\n\nfunc undot(s string) []int {\n    ss := strings.Split(s, \".\")\n    is := make([]int, len(ss))\n    for i := 0; i < len(ss); i++ {\n        is[i], _ = strconv.Atoi(ss[i])\n    }\n    return is\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    \n    factNums, _ := genFactBaseNums(3, false)\n    perms := mapToPerms(factNums)\n    for i, fn := range factNums {\n        fmt.Printf(\"%v -> %v\\n\", join(fn, \".\"), join(perms[i], \"\"))\n    }\n\n    \n    _, count := genFactBaseNums(10, true)\n    fmt.Println(\"\\nPermutations generated =\", count)\n    fmt.Println(\"compared to 11! which  =\", factorial(11))\n    fmt.Println()\n\n    \n    fbn51s := []string{\n        \"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\",\n        \"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\",\n    }\n    factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])}\n    perms = mapToPerms(factNums)\n    shoe := []rune(\"A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣\")\n    cards := make([]string, 52)\n    for i := 0; i < 52; i++ {\n        cards[i] = string(shoe[2*i : 2*i+2])\n        if cards[i][0] == 'T' {\n            cards[i] = \"10\" + cards[i][1:]\n        }\n    }\n    for i, fbn51 := range fbn51s {\n        fmt.Println(fbn51)\n        for _, d := range perms[i] {\n            fmt.Print(cards[d])\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    fbn51 := make([]int, 51)\n    for i := 0; i < 51; i++ {\n        fbn51[i] = rand.Intn(52 - i)\n    }\n    fmt.Println(join(fbn51, \".\"))\n    perms = mapToPerms([][]int{fbn51})\n    for _, d := range perms[0] {\n        fmt.Print(cards[d])\n    }\n    fmt.Println()\n}\n", "Python": "\n\nimport math\n\ndef apply_perm(omega,fbn):\n    \n    for m in range(len(fbn)):\n        g = fbn[m]\n        if g > 0:\n            \n            \n            new_first = omega[m+g]\n            \n            omega[m+1:m+g+1] = omega[m:m+g]\n            \n            omega[m] = new_first\n            \n    return omega\n    \ndef int_to_fbn(i):\n    \n    current = i\n    divisor = 2\n    new_fbn = []\n    while current > 0:\n        remainder = current % divisor\n        current = current // divisor\n        new_fbn.append(remainder)\n        divisor += 1\n    \n    return list(reversed(new_fbn))\n    \ndef leading_zeros(l,n):\n   \n   if len(l) < n:\n       return(([0] * (n - len(l))) + l)\n   else:\n       return l\n\ndef get_fbn(n):\n    \n    max = math.factorial(n)\n    \n    for i in range(max):\n        \n        current = i\n        divisor = 1\n        new_fbn = int_to_fbn(i)\n        yield leading_zeros(new_fbn,n-1)\n        \ndef print_write(f, line):\n    \n    print(line)\n    f.write(str(line)+'\\n')     \n    \ndef dot_format(l):\n    \n    \n    if len(l) < 1:\n        return \"\"\n    \n    dot_string = str(l[0])\n    \n    for e in l[1:]:\n        dot_string += \".\"+str(e)\n        \n    return dot_string\n    \ndef str_format(l):\n    \n    if len(l) < 1:\n        return \"\"\n        \n    new_string = \"\"\n        \n    for e in l:\n        new_string += str(e)\n    \n    return new_string \n    \nwith open(\"output.html\", \"w\", encoding=\"utf-8\") as f:\n    f.write(\"<pre>\\n\")\n    \n    \n        \n    omega=[0,1,2,3]\n    \n    four_list = get_fbn(4)\n    \n    for l in four_list:\n        print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l)))\n        \n    print_write(f,\" \")\n    \n    \n    \n    \n    \n    \n        \n    num_permutations = 0\n    \n    for p in get_fbn(11):\n        num_permutations += 1\n        if num_permutations % 1000000 == 0:\n            print_write(f,\"permutations so far = \"+str(num_permutations))\n    \n    print_write(f,\" \")\n    print_write(f,\"Permutations generated = \"+str(num_permutations))\n    print_write(f,\"compared to 11! which  = \"+str(math.factorial(11)))\n    \n    print_write(f,\" \")\n    \n       \n    \n    \n    \n    shoe = []\n    \n    for suit in [u\"\\u2660\",u\"\\u2665\",u\"\\u2666\",u\"\\u2663\"]:\n        for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']:\n            shoe.append(value+suit)\n                    \n    print_write(f,str_format(shoe))\n    \n    p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0]\n    \n    p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1]\n    \n    print_write(f,\" \")\n    print_write(f,dot_format(p1))\n    print_write(f,\" \")\n    print_write(f,str_format(apply_perm(shoe[:],p1)))\n    \n    print_write(f,\" \")\n    print_write(f,dot_format(p2))\n    print_write(f,\" \")\n    print_write(f,str_format(apply_perm(shoe[:],p2)))\n\n    \n    \n    import random\n    \n    max = math.factorial(52)\n    \n    random_int = random.randint(0, max-1)\n\n    myperm = leading_zeros(int_to_fbn(random_int),51)\n    \n    print(len(myperm))\n    \n    print_write(f,\" \")\n    print_write(f,dot_format(myperm))\n    print_write(f,\" \")\n    print_write(f,str_format(apply_perm(shoe[:],myperm)))\n\n    f.write(\"</pre>\\n\")\n"}
{"id": 51020, "name": "Discrete Fourier transform", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\nfunc dft(x []complex128) []complex128 {\n    N := len(x)\n    y := make([]complex128, N)\n    for k := 0; k < N; k++ {\n        for n := 0; n < N; n++ {\n            t := -1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0)\n            y[k] += x[n] * cmplx.Exp(t)\n        }\n    }\n    return y\n}\n\nfunc idft(y []complex128) []float64 {\n    N := len(y)\n    x := make([]complex128, N)\n    for n := 0; n < N; n++ {\n        for k := 0; k < N; k++ {\n            t := 1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0)\n            x[n] += y[k] * cmplx.Exp(t)\n        }\n        x[n] /= complex(float64(N), 0)\n        \n        if math.Abs(imag(x[n])) < 1e-14 {\n            x[n] = complex(real(x[n]), 0)\n        }\n    }\n    z := make([]float64, N)\n    for i, c := range x {\n        z[i] = float64(real(c))\n    }\n    return z\n}\n\nfunc main() {\n    z := []float64{2, 3, 5, 7, 11}\n    x := make([]complex128, len(z))\n    fmt.Println(\"Original sequence:\", z)\n    for i, n := range z {\n        x[i] = complex(n, 0)\n    }\n    y := dft(x)\n    fmt.Println(\"\\nAfter applying the Discrete Fourier Transform:\")\n    fmt.Printf(\"%0.14g\", y)\n    fmt.Println(\"\\n\\nAfter applying the Inverse Discrete Fourier Transform to the above transform:\")\n    z = idft(y)\n    fmt.Printf(\"%0.14g\", z)\n    fmt.Println()\n}\n", "Python": "\nimport cmath\n\n\ndef dft( x ):\n    \n    N                           = len( x )\n    result                      = []\n    for k in range( N ):\n        r                       = 0\n        for n in range( N ):\n            t                   = -2j * cmath.pi * k * n / N\n            r                  += x[n] * cmath.exp( t )\n        result.append( r )\n    return result\n\n\ndef idft( y ):\n    \n    N                           = len( y )\n    result                      = []\n    for n in range( N ):\n        r                       = 0\n        for k in range( N ):\n            t                   = 2j * cmath.pi * k * n / N\n            r                  += y[k] * cmath.exp( t )\n        r                      /= N+0j\n        result.append( r )\n    return result\n\n\nif __name__ == \"__main__\":\n    x                           = [ 2, 3, 5, 7, 11 ]\n    print( \"vals:   \" + ' '.join( f\"{f:11.2f}\" for f in x ))\n    y                           = dft( x )\n    print( \"DFT:    \" + ' '.join( f\"{f:11.2f}\" for f in y ))\n    z                           = idft( y )\n    print( \"inverse:\" + ' '.join( f\"{f:11.2f}\" for f in z ))\n    print( \" - real:\" + ' '.join( f\"{f.real:11.2f}\" for f in z ))\n\n    N                           = 8\n    print( f\"Complex signals, 1-4 cycles in {N} samples; energy into successive DFT bins\" )\n    for rot in (0, 1, 2, 3, -4, -3, -2, -1):    \n        if rot > N/2:\n            print( \"Signal change frequency exceeds sample rate and will result in artifacts\")\n        sig                     = [\n            \n            cmath.rect(\n                1, cmath.pi*2*rot/N*i\n            )\n            for i in range( N )\n        ]\n        print( f\"{rot:2} cycle\" + ' '.join( f\"{f:11.2f}\" for f in sig ))\n        dft_sig                 = dft( sig )\n        print( f\"  DFT:  \" + ' '.join( f\"{f:11.2f}\" for f in dft_sig ))\n        print( f\"   ABS: \" + ' '.join( f\"{abs(f):11.2f}\" for f in dft_sig ))\n"}
{"id": 51021, "name": "Find first missing positive", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc firstMissingPositive(a []int) int {\n    var b []int\n    for _, e := range a {\n        if e > 0 {\n            b = append(b, e)\n        }\n    }\n    sort.Ints(b)\n    le := len(b)\n    if le == 0 || b[0] > 1 {\n        return 1\n    }\n    for i := 1; i < le; i++ {\n        if b[i]-b[i-1] > 1 {\n            return b[i-1] + 1\n        }\n    }\n    return b[le-1] + 1\n}\n\nfunc main() {\n    fmt.Println(\"The first missing positive integers for the following arrays are:\\n\")\n    aa := [][]int{\n        {1, 2, 0}, {3, 4, -1, 1}, {7, 8, 9, 11, 12}, {1, 2, 3, 4, 5},\n        {-6, -5, -2, -1}, {5, -5}, {-2}, {1}, {}}\n    for _, a := range aa {\n        fmt.Println(a, \"->\", firstMissingPositive(a))\n    }\n}\n", "Python": "\n\nfrom itertools import count\n\n\n\ndef firstGap(xs):\n    \n    return next(x for x in count(1) if x not in xs)\n\n\n\n\ndef main():\n    \n    print('\\n'.join([\n        f'{repr(xs)} -> {firstGap(xs)}' for xs in [\n            [1, 2, 0],\n            [3, 4, -1, 1],\n            [7, 8, 9, 11, 12]\n        ]\n    ]))\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51022, "name": "Names to numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar names = map[string]int64{\n    \"one\":         1,\n    \"two\":         2,\n    \"three\":       3,\n    \"four\":        4,\n    \"five\":        5,\n    \"six\":         6,\n    \"seven\":       7,\n    \"eight\":       8,\n    \"nine\":        9,\n    \"ten\":         10,\n    \"eleven\":      11,\n    \"twelve\":      12,\n    \"thirteen\":    13,\n    \"fourteen\":    14,\n    \"fifteen\":     15,\n    \"sixteen\":     16,\n    \"seventeen\":   17,\n    \"eighteen\":    18,\n    \"nineteen\":    19,\n    \"twenty\":      20,\n    \"thirty\":      30,\n    \"forty\":       40,\n    \"fifty\":       50,\n    \"sixty\":       60,\n    \"seventy\":     70,\n    \"eighty\":      80,\n    \"ninety\":      90,\n    \"hundred\":     100,\n    \"thousand\":    1000,\n    \"million\":     1000000,\n    \"billion\":     1000000000,\n    \"trillion\":    1000000000000,\n    \"quadrillion\": 1000000000000000,\n    \"quintillion\": 1000000000000000000,\n}\n\nvar seps = regexp.MustCompile(`,|-| and | `)\nvar zeros = regexp.MustCompile(`^(zero|nought|nil|none|nothing)$`)\n\nfunc nameToNum(name string) (int64, error) {\n    text := strings.ToLower(strings.TrimSpace(name))\n    isNegative := strings.HasPrefix(text, \"minus \")\n    if isNegative {\n        text = text[6:]\n    }\n    if strings.HasPrefix(text, \"a \") {\n        text = \"one\" + text[1:]\n    }\n    words := seps.Split(text, -1)\n    for i := len(words) - 1; i >= 0; i-- {\n        if words[i] == \"\" {\n            if i < len(words)-1 {\n                copy(words[i:], words[i+1:])\n            }\n            words = words[:len(words)-1]\n        }\n    }\n    size := len(words)\n    if size == 1 && zeros.MatchString(words[0]) {\n        return 0, nil\n    }\n    var multiplier, lastNum, sum int64 = 1, 0, 0\n    for i := size - 1; i >= 0; i-- {\n        num, ok := names[words[i]]\n        if !ok {\n            return 0, fmt.Errorf(\"'%s' is not a valid number\", words[i])\n        } else {\n            switch {\n            case num == lastNum, num >= 1000 && lastNum >= 100:\n                return 0, fmt.Errorf(\"'%s' is not a well formed numeric string\", name)\n            case num >= 1000:\n                multiplier = num\n                if i == 0 {\n                    sum += multiplier\n                }\n            case num >= 100:\n                multiplier *= 100\n                if i == 0 {\n                    sum += multiplier\n                }\n            case num >= 20 && lastNum >= 10 && lastNum <= 90:\n                return 0, fmt.Errorf(\"'%s' is not a well formed numeric string\", name)\n            case num >= 20:\n                sum += num * multiplier\n            case lastNum >= 1 && lastNum <= 90:\n                return 0, fmt.Errorf(\"'%s' is not a well formed numeric string\", name)\n            default:\n                sum += num * multiplier\n            }\n        }\n        lastNum = num\n    }\n\n    if isNegative && sum == -sum {\n        return math.MinInt64, nil\n    }\n    if sum < 0 {\n        return 0, fmt.Errorf(\"'%s' is outside the range of an int64\", name)\n    }\n    if isNegative {\n        return -sum, nil\n    } else {\n        return sum, nil\n    }\n}\n\nfunc main() {\n    names := [...]string{\n        \"none\",\n        \"one\",\n        \"twenty-five\",\n        \"minus one hundred and seventeen\",\n        \"hundred and fifty-six\",\n        \"minus two thousand two\",\n        \"nine thousand, seven hundred, one\",\n        \"minus six hundred and twenty six thousand, eight hundred and fourteen\",\n        \"four million, seven hundred thousand, three hundred and eighty-six\",\n        \"fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four\",\n        \"two hundred and one billion, twenty-one million, two thousand and one\",\n        \"minus three hundred trillion, nine million, four hundred and one thousand and thirty-one\",\n        \"seventeen quadrillion, one hundred thirty-seven\",\n        \"a quintillion, eight trillion and five\",\n        \"minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight\",\n    }\n    for _, name := range names {\n        num, err := nameToNum(name)\n        if err != nil {\n            fmt.Println(err)\n        } else {\n            fmt.Printf(\"%20d = %s\\n\", num, name)\n        }\n    }\n}\n", "Python": "from spell_integer import spell_integer, SMALL, TENS, HUGE\n\ndef int_from_words(num):\n    words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split()\n    if words[0] == 'minus':\n        negmult = -1\n        words.pop(0)\n    else:\n        negmult = 1\n    small, total = 0, 0\n    for word in words:\n        if word in SMALL:\n            small += SMALL.index(word)\n        elif word in TENS:\n            small += TENS.index(word) * 10\n        elif word == 'hundred':\n            small *= 100\n        elif word == 'thousand':\n            total += small * 1000\n            small = 0\n        elif word in HUGE:\n            total += small * 1000 ** HUGE.index(word)\n            small = 0\n        else:\n            raise ValueError(\"Don't understand %r part of %r\" % (word, num))\n    return negmult * (total + small)\n\n\nif __name__ == '__main__':\n    \n    for n in range(-10000, 10000, 17):\n        assert n == int_from_words(spell_integer(n))\n\n    for n in range(20):\n        assert 13**n == int_from_words(spell_integer(13**n))\n    \n    print('\\n\n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        txt = spell_integer(n)\n        num = int_from_words(txt)\n        print('%+4i <%s> %s' % (n, '==' if n == num else '??', txt))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        txt = spell_integer(n)\n        num = int_from_words(txt)\n        print('%12i <%s> %s' % (n, '==' if n == num else '??', txt))\n        n //= -10\n    txt = spell_integer(n)\n    num = int_from_words(txt)\n    print('%12i <%s> %s' % (n, '==' if n == num else '??', txt))\n    print('')\n"}
{"id": 51023, "name": "Magic constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc magicConstant(n int) int {\n    return (n*n + 1) * n / 2\n}\n\nvar ss = []string{\n    \"\\u2070\", \"\\u00b9\", \"\\u00b2\", \"\\u00b3\", \"\\u2074\",\n    \"\\u2075\", \"\\u2076\", \"\\u2077\", \"\\u2078\", \"\\u2079\",\n}\n\nfunc superscript(n int) string {\n    if n < 10 {\n        return ss[n]\n    }\n    if n < 20 {\n        return ss[1] + ss[n-10]\n    }\n    return ss[2] + ss[0]\n}\n\nfunc main() {\n    fmt.Println(\"First 20 magic constants:\")\n    for n := 3; n <= 22; n++ {\n        fmt.Printf(\"%5d \", magicConstant(n))\n        if (n-2)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\n1,000th magic constant:\", rcu.Commatize(magicConstant(1002)))\n\n    fmt.Println(\"\\nSmallest order magic square with a constant greater than:\")\n    for i := 1; i <= 20; i++ {\n        goal := math.Pow(10, float64(i))\n        order := int(math.Cbrt(goal*2)) + 1\n        fmt.Printf(\"10%-2s : %9s\\n\", superscript(i), rcu.Commatize(order))\n    }\n}\n", "Python": "\n\ndef a(n):\n    n += 2\n    return n*(n**2 + 1)/2\n \ndef inv_a(x):\n    k = 0\n    while k*(k**2+1)/2+2 < x:\n        k+=1\n    return k\n\n \nif __name__ == '__main__':\n    print(\"The first 20 magic constants are:\");\n    for n in range(1, 20):\n        print(int(a(n)), end = \" \");\n    print(\"\\nThe 1,000th magic constant is:\",int(a(1000)));\n     \n    for e in range(1, 20):\n        print(f'10^{e}: {inv_a(10**e)}');\n"}
{"id": 51024, "name": "Find minimum number of coins that make a given value", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    denoms := []int{200, 100, 50, 20, 10, 5, 2, 1}\n    coins := 0\n    amount := 988\n    remaining := 988\n    fmt.Println(\"The minimum number of coins needed to make a value of\", amount, \"is as follows:\")\n    for _, denom := range denoms {\n        n := remaining / denom\n        if n > 0 {\n            coins += n\n            fmt.Printf(\"  %3d x %d\\n\", denom, n)\n            remaining %= denom\n            if remaining == 0 {\n                break\n            }\n        }\n    }\n    fmt.Println(\"\\nA total of\", coins, \"coins in all.\")\n}\n", "Python": "def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988):\n    print(f\"Available denominations: {denominations}. Total is to be: {total}.\")\n    coins, remaining = sorted(denominations, reverse=True), total\n    for n in range(len(coins)):\n        coinsused, remaining = divmod(remaining, coins[n])\n        if coinsused > 0:\n            print(\"   \", coinsused, \"*\", coins[n])\n\nmakechange()\n"}
{"id": 51025, "name": "Prime numbers which contain 123", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 100_000\n    primes := rcu.Primes(limit * 10)\n    var results []int\n    for _, p := range primes {\n        if p < 1000 || p > 99999 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            results = append(results, p)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Primes under %s which contain '123' when expressed in decimal:\\n\", climit)\n    for i, p := range results {\n        fmt.Printf(\"%7s \", rcu.Commatize(p))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such primes under\", climit, \"\\b.\")\n\n    limit = 1_000_000\n    climit = rcu.Commatize(limit)\n    count := len(results)\n    for _, p := range primes {\n        if p < 100_000 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            count++\n        }\n    }\n    fmt.Println(\"\\nFound\", count, \"such primes under\", climit, \"\\b.\")\n}\n", "Python": "\n\ndef prime(limite, mostrar):\n    global columna\n    columna = 0\n    \n    for n in range(limite):\n        strn = str(n)\n        if isPrime(n) and ('123' in str(n)):\n            columna += 1                \n            if mostrar == True:\n                print(n, end=\"  \");\n                if columna % 8 == 0:\n                    print('')\n    return columna\n\n\nif __name__ == \"__main__\":\n    print(\"Números primos que contienen 123:\")\n    limite = 100000\n    prime(limite, True)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n    limite = 1000000\n    prime(limite, False)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n"}
{"id": 51026, "name": "Prime numbers which contain 123", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 100_000\n    primes := rcu.Primes(limit * 10)\n    var results []int\n    for _, p := range primes {\n        if p < 1000 || p > 99999 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            results = append(results, p)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Primes under %s which contain '123' when expressed in decimal:\\n\", climit)\n    for i, p := range results {\n        fmt.Printf(\"%7s \", rcu.Commatize(p))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such primes under\", climit, \"\\b.\")\n\n    limit = 1_000_000\n    climit = rcu.Commatize(limit)\n    count := len(results)\n    for _, p := range primes {\n        if p < 100_000 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            count++\n        }\n    }\n    fmt.Println(\"\\nFound\", count, \"such primes under\", climit, \"\\b.\")\n}\n", "Python": "\n\ndef prime(limite, mostrar):\n    global columna\n    columna = 0\n    \n    for n in range(limite):\n        strn = str(n)\n        if isPrime(n) and ('123' in str(n)):\n            columna += 1                \n            if mostrar == True:\n                print(n, end=\"  \");\n                if columna % 8 == 0:\n                    print('')\n    return columna\n\n\nif __name__ == \"__main__\":\n    print(\"Números primos que contienen 123:\")\n    limite = 100000\n    prime(limite, True)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n    limite = 1000000\n    prime(limite, False)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n"}
{"id": 51027, "name": "Function frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"go/token\"\n    \"io/ioutil\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    if len(os.Args) != 2 {\n        fmt.Println(\"usage ff <go source filename>\")\n        return\n    }\n    src, err := ioutil.ReadFile(os.Args[1])\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fs := token.NewFileSet()\n    a, err := parser.ParseFile(fs, os.Args[1], src, 0)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f := fs.File(a.Pos())\n    m := make(map[string]int)\n    ast.Inspect(a, func(n ast.Node) bool {\n        if ce, ok := n.(*ast.CallExpr); ok {\n            start := f.Offset(ce.Pos())\n            end := f.Offset(ce.Lparen)\n            m[string(src[start:end])]++\n        }\n        return true\n    })\n    cs := make(calls, 0, len(m))\n    for k, v := range m {\n        cs = append(cs, &call{k, v})\n    }\n    sort.Sort(cs)\n    for i, c := range cs {\n        fmt.Printf(\"%-20s %4d\\n\", c.expr, c.count)\n        if i == 9 {\n            break\n        }\n    }\n}\n\ntype call struct {\n    expr  string\n    count int\n}\ntype calls []*call\n\nfunc (c calls) Len() int           { return len(c) }\nfunc (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c calls) Less(i, j int) bool { return c[i].count > c[j].count }\n", "Python": "import ast\n\nclass CallCountingVisitor(ast.NodeVisitor):\n\n    def __init__(self):\n        self.calls = {}\n\n    def visit_Call(self, node):\n        if isinstance(node.func, ast.Name):\n            fun_name = node.func.id\n            call_count = self.calls.get(fun_name, 0)\n            self.calls[fun_name] = call_count + 1\n        self.generic_visit(node)\n\nfilename = input('Enter a filename to parse: ')\nwith open(filename, encoding='utf-8') as f:\n    contents = f.read()\nroot = ast.parse(contents, filename=filename) \nvisitor = CallCountingVisitor()\nvisitor.visit(root)\ntop10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10]\nfor name, count in top10:\n    print(name,'called',count,'times')\n"}
{"id": 51028, "name": "Price list behind API", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar minDelta = 1.0\n\nfunc getMaxPrice(prices []float64) float64 {\n    max := prices[0]\n    for i := 1; i < len(prices); i++ {\n        if prices[i] > max {\n            max = prices[i]\n        }\n    }\n    return max\n}\n\nfunc getPRangeCount(prices []float64, min, max float64) int {\n    count := 0\n    for _, price := range prices {\n        if price >= min && price <= max {\n            count++\n        }\n    }\n    return count\n}\n\nfunc get5000(prices []float64, min, max float64, n int) (float64, int) {\n    count := getPRangeCount(prices, min, max)\n    delta := (max - min) / 2\n    for count != n && delta >= minDelta/2 {\n        if count > n {\n            max -= delta\n        } else {\n            max += delta\n        }\n        max = math.Floor(max)\n        count = getPRangeCount(prices, min, max)\n        delta /= 2\n    }\n    return max, count\n}\n\nfunc getAll5000(prices []float64, min, max float64, n int) [][3]float64 {\n    pmax, pcount := get5000(prices, min, max, n)\n    res := [][3]float64{{min, pmax, float64(pcount)}}\n    for pmax < max {\n        pmin := pmax + 1\n        pmax, pcount = get5000(prices, pmin, max, n)\n        if pcount == 0 {\n            log.Fatal(\"Price list from\", pmin, \"has too many with same price.\")\n        }\n        res = append(res, [3]float64{pmin, pmax, float64(pcount)})\n    }\n    return res\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    numPrices := 99000 + rand.Intn(2001)\n    maxPrice := 1e5\n    prices := make([]float64, numPrices) \n    for i := 0; i < numPrices; i++ {\n        prices[i] = float64(rand.Intn(int(maxPrice) + 1))\n    }\n    actualMax := getMaxPrice(prices)\n    fmt.Println(\"Using\", numPrices, \"items with prices from 0 to\", actualMax, \"\\b:\")\n    res := getAll5000(prices, 0, actualMax, 5000)\n    fmt.Println(\"Split into\", len(res), \"bins of approx 5000 elements:\")\n    total := 0\n    for _, r := range res {\n        min := int(r[0])\n        tmx := r[1]\n        if tmx > actualMax {\n            tmx = actualMax\n        }\n        max := int(tmx)\n        cnt := int(r[2])\n        total += cnt\n        fmt.Printf(\"   From %6d to %6d with %4d items\\n\", min, max, cnt)\n    }\n    if total != numPrices {\n        fmt.Println(\"Something went wrong - grand total of\", total, \"doesn't equal\", numPrices, \"\\b!\")\n    }\n}\n", "Python": "import random\n\n\nprice_list_size = random.choice(range(99_000, 101_000))\nprice_list = random.choices(range(100_000), k=price_list_size)\n\ndelta_price = 1     \n\n\ndef get_prange_count(startp, endp):\n    return len([r for r in price_list if startp <= r <= endp])\n\ndef get_max_price():\n    return max(price_list)\n\n\ndef get_5k(mn=0, mx=get_max_price(), num=5_000):\n    \"Binary search for num items between mn and mx, adjusting mx\"\n    count = get_prange_count(mn, mx)\n    delta_mx = (mx - mn) / 2\n    while count != num and delta_mx >= delta_price / 2:\n        mx += -delta_mx if count > num else +delta_mx\n        mx = mx // 1    \n        count, delta_mx = get_prange_count(mn, mx), delta_mx / 2\n    return mx, count\n\ndef get_all_5k(mn=0, mx=get_max_price(), num=5_000):\n    \"Get all non-overlapping ranges\"\n    partmax, partcount = get_5k(mn, mx, num)\n    result = [(mn, partmax, partcount)]\n    while partmax < mx:\n        partmin = partmax + delta_price \n        partmax, partcount = get_5k(partmin, mx, num)\n        assert partcount > 0, \\\n            f\"price_list from {partmin} with too many of the same price\"\n        result.append((partmin, partmax, partcount))\n    return result\n\nif __name__ == '__main__':\n    print(f\"Using {price_list_size} random prices from 0 to {get_max_price()}\")\n    result = get_all_5k()\n    print(f\"Splits into {len(result)} bins of approx 5000 elements\")\n    for mn, mx, count in result:\n        print(f\"  From {mn:8.1f} ... {mx:8.1f} with {count} items.\")\n\n    if len(price_list) != sum(count for mn, mx, count in result):\n        print(\"\\nWhoops! Some items missing:\")\n"}
{"id": 51029, "name": "Cullen and Woodall numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n)\n\nfunc cullen(n uint) *big.Int {\n    one := big.NewInt(1)\n    bn := big.NewInt(int64(n))\n    res := new(big.Int).Lsh(one, n)\n    res.Mul(res, bn)\n    return res.Add(res, one)\n}\n\nfunc woodall(n uint) *big.Int {\n    res := cullen(n)\n    return res.Sub(res, big.NewInt(2))\n}\n\nfunc main() {\n    fmt.Println(\"First 20 Cullen numbers (n * 2^n + 1):\")\n    for n := uint(1); n <= 20; n++ {\n        fmt.Printf(\"%d \", cullen(n))\n    }\n\n    fmt.Println(\"\\n\\nFirst 20 Woodall numbers (n * 2^n - 1):\")\n    for n := uint(1); n <= 20; n++ {\n        fmt.Printf(\"%d \", woodall(n))\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 Cullen primes (in terms of n):\")\n    count := 0\n    for n := uint(1); count < 5; n++ {\n        cn := cullen(n)\n        if cn.ProbablyPrime(15) {\n            fmt.Printf(\"%d \", n)\n            count++\n        }\n    }\n\n    fmt.Println(\"\\n\\nFirst 12 Woodall primes (in terms of n):\")\n    count = 0\n    for n := uint(1); count < 12; n++ {\n        cn := woodall(n)\n        if cn.ProbablyPrime(15) {\n            fmt.Printf(\"%d \", n)\n            count++\n        }\n    }\n    fmt.Println()\n}\n", "Python": "print(\"working...\")\nprint(\"First 20 Cullen numbers:\")\n\nfor n in range(1,21):\n    num = n*pow(2,n)+1\n    print(str(num),end= \" \")\n\nprint()\nprint(\"First 20 Woodall numbers:\")\n\nfor n in range(1,21):\n    num = n*pow(2,n)-1\n    print(str(num),end=\" \")\n\nprint()\nprint(\"done...\")\n"}
{"id": 51030, "name": "Cyclops numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc findFirst(list []int) (int, int) {\n    for i, n := range list {\n        if n > 1e7 {\n            return n, i\n        }\n    }\n    return -1, -1\n}\n\nfunc reverse(s string) string {\n    chars := []rune(s)\n    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n        chars[i], chars[j] = chars[j], chars[i]\n    }\n    return string(chars)\n}\n\nfunc main() {\n    ranges := [][2]int{\n        {0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111},\n    }\n    var cyclops []int\n    for _, r := range ranges {\n        numDigits := len(fmt.Sprint(r[0]))\n        center := numDigits / 2\n        for i := r[0]; i <= r[1]; i++ {\n            digits := rcu.Digits(i, 10)\n            if digits[center] == 0 {\n                count := 0\n                for _, d := range digits {\n                    if d == 0 {\n                        count++\n                    }\n                }\n                if count == 1 {\n                    cyclops = append(cyclops, i)\n                }\n            }\n        }\n    }\n    fmt.Println(\"The first 50 cyclops numbers are:\")\n    for i, n := range cyclops[0:50] {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i := findFirst(cyclops)\n    ns, is := rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n\n    var primes []int\n    for _, n := range cyclops {\n        if rcu.IsPrime(n) {\n            primes = append(primes, n)\n        }\n    }\n    fmt.Println(\"\\n\\nThe first 50 prime cyclops numbers are:\")\n    for i, n := range primes[0:50] {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i = findFirst(primes)\n    ns, is = rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n\n    var bpcyclops []int\n    var ppcyclops []int\n    for _, p := range primes {\n        ps := fmt.Sprint(p)\n        split := strings.Split(ps, \"0\")\n        noMiddle, _ := strconv.Atoi(split[0] + split[1])\n        if rcu.IsPrime(noMiddle) {\n            bpcyclops = append(bpcyclops, p)\n        }\n        if ps == reverse(ps) {\n            ppcyclops = append(ppcyclops, p)\n        }\n    }\n\n    fmt.Println(\"\\n\\nThe first 50 blind prime cyclops numbers are:\")\n    for i, n := range bpcyclops[0:50] {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i = findFirst(bpcyclops)\n    ns, is = rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n\n    fmt.Println(\"\\n\\nThe first 50 palindromic prime cyclops numbers are:\\n\")\n    for i, n := range ppcyclops[0:50] {\n        fmt.Printf(\"%9s \", rcu.Commatize(n))\n        if (i+1)%8 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i = findFirst(ppcyclops)\n    ns, is = rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\n\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n}\n", "Python": "from sympy import isprime\n\n\ndef print50(a, width=8):\n    for i, n in enumerate(a):\n        print(f'{n: {width},}', end='\\n' if (i + 1) % 10 == 0 else '')\n\n\ndef generate_cyclops(maxdig=9):\n    yield 0\n    for d in range((maxdig + 1) // 2):\n        arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))]\n        for left in arr:\n            for right in arr:\n                yield int(left + '0' + right)\n\n\ndef generate_prime_cyclops():\n    for c in generate_cyclops():\n        if isprime(c):\n            yield c\n\n\ndef generate_blind_prime_cyclops():\n    for c in generate_prime_cyclops():\n        cstr = str(c)\n        mid = len(cstr) // 2\n        if isprime(int(cstr[:mid] + cstr[mid+1:])):\n            yield c\n\n\ndef generate_palindromic_cyclops(maxdig=9):\n    for d in range((maxdig + 1) // 2):\n        arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))]\n        for s in arr:\n            yield int(s + '0' + s[::-1])\n\n\ndef generate_palindromic_prime_cyclops():\n    for c in generate_palindromic_cyclops():\n        if isprime(c):\n            yield c\n\n\nprint('The first 50 cyclops numbers are:')\ngen = generate_cyclops()\nprint50([next(gen) for _ in range(50)])\nfor i, c in enumerate(generate_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next cyclops number after 10,000,000 is {c} at position {i:,}.')\n        break\n\nprint('\\nThe first 50 prime cyclops numbers are:')\ngen = generate_prime_cyclops()\nprint50([next(gen) for _ in range(50)])\nfor i, c in enumerate(generate_prime_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next prime cyclops number after 10,000,000 is {c} at position {i:,}.')\n        break\n\nprint('\\nThe first 50 blind prime cyclops numbers are:')\ngen = generate_blind_prime_cyclops()\nprint50([next(gen) for _ in range(50)])\nfor i, c in enumerate(generate_blind_prime_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next blind prime cyclops number after 10,000,000 is {c} at position {i:,}.')\n        break\n\nprint('\\nThe first 50 palindromic prime cyclops numbers are:')\ngen = generate_palindromic_prime_cyclops()\nprint50([next(gen) for _ in range(50)], 11)\nfor i, c in enumerate(generate_palindromic_prime_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next palindromic prime cyclops number after 10,000,000 is {c} at position {i}.')\n        break\n"}
{"id": 51031, "name": "Prime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    c := rcu.PrimeSieve(5505, false)\n    var triples [][3]int\n    fmt.Println(\"Prime triplets: p, p + 2, p + 6 where p < 5,500:\")\n    for i := 3; i < 5500; i += 2 {\n        if !c[i] && !c[i+2] && !c[i+6] {\n            triples = append(triples, [3]int{i, i + 2, i + 6})\n        }\n    }\n    for _, triple := range triples {\n        var t [3]string\n        for i := 0; i < 3; i++ {\n            t[i] = rcu.Commatize(triple[i])\n        }\n        fmt.Printf(\"%5s  %5s  %5s\\n\", t[0], t[1], t[2])\n    }\n    fmt.Println(\"\\nFound\", len(triples), \"such prime triplets.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    for p in range(3, 5499, 2):\n        if not isPrime(p+6):\n            continue\n        if not isPrime(p+2):\n            continue\n        if not isPrime(p):\n            continue\n        print(f'[{p} {p+2} {p+6}]')\n"}
{"id": 51032, "name": "Prime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    c := rcu.PrimeSieve(5505, false)\n    var triples [][3]int\n    fmt.Println(\"Prime triplets: p, p + 2, p + 6 where p < 5,500:\")\n    for i := 3; i < 5500; i += 2 {\n        if !c[i] && !c[i+2] && !c[i+6] {\n            triples = append(triples, [3]int{i, i + 2, i + 6})\n        }\n    }\n    for _, triple := range triples {\n        var t [3]string\n        for i := 0; i < 3; i++ {\n            t[i] = rcu.Commatize(triple[i])\n        }\n        fmt.Printf(\"%5s  %5s  %5s\\n\", t[0], t[1], t[2])\n    }\n    fmt.Println(\"\\nFound\", len(triples), \"such prime triplets.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    for p in range(3, 5499, 2):\n        if not isPrime(p+6):\n            continue\n        if not isPrime(p+2):\n            continue\n        if not isPrime(p):\n            continue\n        print(f'[{p} {p+2} {p+6}]')\n"}
{"id": 51033, "name": "Find Chess960 starting position identifier", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar glyphs = []rune(\"♜♞♝♛♚♖♘♗♕♔\")\nvar names = map[rune]string{'R': \"rook\", 'N': \"knight\", 'B': \"bishop\", 'Q': \"queen\", 'K': \"king\"}\nvar g2lMap = map[rune]string{\n    '♜': \"R\", '♞': \"N\", '♝': \"B\", '♛': \"Q\", '♚': \"K\",\n    '♖': \"R\", '♘': \"N\", '♗': \"B\", '♕': \"Q\", '♔': \"K\",\n}\n\nvar ntable = map[string]int{\"01\": 0, \"02\": 1, \"03\": 2, \"04\": 3, \"12\": 4, \"13\": 5, \"14\": 6, \"23\": 7, \"24\": 8, \"34\": 9}\n\nfunc g2l(pieces string) string {\n    lets := \"\"\n    for _, p := range pieces {\n        lets += g2lMap[p]\n    }\n    return lets\n}\n\nfunc spid(pieces string) int {\n    pieces = g2l(pieces) \n\n    \n    if len(pieces) != 8 {\n        log.Fatal(\"There must be exactly 8 pieces.\")\n    }\n    for _, one := range \"KQ\" {\n        count := 0\n        for _, p := range pieces {\n            if p == one {\n                count++\n            }\n        }\n        if count != 1 {\n            log.Fatalf(\"There must be one %s.\", names[one])\n        }\n    }\n    for _, two := range \"RNB\" {\n        count := 0\n        for _, p := range pieces {\n            if p == two {\n                count++\n            }\n        }\n        if count != 2 {\n            log.Fatalf(\"There must be two %s.\", names[two])\n        }\n    }\n    r1 := strings.Index(pieces, \"R\")\n    r2 := strings.Index(pieces[r1+1:], \"R\") + r1 + 1\n    k := strings.Index(pieces, \"K\")\n    if k < r1 || k > r2 {\n        log.Fatal(\"The king must be between the rooks.\")\n    }\n    b1 := strings.Index(pieces, \"B\")\n    b2 := strings.Index(pieces[b1+1:], \"B\") + b1 + 1\n    if (b2-b1)%2 == 0 {\n        log.Fatal(\"The bishops must be on opposite color squares.\")\n    }\n\n    \n    piecesN := strings.ReplaceAll(pieces, \"Q\", \"\")\n    piecesN = strings.ReplaceAll(piecesN, \"B\", \"\")\n    n1 := strings.Index(piecesN, \"N\")\n    n2 := strings.Index(piecesN[n1+1:], \"N\") + n1 + 1\n    np := fmt.Sprintf(\"%d%d\", n1, n2)\n    N := ntable[np]\n\n    piecesQ := strings.ReplaceAll(pieces, \"B\", \"\")\n    Q := strings.Index(piecesQ, \"Q\")\n\n    D := strings.Index(\"0246\", fmt.Sprintf(\"%d\", b1))\n    L := strings.Index(\"1357\", fmt.Sprintf(\"%d\", b2))\n    if D == -1 {\n        D = strings.Index(\"0246\", fmt.Sprintf(\"%d\", b2))\n        L = strings.Index(\"1357\", fmt.Sprintf(\"%d\", b1))\n    }\n\n    return 96*N + 16*Q + 4*D + L\n}\n\nfunc main() {\n    for _, pieces := range []string{\"♕♘♖♗♗♘♔♖\", \"♖♘♗♕♔♗♘♖\", \"♖♕♘♗♗♔♖♘\", \"♖♘♕♗♗♔♖♘\"} {\n        fmt.Printf(\"%s or %s has SP-ID of %d\\n\", pieces, g2l(pieces), spid(pieces))\n    }\n}\n", "Python": "\ndef validate_position(candidate: str):\n    assert (\n        len(candidate) == 8\n    ), f\"candidate position has invalide len = {len(candidate)}\"\n\n    valid_pieces = {\"R\": 2, \"N\": 2, \"B\": 2, \"Q\": 1, \"K\": 1}\n    assert {\n        piece for piece in candidate\n    } == valid_pieces.keys(), f\"candidate position contains invalid pieces\"\n    for piece_type in valid_pieces.keys():\n        assert (\n            candidate.count(piece_type) == valid_pieces[piece_type]\n        ), f\"piece type '{piece_type}' has invalid count\"\n\n    bishops_pos = [index for index, \n                   value in enumerate(candidate) if value == \"B\"]\n    assert (\n        bishops_pos[0] % 2 != bishops_pos[1] % 2\n    ), f\"candidate position has both bishops in the same color\"\n\n    assert [piece for piece in candidate if piece in \"RK\"] == [\n        \"R\",\n        \"K\",\n        \"R\",\n    ], \"candidate position has K outside of RR\"\n\n\ndef calc_position(start_pos: str):\n    try:\n        validate_position(start_pos)\n    except AssertionError:\n        raise AssertionError\n    \n    subset_step1 = [piece for piece in start_pos if piece not in \"QB\"]\n    nights_positions = [\n        index for index, value in enumerate(subset_step1) if value == \"N\"\n    ]\n    nights_table = {\n        (0, 1): 0,\n        (0, 2): 1,\n        (0, 3): 2,\n        (0, 4): 3,\n        (1, 2): 4,\n        (1, 3): 5,\n        (1, 4): 6,\n        (2, 3): 7,\n        (2, 4): 8,\n        (3, 4): 9,\n    }\n    N = nights_table.get(tuple(nights_positions))\n\n    \n    subset_step2 = [piece for piece in start_pos if piece != \"B\"]\n    Q = subset_step2.index(\"Q\")\n\n    \n    dark_squares = [\n        piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2)\n    ]\n    light_squares = [\n        piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2)\n    ]\n    D = dark_squares.index(\"B\")\n    L = light_squares.index(\"B\")\n\n    return 4 * (4 * (6*N + Q) + D) + L\n\nif __name__ == '__main__':\n    for example in [\"QNRBBNKR\", \"RNBQKBNR\", \"RQNBBKRN\", \"RNQBBKRN\"]:\n        print(f'Position: {example}; Chess960 PID= {calc_position(example)}')\n"}
{"id": 51034, "name": "Conjugate a Latin verb", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nvar endings = [][]string{\n    {\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"},\n    {\"eo\", \"es\", \"et\", \"emus\", \"etis\", \"ent\"},\n    {\"o\", \"is\", \"it\", \"imus\", \"itis\", \"unt\"},\n    {\"io\", \"is\", \"it\", \"imus\", \"itis\", \"iunt\"},\n}\n\nvar infinEndings = []string{\"are\", \"ēre\", \"ere\", \"ire\"}\n\nvar pronouns = []string{\"I\", \"you (singular)\", \"he, she or it\", \"we\", \"you (plural)\", \"they\"}\n\nvar englishEndings = []string{\"\", \"\", \"s\", \"\", \"\", \"\"}\n\nfunc conjugate(infinitive, english string) {\n    letters := []rune(infinitive)\n    le := len(letters)\n    if le < 4 {\n        log.Fatal(\"Infinitive is too short for a regular verb.\")\n    }\n    infinEnding := string(letters[le-3:])\n    conj := -1\n    for i, s := range infinEndings {\n        if s == infinEnding {\n            conj = i\n            break\n        }\n    }\n    if conj == -1 {\n        log.Fatalf(\"Infinitive ending -%s not recognized.\", infinEnding)\n    }\n    stem := string(letters[:le-3])\n    fmt.Printf(\"Present indicative tense, active voice, of '%s' to '%s':\\n\", infinitive, english)\n    for i, ending := range endings[conj] {\n        fmt.Printf(\"    %s%-4s  %s %s%s\\n\", stem, ending, pronouns[i], english, englishEndings[i])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    pairs := [][2]string{{\"amare\", \"love\"}, {\"vidēre\", \"see\"}, {\"ducere\", \"lead\"}, {\"audire\", \"hear\"}}\n    for _, pair := range pairs {\n        conjugate(pair[0], pair[1])\n    }\n}\n", "Python": "\n\n \ndef conjugate(infinitive): \n    if not infinitive[-3:] == \"are\":\n        print(\"'\", infinitive, \"' non prima coniugatio verbi.\\n\", sep='')\n        return False\n    \n    stem = infinitive[0:-3]\n    if len(stem) == 0:\n        print(\"\\'\", infinitive, \"\\' non satis diu conjugatus\\n\", sep='')\n        return False\n\n    print(\"Praesens indicativi temporis of '\", infinitive, \"':\", sep='') \n    for ending in (\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"):\n        print(\"     \", stem, ending, sep='')\n    print()\n \n \nif __name__ == '__main__':\n    for infinitive in (\"amare\", \"dare\", \"qwerty\", \"are\"):\n        conjugate(infinitive)\n"}
{"id": 51035, "name": "Conjugate a Latin verb", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nvar endings = [][]string{\n    {\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"},\n    {\"eo\", \"es\", \"et\", \"emus\", \"etis\", \"ent\"},\n    {\"o\", \"is\", \"it\", \"imus\", \"itis\", \"unt\"},\n    {\"io\", \"is\", \"it\", \"imus\", \"itis\", \"iunt\"},\n}\n\nvar infinEndings = []string{\"are\", \"ēre\", \"ere\", \"ire\"}\n\nvar pronouns = []string{\"I\", \"you (singular)\", \"he, she or it\", \"we\", \"you (plural)\", \"they\"}\n\nvar englishEndings = []string{\"\", \"\", \"s\", \"\", \"\", \"\"}\n\nfunc conjugate(infinitive, english string) {\n    letters := []rune(infinitive)\n    le := len(letters)\n    if le < 4 {\n        log.Fatal(\"Infinitive is too short for a regular verb.\")\n    }\n    infinEnding := string(letters[le-3:])\n    conj := -1\n    for i, s := range infinEndings {\n        if s == infinEnding {\n            conj = i\n            break\n        }\n    }\n    if conj == -1 {\n        log.Fatalf(\"Infinitive ending -%s not recognized.\", infinEnding)\n    }\n    stem := string(letters[:le-3])\n    fmt.Printf(\"Present indicative tense, active voice, of '%s' to '%s':\\n\", infinitive, english)\n    for i, ending := range endings[conj] {\n        fmt.Printf(\"    %s%-4s  %s %s%s\\n\", stem, ending, pronouns[i], english, englishEndings[i])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    pairs := [][2]string{{\"amare\", \"love\"}, {\"vidēre\", \"see\"}, {\"ducere\", \"lead\"}, {\"audire\", \"hear\"}}\n    for _, pair := range pairs {\n        conjugate(pair[0], pair[1])\n    }\n}\n", "Python": "\n\n \ndef conjugate(infinitive): \n    if not infinitive[-3:] == \"are\":\n        print(\"'\", infinitive, \"' non prima coniugatio verbi.\\n\", sep='')\n        return False\n    \n    stem = infinitive[0:-3]\n    if len(stem) == 0:\n        print(\"\\'\", infinitive, \"\\' non satis diu conjugatus\\n\", sep='')\n        return False\n\n    print(\"Praesens indicativi temporis of '\", infinitive, \"':\", sep='') \n    for ending in (\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"):\n        print(\"     \", stem, ending, sep='')\n    print()\n \n \nif __name__ == '__main__':\n    for infinitive in (\"amare\", \"dare\", \"qwerty\", \"are\"):\n        conjugate(infinitive)\n"}
{"id": 51036, "name": "Fortunate numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(379)\n    primorial := big.NewInt(1)\n    var fortunates []int\n    bPrime := new(big.Int)\n    for _, prime := range primes {\n        bPrime.SetUint64(uint64(prime))\n        primorial.Mul(primorial, bPrime)\n        for j := 3; ; j += 2 {\n            jj := big.NewInt(int64(j))\n            bPrime.Add(primorial, jj)\n            if bPrime.ProbablyPrime(5) {\n                fortunates = append(fortunates, j)\n                break\n            }\n        }\n    }\n    m := make(map[int]bool)\n    for _, f := range fortunates {\n        m[f] = true\n    }\n    fortunates = fortunates[:0]\n    for k := range m {\n        fortunates = append(fortunates, k)\n    }\n    sort.Ints(fortunates)\n    fmt.Println(\"After sorting, the first 50 distinct fortunate numbers are:\")\n    for i, f := range fortunates[0:50] {\n        fmt.Printf(\"%3d \", f)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n", "Python": "from sympy.ntheory.generate import primorial\nfrom sympy.ntheory import isprime\n\ndef fortunate_number(n):\n    \n    \n    \n    i = 3\n    primorial_ = primorial(n)\n    while True:\n        if isprime(primorial_ + i):\n            return i\n        i += 2\n\nfortunate_numbers = set()\nfor i in range(1, 76):\n    fortunate_numbers.add(fortunate_number(i))\n\n\nfirst50 = sorted(list(fortunate_numbers))[:50]\n\nprint('The first 50 fortunate numbers:')\nprint(('{:<3} ' * 10).format(*(first50[:10])))\nprint(('{:<3} ' * 10).format(*(first50[10:20])))\nprint(('{:<3} ' * 10).format(*(first50[20:30])))\nprint(('{:<3} ' * 10).format(*(first50[30:40])))\nprint(('{:<3} ' * 10).format(*(first50[40:])))\n"}
{"id": 51037, "name": "Sort an outline at every level", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc sortedOutline(originalOutline []string, ascending bool) {\n    outline := make([]string, len(originalOutline))\n    copy(outline, originalOutline) \n    indent := \"\"\n    del := \"\\x7f\"\n    sep := \"\\x00\"\n    var messages []string\n    if strings.TrimLeft(outline[0], \" \\t\") != outline[0] {\n        fmt.Println(\"    outline structure is unclear\")\n        return\n    }\n    for i := 1; i < len(outline); i++ {\n        line := outline[i]\n        lc := len(line)\n        if strings.HasPrefix(line, \"  \") || strings.HasPrefix(line, \" \\t\") || line[0] == '\\t' {\n            lc2 := len(strings.TrimLeft(line, \" \\t\"))\n            currIndent := line[0 : lc-lc2]\n            if indent == \"\" {\n                indent = currIndent\n            } else {\n                correctionNeeded := false\n                if (strings.ContainsRune(currIndent, '\\t') && !strings.ContainsRune(indent, '\\t')) ||\n                    (!strings.ContainsRune(currIndent, '\\t') && strings.ContainsRune(indent, '\\t')) {\n                    m := fmt.Sprintf(\"corrected inconsistent whitespace use at line %q\", line)\n                    messages = append(messages, indent+m)\n                    correctionNeeded = true\n                } else if len(currIndent)%len(indent) != 0 {\n                    m := fmt.Sprintf(\"corrected inconsistent indent width at line %q\", line)\n                    messages = append(messages, indent+m)\n                    correctionNeeded = true\n                }\n                if correctionNeeded {\n                    mult := int(math.Round(float64(len(currIndent)) / float64(len(indent))))\n                    outline[i] = strings.Repeat(indent, mult) + line[lc-lc2:]\n                }\n            }\n        }\n    }\n    levels := make([]int, len(outline))\n    levels[0] = 1\n    margin := \"\"\n    for level := 1; ; level++ {\n        allPos := true\n        for i := 1; i < len(levels); i++ {\n            if levels[i] == 0 {\n                allPos = false\n                break\n            }\n        }\n        if allPos {\n            break\n        }\n        mc := len(margin)\n        for i := 1; i < len(outline); i++ {\n            if levels[i] == 0 {\n                line := outline[i]\n                if strings.HasPrefix(line, margin) && line[mc] != ' ' && line[mc] != '\\t' {\n                    levels[i] = level\n                }\n            }\n        }\n        margin += indent\n    }\n    lines := make([]string, len(outline))\n    lines[0] = outline[0]\n    var nodes []string\n    for i := 1; i < len(outline); i++ {\n        if levels[i] > levels[i-1] {\n            if len(nodes) == 0 {\n                nodes = append(nodes, outline[i-1])\n            } else {\n                nodes = append(nodes, sep+outline[i-1])\n            }\n        } else if levels[i] < levels[i-1] {\n            j := levels[i-1] - levels[i]\n            nodes = nodes[0 : len(nodes)-j]\n        }\n        if len(nodes) > 0 {\n            lines[i] = strings.Join(nodes, \"\") + sep + outline[i]\n        } else {\n            lines[i] = outline[i]\n        }\n    }\n    if ascending {\n        sort.Strings(lines)\n    } else {\n        maxLen := len(lines[0])\n        for i := 1; i < len(lines); i++ {\n            if len(lines[i]) > maxLen {\n                maxLen = len(lines[i])\n            }\n        }\n        for i := 0; i < len(lines); i++ {\n            lines[i] = lines[i] + strings.Repeat(del, maxLen-len(lines[i]))\n        }\n        sort.Sort(sort.Reverse(sort.StringSlice(lines)))\n    }\n    for i := 0; i < len(lines); i++ {\n        s := strings.Split(lines[i], sep)\n        lines[i] = s[len(s)-1]\n        if !ascending {\n            lines[i] = strings.TrimRight(lines[i], del)\n        }\n    }\n    if len(messages) > 0 {\n        fmt.Println(strings.Join(messages, \"\\n\"))\n        fmt.Println()\n    }\n    fmt.Println(strings.Join(lines, \"\\n\"))\n}\n\nfunc main() {\n    outline := []string{\n        \"zeta\",\n        \"    beta\",\n        \"    gamma\",\n        \"        lambda\",\n        \"        kappa\",\n        \"        mu\",\n        \"    delta\",\n        \"alpha\",\n        \"    theta\",\n        \"    iota\",\n        \"    epsilon\",\n    }\n\n    outline2 := make([]string, len(outline))\n    for i := 0; i < len(outline); i++ {\n        outline2[i] = strings.ReplaceAll(outline[i], \"    \", \"\\t\")\n    }\n\n    outline3 := []string{\n        \"alpha\",\n        \"    epsilon\",\n        \"        iota\",\n        \"    theta\",\n        \"zeta\",\n        \"    beta\",\n        \"    delta\",\n        \"    gamma\",\n        \"    \\t   kappa\", \n        \"        lambda\",\n        \"        mu\",\n    }\n\n    outline4 := []string{\n        \"zeta\",\n        \"    beta\",\n        \"   gamma\",\n        \"        lambda\",\n        \"         kappa\",\n        \"        mu\",\n        \"    delta\",\n        \"alpha\",\n        \"    theta\",\n        \"    iota\",\n        \"    epsilon\",\n    }\n\n    fmt.Println(\"Four space indented outline, ascending sort:\")\n    sortedOutline(outline, true)\n\n    fmt.Println(\"\\nFour space indented outline, descending sort:\")\n    sortedOutline(outline, false)\n\n    fmt.Println(\"\\nTab indented outline, ascending sort:\")\n    sortedOutline(outline2, true)\n\n    fmt.Println(\"\\nTab indented outline, descending sort:\")\n    sortedOutline(outline2, false)\n\n    fmt.Println(\"\\nFirst unspecified outline, ascending sort:\")\n    sortedOutline(outline3, true)\n\n    fmt.Println(\"\\nFirst unspecified outline, descending sort:\")\n    sortedOutline(outline3, false)\n\n    fmt.Println(\"\\nSecond unspecified outline, ascending sort:\")\n    sortedOutline(outline4, true)\n\n    fmt.Println(\"\\nSecond unspecified outline, descending sort:\")\n    sortedOutline(outline4, false)\n}\n", "Python": "\n\n\nfrom itertools import chain, product, takewhile, tee\nfrom functools import cmp_to_key, reduce\n\n\n\n\n\n\n\ndef sortedOutline(cmp):\n    \n    def go(outlineText):\n        indentTuples = indentTextPairs(\n            outlineText.splitlines()\n        )\n        return bindLR(\n            minimumIndent(enumerate(indentTuples))\n        )(lambda unitIndent: Right(\n            outlineFromForest(\n                unitIndent,\n                nest(foldTree(\n                    lambda x: lambda xs: Node(x)(\n                        sorted(xs, key=cmp_to_key(cmp))\n                    )\n                )(Node('')(\n                    forestFromIndentLevels(\n                        indentLevelsFromLines(\n                            unitIndent\n                        )(indentTuples)\n                    )\n                )))\n            )\n        ))\n    return go\n\n\n\n\ndef main():\n    \n\n    ascending = comparing(root)\n    descending = flip(ascending)\n\n    spacedOutline = \n\n    tabbedOutline = \n\n    confusedOutline = \n\n    raggedOutline = \n\n    def displaySort(kcmp):\n        \n        k, cmp = kcmp\n        return [\n            tested(cmp, k, label)(\n                outline\n            ) for (label, outline) in [\n                ('4-space indented', spacedOutline),\n                ('tab indented', tabbedOutline),\n                ('Unknown 1', confusedOutline),\n                ('Unknown 2', raggedOutline)\n            ]\n        ]\n\n    def tested(cmp, cmpName, outlineName):\n        \n        def go(outline):\n            print('\\n' + outlineName, cmpName + ':')\n            either(print)(print)(\n                sortedOutline(cmp)(outline)\n            )\n        return go\n\n    \n    ap([\n        displaySort\n    ])([\n        (\"(A -> Z)\", ascending),\n        (\"(Z -> A)\", descending)\n    ])\n\n\n\n\n\ndef forestFromIndentLevels(tuples):\n    \n    def go(xs):\n        if xs:\n            intIndent, v = xs[0]\n            firstTreeLines, rest = span(\n                lambda x: intIndent < x[0]\n            )(xs[1:])\n            return [Node(v)(go(firstTreeLines))] + go(rest)\n        else:\n            return []\n    return go(tuples)\n\n\n\n\ndef indentLevelsFromLines(indentUnit):\n    \n    def go(xs):\n        w = len(indentUnit)\n        return [\n            (len(x[0]) // w, x[1])\n            for x in xs\n        ]\n    return go\n\n\n\ndef indentTextPairs(xs):\n    \n    def indentAndText(s):\n        pfx = list(takewhile(lambda c: c.isspace(), s))\n        return (pfx, s[len(pfx):])\n    return [indentAndText(x) for x in xs]\n\n\n\ndef outlineFromForest(tabString, forest):\n    \n    def go(indent):\n        def serial(node):\n            return [indent + root(node)] + list(\n                concatMap(\n                    go(tabString + indent)\n                )(nest(node))\n            )\n        return serial\n    return '\\n'.join(\n        concatMap(go(''))(forest)\n    )\n\n\n\n\n\n\ndef minimumIndent(indexedPrefixes):\n    \n    (xs, ts) = tee(indexedPrefixes)\n    (ys, zs) = tee(ts)\n\n    def mindentLR(charSet):\n        if list(charSet):\n            def w(x):\n                return len(x[1][0])\n\n            unit = min(filter(w, ys), key=w)[1][0]\n            unitWidth = len(unit)\n\n            def widthCheck(a, ix):\n                \n                wx = len(ix[1][0])\n                return a if (a or 0 == wx) else (\n                    ix[0] if 0 != wx % unitWidth else a\n                )\n            oddLine = reduce(widthCheck, zs, None)\n            return Left(\n                'Inconsistent indentation width at line ' + (\n                    str(1 + oddLine)\n                )\n            ) if oddLine else Right(''.join(unit))\n        else:\n            return Right('')\n\n    def tabSpaceCheck(a, ics):\n        \n        charSet = a[0].union(set(ics[1][0]))\n        return a if a[1] else (\n            charSet, ics[0] if 1 < len(charSet) else None\n        )\n\n    indentCharSet, mbAnomalyLine = reduce(\n        tabSpaceCheck, xs, (set([]), None)\n    )\n    return bindLR(\n        Left(\n            'Mixed indent characters found in line ' + str(\n                1 + mbAnomalyLine\n            )\n        ) if mbAnomalyLine else Right(list(indentCharSet))\n    )(mindentLR)\n\n\n\n\n\ndef Left(x):\n    \n    return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n\ndef Right(x):\n    \n    return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}\n\n\n\ndef ap(fs):\n    \n    def go(xs):\n        return [\n            f(x) for (f, x)\n            in product(fs, xs)\n        ]\n    return go\n\n\n\ndef bindLR(m):\n    \n    def go(mf):\n        return (\n            mf(m.get('Right')) if None is m.get('Left') else m\n        )\n    return go\n\n\n\ndef comparing(f):\n    \n    def go(x, y):\n        fx = f(x)\n        fy = f(y)\n        return -1 if fx < fy else (1 if fx > fy else 0)\n    return go\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef either(fl):\n    \n    return lambda fr: lambda e: fl(e['Left']) if (\n        None is e['Right']\n    ) else fr(e['Right'])\n\n\n\ndef flip(f):\n    \n    return lambda a, b: f(b, a)\n\n\n\ndef foldTree(f):\n    \n    def go(node):\n        return f(root(node))([\n            go(x) for x in nest(node)\n        ])\n    return go\n\n\n\ndef nest(t):\n    \n    return t.get('nest')\n\n\n\ndef root(t):\n    \n    return t.get('root')\n\n\n\ndef span(p):\n    \n    def match(ab):\n        b = ab[1]\n        return not b or not p(b[0])\n\n    def f(ab):\n        a, b = ab\n        return a + [b[0]], b[1:]\n\n    def go(xs):\n        return until(match)(f)(([], xs))\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51038, "name": "Smallest multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n)\n\nfunc lcm(n int) *big.Int {\n    lcm := big.NewInt(1)\n    t := new(big.Int)\n    for _, p := range rcu.Primes(n) {\n        f := p\n        for f*p <= n {\n            f *= p\n        }\n        lcm.Mul(lcm, t.SetUint64(uint64(f)))\n    }\n    return lcm\n}\n\nfunc main() {\n    fmt.Println(\"The LCMs of the numbers 1 to N inclusive is:\")\n    for _, i := range []int{10, 20, 200, 2000} {\n        fmt.Printf(\"%4d: %s\\n\", i, lcm(i))\n    }\n}\n", "Python": "\n\nfrom math import gcd\nfrom functools import reduce\n\n\ndef lcm(a, b):\n    \n    return 0 if 0 == a or 0 == b else (\n        abs(a * b) // gcd(a, b)\n    )\n\n\nfor i in [10, 20, 200, 2000]:\n    print(str(i) + ':', reduce(lcm, range(1, i + 1)))\n"}
{"id": 51039, "name": "Meissel–Mertens constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc contains(a []int, f int) bool {\n    for _, e := range a {\n        if e == f {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const euler = 0.57721566490153286\n    primes := rcu.Primes(1 << 31)\n    pc := len(primes)\n    sum := 0.0\n    fmt.Println(\"Primes added         M\")\n    fmt.Println(\"------------  --------------\")\n    for i, p := range primes {\n        rp := 1.0 / float64(p)\n        sum += math.Log(1.0-rp) + rp\n        c := i + 1\n        if (c%1e7) == 0 || c == pc {\n            fmt.Printf(\"%11s   %0.12f\\n\", rcu.Commatize(c), sum+euler)\n        }\n    }\n}\n", "Python": "\n\nfrom math import log\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    Euler = 0.57721566490153286\n    m = 0\n    for x in range(2, 10_000_000):\n        if isPrime(x):\n            m += log(1-(1/x)) + (1/x)\n\n    print(\"MM =\", Euler + m)\n"}
{"id": 51040, "name": "Unicode strings", "Go": "    var i int\n    var u rune\n    for i, u = range \"voilà\" {\n        fmt.Println(i, u)\n    }\n", "Python": "\n\n\nu = 'abcdé'\nprint(ord(u[-1]))\n"}
{"id": 51041, "name": "Quadrat special primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc commas(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(15999)\n    fmt.Println(\"Quadrat special primes under 16,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Sqrt\")\n    lastQuadSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 16000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastQuadSpecial\n        if isSquare(gap) {\n            sqrt := int(math.Sqrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastQuadSpecial), commas(i), commas(gap), sqrt)\n            lastQuadSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 2\n    j = 1\n    print(2, end = \" \");\n    while True:\n        while True:\n            if isPrime(p + j*j):\n                break\n            j += 1\n        p += j*j\n        if p > 16000:\n            break\n        print(p, end = \" \");\n        j = 1\n"}
{"id": 51042, "name": "Quadrat special primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc commas(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(15999)\n    fmt.Println(\"Quadrat special primes under 16,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Sqrt\")\n    lastQuadSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 16000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastQuadSpecial\n        if isSquare(gap) {\n            sqrt := int(math.Sqrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastQuadSpecial), commas(i), commas(gap), sqrt)\n            lastQuadSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 2\n    j = 1\n    print(2, end = \" \");\n    while True:\n        while True:\n            if isPrime(p + j*j):\n                break\n            j += 1\n        p += j*j\n        if p > 16000:\n            break\n        print(p, end = \" \");\n        j = 1\n"}
{"id": 51043, "name": "Bioinformatics_Global alignment", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\n\nfunc getPerms(input []string) [][]string {\n    perms := [][]string{input}\n    le := len(input)\n    a := make([]string, le)\n    copy(a, input)\n    n := le - 1\n    fact := factorial(n + 1)\n\n    for c := 1; c < fact; c++ {\n        i := n - 1\n        j := n\n        for i >= 0 && a[i] > a[i+1] {\n            i--\n        }\n        if i == -1 {\n            i = n\n        }\n        for a[j] < a[i] {\n            j--\n        }\n        a[i], a[j] = a[j], a[i]\n        j = n\n        i++\n        if i == n+1 {\n            i = 0\n        }\n        for i < j {\n            a[i], a[j] = a[j], a[i]\n            i++\n            j--\n        }\n        b := make([]string, le)\n        copy(b, a)\n        perms = append(perms, b)\n    }\n    return perms\n}\n\n\nfunc distinct(slist []string) []string {\n    distinctSet := make(map[string]int, len(slist))\n    i := 0\n    for _, s := range slist {\n        if _, ok := distinctSet[s]; !ok {\n            distinctSet[s] = i\n            i++\n        }\n    }\n    result := make([]string, len(distinctSet))\n    for s, i := range distinctSet {\n        result[i] = s\n    }\n    return result\n}\n\n\nfunc printCounts(seq string) {\n    bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}}\n    for _, c := range seq {\n        for _, base := range bases {\n            if c == base[0] {\n                base[1]++\n            }\n        }\n    }\n    sum := 0\n    fmt.Println(\"\\nNucleotide counts for\", seq, \"\\b:\\n\")\n    for _, base := range bases {\n        fmt.Printf(\"%10c%12d\\n\", base[0], base[1])\n        sum += int(base[1])\n    }\n    le := len(seq)\n    fmt.Printf(\"%10s%12d\\n\", \"Other\", le-sum)\n    fmt.Printf(\"  ____________________\\n%14s%8d\\n\", \"Total length\", le)\n}\n\n\nfunc headTailOverlap(s1, s2 string) int {\n    for start := 0; ; start++ {\n        ix := strings.IndexByte(s1[start:], s2[0])\n        if ix == -1 {\n            return 0\n        } else {\n            start += ix\n        }\n        if strings.HasPrefix(s2, s1[start:]) {\n            return len(s1) - start\n        }\n    }\n}\n\n\nfunc deduplicate(slist []string) []string {\n    var filtered []string\n    arr := distinct(slist)\n    for i, s1 := range arr {\n        withinLarger := false\n        for j, s2 := range arr {\n            if j != i && strings.Contains(s2, s1) {\n                withinLarger = true\n                break\n            }\n        }\n        if !withinLarger {\n            filtered = append(filtered, s1)\n        }\n    }\n    return filtered\n}\n\n\nfunc shortestCommonSuperstring(slist []string) string {\n    ss := deduplicate(slist)\n    shortestSuper := strings.Join(ss, \"\")\n    for _, perm := range getPerms(ss) {\n        sup := perm[0]\n        for i := 0; i < len(ss)-1; i++ {\n            overlapPos := headTailOverlap(perm[i], perm[i+1])\n            sup += perm[i+1][overlapPos:]\n        }\n        if len(sup) < len(shortestSuper) {\n            shortestSuper = sup\n        }\n    }\n    return shortestSuper\n}\n\nfunc main() {\n    testSequences := [][]string{\n        {\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"},\n        {\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"},\n        {\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"},\n        {\n            \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n            \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n            \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n            \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n            \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n            \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n        },\n    }\n\n    for _, test := range testSequences {\n        scs := shortestCommonSuperstring(test)\n        printCounts(scs)\n    }\n}\n", "Python": "import os\n\nfrom collections import Counter\nfrom functools import reduce\nfrom itertools import permutations\n\nBASES = (\"A\", \"C\", \"G\", \"T\")\n\n\ndef deduplicate(sequences):\n    \n    sequences = set(sequences)\n    duplicates = set()\n\n    for s, t in permutations(sequences, 2):\n        if s != t and s in t:\n            duplicates.add(s)\n\n    return sequences - duplicates\n\n\ndef smash(s, t):\n    \n    for i in range(len(s)):\n        if t.startswith(s[i:]):\n            return s[:i] + t\n    return s + t\n\n\ndef shortest_superstring(sequences):\n    \n    sequences = deduplicate(sequences)\n    shortest = \"\".join(sequences)\n\n    for perm in permutations(sequences):\n        superstring = reduce(smash, perm)\n        if len(superstring) < len(shortest):\n            shortest = superstring\n\n    return shortest\n\n\ndef shortest_superstrings(sequences):\n    \n    sequences = deduplicate(sequences)\n\n    shortest = set([\"\".join(sequences)])\n    shortest_length = sum(len(s) for s in sequences)\n\n    for perm in permutations(sequences):\n        superstring = reduce(smash, perm)\n        superstring_length = len(superstring)\n        if superstring_length < shortest_length:\n            shortest.clear()\n            shortest.add(superstring)\n            shortest_length = superstring_length\n        elif superstring_length == shortest_length:\n            shortest.add(superstring)\n\n    return shortest\n\n\ndef print_report(sequence):\n    \n    buf = [f\"Nucleotide counts for {sequence}:\\n\"]\n\n    counts = Counter(sequence)\n    for base in BASES:\n        buf.append(f\"{base:>10}{counts.get(base, 0):>12}\")\n\n    other = sum(v for k, v in counts.items() if k not in BASES)\n    buf.append(f\"{'Other':>10}{other:>12}\")\n\n    buf.append(\" \" * 5 + \"_\" * 17)\n    buf.append(f\"{'Total length':>17}{sum(counts.values()):>5}\")\n\n    print(os.linesep.join(buf), \"\\n\")\n\n\nif __name__ == \"__main__\":\n    test_cases = [\n        (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"),\n        (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"),\n        (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"),\n        (\n            \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n            \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n            \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n            \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n            \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n            \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n        ),\n    ]\n\n    for case in test_cases:\n        for superstring in shortest_superstrings(case):\n            print_report(superstring)\n\n    \n    \n    \n    \n    \n    \n"}
{"id": 51044, "name": "Strassen's algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\ntype Matrix [][]float64\n\nfunc (m Matrix) rows() int { return len(m) }\nfunc (m Matrix) cols() int { return len(m[0]) }\n\nfunc (m Matrix) add(m2 Matrix) Matrix {\n    if m.rows() != m2.rows() || m.cols() != m2.cols() {\n        log.Fatal(\"Matrices must have the same dimensions.\")\n    }\n    c := make(Matrix, m.rows())\n    for i := 0; i < m.rows(); i++ {\n        c[i] = make([]float64, m.cols())\n        for j := 0; j < m.cols(); j++ {\n            c[i][j] = m[i][j] + m2[i][j]\n        }\n    }\n    return c\n}\n\nfunc (m Matrix) sub(m2 Matrix) Matrix {\n    if m.rows() != m2.rows() || m.cols() != m2.cols() {\n        log.Fatal(\"Matrices must have the same dimensions.\")\n    }\n    c := make(Matrix, m.rows())\n    for i := 0; i < m.rows(); i++ {\n        c[i] = make([]float64, m.cols())\n        for j := 0; j < m.cols(); j++ {\n            c[i][j] = m[i][j] - m2[i][j]\n        }\n    }\n    return c\n}\n\nfunc (m Matrix) mul(m2 Matrix) Matrix {\n    if m.cols() != m2.rows() {\n        log.Fatal(\"Cannot multiply these matrices.\")\n    }\n    c := make(Matrix, m.rows())\n    for i := 0; i < m.rows(); i++ {\n        c[i] = make([]float64, m2.cols())\n        for j := 0; j < m2.cols(); j++ {\n            for k := 0; k < m2.rows(); k++ {\n                c[i][j] += m[i][k] * m2[k][j]\n            }\n        }\n    }\n    return c\n}\n\nfunc (m Matrix) toString(p int) string {\n    s := make([]string, m.rows())\n    pow := math.Pow(10, float64(p))\n    for i := 0; i < m.rows(); i++ {\n        t := make([]string, m.cols())\n        for j := 0; j < m.cols(); j++ {\n            r := math.Round(m[i][j]*pow) / pow\n            t[j] = fmt.Sprintf(\"%g\", r)\n            if t[j] == \"-0\" {\n                t[j] = \"0\"\n            }\n        }\n        s[i] = fmt.Sprintf(\"%v\", t)\n    }\n    return fmt.Sprintf(\"%v\", s)\n}\n\nfunc params(r, c int) [4][6]int {\n    return [4][6]int{\n        {0, r, 0, c, 0, 0},\n        {0, r, c, 2 * c, 0, c},\n        {r, 2 * r, 0, c, r, 0},\n        {r, 2 * r, c, 2 * c, r, c},\n    }\n}\n\nfunc toQuarters(m Matrix) [4]Matrix {\n    r := m.rows() / 2\n    c := m.cols() / 2\n    p := params(r, c)\n    var quarters [4]Matrix\n    for k := 0; k < 4; k++ {\n        q := make(Matrix, r)\n        for i := p[k][0]; i < p[k][1]; i++ {\n            q[i-p[k][4]] = make([]float64, c)\n            for j := p[k][2]; j < p[k][3]; j++ {\n                q[i-p[k][4]][j-p[k][5]] = m[i][j]\n            }\n        }\n        quarters[k] = q\n    }\n    return quarters\n}\n\nfunc fromQuarters(q [4]Matrix) Matrix {\n    r := q[0].rows()\n    c := q[0].cols()\n    p := params(r, c)\n    r *= 2\n    c *= 2\n    m := make(Matrix, r)\n    for i := 0; i < c; i++ {\n        m[i] = make([]float64, c)\n    }\n    for k := 0; k < 4; k++ {\n        for i := p[k][0]; i < p[k][1]; i++ {\n            for j := p[k][2]; j < p[k][3]; j++ {\n                m[i][j] = q[k][i-p[k][4]][j-p[k][5]]\n            }\n        }\n    }\n    return m\n}\n\nfunc strassen(a, b Matrix) Matrix {\n    if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() {\n        log.Fatal(\"Matrices must be square and of equal size.\")\n    }\n    if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 {\n        log.Fatal(\"Size of matrices must be a power of two.\")\n    }\n    if a.rows() == 1 {\n        return a.mul(b)\n    }\n    qa := toQuarters(a)\n    qb := toQuarters(b)\n    p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3]))\n    p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3]))\n    p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1]))\n    p4 := strassen(qa[0].add(qa[1]), qb[3])\n    p5 := strassen(qa[0], qb[1].sub(qb[3]))\n    p6 := strassen(qa[3], qb[2].sub(qb[0]))\n    p7 := strassen(qa[2].add(qa[3]), qb[0])\n    var q [4]Matrix\n    q[0] = p1.add(p2).sub(p4).add(p6)\n    q[1] = p4.add(p5)\n    q[2] = p6.add(p7)\n    q[3] = p2.sub(p3).add(p5).sub(p7)\n    return fromQuarters(q)\n}\n\nfunc main() {\n    a := Matrix{{1, 2}, {3, 4}}\n    b := Matrix{{5, 6}, {7, 8}}\n    c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}}\n    d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24},\n        {3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}}\n    e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}\n    f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}\n    fmt.Println(\"Using 'normal' matrix multiplication:\")\n    fmt.Printf(\"  a * b = %v\\n\", a.mul(b))\n    fmt.Printf(\"  c * d = %v\\n\", c.mul(d).toString(6))\n    fmt.Printf(\"  e * f = %v\\n\", e.mul(f))\n    fmt.Println(\"\\nUsing 'Strassen' matrix multiplication:\")\n    fmt.Printf(\"  a * b = %v\\n\", strassen(a, b))\n    fmt.Printf(\"  c * d = %v\\n\", strassen(c, d).toString(6))\n    fmt.Printf(\"  e * f = %v\\n\", strassen(e, f))\n}\n", "Python": "\n\nfrom __future__ import annotations\nfrom itertools import chain\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\n\n\nclass Shape(NamedTuple):\n    rows: int\n    cols: int\n\n\nclass Matrix(List):\n    \n\n    @classmethod\n    def block(cls, blocks) -> Matrix:\n        \n        m = Matrix()\n        for hblock in blocks:\n            for row in zip(*hblock):\n                m.append(list(chain.from_iterable(row)))\n\n        return m\n\n    def dot(self, b: Matrix) -> Matrix:\n        \n        assert self.shape.cols == b.shape.rows\n        m = Matrix()\n        for row in self:\n            new_row = []\n            for c in range(len(b[0])):\n                col = [b[r][c] for r in range(len(b))]\n                new_row.append(sum(x * y for x, y in zip(row, col)))\n            m.append(new_row)\n        return m\n\n    def __matmul__(self, b: Matrix) -> Matrix:\n        return self.dot(b)\n\n    def __add__(self, b: Matrix) -> Matrix:\n        \n        assert self.shape == b.shape\n        rows, cols = self.shape\n        return Matrix(\n            [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]\n        )\n\n    def __sub__(self, b: Matrix) -> Matrix:\n        \n        assert self.shape == b.shape\n        rows, cols = self.shape\n        return Matrix(\n            [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)]\n        )\n\n    def strassen(self, b: Matrix) -> Matrix:\n        \n        rows, cols = self.shape\n\n        assert rows == cols, \"matrices must be square\"\n        assert self.shape == b.shape, \"matrices must be the same shape\"\n        assert rows and (rows & rows - 1) == 0, \"shape must be a power of 2\"\n\n        if rows == 1:\n            return self.dot(b)\n\n        p = rows // 2  \n\n        a11 = Matrix([n[:p] for n in self[:p]])\n        a12 = Matrix([n[p:] for n in self[:p]])\n        a21 = Matrix([n[:p] for n in self[p:]])\n        a22 = Matrix([n[p:] for n in self[p:]])\n\n        b11 = Matrix([n[:p] for n in b[:p]])\n        b12 = Matrix([n[p:] for n in b[:p]])\n        b21 = Matrix([n[:p] for n in b[p:]])\n        b22 = Matrix([n[p:] for n in b[p:]])\n\n        m1 = (a11 + a22).strassen(b11 + b22)\n        m2 = (a21 + a22).strassen(b11)\n        m3 = a11.strassen(b12 - b22)\n        m4 = a22.strassen(b21 - b11)\n        m5 = (a11 + a12).strassen(b22)\n        m6 = (a21 - a11).strassen(b11 + b12)\n        m7 = (a12 - a22).strassen(b21 + b22)\n\n        c11 = m1 + m4 - m5 + m7\n        c12 = m3 + m5\n        c21 = m2 + m4\n        c22 = m1 - m2 + m3 + m6\n\n        return Matrix.block([[c11, c12], [c21, c22]])\n\n    def round(self, ndigits: Optional[int] = None) -> Matrix:\n        return Matrix([[round(i, ndigits) for i in row] for row in self])\n\n    @property\n    def shape(self) -> Shape:\n        cols = len(self[0]) if self else 0\n        return Shape(len(self), cols)\n\n\ndef examples():\n    a = Matrix(\n        [\n            [1, 2],\n            [3, 4],\n        ]\n    )\n    b = Matrix(\n        [\n            [5, 6],\n            [7, 8],\n        ]\n    )\n    c = Matrix(\n        [\n            [1, 1, 1, 1],\n            [2, 4, 8, 16],\n            [3, 9, 27, 81],\n            [4, 16, 64, 256],\n        ]\n    )\n    d = Matrix(\n        [\n            [4, -3, 4 / 3, -1 / 4],\n            [-13 / 3, 19 / 4, -7 / 3, 11 / 24],\n            [3 / 2, -2, 7 / 6, -1 / 4],\n            [-1 / 6, 1 / 4, -1 / 6, 1 / 24],\n        ]\n    )\n    e = Matrix(\n        [\n            [1, 2, 3, 4],\n            [5, 6, 7, 8],\n            [9, 10, 11, 12],\n            [13, 14, 15, 16],\n        ]\n    )\n    f = Matrix(\n        [\n            [1, 0, 0, 0],\n            [0, 1, 0, 0],\n            [0, 0, 1, 0],\n            [0, 0, 0, 1],\n        ]\n    )\n\n    print(\"Naive matrix multiplication:\")\n    print(f\"  a * b = {a @ b}\")\n    print(f\"  c * d = {(c @ d).round()}\")\n    print(f\"  e * f = {e @ f}\")\n\n    print(\"Strassen's matrix multiplication:\")\n    print(f\"  a * b = {a.strassen(b)}\")\n    print(f\"  c * d = {c.strassen(d).round()}\")\n    print(f\"  e * f = {e.strassen(f)}\")\n\n\nif __name__ == \"__main__\":\n    examples()\n"}
{"id": 51045, "name": "Topic variable", "Go": "package main\n\nimport (\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"text/template\"\n)\n\nfunc sqr(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(f*f, 'f', -1, 64)\n}\n\nfunc sqrt(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)\n}\n\nfunc main() {\n    f := template.FuncMap{\"sqr\": sqr, \"sqrt\": sqrt}\n    t := template.Must(template.New(\"\").Funcs(f).Parse(`. = {{.}}\nsquare: {{sqr .}}\nsquare root: {{sqrt .}}\n`))\n    t.Execute(os.Stdout, \"3\")\n}\n", "Python": ">>> 3\n3\n>>> _*_, _**0.5\n(9, 1.7320508075688772)\n>>>\n"}
{"id": 51046, "name": "Topic variable", "Go": "package main\n\nimport (\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"text/template\"\n)\n\nfunc sqr(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(f*f, 'f', -1, 64)\n}\n\nfunc sqrt(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)\n}\n\nfunc main() {\n    f := template.FuncMap{\"sqr\": sqr, \"sqrt\": sqrt}\n    t := template.Must(template.New(\"\").Funcs(f).Parse(`. = {{.}}\nsquare: {{sqr .}}\nsquare root: {{sqrt .}}\n`))\n    t.Execute(os.Stdout, \"3\")\n}\n", "Python": ">>> 3\n3\n>>> _*_, _**0.5\n(9, 1.7320508075688772)\n>>>\n"}
{"id": 51047, "name": "Add a variable to a class instance at runtime", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n", "Python": "class empty(object):\n    pass\ne = empty()\n"}
{"id": 51048, "name": "Faces from a mesh", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\n\nfunc contains(s []int, f int) bool {\n    for _, e := range s {\n        if e == f {\n            return true\n        }\n    }\n    return false\n}\n\n\nfunc sliceEqual(s1, s2 []int) bool {\n    for i := 0; i < len(s1); i++ {\n        if s1[i] != s2[i] {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\n\nfunc perimEqual(p1, p2 []int) bool {\n    le := len(p1)\n    if le != len(p2) {\n        return false\n    }\n    for _, p := range p1 {\n        if !contains(p2, p) {\n            return false\n        }\n    }\n    \n    c := make([]int, le)\n    copy(c, p1)\n    for r := 0; r < 2; r++ {\n        for i := 0; i < le; i++ {\n            if sliceEqual(c, p2) {\n                return true\n            }\n            \n            t := c[le-1]\n            copy(c[1:], c[0:le-1])\n            c[0] = t\n        }\n        \n        reverse(c)\n    }\n    return false\n}\n\ntype edge [2]int\n\n\nfunc faceToPerim(face []edge) []int {\n    \n    le := len(face)\n    if le == 0 {\n        return nil\n    }\n    edges := make([]edge, le)\n    for i := 0; i < le; i++ {\n        \n        if face[i][1] <= face[i][0] {\n            return nil\n        }\n        edges[i] = face[i]\n    }\n    \n    sort.Slice(edges, func(i, j int) bool {\n        if edges[i][0] != edges[j][0] {\n            return edges[i][0] < edges[j][0]\n        }\n        return edges[i][1] < edges[j][1]\n    })\n    var perim []int\n    first, last := edges[0][0], edges[0][1]\n    perim = append(perim, first, last)\n    \n    copy(edges, edges[1:])\n    edges = edges[0 : le-1]\n    le--\nouter:\n    for le > 0 {\n        for i, e := range edges {\n            found := false\n            if e[0] == last {\n                perim = append(perim, e[1])\n                last, found = e[1], true\n            } else if e[1] == last {\n                perim = append(perim, e[0])\n                last, found = e[0], true\n            }\n            if found {\n                \n                copy(edges[i:], edges[i+1:])\n                edges = edges[0 : le-1]\n                le--\n                if last == first {\n                    if le == 0 {\n                        break outer\n                    } else {\n                        return nil\n                    }\n                }\n                continue outer\n            }\n        }\n    }\n    return perim[0 : len(perim)-1]\n}\n\nfunc main() {\n    fmt.Println(\"Perimeter format equality checks:\")\n    areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8})\n    fmt.Printf(\"  Q == R is %t\\n\", areEqual)\n    areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18})\n    fmt.Printf(\"  U == V is %t\\n\", areEqual)\n    e := []edge{{7, 11}, {1, 11}, {1, 7}}\n    f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}}\n    g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}}\n    h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}}\n    fmt.Println(\"\\nEdge to perimeter format translations:\")\n    for i, face := range [][]edge{e, f, g, h} {\n        perim := faceToPerim(face)\n        if perim == nil {\n            fmt.Printf(\"  %c => Invalid edge format\\n\", i + 'E')\n        } else {\n            fmt.Printf(\"  %c => %v\\n\", i + 'E', perim)\n        }\n    }\n}\n", "Python": "def perim_equal(p1, p2):\n    \n    if len(p1) != len(p2) or set(p1) != set(p2):\n        return False\n    if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):\n        return True\n    p2 = p2[::-1] \n    return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))\n\ndef edge_to_periphery(e):\n    edges = sorted(e)\n    p = list(edges.pop(0)) if edges else []\n    last = p[-1] if p else None\n    while edges:\n        for n, (i, j) in enumerate(edges):\n            if i == last:\n                p.append(j)\n                last = j\n                edges.pop(n)\n                break\n            elif j == last:\n                p.append(i)\n                last = i\n                edges.pop(n)\n                break\n        else:\n            \n            return \">>>Error! Invalid edge format<<<\"\n    return p[:-1]\n\nif __name__ == '__main__':\n    print('Perimeter format equality checks:')\n    for eq_check in [\n            { 'Q': (8, 1, 3),\n              'R': (1, 3, 8)},\n            { 'U': (18, 8, 14, 10, 12, 17, 19),\n              'V': (8, 14, 10, 12, 17, 19, 18)} ]:\n        (n1, p1), (n2, p2) = eq_check.items()\n        eq = '==' if perim_equal(p1, p2) else '!='\n        print(' ', n1, eq, n2)\n\n    print('\\nEdge to perimeter format translations:')\n    edge_d = {\n     'E': {(1, 11), (7, 11), (1, 7)},\n     'F': {(11, 23), (1, 17), (17, 23), (1, 11)},\n     'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)},\n     'H': {(1, 3), (9, 11), (3, 11), (1, 11)}\n            }\n    for name, edges in edge_d.items():\n        print(f\"  {name}: {edges}\\n     -> {edge_to_periphery(edges)}\")\n"}
{"id": 51049, "name": "Resistance network calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc argmax(m [][]float64, i int) int {\n    col := make([]float64, len(m))\n    max, maxx := -1.0, -1\n    for x := 0; x < len(m); x++ {\n        col[x] = math.Abs(m[x][i])\n        if col[x] > max {\n            max = col[x]\n            maxx = x\n        }\n    }\n    return maxx\n}\n\nfunc gauss(m [][]float64) []float64 {\n    n, p := len(m), len(m[0])\n    for i := 0; i < n; i++ {\n        k := i + argmax(m[i:n], i)\n        m[i], m[k] = m[k], m[i]\n        t := 1 / m[i][i]\n        for j := i + 1; j < p; j++ {\n            m[i][j] *= t\n        }\n        for j := i + 1; j < n; j++ {\n            t = m[j][i]\n            for l := i + 1; l < p; l++ {\n                m[j][l] -= t * m[i][l]\n            }\n        }\n    }\n    for i := n - 1; i >= 0; i-- {\n        for j := 0; j < i; j++ {\n            m[j][p-1] -= m[j][i] * m[i][p-1]\n        }\n    }\n    col := make([]float64, len(m))\n    for x := 0; x < len(m); x++ {\n        col[x] = m[x][p-1]\n    }\n    return col\n}\n\nfunc network(n, k0, k1 int, s string) float64 {\n    m := make([][]float64, n)\n    for i := 0; i < n; i++ {\n        m[i] = make([]float64, n+1)\n    }\n    for _, resistor := range strings.Split(s, \"|\") {\n        rarr := strings.Fields(resistor)\n        a, _ := strconv.Atoi(rarr[0])\n        b, _ := strconv.Atoi(rarr[1])\n        ri, _ := strconv.Atoi(rarr[2])\n        r := 1.0 / float64(ri)\n        m[a][a] += r\n        m[b][b] += r\n        if a > 0 {\n            m[a][b] -= r\n        }\n        if b > 0 {\n            m[b][a] -= r\n        }\n    }\n    m[k0][k0] = 1\n    m[k1][n] = 1\n    return gauss(m)[k1]\n}\n\nfunc main() {\n    var fa [4]float64\n    fa[0] = network(7, 0, 1, \"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8\")\n    fa[1] = network(9, 0, 8, \"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1\")\n    fa[2] = network(16, 0, 15, \"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1\")\n    fa[3] = network(4, 0, 3, \"0 1 150|0 2 50|1 3 300|2 3 250\")\n    for _, f := range fa {\n        fmt.Printf(\"%.6g\\n\", f)\n    }\n}\n", "Python": "from fractions import Fraction\n\ndef gauss(m):\n\tn, p = len(m), len(m[0])\n\tfor i in range(n):\n\t\tk = max(range(i, n), key = lambda x: abs(m[x][i]))\n\t\tm[i], m[k] = m[k], m[i]\n\t\tt = 1 / m[i][i]\n\t\tfor j in range(i + 1, p): m[i][j] *= t\n\t\tfor j in range(i + 1, n):\n\t\t\tt = m[j][i]\n\t\t\tfor k in range(i + 1, p): m[j][k] -= t * m[i][k]\n\tfor i in range(n - 1, -1, -1):\n\t\tfor j in range(i): m[j][-1] -= m[j][i] * m[i][-1]\n\treturn [row[-1] for row in m]\n\ndef network(n,k0,k1,s):\n\tm = [[0] * (n+1) for i in range(n)]\n\tresistors = s.split('|')\n\tfor resistor in resistors:\n\t\ta,b,r = resistor.split(' ')\n\t\ta,b,r = int(a), int(b), Fraction(1,int(r))\n\t\tm[a][a] += r\n\t\tm[b][b] += r\n\t\tif a > 0: m[a][b] -= r\n\t\tif b > 0: m[b][a] -= r\n\tm[k0][k0] = Fraction(1, 1)\n\tm[k1][-1] = Fraction(1, 1)\n\treturn gauss(m)[k1]\n\nassert 10             == network(7,0,1,\"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8\")\nassert 3/2            == network(3*3,0,3*3-1,\"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1\")\nassert Fraction(13,7) == network(4*4,0,4*4-1,\"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1\")\nassert 180            == network(4,0,3,\"0 1 150|0 2 50|1 3 300|2 3 250\")\n"}
{"id": 51050, "name": "Bioinformatics_Subsequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"regexp\"\n    \"time\"\n)\n\nconst base = \"ACGT\"\n\nfunc findDnaSubsequence(dnaSize, chunkSize int) {\n    dnaSeq := make([]byte, dnaSize)\n    for i := 0; i < dnaSize; i++ {\n        dnaSeq[i] = base[rand.Intn(4)]\n    }\n    dnaStr := string(dnaSeq)\n    dnaSubseq := make([]byte, 4)\n    for i := 0; i < 4; i++ {\n        dnaSubseq[i] = base[rand.Intn(4)]\n    }\n    dnaSubstr := string(dnaSubseq)\n    fmt.Println(\"DNA sequnence:\")\n    for i := chunkSize; i <= len(dnaStr); i += chunkSize {\n        start := i - chunkSize\n        fmt.Printf(\"%3d..%3d: %s\\n\", start+1, i, dnaStr[start:i])\n    }\n    fmt.Println(\"\\nSubsequence to locate:\", dnaSubstr)\n    var r = regexp.MustCompile(dnaSubstr)\n    var matches = r.FindAllStringIndex(dnaStr, -1)\n    if len(matches) == 0 {\n        fmt.Println(\"No matches found.\")\n    } else {\n        fmt.Println(\"Matches found at the following indices:\")\n        for _, m := range matches {\n            fmt.Printf(\"%3d..%-3d\\n\", m[0]+1, m[1])\n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    findDnaSubsequence(200, 20)\n    fmt.Println()\n    findDnaSubsequence(600, 40)\n}\n", "Python": " \nfrom random import choice\nimport regex as re \nimport time\n\ndef generate_sequence(n: int ) -> str:\n    return \"\".join([ choice(['A','C','G','T']) for _ in range(n) ])\n\ndef dna_findall(needle: str, haystack: str) -> None:\n\n    if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0:\n        print(\"No matches found\")\n    else:\n        print(f\"Found {needle} at the following indices: \")\n        for match in re.finditer(needle, haystack, overlapped=True):\n            print(f\"{match.start()}:{match.end()} \")\n\ndna_seq = generate_sequence(200)\nsample_seq = generate_sequence(4)\n\nc = 1\nfor i in dna_seq:\n    print(i, end=\"\") if c % 20 != 0 else print(f\"{i}\")\n    c += 1\nprint(f\"\\nSearch Sample: {sample_seq}\")\n\ndna_findall(sample_seq, dna_seq)\n"}
{"id": 51051, "name": "Nested templated data", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"text/template\"\n)\n\nfunc main() {\n    const t = `[[[{{index .P 1}}, {{index .P 2}}],\n  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n  {{index .P 5}}]]\n`\n    type S struct {\n        P map[int]string\n    }\n\n    var s S\n    s.P = map[int]string{\n        0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n        4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n    }\n    tmpl := template.Must(template.New(\"\").Parse(t))\n    tmpl.Execute(os.Stdout, s)\n\n    var unused []int\n    for k, _ := range s.P {\n        if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n            unused = append(unused, k)\n        }\n    }\n    sort.Ints(unused)\n    fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}\n", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n"}
{"id": 51052, "name": "Bitmap_Read an image through a pipe", "Go": "package main\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    c := exec.Command(\"convert\", \"Unfilledcirc.png\", \"-depth\", \"1\", \"ppm:-\")\n    pipe, err := c.StdoutPipe()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = c.Start(); err != nil {\n        log.Fatal(err)\n    }\n    b, err := raster.ReadPpmFrom(pipe)\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = b.WritePpmFile(\"Unfilledcirc.ppm\"); err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "\n\nfrom PIL import Image\n\n\n\nim = Image.open(\"boxes_1.jpg\")\nim.save(\"boxes_1v2.ppm\")\n"}
{"id": 51053, "name": "Bitmap_Read an image through a pipe", "Go": "package main\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    c := exec.Command(\"convert\", \"Unfilledcirc.png\", \"-depth\", \"1\", \"ppm:-\")\n    pipe, err := c.StdoutPipe()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = c.Start(); err != nil {\n        log.Fatal(err)\n    }\n    b, err := raster.ReadPpmFrom(pipe)\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = b.WritePpmFile(\"Unfilledcirc.ppm\"); err != nil {\n        log.Fatal(err)\n    }\n}\n", "Python": "\n\nfrom PIL import Image\n\n\n\nim = Image.open(\"boxes_1.jpg\")\nim.save(\"boxes_1v2.ppm\")\n"}
{"id": 51054, "name": "Memory layout of a data structure", "Go": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9  rs232p9 = 1 << iota \n\tRD9                      \n\tTD9                      \n\tDTR9                     \n\tSG9                      \n\tDSR9                     \n\tRTS9                     \n\tCTS9                     \n\tRI9                      \n)\n\nfunc main() {\n\t\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}\n", "Python": "from ctypes import Structure, c_int\n\nrs232_9pin  = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg\"\n                \"_11 SCD SCS STD TC  SRD RC\"\n                \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]\n"}
{"id": 51055, "name": "Memory layout of a data structure", "Go": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9  rs232p9 = 1 << iota \n\tRD9                      \n\tTD9                      \n\tDTR9                     \n\tSG9                      \n\tDSR9                     \n\tRTS9                     \n\tCTS9                     \n\tRI9                      \n)\n\nfunc main() {\n\t\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}\n", "Python": "from ctypes import Structure, c_int\n\nrs232_9pin  = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg\"\n                \"_11 SCD SCS STD TC  SRD RC\"\n                \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]\n"}
{"id": 51056, "name": "Sum of two adjacent numbers are primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(math.Log(1e7) * 1e7 * 1.2) \n    primes := rcu.Primes(limit)\n    fmt.Println(\"The first 20 pairs of natural numbers whose sum is prime are:\")\n    for i := 1; i <= 20; i++ {\n        p := primes[i]\n        hp := p / 2\n        fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n    }\n    fmt.Println(\"\\nThe 10 millionth such pair is:\")\n    p := primes[1e7]\n    hp := p / 2\n    fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == \"__main__\":\n    n = 0\n    num = 0\n\n    print('The first 20 pairs of numbers whose sum is prime:') \n    while True:\n        n += 1\n        suma = 2*n+1\n        if isPrime(suma):\n            num += 1\n            if num < 21:\n                print('{:2}'.format(n), \"+\", '{:2}'.format(n+1), \"=\", '{:2}'.format(suma))\n            else:\n                break\n"}
{"id": 51057, "name": "Mastermind", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n", "Python": "import random\n\n\ndef encode(correct, guess):\n    output_arr = [''] * len(correct)\n\n    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):\n        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'\n\n    return ''.join(output_arr)\n\n\ndef safe_int_input(prompt, min_val, max_val):\n    while True:\n        user_input = input(prompt)\n\n        try:\n            user_input = int(user_input)\n        except ValueError:\n            continue\n\n        if min_val <= user_input <= max_val:\n            return user_input\n\n\ndef play_game():\n    print(\"Welcome to Mastermind.\")\n    print(\"You will need to guess a random code.\")\n    print(\"For each guess, you will receive a hint.\")\n    print(\"In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.\")\n    print()\n\n    number_of_letters = safe_int_input(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n    code_length = safe_int_input(\"Select a length for the code (4-10): \", 4, 10)\n\n    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]\n    code = ''.join(random.choices(letters, k=code_length))\n    guesses = []\n\n    while True:\n        print()\n        guess = input(f\"Enter a guess of length {code_length} ({letters}): \").upper().strip()\n\n        if len(guess) != code_length or any([char not in letters for char in guess]):\n            continue\n        elif guess == code:\n            print(f\"\\nYour guess {guess} was correct!\")\n            break\n        else:\n            guesses.append(f\"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}\")\n\n        for i_guess in guesses:\n            print(\"------------------------------------\")\n            print(i_guess)\n        print(\"------------------------------------\")\n\n\nif __name__ == '__main__':\n    play_game()\n"}
{"id": 51058, "name": "Mastermind", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n", "Python": "import random\n\n\ndef encode(correct, guess):\n    output_arr = [''] * len(correct)\n\n    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):\n        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'\n\n    return ''.join(output_arr)\n\n\ndef safe_int_input(prompt, min_val, max_val):\n    while True:\n        user_input = input(prompt)\n\n        try:\n            user_input = int(user_input)\n        except ValueError:\n            continue\n\n        if min_val <= user_input <= max_val:\n            return user_input\n\n\ndef play_game():\n    print(\"Welcome to Mastermind.\")\n    print(\"You will need to guess a random code.\")\n    print(\"For each guess, you will receive a hint.\")\n    print(\"In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.\")\n    print()\n\n    number_of_letters = safe_int_input(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n    code_length = safe_int_input(\"Select a length for the code (4-10): \", 4, 10)\n\n    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]\n    code = ''.join(random.choices(letters, k=code_length))\n    guesses = []\n\n    while True:\n        print()\n        guess = input(f\"Enter a guess of length {code_length} ({letters}): \").upper().strip()\n\n        if len(guess) != code_length or any([char not in letters for char in guess]):\n            continue\n        elif guess == code:\n            print(f\"\\nYour guess {guess} was correct!\")\n            break\n        else:\n            guesses.append(f\"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}\")\n\n        for i_guess in guesses:\n            print(\"------------------------------------\")\n            print(i_guess)\n        print(\"------------------------------------\")\n\n\nif __name__ == '__main__':\n    play_game()\n"}
{"id": 51059, "name": "Maximum difference between adjacent elements of list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3}\n    maxDiff := -1.0\n    var maxPairs [][2]float64\n    for i := 1; i < len(list); i++ {\n        diff := math.Abs(list[i-1] - list[i])\n        if diff > maxDiff {\n            maxDiff = diff\n            maxPairs = [][2]float64{{list[i-1], list[i]}}\n        } else if diff == maxDiff {\n            maxPairs = append(maxPairs, [2]float64{list[i-1], list[i]})\n        }\n    }\n    fmt.Println(\"The maximum difference between adjacent pairs of the list is:\", maxDiff)\n    fmt.Println(\"The pairs with this difference are:\", maxPairs)\n}\n", "Python": "\n\n\n\ndef maxDeltas(ns):\n    \n    pairs = [\n        (abs(a - b), (a, b)) for a, b\n        in zip(ns, ns[1:])\n    ]\n    delta = max(pairs, key=lambda ab: ab[0])[0]\n\n    return [\n        ab for ab in pairs\n        if delta == ab[0]\n    ]\n\n\n\n\ndef main():\n    \n\n    maxPairs = maxDeltas([\n        1, 8, 2, -3, 0, 1, 1, -2.3, 0,\n        5.5, 8, 6, 2, 9, 11, 10, 3\n    ])\n\n    for ab in maxPairs:\n        print(ab)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51060, "name": "Composite numbers k with no single digit factors whose factors are all substrings of k", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    count := 0\n    k := 11 * 11\n    var res []int\n    for count < 20 {\n        if k%3 == 0 || k%5 == 0 || k%7 == 0 {\n            k += 2\n            continue\n        }\n        factors := rcu.PrimeFactors(k)\n        if len(factors) > 1 {\n            s := strconv.Itoa(k)\n            includesAll := true\n            prev := -1\n            for _, f := range factors {\n                if f == prev {\n                    continue\n                }\n                fs := strconv.Itoa(f)\n                if strings.Index(s, fs) == -1 {\n                    includesAll = false\n                    break\n                }\n            }\n            if includesAll {\n                res = append(res, k)\n                count++\n            }\n        }\n        k += 2\n    }\n    for _, e := range res[0:10] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n    for _, e := range res[10:20] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n}\n", "Python": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n    if n < 10 or isprime(n):\n        return False\n    strn = str(n)\n    pfacs = factorint(n).keys()\n    return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n    if contains_its_prime_factors_all_over_7(n):\n        found += 1\n        print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n        if found == 20:\n            break\n"}
{"id": 51061, "name": "Composite numbers k with no single digit factors whose factors are all substrings of k", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    count := 0\n    k := 11 * 11\n    var res []int\n    for count < 20 {\n        if k%3 == 0 || k%5 == 0 || k%7 == 0 {\n            k += 2\n            continue\n        }\n        factors := rcu.PrimeFactors(k)\n        if len(factors) > 1 {\n            s := strconv.Itoa(k)\n            includesAll := true\n            prev := -1\n            for _, f := range factors {\n                if f == prev {\n                    continue\n                }\n                fs := strconv.Itoa(f)\n                if strings.Index(s, fs) == -1 {\n                    includesAll = false\n                    break\n                }\n            }\n            if includesAll {\n                res = append(res, k)\n                count++\n            }\n        }\n        k += 2\n    }\n    for _, e := range res[0:10] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n    for _, e := range res[10:20] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n}\n", "Python": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n    if n < 10 or isprime(n):\n        return False\n    strn = str(n)\n    pfacs = factorint(n).keys()\n    return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n    if contains_its_prime_factors_all_over_7(n):\n        found += 1\n        print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n        if found == 20:\n            break\n"}
{"id": 51062, "name": "Functional coverage tree", "Go": "package main\n\nimport \"fmt\"\n\ntype FCNode struct {\n    name     string\n    weight   int\n    coverage float64\n    children []*FCNode\n    parent   *FCNode\n}\n\nfunc newFCN(name string, weight int, coverage float64) *FCNode {\n    return &FCNode{name, weight, coverage, nil, nil}\n}\n\nfunc (n *FCNode) addChildren(nodes []*FCNode) {\n    for _, node := range nodes {\n        node.parent = n\n        n.children = append(n.children, node)\n    }\n    n.updateCoverage()\n}\n\nfunc (n *FCNode) setCoverage(value float64) {\n    if n.coverage != value {\n        n.coverage = value\n        \n        if n.parent != nil {\n            n.parent.updateCoverage()\n        }\n    }\n}\n\nfunc (n *FCNode) updateCoverage() {\n    v1 := 0.0\n    v2 := 0\n    for _, node := range n.children {\n        v1 += float64(node.weight) * node.coverage\n        v2 += node.weight\n    }\n    n.setCoverage(v1 / float64(v2))\n}\n\nfunc (n *FCNode) show(level int) {\n    indent := level * 4\n    nl := len(n.name) + indent\n    fmt.Printf(\"%*s%*s  %3d   | %8.6f |\\n\", nl, n.name, 32-nl, \"|\", n.weight, n.coverage)\n    if len(n.children) == 0 {\n        return\n    }\n    for _, child := range n.children {\n        child.show(level + 1)\n    }\n}\n\nvar houses = []*FCNode{\n    newFCN(\"house1\", 40, 0),\n    newFCN(\"house2\", 60, 0),\n}\n\nvar house1 = []*FCNode{\n    newFCN(\"bedrooms\", 1, 0.25),\n    newFCN(\"bathrooms\", 1, 0),\n    newFCN(\"attic\", 1, 0.75),\n    newFCN(\"kitchen\", 1, 0.1),\n    newFCN(\"living_rooms\", 1, 0),\n    newFCN(\"basement\", 1, 0),\n    newFCN(\"garage\", 1, 0),\n    newFCN(\"garden\", 1, 0.8),\n}\n\nvar house2 = []*FCNode{\n    newFCN(\"upstairs\", 1, 0),\n    newFCN(\"groundfloor\", 1, 0),\n    newFCN(\"basement\", 1, 0),\n}\n\nvar h1Bathrooms = []*FCNode{\n    newFCN(\"bathroom1\", 1, 0.5),\n    newFCN(\"bathroom2\", 1, 0),\n    newFCN(\"outside_lavatory\", 1, 1),\n}\n\nvar h1LivingRooms = []*FCNode{\n    newFCN(\"lounge\", 1, 0),\n    newFCN(\"dining_room\", 1, 0),\n    newFCN(\"conservatory\", 1, 0),\n    newFCN(\"playroom\", 1, 1),\n}\n\nvar h2Upstairs = []*FCNode{\n    newFCN(\"bedrooms\", 1, 0),\n    newFCN(\"bathroom\", 1, 0),\n    newFCN(\"toilet\", 1, 0),\n    newFCN(\"attics\", 1, 0.6),\n}\n\nvar h2Groundfloor = []*FCNode{\n    newFCN(\"kitchen\", 1, 0),\n    newFCN(\"living_rooms\", 1, 0),\n    newFCN(\"wet_room_&_toilet\", 1, 0),\n    newFCN(\"garage\", 1, 0),\n    newFCN(\"garden\", 1, 0.9),\n    newFCN(\"hot_tub_suite\", 1, 1),\n}\n\nvar h2Basement = []*FCNode{\n    newFCN(\"cellars\", 1, 1),\n    newFCN(\"wine_cellar\", 1, 1),\n    newFCN(\"cinema\", 1, 0.75),\n}\n\nvar h2UpstairsBedrooms = []*FCNode{\n    newFCN(\"suite_1\", 1, 0),\n    newFCN(\"suite_2\", 1, 0),\n    newFCN(\"bedroom_3\", 1, 0),\n    newFCN(\"bedroom_4\", 1, 0),\n}\n\nvar h2GroundfloorLivingRooms = []*FCNode{\n    newFCN(\"lounge\", 1, 0),\n    newFCN(\"dining_room\", 1, 0),\n    newFCN(\"conservatory\", 1, 0),\n    newFCN(\"playroom\", 1, 0),\n}\n\nfunc main() {\n    cleaning := newFCN(\"cleaning\", 1, 0)\n\n    house1[1].addChildren(h1Bathrooms)\n    house1[4].addChildren(h1LivingRooms)\n    houses[0].addChildren(house1)\n\n    h2Upstairs[0].addChildren(h2UpstairsBedrooms)\n    house2[0].addChildren(h2Upstairs)\n    h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)\n    house2[1].addChildren(h2Groundfloor)\n    house2[2].addChildren(h2Basement)\n    houses[1].addChildren(house2)\n\n    cleaning.addChildren(houses)\n    topCoverage := cleaning.coverage\n    fmt.Printf(\"TOP COVERAGE = %8.6f\\n\\n\", topCoverage)\n    fmt.Println(\"NAME HIERARCHY                 | WEIGHT | COVERAGE |\")\n    cleaning.show(0)\n\n    h2Basement[2].setCoverage(1) \n    diff := cleaning.coverage - topCoverage\n    fmt.Println(\"\\nIf the coverage of the Cinema node were increased from 0.75 to 1\")\n    fmt.Print(\"the top level coverage would increase by \")\n    fmt.Printf(\"%8.6f to %8.6f\\n\", diff, topCoverage+diff)\n    h2Basement[2].setCoverage(0.75) \n}\n", "Python": "from itertools import zip_longest\n\n\nfc2 = \n\nNAME, WT, COV = 0, 1, 2\n\ndef right_type(txt):\n    try:\n        return float(txt)\n    except ValueError:\n        return txt\n\ndef commas_to_list(the_list, lines, start_indent=0):\n    \n    for n, line in lines:\n        indent = 0\n        while line.startswith(' ' * (4 * indent)):\n            indent += 1\n        indent -= 1\n        fields = [right_type(f) for f in line.strip().split(',')]\n        if indent == start_indent:\n            the_list.append(fields)\n        elif indent > start_indent:\n            lst = [fields]\n            sub = commas_to_list(lst, lines, indent)\n            the_list[-1] = (the_list[-1], lst)\n            if sub not in (None, ['']) :\n                the_list.append(sub)\n        else:\n            return fields if fields else None\n    return None\n\n\ndef pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']):\n    \n    lhs = ' ' * (4 * indent)\n    for item in lst:\n        if type(item) != tuple:\n            name, *rest = item\n            print(widths[0] % (lhs + name), end='|')\n            for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):\n                if type(item) == str:\n                    width = width[:-1] + 's'\n                print(width % item, end='|')\n            print()\n        else:\n            item, children = item\n            name, *rest = item\n            print(widths[0] % (lhs + name), end='|')\n            for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):\n                if type(item) == str:\n                    width = width[:-1] + 's'\n                print(width % item, end='|')\n            print()\n            pptreefields(children, indent+1)\n\n\ndef default_field(node_list):\n    node_list[WT] = node_list[WT] if node_list[WT] else 1.0\n    node_list[COV] = node_list[COV] if node_list[COV] else 0.0\n\ndef depth_first(tree, visitor=default_field):\n    for item in tree:\n        if type(item) == tuple:\n            item, children = item\n            depth_first(children, visitor)\n        visitor(item)\n            \n\ndef covercalc(tree):\n    \n    sum_covwt, sum_wt = 0, 0\n    for item in tree:\n        if type(item) == tuple:\n            item, children = item\n            item[COV] = covercalc(children)\n        sum_wt  += item[WT]\n        sum_covwt += item[COV] * item[WT]\n    cov = sum_covwt / sum_wt\n    return cov\n\nif __name__ == '__main__':        \n    lstc = []\n    commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\\n'))))\n    \n    \n    \n    depth_first(lstc)\n    \n    \n    print('\\n\\nTOP COVERAGE = %f\\n' % covercalc(lstc))\n    depth_first(lstc)\n    pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)\n"}
{"id": 51063, "name": "Smallest enclosing circle problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype Point struct{ x, y float64 }\n\ntype Circle struct {\n    c Point\n    r float64\n}\n\n\nfunc (p Point) String() string { return fmt.Sprintf(\"(%f, %f)\", p.x, p.y) }\n\n\nfunc distSq(a, b Point) float64 {\n    return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)\n}\n\n\nfunc getCircleCenter(bx, by, cx, cy float64) Point {\n    b := bx*bx + by*by\n    c := cx*cx + cy*cy\n    d := bx*cy - by*cx\n    return Point{(cy*b - by*c) / (2 * d), (bx*c - cx*b) / (2 * d)}\n}\n\n\nfunc (ci Circle) contains(p Point) bool {\n    return distSq(ci.c, p) <= ci.r*ci.r\n}\n\n\nfunc (ci Circle) encloses(ps []Point) bool {\n    for _, p := range ps {\n        if !ci.contains(p) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (ci Circle) String() string { return fmt.Sprintf(\"{%v, %f}\", ci.c, ci.r) }\n\n\nfunc circleFrom3(a, b, c Point) Circle {\n    i := getCircleCenter(b.x-a.x, b.y-a.y, c.x-a.x, c.y-a.y)\n    i.x += a.x\n    i.y += a.y\n    return Circle{i, math.Sqrt(distSq(i, a))}\n}\n\n\nfunc circleFrom2(a, b Point) Circle {\n    c := Point{(a.x + b.x) / 2, (a.y + b.y) / 2}\n    return Circle{c, math.Sqrt(distSq(a, b)) / 2}\n}\n\n\nfunc secTrivial(rs []Point) Circle {\n    size := len(rs)\n    if size > 3 {\n        log.Fatal(\"There shouldn't be more than 3 points.\")\n    }\n    if size == 0 {\n        return Circle{Point{0, 0}, 0}\n    }\n    if size == 1 {\n        return Circle{rs[0], 0}\n    }\n    if size == 2 {\n        return circleFrom2(rs[0], rs[1])\n    }\n    for i := 0; i < 2; i++ {\n        for j := i + 1; j < 3; j++ {\n            c := circleFrom2(rs[i], rs[j])\n            if c.encloses(rs) {\n                return c\n            }\n        }\n    }\n    return circleFrom3(rs[0], rs[1], rs[2])\n}\n\n\nfunc welzlHelper(ps, rs []Point, n int) Circle {\n    rc := make([]Point, len(rs))\n    copy(rc, rs) \n    if n == 0 || len(rc) == 3 {\n        return secTrivial(rc)\n    }\n    idx := rand.Intn(n)\n    p := ps[idx]\n    ps[idx], ps[n-1] = ps[n-1], p\n    d := welzlHelper(ps, rc, n-1)\n    if d.contains(p) {\n        return d\n    }\n    rc = append(rc, p)\n    return welzlHelper(ps, rc, n-1)\n}\n\n\nfunc welzl(ps []Point) Circle {\n    var pc = make([]Point, len(ps))\n    copy(pc, ps)\n    rand.Shuffle(len(pc), func(i, j int) {\n        pc[i], pc[j] = pc[j], pc[i]\n    })\n    return welzlHelper(pc, []Point{}, len(pc))\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := [][]Point{\n        {Point{0, 0}, Point{0, 1}, Point{1, 0}},\n        {Point{5, -2}, Point{-3, -2}, Point{-2, 5}, Point{1, 6}, Point{0, 2}},\n    }\n    for _, test := range tests {\n        fmt.Println(welzl(test))\n    }\n}\n", "Python": "import numpy as np\n\nclass ProjectorStack:\n    \n    def __init__(self, vec):\n        self.vs = np.array(vec)\n        \n    def push(self, v):\n        if len(self.vs) == 0:\n            self.vs = np.array([v])\n        else:\n            self.vs = np.append(self.vs, [v], axis=0)\n        return self\n    \n    def pop(self):\n        if len(self.vs) > 0:\n            ret, self.vs = self.vs[-1], self.vs[:-1]\n            return ret\n    \n    def __mul__(self, v):\n        s = np.zeros(len(v))\n        for vi in self.vs:\n            s = s + vi * np.dot(vi, v)\n        return s\n    \nclass GaertnerBoundary:\n    \n    def __init__(self, pts):\n        self.projector = ProjectorStack([])\n        self.centers, self.square_radii = np.array([]), np.array([])\n        self.empty_center = np.array([np.NaN for _ in pts[0]])\n\n\ndef push_if_stable(bound, pt):\n    if len(bound.centers) == 0:\n        bound.square_radii = np.append(bound.square_radii, 0.0)\n        bound.centers = np.array([pt])\n        return True\n    q0, center = bound.centers[0], bound.centers[-1]\n    C, r2  = center - q0, bound.square_radii[-1]\n    Qm, M = pt - q0, bound.projector\n    Qm_bar = M * Qm\n    residue, e = Qm - Qm_bar, sqdist(Qm, C) - r2\n    z, tol = 2 * sqnorm(residue), np.finfo(float).eps * max(r2, 1.0)\n    isstable = np.abs(z) > tol\n    if isstable:\n        center_new  = center + (e / z) * residue\n        r2new = r2 + (e * e) / (2 * z)\n        bound.projector.push(residue / np.linalg.norm(residue))\n        bound.centers = np.append(bound.centers, np.array([center_new]), axis=0)\n        bound.square_radii = np.append(bound.square_radii, r2new)\n    return isstable\n\ndef pop(bound):\n    n = len(bound.centers)\n    bound.centers = bound.centers[:-1]\n    bound.square_radii = bound.square_radii[:-1]\n    if n >= 2:\n        bound.projector.pop()\n    return bound\n\n\nclass NSphere:\n    def __init__(self, c, sqr):\n        self.center = np.array(c)\n        self.sqradius = sqr\n\ndef isinside(pt, nsphere, atol=1e-6, rtol=0.0):\n    r2, R2 = sqdist(pt, nsphere.center), nsphere.sqradius\n    return r2 <= R2 or np.isclose(r2, R2, atol=atol**2,rtol=rtol**2)\n\ndef allinside(pts, nsphere, atol=1e-6, rtol=0.0):\n    for p in pts:\n        if not isinside(p, nsphere, atol, rtol):\n            return False\n    return True\n\ndef move_to_front(pts, i):\n    pt = pts[i]\n    for j in range(len(pts)):\n        pts[j], pt = pt, np.array(pts[j])\n        if j == i:\n            break\n    return pts\n\ndef dist(p1, p2):\n    return np.linalg.norm(p1 - p2)\n\ndef sqdist(p1, p2):\n    return sqnorm(p1 - p2)\n\ndef sqnorm(p):\n    return np.sum(np.array([x * x for x in p]))\n\ndef ismaxlength(bound):\n    len(bound.centers) == len(bound.empty_center) + 1\n\ndef makeNSphere(bound):\n    if len(bound.centers) == 0: \n        return NSphere(bound.empty_center, 0.0)\n    return NSphere(bound.centers[-1], bound.square_radii[-1])\n\ndef _welzl(pts, pos, bdry):\n    support_count, nsphere = 0, makeNSphere(bdry)\n    if ismaxlength(bdry):\n        return nsphere, 0\n    for i in range(pos):\n        if not isinside(pts[i], nsphere):\n            isstable = push_if_stable(bdry, pts[i])\n            if isstable:\n                nsphere, s = _welzl(pts, i, bdry)\n                pop(bdry)\n                move_to_front(pts, i)\n                support_count = s + 1\n    return nsphere, support_count\n\ndef find_max_excess(nsphere, pts, k1):\n    err_max, k_max = -np.Inf, k1 - 1\n    for (k, pt) in enumerate(pts[k_max:]):\n        err = sqdist(pt, nsphere.center) - nsphere.sqradius\n        if  err > err_max:\n            err_max, k_max = err, k + k1\n    return err_max, k_max - 1\n\ndef welzl(points, maxiterations=2000):\n    pts, eps = np.array(points, copy=True), np.finfo(float).eps\n    bdry, t = GaertnerBoundary(pts), 1\n    nsphere, s = _welzl(pts, t, bdry)\n    for i in range(maxiterations):\n        e, k = find_max_excess(nsphere, pts, t + 1)\n        if e <= eps:\n            break\n        pt = pts[k]\n        push_if_stable(bdry, pt)\n        nsphere_new, s_new = _welzl(pts, s, bdry)\n        pop(bdry)\n        move_to_front(pts, k)\n        nsphere = nsphere_new\n        t, s = s + 1, s_new + 1\n    return nsphere\n\nif __name__ == '__main__':\n    TESTDATA =[\n        np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]]),\n        np.array([[5.0, -2.0], [-3.0, -2.0], [-2.0, 5.0], [1.0, 6.0], [0.0, 2.0]]),\n        np.array([[2.0, 4.0, -1.0], [1.0, 5.0, -3.0], [8.0, -4.0, 1.0], [3.0, 9.0, -5.0]]),\n        np.random.normal(size=(8, 5))\n    ]\n    for test in TESTDATA:\n        nsphere = welzl(test)\n        print(\"For points: \", test)\n        print(\"    Center is at: \", nsphere.center)\n        print(\"    Radius is: \", np.sqrt(nsphere.sqradius), \"\\n\")\n"}
{"id": 51064, "name": "Brace expansion using ranges", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc sign(n int) int {\n    switch {\n    case n < 0:\n        return -1\n    case n > 0:\n        return 1\n    }\n    return 0\n}\n\nfunc abs(n int) int {\n    if n < 0 {\n        return -n\n    }\n    return n\n}\n\nfunc parseRange(r string) []string {\n    if r == \"\" {\n        return []string{\"{}\"} \n    }\n    sp := strings.Split(r, \"..\")\n    if len(sp) == 1 {\n        return []string{\"{\" + r + \"}\"} \n    }\n    sta := sp[0]\n    end := sp[1]\n    inc := \"1\"\n    if len(sp) > 2 {\n        inc = sp[2]\n    }\n    n1, ok1 := strconv.Atoi(sta)\n    n2, ok2 := strconv.Atoi(end)\n    n3, ok3 := strconv.Atoi(inc)\n    if ok3 != nil {\n        return []string{\"{\" + r + \"}\"} \n    }\n    numeric := (ok1 == nil) && (ok2 == nil)\n    if !numeric {\n        if (ok1 == nil && ok2 != nil) || (ok1 != nil && ok2 == nil) {\n            return []string{\"{\" + r + \"}\"} \n        }\n        if utf8.RuneCountInString(sta) != 1 || utf8.RuneCountInString(end) != 1 {\n            return []string{\"{\" + r + \"}\"} \n        }\n        n1 = int(([]rune(sta))[0])\n        n2 = int(([]rune(end))[0])\n    }\n    width := 1\n    if numeric {\n        if len(sta) < len(end) {\n            width = len(end)\n        } else {\n            width = len(sta)\n        }\n    }\n    if n3 == 0 { \n        if numeric {\n            return []string{fmt.Sprintf(\"%0*d\", width, n1)}\n        } else {\n            return []string{sta}\n        }\n    }\n    var res []string\n    asc := n1 < n2\n    if n3 < 0 {\n        asc = !asc\n        t := n1\n        d := abs(n1-n2) % (-n3)\n        n1 = n2 - d*sign(n2-n1)\n        n2 = t\n        n3 = -n3\n    }\n    i := n1\n    if asc {\n        for ; i <= n2; i += n3 {\n            if numeric {\n                res = append(res, fmt.Sprintf(\"%0*d\", width, i))\n            } else {\n                res = append(res, string(rune(i)))\n            }\n        }\n    } else {\n        for ; i >= n2; i -= n3 {\n            if numeric {\n                res = append(res, fmt.Sprintf(\"%0*d\", width, i))\n            } else {\n                res = append(res, string(rune(i)))\n            }\n        }\n    }\n    return res\n}\n\nfunc rangeExpand(s string) []string {\n    res := []string{\"\"}\n    rng := \"\"\n    inRng := false\n    for _, c := range s {\n        if c == '{' && !inRng {\n            inRng = true\n            rng = \"\"\n        } else if c == '}' && inRng {\n            rngRes := parseRange(rng)\n            rngLen := len(rngRes)\n            var res2 []string\n            for i := 0; i < len(res); i++ {\n                for j := 0; j < rngLen; j++ {\n                    res2 = append(res2, res[i]+rngRes[j])\n                }\n            }\n            res = res2\n            inRng = false\n        } else if inRng {\n            rng += string(c)\n        } else {\n            for i := 0; i < len(res); i++ {\n                res[i] += string(c)\n            }\n        }\n    }\n    if inRng {\n        for i := 0; i < len(res); i++ {\n            res[i] += \"{\" + rng \n        }\n    }\n    return res\n}\n\nfunc main() {\n    examples := []string{\n        \"simpleNumberRising{1..3}.txt\",\n        \"simpleAlphaDescending-{Z..X}.txt\",\n        \"steppedDownAndPadded-{10..00..5}.txt\",\n        \"minusSignFlipsSequence {030..20..-5}.txt\",\n        \"reverseSteppedNumberRising{1..6..-2}.txt\",\n        \"combined-{Q..P}{2..1}.txt\",\n        \"emoji{🌵..🌶}{🌽..🌾}etc\",\n        \"li{teral\",\n        \"rangeless{}empty\",\n        \"rangeless{random}string\",\n        \"mixedNumberAlpha{5..k}\",\n        \"steppedAlphaRising{P..Z..2}.txt\",\n        \"stops after endpoint-{02..10..3}.txt\",\n        \"steppedNumberRising{1..6..2}.txt\",\n        \"steppedNumberDescending{20..9..2}\",\n        \"steppedAlphaDescending-{Z..M..2}.txt\",\n        \"reversedSteppedAlphaDescending-{Z..M..-2}.txt\",\n    }\n    for _, s := range examples {\n        fmt.Print(s, \"->\\n    \")\n        res := rangeExpand(s)\n        fmt.Println(strings.Join(res, \"\\n    \"))\n        fmt.Println()\n    }\n}\n", "Python": "\n\nfrom __future__ import annotations\n\nimport itertools\nimport re\n\nfrom abc import ABC\nfrom abc import abstractmethod\n\nfrom typing import Iterable\nfrom typing import Optional\n\n\nRE_SPEC = [\n    (\n        \"INT_RANGE\",\n        r\"\\{(?P<int_start>[0-9]+)..(?P<int_stop>[0-9]+)(?:(?:..)?(?P<int_step>-?[0-9]+))?}\",\n    ),\n    (\n        \"ORD_RANGE\",\n        r\"\\{(?P<ord_start>[^0-9])..(?P<ord_stop>[^0-9])(?:(?:..)?(?P<ord_step>-?[0-9]+))?}\",\n    ),\n    (\n        \"LITERAL\",\n        r\".+?(?=\\{|$)\",\n    ),\n]\n\n\nRE_EXPRESSION = re.compile(\n    \"|\".join(rf\"(?P<{name}>{pattern})\" for name, pattern in RE_SPEC)\n)\n\n\nclass Expression(ABC):\n    \n\n    @abstractmethod\n    def expand(self, prefix: str) -> Iterable[str]:\n        pass\n\n\nclass Literal(Expression):\n    \n\n    def __init__(self, value: str):\n        self.value = value\n\n    def expand(self, prefix: str) -> Iterable[str]:\n        return [f\"{prefix}{self.value}\"]\n\n\nclass IntRange(Expression):\n    \n\n    def __init__(\n        self, start: int, stop: int, step: Optional[int] = None, zfill: int = 0\n    ):\n        self.start, self.stop, self.step = fix_range(start, stop, step)\n        self.zfill = zfill\n\n    def expand(self, prefix: str) -> Iterable[str]:\n        return (\n            f\"{prefix}{str(i).zfill(self.zfill)}\"\n            for i in range(self.start, self.stop, self.step)\n        )\n\n\nclass OrdRange(Expression):\n    \n\n    def __init__(self, start: str, stop: str, step: Optional[int] = None):\n        self.start, self.stop, self.step = fix_range(ord(start), ord(stop), step)\n\n    def expand(self, prefix: str) -> Iterable[str]:\n        return (f\"{prefix}{chr(i)}\" for i in range(self.start, self.stop, self.step))\n\n\ndef expand(expressions: Iterable[Expression]) -> Iterable[str]:\n    \n    expanded = [\"\"]\n\n    for expression in expressions:\n        expanded = itertools.chain.from_iterable(\n            [expression.expand(prefix) for prefix in expanded]\n        )\n\n    return expanded\n\n\ndef zero_fill(start, stop) -> int:\n    \n\n    def _zfill(s):\n        if len(s) <= 1 or not s.startswith(\"0\"):\n            return 0\n        return len(s)\n\n    return max(_zfill(start), _zfill(stop))\n\n\ndef fix_range(start, stop, step):\n    \n    if not step:\n        \n        if start <= stop:\n            \n            step = 1\n        else:\n            \n            step = -1\n\n    elif step < 0:\n        \n        start, stop = stop, start\n\n        if start < stop:\n            step = abs(step)\n        else:\n            start -= 1\n            stop -= 1\n\n    elif start > stop:\n        \n        step = -step\n\n    \n    if (start - stop) % step == 0:\n        stop += step\n\n    return start, stop, step\n\n\ndef parse(expression: str) -> Iterable[Expression]:\n    \n    for match in RE_EXPRESSION.finditer(expression):\n        kind = match.lastgroup\n\n        if kind == \"INT_RANGE\":\n            start = match.group(\"int_start\")\n            stop = match.group(\"int_stop\")\n            step = match.group(\"int_step\")\n            zfill = zero_fill(start, stop)\n\n            if step is not None:\n                step = int(step)\n\n            yield IntRange(int(start), int(stop), step, zfill=zfill)\n\n        elif kind == \"ORD_RANGE\":\n            start = match.group(\"ord_start\")\n            stop = match.group(\"ord_stop\")\n            step = match.group(\"ord_step\")\n\n            if step is not None:\n                step = int(step)\n\n            yield OrdRange(start, stop, step)\n\n        elif kind == \"LITERAL\":\n            yield Literal(match.group())\n\n\ndef examples():\n    cases = [\n        r\"simpleNumberRising{1..3}.txt\",\n        r\"simpleAlphaDescending-{Z..X}.txt\",\n        r\"steppedDownAndPadded-{10..00..5}.txt\",\n        r\"minusSignFlipsSequence {030..20..-5}.txt\",\n        r\"reverseSteppedNumberRising{1..6..-2}.txt\",\n        r\"combined-{Q..P}{2..1}.txt\",\n        r\"emoji{🌵..🌶}{🌽..🌾}etc\",\n        r\"li{teral\",\n        r\"rangeless{}empty\",\n        r\"rangeless{random}string\",\n        \n        r\"steppedNumberRising{1..6..2}.txt\",\n        r\"steppedNumberDescending{20..9..2}.txt\",\n        r\"steppedAlphaDescending-{Z..M..2}.txt\",\n        r\"reverseSteppedAlphaRising{A..F..-2}.txt\",\n        r\"reversedSteppedAlphaDescending-{Z..M..-2}.txt\",\n    ]\n\n    for case in cases:\n        print(f\"{case} ->\")\n        expressions = parse(case)\n\n        for itm in expand(expressions):\n            print(f\"{' '*4}{itm}\")\n\n        print(\"\")  \n\n\nif __name__ == \"__main__\":\n    examples()\n"}
{"id": 51065, "name": "Colour pinstripe_Printer", "Go": "package main\n \nimport (\n    \"github.com/fogleman/gg\"\n    \"log\"\n    \"os/exec\"\n    \"runtime\"\n)\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() / 7\n    for b := 1; b <= 11; 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(842, 595)\n    pinstripe(dc)\n    fileName := \"color_pinstripe.png\"\n    dc.SavePNG(fileName)\n    var cmd *exec.Cmd\n    if runtime.GOOS == \"windows\" {\n        cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n    } else {\n        cmd = exec.Command(\"lp\", fileName)\n    }\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }   \n}\n", "Python": "from turtle import *\nfrom PIL import Image\nimport time\nimport subprocess\n\n\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\nscreen = getscreen()\n\n\n\n\ninch_width = 11.0\ninch_height = 8.5\n\npixels_per_inch = 100\n\npix_width = int(inch_width*pixels_per_inch)\npix_height = int(inch_height*pixels_per_inch)\n\nscreen.setup (width=pix_width, height=pix_height, startx=0, starty=0)\n\nscreen.screensize(pix_width,pix_height)\n\n\n\n\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nbottom_edge = -screen.window_height()//2\n\ntop_edge = screen.window_height()//2\n\n\n\nscreen.delay(0)\nscreen.tracer(5)\n\nfor inch in range(int(inch_width)-1):\n    line_width = inch + 1\n    pensize(line_width)\n    colornum = 0\n\n    min_x = left_edge + (inch * pixels_per_inch)\n    max_x = left_edge + ((inch+1) * pixels_per_inch)\n    \n    for y in range(bottom_edge,top_edge,line_width):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(min_x,y)\n        pendown()\n        setposition(max_x,y)\n         \nscreen.getcanvas().postscript(file=\"striped.eps\")\n\n\n\n\nim = Image.open(\"striped.eps\")\nim.save(\"striped.jpg\")\n\n\n    \nsubprocess.run([\"mspaint\", \"/pt\", \"striped.jpg\"])\n"}
{"id": 51066, "name": "Determine sentence type", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc sentenceType(s string) string {\n    if len(s) == 0 {\n        return \"\"\n    }\n    var types []string\n    for _, c := range s {\n        if c == '?' {\n            types = append(types, \"Q\")\n        } else if c == '!' {\n            types = append(types, \"E\")\n        } else if c == '.' {\n            types = append(types, \"S\")\n        }\n    }\n    if strings.IndexByte(\"?!.\", s[len(s)-1]) == -1 {\n        types = append(types, \"N\")\n    }\n    return strings.Join(types, \"|\")\n}\n\nfunc main() {\n    s := \"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it\"\n    fmt.Println(sentenceType(s))\n}\n", "Python": "import re\n\ntxt = \n\ndef haspunctotype(s):\n    return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N'\n\ntxt = re.sub('\\n', '', txt)\npars = [s.strip() for s in re.split(\"(?:(?:(?<=[\\?\\!\\.])(?:))|(?:(?:)(?=[\\?\\!\\.])))\", txt)]\nif len(pars) % 2:\n    pars.append('')  \nfor i in range(0, len(pars)-1, 2):\n    print((pars[i] + pars[i + 1]).ljust(54), \"==>\", haspunctotype(pars[i + 1]))\n"}
{"id": 51067, "name": "Long literals, with continuations", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\n\n\n\nvar elements = `\n    hydrogen     helium        lithium      beryllium\n    boron        carbon        nitrogen     oxygen\n    fluorine     neon          sodium       magnesium\n    aluminum     silicon       phosphorous  sulfur\n    chlorine     argon         potassium    calcium\n    scandium     titanium      vanadium     chromium\n    manganese    iron          cobalt       nickel\n    copper       zinc          gallium      germanium\n    arsenic      selenium      bromine      krypton\n    rubidium     strontium     yttrium      zirconium\n    niobium      molybdenum    technetium   ruthenium\n    rhodium      palladium     silver       cadmium\n    indium       tin           antimony     tellurium\n    iodine       xenon         cesium       barium\n    lanthanum    cerium        praseodymium neodymium\n    promethium   samarium      europium     gadolinium\n    terbium      dysprosium    holmium      erbium\n    thulium      ytterbium     lutetium     hafnium\n    tantalum     tungsten      rhenium      osmium\n    iridium      platinum      gold         mercury\n    thallium     lead          bismuth      polonium\n    astatine     radon         francium     radium\n    actinium     thorium       protactinium uranium\n    neptunium    plutonium     americium    curium\n    berkelium    californium   einsteinium  fermium\n    mendelevium  nobelium      lawrencium   rutherfordium\n    dubnium      seaborgium    bohrium      hassium\n    meitnerium   darmstadtium  roentgenium  copernicium\n    nihonium     flerovium     moscovium    livermorium\n    tennessine   oganesson\n`\n\nfunc main() {\n    lastRevDate := \"March 24th, 2020\"\n    re := regexp.MustCompile(`\\s+`) \n    els := re.Split(strings.TrimSpace(elements), -1)\n    numEls := len(els)\n    \n    elements2 := strings.Join(els, \" \")\n    \n    fmt.Println(\"Last revision Date: \", lastRevDate)\n    fmt.Println(\"Number of elements: \", numEls)\n    \n    \n    lix := strings.LastIndex(elements2, \" \") \n    fmt.Println(\"Last element      : \", elements2[lix+1:])\n}\n", "Python": "\n\nrevision = \"October 13th 2020\"\n\n\n\n\nelements = (\n    \"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine \"\n    \"neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon \"\n    \"potassium calcium scandium titanium vanadium chromium manganese iron \"\n    \"cobalt nickel copper zinc gallium germanium arsenic selenium bromine \"\n    \"krypton rubidium strontium yttrium zirconium niobium molybdenum \"\n    \"technetium ruthenium rhodium palladium silver cadmium indium tin \"\n    \"antimony tellurium iodine xenon cesium barium lanthanum cerium \"\n    \"praseodymium neodymium promethium samarium europium gadolinium terbium \"\n    \"dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum \"\n    \"tungsten rhenium osmium iridium platinum gold mercury thallium lead \"\n    \"bismuth polonium astatine radon francium radium actinium thorium \"\n    \"protactinium uranium neptunium plutonium americium curium berkelium \"\n    \"californium einsteinium fermium mendelevium nobelium lawrencium \"\n    \"rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium \"\n    \"roentgenium copernicium nihonium flerovium moscovium livermorium \"\n    \"tennessine oganesson\"\n)\n\n\ndef report():\n    \n    items = elements.split()\n\n    print(f\"Last revision date: {revision}\")\n    print(f\"Number of elements: {len(items)}\")\n    print(f\"Last element      : {items[-1]}\")\n\n\nif __name__ == \"__main__\":\n    report()\n"}
{"id": 51068, "name": "Set right-adjacent bits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype test struct {\n    bs string\n    n  int\n}\n\nfunc setRightBits(bits []byte, e, n int) []byte {\n    if e == 0 || n <= 0 {\n        return bits\n    }\n    bits2 := make([]byte, len(bits))\n    copy(bits2, bits)\n    for i := 0; i < e-1; i++ {\n        c := bits[i]\n        if c == 1 {\n            j := i + 1\n            for j <= i+n && j < e {\n                bits2[j] = 1\n                j++\n            }\n        }\n    }\n    return bits2\n}\n\nfunc main() {\n    b := \"010000000000100000000010000000010000000100000010000010000100010010\"\n    tests := []test{\n        test{\"1000\", 2}, test{\"0100\", 2}, test{\"0010\", 2}, test{\"0000\", 2},\n        test{b, 0}, test{b, 1}, test{b, 2}, test{b, 3},\n    }\n    for _, test := range tests {\n        bs := test.bs\n        e := len(bs)\n        n := test.n\n        fmt.Println(\"n =\", n, \"\\b; Width e =\", e, \"\\b:\")\n        fmt.Println(\"    Input b:\", bs)\n        bits := []byte(bs)\n        for i := 0; i < len(bits); i++ {\n            bits[i] = bits[i] - '0'\n        }\n        bits = setRightBits(bits, e, n)\n        var sb strings.Builder\n        for i := 0; i < len(bits); i++ {\n            sb.WriteByte(bits[i] + '0')\n        }\n        fmt.Println(\"    Result :\", sb.String())\n    }\n}\n", "Python": "from operator import or_\nfrom functools import reduce\n\ndef set_right_adjacent_bits(n: int, b: int) -> int:\n    return reduce(or_, (b >> x for x in range(n+1)), 0)\n\n\nif __name__ == \"__main__\":\n    print(\"SAME n & Width.\\n\")\n    n = 2  \n    bits = \"1000 0100 0010 0000\"\n    first = True\n    for b_str in bits.split():\n        b = int(b_str, 2)\n        e = len(b_str)\n        if first:\n            first = False\n            print(f\"n = {n}; Width e = {e}:\\n\")\n        result = set_right_adjacent_bits(n, b)\n        print(f\"     Input b: {b:0{e}b}\")\n        print(f\"      Result: {result:0{e}b}\\n\")\n        \n    print(\"SAME Input & Width.\\n\")\n    \n    bits = '01' + '1'.join('0'*x for x in range(10, 0, -1))\n    for n in range(4):\n        first = True\n        for b_str in bits.split():\n            b = int(b_str, 2)\n            e = len(b_str)\n            if first:\n                first = False\n                print(f\"n = {n}; Width e = {e}:\\n\")\n            result = set_right_adjacent_bits(n, b)\n            print(f\"     Input b: {b:0{e}b}\")\n            print(f\"      Result: {result:0{e}b}\\n\")\n"}
{"id": 51069, "name": "Cubic special primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n"}
{"id": 51070, "name": "Cubic special primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n"}
{"id": 51071, "name": "Cubic special primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n"}
{"id": 51072, "name": "Cubic special primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n"}
{"id": 51073, "name": "Geohash", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype Location struct{ lat, lng float64 }\n\nfunc (loc Location) String() string { return fmt.Sprintf(\"[%f, %f]\", loc.lat, loc.lng) }\n\ntype Range struct{ lower, upper float64 }\n\nvar gBase32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\n\nfunc encodeGeohash(loc Location, prec int) string {\n    latRange := Range{-90, 90}\n    lngRange := Range{-180, 180}\n    var hash strings.Builder\n    hashVal := 0\n    bits := 0\n    even := true\n    for hash.Len() < prec {\n        val := loc.lat\n        rng := latRange\n        if even {\n            val = loc.lng\n            rng = lngRange\n        }\n        mid := (rng.lower + rng.upper) / 2\n        if val > mid {\n            hashVal = (hashVal << 1) + 1\n            rng = Range{mid, rng.upper}\n            if even {\n                lngRange = Range{mid, lngRange.upper}\n            } else {\n                latRange = Range{mid, latRange.upper}\n            }\n        } else {\n            hashVal <<= 1\n            if even {\n                lngRange = Range{lngRange.lower, mid}\n            } else {\n                latRange = Range{latRange.lower, mid}\n            }\n        }\n        even = !even\n        if bits < 4 {\n            bits++\n        } else {\n            bits = 0\n            hash.WriteByte(gBase32[hashVal])\n            hashVal = 0\n        }\n    }\n    return hash.String()\n}\n\nfunc main() {\n    locs := []Location{\n        {51.433718, -0.214126},\n        {51.433718, -0.214126},\n        {57.64911, 10.40744},\n    }\n    precs := []int{2, 9, 11}\n\n    for i, loc := range locs {\n        geohash := encodeGeohash(loc, precs[i])\n        fmt.Printf(\"geohash for %v, precision %-2d = %s\\n\", loc, precs[i], geohash)\n    }\n}\n", "Python": "ch32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\nbool2ch = {f\"{i:05b}\": ch for i, ch in enumerate(ch32)}\nch2bool = {v : k for k, v in bool2ch.items()}\n\ndef bisect(val, mn, mx, bits):\n    mid = (mn + mx) / 2\n    if val < mid:\n        bits <<= 1                        \n        mx = mid                          \n    else:\n        bits = bits << 1 | 1              \n        mn = mid                          \n\n    return mn, mx, bits\n\ndef encoder(lat, lng, pre):\n    latmin, latmax = -90, 90\n    lngmin, lngmax = -180, 180\n    bits = 0\n    for i in range(pre * 5):\n        if i % 2:\n            \n            latmin, latmax, bits = bisect(lat, latmin, latmax, bits)\n        else:\n            \n            lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits)\n    \n    b = f\"{bits:0{pre * 5}b}\"\n    geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre))\n\n    return ''.join(geo)\n\ndef decoder(geo):\n    minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True\n    for c in geo:\n        for bit in ch2bool[c]:\n            minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2\n            latlong = not latlong\n\n    return minmaxes\n\nif __name__ == '__main__':\n    for (lat, lng), pre in [([51.433718, -0.214126],  2),\n                            ([51.433718, -0.214126],  9),\n                            ([57.64911,  10.40744] , 11),\n                            ([57.64911,  10.40744] , 22)]:\n        print(\"encoder(lat=%f, lng=%f, pre=%i) = %r\"\n              % (lat, lng, pre, encoder(lat, lng, pre)))\n"}
{"id": 51074, "name": "Geohash", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype Location struct{ lat, lng float64 }\n\nfunc (loc Location) String() string { return fmt.Sprintf(\"[%f, %f]\", loc.lat, loc.lng) }\n\ntype Range struct{ lower, upper float64 }\n\nvar gBase32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\n\nfunc encodeGeohash(loc Location, prec int) string {\n    latRange := Range{-90, 90}\n    lngRange := Range{-180, 180}\n    var hash strings.Builder\n    hashVal := 0\n    bits := 0\n    even := true\n    for hash.Len() < prec {\n        val := loc.lat\n        rng := latRange\n        if even {\n            val = loc.lng\n            rng = lngRange\n        }\n        mid := (rng.lower + rng.upper) / 2\n        if val > mid {\n            hashVal = (hashVal << 1) + 1\n            rng = Range{mid, rng.upper}\n            if even {\n                lngRange = Range{mid, lngRange.upper}\n            } else {\n                latRange = Range{mid, latRange.upper}\n            }\n        } else {\n            hashVal <<= 1\n            if even {\n                lngRange = Range{lngRange.lower, mid}\n            } else {\n                latRange = Range{latRange.lower, mid}\n            }\n        }\n        even = !even\n        if bits < 4 {\n            bits++\n        } else {\n            bits = 0\n            hash.WriteByte(gBase32[hashVal])\n            hashVal = 0\n        }\n    }\n    return hash.String()\n}\n\nfunc main() {\n    locs := []Location{\n        {51.433718, -0.214126},\n        {51.433718, -0.214126},\n        {57.64911, 10.40744},\n    }\n    precs := []int{2, 9, 11}\n\n    for i, loc := range locs {\n        geohash := encodeGeohash(loc, precs[i])\n        fmt.Printf(\"geohash for %v, precision %-2d = %s\\n\", loc, precs[i], geohash)\n    }\n}\n", "Python": "ch32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\nbool2ch = {f\"{i:05b}\": ch for i, ch in enumerate(ch32)}\nch2bool = {v : k for k, v in bool2ch.items()}\n\ndef bisect(val, mn, mx, bits):\n    mid = (mn + mx) / 2\n    if val < mid:\n        bits <<= 1                        \n        mx = mid                          \n    else:\n        bits = bits << 1 | 1              \n        mn = mid                          \n\n    return mn, mx, bits\n\ndef encoder(lat, lng, pre):\n    latmin, latmax = -90, 90\n    lngmin, lngmax = -180, 180\n    bits = 0\n    for i in range(pre * 5):\n        if i % 2:\n            \n            latmin, latmax, bits = bisect(lat, latmin, latmax, bits)\n        else:\n            \n            lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits)\n    \n    b = f\"{bits:0{pre * 5}b}\"\n    geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre))\n\n    return ''.join(geo)\n\ndef decoder(geo):\n    minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True\n    for c in geo:\n        for bit in ch2bool[c]:\n            minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2\n            latlong = not latlong\n\n    return minmaxes\n\nif __name__ == '__main__':\n    for (lat, lng), pre in [([51.433718, -0.214126],  2),\n                            ([51.433718, -0.214126],  9),\n                            ([57.64911,  10.40744] , 11),\n                            ([57.64911,  10.40744] , 22)]:\n        print(\"encoder(lat=%f, lng=%f, pre=%i) = %r\"\n              % (lat, lng, pre, encoder(lat, lng, pre)))\n"}
{"id": 51075, "name": "Natural sorting", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar tests = []struct {\n    descr string\n    list  []string\n}{\n    {\"Ignoring leading spaces\", []string{\n        \"ignore leading spaces: 2-2\",\n        \" ignore leading spaces: 2-1\",\n        \"  ignore leading spaces: 2+0\",\n        \"   ignore leading spaces: 2+1\",\n    }},\n    {\"Ignoring multiple adjacent spaces\", []string{\n        \"ignore m.a.s spaces: 2-2\",\n        \"ignore m.a.s  spaces: 2-1\",\n        \"ignore m.a.s   spaces: 2+0\",\n        \"ignore m.a.s    spaces: 2+1\",\n    }},\n    {\"Equivalent whitespace characters\", []string{\n        \"Equiv. spaces: 3-3\",\n        \"Equiv.\\rspaces: 3-2\",\n        \"Equiv.\\fspaces: 3-1\",\n        \"Equiv.\\bspaces: 3+0\",\n        \"Equiv.\\nspaces: 3+1\",\n        \"Equiv.\\tspaces: 3+2\",\n    }},\n    {\"Case Indepenent sort\", []string{\n        \"cASE INDEPENENT: 3-2\",\n        \"caSE INDEPENENT: 3-1\",\n        \"casE INDEPENENT: 3+0\",\n        \"case INDEPENENT: 3+1\",\n    }},\n    {\"Numeric fields as numerics\", []string{\n        \"foo100bar99baz0.txt\",\n        \"foo100bar10baz0.txt\",\n        \"foo1000bar99baz10.txt\",\n        \"foo1000bar99baz9.txt\",\n    }},\n}\n\nfunc main() {\n    for _, test := range tests {\n        fmt.Println(test.descr)\n        fmt.Println(\"Input order:\")\n        for _, s := range test.list {\n            fmt.Printf(\"   %q\\n\", s)\n        }\n        fmt.Println(\"Natural order:\")\n        l := make(list, len(test.list))\n        for i, s := range test.list {\n            l[i] = newNatStr(s)\n        }\n        sort.Sort(l)\n        for _, s := range l {\n            fmt.Printf(\"   %q\\n\", s.s)\n        }\n        fmt.Println()\n    }\n}\n\n\ntype natStr struct {\n    s string \n    t []tok  \n}\n\nfunc newNatStr(s string) (t natStr) {\n    t.s = s\n    s = strings.ToLower(strings.Join(strings.Fields(s), \" \"))\n    x := dx.FindAllString(s, -1)\n    t.t = make([]tok, len(x))\n    for i, s := range x {\n        if n, err := strconv.Atoi(s); err == nil {\n            t.t[i].n = n\n        } else {\n            t.t[i].s = s\n        }\n    }\n    return t\n}\n\nvar dx = regexp.MustCompile(`\\d+|\\D+`)\n\n\ntype tok struct {\n    s string\n    n int\n}\n\n\nfunc (f1 tok) Cmp(f2 tok) int {\n    switch {\n    case f1.s == \"\":\n        switch {\n        case f2.s > \"\" || f1.n < f2.n:\n            return -1\n        case f1.n > f2.n:\n            return 1\n        }\n    case f2.s == \"\" || f1.s > f2.s:\n        return 1\n    case f1.s < f2.s:\n        return -1\n    }\n    return 0\n}\n\ntype list []natStr\n\nfunc (l list) Len() int      { return len(l) }\nfunc (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] }\nfunc (l list) Less(i, j int) bool {\n    ti := l[i].t\n    for k, t := range l[j].t {\n        if k == len(ti) {\n            return true\n        }\n        switch ti[k].Cmp(t) {\n        case -1:\n            return true\n        case 1:\n            return false\n        }\n    }\n    return false\n}\n", "Python": "\n\n\n\nfrom itertools import groupby\nfrom unicodedata import decomposition, name\nfrom pprint import pprint as pp\n\ncommonleaders = ['the'] \nreplacements = {u'ß': 'ss',  \n                u'ſ': 's',\n                u'ʒ': 's',\n                }\n\nhexdigits = set('0123456789abcdef')\ndecdigits = set('0123456789')   \n\ndef splitchar(c):\n    ' De-ligature. De-accent a char'\n    de = decomposition(c)\n    if de:\n        \n        de = [d for d in de.split()\n                  if all(c.lower()\n                         in hexdigits for c in d)]\n        n = name(c, c).upper()\n        \n        if len(de)> 1 and 'PRECEDE' in n:\n            \n            de[1], de[0] = de[0], de[1]\n        tmp = [ unichr(int(k, 16)) for k in de]\n        base, others = tmp[0], tmp[1:]\n        if 'LIGATURE' in n:\n            \n            base += others.pop(0)\n    else:\n        base = c\n    return base\n    \n\ndef sortkeygen(s):\n    \n    \n    s = unicode(s).strip()\n    \n    s = ' '.join(s.split())\n    \n    s = s.lower()\n    \n    words = s.split()\n    if len(words) > 1 and words[0] in commonleaders:\n        s = ' '.join( words[1:])\n    \n    s = ''.join(splitchar(c) for c in s)\n    \n    s = ''.join( replacements.get(ch, ch) for ch in s )\n    \n    s = [ int(\"\".join(g)) if isinteger else \"\".join(g)\n          for isinteger,g in groupby(s, lambda x: x in decdigits)]\n\n    return s\n\ndef naturalsort(items):\n    \n    return sorted(items, key=sortkeygen)\n\nif __name__ == '__main__':\n    import string\n    \n    ns = naturalsort\n\n    print '\\n\n    txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3)\n           for i,ch in enumerate(reversed(string.whitespace))]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    s = 'CASE INDEPENENT'\n    txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt',\n           'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['The Wind in the Willows','The 40th step more',\n                         'The 39 steps', 'Wanda']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv. %s accents: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(u'\\xfd\\xddyY')]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = [u'\\462 ligatured ij', 'no ligature',]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n    \n    print '\\n\n    s = u'ʒſßs' \n    txt = ['Start with an %s: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(s)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; print '\\n'.join(sorted(txt))\n    print 'Naturally sorted:'; print '\\n'.join(ns(txt))\n"}
{"id": 51076, "name": "Natural sorting", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar tests = []struct {\n    descr string\n    list  []string\n}{\n    {\"Ignoring leading spaces\", []string{\n        \"ignore leading spaces: 2-2\",\n        \" ignore leading spaces: 2-1\",\n        \"  ignore leading spaces: 2+0\",\n        \"   ignore leading spaces: 2+1\",\n    }},\n    {\"Ignoring multiple adjacent spaces\", []string{\n        \"ignore m.a.s spaces: 2-2\",\n        \"ignore m.a.s  spaces: 2-1\",\n        \"ignore m.a.s   spaces: 2+0\",\n        \"ignore m.a.s    spaces: 2+1\",\n    }},\n    {\"Equivalent whitespace characters\", []string{\n        \"Equiv. spaces: 3-3\",\n        \"Equiv.\\rspaces: 3-2\",\n        \"Equiv.\\fspaces: 3-1\",\n        \"Equiv.\\bspaces: 3+0\",\n        \"Equiv.\\nspaces: 3+1\",\n        \"Equiv.\\tspaces: 3+2\",\n    }},\n    {\"Case Indepenent sort\", []string{\n        \"cASE INDEPENENT: 3-2\",\n        \"caSE INDEPENENT: 3-1\",\n        \"casE INDEPENENT: 3+0\",\n        \"case INDEPENENT: 3+1\",\n    }},\n    {\"Numeric fields as numerics\", []string{\n        \"foo100bar99baz0.txt\",\n        \"foo100bar10baz0.txt\",\n        \"foo1000bar99baz10.txt\",\n        \"foo1000bar99baz9.txt\",\n    }},\n}\n\nfunc main() {\n    for _, test := range tests {\n        fmt.Println(test.descr)\n        fmt.Println(\"Input order:\")\n        for _, s := range test.list {\n            fmt.Printf(\"   %q\\n\", s)\n        }\n        fmt.Println(\"Natural order:\")\n        l := make(list, len(test.list))\n        for i, s := range test.list {\n            l[i] = newNatStr(s)\n        }\n        sort.Sort(l)\n        for _, s := range l {\n            fmt.Printf(\"   %q\\n\", s.s)\n        }\n        fmt.Println()\n    }\n}\n\n\ntype natStr struct {\n    s string \n    t []tok  \n}\n\nfunc newNatStr(s string) (t natStr) {\n    t.s = s\n    s = strings.ToLower(strings.Join(strings.Fields(s), \" \"))\n    x := dx.FindAllString(s, -1)\n    t.t = make([]tok, len(x))\n    for i, s := range x {\n        if n, err := strconv.Atoi(s); err == nil {\n            t.t[i].n = n\n        } else {\n            t.t[i].s = s\n        }\n    }\n    return t\n}\n\nvar dx = regexp.MustCompile(`\\d+|\\D+`)\n\n\ntype tok struct {\n    s string\n    n int\n}\n\n\nfunc (f1 tok) Cmp(f2 tok) int {\n    switch {\n    case f1.s == \"\":\n        switch {\n        case f2.s > \"\" || f1.n < f2.n:\n            return -1\n        case f1.n > f2.n:\n            return 1\n        }\n    case f2.s == \"\" || f1.s > f2.s:\n        return 1\n    case f1.s < f2.s:\n        return -1\n    }\n    return 0\n}\n\ntype list []natStr\n\nfunc (l list) Len() int      { return len(l) }\nfunc (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] }\nfunc (l list) Less(i, j int) bool {\n    ti := l[i].t\n    for k, t := range l[j].t {\n        if k == len(ti) {\n            return true\n        }\n        switch ti[k].Cmp(t) {\n        case -1:\n            return true\n        case 1:\n            return false\n        }\n    }\n    return false\n}\n", "Python": "\n\n\n\nfrom itertools import groupby\nfrom unicodedata import decomposition, name\nfrom pprint import pprint as pp\n\ncommonleaders = ['the'] \nreplacements = {u'ß': 'ss',  \n                u'ſ': 's',\n                u'ʒ': 's',\n                }\n\nhexdigits = set('0123456789abcdef')\ndecdigits = set('0123456789')   \n\ndef splitchar(c):\n    ' De-ligature. De-accent a char'\n    de = decomposition(c)\n    if de:\n        \n        de = [d for d in de.split()\n                  if all(c.lower()\n                         in hexdigits for c in d)]\n        n = name(c, c).upper()\n        \n        if len(de)> 1 and 'PRECEDE' in n:\n            \n            de[1], de[0] = de[0], de[1]\n        tmp = [ unichr(int(k, 16)) for k in de]\n        base, others = tmp[0], tmp[1:]\n        if 'LIGATURE' in n:\n            \n            base += others.pop(0)\n    else:\n        base = c\n    return base\n    \n\ndef sortkeygen(s):\n    \n    \n    s = unicode(s).strip()\n    \n    s = ' '.join(s.split())\n    \n    s = s.lower()\n    \n    words = s.split()\n    if len(words) > 1 and words[0] in commonleaders:\n        s = ' '.join( words[1:])\n    \n    s = ''.join(splitchar(c) for c in s)\n    \n    s = ''.join( replacements.get(ch, ch) for ch in s )\n    \n    s = [ int(\"\".join(g)) if isinteger else \"\".join(g)\n          for isinteger,g in groupby(s, lambda x: x in decdigits)]\n\n    return s\n\ndef naturalsort(items):\n    \n    return sorted(items, key=sortkeygen)\n\nif __name__ == '__main__':\n    import string\n    \n    ns = naturalsort\n\n    print '\\n\n    txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3)\n           for i,ch in enumerate(reversed(string.whitespace))]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    s = 'CASE INDEPENENT'\n    txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt',\n           'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['The Wind in the Willows','The 40th step more',\n                         'The 39 steps', 'Wanda']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv. %s accents: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(u'\\xfd\\xddyY')]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = [u'\\462 ligatured ij', 'no ligature',]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n    \n    print '\\n\n    s = u'ʒſßs' \n    txt = ['Start with an %s: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(s)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; print '\\n'.join(sorted(txt))\n    print 'Naturally sorted:'; print '\\n'.join(ns(txt))\n"}
{"id": 51077, "name": "Positive decimal integers with the digit 1 occurring exactly twice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Decimal numbers under 1,000 whose digits include two 1's:\")\n    var results []int\n    for i := 11; i <= 911; i++ {\n        digits := rcu.Digits(i, 10)\n        count := 0\n        for _, d := range digits {\n            if d == 1 {\n                count++\n            }\n        }\n        if count == 2 {\n            results = append(results, i)\n        }\n    }\n    for i, n := range results {\n        fmt.Printf(\"%5d\", n)\n        if (i+1)%7 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such numbers.\")\n}\n", "Python": "\n\nfrom itertools import permutations\n\nfor i in range(0,10):\n    if i!=1:\n        baseList = [1,1]\n        baseList.append(i)\n        [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]\n"}
{"id": 51078, "name": "Positive decimal integers with the digit 1 occurring exactly twice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Decimal numbers under 1,000 whose digits include two 1's:\")\n    var results []int\n    for i := 11; i <= 911; i++ {\n        digits := rcu.Digits(i, 10)\n        count := 0\n        for _, d := range digits {\n            if d == 1 {\n                count++\n            }\n        }\n        if count == 2 {\n            results = append(results, i)\n        }\n    }\n    for i, n := range results {\n        fmt.Printf(\"%5d\", n)\n        if (i+1)%7 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such numbers.\")\n}\n", "Python": "\n\nfrom itertools import permutations\n\nfor i in range(0,10):\n    if i!=1:\n        baseList = [1,1]\n        baseList.append(i)\n        [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]\n"}
{"id": 51079, "name": "Odd and square numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    pow := 1\n    for p := 0; p < 5; p++ {\n        low := int(math.Ceil(math.Sqrt(float64(pow))))\n        if low%2 == 0 {\n            low++\n        }\n        pow *= 10\n        high := int(math.Sqrt(float64(pow)))\n        var oddSq []int\n        for i := low; i <= high; i += 2 {\n            oddSq = append(oddSq, i*i)\n        }\n        fmt.Println(len(oddSq), \"odd squares from\", pow/10, \"to\", pow, \"\\b:\")\n        for i := 0; i < len(oddSq); i++ {\n            fmt.Printf(\"%d \", oddSq[i])\n            if (i+1)%10 == 0 {\n                fmt.Println()\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Python": "import math\nszamok=[]\nlimit = 1000\n\nfor i in range(1,int(math.ceil(math.sqrt(limit))),2):\n    num = i*i\n    if (num < 1000 and num > 99):\n        szamok.append(num)\n\nprint(szamok)\n"}
{"id": 51080, "name": "Odd and square numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    pow := 1\n    for p := 0; p < 5; p++ {\n        low := int(math.Ceil(math.Sqrt(float64(pow))))\n        if low%2 == 0 {\n            low++\n        }\n        pow *= 10\n        high := int(math.Sqrt(float64(pow)))\n        var oddSq []int\n        for i := low; i <= high; i += 2 {\n            oddSq = append(oddSq, i*i)\n        }\n        fmt.Println(len(oddSq), \"odd squares from\", pow/10, \"to\", pow, \"\\b:\")\n        for i := 0; i < len(oddSq); i++ {\n            fmt.Printf(\"%d \", oddSq[i])\n            if (i+1)%10 == 0 {\n                fmt.Println()\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Python": "import math\nszamok=[]\nlimit = 1000\n\nfor i in range(1,int(math.ceil(math.sqrt(limit))),2):\n    num = i*i\n    if (num < 1000 and num > 99):\n        szamok.append(num)\n\nprint(szamok)\n"}
{"id": 51081, "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", "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": 51082, "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", "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": 51083, "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", "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": 51084, "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", "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": 51085, "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", "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": 51086, "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", "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": 51087, "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", "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": 51088, "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", "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": 51089, "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", "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": 51090, "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", "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": 51091, "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", "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": 51092, "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", "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": 51093, "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", "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": 51094, "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", "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": 51095, "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", "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": 51096, "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", "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": 51097, "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", "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": 51098, "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", "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": 51099, "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", "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": 51100, "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", "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": 51101, "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", "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": 51102, "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", "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": 51103, "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", "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": 51104, "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", "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": 51105, "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", "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": 51106, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 51107, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 51108, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 51109, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 51110, "name": "Peano curve", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\n}\n", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\n"}
{"id": 51111, "name": "Seven-sided dice from five-sided dice", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 51112, "name": "Magnanimous numbers", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\n"}
{"id": 51113, "name": "Extensible prime generator", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n"}
{"id": 51114, "name": "Create a two-dimensional array at runtime", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n"}
{"id": 51115, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 51116, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 51117, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n"}
{"id": 51118, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 51119, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 51120, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 51121, "name": "Return multiple values", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n"}
{"id": 51122, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 51123, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 51124, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 51125, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 51126, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 51127, "name": "LU decomposition", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\n}\n", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 51128, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 51129, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 51130, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 51131, "name": "Variable-length quantity", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51132, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 51133, "name": "Text processing_1", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n"}
{"id": 51134, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 51135, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 51136, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 51137, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 51138, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 51139, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 51140, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 51141, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 51142, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 51143, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 51144, "name": "Stack", "C++": "#include <stack>\n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 51145, "name": "Totient function", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 51146, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 51147, "name": "Fractran", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n"}
{"id": 51148, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n"}
{"id": 51149, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 51150, "name": "Animation", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 51151, "name": "List comprehensions", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 51152, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 51153, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 51154, "name": "Case-sensitivity of identifiers", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n"}
{"id": 51155, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n"}
{"id": 51156, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 51157, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 51158, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 51159, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 51160, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 51161, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 51162, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 51163, "name": "Twin primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 51164, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 51165, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 51166, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51167, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 51168, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 51169, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 51170, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 51171, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 51172, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 51173, "name": "Short-circuit evaluation", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 51174, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 51175, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 51176, "name": "Arithmetic numbers", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 51177, "name": "Arithmetic numbers", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n"}
{"id": 51178, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 51179, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 51180, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 51181, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n"}
{"id": 51182, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 51183, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 51184, "name": "Sorting algorithms_Bead sort", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 51185, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 51186, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 51187, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 51188, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 51189, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 51190, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 51191, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 51192, "name": "Square-free integers", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51193, "name": "Jaro similarity", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n"}
{"id": 51194, "name": "Fairshare between two and more", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 51195, "name": "Parsing_Shunting-yard algorithm", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 51196, "name": "Prime triangle", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n"}
{"id": 51197, "name": "Trabb Pardo–Knuth algorithm", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n"}
{"id": 51198, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 51199, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 51200, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n"}
{"id": 51201, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n"}
{"id": 51202, "name": "Rep-string", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n"}
{"id": 51203, "name": "Literals_String", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n"}
{"id": 51204, "name": "Enumerations", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 51205, "name": "Parse an IP Address", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n"}
{"id": 51206, "name": "Textonyms", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n"}
{"id": 51207, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n"}
{"id": 51208, "name": "Type detection", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n"}
{"id": 51209, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n"}
{"id": 51210, "name": "Zhang-Suen thinning algorithm", "C++": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <valarray>\nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n    friend class ZhangSuen;\n    using pixel_t = char;\n    static const pixel_t BLACK_PIX;\n    static const pixel_t WHITE_PIX;\n\n    Image(unsigned width = 1, unsigned height = 1) \n    : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n    {}\n    Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n    {}\n    Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n    {}\n    ~Image() = default;\n    Image& operator=(const Image& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = i.data_;\n        }\n        return *this;\n    }\n    Image& operator=(Image&& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = std::move(i.data_);\n        }\n        return *this;\n    }\n    size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n    bool operator()(unsigned x, unsigned y) {\n        return data_[idx(x, y)];\n    }\n    friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n        o << i.width_ << \" x \" << i.height_ << std::endl;\n        size_t px = 0;\n        for(const auto& e : i.data_) {\n            o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n            if (++px % i.width_ == 0)\n                o << std::endl;\n        }\n        return o << std::endl;\n    }\n    friend std::istream& operator>>(std::istream& in, Image& img) {\n        auto it = std::begin(img.data_);\n        const auto end = std::end(img.data_);\n        Image::pixel_t tmp;\n        while(in && it != end) {\n            in >> tmp;\n            if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n                throw \"Bad character found in image\";\n            *it = (tmp == Image::BLACK_PIX)?1:0;\n            ++it;\n        }\n        return in;\n    }\n    unsigned width() const noexcept { return width_; }\n    unsigned height() const noexcept { return height_; }\n    struct Neighbours {\n        \n        \n        \n        Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n        : img_{img}\n        , p1_{img.idx(p1_x, p1_y)}\n        , p2_{p1_ - img.width()}\n        , p3_{p2_ + 1}\n        , p4_{p1_ + 1}\n        , p5_{p4_ + img.width()}\n        , p6_{p5_ - 1}\n        , p7_{p6_ - 1}\n        , p8_{p1_ - 1}\n        , p9_{p2_ - 1} \n        {}\n        const Image& img_;\n        const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n        const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n        const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n        const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n        const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n        const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n        const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n        const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n        const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n        const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n    };\n    Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n    unsigned height_ { 0 };\n    unsigned width_ { 0 };\n    std::valarray<pixel_t> data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n    \n    unsigned transitions_white_black(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += (a.p9() == 0) && a.p2();\n        sum += (a.p2() == 0) && a.p3();\n        sum += (a.p3() == 0) && a.p4();\n        sum += (a.p8() == 0) && a.p9();\n        sum += (a.p4() == 0) && a.p5();\n        sum += (a.p7() == 0) && a.p8();\n        sum += (a.p6() == 0) && a.p7();\n        sum += (a.p5() == 0) && a.p6();\n        return sum;\n    }\n\n    \n    unsigned black_pixels(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += a.p9();\n        sum += a.p2();\n        sum += a.p3();\n        sum += a.p8();\n        sum += a.p4();\n        sum += a.p7();\n        sum += a.p6();\n        sum += a.p5();\n        return sum;\n    }\n    const Image& operator()(const Image& img) {\n        tmp_a_ = img;\n        size_t changed_pixels = 0;\n        do {\n            changed_pixels = 0;\n            \n            tmp_b_ = tmp_a_;\n            for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n                    if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n                        auto n = tmp_a_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p6() == 0)\n                                && (n.p4() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_b_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n            \n            tmp_a_ = tmp_b_;\n            for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n                    if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n                        auto n = tmp_b_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p8() == 0)\n                                && (n.p2() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_a_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n        } while(changed_pixels > 0);\n        return tmp_a_;\n    }\nprivate:\n    Image tmp_a_;\n    Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n    using namespace std;\n    Image img(32, 10);\n    istringstream iss{input};\n    iss >> img;\n    cout << img;\n    cout << \"ZhangSuen\" << endl;\n    ZhangSuen zs;\n    Image res = std::move(zs(img));\n    cout << res << endl;\n\n    Image img2(58,18);\n    istringstream iss2{input2};\n    iss2 >> img2;\n    cout << img2;\n    cout << \"ZhangSuen with big image\" << endl;\n    Image res2 = std::move(zs(img2));\n    cout << res2 << endl;\n    return 0;\n}\n", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n"}
{"id": 51211, "name": "Variable declaration reset", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n"}
{"id": 51212, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n"}
{"id": 51213, "name": "Words from neighbour ones", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n"}
{"id": 51214, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n"}
{"id": 51215, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 51216, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n"}
{"id": 51217, "name": "Brace expansion", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51218, "name": "GUI component interaction", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 51219, "name": "GUI component interaction", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 51220, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n"}
{"id": 51221, "name": "Spelling of ordinal numbers", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n"}
{"id": 51222, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 51223, "name": "Addition chains", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 51224, "name": "Repeat", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n"}
{"id": 51225, "name": "Sparkline in unicode", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 51226, "name": "Sparkline in unicode", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 51227, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 51228, "name": "Chemical calculator", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51229, "name": "Pythagorean quadruples", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n"}
{"id": 51230, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 51231, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n"}
{"id": 51232, "name": "Zebra puzzle", "C++": "#include <stdio.h>\n#include <string.h>\n\n#define defenum(name, val0, val1, val2, val3, val4) \\\n    enum name { val0, val1, val2, val3, val4 }; \\\n    const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }\n\ndefenum( Attrib,    Color, Man, Drink, Animal, Smoke );\ndefenum( Colors,    Red, Green, White, Yellow, Blue );\ndefenum( Mans,      English, Swede, Dane, German, Norwegian );\ndefenum( Drinks,    Tea, Coffee, Milk, Beer, Water );\ndefenum( Animals,   Dog, Birds, Cats, Horse, Zebra );\ndefenum( Smokes,    PallMall, Dunhill, Blend, BlueMaster, Prince );\n\nvoid printHouses(int ha[5][5]) {\n    const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};\n\n    printf(\"%-10s\", \"House\");\n    for (const char *name : Attrib_str) printf(\"%-10s\", name);\n    printf(\"\\n\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        for (int j = 0; j < 5; j++) printf(\"%-10s\", attr_names[j][ha[i][j]]);\n        printf(\"\\n\");\n    }\n}\n\nstruct HouseNoRule {\n    int houseno;\n    Attrib a; int v;\n} housenos[] = {\n    {2, Drink, Milk},     \n    {0, Man, Norwegian}   \n};\n\nstruct AttrPairRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&\n               ((ha[i][a1] == v1 && ha[i][a2] != v2) ||\n                (ha[i][a1] != v1 && ha[i][a2] == v2));\n    }\n} pairs[] = {\n    {Man, English,      Color, Red},     \n    {Man, Swede,        Animal, Dog},    \n    {Man, Dane,         Drink, Tea},     \n    {Color, Green,      Drink, Coffee},  \n    {Smoke, PallMall,   Animal, Birds},  \n    {Smoke, Dunhill,    Color, Yellow},  \n    {Smoke, BlueMaster, Drink, Beer},    \n    {Man, German,       Smoke, Prince}    \n};\n\nstruct NextToRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] == v1) &&\n               ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||\n                (i == 4 && ha[i - 1][a2] != v2) ||\n                (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));\n    }\n} nexttos[] = {\n    {Smoke, Blend,      Animal, Cats},    \n    {Smoke, Dunhill,    Animal, Horse},   \n    {Man, Norwegian,    Color, Blue},     \n    {Smoke, Blend,      Drink, Water}     \n};\n\nstruct LeftOfRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5]) {\n        return (ha[0][a2] == v2) || (ha[4][a1] == v1);\n    }\n\n    bool invalid(int ha[5][5], int i) {\n        return ((i > 0 && ha[i][a1] >= 0) &&\n                ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||\n                 (ha[i - 1][a1] != v1 && ha[i][a2] == v2)));\n    }\n} leftofs[] = {\n    {Color, Green,  Color, White}     \n};\n\nbool invalid(int ha[5][5]) {\n    for (auto &rule : leftofs) if (rule.invalid(ha)) return true;\n\n    for (int i = 0; i < 5; i++) {\n#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;\n        eval_rules(pairs);\n        eval_rules(nexttos);\n        eval_rules(leftofs);\n    }\n    return false;\n}\n\nvoid search(bool used[5][5], int ha[5][5], const int hno, const int attr) {\n    int nexthno, nextattr;\n    if (attr < 4) {\n        nextattr = attr + 1;\n        nexthno = hno;\n    } else {\n        nextattr = 0;\n        nexthno = hno + 1;\n    }\n\n    if (ha[hno][attr] != -1) {\n        search(used, ha, nexthno, nextattr);\n    } else {\n        for (int i = 0; i < 5; i++) {\n            if (used[attr][i]) continue;\n            used[attr][i] = true;\n            ha[hno][attr] = i;\n\n            if (!invalid(ha)) {\n                if ((hno == 4) && (attr == 4)) {\n                    printHouses(ha);\n                } else {\n                    search(used, ha, nexthno, nextattr);\n                }\n            }\n\n            used[attr][i] = false;\n        }\n        ha[hno][attr] = -1;\n    }\n}\n\nint main() {\n    bool used[5][5] = {};\n    int ha[5][5]; memset(ha, -1, sizeof(ha));\n\n    for (auto &rule : housenos) {\n        ha[rule.houseno][rule.a] = rule.v;\n        used[rule.a][rule.v] = true;\n    }\n\n    search(used, ha, 0, 0);\n\n    return 0;\n}\n", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n"}
{"id": 51233, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 51234, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n"}
{"id": 51235, "name": "Practical numbers", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n"}
{"id": 51236, "name": "Literals_Floating point", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n"}
{"id": 51237, "name": "Word search", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51238, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 51239, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 51240, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 51241, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 51242, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 51243, "name": "Long year", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n"}
{"id": 51244, "name": "Zumkeller numbers", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n"}
{"id": 51245, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 51246, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 51247, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 51248, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 51249, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 51250, "name": "Dijkstra's algorithm", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n"}
{"id": 51251, "name": "Geometric algebra", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n"}
{"id": 51252, "name": "Associative array_Iteration", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n"}
{"id": 51253, "name": "Define a primitive data type", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n"}
{"id": 51254, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n"}
{"id": 51255, "name": "Sierpinski square curve", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n"}
{"id": 51256, "name": "Find words whose first and last three letters are equal", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        const size_t len = word.size();\n        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)\n            std::cout << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\nset d= createobject(\"Scripting.Dictionary\")\nfor each aa in a\n  x=trim(aa)\n  l=len(x)\n  if l>5 then\n   d.removeall\n   for i=1 to 3\n     m=mid(x,i,1)\n     if not d.exists(m) then d.add m,null\n   next\n   res=true\n   for i=l-2 to l\n     m=mid(x,i,1)\n     if not d.exists(m) then \n       res=false:exit for \n      else\n        d.remove(m)\n      end if        \n   next \n   if res then \n     wscript.stdout.write left(x & space(15),15)\n     if left(x,3)=right(x,3) then  wscript.stdout.write \"*\"\n     wscript.stdout.writeline\n    end if \n  end if\nnext\n"}
{"id": 51257, "name": "Word break problem", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51258, "name": "Latin Squares in reduced form", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51259, "name": "UPC", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n"}
{"id": 51260, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 51261, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 51262, "name": "Playfair cipher", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 51263, "name": "Closest-pair problem", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n"}
{"id": 51264, "name": "Address of a variable", "C++": "int i;\nvoid* address_of_i = &i;\n", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n"}
{"id": 51265, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n"}
{"id": 51266, "name": "Associative array_Creation", "C++": "#include <map>\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 51267, "name": "Associative array_Creation", "C++": "#include <map>\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 51268, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n"}
{"id": 51269, "name": "Color wheel", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n"}
{"id": 51270, "name": "Find words which contain the most consonants", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n"}
{"id": 51271, "name": "Find words which contain the most consonants", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n"}
{"id": 51272, "name": "Minesweeper game", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\nusing namespace std;\ntypedef unsigned char byte;\n\nenum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };\n\nclass fieldData\n{\npublic:\n    fieldData() : value( CLOSED ), open( false ) {}\n    byte value;\n    bool open, mine;\n};\n\nclass game\n{\npublic:\n    ~game()\n    { if( field ) delete [] field; }\n\n    game( int x, int y )\n    {\n        go = false; wid = x; hei = y;\n\tfield = new fieldData[x * y];\n\tmemset( field, 0, x * y * sizeof( fieldData ) );\n\toMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;\n\tmMines = 0;\n\tint mx, my, m = 0;\n\tfor( ; m < oMines; m++ )\n\t{\n\t    do\n\t    { mx = rand() % wid; my = rand() % hei; }\n\t    while( field[mx + wid * my].mine );\n\t    field[mx + wid * my].mine = true;\n\t}\n\tgraphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; \n\tgraphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; \n    }\n\t\n    void gameLoop()\n    {\n\tstring c, r, a;\n\tint col, row;\n\twhile( !go )\n\t{\n\t    drawBoard();\n\t    cout << \"Enter column, row and an action( c r a ):\\nActions: o => open, f => flag, ? => unknown\\n\";\n\t    cin >> c >> r >> a;\n\t    if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;\n\t    col = c[0] - 65; row = r[0] - 49;\n\t    makeMove( col, row, a );\n\t}\n    }\n\nprivate:\n    void makeMove( int x, int y, string a )\n    {\n\tfieldData* fd = &field[wid * y + x];\n\tif( fd->open && fd->value < CLOSED )\n\t{\n\t    cout << \"This cell is already open!\";\n\t    Sleep( 3000 ); return;\n\t}\n\tif( a[0] == 'O' ) openCell( x, y );\n\telse if( a[0] == 'F' ) \n\t{\n\t    fd->open = true;\n\t    fd->value = FLAG;\n\t    mMines++;\n\t    checkWin();\n\t}\n\telse\n\t{\n\t    fd->open = true;\n\t    fd->value = UNKNOWN;\n\t}\n    }\n\n    bool openCell( int x, int y )\n    {\n\tif( !isInside( x, y ) ) return false;\n\tif( field[x + y * wid].mine ) boom();\n\telse \n\t{\n\t    if( field[x + y * wid].value == FLAG )\n\t    {\n\t\tfield[x + y * wid].value = CLOSED;\n\t\tfield[x + y * wid].open = false;\n\t\tmMines--;\n\t    }\n\t    recOpen( x, y );\n\t    checkWin();\n\t}\n\treturn true;\n    }\n\n    void drawBoard()\n    {\n\tsystem( \"cls\" );\n\tcout << \"Marked mines: \" << mMines << \" from \" << oMines << \"\\n\\n\";\t\t\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"  \" << ( char )( 65 + x ) << \" \"; \n\tcout << \"\\n\"; int yy;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = y * wid;\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << \"+---\";\n\n\t    cout << \"+\\n\"; fieldData* fd;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy]; cout<< \"| \";\n\t\tif( !fd->open ) cout << ( char )graphs[1] << \" \";\n\t\telse \n\t\t{\n\t\t    if( fd->value > 9 )\n\t\t\tcout << ( char )graphs[fd->value - 9] << \" \";\n\t\t    else\n\t\t    {\n\t\t\tif( fd->value < 1 ) cout << \"  \";\n\t\t\t    else cout << ( char )(fd->value + 48 ) << \" \";\n\t\t    }\n\t\t}\n\t    }\n\t    cout << \"| \" << y + 1 << \"\\n\";\n\t}\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"+---\";\n\n\tcout << \"+\\n\\n\";\n    }\n\n    void checkWin()\n    {\n\tint z = wid * hei - oMines, yy;\n\tfieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->open && fd->value != FLAG ) z--;\n\t    }\n\t}\n\tif( !z ) lastMsg( \"Congratulations, you won the game!\");\n    }\n\n    void boom()\n    {\n\tint yy; fieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->value == FLAG )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = fd->mine ? MINE : ERR;\n\t\t}\n\t\telse if( fd->mine )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = MINE;\n\t\t}\n\t    }\n\t}\n\tlastMsg( \"B O O O M M M M M !\" );\n    }\n\n    void lastMsg( string s )\n    {\n\tgo = true; drawBoard();\n\tcout << s << \"\\n\\n\";\n    }\n\n    bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }\n\n    void recOpen( int x, int y )\n    {\n\tif( !isInside( x, y ) || field[x + y * wid].open ) return;\n\tint bc = getMineCount( x, y );\n\tfield[x + y * wid].open = true;\n\tfield[x + y * wid].value = bc;\n\tif( bc ) return;\n\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\trecOpen( x + xx, y + yy );\n\t    }\n    }\n\n    int getMineCount( int x, int y )\n    {\n\tint m = 0;\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\tif( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;\n\t    }\n\t\t\n\treturn m;\n    }\n\t\n    int wid, hei, mMines, oMines;\n    fieldData* field; bool go;\n    int graphs[6];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    game g( 4, 6 ); g.gameLoop();\n    return system( \"pause\" );\n}\n", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n"}
{"id": 51273, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n"}
{"id": 51274, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n"}
{"id": 51275, "name": "Nested templated data", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n", "VB": "Public Sub test()\n    Dim t(2) As Variant\n    t(0) = [{1,2}]\n    t(1) = [{3,4,1}]\n    t(2) = 5\n    p = [{\"Payload#0\",\"Payload#1\",\"Payload#2\",\"Payload#3\",\"Payload#4\",\"Payload#5\",\"Payload#6\"}]\n    Dim q(6) As Boolean\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            For j = LBound(t(i)) To UBound(t(i))\n                q(t(i)(j)) = True\n                t(i)(j) = p(t(i)(j) + 1)\n            Next j\n        Else\n            q(t(i)) = True\n            t(i) = p(t(i) + 1)\n        End If\n    Next i\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            Debug.Print Join(t(i), \", \")\n        Else\n            Debug.Print t(i)\n        End If\n    Next i\n    For i = LBound(q) To UBound(q)\n        If Not q(i) Then Debug.Print p(i + 1); \" is not used\"\n    Next i\nEnd Sub\n"}
{"id": 51276, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/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": 51277, "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", "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": 51278, "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", "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": 51279, "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", "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": 51280, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 51281, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51282, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51283, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 51284, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 51285, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\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": 51286, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 51287, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 51288, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 51289, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 51290, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 51291, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 51292, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 51293, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 51294, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 51295, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 51296, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 51297, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 51298, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 51299, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 51300, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n"}
{"id": 51301, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 51302, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 51303, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 51304, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 51305, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 51306, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 51307, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 51308, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 51309, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n"}
{"id": 51310, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 51311, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 51312, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 51313, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 51314, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n"}
{"id": 51315, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 51316, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 51317, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 51318, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 51319, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n"}
{"id": 51320, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 51321, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 51322, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 51323, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 51324, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n"}
{"id": 51325, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 51326, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n"}
{"id": 51327, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 51328, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 51329, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n"}
{"id": 51330, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n"}
{"id": 51331, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 51332, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 51333, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 51334, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 51335, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n"}
{"id": 51336, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 51337, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 51338, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 51339, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n"}
{"id": 51340, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n"}
{"id": 51341, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 51342, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n"}
{"id": 51343, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n"}
{"id": 51344, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n"}
{"id": 51345, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n"}
{"id": 51346, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 51347, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n"}
{"id": 51348, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n"}
{"id": 51349, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 51350, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 51351, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n"}
{"id": 51352, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n"}
{"id": 51353, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n"}
{"id": 51354, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "C#": "int j;\n"}
{"id": 51355, "name": "Add a variable to a class instance at runtime", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n", "C#": "\n\n\n\n\n\n\n\nusing System;\nusing System.Dynamic;\n\nnamespace DynamicClassVariable\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            \n            \n            dynamic sampleObj = new ExpandoObject();\n            \n            sampleObj.bar = 1;\n            Console.WriteLine( \"sampleObj.bar = {0}\", sampleObj.bar );\n\n            \n            \n            \n            \n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 51356, "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": 51357, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 51358, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 51359, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 51360, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51361, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51362, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51363, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51364, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51365, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51366, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 51367, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 51368, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 51369, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 51370, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 51371, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 51372, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 51373, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 51374, "name": "Entropy_Narcissist", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\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": 51375, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 51376, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 51377, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\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": 51378, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 51379, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 51380, "name": "Rock-paper-scissors", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\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": 51381, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(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": 51382, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(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": 51383, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(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": 51384, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 51385, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 51386, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 51387, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download 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": 51388, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download 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": 51389, "name": "FTP", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download 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": 51390, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 51391, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 51392, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 51393, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 51394, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 51395, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\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": 51396, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 51397, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 51398, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\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": 51399, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 51400, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 51401, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 51402, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 51403, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 51404, "name": "Colour bars_Display", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\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": 51405, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\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": 51406, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\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": 51407, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\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": 51408, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\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": 51409, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\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": 51410, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\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": 51411, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\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": 51412, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\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": 51413, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\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": 51414, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 51415, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 51416, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 51417, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 51418, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 51419, "name": "File extension is in extensions list", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 51420, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\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": 51421, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\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": 51422, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\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": 51423, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\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": 51424, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\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": 51425, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\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": 51426, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\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": 51427, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\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": 51428, "name": "Date manipulation", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\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": 51429, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\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": 51430, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\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": 51431, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\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": 51432, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\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": 51433, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\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": 51434, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\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": 51435, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 51436, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 51437, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 51438, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 51439, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 51440, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\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": 51441, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 51442, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 51443, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 51444, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\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": 51445, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\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": 51446, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\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": 51447, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 51448, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 51449, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 51450, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\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": 51451, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\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": 51452, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\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": 51453, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\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": 51454, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\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": 51455, "name": "Sorting algorithms_Stooge sort", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\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": 51456, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\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": 51457, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\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": 51458, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\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": 51459, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\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": 51460, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\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": 51461, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\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": 51462, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$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": 51463, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$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": 51464, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$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": 51465, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\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": 51466, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\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": 51467, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\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": 51468, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\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": 51469, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\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": 51470, "name": "Singleton", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\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": 51471, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\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": 51472, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\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": 51473, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\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": 51474, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 51475, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 51476, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 51477, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 51478, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 51479, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 51480, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 51481, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 51482, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 51483, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\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": 51484, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\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": 51485, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\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": 51486, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\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": 51487, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\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": 51488, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\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": 51489, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 51490, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 51491, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 51492, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\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": 51493, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\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": 51494, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\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": 51495, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\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": 51496, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\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": 51497, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\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": 51498, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\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": 51499, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\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": 51500, "name": "Man or boy test", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\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": 51501, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 51502, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 51503, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 51504, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 51505, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 51506, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 51507, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 51508, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 51509, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 51510, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 51511, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 51512, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 51513, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 51514, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 51515, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 51516, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 51517, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 51518, "name": "Inverted index", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 51519, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 51520, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 51521, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 51522, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 51523, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 51524, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 51525, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 51526, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 51527, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 51528, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 51529, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 51530, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 51531, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 51532, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 51533, "name": "Hello world_Line printer", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n"}
{"id": 51534, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 51535, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 51536, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 51537, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 51538, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 51539, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 51540, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 51541, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 51542, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 51543, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n"}
{"id": 51544, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n"}
{"id": 51545, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n"}
{"id": 51546, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 51547, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 51548, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 51549, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 51550, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 51551, "name": "Bitmap_Histogram", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n"}
{"id": 51552, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 51553, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 51554, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 51555, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 51556, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 51557, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 51558, "name": "SOAP", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n"}
{"id": 51559, "name": "SOAP", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n"}
{"id": 51560, "name": "SOAP", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n"}
{"id": 51561, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 51562, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 51563, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 51564, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 51565, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 51566, "name": "Modulinos", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n"}
{"id": 51567, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 51568, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 51569, "name": "Unix_ls", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 51570, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 51571, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 51572, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 51573, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n"}
{"id": 51574, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n"}
{"id": 51575, "name": "Active Directory_Search for a user", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n"}
{"id": 51576, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 51577, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 51578, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 51579, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 51580, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 51581, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 51582, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 51583, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 51584, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 51585, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 51586, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 51587, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 51588, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 51589, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 51590, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 51591, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 51592, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 51593, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 51594, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 51595, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 51596, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 51597, "name": "Bitmap_Bézier curves_Cubic", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n"}
{"id": 51598, "name": "Bitmap_Bézier curves_Cubic", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n"}
{"id": 51599, "name": "Bitmap_Bézier curves_Cubic", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n"}
{"id": 51600, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 51601, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 51602, "name": "Active Directory_Connect", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 51603, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 51604, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 51605, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 51606, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 51607, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 51608, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 51609, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51610, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51611, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51612, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51613, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51614, "name": "Church numerals", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51615, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 51616, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 51617, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 51618, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 51619, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 51620, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 51621, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 51622, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 51623, "name": "Object serialization", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 51624, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51625, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51626, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51627, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 51628, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 51629, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 51630, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 51631, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 51632, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 51633, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 51634, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 51635, "name": "Markov chain text generator", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 51636, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 51637, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 51638, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 51639, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 51640, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 51641, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 51642, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Python": "print()\n"}
{"id": 51643, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Python": "print()\n"}
{"id": 51644, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Python": "print()\n"}
{"id": 51645, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Python": "print()\n"}
{"id": 51646, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Python": "print()\n"}
{"id": 51647, "name": "Here document", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n", "Python": "print()\n"}
{"id": 51648, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 51649, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 51650, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 51651, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n"}
{"id": 51652, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n"}
{"id": 51653, "name": "Respond to an unknown method call", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n"}
{"id": 51654, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 51655, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 51656, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 51657, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 51658, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 51659, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 51660, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 51661, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 51662, "name": "Polymorphism", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 51663, "name": "Minesweeper game", "PHP": "<?php\ndefine('MINEGRID_WIDTH',  6);\ndefine('MINEGRID_HEIGHT', 4);\n\ndefine('MINESWEEPER_NOT_EXPLORED', -1);\ndefine('MINESWEEPER_MINE',         -2);\ndefine('MINESWEEPER_FLAGGED',      -3);\ndefine('MINESWEEPER_FLAGGED_MINE', -4);\ndefine('ACTIVATED_MINE',           -5);\n\nfunction check_field($field) {\n    if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nfunction explore_field($field) {\n    if (!isset($_SESSION['minesweeper'][$field])\n     || !in_array($_SESSION['minesweeper'][$field],\n                  array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {\n        return;\n    }\n\n    $mines = 0;\n\n    $fields  = &$_SESSION['minesweeper'];\n\n\n    if ($field % MINEGRID_WIDTH !== 1) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);\n        $mines += check_field(@$fields[$field - 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);\n    }\n\n    $mines += check_field(@$fields[$field - MINEGRID_WIDTH]);\n    $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);\n\n    if ($field % MINEGRID_WIDTH !== 0) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);\n        $mines += check_field(@$fields[$field + 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);\n    }\n    \n    $fields[$field] = $mines;\n    \n    if ($mines === 0) {\n        if ($field % MINEGRID_WIDTH !== 1) {\n            explore_field($field - MINEGRID_WIDTH - 1);\n            explore_field($field - 1);\n            explore_field($field + MINEGRID_WIDTH - 1);\n        }\n        \n        explore_field($field - MINEGRID_WIDTH);\n        explore_field($field + MINEGRID_WIDTH);\n        \n        if ($field % MINEGRID_WIDTH !== 0) {\n            explore_field($field - MINEGRID_WIDTH + 1);\n            explore_field($field + 1);\n            explore_field($field + MINEGRID_WIDTH + 1);\n        }\n    }\n}\n\nsession_start(); // will start session storage\n\nif (!isset($_SESSION['minesweeper'])) {\n\n    $_SESSION['minesweeper'] = array_fill(1,\n                                         MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                         MINESWEEPER_NOT_EXPLORED);\n\n    $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                     0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);\n\n    $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);\n    \n    foreach ($random_keys as $key) {\n        $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;\n    }\n\n    $_SESSION['numberofmines'] = $number_of_mines;\n}\n\nif (isset($_GET['explore'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['explore']])) {\n        switch ($_SESSION['minesweeper'][$_GET['explore']]) {\n            case MINESWEEPER_NOT_EXPLORED:\n                explore_field($_GET['explore']);\n                break;\n            case MINESWEEPER_MINE:\n                $lost = 1;\n                $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\nelseif (isset($_GET['flag'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['flag']])) {\n        $tile = &$_SESSION['minesweeper'][$_GET['flag']];\n        switch ($tile) {\n            case MINESWEEPER_NOT_EXPLORED:\n                $tile = MINESWEEPER_FLAGGED;\n                break;\n            case MINESWEEPER_MINE:\n                $tile = MINESWEEPER_FLAGGED_MINE;\n                break;\n            case MINESWEEPER_FLAGGED:\n                $tile = MINESWEEPER_NOT_EXPLORED;\n                break;\n            case MINESWEEPER_FLAGGED_MINE:\n                $tile = MINESWEEPER_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\n\nif (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])\n && !in_array(MINESWEEPER_FLAGGED,      $_SESSION['minesweeper'])) {\n    $won = true;\n}\n?>\n<!DOCTYPE html>\n<title>Minesweeper</title>\n<style>\ntable {\n    border-collapse: collapse;\n}\n\ntd, a {\n    text-align:      center;\n    width:           1em;\n    height:          1em;\n}\n\na {\n    display:         block;\n    color:           black;\n    text-decoration: none;\n    font-size:       2em;\n}\n</style>\n<script>\nfunction flag(number, e) {\n    if (e.which === 2 || e.which === 3) {\n        location = '?flag=' + number;\n        return false;\n    }\n}\n</script>\n<?php\n    echo \"<p>This field contains $_SESSION[numberofmines] mines.\";\n?>\n<table border=\"1\">\n<?php\n\n$mine_copy = $_SESSION['minesweeper'];\n\nfor ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {\n    echo '<tr>';\n    for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {\n        echo '<td>';\n        \n        $number = array_shift($mine_copy);\n        switch ($number) {\n            case MINESWEEPER_FLAGGED:\n            case MINESWEEPER_FLAGGED_MINE:\n                if (!empty($lost) || !empty($won)) {\n                    if ($number === MINESWEEPER_FLAGGED_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                else {\n                    echo '<a href=# onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">?</a>';\n                }\n                break;\n            case ACTIVATED_MINE:\n                echo '<a>:(</a>';\n                break;\n            case MINESWEEPER_MINE:\n            case MINESWEEPER_NOT_EXPLORED:\n\n\n\n\n                \n                if (!empty($lost)) {\n                    if ($number === MINESWEEPER_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                elseif (!empty($won)) {\n                    echo '<a>*</a>';\n                }\n                else {\n                    echo '<a href=\"?explore=',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         '\" onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">.</a>';\n                }\n                break;\n            case 0:\n                echo '<a></a>';\n                break;\n            default:\n                echo '<a>', $number, '</a>';\n                break;\n        }\n    }\n}\n?>\n</table>\n<?php\nif (!empty($lost)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>You lost :(. <a href=\"?\">Reboot?</a>';\n}\nelseif (!empty($won)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>Congratulations. You won :).';\n}\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 51664, "name": "Minesweeper game", "PHP": "<?php\ndefine('MINEGRID_WIDTH',  6);\ndefine('MINEGRID_HEIGHT', 4);\n\ndefine('MINESWEEPER_NOT_EXPLORED', -1);\ndefine('MINESWEEPER_MINE',         -2);\ndefine('MINESWEEPER_FLAGGED',      -3);\ndefine('MINESWEEPER_FLAGGED_MINE', -4);\ndefine('ACTIVATED_MINE',           -5);\n\nfunction check_field($field) {\n    if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nfunction explore_field($field) {\n    if (!isset($_SESSION['minesweeper'][$field])\n     || !in_array($_SESSION['minesweeper'][$field],\n                  array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {\n        return;\n    }\n\n    $mines = 0;\n\n    $fields  = &$_SESSION['minesweeper'];\n\n\n    if ($field % MINEGRID_WIDTH !== 1) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);\n        $mines += check_field(@$fields[$field - 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);\n    }\n\n    $mines += check_field(@$fields[$field - MINEGRID_WIDTH]);\n    $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);\n\n    if ($field % MINEGRID_WIDTH !== 0) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);\n        $mines += check_field(@$fields[$field + 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);\n    }\n    \n    $fields[$field] = $mines;\n    \n    if ($mines === 0) {\n        if ($field % MINEGRID_WIDTH !== 1) {\n            explore_field($field - MINEGRID_WIDTH - 1);\n            explore_field($field - 1);\n            explore_field($field + MINEGRID_WIDTH - 1);\n        }\n        \n        explore_field($field - MINEGRID_WIDTH);\n        explore_field($field + MINEGRID_WIDTH);\n        \n        if ($field % MINEGRID_WIDTH !== 0) {\n            explore_field($field - MINEGRID_WIDTH + 1);\n            explore_field($field + 1);\n            explore_field($field + MINEGRID_WIDTH + 1);\n        }\n    }\n}\n\nsession_start(); // will start session storage\n\nif (!isset($_SESSION['minesweeper'])) {\n\n    $_SESSION['minesweeper'] = array_fill(1,\n                                         MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                         MINESWEEPER_NOT_EXPLORED);\n\n    $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                     0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);\n\n    $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);\n    \n    foreach ($random_keys as $key) {\n        $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;\n    }\n\n    $_SESSION['numberofmines'] = $number_of_mines;\n}\n\nif (isset($_GET['explore'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['explore']])) {\n        switch ($_SESSION['minesweeper'][$_GET['explore']]) {\n            case MINESWEEPER_NOT_EXPLORED:\n                explore_field($_GET['explore']);\n                break;\n            case MINESWEEPER_MINE:\n                $lost = 1;\n                $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\nelseif (isset($_GET['flag'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['flag']])) {\n        $tile = &$_SESSION['minesweeper'][$_GET['flag']];\n        switch ($tile) {\n            case MINESWEEPER_NOT_EXPLORED:\n                $tile = MINESWEEPER_FLAGGED;\n                break;\n            case MINESWEEPER_MINE:\n                $tile = MINESWEEPER_FLAGGED_MINE;\n                break;\n            case MINESWEEPER_FLAGGED:\n                $tile = MINESWEEPER_NOT_EXPLORED;\n                break;\n            case MINESWEEPER_FLAGGED_MINE:\n                $tile = MINESWEEPER_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\n\nif (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])\n && !in_array(MINESWEEPER_FLAGGED,      $_SESSION['minesweeper'])) {\n    $won = true;\n}\n?>\n<!DOCTYPE html>\n<title>Minesweeper</title>\n<style>\ntable {\n    border-collapse: collapse;\n}\n\ntd, a {\n    text-align:      center;\n    width:           1em;\n    height:          1em;\n}\n\na {\n    display:         block;\n    color:           black;\n    text-decoration: none;\n    font-size:       2em;\n}\n</style>\n<script>\nfunction flag(number, e) {\n    if (e.which === 2 || e.which === 3) {\n        location = '?flag=' + number;\n        return false;\n    }\n}\n</script>\n<?php\n    echo \"<p>This field contains $_SESSION[numberofmines] mines.\";\n?>\n<table border=\"1\">\n<?php\n\n$mine_copy = $_SESSION['minesweeper'];\n\nfor ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {\n    echo '<tr>';\n    for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {\n        echo '<td>';\n        \n        $number = array_shift($mine_copy);\n        switch ($number) {\n            case MINESWEEPER_FLAGGED:\n            case MINESWEEPER_FLAGGED_MINE:\n                if (!empty($lost) || !empty($won)) {\n                    if ($number === MINESWEEPER_FLAGGED_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                else {\n                    echo '<a href=# onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">?</a>';\n                }\n                break;\n            case ACTIVATED_MINE:\n                echo '<a>:(</a>';\n                break;\n            case MINESWEEPER_MINE:\n            case MINESWEEPER_NOT_EXPLORED:\n\n\n\n\n                \n                if (!empty($lost)) {\n                    if ($number === MINESWEEPER_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                elseif (!empty($won)) {\n                    echo '<a>*</a>';\n                }\n                else {\n                    echo '<a href=\"?explore=',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         '\" onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">.</a>';\n                }\n                break;\n            case 0:\n                echo '<a></a>';\n                break;\n            default:\n                echo '<a>', $number, '</a>';\n                break;\n        }\n    }\n}\n?>\n</table>\n<?php\nif (!empty($lost)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>You lost :(. <a href=\"?\">Reboot?</a>';\n}\nelseif (!empty($won)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>Congratulations. You won :).';\n}\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 51665, "name": "Minesweeper game", "PHP": "<?php\ndefine('MINEGRID_WIDTH',  6);\ndefine('MINEGRID_HEIGHT', 4);\n\ndefine('MINESWEEPER_NOT_EXPLORED', -1);\ndefine('MINESWEEPER_MINE',         -2);\ndefine('MINESWEEPER_FLAGGED',      -3);\ndefine('MINESWEEPER_FLAGGED_MINE', -4);\ndefine('ACTIVATED_MINE',           -5);\n\nfunction check_field($field) {\n    if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nfunction explore_field($field) {\n    if (!isset($_SESSION['minesweeper'][$field])\n     || !in_array($_SESSION['minesweeper'][$field],\n                  array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {\n        return;\n    }\n\n    $mines = 0;\n\n    $fields  = &$_SESSION['minesweeper'];\n\n\n    if ($field % MINEGRID_WIDTH !== 1) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);\n        $mines += check_field(@$fields[$field - 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);\n    }\n\n    $mines += check_field(@$fields[$field - MINEGRID_WIDTH]);\n    $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);\n\n    if ($field % MINEGRID_WIDTH !== 0) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);\n        $mines += check_field(@$fields[$field + 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);\n    }\n    \n    $fields[$field] = $mines;\n    \n    if ($mines === 0) {\n        if ($field % MINEGRID_WIDTH !== 1) {\n            explore_field($field - MINEGRID_WIDTH - 1);\n            explore_field($field - 1);\n            explore_field($field + MINEGRID_WIDTH - 1);\n        }\n        \n        explore_field($field - MINEGRID_WIDTH);\n        explore_field($field + MINEGRID_WIDTH);\n        \n        if ($field % MINEGRID_WIDTH !== 0) {\n            explore_field($field - MINEGRID_WIDTH + 1);\n            explore_field($field + 1);\n            explore_field($field + MINEGRID_WIDTH + 1);\n        }\n    }\n}\n\nsession_start(); // will start session storage\n\nif (!isset($_SESSION['minesweeper'])) {\n\n    $_SESSION['minesweeper'] = array_fill(1,\n                                         MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                         MINESWEEPER_NOT_EXPLORED);\n\n    $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                     0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);\n\n    $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);\n    \n    foreach ($random_keys as $key) {\n        $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;\n    }\n\n    $_SESSION['numberofmines'] = $number_of_mines;\n}\n\nif (isset($_GET['explore'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['explore']])) {\n        switch ($_SESSION['minesweeper'][$_GET['explore']]) {\n            case MINESWEEPER_NOT_EXPLORED:\n                explore_field($_GET['explore']);\n                break;\n            case MINESWEEPER_MINE:\n                $lost = 1;\n                $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\nelseif (isset($_GET['flag'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['flag']])) {\n        $tile = &$_SESSION['minesweeper'][$_GET['flag']];\n        switch ($tile) {\n            case MINESWEEPER_NOT_EXPLORED:\n                $tile = MINESWEEPER_FLAGGED;\n                break;\n            case MINESWEEPER_MINE:\n                $tile = MINESWEEPER_FLAGGED_MINE;\n                break;\n            case MINESWEEPER_FLAGGED:\n                $tile = MINESWEEPER_NOT_EXPLORED;\n                break;\n            case MINESWEEPER_FLAGGED_MINE:\n                $tile = MINESWEEPER_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\n\nif (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])\n && !in_array(MINESWEEPER_FLAGGED,      $_SESSION['minesweeper'])) {\n    $won = true;\n}\n?>\n<!DOCTYPE html>\n<title>Minesweeper</title>\n<style>\ntable {\n    border-collapse: collapse;\n}\n\ntd, a {\n    text-align:      center;\n    width:           1em;\n    height:          1em;\n}\n\na {\n    display:         block;\n    color:           black;\n    text-decoration: none;\n    font-size:       2em;\n}\n</style>\n<script>\nfunction flag(number, e) {\n    if (e.which === 2 || e.which === 3) {\n        location = '?flag=' + number;\n        return false;\n    }\n}\n</script>\n<?php\n    echo \"<p>This field contains $_SESSION[numberofmines] mines.\";\n?>\n<table border=\"1\">\n<?php\n\n$mine_copy = $_SESSION['minesweeper'];\n\nfor ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {\n    echo '<tr>';\n    for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {\n        echo '<td>';\n        \n        $number = array_shift($mine_copy);\n        switch ($number) {\n            case MINESWEEPER_FLAGGED:\n            case MINESWEEPER_FLAGGED_MINE:\n                if (!empty($lost) || !empty($won)) {\n                    if ($number === MINESWEEPER_FLAGGED_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                else {\n                    echo '<a href=# onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">?</a>';\n                }\n                break;\n            case ACTIVATED_MINE:\n                echo '<a>:(</a>';\n                break;\n            case MINESWEEPER_MINE:\n            case MINESWEEPER_NOT_EXPLORED:\n\n\n\n\n                \n                if (!empty($lost)) {\n                    if ($number === MINESWEEPER_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                elseif (!empty($won)) {\n                    echo '<a>*</a>';\n                }\n                else {\n                    echo '<a href=\"?explore=',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         '\" onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">.</a>';\n                }\n                break;\n            case 0:\n                echo '<a></a>';\n                break;\n            default:\n                echo '<a>', $number, '</a>';\n                break;\n        }\n    }\n}\n?>\n</table>\n<?php\nif (!empty($lost)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>You lost :(. <a href=\"?\">Reboot?</a>';\n}\nelseif (!empty($won)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>Congratulations. You won :).';\n}\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 51666, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 51667, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 51668, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 51669, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 51670, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 51671, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 51672, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 51673, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 51674, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 51675, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 51676, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 51677, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 51678, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n"}
{"id": 51679, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n"}
{"id": 51680, "name": "Dynamic variable names", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n"}
{"id": 51681, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n"}
{"id": 51682, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n"}
{"id": 51683, "name": "Reflection_List methods", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n"}
{"id": 51684, "name": "Comments", "PHP": "# this is commented\n\n", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n"}
{"id": 51685, "name": "Comments", "PHP": "# this is commented\n\n", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n"}
{"id": 51686, "name": "Comments", "PHP": "# this is commented\n\n", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n"}
{"id": 51687, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n"}
{"id": 51688, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n"}
{"id": 51689, "name": "Send an unknown method call", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n"}
{"id": 51690, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 51691, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 51692, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 51693, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 51694, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 51695, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 51696, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 51697, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 51698, "name": "Runtime evaluation_In an environment", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n"}
{"id": 51699, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Python": ">>> exec \n10\n"}
{"id": 51700, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Python": ">>> exec \n10\n"}
{"id": 51701, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Python": ">>> exec \n10\n"}
{"id": 51702, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Python": ">>> exec \n10\n"}
{"id": 51703, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Python": ">>> exec \n10\n"}
{"id": 51704, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "Python": ">>> exec \n10\n"}
{"id": 51705, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51706, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51707, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51708, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51709, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51710, "name": "Permutations with repetitions", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 51711, "name": "OpenWebNet password", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n"}
{"id": 51712, "name": "OpenWebNet password", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n"}
{"id": 51713, "name": "OpenWebNet password", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n"}
{"id": 51714, "name": "Monads_Writer monad", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n"}
{"id": 51715, "name": "Monads_Writer monad", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n"}
{"id": 51716, "name": "Monads_Writer monad", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n"}
{"id": 51717, "name": "Canny edge detector", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n"}
{"id": 51718, "name": "Canny edge detector", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n"}
{"id": 51719, "name": "Canny edge detector", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n"}
{"id": 51720, "name": "Add a variable to a class instance at runtime", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n", "Python": "class empty(object):\n    pass\ne = empty()\n"}
{"id": 51721, "name": "Add a variable to a class instance at runtime", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n", "Python": "class empty(object):\n    pass\ne = empty()\n"}
{"id": 51722, "name": "Add a variable to a class instance at runtime", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n", "Python": "class empty(object):\n    pass\ne = empty()\n"}
{"id": 51723, "name": "Periodic table", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n"}
{"id": 51724, "name": "Periodic table", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n"}
{"id": 51725, "name": "Periodic table", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n"}
{"id": 51726, "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", "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": 51727, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/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": 51728, "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", "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": 51729, "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", "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": 51730, "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", "VB": "Public Sub Main() \n  \n  Print countSubstring(\"the three truths\", \"th\") \n  Print countSubstring(\"ababababab\", \"abab\") \n  Print countSubString(\"zzzzzzzzzzzzzzz\", \"z\")\n\nEnd \n\nFunction countSubstring(s As String, search As String) As Integer \n\n  If s = \"\" Or search = \"\" Then Return 0 \n  Dim count As Integer = 0, length As Integer = Len(search) \n  For i As Integer = 1 To Len(s) \n    If Mid(s, i, length) = Search Then \n      count += 1 \n      i += length - 1 \n    End If \n  Next \n  Return count \n\nEnd Function\n"}
{"id": 51731, "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", "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": 51732, "name": "Find common directory path", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\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": 51733, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51734, "name": "Recaman's sequence", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$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": 51735, "name": "Tic-tac-toe", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\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": 51736, "name": "DNS query", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n", "VB": "#include \"win\\winsock2.bi\"\n\nFunction GetSiteAddress(stuff As String = \"www.freebasic.net\") As Long\n    Dim As WSADATA _wsadate\n    Dim As in_addr addr\n    Dim As hostent Ptr res\n    Dim As Integer i = 0\n    \n    WSAStartup(MAKEWORD(2,2),@_wsadate)\n    res = gethostbyname(stuff)\n    \n    If res Then\n        Print !\"\\nURL: \"; stuff\n        While (res->h_addr_list[i] <> 0)\n            addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i]))\n            Print \"IPv4 address: \";*inet_ntoa(addr)\n            i+=1\n        Wend\n        WSACleanup()\n        Return 1\n    Else\n        Print \"website error?\"\n        Return 0\n    End If\nEnd Function\n\nGetSiteAddress \"rosettacode.org\"\nGetSiteAddress \"www.kame.net\"\n\nSleep\n"}
{"id": 51737, "name": "Y combinator", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 51738, "name": "Return multiple values", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n"}
{"id": 51739, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 51740, "name": "24 game", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 51741, "name": "Loops_Continue", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 51742, "name": "General FizzBuzz", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 51743, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 51744, "name": "Read a specific line from a file", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 51745, "name": "String case", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 51746, "name": "MD5", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 51747, "name": "Sorting algorithms_Sleep sort", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 51748, "name": "Loops_Nested", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 51749, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 51750, "name": "Pythagorean triples", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 51751, "name": "Remove duplicate elements", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 51752, "name": "Look-and-say sequence", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 51753, "name": "Stack", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 51754, "name": "Conditional structures", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 51755, "name": "Read a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n"}
{"id": 51756, "name": "Sort using a custom comparator", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 51757, "name": "Sorting algorithms_Selection sort", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 51758, "name": "Apply a callback to an array", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 51759, "name": "Case-sensitivity of identifiers", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n"}
{"id": 51760, "name": "Loops_Downward for", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n"}
{"id": 51761, "name": "Write entire file", "PHP": "file_put_contents($filename, $data)\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 51762, "name": "Loops_For", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 51763, "name": "Long multiplication", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51764, "name": "Bulls and cows", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 51765, "name": "Sorting algorithms_Bubble sort", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 51766, "name": "File input_output", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 51767, "name": "Arithmetic_Integer", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 51768, "name": "Matrix transposition", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 51769, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 51770, "name": "Find limit of recursion", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 51771, "name": "Perfect numbers", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 51772, "name": "Sorting algorithms_Bead sort", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 51773, "name": "Arbitrary-precision integers (included)", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 51774, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 51775, "name": "Least common multiple", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 51776, "name": "Loops_Break", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 51777, "name": "Trabb Pardo–Knuth algorithm", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n", "VB": "dim s(10)\nprint \"Enter 11 numbers.\"\nfor i = 0 to 10\n  print i +1;\n  input \" => \"; s(i)\nnext i\nprint\n\nfor i = 10 to 0 step -1\n  print \"f(\"; s(i); \") = \";\n  r = f(s(i))\n  if r > 400 then\n    print \"-=< overflow >=-\"\n  else\n    print r\n  end if\nnext i\nend\n\nfunction f(n)\n  f = sqr(abs(n)) + 5 * n * n * n\nend function\n"}
{"id": 51778, "name": "Middle three digits", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 51779, "name": "Odd word problem", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 51780, "name": "Table creation_Postal addresses", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n"}
{"id": 51781, "name": "Soundex", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n"}
{"id": 51782, "name": "Literals_String", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n"}
{"id": 51783, "name": "Enumerations", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 51784, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 51785, "name": "Execute Brain____", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 51786, "name": "Calendar - for _REAL_ programmers", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n", "VB": "OPTION COMPARE BINARY\nOPTION EXPLICIT ON\nOPTION INFER ON\nOPTION STRICT ON\n\nIMPORTS SYSTEM.GLOBALIZATION\nIMPORTS SYSTEM.TEXT\nIMPORTS SYSTEM.RUNTIME.INTEROPSERVICES\nIMPORTS SYSTEM.RUNTIME.COMPILERSERVICES\n\nMODULE ARGHELPER\n    READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()\n\n    DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN\n\n    SUB INITIALIZEARGUMENTS(ARGS AS STRING())\n        FOR EACH ITEM IN ARGS\n            ITEM = ITEM.TOUPPERINVARIANT()\n\n            IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> \"\"\"\"C THEN\n                DIM COLONPOS = ITEM.INDEXOF(\":\"C, STRINGCOMPARISON.ORDINAL)\n\n                IF COLONPOS <> -1 THEN\n                    \n                    _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))\n                END IF\n            END IF\n        NEXT\n    END SUB\n\n    SUB FROMARGUMENT(OF T)(\n            KEY AS STRING,\n            <OUT> BYREF VAR AS T,\n            GETDEFAULT AS FUNC(OF T),\n            TRYPARSE AS TRYPARSE(OF STRING, T),\n            OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)\n\n        DIM VALUE AS STRING = NOTHING\n        IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN\n            IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN\n                CONSOLE.WRITELINE($\"INVALID VALUE FOR {KEY}: {VALUE}\")\n                ENVIRONMENT.EXIT(-1)\n            END IF\n        ELSE\n            VAR = GETDEFAULT()\n        END IF\n    END SUB\nEND MODULE\n\nMODULE PROGRAM\n    SUB MAIN(ARGS AS STRING())\n        DIM DT AS DATE\n        DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER\n        DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN\n\n        INITIALIZEARGUMENTS(ARGS)\n        FROMARGUMENT(\"DATE\", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)\n        FROMARGUMENT(\"COLS\", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)\n        FROMARGUMENT(\"ROWS\", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)\n        FROMARGUMENT(\"MS/ROW\", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \\ 20)\n        FROMARGUMENT(\"VSTRETCH\", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"HSTRETCH\", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"WSIZE\", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n\n        \n        IF RESIZEWINDOW THEN\n            CONSOLE.WINDOWWIDTH = COLUMNS + 1\n            CONSOLE.WINDOWHEIGHT = ROWS\n        END IF\n\n        IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \\ 22, 1)\n\n        FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)\n            CONSOLE.WRITE(ROW)\n        NEXT\n    END SUB\n\n    ITERATOR FUNCTION GETCALENDARROWS(\n            DT AS DATE,\n            WIDTH AS INTEGER,\n            HEIGHT AS INTEGER,\n            MONTHSPERROW AS INTEGER,\n            VERTSTRETCH AS BOOLEAN,\n            HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n\n        DIM YEAR = DT.YEAR\n        DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))\n        \n        DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3\n\n        YIELD \"[SNOOPY]\".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD ENVIRONMENT.NEWLINE\n\n        DIM MONTH = 0\n        DO WHILE MONTH < 12\n            DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)\n\n            DIM CELLWIDTH = WIDTH \\ MONTHSPERROW\n            DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \\ 20)\n\n            DIM CELLHEIGHT = MONTHGRIDHEIGHT \\ CALENDARROWCOUNT\n            DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \\ 20\n\n            \n            DIM GETMONTHFROM =\n                FUNCTION(M AS INTEGER) BUILDMONTH(\n                    DT:=NEW DATE(DT.YEAR, M, 1),\n                    WIDTH:=CELLCONTENTWIDTH,\n                    HEIGHT:=CELLCONTENTHEIGHT,\n                    VERTSTRETCH:=VERTSTRETCH,\n                    HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))\n\n            \n            DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =\n                ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)\n\n            DIM CALENDARROW AS IENUMERABLE(OF STRING) =\n                INTERLEAVED(\n                    MONTHSTHISROW,\n                    USEINNERSEPARATOR:=FALSE,\n                    USEOUTERSEPARATOR:=TRUE,\n                    OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)\n\n            DIM EN = CALENDARROW.GETENUMERATOR()\n            DIM HASNEXT = EN.MOVENEXT()\n            DO WHILE HASNEXT\n\n                DIM CURRENT AS STRING = EN.CURRENT\n\n                \n                \n                HASNEXT = EN.MOVENEXT()\n                YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)\n            LOOP\n\n            MONTH += MONTHSPERROW\n        LOOP\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION INTERLEAVED(OF T)(\n            SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),\n            OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL INNERSEPARATOR AS T = NOTHING,\n            OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL OUTERSEPARATOR AS T = NOTHING,\n            OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)\n        DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING\n\n        TRY\n            SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()\n            DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH\n            DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN\n\n            DIM ANYPREVITERS AS BOOLEAN = FALSE\n            DO\n                \n                DIM FIRSTACTIVE = -1, LASTACTIVE = -1\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()\n                    IF ENUMERATORSTATES(I) THEN\n                        IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I\n                        LASTACTIVE = I\n                    END IF\n                NEXT\n\n                \n                \n                DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)\n                IF NOT THISITERHASRESULTS THEN EXIT DO\n\n                \n                IF ANYPREVITERS THEN\n                    IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR\n                ELSE\n                    ANYPREVITERS = TRUE\n                END IF\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    IF ENUMERATORSTATES(I) THEN\n                        \n                        IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR\n                        YIELD SOURCEENUMERATORS(I).CURRENT\n                    END IF\n                NEXT\n            LOOP\n\n        FINALLY\n            IF SOURCEENUMERATORS ISNOT NOTHING THEN\n                FOR EACH EN IN SOURCEENUMERATORS\n                    EN.DISPOSE()\n                NEXT\n            END IF\n        END TRY\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n        CONST DAY_WDT = 2 \n        CONST ALLDAYS_WDT = DAY_WDT * 7 \n\n        \n        DT = NEW DATE(DT.YEAR, DT.MONTH, 1)\n\n        \n        DIM DAYSEP AS NEW STRING(\" \"C, MATH.MIN((WIDTH - ALLDAYS_WDT) \\ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))\n        \n        DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \\ 7)\n\n        \n        DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6\n\n        \n        DIM LEFTPAD AS NEW STRING(\" \"C, (WIDTH - BLOCKWIDTH) \\ 2)\n        \n        DIM FULLPAD AS NEW STRING(\" \"C, WIDTH)\n\n        \n        DIM SB AS NEW STRINGBUILDER(LEFTPAD)\n        DIM NUMLINES = 0\n\n        \n        \n        \n        DIM ENDLINE =\n         FUNCTION() AS IENUMERABLE(OF STRING)\n             DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)\n             SB.CLEAR()\n             SB.APPEND(LEFTPAD)\n\n             \n             RETURN IF(NUMLINES >= HEIGHT,\n                 ENUMERABLE.EMPTY(OF STRING)(),\n                 ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)\n                     YIELD FINISHEDLINE\n                     NUMLINES += 1\n\n                     FOR I = 1 TO VERTBLANKCOUNT\n                         IF NUMLINES >= HEIGHT THEN RETURN\n                         YIELD FULLPAD\n                         NUMLINES += 1\n                     NEXT\n                 END FUNCTION())\n         END FUNCTION\n\n        \n        SB.APPEND(PADCENTER(DT.TOSTRING(\"MMMM\", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())\n        SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM STARTWKDY = CINT(DT.DAYOFWEEK)\n\n        \n        DIM FIRSTPAD AS NEW STRING(\" \"C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)\n        SB.APPEND(FIRSTPAD)\n\n        DIM D = DT\n        DO WHILE D.MONTH = DT.MONTH\n            SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $\"{{0,{DAY_WDT}}}\", D.DAY)\n\n            \n            IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN\n                FOR EACH L IN ENDLINE()\n                    YIELD L\n                NEXT\n            ELSE\n                SB.APPEND(DAYSEP)\n            END IF\n\n            D = D.ADDDAYS(1)\n        LOOP\n\n        \n        DIM NEXTLINES AS IENUMERABLE(OF STRING)\n        DO\n            NEXTLINES = ENDLINE()\n            FOR EACH L IN NEXTLINES\n                YIELD L\n            NEXT\n        LOOP WHILE NEXTLINES.ANY()\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    <EXTENSION()>\n    PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = \" \"C) AS STRING\n        RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \\ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)\n    END FUNCTION\nEND MODULE\n"}
{"id": 51787, "name": "Move-to-front algorithm", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 51788, "name": "Execute a system command", "PHP": "@exec($command,$output);\necho nl2br($output);\n", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n"}
{"id": 51789, "name": "XML validation", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n"}
{"id": 51790, "name": "Longest increasing subsequence", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n", "VB": "Sub Lis(arr() As Integer)\n    Dim As Integer lb = Lbound(arr), ub = Ubound(arr)\n    Dim As Integer i, lo, hi, mitad, newl, l = 0\n\tDim As Integer p(ub), m(ub)\n    \n\tFor i = lb To ub\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmitad = Int((lo+hi)/2)\n\t\t\tIf arr(m(mitad)) < arr(i) Then\n\t\t\t\tlo = mitad + 1\n            Else\n\t\t\t\thi = mitad - 1\n            End If\n        Loop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then l = newl\n    Next i\n    \n    Dim As Integer res(l)\n\tDim As Integer k = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\tres(i) = arr(k)\n\t\tk = p(k)\n    Next i\n\t\n    For i = Lbound(res) To Ubound(res)-1\n        Print res(i); \" \";\n    Next i\nEnd Sub\n\nDim As Integer arrA(5) => {3,2,6,4,5,1}\nLis(arrA())\nPrint\nDim As Integer arrB(15) => {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}\nLis(arrB())\n\nSleep\n"}
{"id": 51791, "name": "Brace expansion", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51792, "name": "Self-describing numbers", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 51793, "name": "Modular inverse", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 51794, "name": "Hello world_Web server", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n"}
{"id": 51795, "name": "Update a configuration file", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 51796, "name": "Literals_Floating point", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n"}
{"id": 51797, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 51798, "name": "Break OO privacy", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 51799, "name": "Long year", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n", "VB": "Public Sub Main() \n  \n  For y As Integer = 2000 To 2100 \n    If isLongYear(y) Then Print y, \n  Next\n  \nEnd \n\nFunction p(y As Integer) As Integer \n  \n  Return (y + (y \\ 4) - (y \\ 100) + (y \\ 400)) Mod 7 \n  \nEnd Function \n\nFunction isLongYear(y As Integer) As Boolean \n  \n  If p(y) = 4 Then Return True \n  If p(y - 1) = 3 Then Return True \n  Return False \n  \nEnd Function\n"}
{"id": 51800, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 51801, "name": "Associative array_Merging", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 51802, "name": "Dijkstra's algorithm", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n"}
{"id": 51803, "name": "Associative array_Iteration", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n"}
{"id": 51804, "name": "Hash join", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n"}
{"id": 51805, "name": "Inheritance_Single", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n"}
{"id": 51806, "name": "Associative array_Creation", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 51807, "name": "Reflection_List properties", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 51808, "name": "Align columns", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n"}
{"id": 51809, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 51810, "name": "URL parser", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 51811, "name": "Variables", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n", "VB": "Dim variable As datatype\nDim var1,var2,... As datatype\n"}
{"id": 51812, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "VB": "#macro assign(sym, expr)\n    __fb_unquote__(__fb_eval__(\"#undef \" + sym))\n    __fb_unquote__(__fb_eval__(\"#define \" + sym + \" \" + __fb_quote__(__fb_eval__(expr))))\n#endmacro\n\n#define a, b, x\n\nassign(\"a\", 8)\nassign(\"b\", 7)\nassign(\"x\", Sqr(a) + (Sin(b*3)/2))\nPrint x\n\nassign(\"x\", \"goodbye\")\nPrint x\n\nSleep\n"}
{"id": 51813, "name": "Runtime evaluation", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n", "VB": "#macro assign(sym, expr)\n    __fb_unquote__(__fb_eval__(\"#undef \" + sym))\n    __fb_unquote__(__fb_eval__(\"#define \" + sym + \" \" + __fb_quote__(__fb_eval__(expr))))\n#endmacro\n\n#define a, b, x\n\nassign(\"a\", 8)\nassign(\"b\", 7)\nassign(\"x\", Sqr(a) + (Sin(b*3)/2))\nPrint x\n\nassign(\"x\", \"goodbye\")\nPrint x\n\nSleep\n"}
{"id": 51814, "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", "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": 51815, "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", "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": 51816, "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", "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": 51817, "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", "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": 51818, "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", "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": 51819, "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", "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": 51820, "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", "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": 51821, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\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": 51822, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\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": 51823, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\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": 51824, "name": "Checkpoint synchronization", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 51825, "name": "Checkpoint synchronization", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 51826, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 51827, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 51828, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 51829, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 51830, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 51831, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 51832, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 51833, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 51834, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 51835, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 51836, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 51837, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 51838, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 51839, "name": "Sorting algorithms_Radix sort", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n"}
{"id": 51840, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n"}
{"id": 51841, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 51842, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 51843, "name": "Singleton", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 51844, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n"}
{"id": 51845, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 51846, "name": "Write entire file", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 51847, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 51848, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n"}
{"id": 51849, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 51850, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 51851, "name": "Roots of unity", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 51852, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 51853, "name": "Pell's equation", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 51854, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 51855, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 51856, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 51857, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 51858, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 51859, "name": "Man or boy test", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 51860, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 51861, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 51862, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 51863, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 51864, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 51865, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 51866, "name": "Inverted index", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 51867, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 51868, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 51869, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 51870, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n"}
{"id": 51871, "name": "Sum and product puzzle", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n"}
{"id": 51872, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 51873, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 51874, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 51875, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n"}
{"id": 51876, "name": "Documentation", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n"}
{"id": 51877, "name": "Documentation", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n"}
{"id": 51878, "name": "Problem of Apollonius", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n"}
{"id": 51879, "name": "Chat server", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 51880, "name": "FASTA format", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 51881, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 51882, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 51883, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 51884, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 51885, "name": "Literals_String", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 51886, "name": "GUI_Maximum window dimensions", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n"}
{"id": 51887, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 51888, "name": "Knapsack problem_Unbounded", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n"}
{"id": 51889, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 51890, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 51891, "name": "Type detection", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n"}
{"id": 51892, "name": "Maximum triangle path sum", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n"}
{"id": 51893, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 51894, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 51895, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 51896, "name": "UTF-8 encode and decode", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n"}
{"id": 51897, "name": "Magic squares of doubly even order", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 51898, "name": "Same fringe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n"}
{"id": 51899, "name": "Peaceful chess queen armies", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 51900, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 51901, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 51902, "name": "XML validation", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 51903, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 51904, "name": "Scope modifiers", "C#": "public \nprotected \ninternal \nprotected internal \nprivate \n\nprivate protected \n\n\n\n\n\n\n\n\n\n\n\n", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n"}
{"id": 51905, "name": "Brace expansion", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 51906, "name": "GUI component interaction", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n"}
{"id": 51907, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n"}
{"id": 51908, "name": "Addition chains", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 51909, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n"}
{"id": 51910, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 51911, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 51912, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 51913, "name": "Terminal control_Clear the screen", "C#": "System.Console.Clear();\n", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n"}
{"id": 51914, "name": "Active Directory_Connect", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n"}
{"id": 51915, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 51916, "name": "Sokoban", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n"}
{"id": 51917, "name": "Practical numbers", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n"}
{"id": 51918, "name": "Literals_Floating point", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 51919, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 51920, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 51921, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 51922, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51923, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51924, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51925, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 51926, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 51927, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51928, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51929, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 51930, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 51931, "name": "Word search", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n"}
{"id": 51932, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 51933, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 51934, "name": "Object serialization", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 51935, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 51936, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 51937, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 51938, "name": "Zumkeller numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n"}
{"id": 51939, "name": "Zumkeller numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n"}
{"id": 51940, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 51941, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 51942, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 51943, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 51944, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 51945, "name": "Markov chain text generator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\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.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n"}
{"id": 51946, "name": "Dijkstra's algorithm", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 51947, "name": "Geometric algebra", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n"}
{"id": 51948, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 51949, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 51950, "name": "Associative array_Iteration", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 51951, "name": "Define a primitive data type", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 51952, "name": "Define a primitive data type", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 51953, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51954, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 51955, "name": "Hash join", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 51956, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 51957, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 51958, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 51959, "name": "Latin Squares in reduced form", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n"}
{"id": 51960, "name": "Closest-pair problem", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n"}
{"id": 51961, "name": "Inheritance_Single", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 51962, "name": "Associative array_Creation", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 51963, "name": "Associative array_Creation", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 51964, "name": "Color wheel", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n"}
{"id": 51965, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n"}
{"id": 51966, "name": "Square root by hand", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n"}
{"id": 51967, "name": "Square root by hand", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n"}
{"id": 51968, "name": "Reflection_List properties", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n"}
{"id": 51969, "name": "Minimal steps down to 1", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class MinimalSteps\n{\n    public static void Main() {\n        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });\n        var lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n        Console.WriteLine();\n\n        subtractors = new [] { 2 };\n        lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n    }\n\n    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {\n        for (int goal = 1; goal <= limit; goal++) {\n            var x = lookup[goal];\n            if (x.param == 0) {\n                Console.WriteLine($\"{goal} cannot be reached with these numbers.\");\n                continue;\n            }\n            Console.Write($\"{goal} takes {x.steps} {(x.steps == 1 ? \"step\" : \"steps\")}: \");\n            for (int n = goal; n > 1; ) {\n                Console.Write($\"{n},{x.op}{x.param}=> \");\n                n = x.op == '/' ? n / x.param : n - x.param;\n                x = lookup[n];\n            }\n            Console.WriteLine(\"1\");\n        }\n    }\n\n    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {\n        var maxSteps = lookup.Max(x => x.steps);\n        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();\n        Console.WriteLine(items.Count == 1\n            ? $\"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}\"\n            : $\"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}\"\n        );\n    }\n\n    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)\n    {\n        var lookup = new (char op, int param, int steps)[goal+1];\n        lookup[1] = ('/', 1, 0);\n        for (int n = 1; n < lookup.Length; n++) {\n            var ln = lookup[n];\n            if (ln.param == 0) continue;\n            for (int d = 0; d < divisors.Length; d++) {\n                int target = n * divisors[d];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);\n            }\n            for (int s = 0; s < subtractors.Length; s++) {\n                int target = n + subtractors[s];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);\n            }\n        }\n        return lookup;\n    }\n\n    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(\", \", source);\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MinimalStepsDownToOne {\n\n    public static void main(String[] args) {\n        runTasks(getFunctions1());\n        runTasks(getFunctions2());\n        runTasks(getFunctions3());\n    }\n    \n    private static void runTasks(List<Function> functions) {\n        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);\n\n        \n        int max = 10;\n        populateMap(minPath, functions, max);\n        System.out.printf(\"%nWith functions:  %s%n\", functions);\n        System.out.printf(\"  Minimum steps to 1:%n\");\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int steps = minPath.get(n).size();\n            System.out.printf(\"    %2d: %d step%1s: %s%n\", n, steps, steps == 1 ? \"\" : \"s\", minPath.get(n));\n        }\n        \n        \n        displayMaxMin(minPath, functions, 2000);\n\n        \n        displayMaxMin(minPath, functions, 20000);\n\n        \n        displayMaxMin(minPath, functions, 100000);\n    }\n    \n    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        populateMap(minPath, functions, max);\n        List<Integer> maxIntegers = getMaxMin(minPath, max);\n        int maxSteps = maxIntegers.remove(0);\n        int numCount = maxIntegers.size();\n        System.out.printf(\"  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n\", numCount == 1 ? \"is\" : \"are\", numCount, numCount == 1 ? \"\" : \"s\", max, maxSteps, maxIntegers);\n        \n    }\n    \n    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {\n        int maxSteps = Integer.MIN_VALUE;\n        List<Integer> maxIntegers = new ArrayList<Integer>();\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int len = minPath.get(n).size();\n            if ( len > maxSteps ) {\n                maxSteps = len;\n                maxIntegers.clear();\n                maxIntegers.add(n);\n            }\n            else if ( len == maxSteps ) {\n                maxIntegers.add(n);\n            }\n        }\n        maxIntegers.add(0, maxSteps);\n        return maxIntegers;\n    }\n\n    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        for ( int n = 2 ; n <= max ; n++ ) {\n            if ( minPath.containsKey(n) ) {\n                continue;\n            }\n            Function minFunction = null;\n            int minSteps = Integer.MAX_VALUE;\n            for ( Function f : functions ) {\n                if ( f.actionOk(n) ) {\n                    int result = f.action(n);\n                    int steps = 1 + minPath.get(result).size();\n                    if ( steps < minSteps ) {\n                        minFunction = f;\n                        minSteps = steps;\n                    }\n                }\n            }\n            int result = minFunction.action(n);\n            List<String> path = new ArrayList<String>();\n            path.add(minFunction.toString(n));\n            path.addAll(minPath.get(result));\n            minPath.put(n, path);\n        }\n        \n    }\n\n    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {\n        Map<Integer,List<String>> minPath = new HashMap<>();\n        for ( int i = 2 ; i <= max ; i++ ) {\n            for ( Function f : functions ) {\n                if ( f.actionOk(i) ) {\n                    int result = f.action(i);\n                    if ( result == 1 ) {\n                        List<String> path = new ArrayList<String>();\n                        path.add(f.toString(i));\n                        minPath.put(i, path);\n                    }\n                }\n            }\n        }\n        return minPath;\n    }\n\n    private static List<Function> getFunctions3() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide2Function());\n        functions.add(new Divide3Function());\n        functions.add(new Subtract2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions2() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract2Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions1() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n    \n    public abstract static class Function {\n        abstract public int action(int n);\n        abstract public boolean actionOk(int n);\n        abstract public String toString(int n);\n    }\n    \n    public static class Divide2Function extends Function {\n        @Override public int action(int n) {\n            return n/2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 2 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/2 -> \" + n/2;\n        }\n        \n        @Override public String toString() {\n            return \"Divisor 2\";\n        }\n        \n    }\n\n    public static class Divide3Function extends Function {\n        @Override public int action(int n) {\n            return n/3;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 3 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/3 -> \" + n/3;\n        }\n\n        @Override public String toString() {\n            return \"Divisor 3\";\n        }\n\n    }\n\n    public static class Subtract1Function extends Function {\n        @Override public int action(int n) {\n            return n-1;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return true;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-1 -> \" + (n-1);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 1\";\n        }\n\n    }\n\n    public static class Subtract2Function extends Function {\n        @Override public int action(int n) {\n            return n-2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n > 2;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-2 -> \" + (n-2);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 2\";\n        }\n\n    }\n\n}\n"}
{"id": 51970, "name": "Align columns", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n"}
{"id": 51971, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 51972, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 51973, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 51974, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 51975, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 51976, "name": "Dynamic variable names", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n"}
{"id": 51977, "name": "Data Encryption Standard", "C#": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace DES {\n    class Program {\n        \n        static string ByteArrayToString(byte[] ba) {\n            return BitConverter.ToString(ba).Replace(\"-\", \"\");\n        }\n\n        \n        \n        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(messageBytes, 0, messageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] encryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n\n            return encryptedMessageBytes;\n        }\n\n        \n        \n        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] decryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);\n\n            return decryptedMessageBytes;\n        }\n\n        static void Main(string[] args) {\n            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };\n            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };\n\n            byte[] encStr = Encrypt(plainBytes, keyBytes);\n            Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr));\n\n            byte[] decBytes = Decrypt(encStr, keyBytes);\n            Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decBytes));\n        }\n    }\n}\n", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n"}
{"id": 51978, "name": "Fibonacci matrix-exponentiation", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 51979, "name": "Fibonacci matrix-exponentiation", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 51980, "name": "Commatizing numbers", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n"}
{"id": 51981, "name": "Arithmetic coding_As a generalized change of radix", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n"}
{"id": 51982, "name": "Empty program", "C#": "using System;\nclass Program\n{\n  public static void Main()\n  {\n  }\n}\n", "Java": "module EmptyProgram\n    {\n    void run()\n        {\n        }\n    }\n"}
{"id": 51983, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n"}
{"id": 51984, "name": "Reflection_List methods", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n"}
{"id": 51985, "name": "Send an unknown method call", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n"}
{"id": 51986, "name": "Twelve statements", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n"}
{"id": 51987, "name": "Transportation problem", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace TransportationProblem {\n    class Shipment {\n        public Shipment(double q, double cpu, int r, int c) {\n            Quantity = q;\n            CostPerUnit = cpu;\n            R = r;\n            C = c;\n        }\n\n        public double CostPerUnit { get; }\n\n        public double Quantity { get; set; }\n\n        public int R { get; }\n\n        public int C { get; }\n    }\n\n    class Program {\n        private static int[] demand;\n        private static int[] supply;\n        private static double[,] costs;\n        private static Shipment[,] matrix;\n\n        static void Init(string filename) {\n            string line;\n            using (StreamReader file = new StreamReader(filename)) {\n                line = file.ReadLine();\n                var numArr = line.Split();\n                int numSources = int.Parse(numArr[0]);\n                int numDestinations = int.Parse(numArr[1]);\n\n                List<int> src = new List<int>();\n                List<int> dst = new List<int>();\n\n                line = file.ReadLine();\n                numArr = line.Split();\n                for (int i = 0; i < numSources; i++) {\n                    src.Add(int.Parse(numArr[i]));\n                }\n\n                line = file.ReadLine();\n                numArr = line.Split();\n                for (int i = 0; i < numDestinations; i++) {\n                    dst.Add(int.Parse(numArr[i]));\n                }\n\n                \n                int totalSrc = src.Sum();\n                int totalDst = dst.Sum();\n                if (totalSrc > totalDst) {\n                    dst.Add(totalSrc - totalDst);\n                } else if (totalDst > totalSrc) {\n                    src.Add(totalDst - totalSrc);\n                }\n\n                supply = src.ToArray();\n                demand = dst.ToArray();\n\n                costs = new double[supply.Length, demand.Length];\n                matrix = new Shipment[supply.Length, demand.Length];\n\n                for (int i = 0; i < numSources; i++) {\n                    line = file.ReadLine();\n                    numArr = line.Split();\n                    for (int j = 0; j < numDestinations; j++) {\n                        costs[i, j] = int.Parse(numArr[j]);\n                    }\n                }\n            }\n        }\n\n        static void NorthWestCornerRule() {\n            for (int r = 0, northwest = 0; r < supply.Length; r++) {\n                for (int c = northwest; c < demand.Length; c++) {\n                    int quantity = Math.Min(supply[r], demand[c]);\n                    if (quantity > 0) {\n                        matrix[r, c] = new Shipment(quantity, costs[r, c], r, c);\n\n                        supply[r] -= quantity;\n                        demand[c] -= quantity;\n\n                        if (supply[r] == 0) {\n                            northwest = c;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        static void SteppingStone() {\n            double maxReduction = 0;\n            Shipment[] move = null;\n            Shipment leaving = null;\n\n            FixDegenerateCase();\n\n            for (int r = 0; r < supply.Length; r++) {\n                for (int c = 0; c < demand.Length; c++) {\n                    if (matrix[r, c] != null) {\n                        continue;\n                    }\n\n                    Shipment trial = new Shipment(0, costs[r, c], r, c);\n                    Shipment[] path = GetClosedPath(trial);\n\n                    double reduction = 0;\n                    double lowestQuantity = int.MaxValue;\n                    Shipment leavingCandidate = null;\n\n                    bool plus = true;\n                    foreach (var s in path) {\n                        if (plus) {\n                            reduction += s.CostPerUnit;\n                        } else {\n                            reduction -= s.CostPerUnit;\n                            if (s.Quantity < lowestQuantity) {\n                                leavingCandidate = s;\n                                lowestQuantity = s.Quantity;\n                            }\n                        }\n                        plus = !plus;\n                    }\n                    if (reduction < maxReduction) {\n                        move = path;\n                        leaving = leavingCandidate;\n                        maxReduction = reduction;\n                    }\n                }\n            }\n\n            if (move != null) {\n                double q = leaving.Quantity;\n                bool plus = true;\n                foreach (var s in move) {\n                    s.Quantity += plus ? q : -q;\n                    matrix[s.R, s.C] = s.Quantity == 0 ? null : s;\n                    plus = !plus;\n                }\n                SteppingStone();\n            }\n        }\n\n        static List<Shipment> MatrixToList() {\n            List<Shipment> newList = new List<Shipment>();\n            foreach (var item in matrix) {\n                if (null != item) {\n                    newList.Add(item);\n                }\n            }\n            return newList;\n        }\n\n        static Shipment[] GetClosedPath(Shipment s) {\n            List<Shipment> path = MatrixToList();\n            path.Add(s);\n\n            \n            \n            int before;\n            do {\n                before = path.Count;\n                path.RemoveAll(ship => {\n                    var nbrs = GetNeighbors(ship, path);\n                    return nbrs[0] == null || nbrs[1] == null;\n                });\n            } while (before != path.Count);\n\n            \n            Shipment[] stones = path.ToArray();\n            Shipment prev = s;\n            for (int i = 0; i < stones.Length; i++) {\n                stones[i] = prev;\n                prev = GetNeighbors(prev, path)[i % 2];\n            }\n            return stones;\n        }\n\n        static Shipment[] GetNeighbors(Shipment s, List<Shipment> lst) {\n            Shipment[] nbrs = new Shipment[2];\n            foreach (var o in lst) {\n                if (o != s) {\n                    if (o.R == s.R && nbrs[0] == null) {\n                        nbrs[0] = o;\n                    } else if (o.C == s.C && nbrs[1] == null) {\n                        nbrs[1] = o;\n                    }\n                    if (nbrs[0] != null && nbrs[1] != null) {\n                        break;\n                    }\n                }\n            }\n            return nbrs;\n        }\n\n        static void FixDegenerateCase() {\n            const double eps = double.Epsilon;\n            if (supply.Length + demand.Length - 1 != MatrixToList().Count) {\n                for (int r = 0; r < supply.Length; r++) {\n                    for (int c = 0; c < demand.Length; c++) {\n                        if (matrix[r, c] == null) {\n                            Shipment dummy = new Shipment(eps, costs[r, c], r, c);\n                            if (GetClosedPath(dummy).Length == 0) {\n                                matrix[r, c] = dummy;\n                                return;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        static void PrintResult(string filename) {\n            Console.WriteLine(\"Optimal solution {0}\\n\", filename);\n            double totalCosts = 0;\n\n            for (int r = 0; r < supply.Length; r++) {\n                for (int c = 0; c < demand.Length; c++) {\n                    Shipment s = matrix[r, c];\n                    if (s != null && s.R == r && s.C == c) {\n                        Console.Write(\" {0,3} \", s.Quantity);\n                        totalCosts += (s.Quantity * s.CostPerUnit);\n                    } else {\n                        Console.Write(\"  -  \");\n                    }\n                }\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nTotal costs: {0}\\n\", totalCosts);\n        }\n\n        static void Main() {\n            foreach (var filename in new string[] { \"input1.txt\", \"input2.txt\", \"input3.txt\" }) {\n                Init(filename);\n                NorthWestCornerRule();\n                SteppingStone();\n                PrintResult(filename);\n            }\n        }\n    }\n}\n", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.util.Arrays.stream;\nimport static java.util.stream.Collectors.toCollection;\n\npublic class TransportationProblem {\n\n    private static int[] demand;\n    private static int[] supply;\n    private static double[][] costs;\n    private static Shipment[][] matrix;\n\n    private static class Shipment {\n        final double costPerUnit;\n        final int r, c;\n        double quantity;\n\n        public Shipment(double q, double cpu, int r, int c) {\n            quantity = q;\n            costPerUnit = cpu;\n            this.r = r;\n            this.c = c;\n        }\n    }\n\n    static void init(String filename) throws Exception {\n\n        try (Scanner sc = new Scanner(new File(filename))) {\n            int numSources = sc.nextInt();\n            int numDestinations = sc.nextInt();\n\n            List<Integer> src = new ArrayList<>();\n            List<Integer> dst = new ArrayList<>();\n\n            for (int i = 0; i < numSources; i++)\n                src.add(sc.nextInt());\n\n            for (int i = 0; i < numDestinations; i++)\n                dst.add(sc.nextInt());\n\n            \n            int totalSrc = src.stream().mapToInt(i -> i).sum();\n            int totalDst = dst.stream().mapToInt(i -> i).sum();\n            if (totalSrc > totalDst)\n                dst.add(totalSrc - totalDst);\n            else if (totalDst > totalSrc)\n                src.add(totalDst - totalSrc);\n\n            supply = src.stream().mapToInt(i -> i).toArray();\n            demand = dst.stream().mapToInt(i -> i).toArray();\n\n            costs = new double[supply.length][demand.length];\n            matrix = new Shipment[supply.length][demand.length];\n\n            for (int i = 0; i < numSources; i++)\n                for (int j = 0; j < numDestinations; j++)\n                    costs[i][j] = sc.nextDouble();\n        }\n    }\n\n    static void northWestCornerRule() {\n\n        for (int r = 0, northwest = 0; r < supply.length; r++)\n            for (int c = northwest; c < demand.length; c++) {\n\n                int quantity = Math.min(supply[r], demand[c]);\n                if (quantity > 0) {\n                    matrix[r][c] = new Shipment(quantity, costs[r][c], r, c);\n\n                    supply[r] -= quantity;\n                    demand[c] -= quantity;\n\n                    if (supply[r] == 0) {\n                        northwest = c;\n                        break;\n                    }\n                }\n            }\n    }\n\n    static void steppingStone() {\n        double maxReduction = 0;\n        Shipment[] move = null;\n        Shipment leaving = null;\n\n        fixDegenerateCase();\n\n        for (int r = 0; r < supply.length; r++) {\n            for (int c = 0; c < demand.length; c++) {\n\n                if (matrix[r][c] != null)\n                    continue;\n\n                Shipment trial = new Shipment(0, costs[r][c], r, c);\n                Shipment[] path = getClosedPath(trial);\n\n                double reduction = 0;\n                double lowestQuantity = Integer.MAX_VALUE;\n                Shipment leavingCandidate = null;\n\n                boolean plus = true;\n                for (Shipment s : path) {\n                    if (plus) {\n                        reduction += s.costPerUnit;\n                    } else {\n                        reduction -= s.costPerUnit;\n                        if (s.quantity < lowestQuantity) {\n                            leavingCandidate = s;\n                            lowestQuantity = s.quantity;\n                        }\n                    }\n                    plus = !plus;\n                }\n                if (reduction < maxReduction) {\n                    move = path;\n                    leaving = leavingCandidate;\n                    maxReduction = reduction;\n                }\n            }\n        }\n\n        if (move != null) {\n            double q = leaving.quantity;\n            boolean plus = true;\n            for (Shipment s : move) {\n                s.quantity += plus ? q : -q;\n                matrix[s.r][s.c] = s.quantity == 0 ? null : s;\n                plus = !plus;\n            }\n            steppingStone();\n        }\n    }\n\n    static LinkedList<Shipment> matrixToList() {\n        return stream(matrix)\n                .flatMap(row -> stream(row))\n                .filter(s -> s != null)\n                .collect(toCollection(LinkedList::new));\n    }\n\n    static Shipment[] getClosedPath(Shipment s) {\n        LinkedList<Shipment> path = matrixToList();\n        path.addFirst(s);\n\n        \n        \n        while (path.removeIf(e -> {\n            Shipment[] nbrs = getNeighbors(e, path);\n            return nbrs[0] == null || nbrs[1] == null;\n        }));\n\n        \n        Shipment[] stones = path.toArray(new Shipment[path.size()]);\n        Shipment prev = s;\n        for (int i = 0; i < stones.length; i++) {\n            stones[i] = prev;\n            prev = getNeighbors(prev, path)[i % 2];\n        }\n        return stones;\n    }\n\n    static Shipment[] getNeighbors(Shipment s, LinkedList<Shipment> lst) {\n        Shipment[] nbrs = new Shipment[2];\n        for (Shipment o : lst) {\n            if (o != s) {\n                if (o.r == s.r && nbrs[0] == null)\n                    nbrs[0] = o;\n                else if (o.c == s.c && nbrs[1] == null)\n                    nbrs[1] = o;\n                if (nbrs[0] != null && nbrs[1] != null)\n                    break;\n            }\n        }\n        return nbrs;\n    }\n\n    static void fixDegenerateCase() {\n        final double eps = Double.MIN_VALUE;\n\n        if (supply.length + demand.length - 1 != matrixToList().size()) {\n\n            for (int r = 0; r < supply.length; r++)\n                for (int c = 0; c < demand.length; c++) {\n                    if (matrix[r][c] == null) {\n                        Shipment dummy = new Shipment(eps, costs[r][c], r, c);\n                        if (getClosedPath(dummy).length == 0) {\n                            matrix[r][c] = dummy;\n                            return;\n                        }\n                    }\n                }\n        }\n    }\n\n    static void printResult(String filename) {\n        System.out.printf(\"Optimal solution %s%n%n\", filename);\n        double totalCosts = 0;\n\n        for (int r = 0; r < supply.length; r++) {\n            for (int c = 0; c < demand.length; c++) {\n\n                Shipment s = matrix[r][c];\n                if (s != null && s.r == r && s.c == c) {\n                    System.out.printf(\" %3s \", (int) s.quantity);\n                    totalCosts += (s.quantity * s.costPerUnit);\n                } else\n                    System.out.printf(\"  -  \");\n            }\n            System.out.println();\n        }\n        System.out.printf(\"%nTotal costs: %s%n%n\", totalCosts);\n    }\n\n    public static void main(String[] args) throws Exception {\n\n        for (String filename : new String[]{\"input1.txt\", \"input2.txt\",\n            \"input3.txt\"}) {\n            init(filename);\n            northWestCornerRule();\n            steppingStone();\n            printResult(filename);\n        }\n    }\n}\n"}
{"id": 51988, "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": 51989, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\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": 51990, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\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": 51991, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\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": 51992, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\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": 51993, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\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": 51994, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\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": 51995, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\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": 51996, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\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": 51997, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\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": 51998, "name": "SHA-256 Merkle tree", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\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": 51999, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \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": 52000, "name": "User input_Graphical", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\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": 52001, "name": "Sierpinski arrowhead curve", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\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": 52002, "name": "Text processing_1", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\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": 52003, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\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": 52004, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\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": 52005, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\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": 52006, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\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": 52007, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\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": 52008, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\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": 52009, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\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": 52010, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\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": 52011, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\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": 52012, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\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": 52013, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\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": 52014, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\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": 52015, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "Go": "var intStack []int\n"}
{"id": 52016, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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    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": 52017, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 52018, "name": "Fractran", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\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": 52019, "name": "Fractran", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\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": 52020, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\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    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": 52021, "name": "Galton box animation", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\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": 52022, "name": "Sorting Algorithms_Circle Sort", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\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": 52023, "name": "Kronecker product based fractals", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\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": 52024, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\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": 52025, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\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": 52026, "name": "Circular primes", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\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": 52027, "name": "Circular primes", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\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": 52028, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\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": 52029, "name": "Sorting algorithms_Radix sort", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\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": 52030, "name": "List comprehensions", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\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": 52031, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\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    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": 52032, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\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": 52033, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\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": 52034, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\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": 52035, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\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": 52036, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\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": 52037, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\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": 52038, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \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": 52039, "name": "Safe addition", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\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": 52040, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\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": 52041, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 52042, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 52043, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\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": 52044, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\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": 52045, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\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": 52046, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\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": 52047, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\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": 52048, "name": "Non-continuous subsequences", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\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": 52049, "name": "Fibonacci word_fractal", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\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": 52050, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\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": 52051, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\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": 52052, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\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": 52053, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\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": 52054, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\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": 52055, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\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": 52056, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\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": 52057, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\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": 52058, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\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": 52059, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\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": 52060, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\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": 52061, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\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": 52062, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\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": 52063, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\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": 52064, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\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": 52065, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\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": 52066, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\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": 52067, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\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": 52068, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\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": 52069, "name": "Carmichael 3 strong pseudoprimes", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n"}
{"id": 52070, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 52071, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 52072, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 52073, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 52074, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 52075, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 52076, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 52077, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 52078, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 52079, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 52080, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 52081, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 52082, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 52083, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 52084, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 52085, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 52086, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 52087, "name": "Water collected between towers", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 52088, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 52089, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 52090, "name": "Jaro similarity", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n"}
{"id": 52091, "name": "Sum and product puzzle", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n"}
{"id": 52092, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n"}
{"id": 52093, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n"}
{"id": 52094, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 52095, "name": "Prime triangle", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n"}
{"id": 52096, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 52097, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 52098, "name": "Sequence_ nth number with exactly n divisors", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 52099, "name": "Sequence_ smallest number with exactly n divisors", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n"}
{"id": 52100, "name": "Pancake numbers", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52101, "name": "Generate random chess position", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n"}
{"id": 52102, "name": "Esthetic numbers", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n"}
{"id": 52103, "name": "Topswops", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n"}
{"id": 52104, "name": "Old Russian measure of length", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n"}
{"id": 52105, "name": "Rate counter", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n"}
{"id": 52106, "name": "Rate counter", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n"}
{"id": 52107, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 52108, "name": "Pythagoras tree", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n"}
{"id": 52109, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 52110, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 52111, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 52112, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 52113, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 52114, "name": "Rosetta Code_Tasks without examples", "Java": "import java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\n\npublic class TasksWithoutExamples {\n    private static String readPage(HttpClient client, URI uri) throws IOException, InterruptedException {\n        var request = HttpRequest.newBuilder()\n            .GET()\n            .uri(uri)\n            .timeout(Duration.ofSeconds(5))\n            .setHeader(\"accept\", \"text/html\")\n            .build();\n\n        var response = client.send(request, HttpResponse.BodyHandlers.ofString());\n        return response.body();\n    }\n\n    private static void process(HttpClient client, String base, String task) {\n        try {\n            var re = Pattern.compile(\".*using any language you may know.</div>(.*?)<div id=\\\"toc\\\".*\", Pattern.DOTALL + Pattern.MULTILINE);\n            var re2 = Pattern.compile(\"</?[^>]*>\");\n\n            var page = base + task;\n            String body = readPage(client, new URI(page));\n\n            var matcher = re.matcher(body);\n            if (matcher.matches()) {\n                var group = matcher.group(1);\n                var m2 = re2.matcher(group);\n                var text = m2.replaceAll(\"\");\n                System.out.println(text);\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {\n        var re = Pattern.compile(\"<li><a href=\\\"/wiki/(.*?)\\\"\", Pattern.DOTALL + Pattern.MULTILINE);\n\n        var client = HttpClient.newBuilder()\n            .version(HttpClient.Version.HTTP_1_1)\n            .followRedirects(HttpClient.Redirect.NORMAL)\n            .connectTimeout(Duration.ofSeconds(5))\n            .build();\n\n        var uri = new URI(\"http\", \"rosettacode.org\", \"/wiki/Category:Programming_Tasks\", \"\");\n        var body = readPage(client, uri);\n        var matcher = re.matcher(body);\n\n        var tasks = new ArrayList<String>();\n        while (matcher.find()) {\n            tasks.add(matcher.group(1));\n        }\n\n        var base = \"http:\n        var limit = 3L;\n\n        tasks.stream().limit(limit).forEach(task -> process(client, base, task));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"html\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {    \n    ex := `<li><a href=\"/wiki/(.*?)\"`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    tasks := make([]string, len(matches))\n    for i, match := range matches {\n        tasks[i] = match[1]\n    }\n    const base = \"http:\n    const limit = 3 \n    ex = `(?s)using any language you may know.</div>(.*?)<div id=\"toc\"`\n    ex2 := `</?[^>]*>` \n    re = regexp.MustCompile(ex)\n    re2 := regexp.MustCompile(ex2)\n    for i, task := range tasks {\n        page = base + task\n        resp, _ = http.Get(page)\n        body, _ = ioutil.ReadAll(resp.Body)\n        match := re.FindStringSubmatch(string(body))\n        resp.Body.Close()\n        text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], \"\"))\n        fmt.Println(strings.Replace(task, \"_\", \" \", -1), \"\\n\", text)\n        if i == limit-1 {\n            break\n        }\n        time.Sleep(5 * time.Second) \n    }\n}\n"}
{"id": 52115, "name": "Sine wave", "Java": "import processing.sound.*;\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\nsine.freq(500);\nsine.play();\n\ndelay(5000);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os/exec\"\n)\n\nfunc main() {\n    synthType := \"sine\"\n    duration := \"5\"\n    frequency := \"440\"\n    cmd := exec.Command(\"play\", \"-n\", \"synth\", duration, synthType, frequency)\n    err := cmd.Run()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52116, "name": "Include a file", "Java": "public class Class1 extends Class2\n{\n\t\n}\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 52117, "name": "Include a file", "Java": "public class Class1 extends Class2\n{\n\t\n}\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 52118, "name": "Stern-Brocot sequence", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n"}
{"id": 52119, "name": "Numeric error propagation", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n"}
{"id": 52120, "name": "Soundex", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n"}
{"id": 52121, "name": "List rooted trees", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n"}
{"id": 52122, "name": "Documentation", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n"}
{"id": 52123, "name": "Problem of Apollonius", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n"}
{"id": 52124, "name": "Longest common suffix", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n"}
{"id": 52125, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n"}
{"id": 52126, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n"}
{"id": 52127, "name": "Idiomatically determine all the lowercase and uppercase letters", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n"}
{"id": 52128, "name": "Sum of elements below main diagonal of matrix", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n"}
{"id": 52129, "name": "Sorting algorithms_Tree sort on a linked list", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n"}
{"id": 52130, "name": "Sorting algorithms_Tree sort on a linked list", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n"}
{"id": 52131, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 52132, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 52133, "name": "Numerical integration_Adaptive Simpson's method", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 52134, "name": "Numerical integration_Adaptive Simpson's method", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 52135, "name": "FASTA format", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n"}
{"id": 52136, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 52137, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 52138, "name": "Window creation_X11", "Java": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n  public static void main(String[] args) {\n    Runnable runnable = new Runnable() {\n      public void run() {\n\tcreateAndShow();\n      }\n    };\n    SwingUtilities.invokeLater(runnable);\n  }\n\t\n  static void createAndShow() {\n    JFrame frame = new JFrame(\"Hello World\");\n    frame.setSize(640,480);\n    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n}\n", "Go": "package main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"github.com/jezek/xgb\"\n    \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n    \n    X, err := xgb.NewConn()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    points := []xproto.Point{\n        {10, 10},\n        {10, 20},\n        {20, 10},\n        {20, 20}};\n\n    polyline := []xproto.Point{\n        {50, 10},\n        { 5, 20},     \n        {25,-20},\n        {10, 10}};\n\n    segments := []xproto.Segment{\n        {100, 10, 140, 30},\n        {110, 25, 130, 60}};\n\n    rectangles := []xproto.Rectangle{\n        { 10, 50, 40, 20},\n        { 80, 50, 10, 40}};\n\n    arcs := []xproto.Arc{\n        {10, 100, 60, 40, 0, 90 << 6},\n        {90, 100, 55, 40, 0, 270 << 6}};\n\n    setup := xproto.Setup(X)\n    \n    screen := setup.DefaultScreen(X)\n\n    \n    foreground, _ := xproto.NewGcontextId(X)\n    mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n    values := []uint32{screen.BlackPixel, 0}\n    xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n    \n    win, _ := xproto.NewWindowId(X)\n    winDrawable := xproto.Drawable(win)\n\n    \n    mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n    values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n    xproto.CreateWindow(X,                  \n            screen.RootDepth,               \n            win,                            \n            screen.Root,                    \n            0, 0,                           \n            150, 150,                       \n            10,                             \n            xproto.WindowClassInputOutput,  \n            screen.RootVisual,              \n            mask, values)                   \n\n    \n    xproto.MapWindow(X, win)\n\n    for {\n        evt, err := X.WaitForEvent()\n        switch evt.(type) {\n            case xproto.ExposeEvent:\n                \n                xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n                \n                xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n                \n                xproto.PolySegment(X, winDrawable, foreground, segments)\n\n                \n                xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n                \n                xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n            default:\n                \n        }\n\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    return\n}\n"}
{"id": 52139, "name": "Finite state machine", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n"}
{"id": 52140, "name": "Vibrating rectangles", "Java": "\n\nint counter = 100;\n\nvoid setup(){\n  size(1000,1000);\n}\n\nvoid draw(){\n  \n  for(int i=0;i<20;i++){\n    fill(counter - 5*i);\n    rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);\n  }\n  counter++;\n  \n  if(counter > 255)\n    counter = 100;\n  \n  delay(100);\n}\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n"}
{"id": 52141, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 52142, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 52143, "name": "Pseudo-random numbers_PCG32", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 52144, "name": "Deconvolution_1D", "Java": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n    public static int[] deconv(int[] g, int[] f) {\n        int[] h = new int[g.length - f.length + 1];\n        for (int n = 0; n < h.length; n++) {\n            h[n] = g[n];\n            int lower = Math.max(n - f.length + 1, 0);\n            for (int i = lower; i < n; i++)\n                h[n] -= h[i] * f[n - i];\n            h[n] /= f[0];\n        }\n        return h;\n    }\n\n    public static void main(String[] args) {\n        int[] h = { -8, -9, -3, -1, -6, 7 };\n        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n                96, 31, 55, 36, 29, -43, -7 };\n\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n        sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n        sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n        sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n        System.out.println(sb.toString());\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    h := []float64{-8, -9, -3, -1, -6, 7}\n    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n        96, 31, 55, 36, 29, -43, -7}\n    fmt.Println(h)\n    fmt.Println(deconv(g, f))\n    fmt.Println(f)\n    fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n    h := make([]float64, len(g)-len(f)+1)\n    for n := range h {\n        h[n] = g[n]\n        var lower int\n        if n >= len(f) {\n            lower = n - len(f) + 1\n        }\n        for i := lower; i < n; i++ {\n            h[n] -= h[i] * f[n-i]\n        }\n        h[n] /= f[0]\n    }\n    return h\n}\n"}
{"id": 52145, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 52146, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 52147, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 52148, "name": "Disarium numbers", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52149, "name": "Disarium numbers", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52150, "name": "Sierpinski pentagon", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n"}
{"id": 52151, "name": "Bitmap_Histogram", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n"}
{"id": 52152, "name": "Mutex", "Java": "import java.util.concurrent.Semaphore;\n\npublic class VolatileClass{\n   public Semaphore mutex = new Semaphore(1); \n                                              \n   public void needsToBeSynched(){\n      \n   }\n   \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n"}
{"id": 52153, "name": "Metronome", "Java": "class Metronome{\n\tdouble bpm;\n\tint measure, counter;\n\tpublic Metronome(double bpm, int measure){\n\t\tthis.bpm = bpm;\n\t\tthis.measure = measure;\t\n\t}\n\tpublic void start(){\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tThread.sleep((long)(1000*(60.0/bpm)));\n\t\t\t}catch(InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tcounter++;\n\t\t\tif (counter%measure==0){\n\t\t\t\t System.out.println(\"TICK\");\n\t\t\t}else{\n\t\t\t\t System.out.println(\"TOCK\");\n\t\t\t}\n\t\t}\n\t}\n}\npublic class test {\n\tpublic static void main(String[] args) {\n\t\tMetronome metronome1 = new Metronome(120,4);\n\t\tmetronome1.start();\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 \n\tvar bpb = 4    \n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}\n"}
{"id": 52154, "name": "EKG sequence convergence", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n    public static void main(String[] args) {\n        System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n        for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n            System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n        }\n        System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n        List<Integer> ekg5 = ekg(5, 100);\n        List<Integer> ekg7 = ekg(7, 100);\n        for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n            if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n                System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n                break;\n            }\n        }\n    }\n    \n    \n    private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {\n        List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));\n        Collections.sort(list1);\n        List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));\n        Collections.sort(list2);\n        for ( int i = 0 ; i < n ; i++ ) {\n            if ( list1.get(i) != list2.get(i) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    \n    \n    private static List<Integer> ekg(int two, int maxN) {\n        List<Integer> result = new ArrayList<>();\n        result.add(1);\n        result.add(two);\n        Map<Integer,Integer> seen = new HashMap<>();\n        seen.put(1, 1);\n        seen.put(two, 1);\n        int minUnseen = two == 2 ? 3 : 2;\n        int prev = two;\n        for ( int n = 3 ; n <= maxN ; n++ ) {\n            int test = minUnseen - 1;\n            while ( true ) {\n                test++;\n                if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n                    \n                    result.add(test);\n                    seen.put(test, n);\n                    prev = test;\n                    if ( minUnseen == test ) {\n                        do {\n                            minUnseen++;\n                        } while ( seen.containsKey(minUnseen) );\n                    }\n                    break;\n                }\n            }\n        }\n        return result;\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    \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n    for _, j := range a {\n        if j == b {\n            return true\n        }\n    }\n    return false\n}\n\nfunc gcd(a, b int) int {\n    for a != b {\n        if a > b {\n            a -= b\n        } else {\n            b -= a\n        }\n    }\n    return a\n}\n\nfunc areSame(s, t []int) bool {\n    le := len(s)\n    if le != len(t) {\n        return false\n    }\n    sort.Ints(s)\n    sort.Ints(t)\n    for i := 0; i < le; i++ {\n        if s[i] != t[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100\n    starts := [5]int{2, 5, 7, 9, 10}\n    var ekg [5][limit]int\n\n    for s, start := range starts {\n        ekg[s][0] = 1\n        ekg[s][1] = start\n        for n := 2; n < limit; n++ {\n            for i := 2; ; i++ {\n                \n                \n                if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n                    ekg[s][n] = i\n                    break\n                }\n            }\n        }\n        fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n    }   \n\n    \n    for i := 2; i < limit; i++ {\n        if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n            fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n            return\n        }\n    }\n    fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}\n"}
{"id": 52155, "name": "Rep-string", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n"}
{"id": 52156, "name": "Terminal control_Preserve screen", "Java": "public class PreserveScreen\n{\n    public static void main(String[] args) throws InterruptedException {\n        System.out.print(\"\\033[?1049h\\033[H\");\n        System.out.println(\"Alternate screen buffer\\n\");\n        for (int i = 5; i > 0; i--) {\n            String s = (i > 1) ? \"s\" : \"\";\n            System.out.printf(\"\\rgoing back in %d second%s...\", i, s);\n            Thread.sleep(1000);\n        }\n        System.out.print(\"\\033[?1049l\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"\\033[?1049h\\033[H\")\n    fmt.Println(\"Alternate screen buffer\\n\")\n    s := \"s\"\n    for i := 5; i > 0; i-- {\n        if i == 1 {\n            s = \"\"\n        }\n        fmt.Printf(\"\\rgoing back in %d second%s...\", i, s)\n        time.Sleep(time.Second)\n    }\n    fmt.Print(\"\\033[?1049l\")\n}\n"}
{"id": 52157, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 52158, "name": "Changeable words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n"}
{"id": 52159, "name": "Window management", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 52160, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 52161, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 52162, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 52163, "name": "Mayan numerals", "Java": "import java.math.BigInteger;\n\npublic class MayanNumerals {\n\n    public static void main(String[] args) {\n        for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {\n            displayMyan(BigInteger.valueOf(base10));\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static char[] digits = \"0123456789ABCDEFGHJK\".toCharArray();\n    private static BigInteger TWENTY = BigInteger.valueOf(20);\n    \n    private static void displayMyan(BigInteger numBase10) {\n        System.out.printf(\"As base 10:  %s%n\", numBase10);\n        String numBase20 = \"\";\n        while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {\n            numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;\n            numBase10 = numBase10.divide(TWENTY);\n        }\n        System.out.printf(\"As base 20:  %s%nAs Mayan:%n\", numBase20);\n        displayMyanLine1(numBase20);\n        displayMyanLine2(numBase20);\n        displayMyanLine3(numBase20);\n        displayMyanLine4(numBase20);\n        displayMyanLine5(numBase20);\n        displayMyanLine6(numBase20);\n    }\n \n    private static char boxUL = Character.toChars(9556)[0];\n    private static char boxTeeUp = Character.toChars(9574)[0];\n    private static char boxUR = Character.toChars(9559)[0];\n    private static char boxHorz = Character.toChars(9552)[0];\n    private static char boxVert = Character.toChars(9553)[0];\n    private static char theta = Character.toChars(952)[0];\n    private static char boxLL = Character.toChars(9562)[0];\n    private static char boxLR = Character.toChars(9565)[0];\n    private static char boxTeeLow = Character.toChars(9577)[0];\n    private static char bullet = Character.toChars(8729)[0];\n    private static char dash = Character.toChars(9472)[0];\n    \n    private static void displayMyanLine1(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxUL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeUp : boxUR);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String getBullet(int count) {\n        StringBuilder sb = new StringBuilder();\n        switch ( count ) {\n        case 1:  sb.append(\" \" + bullet + \"  \"); break;\n        case 2:  sb.append(\" \" + bullet + bullet + \" \"); break;\n        case 3:  sb.append(\"\" + bullet + bullet + bullet + \" \"); break;\n        case 4:  sb.append(\"\" + bullet + bullet + bullet + bullet); break;\n        default:  throw new IllegalArgumentException(\"Must be 1-4:  \" + count);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine2(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'G':  sb.append(getBullet(1)); break;\n            case 'H':  sb.append(getBullet(2)); break;\n            case 'J':  sb.append(getBullet(3)); break;\n            case 'K':  sb.append(getBullet(4)); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String DASH = getDash();\n    \n    private static String getDash() {\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < 4 ; i++ ) {\n            sb.append(dash);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine3(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'B':  sb.append(getBullet(1)); break;\n            case 'C':  sb.append(getBullet(2)); break;\n            case 'D':  sb.append(getBullet(3)); break;\n            case 'E':  sb.append(getBullet(4)); break;\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine4(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '6':  sb.append(getBullet(1)); break;\n            case '7':  sb.append(getBullet(2)); break;\n            case '8':  sb.append(getBullet(3)); break;\n            case '9':  sb.append(getBullet(4)); break;\n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine5(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '0':  sb.append(\" \" + theta + \"  \"); break;\n            case '1':  sb.append(getBullet(1)); break;\n            case '2':  sb.append(getBullet(2)); break;\n            case '3':  sb.append(getBullet(3)); break;\n            case '4':  sb.append(getBullet(4)); break;\n            case '5': case '6': case '7': case '8': case '9': \n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine6(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxLL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeLow : boxLR);\n        }\n        System.out.println(sb.toString());\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst (\n    ul = \"╔\"\n    uc = \"╦\"\n    ur = \"╗\"\n    ll = \"╚\"\n    lc = \"╩\"\n    lr = \"╝\"\n    hb = \"═\"\n    vb = \"║\"\n)\n\nvar mayan = [5]string{\n    \"    \",\n    \" ∙  \",\n    \" ∙∙ \",\n    \"∙∙∙ \",\n    \"∙∙∙∙\",\n}\n\nconst (\n    m0 = \" Θ  \"\n    m5 = \"────\"\n)\n\nfunc dec2vig(n uint64) []uint64 {\n    vig := strconv.FormatUint(n, 20)\n    res := make([]uint64, len(vig))\n    for i, d := range vig {\n        res[i], _ = strconv.ParseUint(string(d), 20, 64)\n    }\n    return res\n}\n\nfunc vig2quin(n uint64) [4]string {\n    if n >= 20 {\n        panic(\"Cant't convert a number >= 20\")\n    }\n    res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}\n    if n == 0 {\n        res[3] = m0\n        return res\n    }\n    fives := n / 5\n    rem := n % 5\n    res[3-fives] = mayan[rem]\n    for i := 3; i > 3-int(fives); i-- {\n        res[i] = m5\n    }\n    return res\n}\n\nfunc draw(mayans [][4]string) {\n    lm := len(mayans)\n    fmt.Print(ul)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(uc)\n        } else {\n            fmt.Println(ur)\n        }\n    }\n    for i := 1; i < 5; i++ {\n        fmt.Print(vb)\n        for j := 0; j < lm; j++ {\n            fmt.Print(mayans[j][i-1])\n            fmt.Print(vb)\n        }\n        fmt.Println()\n    }\n    fmt.Print(ll)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(lc)\n        } else {\n            fmt.Println(lr)\n        }\n    }\n}\n\nfunc main() {\n    numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}\n    for _, n := range numbers {\n        fmt.Printf(\"Converting %d to Mayan:\\n\", n)\n        vigs := dec2vig(n)\n        lv := len(vigs)\n        mayans := make([][4]string, lv)\n        for i, vig := range vigs {\n            mayans[i] = vig2quin(vig)\n        }\n        draw(mayans)\n        fmt.Println()\n    }\n}\n"}
{"id": 52164, "name": "Ramsey's theorem", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n"}
{"id": 52165, "name": "Ramsey's theorem", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n"}
{"id": 52166, "name": "GUI_Maximum window dimensions", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n"}
{"id": 52167, "name": "Four is magic", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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": 52168, "name": "Getting the number of decimals", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n"}
{"id": 52169, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 52170, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 52171, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 52172, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 52173, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 52174, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 52175, "name": "Parse an IP Address", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n"}
{"id": 52176, "name": "Knapsack problem_Unbounded", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n"}
{"id": 52177, "name": "Textonyms", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n"}
{"id": 52178, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 52179, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 52180, "name": "Teacup rim text", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52181, "name": "Increasing gaps between consecutive Niven numbers", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n"}
{"id": 52182, "name": "Print debugging statement", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n"}
{"id": 52183, "name": "Superellipse", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n"}
{"id": 52184, "name": "Superellipse", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n"}
{"id": 52185, "name": "Permutations_Rank of a permutation", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n"}
{"id": 52186, "name": "Permutations_Rank of a permutation", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n"}
{"id": 52187, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n"}
{"id": 52188, "name": "Type detection", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n"}
{"id": 52189, "name": "Maximum triangle path sum", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 52190, "name": "Zhang-Suen thinning algorithm", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n"}
{"id": 52191, "name": "Variable declaration reset", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n"}
{"id": 52192, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n"}
{"id": 52193, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n"}
{"id": 52194, "name": "Numbers with equal rises and falls", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n"}
{"id": 52195, "name": "Koch curve", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n"}
{"id": 52196, "name": "Draw pixel 2", "Java": "\n\nsize(640,480);\n\nstroke(#ffff00);\n\nellipse(random(640),random(480),1,1);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 640, 480)\n    img := image.NewRGBA(rect)\n\n    \n    blue := color.RGBA{0, 0, 255, 255}\n    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)\n\n    \n    yellow := color.RGBA{255, 255, 0, 255}\n    width := img.Bounds().Dx()\n    height := img.Bounds().Dy()\n    rand.Seed(time.Now().UnixNano())\n    x := rand.Intn(width)\n    y := rand.Intn(height)\n    img.Set(x, y, yellow)\n\n    \n    cmap := map[color.Color]string{blue: \"blue\", yellow: \"yellow\"}\n    for i := 0; i < width; i++ {\n        for j := 0; j < height; j++ {\n            c := img.At(i, j)\n            if cmap[c] == \"yellow\" {\n                fmt.Printf(\"The color of the pixel at (%d, %d) is yellow\\n\", i, j)\n            }\n        }\n    }\n}\n"}
{"id": 52197, "name": "Draw a pixel", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n"}
{"id": 52198, "name": "Draw a pixel", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n"}
{"id": 52199, "name": "Words from neighbour ones", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n"}
{"id": 52200, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 52201, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 52202, "name": "Magic squares of singly even order", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n"}
{"id": 52203, "name": "Generate Chess960 starting position", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n"}
{"id": 52204, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 52205, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 52206, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 52207, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 52208, "name": "Perlin noise", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n    X := int(math.Floor(x)) & 255\n    Y := int(math.Floor(y)) & 255\n    Z := int(math.Floor(z)) & 255\n    x -= math.Floor(x)\n    y -= math.Floor(y)\n    z -= math.Floor(z)\n    u := fade(x)\n    v := fade(y)\n    w := fade(z)\n    A := p[X] + Y\n    AA := p[A] + Z\n    AB := p[A+1] + Z\n    B := p[X+1] + Y\n    BA := p[B] + Z\n    BB := p[B+1] + Z\n    return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n        grad(p[BA], x-1, y, z)),\n        lerp(u, grad(p[AB], x, y-1, z),\n            grad(p[BB], x-1, y-1, z))),\n        lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n            grad(p[BA+1], x-1, y, z-1)),\n            lerp(u, grad(p[AB+1], x, y-1, z-1),\n                grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n    \n    \n    \n    switch hash & 15 {\n    case 0, 12:\n        return x + y\n    case 1, 14:\n        return y - x\n    case 2:\n        return x - y\n    case 3:\n        return -x - y\n    case 4:\n        return x + z\n    case 5:\n        return z - x\n    case 6:\n        return x - z\n    case 7:\n        return -x - z\n    case 8:\n        return y + z\n    case 9, 13:\n        return z - y\n    case 10:\n        return y - z\n    }\n    \n    return -y - z\n}\n\nvar permutation = []int{\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n    140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n    247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n    57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n    74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n    60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n    65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n    200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n    52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n    207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n    119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n    129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n    218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n    81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n    184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n    222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)\n"}
{"id": 52209, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 52210, "name": "UTF-8 encode and decode", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n"}
{"id": 52211, "name": "Xiaolin Wu's line algorithm", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n    return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n    return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n    return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n    return 1 - fpart(x)\n}\n\n\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n    \n    dx := x2 - x1\n    dy := y2 - y1\n    ax := dx\n    if ax < 0 {\n        ax = -ax\n    }\n    ay := dy\n    if ay < 0 {\n        ay = -ay\n    }\n    \n    var plot func(int, int, float64)\n    if ax < ay {\n        x1, y1 = y1, x1\n        x2, y2 = y2, x2\n        dx, dy = dy, dx\n        plot = func(x, y int, c float64) {\n            g.SetPx(y, x, uint16(c*math.MaxUint16))\n        }\n    } else {\n        plot = func(x, y int, c float64) {\n            g.SetPx(x, y, uint16(c*math.MaxUint16))\n        }\n    }\n    if x2 < x1 {\n        x1, x2 = x2, x1\n        y1, y2 = y2, y1\n    }\n    gradient := dy / dx\n\n    \n    xend := round(x1)\n    yend := y1 + gradient*(xend-x1)\n    xgap := rfpart(x1 + .5)\n    xpxl1 := int(xend) \n    ypxl1 := int(ipart(yend))\n    plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n    intery := yend + gradient \n\n    \n    xend = round(x2)\n    yend = y2 + gradient*(xend-x2)\n    xgap = fpart(x2 + 0.5)\n    xpxl2 := int(xend) \n    ypxl2 := int(ipart(yend))\n    plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n    \n    for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n        plot(x, int(ipart(intery)), rfpart(intery))\n        plot(x, int(ipart(intery))+1, fpart(intery))\n        intery = intery + gradient\n    }\n}\n"}
{"id": 52212, "name": "Keyboard macros", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"unsafe\"\n\nfunc main() {\n    d := C.XOpenDisplay(nil)\n    f7, f6 := C.CString(\"F7\"), C.CString(\"F6\")\n    defer C.free(unsafe.Pointer(f7))\n    defer C.free(unsafe.Pointer(f6))\n\n    if d != nil {\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),\n            C.Mod1Mask, \n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),\n            C.Mod1Mask,\n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n\n        var event C.XEvent\n        for {\n            C.XNextEvent(d, &event)\n            if C.getXEvent_type(event) == C.KeyPress {\n                xkeyEvent := C.getXEvent_xkey(event)\n                s := C.XLookupKeysym(&xkeyEvent, 0)\n                if s == C.XK_F7 {\n                    fmt.Println(\"something's happened\")\n                } else if s == C.XK_F6 {\n                    break\n                }\n            }\n        }\n\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n    } else {\n        fmt.Println(\"XOpenDisplay did not succeed\")\n    }\n}\n"}
{"id": 52213, "name": "McNuggets problem", "Java": "public class McNuggets {\n\n    public static void main(String... args) {\n        int[] SIZES = new int[] { 6, 9, 20 };\n        int MAX_TOTAL = 100;\n        \n        int numSizes = SIZES.length;\n        int[] counts = new int[numSizes];\n        int maxFound = MAX_TOTAL + 1;\n        boolean[] found = new boolean[maxFound];\n        int numFound = 0;\n        int total = 0;\n        boolean advancedState = false;\n        do {\n            if (!found[total]) {\n                found[total] = true;\n                numFound++;\n            }\n            \n            \n            advancedState = false;\n            for (int i = 0; i < numSizes; i++) {\n                int curSize = SIZES[i];\n                if ((total + curSize) > MAX_TOTAL) {\n                    \n                    total -= counts[i] * curSize;\n                    counts[i] = 0;\n                }\n                else {\n                    \n                    counts[i]++;\n                    total += curSize;\n                    advancedState = true;\n                    break;\n                }\n            }\n            \n        } while ((numFound < maxFound) && advancedState);\n        \n        if (numFound < maxFound) {\n            \n            for (int i = MAX_TOTAL; i >= 0; i--) {\n                if (!found[i]) {\n                    System.out.println(\"Largest non-McNugget number in the search space is \" + i);\n                    break;\n                }\n            }\n        }\n        else {\n            System.out.println(\"All numbers in the search space are McNugget numbers\");\n        }\n        \n        return;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n    sv := make([]bool, limit+1) \n    for s := 0; s <= limit; s += 6 {\n        for n := s; n <= limit; n += 9 {\n            for t := n; t <= limit; t += 20 {\n                sv[t] = true\n            }\n        }\n    }\n    for i := limit; i >= 0; i-- {\n        if !sv[i] {\n            fmt.Println(\"Maximum non-McNuggets number is\", i)\n            return\n        }\n    }\n}\n\nfunc main() {\n    mcnugget(100)\n}\n"}
{"id": 52214, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 52215, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 52216, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 52217, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 52218, "name": "Pseudo-random numbers_Xorshift star", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 52219, "name": "Four is the number of letters in the ...", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class FourIsTheNumberOfLetters {\n\n    public static void main(String[] args) {\n        String [] words = neverEndingSentence(201);\n        System.out.printf(\"Display the first 201 numbers in the sequence:%n%3d: \", 1);\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            System.out.printf(\"%2d \", numberOfLetters(words[i]));\n            if ( (i+1) % 25 == 0 ) {\n                System.out.printf(\"%n%3d: \", i+2);\n            }\n        }\n        System.out.printf(\"%nTotal number of characters in the sentence is %d%n\", characterCount(words));\n        for ( int i = 3 ; i <= 7 ; i++ ) {\n            int index = (int) Math.pow(10, i);\n            words = neverEndingSentence(index);\n            String last = words[words.length-1].replace(\",\", \"\");\n            System.out.printf(\"Number of letters of the %s word is %d. The word is \\\"%s\\\".  The sentence length is %,d characters.%n\", toOrdinal(index), numberOfLetters(last), last, characterCount(words));\n        }\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static void displaySentence(String[] words, int lineLength) {\n        int currentLength = 0;\n        for ( String word : words ) {\n            if ( word.length() + currentLength > lineLength ) {\n                String first = word.substring(0, lineLength-currentLength);\n                String second = word.substring(lineLength-currentLength);\n                System.out.println(first);\n                System.out.print(second);\n                currentLength = second.length();\n            }\n            else {\n                System.out.print(word);\n                currentLength += word.length();\n            }\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n            System.out.print(\" \");\n            currentLength++;\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n        }\n        System.out.println();\n    }\n    \n    private static int numberOfLetters(String word) {\n        return word.replace(\",\",\"\").replace(\"-\",\"\").length();\n    }\n    \n    private static long characterCount(String[] words) {\n        int characterCount = 0;\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            characterCount += words[i].length() + 1;\n        }        \n        \n        characterCount--;\n        return characterCount;\n    }\n    \n    private static String[] startSentence = new String[] {\"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\", \"first\", \"word\", \"of\", \"this\", \"sentence,\"};\n    \n    private static String[] neverEndingSentence(int wordCount) {\n        String[] words = new String[wordCount];\n        int index;\n        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {\n            words[index] = startSentence[index];\n        }\n        int sentencePosition = 1;\n        while ( index < wordCount ) {\n            \n            \n            sentencePosition++;\n            String word = words[sentencePosition-1];\n            for ( String wordLoop : numToString(numberOfLetters(word)).split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n            \n            words[index] = \"in\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            words[index] = \"the\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            for ( String wordLoop : (toOrdinal(sentencePosition) + \",\").split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n        }\n        return words;\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n    \n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n"}
{"id": 52220, "name": "ASCII art diagram converter", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n"}
{"id": 52221, "name": "Levenshtein distance_Alignment", "Java": "public class LevenshteinAlignment {\n\n    public static String[] alignment(String a, String b) {\n        a = a.toLowerCase();\n        b = b.toLowerCase();\n        \n        int[][] costs = new int[a.length()+1][b.length()+1];\n        for (int j = 0; j <= b.length(); j++)\n            costs[0][j] = j;\n        for (int i = 1; i <= a.length(); i++) {\n            costs[i][0] = i;\n            for (int j = 1; j <= b.length(); j++) {\n                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);\n            }\n        }\n\n\t\n\tStringBuilder aPathRev = new StringBuilder();\n\tStringBuilder bPathRev = new StringBuilder();\n\tfor (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {\n\t    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append(b.charAt(--j));\n\t    } else if (costs[i][j] == 1 + costs[i-1][j]) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append('-');\n\t    } else if (costs[i][j] == 1 + costs[i][j-1]) {\n\t\taPathRev.append('-');\n\t\tbPathRev.append(b.charAt(--j));\n\t    }\n\t}\n        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};\n    }\n\n    public static void main(String[] args) {\n\tString[] result = alignment(\"rosettacode\", \"raisethysword\");\n\tSystem.out.println(result[0]);\n\tSystem.out.println(result[1]);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"github.com/biogo/biogo/align\"\n    ab \"github.com/biogo/biogo/alphabet\"\n    \"github.com/biogo/biogo/feat\"\n    \"github.com/biogo/biogo/seq/linear\"\n)\n\nfunc main() {\n    \n    \n    lc := ab.Must(ab.NewAlphabet(\"-abcdefghijklmnopqrstuvwxyz\",\n        feat.Undefined, '-', 0, true))\n    \n    \n    \n    \n    nw := make(align.NW, lc.Len())\n    for i := range nw {\n        r := make([]int, lc.Len())\n        nw[i] = r\n        for j := range r {\n            if j != i {\n                r[j] = -1\n            }\n        }\n    }\n    \n    a := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"rosettacode\"))}\n    a.Alpha = lc\n    b := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"raisethysword\"))}\n    b.Alpha = lc\n    \n    aln, err := nw.Align(a, b)\n    \n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fa := align.Format(a, b, aln, '-')\n    fmt.Printf(\"%s\\n%s\\n\", fa[0], fa[1])\n    aa := fmt.Sprint(fa[0])\n    ba := fmt.Sprint(fa[1])\n    ma := make([]byte, len(aa))\n    for i := range ma {\n        if aa[i] == ba[i] {\n            ma[i] = ' '\n        } else {\n            ma[i] = '|'\n        }\n    }\n    fmt.Println(string(ma))\n}\n"}
{"id": 52222, "name": "Same fringe", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n"}
{"id": 52223, "name": "Simulate input_Keyboard", "Java": "import java.awt.Robot\npublic static void type(String str){\n   Robot robot = new Robot();\n   for(char ch:str.toCharArray()){\n      if(Character.isUpperCase(ch)){\n         robot.keyPress(KeyEvent.VK_SHIFT);\n         robot.keyPress((int)ch);\n         robot.keyRelease((int)ch);\n         robot.keyRelease(KeyEvent.VK_SHIFT);\n      }else{\n         char upCh = Character.toUpperCase(ch);\n         robot.keyPress((int)upCh);\n         robot.keyRelease((int)upCh);\n      }\n   }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/micmonay/keybd_event\"\n    \"log\"\n    \"runtime\"\n    \"time\"\n)\n\nfunc main() {\n    kb, err := keybd_event.NewKeyBonding()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    if runtime.GOOS == \"linux\" {\n        time.Sleep(2 * time.Second)\n    }\n\n    \n    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)\n\n    \n    err = kb.Launching()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 52224, "name": "Peaceful chess queen armies", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n"}
{"id": 52225, "name": "Loops_Infinite", "Java": "while (true) {\n   System.out.println(\"SPAM\");\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 52226, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 52227, "name": "Active Directory_Search for a user", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n"}
{"id": 52228, "name": "Singular value decomposition", "Java": "import Jama.Matrix;\npublic class SingularValueDecomposition {\n    public static void main(String[] args) {\n        double[][] matrixArray = {{3, 0}, {4, 5}};\n        var matrix = new Matrix(matrixArray);\n        var svd = matrix.svd();\n        svd.getU().print(0, 10); \n        svd.getS().print(0, 10);\n        svd.getV().print(0, 10);\n    }\n}\n", "Go": "<package main\n\nimport (\n    \"fmt\"\n    \"gonum.org/v1/gonum/mat\"\n    \"log\"\n)\n\nfunc matPrint(m mat.Matrix) {\n    fa := mat.Formatted(m, mat.Prefix(\"\"), mat.Squeeze())\n    fmt.Printf(\"%13.10f\\n\", fa)\n}\n\nfunc main() {\n    var svd mat.SVD\n    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})\n    ok := svd.Factorize(a, mat.SVDFull)\n    if !ok {\n        log.Fatal(\"Something went wrong!\")\n    }\n    u := mat.NewDense(2, 2, nil)\n    svd.UTo(u)\n    fmt.Println(\"U:\")\n    matPrint(u)\n    values := svd.Values(nil)\n    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})\n    fmt.Println(\"\\nΣ:\")\n    matPrint(sigma)\n    vt := mat.NewDense(2, 2, nil)\n    svd.VTo(vt)\n    fmt.Println(\"\\nVT:\")\n    matPrint(vt)\n}\n"}
{"id": 52229, "name": "Test integerness", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n"}
{"id": 52230, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 52231, "name": "Rodrigues’ rotation formula", "Java": "\n\nclass Vector{\n  private double x, y, z;\n\n  public Vector(double x1,double y1,double z1){\n    x = x1;\n    y = y1;\n    z = z1;\n  }\n  \n  void printVector(int x,int y){\n    text(\"( \" + this.x + \" )  \\u00ee + ( \" + this.y + \" ) + \\u0135 ( \" + this.z + \") \\u006b\\u0302\",x,y);\n  }\n\n  public double norm() {\n    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);\n  }\n  \n  public Vector normalize(){\n    double length = this.norm();\n    return new Vector(this.x / length, this.y / length, this.z / length);\n  }\n  \n  public double dotProduct(Vector v2) {\n    return this.x*v2.x + this.y*v2.y + this.z*v2.z;\n  }\n  \n  public Vector crossProduct(Vector v2) {\n    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);\n  }\n  \n  public double getAngle(Vector v2) {\n    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));\n  }\n  \n  public Vector aRotate(Vector v, double a) {\n    double ca = Math.cos(a), sa = Math.sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    Vector[] r = {\n        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),\n        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),\n        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)\n    };\n    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));\n  }\n}\n\nvoid setup(){\n  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);\n  double a = v1.getAngle(v2);\n  Vector cp = v1.crossProduct(v2);\n  Vector normCP = cp.normalize();\n  Vector np = v1.aRotate(normCP,a);\n  \n  size(1200,600);\n  fill(#000000);\n  textSize(30);\n  \n  text(\"v1 = \",10,100);\n  v1.printVector(60,100);\n  text(\"v2 = \",10,150);\n  v2.printVector(60,150);\n  text(\"rV = \",10,200);\n  np.printVector(60,200);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector [3]float64\ntype matrix [3]vector\n\nfunc norm(v vector) float64 {\n    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])\n}\n\nfunc normalize(v vector) vector {\n    length := norm(v)\n    return vector{v[0] / length, v[1] / length, v[2] / length}\n}\n\nfunc dotProduct(v1, v2 vector) float64 {\n    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n}\n\nfunc crossProduct(v1, v2 vector) vector {\n    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}\n}\n\nfunc getAngle(v1, v2 vector) float64 {\n    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))\n}\n\nfunc matrixMultiply(m matrix, v vector) vector {\n    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}\n}\n\nfunc aRotate(p, v vector, a float64) vector {\n    ca, sa := math.Cos(a), math.Sin(a)\n    t := 1 - ca\n    x, y, z := v[0], v[1], v[2]\n    r := matrix{\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},\n    }\n    return matrixMultiply(r, p)\n}\n\nfunc main() {\n    v1 := vector{5, -6, 4}\n    v2 := vector{8, 5, -30}\n    a := getAngle(v1, v2)\n    cp := crossProduct(v1, v2)\n    ncp := normalize(cp)\n    np := aRotate(v1, ncp, a)\n    fmt.Println(np)\n}\n"}
{"id": 52232, "name": "Rodrigues’ rotation formula", "Java": "\n\nclass Vector{\n  private double x, y, z;\n\n  public Vector(double x1,double y1,double z1){\n    x = x1;\n    y = y1;\n    z = z1;\n  }\n  \n  void printVector(int x,int y){\n    text(\"( \" + this.x + \" )  \\u00ee + ( \" + this.y + \" ) + \\u0135 ( \" + this.z + \") \\u006b\\u0302\",x,y);\n  }\n\n  public double norm() {\n    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);\n  }\n  \n  public Vector normalize(){\n    double length = this.norm();\n    return new Vector(this.x / length, this.y / length, this.z / length);\n  }\n  \n  public double dotProduct(Vector v2) {\n    return this.x*v2.x + this.y*v2.y + this.z*v2.z;\n  }\n  \n  public Vector crossProduct(Vector v2) {\n    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);\n  }\n  \n  public double getAngle(Vector v2) {\n    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));\n  }\n  \n  public Vector aRotate(Vector v, double a) {\n    double ca = Math.cos(a), sa = Math.sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    Vector[] r = {\n        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),\n        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),\n        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)\n    };\n    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));\n  }\n}\n\nvoid setup(){\n  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);\n  double a = v1.getAngle(v2);\n  Vector cp = v1.crossProduct(v2);\n  Vector normCP = cp.normalize();\n  Vector np = v1.aRotate(normCP,a);\n  \n  size(1200,600);\n  fill(#000000);\n  textSize(30);\n  \n  text(\"v1 = \",10,100);\n  v1.printVector(60,100);\n  text(\"v2 = \",10,150);\n  v2.printVector(60,150);\n  text(\"rV = \",10,200);\n  np.printVector(60,200);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector [3]float64\ntype matrix [3]vector\n\nfunc norm(v vector) float64 {\n    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])\n}\n\nfunc normalize(v vector) vector {\n    length := norm(v)\n    return vector{v[0] / length, v[1] / length, v[2] / length}\n}\n\nfunc dotProduct(v1, v2 vector) float64 {\n    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n}\n\nfunc crossProduct(v1, v2 vector) vector {\n    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}\n}\n\nfunc getAngle(v1, v2 vector) float64 {\n    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))\n}\n\nfunc matrixMultiply(m matrix, v vector) vector {\n    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}\n}\n\nfunc aRotate(p, v vector, a float64) vector {\n    ca, sa := math.Cos(a), math.Sin(a)\n    t := 1 - ca\n    x, y, z := v[0], v[1], v[2]\n    r := matrix{\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},\n    }\n    return matrixMultiply(r, p)\n}\n\nfunc main() {\n    v1 := vector{5, -6, 4}\n    v2 := vector{8, 5, -30}\n    a := getAngle(v1, v2)\n    cp := crossProduct(v1, v2)\n    ncp := normalize(cp)\n    np := aRotate(v1, ncp, a)\n    fmt.Println(np)\n}\n"}
{"id": 52233, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 52234, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 52235, "name": "Death Star", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": 52236, "name": "Lucky and even lucky numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n    for i := 0; i < luckySize; i++ {\n        luckyOdd[i] = i*2 + 1\n        luckyEven[i] = i*2 + 2\n    }\n}\n\nfunc filterLuckyOdd() {\n    for n := 2; n < len(luckyOdd); n++ {\n        m := luckyOdd[n-1]\n        end := (len(luckyOdd)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyOdd[j:], luckyOdd[j+1:])\n            luckyOdd = luckyOdd[:len(luckyOdd)-1]\n        }\n    }\n}\n\nfunc filterLuckyEven() {\n    for n := 2; n < len(luckyEven); n++ {\n        m := luckyEven[n-1]\n        end := (len(luckyEven)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyEven[j:], luckyEven[j+1:])\n            luckyEven = luckyEven[:len(luckyEven)-1]\n        }\n    }\n}\n\nfunc printSingle(j int, odd bool) error {\n    if odd {\n        if j >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n    } else {\n        if j >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n    }\n    return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n    if odd {\n        if k >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyOdd[j-1 : k])\n    } else {\n        if k >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyEven[j-1 : k])\n    }\n    return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n    var r []int\n    if odd {\n        max := luckyOdd[len(luckyOdd)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyOdd {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    } else {\n        max := luckyEven[len(luckyEven)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyEven {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    }\n    return nil\n}\n\nfunc main() {\n    nargs := len(os.Args)\n    if nargs < 2 || nargs > 4 {\n        log.Fatal(\"there must be between 1 and 3 command line arguments\")\n    }\n    filterLuckyOdd()\n    filterLuckyEven()\n    j, err := strconv.Atoi(os.Args[1])\n    if err != nil || j < 1 {\n        log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n    }\n    if nargs == 2 {\n        if err := printSingle(j, true); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    if nargs == 3 {\n        k, err := strconv.Atoi(os.Args[2])\n        if err != nil {\n            log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n        }\n        if k >= 0 {\n            if j > k {\n                log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n            }\n            if err := printRange(j, k, true); err != nil {\n                log.Fatal(err)\n            }\n        } else {\n            l := -k\n            if j > l {\n                log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n            }\n            if err := printBetween(j, l, true); err != nil {\n                log.Fatal(err)\n            }\n        }\n        return\n    }\n\n    var odd bool\n    switch lucky := strings.ToLower(os.Args[3]); lucky {\n    case \"lucky\":\n        odd = true\n    case \"evenlucky\":\n        odd = false\n    default:\n        log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n    }\n    if os.Args[2] == \",\" {\n        if err := printSingle(j, odd); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    k, err := strconv.Atoi(os.Args[2])\n    if err != nil {\n        log.Fatal(\"second argument must be an integer or a comma\")\n    }\n    if k >= 0 {\n        if j > k {\n            log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n        }\n        if err := printRange(j, k, odd); err != nil {\n            log.Fatal(err)\n        }\n    } else {\n        l := -k\n        if j > l {\n            log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n        }\n        if err := printBetween(j, l, odd); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n"}
{"id": 52237, "name": "Simple database", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n    \"unicode\"\n)\n\n\n\ntype Item struct {\n    Stamp time.Time\n    Name  string\n    Tags  []string `json:\",omitempty\"`\n    Notes string   `json:\",omitempty\"`\n}\n\n\nfunc (i *Item) String() string {\n    s := i.Stamp.Format(time.ANSIC) + \"\\n  Name:  \" + i.Name\n    if len(i.Tags) > 0 {\n        s = fmt.Sprintf(\"%s\\n  Tags:  %v\", s, i.Tags)\n    }\n    if i.Notes > \"\" {\n        s += \"\\n  Notes: \" + i.Notes\n    }\n    return s\n}\n\n\ntype db []*Item\n\n\nfunc (d db) Len() int           { return len(d) }\nfunc (d db) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }\nfunc (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) }\n\n\nconst fn = \"sdb.json\"\n\nfunc main() {\n    if len(os.Args) == 1 {\n        latest()\n        return\n    }\n    switch os.Args[1] {\n    case \"add\":\n        add()\n    case \"latest\":\n        latest()\n    case \"tags\":\n        tags()\n    case \"all\":\n        all()\n    case \"help\":\n        help()\n    default:\n        usage(\"unrecognized command\")\n    }\n}\n\nfunc usage(err string) {\n    if err > \"\" {\n        fmt.Println(err)\n    }\n    fmt.Println(`usage:  sdb [command] [data]\n    where command is one of add, latest, tags, all, or help.`)\n}\n\nfunc help() {\n    usage(\"\")\n    fmt.Println(`\nCommands must be in lower case.\nIf no command is specified, the default command is latest.\n\nLatest prints the latest item.\nAll prints all items in chronological order.\nTags prints the lastest item for each tag.\nHelp prints this message.\n\nAdd adds data as a new record.  The format is,\n\n  name [tags] [notes]\n\nName is the name of the item and is required for the add command.\n\nTags are optional.  A tag is a single word.\nA single tag can be specified without enclosing brackets.\nMultiple tags can be specified by enclosing them in square brackets.\n\nText remaining after tags is taken as notes.  Notes do not have to be\nenclosed in quotes or brackets.  The brackets above are only showing\nthat notes are optional.\n\nQuotes may be useful however--as recognized by your operating system shell\nor command line--to allow entry of arbitrary text.  In particular, quotes\nor escape characters may be needed to prevent the shell from trying to\ninterpret brackets or other special characters.\n\nExamples:\nsdb add Bookends                        \nsdb add Bookends rock my favorite       \nsdb add Bookends [rock folk]            \nsdb add Bookends [] \"Simon & Garfunkel\" \nsdb add \"Simon&Garfunkel [artist]\"      \n    \nAs shown in the last example, if you use features of your shell to pass\nall data as a single string, the item name and tags will still be identified\nby separating whitespace.\n    \nThe database is stored in JSON format in the file \"sdb.json\"\n`)  \n}\n\n\nfunc load() (db, bool) {\n    d, f, ok := open()\n    if ok {\n        f.Close()\n        if len(d) == 0 {\n            fmt.Println(\"no items\")\n            ok = false\n        }\n    }\n    return d, ok\n}\n\n\nfunc open() (d db, f *os.File, ok bool) {\n    var err error\n    f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)\n    if err != nil {\n        fmt.Println(\"cant open??\")\n        fmt.Println(err)\n        return\n    }\n    jd := json.NewDecoder(f)\n    err = jd.Decode(&d)\n    \n    if err != nil && err != io.EOF {\n        fmt.Println(err)\n        f.Close()\n        return\n    }\n    ok = true\n    return\n}\n\n\nfunc latest() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    fmt.Println(d[len(d)-1])\n}\n\n\nfunc all() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    for _, i := range d {\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(i)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n\n\nfunc tags() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    \n    \n    \n    latest := make(map[string]*Item)\n    for _, item := range d {\n        for _, tag := range item.Tags {\n            li, ok := latest[tag]\n            if !ok || item.Stamp.After(li.Stamp) {\n                latest[tag] = item\n            }\n        }\n    }\n    \n    \n    type itemTags struct {\n        item *Item\n        tags []string\n    }\n    inv := make(map[*Item][]string)\n    for tag, item := range latest {\n        inv[item] = append(inv[item], tag)\n    }\n    \n    li := make(db, len(inv))\n    i := 0\n    for item := range inv {\n        li[i] = item\n        i++\n    }\n    sort.Sort(li)\n    \n    for _, item := range li {\n        tags := inv[item]\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(\"Latest item with tags\", tags)\n        fmt.Println(item)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n    \n\nfunc add() { \n    if len(os.Args) < 3 {\n        usage(\"add command requires data\")\n        return\n    } else if len(os.Args) == 3 {\n        add1()\n    } else {\n        add4()\n    }\n}   \n\n\nfunc add1() {\n    data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace)\n    if data == \"\" {\n        \n        usage(\"invalid name\")\n        return \n    }\n    sep := strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(data, nil, \"\")\n        return\n    }\n    name := data[:sep]\n    data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace)\n    if data == \"\" {\n        \n        addItem(name, nil, \"\")\n        return\n    }\n    if data[0] == '[' {\n        sep = strings.Index(data, \"]\")\n        if sep < 0 {\n            \n            addItem(name, strings.Fields(data[1:]), \"\")\n        } else {\n            \n            addItem(name, strings.Fields(data[1:sep]),\n                strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n        }\n        return\n    }\n    sep = strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(name, []string{data}, \"\")\n    } else {\n        \n        addItem(name, []string{data[:sep]},\n            strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n    }\n}\n\n\nfunc add4() {\n    name := os.Args[2]\n    tag1 := os.Args[3]\n    if tag1[0] != '[' {\n        \n        addItem(name, []string{tag1}, strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    if tag1[len(tag1)-1] == ']' {\n        \n        addItem(name, strings.Fields(tag1[1:len(tag1)-1]),\n            strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    \n    var tags []string\n    if tag1 > \"[\" {\n        tags = []string{tag1[1:]}\n    }\n    for x, tag := range os.Args[4:] {\n        if tag[len(tag)-1] != ']' {\n            tags = append(tags, tag)\n        } else {\n            \n            if tag > \"]\" {\n                tags = append(tags, tag[:len(tag)-1])\n            }\n            addItem(name, tags, strings.Join(os.Args[5+x:], \" \"))\n            return\n        }\n    }\n    \n    addItem(name, tags, \"\")\n}\n\n\nfunc addItem(name string, tags []string, notes string) {\n    db, f, ok := open()\n    if !ok {\n        return\n    }\n    defer f.Close()\n    \n    db = append(db, &Item{time.Now(), name, tags, notes})\n    sort.Sort(db)\n    js, err := json.MarshalIndent(db, \"\", \"  \")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if _, err = f.Seek(0, 0); err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Truncate(0)\n    if _, err = f.Write(js); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52238, "name": "Hough transform", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\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\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52239, "name": "Hough transform", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\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\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52240, "name": "Verify distribution uniformity_Chi-squared test", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n"}
{"id": 52241, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n"}
{"id": 52242, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n"}
{"id": 52243, "name": "Topological sort_Extracted top item", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n"}
{"id": 52244, "name": "Topological sort_Extracted top item", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n"}
{"id": 52245, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 52246, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 52247, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 52248, "name": "Superpermutation minimisation", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n"}
{"id": 52249, "name": "GUI component interaction", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 52250, "name": "One of n lines in a file", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 52251, "name": "Summarize and say sequence", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n"}
{"id": 52252, "name": "Summarize and say sequence", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n"}
{"id": 52253, "name": "Spelling of ordinal numbers", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": 52254, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 52255, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n"}
{"id": 52256, "name": "Numeric separator syntax", "Java": "public class NumericSeparatorSyntax {\n\n    public static void main(String[] args) {\n        runTask(\"Underscore allowed as seperator\", 1_000);\n        runTask(\"Multiple consecutive underscores allowed:\", 1__0_0_0);\n        runTask(\"Many multiple consecutive underscores allowed:\", 1________________________00);\n        runTask(\"Underscores allowed in multiple positions\", 1__4__4);\n        runTask(\"Underscores allowed in negative number\", -1__4__4);\n        runTask(\"Underscores allowed in floating point number\", 1__4__4e-5);\n        runTask(\"Underscores allowed in floating point exponent\", 1__4__440000e-1_2);\n        \n        \n        \n        \n    }\n    \n    private static void runTask(String description, long n) {\n        runTask(description, n, \"%d\");\n    }\n\n    private static void runTask(String description, double n) {\n        runTask(description, n, \"%3.7f\");\n    }\n\n    private static void runTask(String description, Number n, String format) {\n        System.out.printf(\"%s:  \" + format + \"%n\", description, n);\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n"}
{"id": 52257, "name": "Repeat", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 52258, "name": "Sparkline in unicode", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n"}
{"id": 52259, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 52260, "name": "Simulate input_Mouse", "Java": "Point p = component.getLocation();\nRobot robot = new Robot();\nrobot.mouseMove(p.getX(), p.getY()); \nrobot.mousePress(InputEvent.BUTTON1_MASK); \n                                       \nrobot.mouseRelease(InputEvent.BUTTON1_MASK);\n", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n"}
{"id": 52261, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 52262, "name": "Terminal control_Clear the screen", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n", "Go": "cls\n"}
{"id": 52263, "name": "Sunflower fractal", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n"}
{"id": 52264, "name": "Vogel's approximation method", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 52265, "name": "Air mass", "Java": "public class AirMass {\n    public static void main(String[] args) {\n        System.out.println(\"Angle     0 m              13700 m\");\n        System.out.println(\"------------------------------------\");\n        for (double z = 0; z <= 90; z+= 5) {\n            System.out.printf(\"%2.0f      %11.8f      %11.8f\\n\",\n                            z, airmass(0.0, z), airmass(13700.0, z));\n        }\n    }\n\n    private static double rho(double a) {\n        \n        return Math.exp(-a / 8500.0);\n    }\n\n    private static double height(double a, double z, double d) {\n        \n        \n        \n        double aa = RE + a;\n        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));\n        return hh - RE;\n    }\n\n    private static double columnDensity(double a, double z) {\n        \n        double sum = 0.0, d = 0.0;\n        while (d < FIN) {\n            \n            double delta = Math.max(DD * d, DD);\n            sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n            d += delta;\n        }\n        return sum;\n    }\n     \n    private static double airmass(double a, double z) {\n        return columnDensity(a, z) / columnDensity(a, 0.0);\n    }\n\n    private static final double RE = 6371000.0; \n    private static final double DD = 0.001; \n    private static final double FIN = 10000000.0; \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    RE  = 6371000 \n    DD  = 0.001   \n    FIN = 1e7     \n)\n\n\nfunc rho(a float64) float64 { return math.Exp(-a / 8500) }\n\n\nfunc radians(degrees float64) float64 { return degrees * math.Pi / 180 }\n\n\n\n\nfunc height(a, z, d float64) float64 {\n    aa := RE + a\n    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))\n    return hh - RE\n}\n\n\nfunc columnDensity(a, z float64) float64 {\n    sum := 0.0\n    d := 0.0\n    for d < FIN {\n        delta := math.Max(DD, DD*d) \n        sum += rho(height(a, z, d+0.5*delta)) * delta\n        d += delta\n    }\n    return sum\n}\n\nfunc airmass(a, z float64) float64 {\n    return columnDensity(a, z) / columnDensity(a, 0)\n}\n\nfunc main() {\n    fmt.Println(\"Angle     0 m              13700 m\")\n    fmt.Println(\"------------------------------------\")\n    for z := 0; z <= 90; z += 5 {\n        fz := float64(z)\n        fmt.Printf(\"%2d      %11.8f      %11.8f\\n\", z, airmass(0, fz), airmass(13700, fz))\n    }\n}\n"}
{"id": 52266, "name": "Sorting algorithms_Pancake sort", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n"}
{"id": 52267, "name": "Chemical calculator", "Java": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\npublic class ChemicalCalculator {\n    private static final Map<String, Double> atomicMass = new HashMap<>();\n\n    static {\n        atomicMass.put(\"H\", 1.008);\n        atomicMass.put(\"He\", 4.002602);\n        atomicMass.put(\"Li\", 6.94);\n        atomicMass.put(\"Be\", 9.0121831);\n        atomicMass.put(\"B\", 10.81);\n        atomicMass.put(\"C\", 12.011);\n        atomicMass.put(\"N\", 14.007);\n        atomicMass.put(\"O\", 15.999);\n        atomicMass.put(\"F\", 18.998403163);\n        atomicMass.put(\"Ne\", 20.1797);\n        atomicMass.put(\"Na\", 22.98976928);\n        atomicMass.put(\"Mg\", 24.305);\n        atomicMass.put(\"Al\", 26.9815385);\n        atomicMass.put(\"Si\", 28.085);\n        atomicMass.put(\"P\", 30.973761998);\n        atomicMass.put(\"S\", 32.06);\n        atomicMass.put(\"Cl\", 35.45);\n        atomicMass.put(\"Ar\", 39.948);\n        atomicMass.put(\"K\", 39.0983);\n        atomicMass.put(\"Ca\", 40.078);\n        atomicMass.put(\"Sc\", 44.955908);\n        atomicMass.put(\"Ti\", 47.867);\n        atomicMass.put(\"V\", 50.9415);\n        atomicMass.put(\"Cr\", 51.9961);\n        atomicMass.put(\"Mn\", 54.938044);\n        atomicMass.put(\"Fe\", 55.845);\n        atomicMass.put(\"Co\", 58.933194);\n        atomicMass.put(\"Ni\", 58.6934);\n        atomicMass.put(\"Cu\", 63.546);\n        atomicMass.put(\"Zn\", 65.38);\n        atomicMass.put(\"Ga\", 69.723);\n        atomicMass.put(\"Ge\", 72.630);\n        atomicMass.put(\"As\", 74.921595);\n        atomicMass.put(\"Se\", 78.971);\n        atomicMass.put(\"Br\", 79.904);\n        atomicMass.put(\"Kr\", 83.798);\n        atomicMass.put(\"Rb\", 85.4678);\n        atomicMass.put(\"Sr\", 87.62);\n        atomicMass.put(\"Y\", 88.90584);\n        atomicMass.put(\"Zr\", 91.224);\n        atomicMass.put(\"Nb\", 92.90637);\n        atomicMass.put(\"Mo\", 95.95);\n        atomicMass.put(\"Ru\", 101.07);\n        atomicMass.put(\"Rh\", 102.90550);\n        atomicMass.put(\"Pd\", 106.42);\n        atomicMass.put(\"Ag\", 107.8682);\n        atomicMass.put(\"Cd\", 112.414);\n        atomicMass.put(\"In\", 114.818);\n        atomicMass.put(\"Sn\", 118.710);\n        atomicMass.put(\"Sb\", 121.760);\n        atomicMass.put(\"Te\", 127.60);\n        atomicMass.put(\"I\", 126.90447);\n        atomicMass.put(\"Xe\", 131.293);\n        atomicMass.put(\"Cs\", 132.90545196);\n        atomicMass.put(\"Ba\", 137.327);\n        atomicMass.put(\"La\", 138.90547);\n        atomicMass.put(\"Ce\", 140.116);\n        atomicMass.put(\"Pr\", 140.90766);\n        atomicMass.put(\"Nd\", 144.242);\n        atomicMass.put(\"Pm\", 145.0);\n        atomicMass.put(\"Sm\", 150.36);\n        atomicMass.put(\"Eu\", 151.964);\n        atomicMass.put(\"Gd\", 157.25);\n        atomicMass.put(\"Tb\", 158.92535);\n        atomicMass.put(\"Dy\", 162.500);\n        atomicMass.put(\"Ho\", 164.93033);\n        atomicMass.put(\"Er\", 167.259);\n        atomicMass.put(\"Tm\", 168.93422);\n        atomicMass.put(\"Yb\", 173.054);\n        atomicMass.put(\"Lu\", 174.9668);\n        atomicMass.put(\"Hf\", 178.49);\n        atomicMass.put(\"Ta\", 180.94788);\n        atomicMass.put(\"W\", 183.84);\n        atomicMass.put(\"Re\", 186.207);\n        atomicMass.put(\"Os\", 190.23);\n        atomicMass.put(\"Ir\", 192.217);\n        atomicMass.put(\"Pt\", 195.084);\n        atomicMass.put(\"Au\", 196.966569);\n        atomicMass.put(\"Hg\", 200.592);\n        atomicMass.put(\"Tl\", 204.38);\n        atomicMass.put(\"Pb\", 207.2);\n        atomicMass.put(\"Bi\", 208.98040);\n        atomicMass.put(\"Po\", 209.0);\n        atomicMass.put(\"At\", 210.0);\n        atomicMass.put(\"Rn\", 222.0);\n        atomicMass.put(\"Fr\", 223.0);\n        atomicMass.put(\"Ra\", 226.0);\n        atomicMass.put(\"Ac\", 227.0);\n        atomicMass.put(\"Th\", 232.0377);\n        atomicMass.put(\"Pa\", 231.03588);\n        atomicMass.put(\"U\", 238.02891);\n        atomicMass.put(\"Np\", 237.0);\n        atomicMass.put(\"Pu\", 244.0);\n        atomicMass.put(\"Am\", 243.0);\n        atomicMass.put(\"Cm\", 247.0);\n        atomicMass.put(\"Bk\", 247.0);\n        atomicMass.put(\"Cf\", 251.0);\n        atomicMass.put(\"Es\", 252.0);\n        atomicMass.put(\"Fm\", 257.0);\n        atomicMass.put(\"Uue\", 315.0);\n        atomicMass.put(\"Ubn\", 299.0);\n    }\n\n    private static double evaluate(String s) {\n        String sym = s + \"[\";\n        double sum = 0.0;\n        StringBuilder symbol = new StringBuilder();\n        String number = \"\";\n        for (int i = 0; i < sym.length(); ++i) {\n            char c = sym.charAt(i);\n            if ('@' <= c && c <= '[') {\n                \n                int n = 1;\n                if (!number.isEmpty()) {\n                    n = Integer.parseInt(number);\n                }\n                if (symbol.length() > 0) {\n                    sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;\n                }\n                if (c == '[') {\n                    break;\n                }\n                symbol = new StringBuilder(String.valueOf(c));\n                number = \"\";\n            } else if ('a' <= c && c <= 'z') {\n                symbol.append(c);\n            } else if ('0' <= c && c <= '9') {\n                number += c;\n            } else {\n                throw new RuntimeException(\"Unexpected symbol \" + c + \" in molecule\");\n            }\n        }\n        return sum;\n    }\n\n    private static String replaceParens(String s) {\n        char letter = 'a';\n        String si = s;\n        while (true) {\n            int start = si.indexOf('(');\n            if (start == -1) {\n                break;\n            }\n\n            for (int i = start + 1; i < si.length(); ++i) {\n                if (si.charAt(i) == ')') {\n                    String expr = si.substring(start + 1, i);\n                    String symbol = \"@\" + letter;\n                    String pattern = Pattern.quote(si.substring(start, i + 1));\n                    si = si.replaceFirst(pattern, symbol);\n                    atomicMass.put(symbol, evaluate(expr));\n                    letter++;\n                    break;\n                }\n                if (si.charAt(i) == '(') {\n                    start = i;\n                }\n            }\n        }\n        return si;\n    }\n\n    public static void main(String[] args) {\n        List<String> molecules = List.of(\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        );\n        for (String molecule : molecules) {\n            double mass = evaluate(replaceParens(molecule));\n            System.out.printf(\"%17s -> %7.3f\\n\", molecule, mass);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n"}
{"id": 52268, "name": "Active Directory_Connect", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n"}
{"id": 52269, "name": "Permutations by swapping", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n"}
{"id": 52270, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n"}
{"id": 52271, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 52272, "name": "Image convolution", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class ImageConvolution\n{\n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n  }\n  \n  private static int bound(int value, int endIndex)\n  {\n    if (value < 0)\n      return 0;\n    if (value < endIndex)\n      return value;\n    return endIndex - 1;\n  }\n  \n  public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)\n  {\n    int inputWidth = inputData.width;\n    int inputHeight = inputData.height;\n    int kernelWidth = kernel.width;\n    int kernelHeight = kernel.height;\n    if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd width\");\n    if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd height\");\n    int kernelWidthRadius = kernelWidth >>> 1;\n    int kernelHeightRadius = kernelHeight >>> 1;\n    \n    ArrayData outputData = new ArrayData(inputWidth, inputHeight);\n    for (int i = inputWidth - 1; i >= 0; i--)\n    {\n      for (int j = inputHeight - 1; j >= 0; j--)\n      {\n        double newValue = 0.0;\n        for (int kw = kernelWidth - 1; kw >= 0; kw--)\n          for (int kh = kernelHeight - 1; kh >= 0; kh--)\n            newValue += kernel.get(kw, kh) * inputData.get(\n                          bound(i + kw - kernelWidthRadius, inputWidth),\n                          bound(j + kh - kernelHeightRadius, inputHeight));\n        outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));\n      }\n    }\n    return outputData;\n  }\n  \n  public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData reds = new ArrayData(width, height);\n    ArrayData greens = new ArrayData(width, height);\n    ArrayData blues = new ArrayData(width, height);\n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        reds.set(x, y, (rgbValue >>> 16) & 0xFF);\n        greens.set(x, y, (rgbValue >>> 8) & 0xFF);\n        blues.set(x, y, rgbValue & 0xFF);\n      }\n    }\n    return new ArrayData[] { reds, greens, blues };\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException\n  {\n    ArrayData reds = redGreenBlue[0];\n    ArrayData greens = redGreenBlue[1];\n    ArrayData blues = redGreenBlue[2];\n    BufferedImage outputImage = new BufferedImage(reds.width, reds.height,\n                                                  BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < reds.height; y++)\n    {\n      for (int x = 0; x < reds.width; x++)\n      {\n        int red = bound(reds.get(x, y), 256);\n        int green = bound(greens.get(x, y), 256);\n        int blue = bound(blues.get(x, y), 256);\n        outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    int kernelWidth = Integer.parseInt(args[2]);\n    int kernelHeight = Integer.parseInt(args[3]);\n    int kernelDivisor = Integer.parseInt(args[4]);\n    System.out.println(\"Kernel size: \" + kernelWidth + \"x\" + kernelHeight +\n                       \", divisor=\" + kernelDivisor);\n    int y = 5;\n    ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);\n    for (int i = 0; i < kernelHeight; i++)\n    {\n      System.out.print(\"[\");\n      for (int j = 0; j < kernelWidth; j++)\n      {\n        kernel.set(j, i, Integer.parseInt(args[y++]));\n        System.out.print(\" \" + kernel.get(j, i) + \" \");\n      }\n      System.out.println(\"]\");\n    }\n    \n    ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);\n    for (int i = 0; i < dataArrays.length; i++)\n      dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);\n    writeOutputImage(args[1], dataArrays);\n    return;\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/jpeg\"\n    \"math\"\n    \"os\"\n)\n\n\n\nfunc kf3(k *[9]float64, src, dst *image.Gray) {\n    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {\n        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {\n            var sum float64\n            var i int\n            for yo := y - 1; yo <= y+1; yo++ {\n                for xo := x - 1; xo <= x+1; xo++ {\n                    if (image.Point{xo, yo}).In(src.Rect) {\n                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)\n                    } else {\n                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)\n                    }\n                    i++\n                }\n            }\n            dst.SetGray(x, y,\n                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})\n        }\n    }\n}\n\nvar blur = [9]float64{\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9}\n\n\n\nfunc blurY(src *image.YCbCr) *image.YCbCr {\n    dst := *src\n\n    \n    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {\n        return &dst\n    }\n\n    \n    srcGray := image.Gray{src.Y, src.YStride, src.Rect}\n    dstGray := srcGray\n    dstGray.Pix = make([]uint8, len(src.Y))\n    kf3(&blur, &srcGray, &dstGray) \n\n    \n    dst.Y = dstGray.Pix                   \n    dst.Cb = append([]uint8{}, src.Cb...) \n    dst.Cr = append([]uint8{}, src.Cr...)\n    return &dst\n}\n\nfunc main() {\n    \n    \n    f, err := os.Open(\"Lenna100.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    img, err := jpeg.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n    y, ok := img.(*image.YCbCr)\n    if !ok {\n        fmt.Println(\"expected color jpeg\")\n        return\n    }\n    f, err = os.Create(\"blur.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52273, "name": "Dice game probabilities", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n"}
{"id": 52274, "name": "Sokoban", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n"}
{"id": 52275, "name": "Practical numbers", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n"}
{"id": 52276, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 52277, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 52278, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n"}
{"id": 52279, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 52280, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 52281, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 52282, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 52283, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 52284, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 52285, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 52286, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 52287, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 52288, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 52289, "name": "Word search", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n"}
{"id": 52290, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 52291, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 52292, "name": "Object serialization", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 52293, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 52294, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 52295, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 52296, "name": "Zumkeller numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 52297, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 52298, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 52299, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 52300, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 52301, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 52302, "name": "Markov chain text generator", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 52303, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 52304, "name": "Geometric algebra", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n"}
{"id": 52305, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 52306, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 52307, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 52308, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n"}
{"id": 52309, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n"}
{"id": 52310, "name": "AVL tree", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n"}
{"id": 52311, "name": "AVL tree", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n"}
{"id": 52312, "name": "Penrose tiling", "Java": "import java.awt.*;\nimport java.util.List;\nimport java.awt.geom.Path2D;\nimport java.util.*;\nimport javax.swing.*;\nimport static java.lang.Math.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class PenroseTiling extends JPanel {\n    \n    class Tile {\n        double x, y, angle, size;\n        Type type;\n\n        Tile(Type t, double x, double y, double a, double s) {\n            type = t;\n            this.x = x;\n            this.y = y;\n            angle = a;\n            size = s;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Tile) {\n                Tile t = (Tile) o;\n                return type == t.type && x == t.x && y == t.y && angle == t.angle;\n            }\n            return false;\n        }\n    }\n\n    enum Type {\n        Kite, Dart\n    }\n\n    static final double G = (1 + sqrt(5)) / 2; \n    static final double T = toRadians(36); \n\n    List<Tile> tiles = new ArrayList<>();\n\n    public PenroseTiling() {\n        int w = 700, h = 450;\n        setPreferredSize(new Dimension(w, h));\n        setBackground(Color.white);\n\n        tiles = deflateTiles(setupPrototiles(w, h), 5);\n    }\n\n    List<Tile> setupPrototiles(int w, int h) {\n        List<Tile> proto = new ArrayList<>();\n\n        \n        for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)\n            proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));\n\n        return proto;\n    }\n\n    List<Tile> deflateTiles(List<Tile> tls, int generation) {\n        if (generation <= 0)\n            return tls;\n\n        List<Tile> next = new ArrayList<>();\n\n        for (Tile tile : tls) {\n            double x = tile.x, y = tile.y, a = tile.angle, nx, ny;\n            double size = tile.size / G;\n\n            if (tile.type == Type.Dart) {\n                next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    nx = x + cos(a - 4 * T * sign) * G * tile.size;\n                    ny = y - sin(a - 4 * T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));\n                }\n\n            } else {\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));\n\n                    nx = x + cos(a - T * sign) * G * tile.size;\n                    ny = y - sin(a - T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));\n                }\n            }\n        }\n        \n        tls = next.stream().distinct().collect(toList());\n\n        return deflateTiles(tls, generation - 1);\n    }\n\n    void drawTiles(Graphics2D g) {\n        double[][] dist = {{G, G, G}, {-G, -1, -G}};\n        for (Tile tile : tiles) {\n            double angle = tile.angle - T;\n            Path2D path = new Path2D.Double();\n            path.moveTo(tile.x, tile.y);\n\n            int ord = tile.type.ordinal();\n            for (int i = 0; i < 3; i++) {\n                double x = tile.x + dist[ord][i] * tile.size * cos(angle);\n                double y = tile.y - dist[ord][i] * tile.size * sin(angle);\n                path.lineTo(x, y);\n                angle += T;\n            }\n            path.closePath();\n            g.setColor(ord == 0 ? Color.orange : Color.yellow);\n            g.fill(path);\n            g.setColor(Color.darkGray);\n            g.draw(path);\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics og) {\n        super.paintComponent(og);\n        Graphics2D g = (Graphics2D) og;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        drawTiles(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(\"Penrose Tiling\");\n            f.setResizable(false);\n            f.add(new PenroseTiling(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\ntype tiletype int\n\nconst (\n    kite tiletype = iota\n    dart\n)\n\ntype tile struct {\n    tt          tiletype\n    x, y        float64\n    angle, size float64\n}\n\nvar gr = (1 + math.Sqrt(5)) / 2 \n\nconst theta = math.Pi / 5 \n\nfunc setupPrototiles(w, h int) []tile {\n    var proto []tile\n    \n    for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {\n        ww := float64(w / 2)\n        hh := float64(h / 2)\n        proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})\n    }\n    return proto\n}\n\nfunc distinctTiles(tls []tile) []tile {\n    tileset := make(map[tile]bool)\n    for _, tl := range tls {\n        tileset[tl] = true\n    }\n    distinct := make([]tile, len(tileset))\n    for tl, _ := range tileset {\n        distinct = append(distinct, tl)\n    }\n    return distinct\n}\n\nfunc deflateTiles(tls []tile, gen int) []tile {\n    if gen <= 0 {\n        return tls\n    }\n    var next []tile\n    for _, tl := range tls {\n        x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr\n        var nx, ny float64\n        if tl.tt == dart {\n            next = append(next, tile{kite, x, y, a + 5*theta, size})\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                nx = x + math.Cos(a-4*theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-4*theta*sign)*gr*tl.size\n                next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})\n            }\n        } else {\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                next = append(next, tile{dart, x, y, a - 4*theta*sign, size})\n                nx = x + math.Cos(a-theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-theta*sign)*gr*tl.size\n                next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})\n            }\n        }\n    }\n    \n    tls = distinctTiles(next)\n    return deflateTiles(tls, gen-1)\n}\n\nfunc drawTiles(dc *gg.Context, tls []tile) {\n    dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}\n    for _, tl := range tls {\n        angle := tl.angle - theta\n        dc.MoveTo(tl.x, tl.y)\n        ord := tl.tt\n        for i := 0; i < 3; i++ {\n            x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)\n            y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)\n            dc.LineTo(x, y)\n            angle += theta\n        }\n        dc.ClosePath()\n        if ord == kite {\n            dc.SetHexColor(\"FFA500\") \n        } else {\n            dc.SetHexColor(\"FFFF00\") \n        }\n        dc.FillPreserve()\n        dc.SetHexColor(\"A9A9A9\") \n        dc.SetLineWidth(1)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    w, h := 700, 450\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    tiles := deflateTiles(setupPrototiles(w, h), 5)\n    drawTiles(dc, tiles)\n    dc.SavePNG(\"penrose_tiling.png\")\n}\n"}
{"id": 52313, "name": "Sphenic numbers", "Java": "import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SphenicNumbers {\n    public static void main(String[] args) {\n        final int limit = 1000000;\n        final int imax = limit / 6;\n        boolean[] sieve = primeSieve(imax + 1);\n        boolean[] sphenic = new boolean[limit + 1];\n        for (int i = 0; i <= imax; ++i) {\n            if (!sieve[i])\n                continue;\n            int jmax = Math.min(imax, limit / (i * i));\n            if (jmax <= i)\n                break;\n            for (int j = i + 1; j <= jmax; ++j) {\n                if (!sieve[j])\n                    continue;\n                int p = i * j;\n                int kmax = Math.min(imax, limit / p);\n                if (kmax <= j)\n                    break;\n                for (int k = j + 1; k <= kmax; ++k) {\n                    if (!sieve[k])\n                        continue;\n                    assert(p * k <= limit);\n                    sphenic[p * k] = true;\n                }\n            }\n        }\n    \n        System.out.println(\"Sphenic numbers < 1000:\");\n        for (int i = 0, n = 0; i < 1000; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++n;\n            System.out.printf(\"%3d%c\", i, n % 15 == 0 ? '\\n' : ' ');\n        }\n    \n        System.out.println(\"\\nSphenic triplets < 10,000:\");\n        for (int i = 0, n = 0; i < 10000; ++i) {\n            if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n                ++n;\n                System.out.printf(\"(%d, %d, %d)%c\",\n                                  i - 2, i - 1, i, n % 3 == 0 ? '\\n' : ' ');\n            }\n        }\n    \n        int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n        for (int i = 0; i < limit; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++count;\n            if (count == 200000)\n                s200000 = i;\n            if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n                ++triplets;\n                if (triplets == 5000)\n                    t5000 = i;\n            }\n        }\n    \n        System.out.printf(\"\\nNumber of sphenic numbers < 1,000,000: %d\\n\", count);\n        System.out.printf(\"Number of sphenic triplets < 1,000,000: %d\\n\", triplets);\n    \n        List<Integer> factors = primeFactors(s200000);\n        assert(factors.size() == 3);\n        System.out.printf(\"The 200,000th sphenic number: %d = %d * %d * %d\\n\",\n                          s200000, factors.get(0), factors.get(1),\n                          factors.get(2));\n        System.out.printf(\"The 5,000th sphenic triplet: (%d, %d, %d)\\n\",\n                          t5000 - 2, t5000 - 1, t5000);\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3, sq = 9; sq < limit; p += 2) {\n            if (sieve[p]) {\n                for (int q = sq; q < limit; q += p << 1)\n                    sieve[q] = false;\n            }\n            sq += (p + 1) << 2;\n        }\n        return sieve;\n    }\n    \n    private static List<Integer> primeFactors(int n) {\n        List<Integer> factors = new ArrayList<>();\n        if (n > 1 && (n & 1) == 0) {\n            factors.add(2);\n            while ((n & 1) == 0)\n                n >>= 1;\n        }\n        for (int p = 3; p * p <= n; p += 2) {\n            if (n % p == 0) {\n                factors.add(p);\n                while (n % p == 0)\n                    n /= p;\n            }\n        }\n        if (n > 1)\n            factors.add(n);\n        return factors;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = 1000000\n    limit2 := int(math.Cbrt(limit)) \n    primes := rcu.Primes(limit / 6)\n    pc := len(primes)\n    var sphenic []int\n    fmt.Println(\"Sphenic numbers less than 1,000:\")\n    for i := 0; i < pc-2; i++ {\n        if primes[i] > limit2 {\n            break\n        }\n        for j := i + 1; j < pc-1; j++ {\n            prod := primes[i] * primes[j]\n            if prod+primes[j+1] >= limit {\n                break\n            }\n            for k := j + 1; k < pc; k++ {\n                res := prod * primes[k]\n                if res >= limit {\n                    break\n                }\n                sphenic = append(sphenic, res)\n            }\n        }\n    }\n    sort.Ints(sphenic)\n    ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })\n    rcu.PrintTable(sphenic[:ix], 15, 3, false)\n    fmt.Println(\"\\nSphenic triplets less than 10,000:\")\n    var triplets [][3]int\n    for i := 0; i < len(sphenic)-2; i++ {\n        s := sphenic[i]\n        if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {\n            triplets = append(triplets, [3]int{s, s + 1, s + 2})\n        }\n    }\n    ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })\n    for i := 0; i < ix; i++ {\n        fmt.Printf(\"%4d \", triplets[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThere are %s sphenic numbers less than 1,000,000.\\n\", rcu.Commatize(len(sphenic)))\n    fmt.Printf(\"There are %s sphenic triplets less than 1,000,000.\\n\", rcu.Commatize(len(triplets)))\n    s := sphenic[199999]\n    pf := rcu.PrimeFactors(s)\n    fmt.Printf(\"The 200,000th sphenic number is %s (%d*%d*%d).\\n\", rcu.Commatize(s), pf[0], pf[1], pf[2])\n    fmt.Printf(\"The 5,000th sphenic triplet is %v.\\n.\", triplets[4999])\n}\n"}
{"id": 52314, "name": "Find duplicate files", "Java": "import java.io.*;\nimport java.nio.*;\nimport java.nio.file.*;\nimport java.nio.file.attribute.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class DuplicateFiles {\n    public static void main(String[] args) {\n        if (args.length != 2) {\n            System.err.println(\"Directory name and minimum file size are required.\");\n            System.exit(1);\n        }\n        try {\n            findDuplicateFiles(args[0], Long.parseLong(args[1]));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void findDuplicateFiles(String directory, long minimumSize)\n        throws IOException, NoSuchAlgorithmException {\n        System.out.println(\"Directory: '\" + directory + \"', minimum size: \" + minimumSize + \" bytes.\");\n        Path path = FileSystems.getDefault().getPath(directory);\n        FileVisitor visitor = new FileVisitor(path, minimumSize);\n        Files.walkFileTree(path, visitor);\n        System.out.println(\"The following sets of files have the same size and checksum:\");\n        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {\n            Map<Object, List<String>> map = e.getValue();\n            if (!containsDuplicates(map))\n                continue;\n            List<List<String>> fileSets = new ArrayList<>(map.values());\n            for (List<String> files : fileSets)\n                Collections.sort(files);\n            Collections.sort(fileSets, new StringListComparator());\n            FileKey key = e.getKey();\n            System.out.println();\n            System.out.println(\"Size: \" + key.size_ + \" bytes\");\n            for (List<String> files : fileSets) {\n                for (int i = 0, n = files.size(); i < n; ++i) {\n                    if (i > 0)\n                        System.out.print(\" = \");\n                    System.out.print(files.get(i));\n                }\n                System.out.println();\n            }\n        }\n    }\n\n    private static class StringListComparator implements Comparator<List<String>> {\n        public int compare(List<String> a, List<String> b) {\n            int len1 = a.size(), len2 = b.size();\n            for (int i = 0; i < len1 && i < len2; ++i) {\n                int c = a.get(i).compareTo(b.get(i));\n                if (c != 0)\n                    return c;\n            }\n            return Integer.compare(len1, len2);\n        }\n    }\n\n    private static boolean containsDuplicates(Map<Object, List<String>> map) {\n        if (map.size() > 1)\n            return true;\n        for (List<String> files : map.values()) {\n            if (files.size() > 1)\n                return true;\n        }\n        return false;\n    }\n\n    private static class FileVisitor extends SimpleFileVisitor<Path> {\n        private MessageDigest digest_;\n        private Path directory_;\n        private long minimumSize_;\n        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();\n\n        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {\n            directory_ = directory;\n            minimumSize_ = minimumSize;\n            digest_ = MessageDigest.getInstance(\"MD5\");\n        }\n\n        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n            if (attrs.size() >= minimumSize_) {\n                FileKey key = new FileKey(file, attrs, getMD5Sum(file));\n                Map<Object, List<String>> map = fileMap_.get(key);\n                if (map == null)\n                    fileMap_.put(key, map = new HashMap<>());\n                List<String> files = map.get(attrs.fileKey());\n                if (files == null)\n                    map.put(attrs.fileKey(), files = new ArrayList<>());\n                Path relative = directory_.relativize(file);\n                files.add(relative.toString());\n            }\n            return FileVisitResult.CONTINUE;\n        }\n\n        private byte[] getMD5Sum(Path file) throws IOException {\n            digest_.reset();\n            try (InputStream in = new FileInputStream(file.toString())) {\n                byte[] buffer = new byte[8192];\n                int bytes;\n                while ((bytes = in.read(buffer)) != -1) {\n                    digest_.update(buffer, 0, bytes);\n                }\n            }\n            return digest_.digest();\n        }\n    }\n\n    private static class FileKey implements Comparable<FileKey> {\n        private byte[] hash_;\n        private long size_;\n\n        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {\n            size_ = attrs.size();\n            hash_ = hash;\n        }\n\n        public int compareTo(FileKey other) {\n            int c = Long.compare(other.size_, size_);\n            if (c == 0)\n                c = hashCompare(hash_, other.hash_);\n            return c;\n        }\n    }\n\n    private static int hashCompare(byte[] a, byte[] b) {\n        int len1 = a.length, len2 = b.length;\n        for (int i = 0; i < len1 && i < len2; ++i) {\n            int c = Byte.compare(a[i], b[i]);\n            if (c != 0)\n                return c;\n        }\n        return Integer.compare(len1, len2);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"crypto/md5\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"path/filepath\"\n    \"sort\"\n    \"time\"\n)\n\ntype fileData struct {\n    filePath string\n    info     os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc checksum(filePath string) hash {\n    bytes, err := ioutil.ReadFile(filePath)\n    check(err)\n    return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n    var dups [][2]fileData\n    m := make(map[hash]fileData)\n    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        if !info.IsDir() && info.Size() >= minSize {\n            h := checksum(path)\n            fd, ok := m[h]\n            fd2 := fileData{path, info}\n            if !ok {\n                m[h] = fd2\n            } else {\n                dups = append(dups, [2]fileData{fd, fd2})\n            }\n        }\n        return nil\n    })\n    check(werr)\n    return dups\n}\n\nfunc main() {\n    dups := findDuplicates(\".\", 1)\n    fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n    fmt.Println(\"File name                 Size      Date last modified\")\n    fmt.Println(\"==========================================================\")\n    sort.Slice(dups, func(i, j int) bool {\n        return dups[i][0].info.Size() > dups[j][0].info.Size() \n    })\n    for _, dup := range dups {\n        for i := 0; i < 2; i++ {\n            d := dup[i]\n            fmt.Printf(\"%-20s  %8d    %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52315, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 52316, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 52317, "name": "Order disjoint list items", "Java": "import java.util.Arrays;\nimport java.util.BitSet;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class OrderDisjointItems {\n\n    public static void main(String[] args) {\n        final String[][] MNs = {{\"the cat sat on the mat\", \"mat cat\"},\n        {\"the cat sat on the mat\", \"cat mat\"},\n        {\"A B C A B C A B C\", \"C A C A\"}, {\"A B C A B D A B E\", \"E A D A\"},\n        {\"A B\", \"B\"}, {\"A B\", \"B A\"}, {\"A B B A\", \"B A\"}, {\"X X Y\", \"X\"}};\n\n        for (String[] a : MNs) {\n            String[] r = orderDisjointItems(a[0].split(\" \"), a[1].split(\" \"));\n            System.out.printf(\"%s | %s -> %s%n\", a[0], a[1], Arrays.toString(r));\n        }\n    }\n\n    \n    static String[] orderDisjointItems(String[] m, String[] n) {\n        for (String e : n) {\n            int idx = ArrayUtils.indexOf(m, e);\n            if (idx != -1)\n                m[idx] = null;\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (m[i] == null)\n                m[i] = n[j++];\n        }\n        return m;\n    }\n\n    \n    static String[] orderDisjointItems2(String[] m, String[] n) {\n        BitSet bitSet = new BitSet(m.length);\n        for (String e : n) {\n            int idx = -1;\n            do {\n                idx = ArrayUtils.indexOf(m, e, idx + 1);\n            } while (idx != -1 && bitSet.get(idx));\n            if (idx != -1)\n                bitSet.set(idx);\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (bitSet.get(i))\n                m[i] = n[j++];\n        }\n        return m;\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype indexSort struct {\n\tval sort.Interface\n\tind []int\n}\n\nfunc (s indexSort) Len() int           { return len(s.ind) }\nfunc (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }\nfunc (s indexSort) Swap(i, j int) {\n\ts.val.Swap(s.ind[i], s.ind[j])\n\ts.ind[i], s.ind[j] = s.ind[j], s.ind[i]\n}\n\nfunc disjointSliceSort(m, n []string) []string {\n\ts := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}\n\tused := make(map[int]bool)\n\tfor _, nw := range n {\n\t\tfor i, mw := range m {\n\t\t\tif used[i] || mw != nw {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tused[i] = true\n\t\t\ts.ind = append(s.ind, i)\n\t\t\tbreak\n\t\t}\n\t}\n\tsort.Sort(s)\n\treturn s.val.(sort.StringSlice)\n}\n\nfunc disjointStringSort(m, n string) string {\n\treturn strings.Join(\n\t\tdisjointSliceSort(strings.Fields(m), strings.Fields(n)), \" \")\n}\n\nfunc main() {\n\tfor _, data := range []struct{ m, n string }{\n\t\t{\"the cat sat on the mat\", \"mat cat\"},\n\t\t{\"the cat sat on the mat\", \"cat mat\"},\n\t\t{\"A B C A B C A B C\", \"C A C A\"},\n\t\t{\"A B C A B D A B E\", \"E A D A\"},\n\t\t{\"A B\", \"B\"},\n\t\t{\"A B\", \"B A\"},\n\t\t{\"A B B A\", \"B A\"},\n\t} {\n\t\tmp := disjointStringSort(data.m, data.n)\n\t\tfmt.Printf(\"%s → %s » %s\\n\", data.m, data.n, mp)\n\t}\n\n}\n"}
{"id": 52318, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 52319, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "Go": "var m = `    leading spaces\n\nand blank lines`\n"}
{"id": 52320, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 52321, "name": "Ramanujan primes", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n"}
{"id": 52322, "name": "Ramanujan primes", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n"}
{"id": 52323, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 52324, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 52325, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 52326, "name": "Most frequent k chars distance", "Java": "import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class SDF {\n\n    \n    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {\n\n        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();\n\n        for (char element : array) {\n            Integer count = countMap.get(element);\n            count = (count == null) ? 1 : count + 1;\n            countMap.put(element, count);\n        }\n\n        return countMap;\n    }\n    \n    \n    private static <K, V extends Comparable<? super V>>\n            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { \n\tList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());\n\t\n\tCollections.sort(list, new Comparator<Map.Entry<K, V>>() {\n\t\tpublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n\t\t    return o2.getValue().compareTo(o1.getValue());\n\t\t}\n\t    });\n\n\t\n\t\n\tHashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();\n\tfor (Map.Entry<K, V> entry : list) {\n\t    sortedHashMap.put(entry.getKey(), entry.getValue());\n\t} \n\treturn sortedHashMap;\n    }\n    \n    public static String mostOcurrencesElement(char[] array, int k) {\n        HashMap<Character, Integer> countMap = countElementOcurrences(array);\n        System.out.println(countMap);\n        Map<Character, Integer> map = descendingSortByValues(countMap); \n        System.out.println(map);\n        int i = 0;\n        String output = \"\";\n        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {\n\t    if (i++ >= k)\n\t\tbreak;\n            output += \"\" + pairs.getKey() + pairs.getValue();\n        }\n        return output;\n    }\n    \n    public static int getDiff(String str1, String str2, int limit) {\n        int similarity = 0;\n\tint k = 0;\n\tfor (int i = 0; i < str1.length() ; i = k) {\n\t    k ++;\n\t    if (Character.isLetter(str1.charAt(i))) {\n\t\tint pos = str2.indexOf(str1.charAt(i));\n\t\t\t\t\n\t\tif (pos >= 0) {\t\n\t\t    String digitStr1 = \"\";\n\t\t    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {\n\t\t\tdigitStr1 += str1.charAt(k);\n\t\t\tk++;\n\t\t    }\n\t\t\t\t\t\n\t\t    int k2 = pos+1;\n\t\t    String digitStr2 = \"\";\n\t\t    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {\n\t\t\tdigitStr2 += str2.charAt(k2);\n\t\t\tk2++;\n\t\t    }\n\t\t\t\t\t\n\t\t    similarity += Integer.parseInt(digitStr2)\n\t\t\t+ Integer.parseInt(digitStr1);\n\t\t\t\t\t\n\t\t} \n\t    }\n\t}\n\treturn Math.abs(limit - similarity);\n    }\n    \n    public static int SDFfunc(String str1, String str2, int limit) {\n        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);\n    }\n\n    public static void main(String[] args) {\n        String input1 = \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\";\n        String input2 = \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\";\n        System.out.println(SDF.SDFfunc(input1,input2,100));\n\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n"}
{"id": 52327, "name": "Text completion", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\n\n\npublic class textCompletionConcept {\n    public static int correct = 0;\n    public static ArrayList<String> listed = new ArrayList<>();\n    public static void main(String[]args) throws IOException, URISyntaxException {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Input word: \");\n        String errorRode = input.next();\n        File file = new File(new \n        File(textCompletionConcept.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath() + File.separator + \"words.txt\");\n        Scanner reader = new Scanner(file);\n        while(reader.hasNext()){\n            double percent;\n            String compareToThis = reader.nextLine();\n                    char[] s1 = errorRode.toCharArray();\n                    char[] s2 = compareToThis.toCharArray();\n                    int maxlen = Math.min(s1.length, s2.length);\n                    for (int index = 0; index < maxlen; index++) {\n                        String x = String.valueOf(s1[index]);\n                        String y = String.valueOf(s2[index]);\n                        if (x.equals(y)) {\n                            correct++;\n                        }\n                    }\n                    double length = Math.max(s1.length, s2.length);\n                    percent = correct / length;\n                    percent *= 100;\n                    boolean perfect = false;\n                    if (percent >= 80 && compareToThis.charAt(0) == errorRode.charAt(0)) {\n                        if(String.valueOf(percent).equals(\"100.00\")){\n                            perfect = true;\n                        }\n                        String addtoit = compareToThis + \" : \" + String.format(\"%.2f\", percent) + \"% similar.\";\n                        listed.add(addtoit);\n                    }\n                    if(compareToThis.contains(errorRode) && !perfect && errorRode.length() * 2 > compareToThis.length()){\n                        String addtoit = compareToThis + \" : 80.00% similar.\";\n                        listed.add(addtoit);\n                    }\n            correct = 0;\n        }\n\n        for(String x : listed){\n            if(x.contains(\"100.00% similar.\")){\n                System.out.println(x);\n                listed.clear();\n                break;\n            }\n        }\n\n        for(String x : listed){\n            System.out.println(x);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n)\n\nfunc levenshtein(s, t string) int {\n    d := make([][]int, len(s)+1)\n    for i := range d {\n        d[i] = make([]int, len(t)+1)\n    }\n    for i := range d {\n        d[i][0] = i\n    }\n    for j := range d[0] {\n        d[0][j] = j\n    }\n    for j := 1; j <= len(t); j++ {\n        for i := 1; i <= len(s); i++ {\n            if s[i-1] == t[j-1] {\n                d[i][j] = d[i-1][j-1]\n            } else {\n                min := d[i-1][j]\n                if d[i][j-1] < min {\n                    min = d[i][j-1]\n                }\n                if d[i-1][j-1] < min {\n                    min = d[i-1][j-1]\n                }\n                d[i][j] = min + 1\n            }\n        }\n\n    }\n    return d[len(s)][len(t)]\n}\n\nfunc main() {\n    search := \"complition\"\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Fields(b)\n    var lev [4][]string\n    for _, word := range words {\n        s := string(word)\n        ld := levenshtein(search, s)\n        if ld < 4 {\n            lev[ld] = append(lev[ld], s)\n        }\n    }\n    fmt.Printf(\"Input word: %s\\n\\n\", search)\n    for i := 1; i < 4; i++ {\n        length := float64(len(search))\n        similarity := (length - float64(i)) * 100 / length\n        fmt.Printf(\"Words which are %4.1f%% similar:\\n\", similarity)\n        fmt.Println(lev[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 52328, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 52329, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 52330, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 52331, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 52332, "name": "Lychrel numbers", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 52333, "name": "Lychrel numbers", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 52334, "name": "Erdös-Selfridge categorization of primes", "Java": "import java.util.*;\n\npublic class ErdosSelfridge {\n    private int[] primes;\n    private int[] category;\n\n    public static void main(String[] args) {\n        ErdosSelfridge es = new ErdosSelfridge(1000000);\n\n        System.out.println(\"First 200 primes:\");\n        for (var e : es.getPrimesByCategory(200).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %d:\\n\", category);\n            for (int i = 0, n = primes.size(); i != n; ++i)\n                System.out.printf(\"%4d%c\", primes.get(i), (i + 1) % 15 == 0 ? '\\n' : ' ');\n            System.out.printf(\"\\n\\n\");\n        }\n\n        System.out.println(\"First 1,000,000 primes:\");\n        for (var e : es.getPrimesByCategory(1000000).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %2d: first = %7d  last = %8d  count = %d\\n\", category,\n                              primes.get(0), primes.get(primes.size() - 1), primes.size());\n        }\n    }\n\n    private ErdosSelfridge(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);\n        List<Integer> primeList = new ArrayList<>();\n        for (int i = 0; i < limit; ++i)\n            primeList.add(primeGen.nextPrime());\n        primes = new int[primeList.size()];\n        for (int i = 0; i < primes.length; ++i)\n            primes[i] = primeList.get(i);\n        category = new int[primes.length];\n    }\n\n    private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {\n        Map<Integer, List<Integer>> result = new TreeMap<>();\n        for (int i = 0; i < limit; ++i) {\n            var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());\n            p.add(primes[i]);\n        }\n        return result;\n    }\n\n    private int getCategory(int index) {\n        if (category[index] != 0)\n            return category[index];\n        int maxCategory = 0;\n        int n = primes[index] + 1;\n        for (int i = 0; n > 1; ++i) {\n            int p = primes[i];\n            if (p * p > n)\n                break;\n            int count = 0;\n            for (; n % p == 0; ++count)\n                n /= p;\n            if (count != 0) {\n                int category = (p <= 3) ? 1 : 1 + getCategory(i);\n                maxCategory = Math.max(maxCategory, category);\n            }\n        }\n        if (n > 1) {\n            int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));\n            maxCategory = Math.max(maxCategory, category);\n        }\n        category[index] = maxCategory;\n        return maxCategory;\n    }\n\n    private int getIndex(int prime) {\n       return Arrays.binarySearch(primes, prime);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nvar limit = int(math.Log(1e6) * 1e6 * 1.2) \nvar primes = rcu.Primes(limit)\n\nvar prevCats = make(map[int]int)\n\nfunc cat(p int) int {\n    if v, ok := prevCats[p]; ok {\n        return v\n    }\n    pf := rcu.PrimeFactors(p + 1)\n    all := true\n    for _, f := range pf {\n        if f != 2 && f != 3 {\n            all = false\n            break\n        }\n    }\n    if all {\n        return 1\n    }\n    if p > 2 {\n        len := len(pf)\n        for i := len - 1; i >= 1; i-- {\n            if pf[i-1] == pf[i] {\n                pf = append(pf[:i], pf[i+1:]...)\n            }\n        }\n    }\n    for c := 2; c <= 11; c++ {\n        all := true\n        for _, f := range pf {\n            if cat(f) >= c {\n                all = false\n                break\n            }\n        }\n        if all {\n            prevCats[p] = c\n            return c\n        }\n    }\n    return 12\n}\n\nfunc main() {\n    es := make([][]int, 12)\n    fmt.Println(\"First 200 primes:\\n\")\n    for _, p := range primes[0:200] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 6; c++ {\n        if len(es[c-1]) > 0 {\n            fmt.Println(\"Category\", c, \"\\b:\")\n            fmt.Println(es[c-1])\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"First million primes:\\n\")\n    for _, p := range primes[200:1e6] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 12; c++ {\n        e := es[c-1]\n        if len(e) > 0 {\n            format := \"Category %-2d: First = %7d  Last = %8d  Count = %6d\\n\"\n            fmt.Printf(format, c, e[0], e[len(e)-1], len(e))\n        }\n    }\n}\n"}
{"id": 52335, "name": "Sierpinski square curve", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n"}
{"id": 52336, "name": "Sierpinski square curve", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n"}
{"id": 52337, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n"}
{"id": 52338, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n"}
{"id": 52339, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 52340, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 52341, "name": "Odd words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class OddWords {\n    public static void main(String[] args) {\n        try {\n            Set<String> dictionary = new TreeSet<>();\n            final int minLength = 5;\n            String fileName = \"unixdict.txt\";\n            if (args.length != 0)\n                fileName = args[0];\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        dictionary.add(line);\n                }\n            }\n            StringBuilder word1 = new StringBuilder();\n            StringBuilder word2 = new StringBuilder();\n            List<StringPair> evenWords = new ArrayList<>();\n            List<StringPair> oddWords = new ArrayList<>();\n            for (String word : dictionary) {\n                int length = word.length();\n                if (length < minLength + 2 * (minLength/2))\n                    continue;\n                word1.setLength(0);\n                word2.setLength(0);\n                for (int i = 0; i < length; ++i) {\n                    if ((i & 1) == 0)\n                        word1.append(word.charAt(i));\n                    else\n                        word2.append(word.charAt(i));\n                }\n                String oddWord = word1.toString();\n                String evenWord = word2.toString();\n                if (dictionary.contains(oddWord))\n                    oddWords.add(new StringPair(word, oddWord));\n                if (dictionary.contains(evenWord))\n                    evenWords.add(new StringPair(word, evenWord));\n            }\n            System.out.println(\"Odd words:\");\n            printWords(oddWords);\n            System.out.println(\"\\nEven words:\");\n            printWords(evenWords);\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n\n    private static void printWords(List<StringPair> strings) {\n        int n = 1;\n        for (StringPair pair : strings) {\n            System.out.printf(\"%2d: %-14s%s\\n\", n++,\n                                    pair.string1, pair.string2);\n        }\n    }\n\n    private static class StringPair {\n        private String string1;\n        private String string2;\n        private StringPair(String s1, String s2) {\n            string1 = s1;\n            string2 = s2;\n        }\n    }\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    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n"}
{"id": 52342, "name": "Ramanujan's constant", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 52343, "name": "Ramanujan's constant", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 52344, "name": "Word break problem", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n"}
{"id": 52345, "name": "Brilliant numbers", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n"}
{"id": 52346, "name": "Brilliant numbers", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n"}
{"id": 52347, "name": "Word ladder", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n"}
{"id": 52348, "name": "Word ladder", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n"}
{"id": 52349, "name": "Earliest difference between prime gaps", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n"}
{"id": 52350, "name": "Earliest difference between prime gaps", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n"}
{"id": 52351, "name": "Latin Squares in reduced form", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n"}
{"id": 52352, "name": "UPC", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 52353, "name": "UPC", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 52354, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 52355, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 52356, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 52357, "name": "Closest-pair problem", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n"}
{"id": 52358, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 52359, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 52360, "name": "Wilson primes of order n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class WilsonPrimes {\n    public static void main(String[] args) {\n        final int limit = 11000;\n        BigInteger[] f = new BigInteger[limit];\n        f[0] = BigInteger.ONE;\n        BigInteger factorial = BigInteger.ONE;\n        for (int i = 1; i < limit; ++i) {\n            factorial = factorial.multiply(BigInteger.valueOf(i));\n            f[i] = factorial;\n        }\n        List<Integer> primes = generatePrimes(limit);\n        System.out.printf(\" n | Wilson primes\\n--------------------\\n\");\n        BigInteger s = BigInteger.valueOf(-1);\n        for (int n = 1; n <= 11; ++n) {\n            System.out.printf(\"%2d |\", n);\n            for (int p : primes) {\n                if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)\n                        .mod(BigInteger.valueOf(p * p))\n                        .equals(BigInteger.ZERO))\n                    System.out.printf(\" %d\", p);\n            }\n            s = s.negate();\n            System.out.println();\n        }\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    \"math/big\"\n    \"rcu\"\n)\n\nfunc main() {\n    const LIMIT = 11000\n    primes := rcu.Primes(LIMIT)\n    facts := make([]*big.Int, LIMIT)\n    facts[0] = big.NewInt(1)\n    for i := int64(1); i < LIMIT; i++ {\n        facts[i] = new(big.Int)\n        facts[i].Mul(facts[i-1], big.NewInt(i))\n    }\n    sign := int64(1)\n    f := new(big.Int)\n    zero := new(big.Int)\n    fmt.Println(\" n:  Wilson primes\")\n    fmt.Println(\"--------------------\")\n    for n := 1; n < 12; n++ {\n        fmt.Printf(\"%2d:  \", n)\n        sign = -sign\n        for _, p := range primes {\n            if p < n {\n                continue\n            }\n            f.Mul(facts[n-1], facts[p-n])\n            f.Sub(f, big.NewInt(sign))\n            p2 := int64(p * p)\n            bp2 := big.NewInt(p2)\n            if f.Rem(f, bp2).Cmp(zero) == 0 {\n                fmt.Printf(\"%d \", p)\n            }\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52361, "name": "Color wheel", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n"}
{"id": 52362, "name": "Plasma effect", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n"}
{"id": 52363, "name": "Rhonda numbers", "Java": "public class RhondaNumbers {\n    public static void main(String[] args) {\n        final int limit = 15;\n        for (int base = 2; base <= 36; ++base) {\n            if (isPrime(base))\n                continue;\n            System.out.printf(\"First %d Rhonda numbers to base %d:\\n\", limit, base);\n            int numbers[] = new int[limit];\n            for (int n = 1, count = 0; count < limit; ++n) {\n                if (isRhonda(base, n))\n                    numbers[count++] = n;\n            }\n            System.out.printf(\"In base 10:\");\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %d\", numbers[i]);\n            System.out.printf(\"\\nIn base %d:\", base);\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %s\", Integer.toString(numbers[i], base));\n            System.out.printf(\"\\n\\n\");\n        }\n    }\n    \n    private static int digitProduct(int base, int n) {\n        int product = 1;\n        for (; n != 0; n /= base)\n            product *= n % base;\n        return product;\n    }\n     \n    private static int primeFactorSum(int n) {\n        int sum = 0;\n        for (; (n & 1) == 0; n >>= 1)\n            sum += 2;\n        for (int p = 3; p * p <= n; p += 2)\n            for (; n % p == 0; n /= p)\n                sum += p;\n        if (n > 1)\n            sum += n;\n        return sum;\n    }\n     \n    private static boolean isPrime(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 (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     \n    private static boolean isRhonda(int base, int n) {\n        return digitProduct(base, n) == base * primeFactorSum(n);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc contains(a []int, n int) bool {\n    for _, e := range a {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    for b := 2; b <= 36; b++ {\n        if rcu.IsPrime(b) {\n            continue\n        }\n        count := 0\n        var rhonda []int\n        for n := 1; count < 15; n++ {\n            digits := rcu.Digits(n, b)\n            if !contains(digits, 0) {\n                var anyEven = false\n                for _, d := range digits {\n                    if d%2 == 0 {\n                        anyEven = true\n                        break\n                    }\n                }\n                if b != 10 || (contains(digits, 5) && anyEven) {\n                    calc1 := 1\n                    for _, d := range digits {\n                        calc1 *= d\n                    }\n                    calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))\n                    if calc1 == calc2 {\n                        rhonda = append(rhonda, n)\n                        count++\n                    }\n                }\n            }\n        }\n        if len(rhonda) > 0 {\n            fmt.Printf(\"\\nFirst 15 Rhonda numbers in base %d:\\n\", b)\n            rhonda2 := make([]string, len(rhonda))\n            counts2 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda2[i] = fmt.Sprintf(\"%d\", r)\n                counts2[i] = len(rhonda2[i])\n            }\n            rhonda3 := make([]string, len(rhonda))\n            counts3 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda3[i] = strconv.FormatInt(int64(r), b)\n                counts3[i] = len(rhonda3[i])\n            }\n            maxLen2 := rcu.MaxInts(counts2)\n            maxLen3 := rcu.MaxInts(counts3)\n            maxLen := maxLen2\n            if maxLen3 > maxLen {\n                maxLen = maxLen3\n            }\n            maxLen++\n            fmt.Printf(\"In base 10: %*s\\n\", maxLen, rhonda2)\n            fmt.Printf(\"In base %-2d: %*s\\n\", b, maxLen, rhonda3)\n        }\n    }\n}\n"}
{"id": 52364, "name": "Polymorphism", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 52365, "name": "Create an object_Native demonstration", "Java": "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\npublic class ImmutableMap {\n\n    public static void main(String[] args) {\n        Map<String,Integer> hashMap = getImmutableMap();\n        try {\n            hashMap.put(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put new value.\");\n        }\n        try {\n            hashMap.clear();\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to clear map.\");\n        }\n        try {\n            hashMap.putIfAbsent(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put if absent.\");\n        }\n        \n        for ( String key : hashMap.keySet() ) {\n            System.out.printf(\"key = %s, value = %s%n\", key, hashMap.get(key));\n        }\n    }\n    \n    private static Map<String,Integer> getImmutableMap() {\n        Map<String,Integer> hashMap = new HashMap<>();\n        hashMap.put(\"Key 1\", 34);\n        hashMap.put(\"Key 2\", 105);\n        hashMap.put(\"Key 3\", 144);\n\n        return Collections.unmodifiableMap(hashMap);\n    }\n    \n}\n", "Go": "package romap\n\ntype Romap struct{ imap map[byte]int }\n\n\nfunc New(m map[byte]int) *Romap {\n    if m == nil {\n        return nil\n    }\n    return &Romap{m}\n}\n\n\nfunc (rom *Romap) Get(key byte) (int, bool) {\n    i, ok := rom.imap[key]\n    return i, ok\n}\n\n\nfunc (rom *Romap) Reset(key byte) {\n    _, ok := rom.imap[key]\n    if ok {\n        rom.imap[key] = 0 \n    }\n}\n"}
{"id": 52366, "name": "Execute CopyPasta Language", "Java": "import java.io.File;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class Copypasta\n{\n\t\n\tpublic static void fatal_error(String errtext)\n\t{\n\t\tStackTraceElement[] stack = Thread.currentThread().getStackTrace();\n\t\tStackTraceElement main = stack[stack.length - 1];\n\t\tString mainClass = main.getClassName();\n\t\tSystem.out.println(\"%\" + errtext);\n\t\tSystem.out.println(\"usage: \" + mainClass + \" [filename.cp]\");\n\t\tSystem.exit(1);\n\t}\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tString fname = null;\n\t\tString source = null;\n\t\ttry\n\t\t{\n\t\t\tfname = args[0];\n\t\t\tsource = new String(Files.readAllBytes(new File(fname).toPath()));\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tfatal_error(\"error while trying to read from specified file\");\n\t\t}\n\n\t\t\n\t\tArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split(\"\\n\")));\n\t\t\n\t\t\n\t\tString clipboard = \"\";\n\t\t\n\t\t\n\t\tint loc = 0;\n\t\twhile(loc < lines.size())\n\t\t{\n\t\t\t\n\t\t\tString command = lines.get(loc).trim();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(command.equals(\"Copy\"))\n\t\t\t\t\tclipboard += lines.get(loc + 1);\n\t\t\t\telse if(command.equals(\"CopyFile\"))\n\t\t\t\t{\n\t\t\t\t\tif(lines.get(loc + 1).equals(\"TheF*ckingCode\"))\n\t\t\t\t\t\tclipboard += source;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tString filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));\n\t\t\t\t\t\tclipboard += filetext;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Duplicate\"))\n\t\t\t\t{\n\t\t\t\t\tString origClipboard = clipboard;\n\n\t\t\t\t\tint amount = Integer.parseInt(lines.get(loc + 1)) - 1;\n\t\t\t\t\tfor(int i = 0; i < amount; i++)\n\t\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Pasta!\"))\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(clipboard);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\n\t\t\t\n\t\t\tloc += 2;\n\t\t}\n\t}\n}\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n"}
{"id": 52367, "name": "Square root by hand", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 52368, "name": "Square root by hand", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 52369, "name": "Reflection_List properties", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 52370, "name": "Minimal steps down to 1", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MinimalStepsDownToOne {\n\n    public static void main(String[] args) {\n        runTasks(getFunctions1());\n        runTasks(getFunctions2());\n        runTasks(getFunctions3());\n    }\n    \n    private static void runTasks(List<Function> functions) {\n        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);\n\n        \n        int max = 10;\n        populateMap(minPath, functions, max);\n        System.out.printf(\"%nWith functions:  %s%n\", functions);\n        System.out.printf(\"  Minimum steps to 1:%n\");\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int steps = minPath.get(n).size();\n            System.out.printf(\"    %2d: %d step%1s: %s%n\", n, steps, steps == 1 ? \"\" : \"s\", minPath.get(n));\n        }\n        \n        \n        displayMaxMin(minPath, functions, 2000);\n\n        \n        displayMaxMin(minPath, functions, 20000);\n\n        \n        displayMaxMin(minPath, functions, 100000);\n    }\n    \n    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        populateMap(minPath, functions, max);\n        List<Integer> maxIntegers = getMaxMin(minPath, max);\n        int maxSteps = maxIntegers.remove(0);\n        int numCount = maxIntegers.size();\n        System.out.printf(\"  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n\", numCount == 1 ? \"is\" : \"are\", numCount, numCount == 1 ? \"\" : \"s\", max, maxSteps, maxIntegers);\n        \n    }\n    \n    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {\n        int maxSteps = Integer.MIN_VALUE;\n        List<Integer> maxIntegers = new ArrayList<Integer>();\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int len = minPath.get(n).size();\n            if ( len > maxSteps ) {\n                maxSteps = len;\n                maxIntegers.clear();\n                maxIntegers.add(n);\n            }\n            else if ( len == maxSteps ) {\n                maxIntegers.add(n);\n            }\n        }\n        maxIntegers.add(0, maxSteps);\n        return maxIntegers;\n    }\n\n    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        for ( int n = 2 ; n <= max ; n++ ) {\n            if ( minPath.containsKey(n) ) {\n                continue;\n            }\n            Function minFunction = null;\n            int minSteps = Integer.MAX_VALUE;\n            for ( Function f : functions ) {\n                if ( f.actionOk(n) ) {\n                    int result = f.action(n);\n                    int steps = 1 + minPath.get(result).size();\n                    if ( steps < minSteps ) {\n                        minFunction = f;\n                        minSteps = steps;\n                    }\n                }\n            }\n            int result = minFunction.action(n);\n            List<String> path = new ArrayList<String>();\n            path.add(minFunction.toString(n));\n            path.addAll(minPath.get(result));\n            minPath.put(n, path);\n        }\n        \n    }\n\n    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {\n        Map<Integer,List<String>> minPath = new HashMap<>();\n        for ( int i = 2 ; i <= max ; i++ ) {\n            for ( Function f : functions ) {\n                if ( f.actionOk(i) ) {\n                    int result = f.action(i);\n                    if ( result == 1 ) {\n                        List<String> path = new ArrayList<String>();\n                        path.add(f.toString(i));\n                        minPath.put(i, path);\n                    }\n                }\n            }\n        }\n        return minPath;\n    }\n\n    private static List<Function> getFunctions3() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide2Function());\n        functions.add(new Divide3Function());\n        functions.add(new Subtract2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions2() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract2Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions1() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n    \n    public abstract static class Function {\n        abstract public int action(int n);\n        abstract public boolean actionOk(int n);\n        abstract public String toString(int n);\n    }\n    \n    public static class Divide2Function extends Function {\n        @Override public int action(int n) {\n            return n/2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 2 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/2 -> \" + n/2;\n        }\n        \n        @Override public String toString() {\n            return \"Divisor 2\";\n        }\n        \n    }\n\n    public static class Divide3Function extends Function {\n        @Override public int action(int n) {\n            return n/3;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 3 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/3 -> \" + n/3;\n        }\n\n        @Override public String toString() {\n            return \"Divisor 3\";\n        }\n\n    }\n\n    public static class Subtract1Function extends Function {\n        @Override public int action(int n) {\n            return n-1;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return true;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-1 -> \" + (n-1);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 1\";\n        }\n\n    }\n\n    public static class Subtract2Function extends Function {\n        @Override public int action(int n) {\n            return n-2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n > 2;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-2 -> \" + (n-2);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 2\";\n        }\n\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n    divs, subs []int\n    mins       [][]string\n)\n\n\nfunc minsteps(n int) {\n    if n == 1 {\n        mins[1] = []string{}\n        return\n    }\n    min := limit\n    var p, q int\n    var op byte\n    for _, div := range divs {\n        if n%div == 0 {\n            d := n / div\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, div, '/'\n            }\n        }\n    }\n    for _, sub := range subs {\n        if d := n - sub; d >= 1 {\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, sub, '-'\n            }\n        }\n    }\n    mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n    mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n    for r := 0; r < 2; r++ {\n        divs = []int{2, 3}\n        if r == 0 {\n            subs = []int{1}\n        } else {\n            subs = []int{2}\n        }\n        mins = make([][]string, limit+1)\n        fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n        fmt.Println(\"  Minimum number of steps to diminish the following numbers down to 1 is:\")\n        for i := 1; i <= limit; i++ {\n            minsteps(i)\n            if i <= 10 {\n                steps := len(mins[i])\n                plural := \"s\"\n                if steps == 1 {\n                    plural = \" \"\n                }\n                fmt.Printf(\"    %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n            }\n        }\n        for _, lim := range []int{2000, 20000, 50000} {\n            max := 0\n            for _, min := range mins[0 : lim+1] {\n                m := len(min)\n                if m > max {\n                    max = m\n                }\n            }\n            var maxs []int\n            for i, min := range mins[0 : lim+1] {\n                if len(min) == max {\n                    maxs = append(maxs, i)\n                }\n            }\n            nums := len(maxs)\n            verb, verb2, plural := \"are\", \"have\", \"s\"\n            if nums == 1 {\n                verb, verb2, plural = \"is\", \"has\", \"\"\n            }\n            fmt.Printf(\"  There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n            fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n            fmt.Println(\"   \", maxs)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52371, "name": "Align columns", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n"}
{"id": 52372, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 52373, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 52374, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 52375, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 52376, "name": "Dynamic variable names", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n"}
{"id": 52377, "name": "Dynamic variable names", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n"}
{"id": 52378, "name": "Data Encryption Standard", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n"}
{"id": 52379, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 52380, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 52381, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 52382, "name": "Commatizing numbers", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n"}
{"id": 52383, "name": "Arithmetic coding_As a generalized change of radix", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n"}
{"id": 52384, "name": "Kosaraju", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n"}
{"id": 52385, "name": "Reflection_List methods", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 52386, "name": "Send an unknown method call", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n"}
{"id": 52387, "name": "Particle swarm optimization", "Java": "import java.util.Arrays;\nimport java.util.Objects;\nimport java.util.Random;\nimport java.util.function.Function;\n\npublic class App {\n    static class Parameters {\n        double omega;\n        double phip;\n        double phig;\n\n        Parameters(double omega, double phip, double phig) {\n            this.omega = omega;\n            this.phip = phip;\n            this.phig = phig;\n        }\n    }\n\n    static class State {\n        int iter;\n        double[] gbpos;\n        double gbval;\n        double[] min;\n        double[] max;\n        Parameters parameters;\n        double[][] pos;\n        double[][] vel;\n        double[][] bpos;\n        double[] bval;\n        int nParticles;\n        int nDims;\n\n        State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) {\n            this.iter = iter;\n            this.gbpos = gbpos;\n            this.gbval = gbval;\n            this.min = min;\n            this.max = max;\n            this.parameters = parameters;\n            this.pos = pos;\n            this.vel = vel;\n            this.bpos = bpos;\n            this.bval = bval;\n            this.nParticles = nParticles;\n            this.nDims = nDims;\n        }\n\n        void report(String testfunc) {\n            System.out.printf(\"Test Function        : %s\\n\", testfunc);\n            System.out.printf(\"Iterations           : %d\\n\", iter);\n            System.out.printf(\"Global Best Position : %s\\n\", Arrays.toString(gbpos));\n            System.out.printf(\"Global Best value    : %.15f\\n\", gbval);\n        }\n    }\n\n    private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) {\n        int nDims = min.length;\n        double[][] pos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            pos[i] = min.clone();\n        }\n        double[][] vel = new double[nParticles][nDims];\n        double[][] bpos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            bpos[i] = min.clone();\n        }\n        double[] bval = new double[nParticles];\n        for (int i = 0; i < bval.length; ++i) {\n            bval[i] = Double.POSITIVE_INFINITY;\n        }\n        int iter = 0;\n        double[] gbpos = new double[nDims];\n        for (int i = 0; i < gbpos.length; ++i) {\n            gbpos[i] = Double.POSITIVE_INFINITY;\n        }\n        double gbval = Double.POSITIVE_INFINITY;\n        return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n    }\n\n    private static Random r = new Random();\n\n    private static State pso(Function<double[], Double> fn, State y) {\n        Parameters p = y.parameters;\n        double[] v = new double[y.nParticles];\n        double[][] bpos = new double[y.nParticles][];\n        for (int i = 0; i < y.nParticles; ++i) {\n            bpos[i] = y.min.clone();\n        }\n        double[] bval = new double[y.nParticles];\n        double[] gbpos = new double[y.nDims];\n        double gbval = Double.POSITIVE_INFINITY;\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            v[j] = fn.apply(y.pos[j]);\n            \n            if (v[j] < y.bval[j]) {\n                bpos[j] = y.pos[j];\n                bval[j] = v[j];\n            } else {\n                bpos[j] = y.bpos[j];\n                bval[j] = y.bval[j];\n            }\n            if (bval[j] < gbval) {\n                gbval = bval[j];\n                gbpos = bpos[j];\n            }\n        }\n        double rg = r.nextDouble();\n        double[][] pos = new double[y.nParticles][y.nDims];\n        double[][] vel = new double[y.nParticles][y.nDims];\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            double rp = r.nextDouble();\n            boolean ok = true;\n            Arrays.fill(vel[j], 0.0);\n            Arrays.fill(pos[j], 0.0);\n            for (int k = 0; k < y.nDims; ++k) {\n                vel[j][k] = p.omega * y.vel[j][k] +\n                    p.phip * rp * (bpos[j][k] - y.pos[j][k]) +\n                    p.phig * rg * (gbpos[k] - y.pos[j][k]);\n                pos[j][k] = y.pos[j][k] + vel[j][k];\n                ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];\n            }\n            if (!ok) {\n                for (int k = 0; k < y.nDims; ++k) {\n                    pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble();\n                }\n            }\n        }\n        int iter = 1 + y.iter;\n        return new State(\n            iter, gbpos, gbval, y.min, y.max, y.parameters,\n            pos, vel, bpos, bval, y.nParticles, y.nDims\n        );\n    }\n\n    private static State iterate(Function<double[], Double> fn, int n, State y) {\n        State r = y;\n        if (n == Integer.MAX_VALUE) {\n            State old = y;\n            while (true) {\n                r = pso(fn, r);\n                if (Objects.equals(r, old)) break;\n                old = r;\n            }\n        } else {\n            for (int i = 0; i < n; ++i) {\n                r = pso(fn, r);\n            }\n        }\n        return r;\n    }\n\n    private static double mccormick(double[] x) {\n        double a = x[0];\n        double b = x[1];\n        return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;\n    }\n\n    private static double michalewicz(double[] x) {\n        int m = 10;\n        int d = x.length;\n        double sum = 0.0;\n        for (int i = 1; i < d; ++i) {\n            double j = x[i - 1];\n            double k = Math.sin(i * j * j / Math.PI);\n            sum += Math.sin(j) * Math.pow(k, 2.0 * m);\n        }\n        return -sum;\n    }\n\n    public static void main(String[] args) {\n        State state = psoInit(\n            new double[]{-1.5, -3.0},\n            new double[]{4.0, 4.0},\n            new Parameters(0.0, 0.6, 0.3),\n            100\n        );\n        state = iterate(App::mccormick, 40, state);\n        state.report(\"McCormick\");\n        System.out.printf(\"f(-.54719, -1.54719) : %.15f\\n\", mccormick(new double[]{-.54719, -1.54719}));\n        System.out.println();\n\n        state = psoInit(\n            new double[]{0.0, 0.0},\n            new double[]{Math.PI, Math.PI},\n            new Parameters(0.3, 3.0, 0.3),\n            1000\n        );\n        state = iterate(App::michalewicz, 30, state);\n        state.report(\"Michalewicz (2D)\");\n        System.out.printf(\"f(2.20, 1.57)        : %.15f\\n\", michalewicz(new double[]{2.20, 1.57}));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype ff = func([]float64) float64\n\ntype parameters struct{ omega, phip, phig float64 }\n\ntype state struct {\n    iter       int\n    gbpos      []float64\n    gbval      float64\n    min        []float64\n    max        []float64\n    params     parameters\n    pos        [][]float64\n    vel        [][]float64\n    bpos       [][]float64\n    bval       []float64\n    nParticles int\n    nDims      int\n}\n\nfunc (s state) report(testfunc string) {\n    fmt.Println(\"Test Function        :\", testfunc)\n    fmt.Println(\"Iterations           :\", s.iter)\n    fmt.Println(\"Global Best Position :\", s.gbpos)\n    fmt.Println(\"Global Best Value    :\", s.gbval)\n}\n\nfunc psoInit(min, max []float64, params parameters, nParticles int) *state {\n    nDims := len(min)\n    pos := make([][]float64, nParticles)\n    vel := make([][]float64, nParticles)\n    bpos := make([][]float64, nParticles)\n    bval := make([]float64, nParticles)\n    for i := 0; i < nParticles; i++ {\n        pos[i] = min\n        vel[i] = make([]float64, nDims)\n        bpos[i] = min\n        bval[i] = math.Inf(1)\n    }\n    iter := 0\n    gbpos := make([]float64, nDims)\n    for i := 0; i < nDims; i++ {\n        gbpos[i] = math.Inf(1)\n    }\n    gbval := math.Inf(1)\n    return &state{iter, gbpos, gbval, min, max, params,\n        pos, vel, bpos, bval, nParticles, nDims}\n}\n\nfunc pso(fn ff, y *state) *state {\n    p := y.params\n    v := make([]float64, y.nParticles)\n    bpos := make([][]float64, y.nParticles)\n    bval := make([]float64, y.nParticles)\n    gbpos := make([]float64, y.nDims)\n    gbval := math.Inf(1)\n    for j := 0; j < y.nParticles; j++ {\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j] {\n            bpos[j] = y.pos[j]\n            bval[j] = v[j]\n        } else {\n            bpos[j] = y.bpos[j]\n            bval[j] = y.bval[j]\n        }\n        if bval[j] < gbval {\n            gbval = bval[j]\n            gbpos = bpos[j]\n        }\n    }\n    rg := rand.Float64()\n    pos := make([][]float64, y.nParticles)\n    vel := make([][]float64, y.nParticles)\n    for j := 0; j < y.nParticles; j++ {\n        pos[j] = make([]float64, y.nDims)\n        vel[j] = make([]float64, y.nDims)\n        \n        rp := rand.Float64()\n        ok := true\n        for z := 0; z < y.nDims; z++ {\n            pos[j][z] = 0\n            vel[j][z] = 0\n        }\n        for k := 0; k < y.nDims; k++ {\n            vel[j][k] = p.omega*y.vel[j][k] +\n                p.phip*rp*(bpos[j][k]-y.pos[j][k]) +\n                p.phig*rg*(gbpos[k]-y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]\n        }\n        if !ok {\n            for k := 0; k < y.nDims; k++ {\n                pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64()\n            }\n        }\n    }\n    iter := 1 + y.iter\n    return &state{iter, gbpos, gbval, y.min, y.max, y.params,\n        pos, vel, bpos, bval, y.nParticles, y.nDims}\n}\n\nfunc iterate(fn ff, n int, y *state) *state {\n    r := y\n    for i := 0; i < n; i++ {\n        r = pso(fn, r)\n    }\n    return r\n}\n\nfunc mccormick(x []float64) float64 {\n    a, b := x[0], x[1]\n    return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a\n}\n\nfunc michalewicz(x []float64) float64 {\n    m := 10.0\n    sum := 0.0\n    for i := 1; i <= len(x); i++ {\n        j := x[i-1]\n        k := math.Sin(float64(i) * j * j / math.Pi)\n        sum += math.Sin(j) * math.Pow(k, 2*m)\n    }\n    return -sum\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    st := psoInit(\n        []float64{-1.5, -3.0},\n        []float64{4.0, 4.0},\n        parameters{0.0, 0.6, 0.3},\n        100,\n    )\n    st = iterate(mccormick, 40, st)\n    st.report(\"McCormick\")\n    fmt.Println(\"f(-.54719, -1.54719) :\", mccormick([]float64{-.54719, -1.54719}))\n    fmt.Println()\n    st = psoInit(\n        []float64{0.0, 0.0},\n        []float64{math.Pi, math.Pi},\n        parameters{0.3, 0.3, 0.3},\n        1000,\n    )\n    st = iterate(michalewicz, 30, st)\n    st.report(\"Michalewicz (2D)\")\n    fmt.Println(\"f(2.20, 1.57)        :\", michalewicz([]float64{2.2, 1.57}))\n"}
{"id": 52388, "name": "Interactive programming (repl)", "Java": "public static void main(String[] args) {\n    System.out.println(concat(\"Rosetta\", \"Code\", \":\"));\n}\n\npublic static String concat(String a, String b, String c) {\n   return a + c + c + b;\n}\n\nRosetta::Code\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc f(s1, s2, sep string) string {\n\treturn s1 + sep + sep + s2\n}\n\nfunc main() {\n\tfmt.Println(f(\"Rosetta\", \"Code\", \":\"))\n}\n"}
{"id": 52389, "name": "Index finite lists of positive integers", "Java": "import java.math.BigInteger;\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.Collectors.*;\n\npublic class Test3 {\n    static BigInteger rank(int[] x) {\n        String s = stream(x).mapToObj(String::valueOf).collect(joining(\"F\"));\n        return new BigInteger(s, 16);\n    }\n\n    static List<BigInteger> unrank(BigInteger n) {\n        BigInteger sixteen = BigInteger.valueOf(16);\n        String s = \"\";\n        while (!n.equals(BigInteger.ZERO)) {\n            s = \"0123456789ABCDEF\".charAt(n.mod(sixteen).intValue()) + s;\n            n = n.divide(sixteen);\n        }\n        return stream(s.split(\"F\")).map(x -> new BigInteger(x)).collect(toList());\n    }\n\n    public static void main(String[] args) {\n        int[] s = {1, 2, 3, 10, 100, 987654321};\n        System.out.println(Arrays.toString(s));\n        System.out.println(rank(s));\n        System.out.println(unrank(rank(s)));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc rank(l []uint) (r big.Int) {\n    for _, n := range l {\n        r.Lsh(&r, n+1)\n        r.SetBit(&r, int(n), 1)\n    }\n    return\n}\n\nfunc unrank(n big.Int) (l []uint) {\n    m := new(big.Int).Set(&n)\n    for a := m.BitLen(); a > 0; {\n        m.SetBit(m, a-1, 0)\n        b := m.BitLen()\n        l = append(l, uint(a-b-1))\n        a = b\n    }\n    return\n}\n\nfunc main() {\n    var b big.Int\n    for i := 0; i <= 10; i++ {\n        b.SetInt64(int64(i))\n        u := unrank(b)\n        r := rank(u)\n        fmt.Println(i, u, &r)\n    }\n    b.SetString(\"12345678901234567890\", 10)\n    u := unrank(b)\n    r := rank(u)\n    fmt.Printf(\"\\n%v\\n%d\\n%d\\n\", &b, u, &r)\n}\n"}
{"id": 52390, "name": "Make a backup file", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52391, "name": "Make a backup file", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52392, "name": "Generalised floating point addition", "Java": "import java.math.BigDecimal;\n\npublic class GeneralisedFloatingPointAddition {\n\n    public static void main(String[] args) {\n        BigDecimal oneExp72 = new BigDecimal(\"1E72\");\n        for ( int i = 0 ; i <= 21+7 ; i++ ) {\n            String s = \"12345679\";\n            for ( int j = 0 ; j < i ; j++ ) {\n                s += \"012345679\";\n            }\n            int exp = 63 - 9*i;\n            s += \"E\" + exp;\n            BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal(\"1E\" + exp));\n            System.out.printf(\"Test value (%s) equals computed value: %b.  Computed = %s%n\", oneExp72, num.compareTo(oneExp72) == 0 , num);\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc repeatedAdd(bf *big.Float, times int) *big.Float {\n    if times < 2 {\n        return bf\n    }\n    var sum big.Float\n    for i := 0; i < times; i++ {\n        sum.Add(&sum, bf)\n    }\n    return &sum\n}\n\nfunc main() {\n    s := \"12345679\"\n    t := \"123456790\"\n    e := 63\n    var bf, extra big.Float\n    for n := -7; n <= 21; n++ {\n        bf.SetString(fmt.Sprintf(\"%se%d\", s, e))\n        extra.SetString(fmt.Sprintf(\"1e%d\", e))\n        bf = *repeatedAdd(&bf, 81)\n        bf.Add(&bf, &extra)\n        fmt.Printf(\"%2d : %s\\n\", n, bf.String())\n        s = t + s\n        e -= 9\n    }\n}\n"}
{"id": 52393, "name": "Generalised floating point addition", "Java": "import java.math.BigDecimal;\n\npublic class GeneralisedFloatingPointAddition {\n\n    public static void main(String[] args) {\n        BigDecimal oneExp72 = new BigDecimal(\"1E72\");\n        for ( int i = 0 ; i <= 21+7 ; i++ ) {\n            String s = \"12345679\";\n            for ( int j = 0 ; j < i ; j++ ) {\n                s += \"012345679\";\n            }\n            int exp = 63 - 9*i;\n            s += \"E\" + exp;\n            BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal(\"1E\" + exp));\n            System.out.printf(\"Test value (%s) equals computed value: %b.  Computed = %s%n\", oneExp72, num.compareTo(oneExp72) == 0 , num);\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc repeatedAdd(bf *big.Float, times int) *big.Float {\n    if times < 2 {\n        return bf\n    }\n    var sum big.Float\n    for i := 0; i < times; i++ {\n        sum.Add(&sum, bf)\n    }\n    return &sum\n}\n\nfunc main() {\n    s := \"12345679\"\n    t := \"123456790\"\n    e := 63\n    var bf, extra big.Float\n    for n := -7; n <= 21; n++ {\n        bf.SetString(fmt.Sprintf(\"%se%d\", s, e))\n        extra.SetString(fmt.Sprintf(\"1e%d\", e))\n        bf = *repeatedAdd(&bf, 81)\n        bf.Add(&bf, &extra)\n        fmt.Printf(\"%2d : %s\\n\", n, bf.String())\n        s = t + s\n        e -= 9\n    }\n}\n"}
{"id": 52394, "name": "Reverse the gender of a string", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n"}
{"id": 52395, "name": "Reverse the gender of a string", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n"}
{"id": 52396, "name": "Audio alarm", "Java": "import com.sun.javafx.application.PlatformImpl;\nimport java.io.File;\nimport java.util.Scanner;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport javafx.scene.media.Media;\nimport javafx.scene.media.MediaPlayer;\n\npublic class AudioAlarm {\n\n    public static void main(String[] args) throws InterruptedException {\n        Scanner input = new Scanner(System.in);\n\n        System.out.print(\"Enter a number of seconds: \");\n        int seconds = Integer.parseInt(input.nextLine());\n\n        System.out.print(\"Enter a filename (must end with .mp3 or .wav): \");\n        String audio = input.nextLine();\n\n        TimeUnit.SECONDS.sleep(seconds);\n\n        Media media = new Media(new File(audio).toURI().toString());\n        AtomicBoolean stop = new AtomicBoolean();\n        Runnable onEnd = () -> stop.set(true);\n\n        PlatformImpl.startup(() -> {}); \n\n        MediaPlayer player = new MediaPlayer(media);\n        player.setOnEndOfMedia(onEnd);\n        player.setOnError(onEnd);\n        player.setOnHalted(onEnd);\n        player.play();\n\n        while (!stop.get()) {\n            Thread.sleep(100);\n        }\n        System.exit(0); \n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    number := 0\n    for number < 1 {\n        fmt.Print(\"Enter number of seconds delay > 0 : \")\n        scanner.Scan()\n        input := scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n        number, _ = strconv.Atoi(input)\n    }\n\n    filename := \"\"\n    for filename == \"\" {\n        fmt.Print(\"Enter name of .mp3 file to play (without extension) : \")\n        scanner.Scan()\n        filename = scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n    }\n\n    cls := \"\\033[2J\\033[0;0H\" \n    fmt.Printf(\"%sAlarm will sound in %d seconds...\", cls, number)\n    time.Sleep(time.Duration(number) * time.Second)\n    fmt.Printf(cls)\n    cmd := exec.Command(\"play\", filename+\".mp3\")\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 52397, "name": "Decimal floating point number to binary", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n"}
{"id": 52398, "name": "Decimal floating point number to binary", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n"}
{"id": 52399, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 52400, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 52401, "name": "Check Machin-like formulas", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n"}
{"id": 52402, "name": "Check Machin-like formulas", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n"}
{"id": 52403, "name": "MD5_Implementation", "Java": "class MD5\n{\n\n  private static final int INIT_A = 0x67452301;\n  private static final int INIT_B = (int)0xEFCDAB89L;\n  private static final int INIT_C = (int)0x98BADCFEL;\n  private static final int INIT_D = 0x10325476;\n  \n  private static final int[] SHIFT_AMTS = {\n    7, 12, 17, 22,\n    5,  9, 14, 20,\n    4, 11, 16, 23,\n    6, 10, 15, 21\n  };\n  \n  private static final int[] TABLE_T = new int[64];\n  static\n  {\n    for (int i = 0; i < 64; i++)\n      TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));\n  }\n  \n  public static byte[] computeMD5(byte[] message)\n  {\n    int messageLenBytes = message.length;\n    int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;\n    int totalLen = numBlocks << 6;\n    byte[] paddingBytes = new byte[totalLen - messageLenBytes];\n    paddingBytes[0] = (byte)0x80;\n    \n    long messageLenBits = (long)messageLenBytes << 3;\n    for (int i = 0; i < 8; i++)\n    {\n      paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;\n      messageLenBits >>>= 8;\n    }\n    \n    int a = INIT_A;\n    int b = INIT_B;\n    int c = INIT_C;\n    int d = INIT_D;\n    int[] buffer = new int[16];\n    for (int i = 0; i < numBlocks; i ++)\n    {\n      int index = i << 6;\n      for (int j = 0; j < 64; j++, index++)\n        buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);\n      int originalA = a;\n      int originalB = b;\n      int originalC = c;\n      int originalD = d;\n      for (int j = 0; j < 64; j++)\n      {\n        int div16 = j >>> 4;\n        int f = 0;\n        int bufferIndex = j;\n        switch (div16)\n        {\n          case 0:\n            f = (b & c) | (~b & d);\n            break;\n            \n          case 1:\n            f = (b & d) | (c & ~d);\n            bufferIndex = (bufferIndex * 5 + 1) & 0x0F;\n            break;\n            \n          case 2:\n            f = b ^ c ^ d;\n            bufferIndex = (bufferIndex * 3 + 5) & 0x0F;\n            break;\n            \n          case 3:\n            f = c ^ (b | ~d);\n            bufferIndex = (bufferIndex * 7) & 0x0F;\n            break;\n        }\n        int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);\n        a = d;\n        d = c;\n        c = b;\n        b = temp;\n      }\n      \n      a += originalA;\n      b += originalB;\n      c += originalC;\n      d += originalD;\n    }\n    \n    byte[] md5 = new byte[16];\n    int count = 0;\n    for (int i = 0; i < 4; i++)\n    {\n      int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));\n      for (int j = 0; j < 4; j++)\n      {\n        md5[count++] = (byte)n;\n        n >>>= 8;\n      }\n    }\n    return md5;\n  }\n  \n  public static String toHexString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      sb.append(String.format(\"%02X\", b[i] & 0xFF));\n    }\n    return sb.toString();\n  }\n\n  public static void main(String[] args)\n  {\n    String[] testStrings = { \"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" };\n    for (String s : testStrings)\n      System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\");\n    return;\n  }\n  \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"bytes\"\n    \"encoding/binary\"\n)\n\ntype testCase struct {\n    hashCode string\n    string\n}\n\nvar testCases = []testCase{\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\nfunc main() {\n    for _, tc := range testCases {\n        fmt.Printf(\"%s\\n%x\\n\\n\", tc.hashCode, md5(tc.string))\n    }\n}\n\nvar shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}\nvar table [64]uint32\n\nfunc init() {\n    for i := range table {\n        table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))\n    }\n}\n\nfunc md5(s string) (r [16]byte) {\n    padded := bytes.NewBuffer([]byte(s))\n    padded.WriteByte(0x80)\n    for padded.Len() % 64 != 56 {\n        padded.WriteByte(0)\n    }\n    messageLenBits := uint64(len(s)) * 8\n    binary.Write(padded, binary.LittleEndian, messageLenBits)\n\n    var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476\n    var buffer [16]uint32\n    for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { \n        a1, b1, c1, d1 := a, b, c, d\n        for j := 0; j < 64; j++ {\n            var f uint32\n            bufferIndex := j\n            round := j >> 4\n            switch round {\n            case 0:\n                f = (b1 & c1) | (^b1 & d1)\n            case 1:\n                f = (b1 & d1) | (c1 & ^d1)\n                bufferIndex = (bufferIndex*5 + 1) & 0x0F\n            case 2:\n                f = b1 ^ c1 ^ d1\n                bufferIndex = (bufferIndex*3 + 5) & 0x0F\n            case 3:\n                f = c1 ^ (b1 | ^d1)\n                bufferIndex = (bufferIndex * 7) & 0x0F\n            }\n            sa := shift[(round<<2)|(j&3)]\n            a1 += f + buffer[bufferIndex] + table[j]\n            a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1\n        }\n        a, b, c, d = a+a1, b+b1, c+c1, d+d1\n    }\n\n    binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})\n    return\n}\n"}
{"id": 52404, "name": "K-means++ clustering", "Java": "import java.util.Random;\n\npublic class KMeansWithKpp{\n\t\t\n\t\tpublic Point[] points;\n\t\tpublic Point[] centroids;\n\t\tRandom rand;\n\t\tpublic int n;\n\t\tpublic int k;\n\n\t\t\n\t\tprivate KMeansWithKpp(){\n\t\t}\n\n\t\tKMeansWithKpp(Point[] p, int clusters){\n\t\t\t\tpoints = p;\n\t\t\t\tn = p.length;\n\t\t\t\tk = Math.max(1, clusters);\n\t\t\t\tcentroids = new Point[k];\n\t\t\t\trand = new Random();\n\t\t}\n\n\n\t\tprivate static double distance(Point a, Point b){\n\t\t\t\treturn (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n\t\t}\n\n\t\tprivate static int nearest(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tint index = pt.group;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn index;\n\t\t}\n\n\t\tprivate static double nearestDistance(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn minD;\n\t\t}\n\n\t\tprivate void kpp(){\n\t\t\t\tcentroids[0] = points[rand.nextInt(n)];\n\t\t\t\tdouble[] dist = new double[n];\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor (int i = 1; i < k; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tdist[j] = nearestDistance(points[j], centroids, i);\n\t\t\t\t\t\t\t\tsum += dist[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tif ((sum -= dist[j]) > 0)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tcentroids[i].x = points[j].x;\n\t\t\t\t\t\t\t\tcentroids[i].y = points[j].y;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tpoints[i].group = nearest(points[i], centroids, k);\n\t\t\t\t}\n\t\t}\n\n\t\tpublic void kMeans(int maxTimes){\n\t\t\t\tif (k == 1 || n <= 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(k >= n){\n\t\t\t\t\t\tfor(int i =0; i < n; i++){\n\t\t\t\t\t\t\t\tpoints[i].group = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxTimes = Math.max(1, maxTimes);\n\t\t\t\tint changed;\n\t\t\t\tint bestPercent = n/1000;\n\t\t\t\tint minIndex;\n\t\t\t\tkpp();\n\t\t\t\tdo {\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x = 0.0;\n\t\t\t\t\t\t\t\tc.y = 0.0;\n\t\t\t\t\t\t\t\tc.group = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tif(pt.group < 0 || pt.group > centroids.length){\n\t\t\t\t\t\t\t\t\t\tpt.group = rand.nextInt(centroids.length);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcentroids[pt.group].x += pt.x;\n\t\t\t\t\t\t\t\tcentroids[pt.group].y = pt.y;\n\t\t\t\t\t\t\t\tcentroids[pt.group].group++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x /= c.group;\n\t\t\t\t\t\t\t\tc.y /= c.group;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tminIndex = nearest(pt, centroids, k);\n\t\t\t\t\t\t\t\tif (k != pt.group) {\n\t\t\t\t\t\t\t\t\t\tchanged++;\n\t\t\t\t\t\t\t\t\t\tpt.group = minIndex;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxTimes--;\n\t\t\t\t} while (changed > bestPercent && maxTimes > 0);\n\t\t}\n}\n\n\n\n\nclass Point{\n\t\tpublic double x;\n\t\tpublic double y;\n\t\tpublic int group;\n\n\t\tPoint(){\n\t\t\t\tx = y = 0.0;\n\t\t\t\tgroup = 0;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){\n\t\t\t\tif (size <= 0)\n\t\t\t\t\t\treturn null;\n\t\t\t\tdouble xdiff, ydiff;\n\t\t\t\txdiff = maxX - minX;\n\t\t\t\tydiff = maxY - minY;\n\t\t\t\tif (minX > maxX) {\n\t\t\t\t\t\txdiff = minX - maxX;\n\t\t\t\t\t\tminX = maxX;\n\t\t\t\t}\n\t\t\t\tif (maxY < minY) {\n\t\t\t\t\t\tydiff = minY - maxY;\n\t\t\t\t\t\tminY = maxY;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tdata[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPolarData(double radius, int size){\n\t\t\t\tif (size <= 0) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tdouble radi, arg;\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tradi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\targ = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].x = radi * Math.cos(arg);\n\t\t\t\t\t\tdata[i].y = radi * Math.sin(arg);\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\t\t\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype r2 struct {\n    x, y float64\n}\n\ntype r2c struct {\n    r2\n    c int \n}\n\n\nfunc kmpp(k int, data []r2c) {\n    kMeans(data, kmppSeeds(k, data))\n}\n\n\n\nfunc kmppSeeds(k int, data []r2c) []r2 {\n    s := make([]r2, k)\n    s[0] = data[rand.Intn(len(data))].r2\n    d2 := make([]float64, len(data))\n    for i := 1; i < k; i++ {\n        var sum float64\n        for j, p := range data {\n            _, dMin := nearest(p, s[:i])\n            d2[j] = dMin * dMin\n            sum += d2[j]\n        }\n        target := rand.Float64() * sum\n        j := 0\n        for sum = d2[0]; sum < target; sum += d2[j] {\n            j++\n        }\n        s[i] = data[j].r2\n    }\n    return s\n}\n\n\n\n\nfunc nearest(p r2c, mean []r2) (int, float64) {\n    iMin := 0\n    dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y)\n    for i := 1; i < len(mean); i++ {\n        d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y)\n        if d < dMin {\n            dMin = d\n            iMin = i\n        }\n    }\n    return iMin, dMin\n}\n\n\nfunc kMeans(data []r2c, mean []r2) {\n    \n    for i, p := range data {\n        cMin, _ := nearest(p, mean)\n        data[i].c = cMin\n    }\n    mLen := make([]int, len(mean))\n    for {\n        \n        for i := range mean {\n            mean[i] = r2{}\n            mLen[i] = 0\n        }\n        for _, p := range data {\n            mean[p.c].x += p.x\n            mean[p.c].y += p.y\n            mLen[p.c]++\n        }\n        for i := range mean {\n            inv := 1 / float64(mLen[i])\n            mean[i].x *= inv\n            mean[i].y *= inv\n        }\n        \n        var changes int\n        for i, p := range data {\n            if cMin, _ := nearest(p, mean); cMin != p.c {\n                changes++\n                data[i].c = cMin\n            }\n        }\n        if changes == 0 {\n            return\n        }\n    }\n}\n\n\ntype ecParam struct {\n    k          int\n    nPoints    int\n    xBox, yBox int\n    stdv       int\n}\n\n\nfunc main() {\n    ec := &ecParam{6, 30000, 300, 200, 30}\n    \n    origin, data := genECData(ec)\n    vis(ec, data, \"origin\")\n    fmt.Println(\"Data set origins:\")\n    fmt.Println(\"    x      y\")\n    for _, o := range origin {\n        fmt.Printf(\"%5.1f  %5.1f\\n\", o.x, o.y)\n    }\n\n    kmpp(ec.k, data)\n    \n    fmt.Println(\n        \"\\nCluster centroids, mean distance from centroid, number of points:\")\n    fmt.Println(\"    x      y  distance  points\")\n    cent := make([]r2, ec.k)\n    cLen := make([]int, ec.k)\n    inv := make([]float64, ec.k)\n    for _, p := range data {\n        cent[p.c].x += p.x \n        cent[p.c].y += p.y \n        cLen[p.c]++\n    }\n    for i, iLen := range cLen {\n        inv[i] = 1 / float64(iLen)\n        cent[i].x *= inv[i]\n        cent[i].y *= inv[i]\n    }\n    dist := make([]float64, ec.k)\n    for _, p := range data {\n        dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y)\n    }\n    for i, iLen := range cLen {\n        fmt.Printf(\"%5.1f  %5.1f  %8.1f  %6d\\n\",\n            cent[i].x, cent[i].y, dist[i]*inv[i], iLen)\n    }\n    vis(ec, data, \"clusters\")\n}\n\n\n\n\n\n\n\nfunc genECData(ec *ecParam) (orig []r2, data []r2c) {\n    rand.Seed(time.Now().UnixNano())\n    orig = make([]r2, ec.k)\n    data = make([]r2c, ec.nPoints)\n    for i, n := 0, 0; i < ec.k; i++ {\n        x := rand.Float64() * float64(ec.xBox)\n        y := rand.Float64() * float64(ec.yBox)\n        orig[i] = r2{x, y}\n        for j := ec.nPoints / ec.k; j > 0; j-- {\n            data[n].x = rand.NormFloat64()*float64(ec.stdv) + x\n            data[n].y = rand.NormFloat64()*float64(ec.stdv) + y\n            data[n].c = i\n            n++\n        }\n    }\n    return\n}\n\n\nfunc vis(ec *ecParam, data []r2c, fn string) {\n    colors := make([]color.NRGBA, ec.k)\n    for i := range colors {\n        i3 := i * 3\n        third := i3 / ec.k\n        frac := uint8((i3 % ec.k) * 255 / ec.k)\n        switch third {\n        case 0:\n            colors[i] = color.NRGBA{frac, 255 - frac, 0, 255}\n        case 1:\n            colors[i] = color.NRGBA{0, frac, 255 - frac, 255}\n        case 2:\n            colors[i] = color.NRGBA{255 - frac, 0, frac, 255}\n        }\n    }\n    bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv)\n    im := image.NewNRGBA(bounds)\n    draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    fMinX := float64(bounds.Min.X)\n    fMaxX := float64(bounds.Max.X)\n    fMinY := float64(bounds.Min.Y)\n    fMaxY := float64(bounds.Max.Y)\n    for _, p := range data {\n        imx := math.Floor(p.x)\n        imy := math.Floor(float64(ec.yBox) - p.y)\n        if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY {\n            im.SetNRGBA(int(imx), int(imy), colors[p.c])\n        }\n    }\n    f, err := os.Create(fn + \".png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = png.Encode(f, im)\n    if err != nil {\n        fmt.Println(err)\n    }\n    err = f.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52405, "name": "Maze solving", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class MazeSolver\n{\n    \n    private static String[] readLines (InputStream f) throws IOException\n    {\n        BufferedReader r =\n            new BufferedReader (new InputStreamReader (f, \"US-ASCII\"));\n        ArrayList<String> lines = new ArrayList<String>();\n        String line;\n        while ((line = r.readLine()) != null)\n            lines.add (line);\n        return lines.toArray(new String[0]);\n    }\n\n    \n    private static char[][] decimateHorizontally (String[] lines)\n    {\n        final int width = (lines[0].length() + 1) / 2;\n        char[][] c = new char[lines.length][width];\n        for (int i = 0  ;  i < lines.length  ;  i++)\n            for (int j = 0  ;  j < width  ;  j++)\n                c[i][j] = lines[i].charAt (j * 2);\n        return c;\n    }\n\n    \n    private static boolean solveMazeRecursively (char[][] maze,\n                                                 int x, int y, int d)\n    {\n        boolean ok = false;\n        for (int i = 0  ;  i < 4  &&  !ok  ;  i++)\n            if (i != d)\n                switch (i)\n                    {\n                        \n                    case 0:\n                        if (maze[y-1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y - 2, 2);\n                        break;\n                    case 1:\n                        if (maze[y][x+1] == ' ')\n                            ok = solveMazeRecursively (maze, x + 2, y, 3);\n                        break;\n                    case 2:\n                        if (maze[y+1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y + 2, 0);\n                        break;\n                    case 3:\n                        if (maze[y][x-1] == ' ')\n                            ok = solveMazeRecursively (maze, x - 2, y, 1);\n                        break;\n                    }\n        \n        if (x == 1  &&  y == 1)\n            ok = true;\n        \n        if (ok)\n            {\n                maze[y][x] = '*';\n                switch (d)\n                    {\n                    case 0:\n                        maze[y-1][x] = '*';\n                        break;\n                    case 1:\n                        maze[y][x+1] = '*';\n                        break;\n                    case 2:\n                        maze[y+1][x] = '*';\n                        break;\n                    case 3:\n                        maze[y][x-1] = '*';\n                        break;\n                    }\n            }\n        return ok;\n    }\n\n    \n    private static void solveMaze (char[][] maze)\n    {\n        solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1);\n    }\n\n    \n    private static String[] expandHorizontally (char[][] maze)\n    {\n        char[] tmp = new char[3];\n        String[] lines = new String[maze.length];\n        for (int i = 0  ;  i < maze.length  ;  i++)\n            {\n                StringBuilder sb = new StringBuilder(maze[i].length * 2);\n                for (int j = 0  ;  j < maze[i].length  ;  j++)\n                    if (j % 2 == 0)\n                        sb.append (maze[i][j]);\n                    else\n                        {\n                            tmp[0] = tmp[1] = tmp[2] = maze[i][j];\n                            if (tmp[1] == '*')\n                                tmp[0] = tmp[2] = ' ';\n                            sb.append (tmp);\n                        }\n                lines[i] = sb.toString();\n            }\n        return lines;\n    }\n\n    \n    public static void main (String[] args) throws IOException\n    {\n        InputStream f = (args.length > 0\n                         ?  new FileInputStream (args[0])\n                         :  System.in);\n        String[] lines = readLines (f);\n        char[][] maze = decimateHorizontally (lines);\n        solveMaze (maze);\n        String[] solvedLines = expandHorizontally (maze);\n        for (int i = 0  ;  i < solvedLines.length  ;  i++)\n            System.out.println (solvedLines[i]);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\" \n    \"math/rand\"\n    \"time\"\n)\n\ntype maze struct { \n    c2 [][]byte \n    h2 [][]byte \n    v2 [][]byte \n}\n\nfunc newMaze(rows, cols int) *maze {\n    c := make([]byte, rows*cols)              \n    h := bytes.Repeat([]byte{'-'}, rows*cols) \n    v := bytes.Repeat([]byte{'|'}, rows*cols) \n    c2 := make([][]byte, rows)                \n    h2 := make([][]byte, rows)                \n    v2 := make([][]byte, rows)                \n    for i := range h2 {\n        c2[i] = c[i*cols : (i+1)*cols]\n        h2[i] = h[i*cols : (i+1)*cols]\n        v2[i] = v[i*cols : (i+1)*cols]\n    }\n    return &maze{c2, h2, v2}\n}   \n    \nfunc (m *maze) String() string {\n    hWall := []byte(\"+---\")\n    hOpen := []byte(\"+   \")\n    vWall := []byte(\"|   \")\n    vOpen := []byte(\"    \")\n    rightCorner := []byte(\"+\\n\")\n    rightWall := []byte(\"|\\n\")\n    var b []byte\n    for r, hw := range m.h2 {\n        for _, h := range hw {\n            if h == '-' || r == 0 {\n                b = append(b, hWall...)\n            } else {\n                b = append(b, hOpen...)\n                if h != '-' && h != 0 {\n                    b[len(b)-2] = h\n                }\n            }\n        }\n        b = append(b, rightCorner...)\n        for c, vw := range m.v2[r] {\n            if vw == '|' || c == 0 {\n                b = append(b, vWall...)\n            } else {\n                b = append(b, vOpen...)\n                if vw != '|' && vw != 0 {\n                    b[len(b)-4] = vw\n                }\n            }\n            if m.c2[r][c] != 0 {\n                b[len(b)-2] = m.c2[r][c]\n            }\n        }\n        b = append(b, rightWall...)\n    }\n    for _ = range m.h2[0] {\n        b = append(b, hWall...)\n    }\n    b = append(b, rightCorner...)\n    return string(b)\n}\n\nfunc (m *maze) gen() {\n    m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))\n}\n\nconst (\n    up = iota\n    dn\n    rt\n    lf\n)\n\nfunc (m *maze) g2(r, c int) {\n    m.c2[r][c] = ' '\n    for _, dir := range rand.Perm(4) {\n        switch dir {\n        case up:\n            if r > 0 && m.c2[r-1][c] == 0 {\n                m.h2[r][c] = 0\n                m.g2(r-1, c)\n            }\n        case lf:\n            if c > 0 && m.c2[r][c-1] == 0 {\n                m.v2[r][c] = 0\n                m.g2(r, c-1)\n            }\n        case dn:\n            if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {\n                m.h2[r+1][c] = 0\n                m.g2(r+1, c)\n            }\n        case rt:\n            if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {\n                m.v2[r][c+1] = 0\n                m.g2(r, c+1)\n            } \n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const height = 4\n    const width = 7\n    m := newMaze(height, width)\n    m.gen() \n    m.solve(\n        rand.Intn(height), rand.Intn(width),\n        rand.Intn(height), rand.Intn(width))\n    fmt.Print(m)\n}   \n    \nfunc (m *maze) solve(ra, ca, rz, cz int) {\n    var rSolve func(ra, ca, dir int) bool\n    rSolve = func(r, c, dir int) bool {\n        if r == rz && c == cz {\n            m.c2[r][c] = 'F'\n            return true\n        }\n        if dir != dn && m.h2[r][c] == 0 {\n            if rSolve(r-1, c, up) {\n                m.c2[r][c] = '^'\n                m.h2[r][c] = '^'\n                return true\n            }\n        }\n        if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 {\n            if rSolve(r+1, c, dn) {\n                m.c2[r][c] = 'v'\n                m.h2[r+1][c] = 'v'\n                return true\n            }\n        }\n        if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 {\n            if rSolve(r, c+1, rt) {\n                m.c2[r][c] = '>'\n                m.v2[r][c+1] = '>'\n                return true\n            }\n        }\n        if dir != rt && m.v2[r][c] == 0 {\n            if rSolve(r, c-1, lf) {\n                m.c2[r][c] = '<'\n                m.v2[r][c] = '<'\n                return true\n            }\n        }\n        return false\n    }\n    rSolve(ra, ca, -1)\n    m.c2[ra][ca] = 'S'\n}\n"}
{"id": 52406, "name": "Generate random numbers without repeating a value", "Java": "import java.util.*;\n\npublic class RandomShuffle {\n    public static void main(String[] args) {\n        Random rand = new Random();\n        List<Integer> list = new ArrayList<>();\n        for (int j = 1; j <= 20; ++j)\n            list.add(j);\n        Collections.shuffle(list, rand);\n        System.out.println(list);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\nfunc generate(from, to int64) {\n    if to < from || from < 0 {\n        log.Fatal(\"Invalid range.\")\n    }\n    span := to - from + 1\n    generated := make([]bool, span) \n    count := span\n    for count > 0 {\n        n := from + rand.Int63n(span) \n        if !generated[n-from] {\n            generated[n-from] = true\n            fmt.Printf(\"%2d \", n)\n            count--\n        }\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    \n    for i := 1; i <= 5; i++ {\n        generate(1, 20)\n    }\n}\n"}
{"id": 52407, "name": "Solve triangle solitare puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\n\npublic class IQPuzzle {\n\n    public static void main(String[] args) {\n        System.out.printf(\"  \");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"  %,6d\", start);\n        }\n        System.out.printf(\"%n\");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"%2d\", start);\n            Map<Integer,Integer> solutions = solve(start);    \n            for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {\n                System.out.printf(\"  %,6d\", solutions.containsKey(end) ? solutions.get(end) : 0);\n            }\n            System.out.printf(\"%n\");\n        }\n        int moveNum = 0;\n        System.out.printf(\"%nOne Solution:%n\");\n        for ( Move m : oneSolution ) {\n            moveNum++;\n            System.out.printf(\"Move %d = %s%n\", moveNum, m);\n        }\n    }\n    \n    private static List<Move> oneSolution = null;\n    \n    private static Map<Integer, Integer> solve(int emptyPeg) {\n        Puzzle puzzle = new Puzzle(emptyPeg);\n        Map<Integer,Integer> solutions = new HashMap<>();\n        Stack<Puzzle> stack = new Stack<Puzzle>();\n        stack.push(puzzle);\n        while ( ! stack.isEmpty() ) {\n            Puzzle p = stack.pop();\n            if ( p.solved() ) {\n                solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);\n                if ( oneSolution == null ) {\n                    oneSolution = p.moves;\n                }\n                continue;\n            }\n            for ( Move move : p.getValidMoves() ) {\n                Puzzle pMove = p.move(move);\n                stack.add(pMove);\n            }\n        }\n        \n        return solutions;\n    }\n    \n    private static class Puzzle {\n        \n        public static int MAX_PEGS = 16;\n        private boolean[] pegs = new boolean[MAX_PEGS];  \n        \n        private List<Move> moves;\n\n        public Puzzle(int emptyPeg) {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            pegs[emptyPeg] = false;\n            moves = new ArrayList<>();\n        }\n\n        public Puzzle() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            moves = new ArrayList<>();\n        }\n\n        private static Map<Integer,List<Move>> validMoves = new HashMap<>(); \n        static {\n            validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));\n            validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));\n            validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));\n            validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));\n            validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));\n            validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));\n            validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));\n            validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));\n            validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));\n            validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));\n            validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));\n            validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));\n            validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));\n            validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));\n            validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));\n        }\n        \n        public List<Move> getValidMoves() {\n            List<Move> moves = new ArrayList<Move>();\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    for ( Move testMove : validMoves.get(i) ) {\n                        if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {\n                            moves.add(testMove);\n                        }\n                    }\n                }\n            }\n            return moves;\n        }\n\n        public boolean solved() {\n            boolean foundFirstPeg = false;\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    if ( foundFirstPeg ) {\n                        return false;\n                    }\n                    foundFirstPeg = true;\n                }\n            }\n            return true;\n        }\n        \n        public Puzzle move(Move move) {\n            Puzzle p = new Puzzle();\n            if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {\n                throw new RuntimeException(\"Invalid move.\");\n            }\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                p.pegs[i] = pegs[i];\n            }\n            p.pegs[move.start] = false;\n            p.pegs[move.jump] = false;\n            p.pegs[move.end] = true;\n            for ( Move m : moves ) {\n                p.moves.add(new Move(m.start, m.jump, m.end));\n            }\n            p.moves.add(new Move(move.start, move.jump, move.end));\n            return p;\n        }\n        \n        public int getLastPeg() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    return i;\n                }\n            }\n            throw new RuntimeException(\"ERROR:  Illegal position.\");\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"[\");\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                sb.append(pegs[i] ? 1 : 0);\n                sb.append(\",\");\n            }\n            sb.setLength(sb.length()-1);            \n            sb.append(\"]\");\n            return sb.toString();\n        }\n    }\n    \n    private static class Move {\n        int start;\n        int jump;\n        int end;\n        \n        public Move(int s, int j, int e) {\n            start = s; jump = j; end = e;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"{\");\n            sb.append(\"s=\" + start);\n            sb.append(\", j=\" + jump);\n            sb.append(\", e=\" + end);\n            sb.append(\"}\");\n            return sb.toString();\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype solution struct{ peg, over, land int }\n\ntype move struct{ from, to int }\n\nvar emptyStart = 1\n\nvar board [16]bool\n\nvar jumpMoves = [16][]move{\n    {},\n    {{2, 4}, {3, 6}},\n    {{4, 7}, {5, 9}},\n    {{5, 8}, {6, 10}},\n    {{2, 1}, {5, 6}, {7, 11}, {8, 13}},\n    {{8, 12}, {9, 14}},\n    {{3, 1}, {5, 4}, {9, 13}, {10, 15}},\n    {{4, 2}, {8, 9}},\n    {{5, 3}, {9, 10}},\n    {{5, 2}, {8, 7}},\n    {{9, 8}},\n    {{12, 13}},\n    {{8, 5}, {13, 14}},\n    {{8, 4}, {9, 6}, {12, 11}, {14, 15}},\n    {{9, 5}, {13, 12}},\n    {{10, 6}, {14, 13}},\n}\n\nvar solutions []solution\n\nfunc initBoard() {\n    for i := 1; i < 16; i++ {\n        board[i] = true\n    }\n    board[emptyStart] = false\n}\n\nfunc (sol solution) split() (int, int, int) {\n    return sol.peg, sol.over, sol.land\n}\n\nfunc (mv move) split() (int, int) {\n    return mv.from, mv.to\n}\n\nfunc drawBoard() {\n    var pegs [16]byte\n    for i := 1; i < 16; i++ {\n        if board[i] {\n            pegs[i] = fmt.Sprintf(\"%X\", i)[0]\n        } else {\n            pegs[i] = '-'\n        }\n    }\n    fmt.Printf(\"       %c\\n\", pegs[1])\n    fmt.Printf(\"      %c %c\\n\", pegs[2], pegs[3])\n    fmt.Printf(\"     %c %c %c\\n\", pegs[4], pegs[5], pegs[6])\n    fmt.Printf(\"    %c %c %c %c\\n\", pegs[7], pegs[8], pegs[9], pegs[10])\n    fmt.Printf(\"   %c %c %c %c %c\\n\", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n}\n\nfunc solved() bool {\n    count := 0\n    for _, b := range board {\n        if b {\n            count++\n        }\n    }\n    return count == 1 \n}\n\nfunc solve() {\n    if solved() {\n        return\n    }\n    for peg := 1; peg < 16; peg++ {\n        if board[peg] {\n            for _, mv := range jumpMoves[peg] {\n                over, land := mv.split()\n                if board[over] && !board[land] {\n                    saveBoard := board\n                    board[peg] = false\n                    board[over] = false\n                    board[land] = true\n                    solutions = append(solutions, solution{peg, over, land})\n                    solve()\n                    if solved() {\n                        return \n                    }\n                    board = saveBoard\n                    solutions = solutions[:len(solutions)-1]\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    initBoard()\n    solve()\n    initBoard()\n    drawBoard()\n    fmt.Printf(\"Starting with peg %X removed\\n\\n\", emptyStart)\n    for _, solution := range solutions {\n        peg, over, land := solution.split()\n        board[peg] = false\n        board[over] = false\n        board[land] = true\n        drawBoard()\n        fmt.Printf(\"Peg %X jumped over %X to land on %X\\n\\n\", peg, over, land)\n    }\n}\n"}
{"id": 52408, "name": "Pseudorandom number generator image", "Java": "import javax.imageio.ImageIO;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport java.util.Random;\nimport java.util.Scanner;\n\n\npublic class csprngBBS {\n    public static Scanner input = new Scanner(System.in);\n    private static final String fileformat = \"png\";\n    private static String bitsStri = \"\";\n    private static String parityEven = \"\";\n    private static String leastSig = \"\";\n    private static String randomJavaUtil = \"\";\n    private static int width = 0;\n    private static int BIT_LENGTH = 0;\n    private static final Random rand = new SecureRandom();\n    private static BigInteger p = null; \n    private static BigInteger q = null; \n    private static BigInteger m = null;\n    private static BigInteger seed = null; \n    private static BigInteger seedFinal = null;\n    private static final Random randMathUtil = new SecureRandom();\n    public static void main(String[] args) throws IOException {\n        System.out.print(\"Width: \");\n        width = input.nextInt();\n        System.out.print(\"Bit-Length: \");\n        BIT_LENGTH = input.nextInt();\n        System.out.print(\"Generator format: \");\n        String useGenerator = input.next();\n        p = BigInteger.probablePrime(BIT_LENGTH, rand);\n        q = BigInteger.probablePrime(BIT_LENGTH, rand);\n        m = p.multiply(q);\n        seed = BigInteger.probablePrime(BIT_LENGTH,rand);\n        seedFinal = seed.add(BigInteger.ZERO);\n        if(useGenerator.contains(\"parity\") && useGenerator.contains(\"significant\")) {\n            findLeastSignificant();\n            findBitParityEven();\n            createImage(parityEven, \"parityEven\");\n            createImage(leastSig, \"significant\");\n        }\n\n        if(useGenerator.contains(\"parity\") && !useGenerator.contains(\"significant\")){\n            findBitParityEven();\n        }\n\n        if(useGenerator.contains(\"significant\") && !useGenerator.contains(\"parity\")){\n            findLeastSignificant();\n            createImage(leastSig, \"significant\");\n        }\n\n        if(useGenerator.contains(\"util\")){\n            findRandomJava(randMathUtil);\n            createImage(randomJavaUtil, \"randomUtilJava\");\n        }\n    }\n    public static void findRandomJava(Random random){\n        for(int x = 1; x <= Math.pow(width, 2); x++){\n            randomJavaUtil += random.nextInt(2);\n        }\n    }\n\n    public static void findBitParityEven(){\n        for(int x = 1; x <= Math.pow(width, 2); x++) {\n            seed = seed.pow(2).mod(m);\n            bitsStri = convertBinary(seed);\n            char[] bits = bitsStri.toCharArray();\n            int counter = 0;\n            for (char bit : bits) {\n                if (bit == '1') {\n                    counter++;\n                }\n            }\n            if (counter % 2 != 0) {\n                parityEven += \"1\";\n            } else {\n                parityEven += \"0\";\n            }\n        }\n    }\n\n    public static void findLeastSignificant(){\n        seed = seedFinal;\n        for(int x = 1; x <= Math.pow(width, 2); x++){\n            seed = seed.pow(2).mod(m);\n            leastSig += bitsStri.substring(bitsStri.length() - 1);\n        }\n    }\n\n    public static String convertBinary(BigInteger value){\n        StringBuilder total = new StringBuilder();\n        BigInteger two = BigInteger.TWO;\n        while(value.compareTo(BigInteger.ZERO) > 0){\n            total.append(value.mod(two));\n            value = value.divide(two);\n        }\n        return total.reverse().toString();\n    }\n\n    public static void createImage(String useThis, String fileName) throws IOException {\n        int length = csprngBBS.width;\n        \n        BufferedImage bufferedImage = new BufferedImage(length, length, 1);\n        \n        Graphics2D g2d = bufferedImage.createGraphics();\n        for (int y = 1; y <= length; y++) {\n            for (int x = 1; x <= length; x++) {\n                if (useThis.startsWith(\"1\")) {\n                    useThis = useThis.substring(1);\n                    g2d.setColor(Color.BLACK);\n                    g2d.fillRect(x, y, 1, 1);\n                } else if (useThis.startsWith(\"0\")) {\n                    useThis = useThis.substring(1);\n                    g2d.setColor(Color.WHITE);\n                    g2d.fillRect(x, y, 1, 1);\n                }\n            }\n            System.out.print(y + \"\\t\");\n        }\n        \n        g2d.dispose();\n        \n        File file = new File(\"REPLACEFILEPATHHERE\" + fileName + \".\" + fileformat);\n        ImageIO.write(bufferedImage, fileformat, file);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    img := image.NewNRGBA(image.Rect(0, 0, 1000, 1000))\n    for x := 0; x < 1000; x++ {\n        for y := 0; y < 1000; y++ {\n            col := color.RGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), 255}\n            img.Set(x, y, col)\n        }\n    }\n    fileName := \"pseudorandom_number_generator.png\"\n    imgFile, err := os.Create(fileName)\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer imgFile.Close()\n\n    if err := png.Encode(imgFile, img); err != nil {\n        imgFile.Close()\n        log.Fatal(err)\n    }\n}\n"}
{"id": 52409, "name": "Non-transitive dice", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n    private static List<List<Integer>> fourFaceCombos() {\n        List<List<Integer>> res = new ArrayList<>();\n        Set<Integer> found = new HashSet<>();\n\n        for (int i = 1; i <= 4; i++) {\n            for (int j = 1; j <= 4; j++) {\n                for (int k = 1; k <= 4; k++) {\n                    for (int l = 1; l <= 4; l++) {\n                        List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());\n\n                        int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);\n                        if (found.add(key)) {\n                            res.add(c);\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static int cmp(List<Integer> x, List<Integer> y) {\n        int xw = 0;\n        int yw = 0;\n        for (int i = 0; i < 4; i++) {\n            for (int j = 0; j < 4; j++) {\n                if (x.get(i) > y.get(j)) {\n                    xw++;\n                } else if (x.get(i) < y.get(j)) {\n                    yw++;\n                }\n            }\n        }\n        return Integer.compare(xw, yw);\n    }\n\n    private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (List<Integer> kl : cs) {\n                        if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {\n                            res.add(List.of(cs.get(i), cs.get(j), kl));\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (int k = 0; k < cs.size(); k++) {\n                        if (cmp(cs.get(j), cs.get(k)) == -1) {\n                            for (List<Integer> ll : cs) {\n                                if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {\n                                    res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> combos = fourFaceCombos();\n        System.out.printf(\"Number of eligible 4-faced dice: %d%n\", combos.size());\n        System.out.println();\n\n        List<List<List<Integer>>> it3 = findIntransitive3(combos);\n        System.out.printf(\"%d ordered lists of 3 non-transitive dice found, namely:%n\", it3.size());\n        for (List<List<Integer>> a : it3) {\n            System.out.println(a);\n        }\n        System.out.println();\n\n        List<List<List<Integer>>> it4 = findIntransitive4(combos);\n        System.out.printf(\"%d ordered lists of 4 non-transitive dice found, namely:%n\", it4.size());\n        for (List<List<Integer>> a : it4) {\n            System.out.println(a);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n    found := make([]bool, 256)\n    for i := 1; i <= 4; i++ {\n        for j := 1; j <= 4; j++ {\n            for k := 1; k <= 4; k++ {\n                for l := 1; l <= 4; l++ {\n                    c := [4]int{i, j, k, l}\n                    sort.Ints(c[:])\n                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n                    if !found[key] {\n                        found[key] = true\n                        res = append(res, c)\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc cmp(x, y [4]int) int {\n    xw := 0\n    yw := 0\n    for i := 0; i < 4; i++ {\n        for j := 0; j < 4; j++ {\n            if x[i] > y[j] {\n                xw++\n            } else if y[j] > x[i] {\n                yw++\n            }\n        }\n    }\n    if xw < yw {\n        return -1\n    } else if xw > yw {\n        return 1\n    }\n    return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n    var c = len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                first := cmp(cs[i], cs[j])\n                if first == -1 {\n                    second := cmp(cs[j], cs[k])\n                    if second == -1 {\n                        third := cmp(cs[i], cs[k])\n                        if third == 1 {\n                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n    c := len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                for l := 0; l < c; l++ {\n                    first := cmp(cs[i], cs[j])\n                    if first == -1 {\n                        second := cmp(cs[j], cs[k])\n                        if second == -1 {\n                            third := cmp(cs[k], cs[l])\n                            if third == -1 {\n                                fourth := cmp(cs[i], cs[l])\n                                if fourth == 1 {\n                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc main() {\n    combs := fourFaceCombs()\n    fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n    it3 := findIntransitive3(combs)\n    fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n    for _, a := range it3 {\n        fmt.Println(a)\n    }\n    it4 := findIntransitive4(combs)\n    fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n    for _, a := range it4 {\n        fmt.Println(a)\n    }\n}\n"}
{"id": 52410, "name": "History variables", "Java": "public class HistoryVariable\n{\n    private Object value;\n\n    public HistoryVariable(Object v)\n    {\n        value = v;\n    }\n\n    public void update(Object v)\n    {\n        value = v;\n    }\n\n    public Object undo()\n    {\n        return value;\n    }\n\n    @Override\n    public String toString()\n    {\n        return value.toString();\n    }\n\n    public void dispose()\n    {\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"sync\"\n    \"time\"\n)\n\n\ntype history struct {\n    timestamp tsFunc\n    hs        []hset\n}\n\n\ntype tsFunc func() time.Time\n\n\ntype hset struct {\n    int           \n    t   time.Time \n}\n\n\nfunc newHistory(ts tsFunc) history {\n    return history{ts, []hset{{t: ts()}}}\n}   \n    \n\nfunc (h history) int() int {\n    return h.hs[len(h.hs)-1].int\n}\n    \n\nfunc (h *history) set(x int) time.Time {\n    t := h.timestamp()\n    h.hs = append(h.hs, hset{x, t})\n    return t\n}\n\n\nfunc (h history) dump() {\n    for _, hs := range h.hs {\n        fmt.Println(hs.t.Format(time.StampNano), hs.int)\n    }\n}   \n    \n\n\nfunc (h history) recall(t time.Time) (int,  bool) {\n    i := sort.Search(len(h.hs), func(i int) bool {\n        return h.hs[i].t.After(t)\n    })\n    if i > 0 {\n        return h.hs[i-1].int, true\n    }\n    return 0, false\n}\n\n\n\n\n\nfunc newTimestamper() tsFunc {\n    var last time.Time\n    return func() time.Time {\n        if t := time.Now(); t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n        }\n        return last\n    }\n}\n\n\n\nfunc newProtectedTimestamper() tsFunc {\n    var last time.Time\n    var m sync.Mutex\n    return func() (t time.Time) {\n        t = time.Now()\n        m.Lock() \n        if t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n            t = last\n        }\n        m.Unlock()\n        return\n    }\n}\n\nfunc main() {\n    \n    ts := newTimestamper()\n    \n    h := newHistory(ts)\n    \n    ref := []time.Time{h.set(3), h.set(1), h.set(4)}\n    \n    fmt.Println(\"History of variable h:\")\n    h.dump() \n    \n    \n    fmt.Println(\"Recalling values:\")\n    for _, t := range ref {\n        rv, _ := h.recall(t)\n        fmt.Println(rv)\n    }\n}\n"}
{"id": 52411, "name": "Perceptron", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.util.*;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class Perceptron extends JPanel {\n\n    class Trainer {\n        double[] inputs;\n        int answer;\n\n        Trainer(double x, double y, int a) {\n            inputs = new double[]{x, y, 1};\n            answer = a;\n        }\n    }\n\n    Trainer[] training = new Trainer[2000];\n    double[] weights;\n    double c = 0.00001;\n    int count;\n\n    public Perceptron(int n) {\n        Random r = new Random();\n        Dimension dim = new Dimension(640, 360);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        weights = new double[n];\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] = r.nextDouble() * 2 - 1;\n        }\n\n        for (int i = 0; i < training.length; i++) {\n            double x = r.nextDouble() * dim.width;\n            double y = r.nextDouble() * dim.height;\n\n            int answer = y < f(x) ? -1 : 1;\n\n            training[i] = new Trainer(x, y, answer);\n        }\n\n        new Timer(10, (ActionEvent e) -> {\n            repaint();\n        }).start();\n    }\n\n    private double f(double x) {\n        return x * 0.7 + 40;\n    }\n\n    int feedForward(double[] inputs) {\n        assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n        double sum = 0;\n        for (int i = 0; i < weights.length; i++) {\n            sum += inputs[i] * weights[i];\n        }\n        return activate(sum);\n    }\n\n    int activate(double s) {\n        return s > 0 ? 1 : -1;\n    }\n\n    void train(double[] inputs, int desired) {\n        int guess = feedForward(inputs);\n        double error = desired - guess;\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] += c * error * inputs[i];\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        \n        int x = getWidth();\n        int y = (int) f(x);\n        g.setStroke(new BasicStroke(2));\n        g.setColor(Color.orange);\n        g.drawLine(0, (int) f(0), x, y);\n\n        train(training[count].inputs, training[count].answer);\n        count = (count + 1) % training.length;\n\n        g.setStroke(new BasicStroke(1));\n        g.setColor(Color.black);\n        for (int i = 0; i < count; i++) {\n            int guess = feedForward(training[i].inputs);\n\n            x = (int) training[i].inputs[0] - 4;\n            y = (int) training[i].inputs[1] - 4;\n\n            if (guess > 0)\n                g.drawOval(x, y, 8, 8);\n            else\n                g.fillOval(x, y, 8, 8);\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(\"Perceptron\");\n            f.setResizable(false);\n            f.add(new Perceptron(3), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst c = 0.00001\n\nfunc linear(x float64) float64 {\n    return x*0.7 + 40\n}\n\ntype trainer struct {\n    inputs []float64\n    answer int\n}\n\nfunc newTrainer(x, y float64, a int) *trainer {\n    return &trainer{[]float64{x, y, 1}, a}\n}\n\ntype perceptron struct {\n    weights  []float64\n    training []*trainer\n}\n\nfunc newPerceptron(n, w, h int) *perceptron {\n    weights := make([]float64, n)\n    for i := 0; i < n; i++ {\n        weights[i] = rand.Float64()*2 - 1\n    }\n\n    training := make([]*trainer, 2000)\n    for i := 0; i < 2000; i++ {\n        x := rand.Float64() * float64(w)\n        y := rand.Float64() * float64(h)\n        answer := 1\n        if y < linear(x) {\n            answer = -1\n        }\n        training[i] = newTrainer(x, y, answer)\n    }\n    return &perceptron{weights, training}\n}\n\nfunc (p *perceptron) feedForward(inputs []float64) int {\n    if len(inputs) != len(p.weights) {\n        panic(\"weights and input length mismatch, program terminated\")\n    }\n    sum := 0.0\n    for i, w := range p.weights {\n        sum += inputs[i] * w\n    }\n    if sum > 0 {\n        return 1\n    }\n    return -1\n}\n\nfunc (p *perceptron) train(inputs []float64, desired int) {\n    guess := p.feedForward(inputs)\n    err := float64(desired - guess)\n    for i := range p.weights {\n        p.weights[i] += c * err * inputs[i]\n    }\n}\n\nfunc (p *perceptron) draw(dc *gg.Context, iterations int) {\n    le := len(p.training)\n    for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le {\n        p.train(p.training[count].inputs, p.training[count].answer)\n    }\n    x := float64(dc.Width())\n    y := linear(x)\n    dc.SetLineWidth(2)\n    dc.SetRGB255(0, 0, 0) \n    dc.DrawLine(0, linear(0), x, y)\n    dc.Stroke()\n    dc.SetLineWidth(1)\n    for i := 0; i < le; i++ {\n        guess := p.feedForward(p.training[i].inputs)\n        x := p.training[i].inputs[0] - 4\n        y := p.training[i].inputs[1] - 4\n        if guess > 0 {\n            dc.SetRGB(0, 0, 1) \n        } else {\n            dc.SetRGB(1, 0, 0) \n        }\n        dc.DrawCircle(x, y, 8)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    w, h := 640, 360\n    perc := newPerceptron(3, w, h)\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    perc.draw(dc, 2000)\n    dc.SavePNG(\"perceptron.png\")\n}\n"}
{"id": 52412, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 52413, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 52414, "name": "Pisano period", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class PisanoPeriod {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Print pisano(p^2) for every prime p lower than 15%n\");\n        for ( long i = 2 ; i < 15 ; i++ ) { \n            if ( isPrime(i) ) {\n                long n = i*i; \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(p) for every prime p lower than 180%n\");\n        for ( long n = 2 ; n < 180 ; n++ ) { \n            if ( isPrime(n) ) { \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(n) for every integer from 1 to 180%n\");\n        for ( long n = 1 ; n <= 180 ; n++ ) { \n            System.out.printf(\"%3d  \", pisano(n));\n            if ( n % 10 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n\n        \n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\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    \n    private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();\n    static {\n        PERIOD_MEMO.put(2L, 3L);\n        PERIOD_MEMO.put(3L, 8L);\n        PERIOD_MEMO.put(5L, 20L);        \n    }\n    \n    \n    private static long pisano(long n) {\n        if ( PERIOD_MEMO.containsKey(n) ) {\n            return PERIOD_MEMO.get(n);\n        }\n        if ( n == 1 ) {\n            return 1;\n        }\n        Map<Long,Long> factors = getFactors(n);\n        \n        \n        \n        if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {\n            long result = 3 * n / 2;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 4*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 6*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        List<Long> primes = new ArrayList<>(factors.keySet());\n        long prime = primes.get(0);\n        if ( factors.size() == 1 && factors.get(prime) == 1 ) {\n            List<Long> divisors = new ArrayList<>();\n            if ( n % 10 == 1 || n % 10 == 9 ) {\n                for ( long divisor : getDivisors(prime-1) ) {\n                    if ( divisor % 2 == 0 ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            else {\n                List<Long> pPlus1Divisors = getDivisors(prime+1);\n                for ( long divisor : getDivisors(2*prime+2) ) {\n                    if ( !  pPlus1Divisors.contains(divisor) ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            Collections.sort(divisors);\n            for ( long divisor : divisors ) {\n                if ( fibModIdentity(divisor, prime) ) {\n                    PERIOD_MEMO.put(prime, divisor);\n                    return divisor;\n                }\n            }\n            throw new RuntimeException(\"ERROR 144: Divisor not found.\");\n        }\n        long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);\n        for ( int i = 1 ; i < primes.size() ; i++ ) {\n            prime = primes.get(i);\n            period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));\n        }\n        PERIOD_MEMO.put(n, period);\n        return period;\n    }\n    \n    \n    private static boolean fibModIdentity(long n, long mod) {\n        long aRes = 0;\n        long bRes = 1;\n        long cRes = 1;\n        long aBase = 0;\n        long bBase = 1;\n        long cBase = 1;\n        while ( n > 0 ) {\n            if ( n % 2 == 1 ) {\n                long temp1 = 0, temp2 = 0, temp3 = 0;\n                if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {\n                    temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;\n                    temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;\n                    temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;\n                }\n                else {\n                    temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;\n                    temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;\n                    temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;\n                }\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            n >>= 1L;\n            long temp1 = 0, temp2 = 0, temp3 = 0; \n            if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {\n                temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;\n                temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;\n                temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;\n            }\n            else {\n                temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;\n                temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;\n                temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;\n            }\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;\n    }\n\n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        \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        \n        return x % modulus;\n    }\n\n    private static final List<Long> getDivisors(long number) {\n        List<Long> divisors = new ArrayList<>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                long div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n    public static long lcm(long a, long b) {\n        return a*b/gcd(a,b);\n    }\n\n    public 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 final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();\n    static {\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        factors.put(2L, 1L);\n        allFactors.put(2L, factors);\n    }\n\n    public static Long MAX_ALL_FACTORS = 100000L;\n\n    public static final Map<Long,Long> getFactors(Long number) {\n        if ( allFactors.containsKey(number) ) {\n            return allFactors.get(number);\n        }\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        if ( number % 2 == 0 ) {\n            Map<Long,Long> factorsdDivTwo = getFactors(number/2);\n            factors.putAll(factorsdDivTwo);\n            factors.merge(2L, 1L, (v1, v2) -> v1 + v2);\n            if ( number < MAX_ALL_FACTORS ) {\n                allFactors.put(number, factors);\n            }\n            return factors;\n        }\n        boolean prime = true;\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 3 ; i <= sqrt ; i += 2 ) {\n            if ( number % i == 0 ) {\n                prime = false;\n                factors.putAll(getFactors(number/i));\n                factors.merge(i, 1L, (v1, v2) -> v1 + v2);\n                if ( number < MAX_ALL_FACTORS ) {\n                    allFactors.put(number, factors);\n                }\n                return factors;\n            }\n        }\n        if ( prime ) {\n            factors.put(number, 1L);\n            if ( number < MAX_ALL_FACTORS ) { \n                allFactors.put(number, factors);\n            }\n        }\n        return factors;\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(a, b uint) uint {\n    if b == 0 {\n        return a\n    }\n    return gcd(b, a%b)\n}\n\nfunc lcm(a, b uint) uint {\n    return a / gcd(a, b) * b\n}\n\nfunc ipow(x, p uint) uint {\n    prod := uint(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\n\nfunc getPrimes(n uint) []uint {\n    var primes []uint\n    for i := uint(2); i <= n; i++ {\n        div := n / i\n        mod := n % i\n        for mod == 0 {\n            primes = append(primes, i)\n            n = div\n            div = n / i\n            mod = n % i\n        }\n    }\n    return primes\n}\n\n\nfunc isPrime(n uint) 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 := uint(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\n\nfunc pisanoPeriod(m uint) uint {\n    var p, c uint = 0, 1\n    for i := uint(0); i < m*m; i++ {\n        p, c = c, (p+c)%m\n        if p == 0 && c == 1 {\n            return i + 1\n        }\n    }\n    return 1\n}\n\n\nfunc pisanoPrime(p uint, k uint) uint {\n    if !isPrime(p) || k == 0 {\n        return 0 \n    }\n    return ipow(p, k-1) * pisanoPeriod(p)\n}\n\n\nfunc pisano(m uint) uint {\n    primes := getPrimes(m)\n    primePowers := make(map[uint]uint)\n    for _, p := range primes {\n        primePowers[p]++\n    }\n    var pps []uint\n    for k, v := range primePowers {\n        pps = append(pps, pisanoPrime(k, v))\n    }\n    if len(pps) == 0 {\n        return 1\n    }\n    if len(pps) == 1 {\n        return pps[0]\n    }    \n    f := pps[0]\n    for i := 1; i < len(pps); i++ {\n        f = lcm(f, pps[i])\n    }\n    return f\n}\n\nfunc main() {\n    for p := uint(2); p < 15; p++ {\n        pp := pisanoPrime(p, 2)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%2d: 2) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    for p := uint(2); p < 180; p++ {\n        pp := pisanoPrime(p, 1)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%3d: 1) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    fmt.Println(\"pisano(n) for integers 'n' from 1 to 180 are:\")\n    for n := uint(1); n <= 180; n++ {\n        fmt.Printf(\"%3d \", pisano(n))\n        if n != 1 && n%15 == 0 {\n            fmt.Println()\n        }\n    }    \n    fmt.Println()\n}\n"}
{"id": 52415, "name": "Railway circuit", "Java": "package railwaycircuit;\n\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.IntStream.range;\n\npublic class RailwayCircuit {\n    final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0;\n\n    static String normalize(int[] tracks) {\n        char[] a = new char[tracks.length];\n        for (int i = 0; i < a.length; i++)\n            a[i] = \"abc\".charAt(tracks[i] + 1);\n\n        \n        String norm = new String(a);\n        for (int i = 0, len = a.length; i < len; i++) {\n\n            String s = new String(a);\n            if (s.compareTo(norm) < 0)\n                norm = s;\n\n            char tmp = a[0];\n            for (int j = 1; j < a.length; j++)\n                a[j - 1] = a[j];\n            a[len - 1] = tmp;\n        }\n        return norm;\n    }\n\n    static boolean fullCircleStraight(int[] tracks, int nStraight) {\n        if (nStraight == 0)\n            return true;\n\n        \n        if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight)\n            return false;\n\n        \n        int[] straight = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == STRAIGHT)\n                straight[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6])\n                && range(0, 8).anyMatch(i -> straight[i] != straight[i + 4]));\n    }\n\n    static boolean fullCircleRight(int[] tracks) {\n\n        \n        if (stream(tracks).map(i -> i * 30).sum() % 360 != 0)\n            return false;\n\n        \n        int[] rTurns = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == RIGHT)\n                rTurns[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6])\n                && range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4]));\n    }\n\n    static void circuits(int nCurved, int nStraight) {\n        Map<String, int[]> solutions = new HashMap<>();\n\n        PermutationsGen gen = getPermutationsGen(nCurved, nStraight);\n        while (gen.hasNext()) {\n\n            int[] tracks = gen.next();\n\n            if (!fullCircleStraight(tracks, nStraight))\n                continue;\n\n            if (!fullCircleRight(tracks))\n                continue;\n\n            solutions.put(normalize(tracks), tracks.clone());\n        }\n        report(solutions, nCurved, nStraight);\n    }\n\n    static PermutationsGen getPermutationsGen(int nCurved, int nStraight) {\n        assert (nCurved + nStraight - 12) % 4 == 0 : \"input must be 12 + k * 4\";\n\n        int[] trackTypes = new int[]{RIGHT, LEFT};\n\n        if (nStraight != 0) {\n            if (nCurved == 12)\n                trackTypes = new int[]{RIGHT, STRAIGHT};\n            else\n                trackTypes = new int[]{RIGHT, LEFT, STRAIGHT};\n        }\n\n        return new PermutationsGen(nCurved + nStraight, trackTypes);\n    }\n\n    static void report(Map<String, int[]> sol, int numC, int numS) {\n\n        int size = sol.size();\n        System.out.printf(\"%n%d solution(s) for C%d,%d %n\", size, numC, numS);\n\n        if (size < 10)\n            sol.values().stream().forEach(tracks -> {\n                stream(tracks).forEach(i -> System.out.printf(\"%2d \", i));\n                System.out.println();\n            });\n    }\n\n    public static void main(String[] args) {\n        circuits(12, 0);\n        circuits(16, 0);\n        circuits(20, 0);\n        circuits(24, 0);\n        circuits(12, 4);\n    }\n}\n\nclass PermutationsGen {\n    \n    private int[] indices;\n    private int[] choices;\n    private int[] sequence;\n    private int carry;\n\n    PermutationsGen(int numPositions, int[] choices) {\n        indices = new int[numPositions];\n        sequence = new int[numPositions];\n        this.choices = choices;\n    }\n\n    int[] next() {\n        carry = 1;\n        \n        for (int i = 1; i < indices.length && carry > 0; i++) {\n            indices[i] += carry;\n            carry = 0;\n\n            if (indices[i] == choices.length) {\n                carry = 1;\n                indices[i] = 0;\n            }\n        }\n\n        for (int i = 0; i < indices.length; i++)\n            sequence[i] = choices[indices[i]];\n\n        return sequence;\n    }\n\n    boolean hasNext() {\n        return carry != 1;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    right    = 1\n    left     = -1\n    straight = 0\n)\n\nfunc normalize(tracks []int) string {\n    size := len(tracks)\n    a := make([]byte, size)\n    for i := 0; i < size; i++ {\n        a[i] = \"abc\"[tracks[i]+1]\n    }\n\n    \n\n    norm := string(a)\n    for i := 0; i < size; i++ {\n        s := string(a)\n        if s < norm {\n            norm = s\n        }\n        tmp := a[0]\n        copy(a, a[1:])\n        a[size-1] = tmp\n    }\n    return norm\n}\n\nfunc fullCircleStraight(tracks []int, nStraight int) bool {\n    if nStraight == 0 {\n        return true\n    }\n\n    \n    count := 0\n    for _, track := range tracks {\n        if track == straight {\n            count++\n        }\n    }\n    if count != nStraight {\n        return false\n    }\n\n    \n    var straightTracks [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == straight {\n            straightTracks[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if straightTracks[i] != straightTracks[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if straightTracks[i] != straightTracks[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc fullCircleRight(tracks []int) bool {\n    \n    sum := 0\n    for _, track := range tracks {\n        sum += track * 30\n    }\n    if sum%360 != 0 {\n        return false\n    }\n\n    \n    var rTurns [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == right {\n            rTurns[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if rTurns[i] != rTurns[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if rTurns[i] != rTurns[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc circuits(nCurved, nStraight int) {\n    solutions := make(map[string][]int)\n    gen := getPermutationsGen(nCurved, nStraight)\n    for gen.hasNext() {\n        tracks := gen.next()\n        if !fullCircleStraight(tracks, nStraight) {\n            continue\n        }\n        if !fullCircleRight(tracks) {\n            continue\n        }\n        tracks2 := make([]int, len(tracks))\n        copy(tracks2, tracks)\n        solutions[normalize(tracks)] = tracks2\n    }\n    report(solutions, nCurved, nStraight)\n}\n\nfunc getPermutationsGen(nCurved, nStraight int) PermutationsGen {\n    if (nCurved+nStraight-12)%4 != 0 {\n        panic(\"input must be 12 + k * 4\")\n    }\n    var trackTypes []int\n    switch nStraight {\n    case 0:\n        trackTypes = []int{right, left}\n    case 12:\n        trackTypes = []int{right, straight}\n    default:\n        trackTypes = []int{right, left, straight}\n    }\n    return NewPermutationsGen(nCurved+nStraight, trackTypes)\n}\n\nfunc report(sol map[string][]int, numC, numS int) {\n    size := len(sol)\n    fmt.Printf(\"\\n%d solution(s) for C%d,%d \\n\", size, numC, numS)\n    if numC <= 20 {\n        for _, tracks := range sol {\n            for _, track := range tracks {\n                fmt.Printf(\"%2d \", track)\n            }\n            fmt.Println()\n        }\n    }\n}\n\n\ntype PermutationsGen struct {\n    NumPositions int\n    choices      []int\n    indices      []int\n    sequence     []int\n    carry        int\n}\n\nfunc NewPermutationsGen(numPositions int, choices []int) PermutationsGen {\n    indices := make([]int, numPositions)\n    sequence := make([]int, numPositions)\n    carry := 0\n    return PermutationsGen{numPositions, choices, indices, sequence, carry}\n}\n\nfunc (p *PermutationsGen) next() []int {\n    p.carry = 1\n\n    \n    for i := 1; i < len(p.indices) && p.carry > 0; i++ {\n        p.indices[i] += p.carry\n        p.carry = 0\n        if p.indices[i] == len(p.choices) {\n            p.carry = 1\n            p.indices[i] = 0\n        }\n    }\n    for j := 0; j < len(p.indices); j++ {\n        p.sequence[j] = p.choices[p.indices[j]]\n    }\n    return p.sequence\n}\n\nfunc (p *PermutationsGen) hasNext() bool {\n    return p.carry != 1\n}\n\nfunc main() {\n    for n := 12; n <= 28; n += 4 {\n        circuits(n, 0)\n    }\n    circuits(12, 4)\n}\n"}
{"id": 52416, "name": "Free polyominoes enumeration", "Java": "import java.awt.Point;\nimport java.util.*;\nimport static java.util.Arrays.asList;\nimport java.util.function.Function;\nimport static java.util.Comparator.comparing;\nimport static java.util.stream.Collectors.toList;\n\npublic class FreePolyominoesEnum {\n    static final List<Function<Point, Point>> transforms = new ArrayList<>();\n\n    static {\n        transforms.add(p -> new Point(p.y, -p.x));\n        transforms.add(p -> new Point(-p.x, -p.y));\n        transforms.add(p -> new Point(-p.y, p.x));\n        transforms.add(p -> new Point(-p.x, p.y));\n        transforms.add(p -> new Point(-p.y, -p.x));\n        transforms.add(p -> new Point(p.x, -p.y));\n        transforms.add(p -> new Point(p.y, p.x));\n    }\n\n    static Point findMinima(List<Point> poly) {\n        return new Point(\n                poly.stream().mapToInt(a -> a.x).min().getAsInt(),\n                poly.stream().mapToInt(a -> a.y).min().getAsInt());\n    }\n\n    static List<Point> translateToOrigin(List<Point> poly) {\n        final Point min = findMinima(poly);\n        poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));\n        return poly;\n    }\n\n    static List<List<Point>> rotationsAndReflections(List<Point> poly) {\n        List<List<Point>> lst = new ArrayList<>();\n        lst.add(poly);\n        for (Function<Point, Point> t : transforms)\n            lst.add(poly.stream().map(t).collect(toList()));\n        return lst;\n    }\n\n    static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)\n            .thenComparingInt(p -> p.y);\n\n    static List<Point> normalize(List<Point> poly) {\n        return rotationsAndReflections(poly).stream()\n                .map(lst -> translateToOrigin(lst))\n                .map(lst -> lst.stream().sorted(byCoords).collect(toList()))\n                .min(comparing(Object::toString)) \n                .get();\n    }\n\n    static List<Point> neighborhoods(Point p) {\n        return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),\n                new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));\n    }\n\n    static List<Point> concat(List<Point> lst, Point pt) {\n        List<Point> r = new ArrayList<>();\n        r.addAll(lst);\n        r.add(pt);\n        return r;\n    }\n\n    static List<Point> newPoints(List<Point> poly) {\n        return poly.stream()\n                .flatMap(p -> neighborhoods(p).stream())\n                .filter(p -> !poly.contains(p))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> constructNextRank(List<Point> poly) {\n        return newPoints(poly).stream()\n                .map(p -> normalize(concat(poly, p)))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> rank(int n) {\n        if (n < 0)\n            throw new IllegalArgumentException(\"n cannot be negative\");\n\n        if (n < 2) {\n            List<List<Point>> r = new ArrayList<>();\n            if (n == 1)\n                r.add(asList(new Point(0, 0)));\n            return r;\n        }\n\n        return rank(n - 1).stream()\n                .parallel()\n                .flatMap(lst -> constructNextRank(lst).stream())\n                .distinct()\n                .collect(toList());\n    }\n\n    public static void main(String[] args) {\n        for (List<Point> poly : rank(5)) {\n            for (Point p : poly)\n                System.out.printf(\"(%d,%d) \", p.x, p.y);\n            System.out.println();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype point struct{ x, y int }\ntype polyomino []point\ntype pointset map[point]bool\n\nfunc (p point) rotate90() point  { return point{p.y, -p.x} }\nfunc (p point) rotate180() point { return point{-p.x, -p.y} }\nfunc (p point) rotate270() point { return point{-p.y, p.x} }\nfunc (p point) reflect() point   { return point{-p.x, p.y} }\n\nfunc (p point) String() string { return fmt.Sprintf(\"(%d, %d)\", p.x, p.y) }\n\n\nfunc (p point) contiguous() polyomino {\n    return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y},\n        point{p.x, p.y - 1}, point{p.x, p.y + 1}}\n}\n\n\nfunc (po polyomino) minima() (int, int) {\n    minx := po[0].x\n    miny := po[0].y\n    for i := 1; i < len(po); i++ {\n        if po[i].x < minx {\n            minx = po[i].x\n        }\n        if po[i].y < miny {\n            miny = po[i].y\n        }\n    }\n    return minx, miny\n}\n\nfunc (po polyomino) translateToOrigin() polyomino {\n    minx, miny := po.minima()\n    res := make(polyomino, len(po))\n    for i, p := range po {\n        res[i] = point{p.x - minx, p.y - miny}\n    }\n    sort.Slice(res, func(i, j int) bool {\n        return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y)\n    })\n    return res\n}\n\n\nfunc (po polyomino) rotationsAndReflections() []polyomino {\n    rr := make([]polyomino, 8)\n    for i := 0; i < 8; i++ {\n        rr[i] = make(polyomino, len(po))\n    }\n    copy(rr[0], po)\n    for j := 0; j < len(po); j++ {\n        rr[1][j] = po[j].rotate90()\n        rr[2][j] = po[j].rotate180()\n        rr[3][j] = po[j].rotate270()\n        rr[4][j] = po[j].reflect()\n        rr[5][j] = po[j].rotate90().reflect()\n        rr[6][j] = po[j].rotate180().reflect()\n        rr[7][j] = po[j].rotate270().reflect()\n    }\n    return rr\n}\n\nfunc (po polyomino) canonical() polyomino {\n    rr := po.rotationsAndReflections()\n    minr := rr[0].translateToOrigin()\n    mins := minr.String()\n    for i := 1; i < 8; i++ {\n        r := rr[i].translateToOrigin()\n        s := r.String()\n        if s < mins {\n            minr = r\n            mins = s\n        }\n    }\n    return minr\n}\n\nfunc (po polyomino) String() string {\n    return fmt.Sprintf(\"%v\", []point(po))\n}\n\nfunc (po polyomino) toPointset() pointset {\n    pset := make(pointset, len(po))\n    for _, p := range po {\n        pset[p] = true\n    }\n    return pset\n}\n\n\nfunc (po polyomino) newPoints() polyomino {\n    pset := po.toPointset()\n    m := make(pointset) \n    for _, p := range po {\n        pts := p.contiguous()\n        for _, pt := range pts {\n            if !pset[pt] {\n                m[pt] = true \n            }\n        }\n    }\n    poly := make(polyomino, 0, len(m))\n    for k := range m {\n        poly = append(poly, k)\n    }\n    return poly\n}\n\nfunc (po polyomino) newPolys() []polyomino {\n    pts := po.newPoints()\n    res := make([]polyomino, len(pts))\n    for i, pt := range pts {\n        poly := make(polyomino, len(po))\n        copy(poly, po)\n        poly = append(poly, pt)\n        res[i] = poly.canonical()\n    }\n    return res\n}\n\nvar monomino = polyomino{point{0, 0}}\nvar monominoes = []polyomino{monomino}\n\n\nfunc rank(n int) []polyomino {\n    switch {\n    case n < 0:\n        panic(\"n cannot be negative. Program terminated.\")\n    case n == 0:\n        return []polyomino{}\n    case n == 1:\n        return monominoes\n    default:\n        r := rank(n - 1)\n        m := make(map[string]bool)\n        var polys []polyomino\n        for _, po := range r {\n            for _, po2 := range po.newPolys() {\n                if s := po2.String(); !m[s] {\n                    polys = append(polys, po2)\n                    m[s] = true\n                }\n            }\n        }\n        sort.Slice(polys, func(i, j int) bool {\n            return polys[i].String() < polys[j].String()\n        })\n        return polys\n    }\n}\n\nfunc main() {\n    const n = 5\n    fmt.Printf(\"All free polyominoes of rank %d:\\n\\n\", n)\n    for _, poly := range rank(n) {\n        for _, pt := range poly {\n            fmt.Printf(\"%s \", pt)\n        }\n        fmt.Println()\n    }\n    const k = 10\n    fmt.Printf(\"\\nNumber of free polyominoes of ranks 1 to %d:\\n\", k)\n    for i := 1; i <= k; i++ {\n        fmt.Printf(\"%d \", len(rank(i)))\n    }\n    fmt.Println()\n}\n"}
{"id": 52417, "name": "Use a REST API", "Java": "package src;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.net.URI;\n\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\n\n\n\npublic class EventGetter {\n\t\n\n\tString city = \"\";\n\tString topic = \"\";\n\t\n\tpublic String getEvent(String path_code,String key) throws Exception{\n\t\tString responseString = \"\";\n\t\t\n\t\tURI request = new URIBuilder()\t\t\t\n\t\t\t.setScheme(\"http\")\n\t\t\t.setHost(\"api.meetup.com\")\n\t\t\t.setPath(path_code)\n\t\t\t\n\t\t\t.setParameter(\"topic\", topic)\n\t\t\t.setParameter(\"city\", city)\n\t\t\t\n\t\t\t.setParameter(\"key\", key)\n\t\t\t.build();\n\t\t\n\t\tHttpGet get = new HttpGet(request);\t\t\t\n\t\tSystem.out.println(\"Get request : \"+get.toString());\n\t\t\n\t\tCloseableHttpClient client = HttpClients.createDefault();\n\t\tCloseableHttpResponse response = client.execute(get);\n\t\tresponseString = EntityUtils.toString(response.getEntity());\n\t\t\n\t\treturn responseString;\n\t}\n\t\n\tpublic String getApiKey(String key_path){\n\t\tString key = \"\";\n\t\t\n\t\ttry{\n\t\t\tBufferedReader reader = new BufferedReader(new FileReader(key_path));\t\n\t\t\tkey = reader.readLine().toString();\t\t\t\t\t\t\t\t\t\n\t\t\treader.close();\n\t\t}\n\t\tcatch(Exception e){System.out.println(e.toString());}\n\t\t\n\t\treturn key;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t}\n\t\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar key string\n\nfunc init() {\n\t\n\t\n\tconst keyFile = \"api_key.txt\"\n\tf, err := os.Open(keyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkeydata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkey = strings.TrimSpace(string(keydata))\n}\n\ntype EventResponse struct {\n\tResults []Result\n\t\n}\n\ntype Result struct {\n\tID          string\n\tStatus      string\n\tName        string\n\tEventURL    string `json:\"event_url\"`\n\tDescription string\n\tTime        EventTime\n\t\n}\n\n\n\ntype EventTime struct{ time.Time }\n\nfunc (et *EventTime) UnmarshalJSON(data []byte) error {\n\tvar msec int64\n\tif err := json.Unmarshal(data, &msec); err != nil {\n\t\treturn err\n\t}\n\tet.Time = time.Unix(0, msec*int64(time.Millisecond))\n\treturn nil\n}\n\nfunc (et EventTime) MarshalJSON() ([]byte, error) {\n\tmsec := et.UnixNano() / int64(time.Millisecond)\n\treturn json.Marshal(msec)\n}\n\n\nfunc (r *Result) String() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintln(&b, \"ID:\", r.ID)\n\tfmt.Fprintln(&b, \"URL:\", r.EventURL)\n\tfmt.Fprintln(&b, \"Time:\", r.Time.Format(time.UnixDate))\n\td := r.Description\n\tconst limit = 65\n\tif len(d) > limit {\n\t\td = d[:limit-1] + \"…\"\n\t}\n\tfmt.Fprintln(&b, \"Description:\", d)\n\treturn b.String()\n}\n\nfunc main() {\n\tv := url.Values{\n\t\t\n\t\t\n\t\t\"topic\": []string{\"photo\"},\n\t\t\"time\":  []string{\",1w\"},\n\t\t\"key\":   []string{key},\n\t}\n\tu := url.URL{\n\t\tScheme:   \"http\",\n\t\tHost:     \"api.meetup.com\",\n\t\tPath:     \"2/open_events.json\",\n\t\tRawQuery: v.Encode(),\n\t}\n\t\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Println(\"HTTP Status:\", resp.Status)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\n\tvar buf bytes.Buffer\n\tif err = json.Indent(&buf, body, \"\", \"  \"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\n\n\tvar evresp EventResponse\n\tjson.Unmarshal(body, &evresp)\n\t\n\n\tfmt.Println(\"Got\", len(evresp.Results), \"events\")\n\tif len(evresp.Results) > 0 {\n\t\tfmt.Println(\"First event:\\n\", &evresp.Results[0])\n\t}\n}\n"}
{"id": 52418, "name": "Twelve statements", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 52419, "name": "Twelve statements", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 52420, "name": "Deming's funnel", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n"}
{"id": 52421, "name": "Deming's funnel", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n"}
{"id": 52422, "name": "Rosetta Code_Fix code tags", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\n\npublic class FixCodeTags \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tString sourcefile=args[0];\n\t\tString convertedfile=args[1];\n\t\tconvert(sourcefile,convertedfile);\n\t}\n\t\tstatic String[] languages = {\"abap\", \"actionscript\", \"actionscript3\",\n\t\t\t\"ada\", \"apache\", \"applescript\", \"apt_sources\", \"asm\", \"asp\",\n\t\t\t\"autoit\", \"avisynth\", \"bar\", \"bash\", \"basic4gl\", \"bf\",\n\t\t\t\"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\",\n\t\t\t\"cfm\", \"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\",\n\t\t\t\"d\", \"delphi\", \"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\",\n\t\t\t\"foo\", \"fortran\", \"freebasic\", \"genero\", \"gettext\", \"glsl\", \"gml\",\n\t\t\t\"gnuplot\", \"go\", \"groovy\", \"haskell\", \"hq9plus\", \"html4strict\",\n\t\t\t\"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\", \"java5\",\n\t\t\t\"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\",\n\t\t\t\"m68k\", \"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\",\n\t\t\t\"mysql\", \"nsis\", \"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\",\n\t\t\t\"oracle11\", \"oracle8\", \"pascal\", \"per\", \"perl\", \"php\", \"php-brief\",\n\t\t\t\"pic16\", \"pixelbender\", \"plsql\", \"povray\", \"powershell\",\n\t\t\t\"progress\", \"prolog\", \"providex\", \"python\", \"qbasic\", \"rails\",\n\t\t\t\"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\", \"scilab\",\n\t\t\t\"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\",\n\t\t\t\"verilog\", \"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\",\n\t\t\t\"whitespace\", \"winbatch\", \"xml\", \"xorg_conf\", \"xpp\", \"z80\"};\n\tstatic void convert(String sourcefile,String convertedfile)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedReader br=new BufferedReader(new FileReader(sourcefile));\n\t\t\t\n\t\t\tStringBuffer sb=new StringBuffer(\"\");\n\t\t\tString line;\n\t\t\twhile((line=br.readLine())!=null)\n\t\t\t{\n\t\t\t\tfor(int i=0;i<languages.length;i++)\n\t\t\t\t{\n\t\t\t\t\tString lang=languages[i];\n\t\t\t\t\tline=line.replaceAll(\"<\"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</\"+lang+\">\", \"</\"+\"lang>\");\n\t\t\t\t\tline=line.replaceAll(\"<code \"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</code>\", \"</\"+\"lang>\");\n\t\t\t\t}\n\t\t\t\tsb.append(line);\n\t\t\t}\n\t\t\tbr.close();\n\t\t\t\n\t\t\tFileWriter fw=new FileWriter(new File(convertedfile));\n\t\t\t\n\t\t\tfw.write(sb.toString());\n\t\t\tfw.close();\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tSystem.out.println(\"Something went horribly wrong: \"+e.getMessage());\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"log\"\nimport \"os\"\nimport \"regexp\"\nimport \"strings\"\n\nfunc main() {\n\terr := fix()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc fix() (err error) {\n\tbuf, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, err := Lang(string(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(out)\n\treturn nil\n}\n\nfunc Lang(in string) (out string, err error) {\n\treg := regexp.MustCompile(\"<[^>]+>\")\n\tout = reg.ReplaceAllStringFunc(in, repl)\n\treturn out, nil\n}\n\nfunc repl(in string) (out string) {\n\tif in == \"</code>\" {\n\t\t\n\t\treturn \"</\"+\"lang>\"\n\t}\n\n\t\n\tmid := in[1 : len(in)-1]\n\n\t\n\tvar langs = []string{\n\t\t\"abap\", \"actionscript\", \"actionscript3\", \"ada\", \"apache\", \"applescript\",\n\t\t\"apt_sources\", \"asm\", \"asp\", \"autoit\", \"avisynth\", \"bash\", \"basic4gl\",\n\t\t\"bf\", \"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\", \"cfm\",\n\t\t\"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\", \"d\", \"delphi\",\n\t\t\"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\", \"fortran\", \"freebasic\",\n\t\t\"genero\", \"gettext\", \"glsl\", \"gml\", \"gnuplot\", \"go\", \"groovy\", \"haskell\",\n\t\t\"hq9plus\", \"html4strict\", \"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\",\n\t\t\"java5\", \"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\", \"m68k\",\n\t\t\"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\", \"mysql\", \"nsis\",\n\t\t\"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\", \"oracle11\", \"oracle8\", \"pascal\",\n\t\t\"per\", \"perl\", \"php\", \"php-brief\", \"pic16\", \"pixelbender\", \"plsql\",\n\t\t\"povray\", \"powershell\", \"progress\", \"prolog\", \"providex\", \"python\",\n\t\t\"qbasic\", \"rails\", \"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\",\n\t\t\"scilab\", \"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\", \"verilog\",\n\t\t\"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\", \"whitespace\", \"winbatch\",\n\t\t\"xml\", \"xorg_conf\", \"xpp\", \"z80\",\n\t}\n\tfor _, lang := range langs {\n\t\tif mid == lang {\n\t\t\t\n\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"/\") {\n\t\t\tif mid[len(\"/\"):] == lang {\n\t\t\t\t\n\t\t\t\treturn \"</\"+\"lang>\"\n\t\t\t}\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"code \") {\n\t\t\tif mid[len(\"code \"):] == lang {\n\t\t\t\t\n\t\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn in\n}\n"}
{"id": 52423, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 52424, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 52425, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 52426, "name": "Selective file copy", "Java": "import java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Scanner;\n\nclass CopysJ {\n\n  public static void main(String[] args) {\n    String ddname_IN  = \"copys.in.txt\";\n    String ddname_OUT = \"copys.out.txt\";\n    if (args.length >= 1) { ddname_IN  = args[0].length() > 0 ? args[0] : ddname_IN; }\n    if (args.length >= 2) { ddname_OUT = args[1].length() > 0 ? args[1] : ddname_OUT; }\n\n    File dd_IN = new File(ddname_IN);\n    File dd_OUT = new File(ddname_OUT);\n\n    try (\n      Scanner scanner_IN = new Scanner(dd_IN);\n      BufferedWriter writer_OUT = new BufferedWriter(new FileWriter(dd_OUT))\n      ) {\n      String a;\n      String b;\n      String c;\n      String d;\n      String c1;\n      String x = \"XXXXX\";\n      String data_IN;\n      String data_OUT;\n      int ib;\n\n      while (scanner_IN.hasNextLine()) {\n        data_IN = scanner_IN.nextLine();\n        ib = 0;\n        a = data_IN.substring(ib, ib += 5);\n        b = data_IN.substring(ib, ib += 5);\n        c = data_IN.substring(ib, ib += 4);\n        c1=Integer.toHexString(new Byte((c.getBytes())[0]).intValue());\n        if (c1.length()<2) { c1=\"0\" + c1; }\n        data_OUT = a + c1 + x;\n        writer_OUT.write(data_OUT);\n        writer_OUT.newLine();\n        System.out.println(data_IN);\n        System.out.println(data_OUT);\n        System.out.println();\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n    return;\n  }\n}\n", "Go": "package main\n\nimport (\n    \"encoding/json\"\n    \"log\"\n    \"os\"\n    \"bytes\"\n    \"errors\"\n    \"strings\"\n)\n\n\ntype s1 struct {\n    A string\n    B string\n    C int\n    D string\n}\n\n\ntype s2 struct {\n    A string\n    C intString \n    X string\n}\n\ntype intString string\n\nfunc (i *intString) UnmarshalJSON(b []byte) error {\n    if len(b) == 0 || bytes.IndexByte([]byte(\"0123456789-\"), b[0]) < 0 {\n        return errors.New(\"Unmarshal intString expected JSON number\")\n    }\n    *i = intString(b)\n    return nil\n}\n\n\nfunc NewS2() *s2 {\n    return &s2{X: \"XXXXX\"}\n}\n\nfunc main() {\n    \n    o1, err := os.Create(\"o1.json\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    e := json.NewEncoder(o1)\n    for i := 1; i <= 5; i++ {\n        err := e.Encode(s1{\n            strings.Repeat(\"A\", i),\n            strings.Repeat(\"B\", i),\n            i,\n            strings.Repeat(\"D\", i),\n        })\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    o1.Close()\n\n    \n    in, err := os.Open(\"o1.json\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    out, err := os.Create(\"out.json\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    \n    d := json.NewDecoder(in)\n    e = json.NewEncoder(out)\n    for d.More() {\n        \n        \n        \n        \n        s := NewS2()\n        if err = d.Decode(s); err != nil {\n            log.Fatal(err)\n        }\n        if err = e.Encode(s); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n"}
{"id": 52427, "name": "Idiomatically determine all the characters that can be used for symbols", "Java": "import java.util.function.IntPredicate;\nimport java.util.stream.IntStream;\n\npublic class Test {\n    public static void main(String[] args) throws Exception {\n        print(\"Java Identifier start:     \", 0, 0x10FFFF, 72,\n                Character::isJavaIdentifierStart, \"%c\");\n\n        print(\"Java Identifier part:      \", 0, 0x10FFFF, 25,\n                Character::isJavaIdentifierPart, \"[%d]\");\n\n        print(\"Identifier ignorable:      \", 0, 0x10FFFF, 25,\n                Character::isIdentifierIgnorable, \"[%d]\");\n\n        print(\"Unicode Identifier start:  \", 0, 0x10FFFF, 72,\n                Character::isUnicodeIdentifierStart, \"%c\");\n\n        print(\"Unicode Identifier part :  \", 0, 0x10FFFF, 25,\n                Character::isUnicodeIdentifierPart, \"[%d]\");\n    }\n\n    static void print(String msg, int start, int end, int limit, \n        IntPredicate p, String fmt) {\n\n        System.out.print(msg);\n        IntStream.rangeClosed(start, end)\n                .filter(p)\n                .limit(limit)\n                .forEach(cp -> System.out.printf(fmt, cp));\n        System.out.println(\"...\");\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"go/ast\"\n\t\"go/parser\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc isValidIdentifier(identifier string) bool {\n\tnode, err := parser.ParseExpr(identifier)\n\tif err != nil {\n\t\treturn false\n\t}\n\tident, ok := node.(*ast.Ident)\n\treturn ok && ident.Name == identifier\n}\n\ntype runeRanges struct {\n\tranges   []string\n\thasStart bool\n\tstart    rune\n\tend      rune\n}\n\nfunc (r *runeRanges) add(cp rune) {\n\tif !r.hasStart {\n\t\tr.hasStart = true\n\t\tr.start = cp\n\t\tr.end = cp\n\t\treturn\n\t}\n\n\tif cp == r.end+1 {\n\t\tr.end = cp\n\t\treturn\n\t}\n\n\tr.writeTo(&r.ranges)\n\n\tr.start = cp\n\tr.end = cp\n}\n\nfunc (r *runeRanges) writeTo(ranges *[]string) {\n\tif r.hasStart {\n\t\tif r.start == r.end {\n\t\t\t*ranges = append(*ranges, fmt.Sprintf(\"%U\", r.end))\n\t\t} else {\n\t\t\t*ranges = append(*ranges, fmt.Sprintf(\"%U-%U\", r.start, r.end))\n\t\t}\n\t}\n}\n\nfunc (r *runeRanges) String() string {\n\tranges := r.ranges\n\tr.writeTo(&ranges)\n\treturn strings.Join(ranges, \", \")\n}\n\nfunc main() {\n\tvar validFirst runeRanges\n\tvar validFollow runeRanges\n\tvar validOnlyFollow runeRanges\n\n\tfor r := rune(0); r <= unicode.MaxRune; r++ {\n\t\tfirst := isValidIdentifier(string([]rune{r}))\n\t\tfollow := isValidIdentifier(string([]rune{'_', r}))\n\t\tif first {\n\t\t\tvalidFirst.add(r)\n\t\t}\n\t\tif follow {\n\t\t\tvalidFollow.add(r)\n\t\t}\n\t\tif follow && !first {\n\t\t\tvalidOnlyFollow.add(r)\n\t\t}\n\t}\n\n\t_, _ = fmt.Println(\"Valid first:\", validFirst.String())\n\t_, _ = fmt.Println(\"Valid follow:\", validFollow.String())\n\t_, _ = fmt.Println(\"Only follow:\", validOnlyFollow.String())\n}\n"}
{"id": 52428, "name": "Assertions in design by contract", "Java": "(...)\nint feedForward(double[] inputs) {\n    assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n    double sum = 0;\n    for (int i = 0; i < weights.length; i++) {\n        sum += inputs[i] * weights[i];\n    }\n    return activate(sum);\n}\n(...)\n", "Go": "func assert(t bool, s string) {\n\tif !t {\n\t\tpanic(s)\n\t}\n}\n\n\tassert(c == 0, \"some text here\")\n"}
{"id": 52429, "name": "Assertions in design by contract", "Java": "(...)\nint feedForward(double[] inputs) {\n    assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n    double sum = 0;\n    for (int i = 0; i < weights.length; i++) {\n        sum += inputs[i] * weights[i];\n    }\n    return activate(sum);\n}\n(...)\n", "Go": "func assert(t bool, s string) {\n\tif !t {\n\t\tpanic(s)\n\t}\n}\n\n\tassert(c == 0, \"some text here\")\n"}
{"id": 52430, "name": "Quoting constructs", "Java": "module test\n    {\n    @Inject Console console;\n    void run()\n        {\n        \n        Char ch = 'x';\n        console.print( $\"ch={ch.quoted()}\");\n\n        \n        String greeting = \"Hello\";\n        console.print( $\"greeting={greeting.quoted()}\");\n\n        \n        \n        \n        String lines = \\|first line\n                        |second line\\\n                        | continued\n                       ;\n        console.print($|lines=\n                       |{lines}\n                     );\n\n        \n        \n        String name = \"Bob\";\n        String msg  = $|{greeting} {name},\n                       |Have a nice day!\n                       |{ch}{ch}{ch}\n                      ;\n        console.print($|msg=\n                       |{msg}\n                     );\n        }\n    }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n)\n\n\n\n\n\n\n\n\nvar (\n    rl1 = 'a'\n    rl2 = '\\'' \n)\n\n\n\nvar (\n    is1 = \"abc\"\n    is2 = \"\\\"ab\\tc\\\"\" \n)\n\n\n\n\n\n\n\nvar (\n    rs1 = `\nfirst\"\nsecond'\nthird\"\n`\n    rs2 = `This is one way of including a ` + \"`\" + ` in a raw string literal.`\n    rs3 = `\\d+` \n)\n\nfunc main() {\n    fmt.Println(rl1, rl2) \n    fmt.Println(is1, is2)\n    fmt.Println(rs1)\n    fmt.Println(rs2)\n    re := regexp.MustCompile(rs3)\n    fmt.Println(re.FindString(\"abcd1234efgh\"))\n\n    \n\n    \n    n := 3\n    fmt.Printf(\"\\nThere are %d quoting constructs in Go.\\n\", n)\n\n    \n    \n    s := \"constructs\"\n    fmt.Println(\"There are\", n, \"quoting\", s, \"in Go.\")\n\n    \n    \n    mapper := func(placeholder string) string {\n        switch placeholder {\n        case \"NUMBER\":\n            return strconv.Itoa(n)\n        case \"TYPES\":\n            return s\n        }\n        return \"\"\n    }\n    fmt.Println(os.Expand(\"There are ${NUMBER} quoting ${TYPES} in Go.\", mapper))\n}\n"}
{"id": 52431, "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": 52432, "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", "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": 52433, "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", "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": 52434, "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", "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": 52435, "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", "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": 52436, "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", "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": 52437, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\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": 52438, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\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": 52439, "name": "Checkpoint synchronization", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\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": 52440, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\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": 52441, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\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": 52442, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\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": 52443, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\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": 52444, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\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": 52445, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\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": 52446, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 52447, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 52448, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\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": 52449, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 52450, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\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": 52451, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\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": 52452, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \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": 52453, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\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": 52454, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\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": 52455, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\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": 52456, "name": "Sorting algorithms_Radix sort", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\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": 52457, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\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": 52458, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\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": 52459, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\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": 52460, "name": "Singleton", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\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": 52461, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\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": 52462, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 52463, "name": "Write entire file", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n"}
{"id": 52464, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 52465, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\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": 52466, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\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": 52467, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\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": 52468, "name": "Roots of unity", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\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": 52469, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 52470, "name": "Pell's equation", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\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": 52471, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\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": 52472, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\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": 52473, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 52474, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(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": 52475, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\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": 52476, "name": "Man or boy test", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\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": 52477, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\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": 52478, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 52479, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 52480, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n"}
{"id": 52481, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 52482, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 52483, "name": "Inverted index", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n"}
{"id": 52484, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 52485, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 52486, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 52487, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n"}
{"id": 52488, "name": "Descending primes", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n"}
{"id": 52489, "name": "Descending primes", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n"}
{"id": 52490, "name": "Sum and product puzzle", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n"}
{"id": 52491, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 52492, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 52493, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 52494, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 52495, "name": "Documentation", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n"}
{"id": 52496, "name": "Problem of Apollonius", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n"}
{"id": 52497, "name": "Chat server", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n"}
{"id": 52498, "name": "FASTA format", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n"}
{"id": 52499, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 52500, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 52501, "name": "Terminal control_Dimensions", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n"}
{"id": 52502, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 52503, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 52504, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 52505, "name": "Literals_String", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 52506, "name": "GUI_Maximum window dimensions", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n"}
{"id": 52507, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 52508, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 52509, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 52510, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n"}
{"id": 52511, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n"}
{"id": 52512, "name": "Maximum triangle path sum", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 52513, "name": "Terminal control_Cursor movement", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n"}
{"id": 52514, "name": "Terminal control_Cursor movement", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n"}
{"id": 52515, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 52516, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n"}
{"id": 52517, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 52518, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n"}
{"id": 52519, "name": "UTF-8 encode and decode", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n"}
{"id": 52520, "name": "Magic squares of doubly even order", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 52521, "name": "Same fringe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n"}
{"id": 52522, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n"}
{"id": 52523, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n"}
{"id": 52524, "name": "Peaceful chess queen armies", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n"}
{"id": 52525, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 52526, "name": "Sum of first n cubes", "C#": "using System; using static System.Console;\nclass Program { static void Main(string[] args) {\n    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)\n      Write(\"{0,-7}{1}\",s, (i+=i==3?-4:1)==0?\"\\n\":\" \"); } }\n", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n"}
{"id": 52527, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 52528, "name": "XML validation", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 52529, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 52530, "name": "Scope modifiers", "C#": "public \nprotected \ninternal \nprotected internal \nprivate \n\nprivate protected \n\n\n\n\n\n\n\n\n\n\n\n", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n"}
{"id": 52531, "name": "Brace expansion", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 52532, "name": "GUI component interaction", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n"}
{"id": 52533, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 52534, "name": "Addition chains", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n"}
{"id": 52535, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 52536, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 52537, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 52538, "name": "The sieve of Sundaram", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n"}
{"id": 52539, "name": "The sieve of Sundaram", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n"}
{"id": 52540, "name": "Chemical calculator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n"}
{"id": 52541, "name": "Active Directory_Connect", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n"}
{"id": 52542, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 52543, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 52544, "name": "Zebra puzzle", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n"}
{"id": 52545, "name": "Rosetta Code_Find unimplemented tasks", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n"}
{"id": 52546, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n"}
{"id": 52547, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n"}
{"id": 52548, "name": "Sokoban", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n"}
{"id": 52549, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 52550, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 52551, "name": "Practical numbers", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n"}
{"id": 52552, "name": "Consecutive primes with ascending or descending differences", "C#": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        const int mil = (int)1e6;\n        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n        {\n            int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n            var desc = new string[] { \"A\", \"\", \"De\" };\n            int[] mx = new int[] { 0, 0, 0 },\n                  bi = new int[] { 0, 0, 0 },\n                   c = new int[] { 2, 2, 2 };\n            WriteLine(\"For primes up to {0:n0}:\", lmt);\n            var pr = PG.Primes(lmt).ToArray();\n            for (int i = 0; i < pr.Length; i++)\n            {\n                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n                if (ld == d)\n                    c[2 - d]++;\n                else\n                {\n                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n                    c[d] = 2;\n                }\n                ld = d; lg = ng;\n            }\n            for (int r = 0; r <= 2; r += 2)\n            {\n                Write(\"{0}scending, found run of {1} consecutive primes:\\n  {2} \",\n                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n                    Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n            }\n        }\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<TG> Primes(int lim)\n    {\n        bool[] flags = new bool[lim + 1];\n        int j = 3, lj = 2;\n        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n            }\n        for (; j <= lim; j += 2)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n            }\n    }\n}\n", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n"}
{"id": 52553, "name": "Literals_Floating point", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 52554, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 52555, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n"}
{"id": 52556, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 52557, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 52558, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 52559, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 52560, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n"}
{"id": 52561, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 52562, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n"}
{"id": 52563, "name": "Word search", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n"}
{"id": 52564, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 52565, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 52566, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 52567, "name": "Object serialization", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n"}
{"id": 52568, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 52569, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 52570, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 52571, "name": "Zumkeller numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n"}
{"id": 52572, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 52573, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 52574, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 52575, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 52576, "name": "Markov chain text generator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n"}
{"id": 52577, "name": "Dijkstra's algorithm", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 52578, "name": "Geometric algebra", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n"}
{"id": 52579, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 52580, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n"}
{"id": 52581, "name": "Associative array_Iteration", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 52582, "name": "Define a primitive data type", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n"}
{"id": 52583, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 52584, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n"}
{"id": 52585, "name": "Hash join", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 52586, "name": "Odd squarefree semiprimes", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n"}
{"id": 52587, "name": "Odd squarefree semiprimes", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n"}
{"id": 52588, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 52589, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 52590, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n"}
{"id": 52591, "name": "Respond to an unknown method call", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n"}
{"id": 52592, "name": "Latin Squares in reduced form", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n"}
{"id": 52593, "name": "Closest-pair problem", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 52594, "name": "Address of a variable", "C#": "int i = 5;\nint* p = &i;\n", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n"}
{"id": 52595, "name": "Inheritance_Single", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 52596, "name": "Associative array_Creation", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 52597, "name": "Color wheel", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n"}
{"id": 52598, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 52599, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n"}
{"id": 52600, "name": "Rare numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nusing UI = System.UInt64;\nusing LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;\nusing Lst = System.Collections.Generic.List<sbyte>;\nusing DT = System.DateTime;\n\nclass Program {\n\n    const sbyte MxD = 19;\n\n    public struct term { public UI coeff; public sbyte a, b;\n        public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } }\n\n    static int[] digs;   static List<UI> res;   static sbyte count = 0;\n    static DT st; static List<List<term>> tLst; static List<LST> lists;\n    static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il;\n    static bool odd; static int nd, nd2; static LST ixs;\n    static int[] cnd, di; static LST dis; static UI Dif;\n\n    \n    static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++)\n            r = r * 10 + (uint)digs[i]; return r; }\n    \n    \n    static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--)\n            r = r * 10 + (uint)digs[i]; return Dif + (r << 1); }\n\n    \n    static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0)\n        { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; }\n\n    \n    static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst();\n        for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; }\n\n    \n    static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0];\n            digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1;\n            if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) {\n                digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; }\n            if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\",\n                (DT.Now - st).TotalMilliseconds, ++count, res.Last()); }\n        else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } }\n\n    \n    static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0;\n            foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]);\n                else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return;\n            dis = new LST { Seq(0, fml[cnd[0]].Count - 1) };\n            foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1));\n            if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0);\n        } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } }\n\n    static void init() { UI pow = 1;\n        \n        tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) {\n            List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1;\n            for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) {\n                terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; }\n            tLst.Add(terms); }\n        \n        fml = new Dictionary<int, LST> {\n            [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } },\n            [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } },\n            [4] = new LST { new Lst { 4, 0 } },\n            [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } };\n        \n        dmd = new Dictionary<int, LST>();\n        for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) {\n                if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j });\n                else dmd[d] = new LST { new Lst { i, j } }; }\n        dl = Seq(-9, 9);    \n        zl = Seq( 0, 0);    \n        el = Seq(-8, 8, 2); \n        ol = Seq(-9, 9, 2); \n        il = Seq( 0, 9); lists = new List<LST>();\n        foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); }\n\n    static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0;\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Unordered Rare Numbers\");\n        for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd];\n            if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); }\n            else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl);\n            ixs = new LST(); \n            foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b });\n            foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); }\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds); }\n        res.Sort();\n        WriteLine(\"\\nThe {0} rare numbers with up to {1} digits are:\", res.Count, MxD);\n        count = 0; foreach (var rare in res) WriteLine(\"{0,2}:{1,27:n0}\", ++count, rare);\n        if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }\n}\n", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n"}
{"id": 52601, "name": "Minesweeper game", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MineFieldModel\n{\n    public int RemainingMinesCount{\n        get{\n            var count = 0;\n            ForEachCell((i,j)=>{\n                if (Mines[i,j] && !Marked[i,j])\n                    count++;\n            });\n            return count;\n        }\n    }\n\n    public bool[,] Mines{get; private set;}\n    public bool[,] Opened{get;private set;}\n    public bool[,] Marked{get; private set;}\n    public int[,] Values{get;private set; }\n    public int Width{ get{return Mines.GetLength(1);} } \n    public int Height{ get{return Mines.GetLength(0);} }\n\n    public MineFieldModel(bool[,] mines)\n    {\n        this.Mines = mines;\n        this.Opened = new bool[Height, Width]; \n        this.Marked = new bool[Height, Width];\n        this.Values = CalculateValues();\n    }\n    \n    private int[,] CalculateValues()\n    {\n        int[,] values = new int[Height, Width];\n        ForEachCell((i,j) =>{\n            var value = 0;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (Mines[i1,j1])\n                    value++;\n            });\n            values[i,j] = value;\n        });\n        return values;\n    }\n\n    \n    public void ForEachCell(Action<int,int> action)\n    {\n        for (var i = 0; i < Height; i++)\n        for (var j = 0; j < Width; j++)\n            action(i,j);\n    }\n\n    \n    public void ForEachNeighbor(int i, int j, Action<int,int> action)\n    {\n        for (var i1 = i-1; i1 <= i+1; i1++)\n        for (var j1 = j-1; j1 <= j+1; j1++)               \n            if (InBounds(j1, i1) && !(i1==i && j1 ==j))\n                action(i1, j1);\n    }\n\n    private bool InBounds(int x, int y)\n    {\n        return y >= 0 && y < Height && x >=0 && x < Width;\n    }\n\n    public event Action Exploded = delegate{};\n    public event Action Win = delegate{};\n    public event Action Updated = delegate{};\n\n    public void OpenCell(int i, int j){\n        if(!Opened[i,j]){\n            if (Mines[i,j])\n                Exploded();\n            else{\n                OpenCellsStartingFrom(i,j);\n                Updated();\n                CheckForVictory();\n            }\n        }\n    }\n\n    void OpenCellsStartingFrom(int i, int j)\n    {\n            Opened[i,j] = true;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1])\n                    OpenCellsStartingFrom(i1, j1);\n            });\n    }\n    \n    void CheckForVictory(){\n        int notMarked = 0;\n        int wrongMarked = 0;\n        ForEachCell((i,j)=>{\n            if (Mines[i,j] && !Marked[i,j])\n                notMarked++;\n            if (!Mines[i,j] && Marked[i,j])\n                wrongMarked++;\n        }); \n        if (notMarked == 0 && wrongMarked == 0)\n            Win();\n    }\n\n    public void Mark(int i, int j){\n        if (!Opened[i,j])\n            Marked[i,j] = true;\n            Updated();\n            CheckForVictory();\n    }\n}\n\nclass MineFieldView: UserControl{\n    public const int CellSize = 40;\n\n    MineFieldModel _model;\n    public MineFieldModel Model{\n        get{ return _model; }\n        set\n        { \n            _model = value; \n            this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2);\n        }\n    }\n    \n    public MineFieldView(){\n        \n        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true);\n        this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);\n\n        this.MouseUp += (o,e)=>{\n            Point cellCoords = GetCell(e.Location);\n            if (Model != null)\n            {\n                if (e.Button == MouseButtons.Left)\n                    Model.OpenCell(cellCoords.Y, cellCoords.X);\n                else if (e.Button == MouseButtons.Right)\n                    Model.Mark(cellCoords.Y, cellCoords.X);\n            }\n        };\n    }\n\n    Point GetCell(Point coords)\n    {\n        var rgn = ClientRectangle;\n        var x = (coords.X - rgn.X)/CellSize;\n        var y = (coords.Y - rgn.Y)/CellSize;\n        return new Point(x,y);\n    }\n         \n    static readonly Brush MarkBrush = new SolidBrush(Color.Blue);\n    static readonly Brush ValueBrush = new SolidBrush(Color.Black);\n    static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control);\n    static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark);\n\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        var g = e.Graphics;\n        if (Model != null)\n        {\n            Model.ForEachCell((i,j)=>\n            {\n                var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize);\n                if (Model.Opened[i,j])\n                {\n                    g.FillRectangle(OpenBrush, bounds);\n                    if (Model.Values[i,j] > 0)\n                    {\n                        DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds);\n                    }\n                } \n                else \n                {\n                    g.FillRectangle(UnexploredBrush, bounds);\n                    if (Model.Marked[i,j])\n                    {\n                        DrawStringInCenter(g, \"?\", MarkBrush, bounds);\n                    }\n                    var outlineOffset = 1;\n                    var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset);\n                    g.DrawRectangle(Pens.Gray, outline);\n                }\n                g.DrawRectangle(Pens.Black, bounds);\n            });\n        }\n\n    }\n\n    static readonly StringFormat FormatCenter = new StringFormat\n                            {\n                                LineAlignment = StringAlignment.Center,\n                                Alignment=StringAlignment.Center\n                            };\n\n    void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds)\n    {\n        PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2);\n        g.DrawString(s, this.Font, brush, center, FormatCenter);\n    }\n\n}\n\nclass MineSweepForm: Form\n{\n\n    MineFieldModel CreateField(int width, int height)\n{\n        var field = new bool[height, width];\n        int mineCount = (int)(0.2 * height * width);\n        var rnd = new Random();\n        while(mineCount > 0)\n        {\n            var x = rnd.Next(width);\n            var y = rnd.Next(height);\n            if (!field[y,x])\n            {\n                field[y,x] = true;\n                mineCount--;\n            }\n        }\n        return new MineFieldModel(field);\n    }\n\n    public MineSweepForm()\n    {\n        var model = CreateField(6, 4);\n        var counter = new Label{ };\n        counter.Text = model.RemainingMinesCount.ToString();\n        var view = new MineFieldView\n                        { \n                            Model = model, BorderStyle = BorderStyle.FixedSingle,\n                        };\n        var stackPanel = new FlowLayoutPanel\n                        {\n                            Dock = DockStyle.Fill,\n                            FlowDirection = FlowDirection.TopDown,\n                            Controls = {counter, view}\n                        };\n        this.Controls.Add(stackPanel);\n        model.Updated += delegate{\n            view.Invalidate();\n            counter.Text = model.RemainingMinesCount.ToString();\n        };\n        model.Exploded += delegate {\n            MessageBox.Show(\"FAIL!\");\n            Close();\n        };\n        model.Win += delegate {\n            MessageBox.Show(\"WIN!\");\n            view.Enabled = false;\n        };\n\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Application.Run(new MineSweepForm());\n    }\n}\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 52602, "name": "Primes with digits in nondecreasing order", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 52603, "name": "Primes with digits in nondecreasing order", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 52604, "name": "Reflection_List properties", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 52605, "name": "Reflection_List properties", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 52606, "name": "Minimal steps down to 1", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class MinimalSteps\n{\n    public static void Main() {\n        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });\n        var lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n        Console.WriteLine();\n\n        subtractors = new [] { 2 };\n        lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n    }\n\n    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {\n        for (int goal = 1; goal <= limit; goal++) {\n            var x = lookup[goal];\n            if (x.param == 0) {\n                Console.WriteLine($\"{goal} cannot be reached with these numbers.\");\n                continue;\n            }\n            Console.Write($\"{goal} takes {x.steps} {(x.steps == 1 ? \"step\" : \"steps\")}: \");\n            for (int n = goal; n > 1; ) {\n                Console.Write($\"{n},{x.op}{x.param}=> \");\n                n = x.op == '/' ? n / x.param : n - x.param;\n                x = lookup[n];\n            }\n            Console.WriteLine(\"1\");\n        }\n    }\n\n    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {\n        var maxSteps = lookup.Max(x => x.steps);\n        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();\n        Console.WriteLine(items.Count == 1\n            ? $\"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}\"\n            : $\"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}\"\n        );\n    }\n\n    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)\n    {\n        var lookup = new (char op, int param, int steps)[goal+1];\n        lookup[1] = ('/', 1, 0);\n        for (int n = 1; n < lookup.Length; n++) {\n            var ln = lookup[n];\n            if (ln.param == 0) continue;\n            for (int d = 0; d < divisors.Length; d++) {\n                int target = n * divisors[d];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);\n            }\n            for (int s = 0; s < subtractors.Length; s++) {\n                int target = n + subtractors[s];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);\n            }\n        }\n        return lookup;\n    }\n\n    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(\", \", source);\n}\n", "Python": "from functools import lru_cache\n\n\n\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n    \"Recursive, memoised minimised steps to 1\"\n\n    def __init__(self, divs=DIVS, subs=SUBS):\n        self.divs, self.subs = divs, subs\n\n    @lru_cache(maxsize=None)\n    def _minrec(self, n):\n        \"Recursive, memoised\"\n        if n == 1:\n            return 0, ['=1']\n        possibles = {}\n        for d in self.divs:\n            if n % d == 0:\n                possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n        for s in self.subs:\n            if n > s:\n                possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n        thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n        ret = 1 + count, [thiskind] + otherkinds\n        return ret\n\n    def __call__(self, n):\n        \"Recursive, memoised\"\n        ans = self._minrec(n)[1][:-1]\n        return len(ans), ans\n\n\nif __name__ == '__main__':\n    for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n        minrec = Minrec(DIVS, SUBS)\n        print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n        print('  Possible divisors:  ', DIVS)\n        print('  Possible decrements:', SUBS)\n        for n in range(1, 11):\n            steps, how = minrec(n)\n            print(f'    minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n        upto = 2000\n        print(f'\\n    Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n        stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n        mx = stepn[-1][0]\n        ans = [x[1] for x in stepn if x[0] == mx]\n        print('      Taking', mx, f'steps is/are the {len(ans)} numbers:',\n              ', '.join(str(n) for n in sorted(ans)))\n        \n        print()\n"}
{"id": 52607, "name": "Align columns", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 52608, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 52609, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 52610, "name": "Idoneal numbers", "C#": "using System;\n\nclass Program {\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int a, b, c, i, n, s3, ab; var res = new int[65];\n    for (n = 1, i = 0; n < 1850; n++) {\n      bool found = true;\n      for (a = 1; a < n; a++)\n         for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {\n            if (ab > n) break;\n            for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {\n                if (s3 == n) found = false;\n                if (s3 >= n) break;\n            }\n         }\n      if (found) res[i++] = n;\n    }\n    sw.Stop();\n    Console.WriteLine(\"The 65 known Idoneal numbers:\");\n    for (i = 0; i < res.Length; i++)\n      Console.Write(\"{0,5}{1}\", res[i], i % 13 == 12 ? \"\\n\" : \"\");\n    Console.Write(\"Calculations took {0} ms\", sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "Python": "\n\n\ndef is_idoneal(num):\n    \n    for a in range(1, num):\n        for b in range(a + 1, num):\n            if a * b + a + b > num:\n                break\n            for c in range(b + 1, num):\n                sum3 = a * b + b * c + a * c\n                if sum3 == num:\n                    return False\n                if sum3 > num:\n                    break\n    return True\n\n\nrow = 0\nfor n in range(1, 2000):\n    if is_idoneal(n):\n        row += 1\n        print(f'{n:5}', end='\\n' if row % 13 == 0 else '')\n"}
{"id": 52611, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 52612, "name": "Base58Check encoding", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 52613, "name": "Dynamic variable names", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n"}
{"id": 52614, "name": "Fibonacci matrix-exponentiation", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n"}
{"id": 52615, "name": "Fibonacci matrix-exponentiation", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n"}
{"id": 52616, "name": "Largest palindrome product", "C#": "using System;\nclass Program {\n\n  static bool isPal(int n) {\n    int rev = 0, lr = -1, rem;\n    while (n > rev) {\n      n = Math.DivRem(n, 10, out rem);\n      if (lr < 0 && rem == 0) return false;\n      lr = rev; rev = 10 * rev + rem;\n      if (n == rev || n == lr) return true;\n    } return false; }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;\n    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = \"\";\n    y /= 11;\n    if ((y & 1) == 0) y--;\n    if (y % 5 == 0) y -= 2;\n    y *= 11;\n    while (y <= max) {\n      c = 0;\n      y10 = y * 10;\n      z = max9 + a[ld = y % 10];\n      p = y * z;\n      while (p >= bp) {\n        if (isPal(p)) {\n          if (p > bp) bp = p;\n          bs = string.Format(\"{0} x {1} = {2}\", y, z - c, bp);\n        }\n        p -= y10; c += 10;\n      }\n      y += ld == 3 ? 44 : 22;\n    }\n    sw.Stop();\n    Console.Write(\"{0} {1} μs\", bs, sw.Elapsed.TotalMilliseconds * 1000.0);\n  }\n}\n", "Python": "\n\nT=[set([(0, 0)])]\n\ndef double(it):\n    for a, b in it:\n        yield a, b\n        yield b, a\n\ndef tails(n):\n    \n    if len(T)<=n:\n        l = set()\n        for i in range(10):\n            for j in range(i, 10):\n                I = i*10**(n-1)\n                J = j*10**(n-1)\n                it = tails(n-1)\n                if I!=J: it = double(it)\n                for t1, t2 in it:\n                    if ((I+t1)*(J+t2)+1)%10**n == 0:\n                        l.add((I+t1, J+t2))\n        T.append(l)\n    return T[n]\n\ndef largestPalindrome(n):\n    \n    m, tail = 0, n // 2\n    head = n - tail\n    up = 10**head\n    for L in range(1, 9*10**(head-1)+1):\n        \n        m = 0\n        sol = None\n        for i in range(1, L + 1):\n            lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)\n            hi = int(up - (up - L)**2 / (up - i))\n            for j in range(lo, hi + 1):\n                I = (up-i) * 10**tail\n                J = (up-j) * 10**tail\n                it = tails(tail)\n                if I!=J: it = double(it)\n                    for t1, t2 in it:\n                        val = (I + t1)*(J + t2)\n                        s = str(val)\n                        if s == s[::-1] and val>m:\n                            sol = (I + t1, J + t2)\n                            m = val\n\n        if m:\n            print(\"{:2d}\\t{:4d}\".format(n, m % 1337), sol, sol[0] * sol[1])\n            return m % 1337\n    return 0\n\nif __name__ == \"__main__\":\n    for k in range(1, 14):\n        largestPalindrome(k)\n"}
{"id": 52617, "name": "Commatizing numbers", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n"}
{"id": 52618, "name": "Arithmetic coding_As a generalized change of radix", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n"}
{"id": 52619, "name": "Kosaraju", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n"}
{"id": 52620, "name": "Reflection_List methods", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n"}
{"id": 52621, "name": "Comments", "C#": "\n\n\n\n\n\n", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n"}
{"id": 52622, "name": "Pentomino tiling", "C#": "using System;\nusing System.Linq;\n\nnamespace PentominoTiling\n{\n    class Program\n    {\n        static readonly char[] symbols = \"FILNPTUVWXYZ-\".ToCharArray();\n\n        static readonly int nRows = 8;\n        static readonly int nCols = 8;\n        static readonly int target = 12;\n        static readonly int blank = 12;\n\n        static int[][] grid = new int[nRows][];\n        static bool[] placed = new bool[target];\n\n        static void Main(string[] args)\n        {\n            var rand = new Random();\n\n            for (int r = 0; r < nRows; r++)\n                grid[r] = Enumerable.Repeat(-1, nCols).ToArray();\n\n            for (int i = 0; i < 4; i++)\n            {\n                int randRow, randCol;\n                do\n                {\n                    randRow = rand.Next(nRows);\n                    randCol = rand.Next(nCols);\n                } \n                while (grid[randRow][randCol] == blank);\n\n                grid[randRow][randCol] = blank;\n            }\n\n            if (Solve(0, 0))\n            {\n                PrintResult();\n            }\n            else\n            {\n                Console.WriteLine(\"no solution\");\n            }\n\n            Console.ReadKey();\n        }\n\n        private static void PrintResult()\n        {\n            foreach (int[] r in grid)\n            {\n                foreach (int i in r)\n                    Console.Write(\"{0} \", symbols[i]);\n                Console.WriteLine();\n            }\n        }\n\n        private static bool Solve(int pos, int numPlaced)\n        {\n            if (numPlaced == target)\n                return true;\n\n            int row = pos / nCols;\n            int col = pos % nCols;\n\n            if (grid[row][col] != -1)\n                return Solve(pos + 1, numPlaced);\n\n            for (int i = 0; i < shapes.Length; i++)\n            {\n                if (!placed[i])\n                {\n                    foreach (int[] orientation in shapes[i])\n                    {\n                        if (!TryPlaceOrientation(orientation, row, col, i))\n                            continue;\n\n                        placed[i] = true;\n\n                        if (Solve(pos + 1, numPlaced + 1))\n                            return true;\n\n                        RemoveOrientation(orientation, row, col);\n                        placed[i] = false;\n                    }\n                }\n            }\n            return false;\n        }\n\n        private static void RemoveOrientation(int[] orientation, int row, int col)\n        {\n            grid[row][col] = -1;\n            for (int i = 0; i < orientation.Length; i += 2)\n                grid[row + orientation[i]][col + orientation[i + 1]] = -1;\n        }\n\n        private static bool TryPlaceOrientation(int[] orientation, int row, int col, int shapeIndex)\n        {\n            for (int i = 0; i < orientation.Length; i += 2)\n            {\n                int x = col + orientation[i + 1];\n                int y = row + orientation[i];\n                if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                    return false;\n            }\n\n            grid[row][col] = shapeIndex;\n            for (int i = 0; i < orientation.Length; i += 2)\n                grid[row + orientation[i]][col + orientation[i + 1]] = shapeIndex;\n\n            return true;\n        }\n\n        \n        static readonly int[][] F = {\n            new int[] {1, -1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 2, 0},\n            new int[] {1, 0, 1, 1, 1, 2, 2, 1}, new int[] {1, 0, 1, 1, 2, -1, 2, 0},\n            new int[] {1, -2, 1, -1, 1, 0, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 1},\n            new int[] {1, -1, 1, 0, 1, 1, 2, -1}, new int[] {1, -1, 1, 0, 2, 0, 2, 1}};\n\n        static readonly int[][] I = {\n            new int[] { 0, 1, 0, 2, 0, 3, 0, 4 }, new int[] { 1, 0, 2, 0, 3, 0, 4, 0 } };\n\n        static readonly int[][] L = {\n            new int[] {1, 0, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, 0, 3, -1, 3, 0},\n            new int[] {0, 1, 0, 2, 0, 3, 1, 3}, new int[] {0, 1, 1, 0, 2, 0, 3, 0},\n            new int[] {0, 1, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 0, 3, 1, 0},\n            new int[] {1, 0, 2, 0, 3, 0, 3, 1}, new int[] {1, -3, 1, -2, 1, -1, 1, 0}};\n\n        static readonly int[][] N = {\n            new int[] {0, 1, 1, -2, 1, -1, 1, 0}, new int[] {1, 0, 1, 1, 2, 1, 3, 1},\n            new int[]  {0, 1, 0, 2, 1, -1, 1, 0}, new int[] {1, 0, 2, 0, 2, 1, 3, 1},\n            new int[] {0, 1, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, -1, 2, 0, 3, -1},\n            new int[] {0, 1, 0, 2, 1, 2, 1, 3}, new int[] {1, -1, 1, 0, 2, -1, 3, -1}};\n\n        static readonly int[][] P = {\n            new int[] {0, 1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 0, 2, 1, 0, 1, 1},\n            new int[] {1, 0, 1, 1, 2, 0, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 1, 1},\n            new int[] {0, 1, 1, 0, 1, 1, 1, 2}, new int[] {1, -1, 1, 0, 2, -1, 2, 0},\n            new int[] {0, 1, 0, 2, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 1, 1, 2, 0}};\n\n        static readonly int[][] T = {\n            new int[] {0, 1, 0, 2, 1, 1, 2, 1}, new int[] {1, -2, 1, -1, 1, 0, 2, 0},\n            new int[] {1, 0, 2, -1, 2, 0, 2, 1}, new int[] {1, 0, 1, 1, 1, 2, 2, 0}};\n\n        static readonly int[][] U = {\n            new int[] {0, 1, 0, 2, 1, 0, 1, 2}, new int[] {0, 1, 1, 1, 2, 0, 2, 1},\n            new int[]  {0, 2, 1, 0, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 2, 0, 2, 1}};\n\n        static readonly int[][] V = {\n            new int[] {1, 0, 2, 0, 2, 1, 2, 2}, new int[] {0, 1, 0, 2, 1, 0, 2, 0},\n            new int[] {1, 0, 2, -2, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 2, 2, 2}};\n\n        static readonly int[][] W = {\n            new int[] {1, 0, 1, 1, 2, 1, 2, 2}, new int[] {1, -1, 1, 0, 2, -2, 2, -1},\n            new int[] {0, 1, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, -1, 1, 0, 2, -1}};\n\n        static readonly int[][] X = { new int[] { 1, -1, 1, 0, 1, 1, 2, 0 } };\n\n        static readonly int[][] Y = {\n            new int[] {1, -2, 1, -1, 1, 0, 1, 1}, new int[] {1, -1, 1, 0, 2, 0, 3, 0},\n            new int[] {0, 1, 0, 2, 0, 3, 1, 1}, new int[] {1, 0, 2, 0, 2, 1, 3, 0},\n            new int[] {0, 1, 0, 2, 0, 3, 1, 2}, new int[] {1, 0, 1, 1, 2, 0, 3, 0},\n            new int[] {1, -1, 1, 0, 1, 1, 1, 2}, new int[] {1, 0, 2, -1, 2, 0, 3, 0}};\n\n        static readonly int[][] Z = {\n            new int[] {0, 1, 1, 0, 2, -1, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 2},\n            new int[] {0, 1, 1, 1, 2, 1, 2, 2}, new int[] {1, -2, 1, -1, 1, 0, 2, -2}};\n\n        static readonly int[][][] shapes = { F, I, L, N, P, T, U, V, W, X, Y, Z };\n    }\n}\n", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n"}
{"id": 52623, "name": "Send an unknown method call", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n"}
{"id": 52624, "name": "Variables", "C#": "int j;\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 52625, "name": "Sieve of Pritchard", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program {\n\n    \n    static List<int> PrimesUpTo(int limit, bool verbose = false) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var members = new SortedSet<int>{ 1 };\n        int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1;\n        List<int> primes = new List<int>(), tl = new List<int>();\n        while (prime < rtlim) {\n            nl = Math.Min(prime * stp, limit);\n            if (stp < limit) {\n                tl.Clear(); \n                foreach (var w in members)\n                    for (n = w + stp; n <= nl; n += stp) tl.Add(n);\n                members.UnionWith(tl); ac += tl.Count;\n            }\n            stp = nl; \n            nxtpr = 5; \n            tl.Clear();\n            foreach (var w in members) {\n                if (nxtpr == 5 && w > prime) nxtpr = w;\n                if ((n = prime * w) > nl) break; else tl.Add(n);\n            }\n            foreach (var itm in tl) members.Remove(itm); rc += tl.Count;\n            primes.Add(prime);\n            prime = prime == 2 ? 3 : nxtpr;\n        }\n        members.Remove(1); primes.AddRange(members); sw.Stop();\n        if (verbose) Console.WriteLine(\"Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms\", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds);\n        return primes;\n    }\n\n    static void Main(string[] args) {\n        Console.WriteLine(\"[{0}]\", string.Join(\", \", PrimesUpTo(150, true)));\n        PrimesUpTo(1000000, true);\n    }\n}\n", "Python": "\n\nfrom numpy import ndarray\nfrom math import isqrt\n\n\ndef pritchard(limit):\n    \n    members = ndarray(limit + 1, dtype=bool)\n    members.fill(False)\n    members[1] = True\n    steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2\n    primes = []\n    while prime <= rtlim:\n        if steplength < limit:\n            for w in range(1, len(members)):\n                if members[w]:\n                    n = w + steplength\n                    while n <= nlimit:\n                        members[n] = True\n                        n += steplength\n            steplength = nlimit\n\n        np = 5\n        mcpy = members.copy()\n        for w in range(1, len(members)):\n            if mcpy[w]:\n                if np == 5 and w > prime:\n                    np = w\n                n = prime * w\n                if n > nlimit:\n                    break  \n                members[n] = False  \n\n        if np < prime:\n            break\n        primes.append(prime)\n        prime = 3 if prime == 2 else np\n        nlimit = min(steplength * prime, limit)  \n\n    newprimes = [i for i in range(2, len(members)) if members[i]]\n    return sorted(primes + newprimes)\n\n\nprint(pritchard(150))\nprint('Number of primes up to 1,000,000:', len(pritchard(1000000)))\n"}
{"id": 52626, "name": "Particle swarm optimization", "C#": "using System;\n\nnamespace ParticleSwarmOptimization {\n    public struct Parameters {\n        public double omega, phip, phig;\n\n        public Parameters(double omega, double phip, double phig) : this() {\n            this.omega = omega;\n            this.phip = phip;\n            this.phig = phig;\n        }\n    }\n\n    public struct State {\n        public int iter;\n        public double[] gbpos;\n        public double gbval;\n        public double[] min;\n        public double[] max;\n        public Parameters parameters;\n        public double[][] pos;\n        public double[][] vel;\n        public double[][] bpos;\n        public double[] bval;\n        public int nParticles;\n        public int nDims;\n\n        public State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) : this() {\n            this.iter = iter;\n            this.gbpos = gbpos;\n            this.gbval = gbval;\n            this.min = min;\n            this.max = max;\n            this.parameters = parameters;\n            this.pos = pos;\n            this.vel = vel;\n            this.bpos = bpos;\n            this.bval = bval;\n            this.nParticles = nParticles;\n            this.nDims = nDims;\n        }\n\n        public void Report(string testfunc) {\n            Console.WriteLine(\"Test Function        : {0}\", testfunc);\n            Console.WriteLine(\"Iterations           : {0}\", iter);\n            Console.WriteLine(\"Global Best Position : {0}\", string.Join(\", \", gbpos));\n            Console.WriteLine(\"Global Best Value    : {0}\", gbval);\n        }\n    }\n\n    class Program {\n        public static State PsoInit(double[] min, double[] max, Parameters parameters, int nParticles) {\n            var nDims = min.Length;\n            double[][] pos = new double[nParticles][];\n            for (int i = 0; i < nParticles; i++) {\n                pos[i] = new double[min.Length];\n                min.CopyTo(pos[i], 0);\n            }\n            double[][] vel = new double[nParticles][];\n            for (int i = 0; i < nParticles; i++) {\n                vel[i] = new double[nDims];\n            }\n            double[][] bpos = new double[nParticles][];\n            for (int i = 0; i < nParticles; i++) {\n                bpos[i] = new double[min.Length];\n                min.CopyTo(bpos[i], 0);\n            }\n            double[] bval = new double[nParticles];\n            for (int i = 0; i < nParticles; i++) {\n                bval[i] = double.PositiveInfinity;\n            }\n            int iter = 0;\n            double[] gbpos = new double[nDims];\n            for (int i = 0; i < nDims; i++) {\n                gbpos[i] = double.PositiveInfinity;\n            }\n            double gbval = double.PositiveInfinity;\n\n            return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n        }\n\n        static Random r = new Random();\n\n        public static State Pso(Func<double[], double> fn, State y) {\n            var p = y.parameters;\n            double[] v = new double[y.nParticles];\n            double[][] bpos = new double[y.nParticles][];\n            for (int i = 0; i < y.nParticles; i++) {\n                bpos[i] = new double[y.min.Length];\n                y.min.CopyTo(bpos[i], 0);\n            }\n            double[] bval = new double[y.nParticles];\n            double[] gbpos = new double[y.nDims];\n            double gbval = double.PositiveInfinity;\n            for (int j = 0; j < y.nParticles; j++) {\n                \n                v[j] = fn.Invoke(y.pos[j]);\n                \n                if (v[j] < y.bval[j]) {\n                    y.pos[j].CopyTo(bpos[j], 0);\n                    bval[j] = v[j];\n                }\n                else {\n                    y.bpos[j].CopyTo(bpos[j], 0);\n                    bval[j] = y.bval[j];\n                }\n                if (bval[j] < gbval) {\n                    gbval = bval[j];\n                    bpos[j].CopyTo(gbpos, 0);\n                }\n            }\n            double rg = r.NextDouble();\n            double[][] pos = new double[y.nParticles][];\n            double[][] vel = new double[y.nParticles][];\n            for (int i = 0; i < y.nParticles; i++) {\n                pos[i] = new double[y.nDims];\n                vel[i] = new double[y.nDims];\n            }\n            for (int j = 0; j < y.nParticles; j++) {\n                \n                double rp = r.NextDouble();\n                bool ok = true;\n                for (int k = 0; k < y.nDims; k++) {\n                    vel[j][k] = 0.0;\n                    pos[j][k] = 0.0;\n                }\n                for (int k = 0; k < y.nDims; k++) {\n                    vel[j][k] = p.omega * y.vel[j][k] +\n                                p.phip * rp * (bpos[j][k] - y.pos[j][k]) +\n                                p.phig * rg * (gbpos[k] - y.pos[j][k]);\n                    pos[j][k] = y.pos[j][k] + vel[j][k];\n                    ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];\n                }\n                if (!ok) {\n                    for (int k = 0; k < y.nDims; k++) {\n                        pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.NextDouble();\n                    }\n                }\n            }\n            var iter = 1 + y.iter;\n            return new State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n        }\n\n        public static State Iterate(Func<double[], double> fn, int n, State y) {\n            State r = y;\n            if (n == int.MaxValue) {\n                State old = y;\n                while (true) {\n                    r = Pso(fn, r);\n                    if (r.Equals(old)) break;\n                    old = r;\n                }\n            }\n            else {\n                for (int i = 0; i < n; i++) {\n                    r = Pso(fn, r);\n                }\n            }\n            return r;\n        }\n\n        public static double Mccormick(double[] x) {\n            var a = x[0];\n            var b = x[1];\n            return Math.Sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;\n        }\n\n        public static double Michalewicz(double[] x) {\n            int m = 10;\n            int d = x.Length;\n            double sum = 0.0;\n            for (int i = 1; i < d; i++) {\n                var j = x[i - 1];\n                var k = Math.Sin(i * j * j / Math.PI);\n                sum += Math.Sin(j) * Math.Pow(k, 2.0 * m);\n            }\n            return -sum;\n        }\n\n        static void Main(string[] args) {\n            var state = PsoInit(\n                new double[] { -1.5, -3.0 },\n                new double[] { 4.0, 4.0 },\n                new Parameters(0.0, 0.6, 0.3),\n                100\n                );\n            state = Iterate(Mccormick, 40, state);\n            state.Report(\"McCormick\");\n            Console.WriteLine(\"f(-.54719, -1.54719) : {0}\", Mccormick(new double[] { -.54719, -1.54719 }));\n            Console.WriteLine();\n\n            state = PsoInit(\n                new double[] { -0.0, -0.0 },\n                new double[] { Math.PI, Math.PI },\n                new Parameters(0.3, 0.3, 0.3),\n                1000\n                );\n            state = Iterate(Michalewicz, 30, state);\n            state.Report(\"Michalewicz (2D)\");\n            Console.WriteLine(\"f(2.20, 1.57)        : {0}\", Michalewicz(new double[] { 2.20, 1.57 }));\n        }\n    }\n}\n", "Python": "import math\nimport random\n\nINFINITY = 1 << 127\nMAX_INT = 1 << 31\n\nclass Parameters:\n    def __init__(self, omega, phip, phig):\n        self.omega = omega\n        self.phip = phip\n        self.phig = phig\n\nclass State:\n    def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):\n        self.iter = iter\n        self.gbpos = gbpos\n        self.gbval = gbval\n        self.min = min\n        self.max = max\n        self.parameters = parameters\n        self.pos = pos\n        self.vel = vel\n        self.bpos = bpos\n        self.bval = bval\n        self.nParticles = nParticles\n        self.nDims = nDims\n\n    def report(self, testfunc):\n        print \"Test Function :\", testfunc\n        print \"Iterations    :\", self.iter\n        print \"Global Best Position :\", self.gbpos\n        print \"Global Best Value    : %.16f\" % self.gbval\n\ndef uniform01():\n    v = random.random()\n    assert 0.0 <= v and v < 1.0\n    return v\n\ndef psoInit(min, max, parameters, nParticles):\n    nDims = len(min)\n    pos = [min[:]] * nParticles\n    vel = [[0.0] * nDims] * nParticles\n    bpos = [min[:]] * nParticles\n    bval = [INFINITY] * nParticles\n    iter = 0\n    gbpos = [INFINITY] * nDims\n    gbval = INFINITY\n    return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n\ndef pso(fn, y):\n    p = y.parameters\n    v = [0.0] * (y.nParticles)\n    bpos = [y.min[:]] * (y.nParticles)\n    bval = [0.0] * (y.nParticles)\n    gbpos = [0.0] * (y.nDims)\n    gbval = INFINITY\n    for j in xrange(0, y.nParticles):\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j]:\n            bpos[j] = y.pos[j][:]\n            bval[j] = v[j]\n        else:\n            bpos[j] = y.bpos[j][:]\n            bval[j] = y.bval[j]\n        if bval[j] < gbval:\n            gbval = bval[j]\n            gbpos = bpos[j][:]\n    rg = uniform01()\n    pos = [[None] * (y.nDims)] * (y.nParticles)\n    vel = [[None] * (y.nDims)] * (y.nParticles)\n    for j in xrange(0, y.nParticles):\n        \n        rp = uniform01()\n        ok = True\n        vel[j] = [0.0] * (len(vel[j]))\n        pos[j] = [0.0] * (len(pos[j]))\n        for k in xrange(0, y.nDims):\n            vel[j][k] = p.omega * y.vel[j][k] \\\n                      + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \\\n                      + p.phig * rg * (gbpos[k] - y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]\n        if not ok:\n            for k in xrange(0, y.nDims):\n                pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()\n    iter = 1 + y.iter\n    return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n\ndef iterate(fn, n, y):\n    r = y\n    old = y\n    if n == MAX_INT:\n        while True:\n            r = pso(fn, r)\n            if r == old:\n                break\n            old = r\n    else:\n        for _ in xrange(0, n):\n            r = pso(fn, r)\n    return r\n\ndef mccormick(x):\n    (a, b) = x\n    return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a\n\ndef michalewicz(x):\n    m = 10\n    d = len(x)\n    sum = 0.0\n    for i in xrange(1, d):\n        j = x[i - 1]\n        k = math.sin(i * j * j / math.pi)\n        sum += math.sin(j) * k ** (2.0 * m)\n    return -sum\n\ndef main():\n    state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)\n    state = iterate(mccormick, 40, state)\n    state.report(\"McCormick\")\n    print \"f(-.54719, -1.54719) : %.16f\" % (mccormick([-.54719, -1.54719]))\n\n    print\n\n    state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)\n    state = iterate(michalewicz, 30, state)\n    state.report(\"Michalewicz (2D)\")\n    print \"f(2.20, 1.57)        : %.16f\" % (michalewicz([2.2, 1.57]))\n\nmain()\n"}
{"id": 52627, "name": "Twelve statements", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n"}
{"id": 52628, "name": "Twelve statements", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n"}
{"id": 52629, "name": "Add a variable to a class instance at runtime", "C#": "\n\n\n\n\n\n\n\nusing System;\nusing System.Dynamic;\n\nnamespace DynamicClassVariable\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            \n            \n            dynamic sampleObj = new ExpandoObject();\n            \n            sampleObj.bar = 1;\n            Console.WriteLine( \"sampleObj.bar = {0}\", sampleObj.bar );\n\n            \n            \n            \n            \n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n}\n", "Python": "class empty(object):\n    pass\ne = empty()\n"}
{"id": 52630, "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": 52631, "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", "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": 52632, "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", "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": 52633, "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", "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": 52634, "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", "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": 52635, "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", "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": 52636, "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", "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": 52637, "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", "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": 52638, "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", "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": 52639, "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", "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": 52640, "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", "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": 52641, "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", "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": 52642, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 52643, "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", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n"}
{"id": 52644, "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", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n"}
{"id": 52645, "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", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\n"}
{"id": 52646, "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", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 52647, "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", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\n"}
{"id": 52648, "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", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n"}
{"id": 52649, "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", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n"}
{"id": 52650, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 52651, "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", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n"}
{"id": 52652, "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", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n"}
{"id": 52653, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 52654, "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", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n"}
{"id": 52655, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 52656, "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", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n"}
{"id": 52657, "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", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n"}
{"id": 52658, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 52659, "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", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n"}
{"id": 52660, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 52661, "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", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n"}
{"id": 52662, "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", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n"}
{"id": 52663, "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", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 52664, "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", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n"}
{"id": 52665, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 52666, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n"}
{"id": 52667, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52668, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n"}
{"id": 52669, "name": "Text processing_1", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n"}
{"id": 52670, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n"}
{"id": 52671, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 52672, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n"}
{"id": 52673, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 52674, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 52675, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 52676, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n"}
{"id": 52677, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n"}
{"id": 52678, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n"}
{"id": 52679, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n"}
{"id": 52680, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n"}
{"id": 52681, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n"}
{"id": 52682, "name": "Fractran", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n"}
{"id": 52683, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n"}
{"id": 52684, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n"}
{"id": 52685, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 52686, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n"}
{"id": 52687, "name": "List comprehensions", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 52688, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n"}
{"id": 52689, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n"}
{"id": 52690, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n"}
{"id": 52691, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n"}
{"id": 52692, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n"}
{"id": 52693, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n"}
{"id": 52694, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 52695, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n"}
{"id": 52696, "name": "Non-continuous subsequences", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n"}
{"id": 52697, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 52698, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n"}
{"id": 52699, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n"}
{"id": 52700, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52701, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52702, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 52703, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n"}
{"id": 52704, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n"}
{"id": 52705, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n"}
{"id": 52706, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n"}
{"id": 52707, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n"}
{"id": 52708, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n"}
{"id": 52709, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 52710, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n"}
{"id": 52711, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n"}
{"id": 52712, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n"}
{"id": 52713, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n"}
{"id": 52714, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n"}
{"id": 52715, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 52716, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n"}
{"id": 52717, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 52718, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n"}
{"id": 52719, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 52720, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n"}
{"id": 52721, "name": "Water collected between towers", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 52722, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52723, "name": "Jaro similarity", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n"}
{"id": 52724, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 52725, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n"}
{"id": 52726, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n"}
{"id": 52727, "name": "Prime triangle", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n"}
{"id": 52728, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n"}
{"id": 52729, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n"}
{"id": 52730, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n"}
{"id": 52731, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n"}
{"id": 52732, "name": "Stern-Brocot sequence", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n"}
{"id": 52733, "name": "Soundex", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n"}
{"id": 52734, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52735, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52736, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 52737, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n"}
{"id": 52738, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 52739, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n"}
{"id": 52740, "name": "Finite state machine", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n"}
{"id": 52741, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 52742, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n"}
{"id": 52743, "name": "Sierpinski pentagon", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n"}
{"id": 52744, "name": "Rep-string", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n"}
{"id": 52745, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n"}
{"id": 52746, "name": "GUI_Maximum window dimensions", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n"}
{"id": 52747, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n"}
{"id": 52748, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 52749, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n"}
{"id": 52750, "name": "Parse an IP Address", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n"}
{"id": 52751, "name": "Knapsack problem_Unbounded", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n"}
{"id": 52752, "name": "Textonyms", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n"}
{"id": 52753, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n"}
{"id": 52754, "name": "Type detection", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n"}
{"id": 52755, "name": "Maximum triangle path sum", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n"}
{"id": 52756, "name": "Zhang-Suen thinning algorithm", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n"}
{"id": 52757, "name": "Zhang-Suen thinning algorithm", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n"}
{"id": 52758, "name": "Variable declaration reset", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n"}
{"id": 52759, "name": "Koch curve", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n"}
{"id": 52760, "name": "Draw a pixel", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n"}
{"id": 52761, "name": "Words from neighbour ones", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n"}
{"id": 52762, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 52763, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n"}
{"id": 52764, "name": "UTF-8 encode and decode", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n"}
{"id": 52765, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n"}
{"id": 52766, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n"}
{"id": 52767, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n"}
{"id": 52768, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n"}
{"id": 52769, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n"}
{"id": 52770, "name": "Death Star", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n"}
{"id": 52771, "name": "Verify distribution uniformity_Chi-squared test", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n"}
{"id": 52772, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52773, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 52774, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n"}
{"id": 52775, "name": "GUI component interaction", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n"}
{"id": 52776, "name": "One of n lines in a file", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n"}
{"id": 52777, "name": "Spelling of ordinal numbers", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n"}
{"id": 52778, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n"}
{"id": 52779, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 52780, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n"}
{"id": 52781, "name": "Repeat", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n"}
{"id": 52782, "name": "Sparkline in unicode", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n"}
{"id": 52783, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n"}
{"id": 52784, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n"}
{"id": 52785, "name": "Terminal control_Clear the screen", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n", "VB": "System.Console.Clear()\n"}
{"id": 52786, "name": "Sorting algorithms_Pancake sort", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n"}
{"id": 52787, "name": "Chemical calculator", "Java": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\npublic class ChemicalCalculator {\n    private static final Map<String, Double> atomicMass = new HashMap<>();\n\n    static {\n        atomicMass.put(\"H\", 1.008);\n        atomicMass.put(\"He\", 4.002602);\n        atomicMass.put(\"Li\", 6.94);\n        atomicMass.put(\"Be\", 9.0121831);\n        atomicMass.put(\"B\", 10.81);\n        atomicMass.put(\"C\", 12.011);\n        atomicMass.put(\"N\", 14.007);\n        atomicMass.put(\"O\", 15.999);\n        atomicMass.put(\"F\", 18.998403163);\n        atomicMass.put(\"Ne\", 20.1797);\n        atomicMass.put(\"Na\", 22.98976928);\n        atomicMass.put(\"Mg\", 24.305);\n        atomicMass.put(\"Al\", 26.9815385);\n        atomicMass.put(\"Si\", 28.085);\n        atomicMass.put(\"P\", 30.973761998);\n        atomicMass.put(\"S\", 32.06);\n        atomicMass.put(\"Cl\", 35.45);\n        atomicMass.put(\"Ar\", 39.948);\n        atomicMass.put(\"K\", 39.0983);\n        atomicMass.put(\"Ca\", 40.078);\n        atomicMass.put(\"Sc\", 44.955908);\n        atomicMass.put(\"Ti\", 47.867);\n        atomicMass.put(\"V\", 50.9415);\n        atomicMass.put(\"Cr\", 51.9961);\n        atomicMass.put(\"Mn\", 54.938044);\n        atomicMass.put(\"Fe\", 55.845);\n        atomicMass.put(\"Co\", 58.933194);\n        atomicMass.put(\"Ni\", 58.6934);\n        atomicMass.put(\"Cu\", 63.546);\n        atomicMass.put(\"Zn\", 65.38);\n        atomicMass.put(\"Ga\", 69.723);\n        atomicMass.put(\"Ge\", 72.630);\n        atomicMass.put(\"As\", 74.921595);\n        atomicMass.put(\"Se\", 78.971);\n        atomicMass.put(\"Br\", 79.904);\n        atomicMass.put(\"Kr\", 83.798);\n        atomicMass.put(\"Rb\", 85.4678);\n        atomicMass.put(\"Sr\", 87.62);\n        atomicMass.put(\"Y\", 88.90584);\n        atomicMass.put(\"Zr\", 91.224);\n        atomicMass.put(\"Nb\", 92.90637);\n        atomicMass.put(\"Mo\", 95.95);\n        atomicMass.put(\"Ru\", 101.07);\n        atomicMass.put(\"Rh\", 102.90550);\n        atomicMass.put(\"Pd\", 106.42);\n        atomicMass.put(\"Ag\", 107.8682);\n        atomicMass.put(\"Cd\", 112.414);\n        atomicMass.put(\"In\", 114.818);\n        atomicMass.put(\"Sn\", 118.710);\n        atomicMass.put(\"Sb\", 121.760);\n        atomicMass.put(\"Te\", 127.60);\n        atomicMass.put(\"I\", 126.90447);\n        atomicMass.put(\"Xe\", 131.293);\n        atomicMass.put(\"Cs\", 132.90545196);\n        atomicMass.put(\"Ba\", 137.327);\n        atomicMass.put(\"La\", 138.90547);\n        atomicMass.put(\"Ce\", 140.116);\n        atomicMass.put(\"Pr\", 140.90766);\n        atomicMass.put(\"Nd\", 144.242);\n        atomicMass.put(\"Pm\", 145.0);\n        atomicMass.put(\"Sm\", 150.36);\n        atomicMass.put(\"Eu\", 151.964);\n        atomicMass.put(\"Gd\", 157.25);\n        atomicMass.put(\"Tb\", 158.92535);\n        atomicMass.put(\"Dy\", 162.500);\n        atomicMass.put(\"Ho\", 164.93033);\n        atomicMass.put(\"Er\", 167.259);\n        atomicMass.put(\"Tm\", 168.93422);\n        atomicMass.put(\"Yb\", 173.054);\n        atomicMass.put(\"Lu\", 174.9668);\n        atomicMass.put(\"Hf\", 178.49);\n        atomicMass.put(\"Ta\", 180.94788);\n        atomicMass.put(\"W\", 183.84);\n        atomicMass.put(\"Re\", 186.207);\n        atomicMass.put(\"Os\", 190.23);\n        atomicMass.put(\"Ir\", 192.217);\n        atomicMass.put(\"Pt\", 195.084);\n        atomicMass.put(\"Au\", 196.966569);\n        atomicMass.put(\"Hg\", 200.592);\n        atomicMass.put(\"Tl\", 204.38);\n        atomicMass.put(\"Pb\", 207.2);\n        atomicMass.put(\"Bi\", 208.98040);\n        atomicMass.put(\"Po\", 209.0);\n        atomicMass.put(\"At\", 210.0);\n        atomicMass.put(\"Rn\", 222.0);\n        atomicMass.put(\"Fr\", 223.0);\n        atomicMass.put(\"Ra\", 226.0);\n        atomicMass.put(\"Ac\", 227.0);\n        atomicMass.put(\"Th\", 232.0377);\n        atomicMass.put(\"Pa\", 231.03588);\n        atomicMass.put(\"U\", 238.02891);\n        atomicMass.put(\"Np\", 237.0);\n        atomicMass.put(\"Pu\", 244.0);\n        atomicMass.put(\"Am\", 243.0);\n        atomicMass.put(\"Cm\", 247.0);\n        atomicMass.put(\"Bk\", 247.0);\n        atomicMass.put(\"Cf\", 251.0);\n        atomicMass.put(\"Es\", 252.0);\n        atomicMass.put(\"Fm\", 257.0);\n        atomicMass.put(\"Uue\", 315.0);\n        atomicMass.put(\"Ubn\", 299.0);\n    }\n\n    private static double evaluate(String s) {\n        String sym = s + \"[\";\n        double sum = 0.0;\n        StringBuilder symbol = new StringBuilder();\n        String number = \"\";\n        for (int i = 0; i < sym.length(); ++i) {\n            char c = sym.charAt(i);\n            if ('@' <= c && c <= '[') {\n                \n                int n = 1;\n                if (!number.isEmpty()) {\n                    n = Integer.parseInt(number);\n                }\n                if (symbol.length() > 0) {\n                    sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;\n                }\n                if (c == '[') {\n                    break;\n                }\n                symbol = new StringBuilder(String.valueOf(c));\n                number = \"\";\n            } else if ('a' <= c && c <= 'z') {\n                symbol.append(c);\n            } else if ('0' <= c && c <= '9') {\n                number += c;\n            } else {\n                throw new RuntimeException(\"Unexpected symbol \" + c + \" in molecule\");\n            }\n        }\n        return sum;\n    }\n\n    private static String replaceParens(String s) {\n        char letter = 'a';\n        String si = s;\n        while (true) {\n            int start = si.indexOf('(');\n            if (start == -1) {\n                break;\n            }\n\n            for (int i = start + 1; i < si.length(); ++i) {\n                if (si.charAt(i) == ')') {\n                    String expr = si.substring(start + 1, i);\n                    String symbol = \"@\" + letter;\n                    String pattern = Pattern.quote(si.substring(start, i + 1));\n                    si = si.replaceFirst(pattern, symbol);\n                    atomicMass.put(symbol, evaluate(expr));\n                    letter++;\n                    break;\n                }\n                if (si.charAt(i) == '(') {\n                    start = i;\n                }\n            }\n        }\n        return si;\n    }\n\n    public static void main(String[] args) {\n        List<String> molecules = List.of(\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        );\n        for (String molecule : molecules) {\n            double mass = evaluate(replaceParens(molecule));\n            System.out.printf(\"%17s -> %7.3f\\n\", molecule, mass);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52788, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n"}
{"id": 52789, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n"}
{"id": 52790, "name": "Practical numbers", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n"}
{"id": 52791, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n"}
{"id": 52792, "name": "Word search", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52793, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 52794, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n"}
{"id": 52795, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 52796, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n"}
{"id": 52797, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n"}
{"id": 52798, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n"}
{"id": 52799, "name": "Zumkeller numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n"}
{"id": 52800, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 52801, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n"}
{"id": 52802, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 52803, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n"}
{"id": 52804, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n"}
{"id": 52805, "name": "Geometric algebra", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n"}
{"id": 52806, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n"}
{"id": 52807, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n"}
{"id": 52808, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n"}
{"id": 52809, "name": "Sierpinski square curve", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n"}
{"id": 52810, "name": "Sierpinski square curve", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n"}
{"id": 52811, "name": "Word break problem", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52812, "name": "Latin Squares in reduced form", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52813, "name": "UPC", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n"}
{"id": 52814, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 52815, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n"}
{"id": 52816, "name": "Closest-pair problem", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n"}
{"id": 52817, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n"}
{"id": 52818, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n"}
{"id": 52819, "name": "Color wheel", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n"}
{"id": 52820, "name": "Square root by hand", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n"}
{"id": 52821, "name": "Square root by hand", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n"}
{"id": 52822, "name": "Reflection_List properties", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52823, "name": "Align columns", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n"}
{"id": 52824, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 52825, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 52826, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n"}
{"id": 52827, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52828, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52829, "name": "Data Encryption Standard", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n", "VB": "Imports System.IO\nImports System.Security.Cryptography\n\nModule Module1\n\n    \n    Function ByteArrayToString(ba As Byte()) As String\n        Return BitConverter.ToString(ba).Replace(\"-\", \"\")\n    End Function\n\n    \n    \n    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateEncryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(messageBytes, 0, messageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim encryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n\n        Return encryptedMessageBytes\n    End Function\n\n    \n    \n    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateDecryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim decryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)\n\n        Return decryptedMessageBytes\n    End Function\n\n    Sub Main()\n        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}\n        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}\n\n        Dim encStr = Encrypt(plainBytes, keyBytes)\n        Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr))\n\n        Dim decStr = Decrypt(encStr, keyBytes)\n        Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decStr))\n    End Sub\n\nEnd Module\n"}
{"id": 52830, "name": "Commatizing numbers", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n"}
{"id": 52831, "name": "Arithmetic coding_As a generalized change of radix", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 52832, "name": "Kosaraju", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n"}
{"id": 52833, "name": "Pentomino tiling", "Java": "package pentominotiling;\n\nimport java.util.*;\n\npublic class PentominoTiling {\n\n    static final char[] symbols = \"FILNPTUVWXYZ-\".toCharArray();\n    static final Random rand = new Random();\n\n    static final int nRows = 8;\n    static final int nCols = 8;\n    static final int blank = 12;\n\n    static int[][] grid = new int[nRows][nCols];\n    static boolean[] placed = new boolean[symbols.length - 1];\n\n    public static void main(String[] args) {\n        shuffleShapes();\n\n        for (int r = 0; r < nRows; r++)\n            Arrays.fill(grid[r], -1);\n\n        for (int i = 0; i < 4; i++) {\n            int randRow, randCol;\n            do {\n                randRow = rand.nextInt(nRows);\n                randCol = rand.nextInt(nCols);\n            } while (grid[randRow][randCol] == blank);\n            grid[randRow][randCol] = blank;\n        }\n\n        if (solve(0, 0)) {\n            printResult();\n        } else {\n            System.out.println(\"no solution\");\n        }\n    }\n\n    static void shuffleShapes() {\n        int n = shapes.length;\n        while (n > 1) {\n            int r = rand.nextInt(n--);\n\n            int[][] tmp = shapes[r];\n            shapes[r] = shapes[n];\n            shapes[n] = tmp;\n\n            char tmpSymbol = symbols[r];\n            symbols[r] = symbols[n];\n            symbols[n] = tmpSymbol;\n        }\n    }\n\n    static void printResult() {\n        for (int[] r : grid) {\n            for (int i : r)\n                System.out.printf(\"%c \", symbols[i]);\n            System.out.println();\n        }\n    }\n\n    static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {\n\n        for (int i = 0; i < o.length; i += 2) {\n            int x = c + o[i + 1];\n            int y = r + o[i];\n            if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                return false;\n        }\n\n        grid[r][c] = shapeIndex;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = shapeIndex;\n\n        return true;\n    }\n\n    static void removeOrientation(int[] o, int r, int c) {\n        grid[r][c] = -1;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = -1;\n    }\n\n    static boolean solve(int pos, int numPlaced) {\n        if (numPlaced == shapes.length)\n            return true;\n\n        int row = pos / nCols;\n        int col = pos % nCols;\n\n        if (grid[row][col] != -1)\n            return solve(pos + 1, numPlaced);\n\n        for (int i = 0; i < shapes.length; i++) {\n            if (!placed[i]) {\n                for (int[] orientation : shapes[i]) {\n\n                    if (!tryPlaceOrientation(orientation, row, col, i))\n                        continue;\n\n                    placed[i] = true;\n\n                    if (solve(pos + 1, numPlaced + 1))\n                        return true;\n\n                    removeOrientation(orientation, row, col);\n                    placed[i] = false;\n                }\n            }\n        }\n        return false;\n    }\n\n    static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};\n\n    static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};\n\n    static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};\n\n    static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};\n\n    static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};\n\n    static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};\n\n    static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};\n\n    static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};\n\n    static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};\n}\n", "VB": "Module Module1\n\n    Dim symbols As Char() = \"XYPFTVNLUZWI█\".ToCharArray(),\n        nRows As Integer = 8, nCols As Integer = 8,\n        target As Integer = 12, blank As Integer = 12,\n        grid As Integer()() = New Integer(nRows - 1)() {},\n        placed As Boolean() = New Boolean(target - 1) {},\n        pens As List(Of List(Of Integer())), rand As Random,\n        seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}\n\n    Sub Main()\n        Unpack(seeds) : rand = New Random() : ShuffleShapes(2)\n        For r As Integer = 0 To nRows - 1\n            grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next\n        For i As Integer = 0 To 3\n            Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)\n            Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank\n        Next\n        If Solve(0, 0) Then\n            PrintResult()\n        Else\n            Console.WriteLine(\"no solution for this configuration:\") : PrintResult()\n        End If\n        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\n    Sub ShuffleShapes(count As Integer) \n        For i As Integer = 0 To count : For j = 0 To pens.Count - 1\n                Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j\n                Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp\n                Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch\n            Next : Next\n    End Sub\n\n    Sub PrintResult() \n        For Each r As Integer() In grid : For Each i As Integer In r\n                Console.Write(\"{0} \", If(i < 0, \".\", symbols(i)))\n            Next : Console.WriteLine() : Next\n    End Sub\n\n    \n    Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean\n        If numPlaced = target Then Return True\n        Dim row As Integer = pos \\ nCols, col As Integer = pos Mod nCols\n        If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)\n        For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then\n                For Each orientation As Integer() In pens(i)\n                    If Not TPO(orientation, row, col, i) Then Continue For\n                    placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True\n                    RmvO(orientation, row, col) : placed(i) = False\n                Next : End If : Next : Return False\n    End Function\n\n    \n    Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)\n        grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = -1 : Next\n    End Sub\n\n    \n    Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,\n                 ByVal sIdx As Integer) As Boolean\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)\n            If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse\n                grid(y)(x) <> -1 Then Return False\n        Next : grid(row)(col) = sIdx\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = sIdx\n        Next : Return True\n    End Function\n\n    \n    \n    \n    \n\n    Sub Unpack(sv As Integer()) \n        pens = New List(Of List(Of Integer())) : For Each item In sv\n            Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),\n                fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7\n                If i = 4 Then Mir(exi) Else Rot(exi)\n                fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))\n            Next : pens.Add(Gen) : Next\n    End Sub\n\n    \n    Function Expand(i As Integer) As List(Of Integer)\n        Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next\n    End Function\n\n    \n    Function ToP(p As List(Of Integer)) As Integer()\n        Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)\n            tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next\n        tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next\n        Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)\n            Dim adj = If((item And 7) > 4, 8, 0)\n            res.Add((adj + item) \\ 8) : res.Add((item And 7) - adj)\n        Next : Return res.ToArray()\n    End Function\n\n    \n    Function TheSame(a As Integer(), b As Integer()) As Boolean\n        For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False\n        Next : Return True\n    End Function\n\n    Sub Rot(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next\n    End Sub\n\n    Sub Mir(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next\n    End Sub\n\nEnd Module\n"}
{"id": 52834, "name": "Make a backup file", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n"}
{"id": 52835, "name": "Make a backup file", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n"}
{"id": 52836, "name": "Check Machin-like formulas", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 52837, "name": "Check Machin-like formulas", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n"}
{"id": 52838, "name": "Solve triangle solitare puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\n\npublic class IQPuzzle {\n\n    public static void main(String[] args) {\n        System.out.printf(\"  \");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"  %,6d\", start);\n        }\n        System.out.printf(\"%n\");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"%2d\", start);\n            Map<Integer,Integer> solutions = solve(start);    \n            for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {\n                System.out.printf(\"  %,6d\", solutions.containsKey(end) ? solutions.get(end) : 0);\n            }\n            System.out.printf(\"%n\");\n        }\n        int moveNum = 0;\n        System.out.printf(\"%nOne Solution:%n\");\n        for ( Move m : oneSolution ) {\n            moveNum++;\n            System.out.printf(\"Move %d = %s%n\", moveNum, m);\n        }\n    }\n    \n    private static List<Move> oneSolution = null;\n    \n    private static Map<Integer, Integer> solve(int emptyPeg) {\n        Puzzle puzzle = new Puzzle(emptyPeg);\n        Map<Integer,Integer> solutions = new HashMap<>();\n        Stack<Puzzle> stack = new Stack<Puzzle>();\n        stack.push(puzzle);\n        while ( ! stack.isEmpty() ) {\n            Puzzle p = stack.pop();\n            if ( p.solved() ) {\n                solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);\n                if ( oneSolution == null ) {\n                    oneSolution = p.moves;\n                }\n                continue;\n            }\n            for ( Move move : p.getValidMoves() ) {\n                Puzzle pMove = p.move(move);\n                stack.add(pMove);\n            }\n        }\n        \n        return solutions;\n    }\n    \n    private static class Puzzle {\n        \n        public static int MAX_PEGS = 16;\n        private boolean[] pegs = new boolean[MAX_PEGS];  \n        \n        private List<Move> moves;\n\n        public Puzzle(int emptyPeg) {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            pegs[emptyPeg] = false;\n            moves = new ArrayList<>();\n        }\n\n        public Puzzle() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            moves = new ArrayList<>();\n        }\n\n        private static Map<Integer,List<Move>> validMoves = new HashMap<>(); \n        static {\n            validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));\n            validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));\n            validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));\n            validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));\n            validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));\n            validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));\n            validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));\n            validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));\n            validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));\n            validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));\n            validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));\n            validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));\n            validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));\n            validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));\n            validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));\n        }\n        \n        public List<Move> getValidMoves() {\n            List<Move> moves = new ArrayList<Move>();\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    for ( Move testMove : validMoves.get(i) ) {\n                        if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {\n                            moves.add(testMove);\n                        }\n                    }\n                }\n            }\n            return moves;\n        }\n\n        public boolean solved() {\n            boolean foundFirstPeg = false;\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    if ( foundFirstPeg ) {\n                        return false;\n                    }\n                    foundFirstPeg = true;\n                }\n            }\n            return true;\n        }\n        \n        public Puzzle move(Move move) {\n            Puzzle p = new Puzzle();\n            if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {\n                throw new RuntimeException(\"Invalid move.\");\n            }\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                p.pegs[i] = pegs[i];\n            }\n            p.pegs[move.start] = false;\n            p.pegs[move.jump] = false;\n            p.pegs[move.end] = true;\n            for ( Move m : moves ) {\n                p.moves.add(new Move(m.start, m.jump, m.end));\n            }\n            p.moves.add(new Move(move.start, move.jump, move.end));\n            return p;\n        }\n        \n        public int getLastPeg() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    return i;\n                }\n            }\n            throw new RuntimeException(\"ERROR:  Illegal position.\");\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"[\");\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                sb.append(pegs[i] ? 1 : 0);\n                sb.append(\",\");\n            }\n            sb.setLength(sb.length()-1);            \n            sb.append(\"]\");\n            return sb.toString();\n        }\n    }\n    \n    private static class Move {\n        int start;\n        int jump;\n        int end;\n        \n        public Move(int s, int j, int e) {\n            start = s; jump = j; end = e;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"{\");\n            sb.append(\"s=\" + start);\n            sb.append(\", j=\" + jump);\n            sb.append(\", e=\" + end);\n            sb.append(\"}\");\n            return sb.toString();\n        }\n    }\n\n}\n", "VB": "Imports System, Microsoft.VisualBasic.DateAndTime\n\nPublic Module Module1\n    Const n As Integer = 5 \n    Dim Board As String \n    Dim Starting As Integer = 1 \n    Dim Target As Integer = 13 \n    Dim Moves As Integer() \n    Dim bi() As Integer \n    Dim ib() As Integer \n    Dim nl As Char = Convert.ToChar(10) \n\n    \n    Public Function Dou(s As String) As String\n        Dou = \"\" : Dim b As Boolean = True\n        For Each ch As Char In s\n            If b Then b = ch <> \" \"\n            If b Then Dou &= ch & \" \" Else Dou = \" \" & Dou\n        Next : Dou = Dou.TrimEnd()\n    End Function\n\n    \n    Public Function Fmt(s As String) As String\n        If s.Length < Board.Length Then Return s\n        Fmt = \"\" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &\n                If(i = n, s.Substring(Board.Length), \"\") & nl\n        Next\n    End Function\n\n    \n    Public Function Triangle(n As Integer) As Integer\n        Return (n * (n + 1)) / 2\n    End Function\n\n    \n    Public Function Init(s As String, pos As Integer) As String\n        Init = s : Mid(Init, pos, 1) = \"0\"\n    End Function\n\n    \n    Public Sub InitIndex()\n        ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0\n        For i As Integer = 0 To ib.Length - 1\n            If i = 0 Then\n                ib(i) = 0 : bi(j) = 0 : j += 1\n            Else\n                If Board(i - 1) = \"1\" Then ib(i) = j : bi(j) = i : j += 1\n            End If\n        Next\n    End Sub\n\n    \n    Public Function solve(brd As String, pegsLeft As Integer) As String\n        If pegsLeft = 1 Then \n            If Target = 0 Then Return \"Completed\" \n            If brd(bi(Target) - 1) = \"1\" Then Return \"Completed\" Else Return \"fail\"\n        End If\n        For i = 1 To Board.Length \n            If brd(i - 1) = \"1\" Then \n                For Each mj In Moves \n                    Dim over As Integer = i + mj \n                    Dim land As Integer = i + 2 * mj \n                    \n                    If land >= 1 AndAlso land <= brd.Length _\n                                AndAlso brd(land - 1) = \"0\" _\n                                AndAlso brd(over - 1) = \"1\" Then\n                        setPegs(brd, \"001\", i, over, land) \n                        \n                        Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)\n                        \n                        If Res.Length <> 4 Then _\n                            Return brd & info(i, over, land) & nl & Res\n                        setPegs(brd, \"110\", i, over, land) \n                    End If\n                Next\n            End If\n        Next\n        Return \"fail\"\n    End Function\n\n    \n    Function info(frm As Integer, over As Integer, dest As Integer) As String\n        Return \"  Peg from \" & ib(frm).ToString() & \" goes to \" & ib(dest).ToString() &\n            \", removing peg at \" & ib(over).ToString()\n    End Function\n\n    \n    Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)\n        Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)\n    End Sub\n\n    \n    Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)\n        x = Math.Max(Math.Min(x, hi), lo)\n    End Sub\n\n    Public Sub Main()\n        Dim t As Integer = Triangle(n) \n        LimitIt(Starting, 1, t) \n        LimitIt(Target, 0, t)\n        Dim stime As Date = Now() \n        Moves = {-n - 1, -n, -1, 1, n, n + 1} \n        Board = New String(\"1\", n * n) \n        For i As Integer = 0 To n - 2 \n            Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(\" \", n - 1 - i)\n        Next\n        InitIndex() \n        Dim B As String = Init(Board, bi(Starting)) \n        Console.WriteLine(Fmt(B & \"  Starting with peg removed from \" & Starting.ToString()))\n        Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)\n        Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & \" ms.\"\n        If res(0).Length = 4 Then\n            If Target = 0 Then\n                Console.WriteLine(\"Unable to find a solution with last peg left anywhere.\")\n            Else\n                Console.WriteLine(\"Unable to find a solution with last peg left at \" &\n                                  Target.ToString() & \".\")\n            End If\n            Console.WriteLine(\"Computation time: \" & ts)\n        Else\n            For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next\n            Console.WriteLine(\"Computation time to first found solution: \" & ts)\n        End If\n        If Diagnostics.Debugger.IsAttached Then Console.ReadLine()\n    End Sub\nEnd Module\n"}
{"id": 52839, "name": "Twelve statements", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n"}
{"id": 52840, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\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": 52841, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\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": 52842, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\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": 52843, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\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": 52844, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\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": 52845, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\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": 52846, "name": "24 game_Solve", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\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": 52847, "name": "Checkpoint synchronization", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\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": 52848, "name": "Variable-length quantity", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\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": 52849, "name": "Record sound", "C": "#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <fcntl.h>\n\nvoid * record(size_t bytes)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_RDONLY))) return 0;\n\tvoid *a = malloc(bytes);\n\tread(fd, a, bytes);\n\tclose(fd);\n\treturn a;\n}\n\nint play(void *buf, size_t len)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_WRONLY))) return 0;\n\twrite(fd, buf, len);\n\tclose(fd);\n\treturn 1;\n}\n\nint main()\n{\n\tvoid *p = record(65536);\n\tplay(p, 65536);\n\treturn 0;\n}\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": 52850, "name": "SHA-256 Merkle tree", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\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": 52851, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\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": 52852, "name": "User input_Graphical", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\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": 52853, "name": "Sierpinski arrowhead curve", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\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": 52854, "name": "Text processing_1", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\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": 52855, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\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": 52856, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\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": 52857, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\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": 52858, "name": "Aliquot sequence classifications", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\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": 52859, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\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": 52860, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\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": 52861, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\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": 52862, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\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": 52863, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\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": 52864, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\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": 52865, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\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": 52866, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "Go": "var intStack []int\n"}
{"id": 52867, "name": "Totient function", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\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    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": 52868, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 52869, "name": "Fractran", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\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": 52870, "name": "Sorting algorithms_Stooge sort", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\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    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": 52871, "name": "Galton box animation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\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": 52872, "name": "Sorting Algorithms_Circle Sort", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\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": 52873, "name": "Kronecker product based fractals", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\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": 52874, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\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": 52875, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\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": 52876, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\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": 52877, "name": "Circular primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\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": 52878, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\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": 52879, "name": "Animation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\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": 52880, "name": "Sorting algorithms_Radix sort", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\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": 52881, "name": "List comprehensions", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\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": 52882, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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    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": 52883, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\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": 52884, "name": "Jacobi symbol", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\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": 52885, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\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": 52886, "name": "K-d tree", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\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": 52887, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\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": 52888, "name": "Singleton", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\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": 52889, "name": "Safe addition", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\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": 52890, "name": "Case-sensitivity of identifiers", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\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": 52891, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 52892, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 52893, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 52894, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\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": 52895, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\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": 52896, "name": "Palindromic gapful numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\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": 52897, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(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    \"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": 52898, "name": "Sierpinski triangle_Graphical", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(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    \"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": 52899, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\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": 52900, "name": "Summarize primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\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": 52901, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\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": 52902, "name": "Common sorted list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\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": 52903, "name": "Non-continuous subsequences", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\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": 52904, "name": "Fibonacci word_fractal", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\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": 52905, "name": "Twin primes", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\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": 52906, "name": "Roots of unity", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\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": 52907, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\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": 52908, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\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": 52909, "name": "Pell's equation", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\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": 52910, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\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": 52911, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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\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": 52912, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\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": 52913, "name": "Product of divisors", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\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": 52914, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\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": 52915, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\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": 52916, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\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": 52917, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\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": 52918, "name": "Short-circuit evaluation", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\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": 52919, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\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": 52920, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\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": 52921, "name": "Carmichael 3 strong pseudoprimes", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n"}
{"id": 52922, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n"}
{"id": 52923, "name": "Arithmetic numbers", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n"}
{"id": 52924, "name": "Image noise", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 52925, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 52926, "name": "Keyboard input_Obtain a Y or N response", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 52927, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 52928, "name": "Conjugate transpose", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n"}
{"id": 52929, "name": "Conjugate transpose", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n"}
{"id": 52930, "name": "Jacobsthal numbers", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 52931, "name": "Jacobsthal numbers", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 52932, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 52933, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 52934, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 52935, "name": "Cistercian numerals", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 52936, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 52937, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 52938, "name": "Draw a sphere", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 52939, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 52940, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 52941, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 52942, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 52943, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 52944, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 52945, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 52946, "name": "Water collected between towers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 52947, "name": "Descending primes", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 52948, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 52949, "name": "Square-free integers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 52950, "name": "Jaro similarity", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n"}
{"id": 52951, "name": "Sum and product puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n"}
{"id": 52952, "name": "Fairshare between two and more", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n"}
{"id": 52953, "name": "Two bullet roulette", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstatic int nextInt(int size) {\n    return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n    bool t = cylinder[5];\n    int i;\n    for (i = 4; i >= 0; i--) {\n        cylinder[i + 1] = cylinder[i];\n    }\n    cylinder[0] = t;\n}\n\nstatic void unload() {\n    int i;\n    for (i = 0; i < 6; i++) {\n        cylinder[i] = false;\n    }\n}\n\nstatic void load() {\n    while (cylinder[0]) {\n        rshift();\n    }\n    cylinder[0] = true;\n    rshift();\n}\n\nstatic void spin() {\n    int lim = nextInt(6) + 1;\n    int i;\n    for (i = 1; i < lim; i++) {\n        rshift();\n    }\n}\n\nstatic bool fire() {\n    bool shot = cylinder[0];\n    rshift();\n    return shot;\n}\n\nstatic int method(const char *s) {\n    unload();\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            load();\n            break;\n        case 'S':\n            spin();\n            break;\n        case 'F':\n            if (fire()) {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n    if (*out != '\\0') {\n        strcat(out, \", \");\n    }\n    strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            append(out, \"load\");\n            break;\n        case 'S':\n            append(out, \"spin\");\n            break;\n        case 'F':\n            append(out, \"fire\");\n            break;\n        }\n    }\n}\n\nstatic void test(char *src) {\n    char buffer[41] = \"\";\n    const int tests = 100000;\n    int sum = 0;\n    int t;\n    double pc;\n\n    for (t = 0; t < tests; t++) {\n        sum += method(src);\n    }\n\n    mstring(src, buffer);\n    pc = 100.0 * sum / tests;\n\n    printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n    srand(time(0));\n\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n    t := cylinder[5]\n    for i := 4; i >= 0; i-- {\n        cylinder[i+1] = cylinder[i]\n    }\n    cylinder[0] = t\n}\n\nfunc unload() {\n    for i := 0; i < 6; i++ {\n        cylinder[i] = false\n    }\n}\n\nfunc load() {\n    for cylinder[0] {\n        rshift()\n    }\n    cylinder[0] = true\n    rshift()\n}\n\nfunc spin() {\n    var lim = 1 + rand.Intn(6)\n    for i := 1; i < lim; i++ {\n        rshift()\n    }\n}\n\nfunc fire() bool {\n    shot := cylinder[0]\n    rshift()\n    return shot\n}\n\nfunc method(s string) int {\n    unload()\n    for _, c := range s {\n        switch c {\n        case 'L':\n            load()\n        case 'S':\n            spin()\n        case 'F':\n            if fire() {\n                return 1\n            }\n        }\n    }\n    return 0\n}\n\nfunc mstring(s string) string {\n    var l []string\n    for _, c := range s {\n        switch c {\n        case 'L':\n            l = append(l, \"load\")\n        case 'S':\n            l = append(l, \"spin\")\n        case 'F':\n            l = append(l, \"fire\")\n        }\n    }\n    return strings.Join(l, \", \")\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := 100000\n    for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n        sum := 0\n        for t := 1; t <= tests; t++ {\n            sum += method(m)\n        }\n        pc := float64(sum) * 100 / float64(tests)\n        fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n    }\n}\n"}
{"id": 52954, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 52955, "name": "Parsing_Shunting-yard algorithm", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 52956, "name": "Prime triangle", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n"}
{"id": 52957, "name": "Trabb Pardo–Knuth algorithm", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 52958, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 52959, "name": "Sequence_ nth number with exactly n divisors", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 52960, "name": "Sequence_ smallest number with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n"}
{"id": 52961, "name": "Pancake numbers", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52962, "name": "Pancake numbers", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 52963, "name": "Generate random chess position", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n"}
{"id": 52964, "name": "Esthetic numbers", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n"}
{"id": 52965, "name": "Esthetic numbers", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n"}
{"id": 52966, "name": "Topswops", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n"}
{"id": 52967, "name": "Old Russian measure of length", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n"}
{"id": 52968, "name": "Rate counter", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n"}
{"id": 52969, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 52970, "name": "Padovan sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n"}
{"id": 52971, "name": "Padovan sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n"}
{"id": 52972, "name": "Pythagoras tree", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n"}
{"id": 52973, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 52974, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 52975, "name": "Colorful numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 52976, "name": "Colorful numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 52977, "name": "Rosetta Code_Tasks without examples", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_tasks_without_examples.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"html\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {    \n    ex := `<li><a href=\"/wiki/(.*?)\"`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    tasks := make([]string, len(matches))\n    for i, match := range matches {\n        tasks[i] = match[1]\n    }\n    const base = \"http:\n    const limit = 3 \n    ex = `(?s)using any language you may know.</div>(.*?)<div id=\"toc\"`\n    ex2 := `</?[^>]*>` \n    re = regexp.MustCompile(ex)\n    re2 := regexp.MustCompile(ex2)\n    for i, task := range tasks {\n        page = base + task\n        resp, _ = http.Get(page)\n        body, _ = ioutil.ReadAll(resp.Body)\n        match := re.FindStringSubmatch(string(body))\n        resp.Body.Close()\n        text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], \"\"))\n        fmt.Println(strings.Replace(task, \"_\", \" \", -1), \"\\n\", text)\n        if i == limit-1 {\n            break\n        }\n        time.Sleep(5 * time.Second) \n    }\n}\n"}
{"id": 52978, "name": "Biorhythms", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n"}
{"id": 52979, "name": "Biorhythms", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n"}
{"id": 52980, "name": "Table creation_Postal addresses", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n"}
{"id": 52981, "name": "Sine wave", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n\nint header[] = {46, 115, 110, 100, 0, 0, 0, 24,\n                255, 255, 255, 255, 0, 0, 0, 3,\n                0, 0, 172, 68, 0, 0, 0, 1};\n\nint main(int argc, char *argv[]){\n        float freq, dur;\n        long i, v;\n\n        if (argc < 3) {\n                printf(\"Usage:\\n\");\n                printf(\"  csine <frequency> <duration>\\n\");\n                exit(1);\n        }\n        freq = atof(argv[1]);\n        dur = atof(argv[2]);\n        for (i = 0; i < 24; i++)\n                putchar(header[i]);\n        for (i = 0; i < dur * 44100; i++) {\n                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));\n                v = v % 65536;\n                putchar(v >> 8);\n                putchar(v % 256);\n        }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os/exec\"\n)\n\nfunc main() {\n    synthType := \"sine\"\n    duration := \"5\"\n    frequency := \"440\"\n    cmd := exec.Command(\"play\", \"-n\", \"synth\", duration, synthType, frequency)\n    err := cmd.Run()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 52982, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n"}
{"id": 52983, "name": "Compiler_code generator", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n"}
{"id": 52984, "name": "Include a file", "C": "\n#include <stdlib.h>\n\n\n#include \"myutil.h\"\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 52985, "name": "Include a file", "C": "\n#include <stdlib.h>\n\n\n#include \"myutil.h\"\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 52986, "name": "VList", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct sublist{\n\tstruct sublist* next;\n\tint *buf;\n} sublist_t;\n\nsublist_t* sublist_new(size_t s)\n{\n\tsublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);\n\tsub->buf = (int*)(sub + 1);\n\tsub->next = 0;\n\treturn sub;\n}\n\ntypedef struct vlist_t {\n\tsublist_t* head;\n\tsize_t last_size, ofs;\n} vlist_t, *vlist;\n\nvlist v_new()\n{\n\tvlist v = malloc(sizeof(vlist_t));\n\tv->head = sublist_new(1);\n\tv->last_size = 1;\n\tv->ofs = 0;\n\treturn v;\n}\n\nvoid v_del(vlist v)\n{\n\tsublist_t *s;\n\twhile (v->head) {\n\t\ts = v->head->next;\n\t\tfree(v->head);\n\t\tv->head = s;\n\t}\n\tfree(v);\n}\n\ninline size_t v_size(vlist v)\n{\n\treturn v->last_size * 2 - v->ofs - 2;\n}\n\nint* v_addr(vlist v, size_t idx)\n{\n\tsublist_t *s = v->head;\n\tsize_t top = v->last_size, i = idx + v->ofs;\n\n\tif (i + 2 >= (top << 1)) {\n\t\tfprintf(stderr, \"!: idx %d out of range\\n\", (int)idx);\n\t\tabort();\n\t}\n\twhile (s && i >= top) {\n\t\ts = s->next, i ^= top;\n\t\ttop >>= 1;\n\t}\n\treturn s->buf + i;\n}\n\ninline int v_elem(vlist v, size_t idx)\n{\n\treturn *v_addr(v, idx);\n}\n\nint* v_unshift(vlist v, int x)\n{\n\tsublist_t* s;\n\tint *p;\n\n\tif (!v->ofs) {\n\t\tif (!(s = sublist_new(v->last_size << 1))) {\n\t\t\tfprintf(stderr, \"?: alloc failure\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tv->ofs = (v->last_size <<= 1);\n\t\ts->next = v->head;\n\t\tv->head = s;\n\t}\n\t*(p = v->head->buf + --v->ofs) = x;\n\treturn p;\n}\n\nint v_shift(vlist v)\n{\n\tsublist_t* s;\n\tint x;\n\n\tif (v->last_size == 1 && v->ofs == 1) {\n\t\tfprintf(stderr, \"!: empty list\\n\");\n\t\tabort();\n\t}\n\tx = v->head->buf[v->ofs++];\n\n\tif (v->ofs == v->last_size) {\n\t\tv->ofs = 0;\n\t\tif (v->last_size > 1) {\n\t\t\ts = v->head, v->head = s->next;\n\t\t\tv->last_size >>= 1;\n\t\t\tfree(s);\n\t\t}\n\t}\n\treturn x;\n}\n\nint main()\n{\n\tint i;\n\n\tvlist v = v_new();\n\tfor (i = 0; i < 10; i++) v_unshift(v, i);\n\n\tprintf(\"size: %d\\n\", v_size(v));\n\tfor (i = 0; i < 10; i++) printf(\"v[%d] = %d\\n\", i, v_elem(v, i));\n\tfor (i = 0; i < 10; i++) printf(\"shift: %d\\n\", v_shift(v));\n\n\t \n\n\tv_del(v);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\" \n\ntype vList struct {\n    base   *vSeg\n    offset int\n}\n\ntype vSeg struct {\n    next *vSeg\n    ele  []vEle\n}\n\n\ntype vEle string\n    \n\nfunc (v vList) index(i int) (r vEle) {\n    if i >= 0 { \n        i += v.offset\n        for sg := v.base; sg != nil; sg = sg.next {\n            if i < len(sg.ele) {\n                return sg.ele[i]\n            }\n            i -= len(sg.ele)\n        }\n    }\n    \n    panic(\"index out of range\")\n}\n\n\nfunc (v vList) cons(a vEle) vList {\n    if v.base == nil {\n        return vList{base: &vSeg{ele: []vEle{a}}}\n    }\n    if v.offset == 0 {\n        l2 := len(v.base.ele) * 2 \n        ele := make([]vEle, l2)\n        ele[l2-1] = a\n        return vList{&vSeg{v.base, ele}, l2 - 1}\n    }\n    v.offset--\n    v.base.ele[v.offset] = a\n    return v\n}   \n\n\n\nfunc (v vList) cdr() vList {\n    if v.base == nil {\n        \n        panic(\"cdr on empty vList\")\n    }\n    v.offset++\n    if v.offset < len(v.base.ele) {\n        return v\n    }\n    return vList{v.base.next, 0}\n}\n\n\nfunc (v vList) length() int {\n    if v.base == nil {\n        return 0\n    }\n    return len(v.base.ele)*2 - v.offset - 1\n}\n\n\nfunc (v vList) String() string {\n    if v.base == nil {\n        return \"[]\"\n    }\n    r := fmt.Sprintf(\"[%v\", v.base.ele[v.offset])\n    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {\n        for _, e := range sl {\n            r = fmt.Sprintf(\"%s %v\", r, e)\n        }\n        sg = sg.next\n        if sg == nil {\n            break\n        }\n        sl = sg.ele\n    }\n    return r + \"]\"\n}\n\n\nfunc (v vList) printStructure() {\n    fmt.Println(\"offset:\", v.offset)\n    for sg := v.base; sg != nil; sg = sg.next {\n        fmt.Printf(\"  %q\\n\", sg.ele) \n    }\n    fmt.Println()\n}\n\n\nfunc main() {\n    var v vList\n    fmt.Println(\"zero value for type.  empty vList:\", v)\n    v.printStructure()\n\n    for a := '6'; a >= '1'; a-- {\n        v = v.cons(vEle(a))\n    }\n    fmt.Println(\"demonstrate cons. 6 elements added:\", v)\n    v.printStructure()\n    \n    v = v.cdr()\n    fmt.Println(\"demonstrate cdr. 1 element removed:\", v)\n    v.printStructure()\n\n    fmt.Println(\"demonstrate length. length =\", v.length())\n    fmt.Println()\n\n    fmt.Println(\"demonstrate element access. v[3] =\", v.index(3))\n    fmt.Println()\n\n    v = v.cdr().cdr()\n    fmt.Println(\"show cdr releasing segment. 2 elements removed:\", v)\n    v.printStructure()\n}\n"}
{"id": 52987, "name": "VList", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct sublist{\n\tstruct sublist* next;\n\tint *buf;\n} sublist_t;\n\nsublist_t* sublist_new(size_t s)\n{\n\tsublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);\n\tsub->buf = (int*)(sub + 1);\n\tsub->next = 0;\n\treturn sub;\n}\n\ntypedef struct vlist_t {\n\tsublist_t* head;\n\tsize_t last_size, ofs;\n} vlist_t, *vlist;\n\nvlist v_new()\n{\n\tvlist v = malloc(sizeof(vlist_t));\n\tv->head = sublist_new(1);\n\tv->last_size = 1;\n\tv->ofs = 0;\n\treturn v;\n}\n\nvoid v_del(vlist v)\n{\n\tsublist_t *s;\n\twhile (v->head) {\n\t\ts = v->head->next;\n\t\tfree(v->head);\n\t\tv->head = s;\n\t}\n\tfree(v);\n}\n\ninline size_t v_size(vlist v)\n{\n\treturn v->last_size * 2 - v->ofs - 2;\n}\n\nint* v_addr(vlist v, size_t idx)\n{\n\tsublist_t *s = v->head;\n\tsize_t top = v->last_size, i = idx + v->ofs;\n\n\tif (i + 2 >= (top << 1)) {\n\t\tfprintf(stderr, \"!: idx %d out of range\\n\", (int)idx);\n\t\tabort();\n\t}\n\twhile (s && i >= top) {\n\t\ts = s->next, i ^= top;\n\t\ttop >>= 1;\n\t}\n\treturn s->buf + i;\n}\n\ninline int v_elem(vlist v, size_t idx)\n{\n\treturn *v_addr(v, idx);\n}\n\nint* v_unshift(vlist v, int x)\n{\n\tsublist_t* s;\n\tint *p;\n\n\tif (!v->ofs) {\n\t\tif (!(s = sublist_new(v->last_size << 1))) {\n\t\t\tfprintf(stderr, \"?: alloc failure\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tv->ofs = (v->last_size <<= 1);\n\t\ts->next = v->head;\n\t\tv->head = s;\n\t}\n\t*(p = v->head->buf + --v->ofs) = x;\n\treturn p;\n}\n\nint v_shift(vlist v)\n{\n\tsublist_t* s;\n\tint x;\n\n\tif (v->last_size == 1 && v->ofs == 1) {\n\t\tfprintf(stderr, \"!: empty list\\n\");\n\t\tabort();\n\t}\n\tx = v->head->buf[v->ofs++];\n\n\tif (v->ofs == v->last_size) {\n\t\tv->ofs = 0;\n\t\tif (v->last_size > 1) {\n\t\t\ts = v->head, v->head = s->next;\n\t\t\tv->last_size >>= 1;\n\t\t\tfree(s);\n\t\t}\n\t}\n\treturn x;\n}\n\nint main()\n{\n\tint i;\n\n\tvlist v = v_new();\n\tfor (i = 0; i < 10; i++) v_unshift(v, i);\n\n\tprintf(\"size: %d\\n\", v_size(v));\n\tfor (i = 0; i < 10; i++) printf(\"v[%d] = %d\\n\", i, v_elem(v, i));\n\tfor (i = 0; i < 10; i++) printf(\"shift: %d\\n\", v_shift(v));\n\n\t \n\n\tv_del(v);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\" \n\ntype vList struct {\n    base   *vSeg\n    offset int\n}\n\ntype vSeg struct {\n    next *vSeg\n    ele  []vEle\n}\n\n\ntype vEle string\n    \n\nfunc (v vList) index(i int) (r vEle) {\n    if i >= 0 { \n        i += v.offset\n        for sg := v.base; sg != nil; sg = sg.next {\n            if i < len(sg.ele) {\n                return sg.ele[i]\n            }\n            i -= len(sg.ele)\n        }\n    }\n    \n    panic(\"index out of range\")\n}\n\n\nfunc (v vList) cons(a vEle) vList {\n    if v.base == nil {\n        return vList{base: &vSeg{ele: []vEle{a}}}\n    }\n    if v.offset == 0 {\n        l2 := len(v.base.ele) * 2 \n        ele := make([]vEle, l2)\n        ele[l2-1] = a\n        return vList{&vSeg{v.base, ele}, l2 - 1}\n    }\n    v.offset--\n    v.base.ele[v.offset] = a\n    return v\n}   \n\n\n\nfunc (v vList) cdr() vList {\n    if v.base == nil {\n        \n        panic(\"cdr on empty vList\")\n    }\n    v.offset++\n    if v.offset < len(v.base.ele) {\n        return v\n    }\n    return vList{v.base.next, 0}\n}\n\n\nfunc (v vList) length() int {\n    if v.base == nil {\n        return 0\n    }\n    return len(v.base.ele)*2 - v.offset - 1\n}\n\n\nfunc (v vList) String() string {\n    if v.base == nil {\n        return \"[]\"\n    }\n    r := fmt.Sprintf(\"[%v\", v.base.ele[v.offset])\n    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {\n        for _, e := range sl {\n            r = fmt.Sprintf(\"%s %v\", r, e)\n        }\n        sg = sg.next\n        if sg == nil {\n            break\n        }\n        sl = sg.ele\n    }\n    return r + \"]\"\n}\n\n\nfunc (v vList) printStructure() {\n    fmt.Println(\"offset:\", v.offset)\n    for sg := v.base; sg != nil; sg = sg.next {\n        fmt.Printf(\"  %q\\n\", sg.ele) \n    }\n    fmt.Println()\n}\n\n\nfunc main() {\n    var v vList\n    fmt.Println(\"zero value for type.  empty vList:\", v)\n    v.printStructure()\n\n    for a := '6'; a >= '1'; a-- {\n        v = v.cons(vEle(a))\n    }\n    fmt.Println(\"demonstrate cons. 6 elements added:\", v)\n    v.printStructure()\n    \n    v = v.cdr()\n    fmt.Println(\"demonstrate cdr. 1 element removed:\", v)\n    v.printStructure()\n\n    fmt.Println(\"demonstrate length. length =\", v.length())\n    fmt.Println()\n\n    fmt.Println(\"demonstrate element access. v[3] =\", v.index(3))\n    fmt.Println()\n\n    v = v.cdr().cdr()\n    fmt.Println(\"show cdr releasing segment. 2 elements removed:\", v)\n    v.printStructure()\n}\n"}
{"id": 52988, "name": "VList", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct sublist{\n\tstruct sublist* next;\n\tint *buf;\n} sublist_t;\n\nsublist_t* sublist_new(size_t s)\n{\n\tsublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);\n\tsub->buf = (int*)(sub + 1);\n\tsub->next = 0;\n\treturn sub;\n}\n\ntypedef struct vlist_t {\n\tsublist_t* head;\n\tsize_t last_size, ofs;\n} vlist_t, *vlist;\n\nvlist v_new()\n{\n\tvlist v = malloc(sizeof(vlist_t));\n\tv->head = sublist_new(1);\n\tv->last_size = 1;\n\tv->ofs = 0;\n\treturn v;\n}\n\nvoid v_del(vlist v)\n{\n\tsublist_t *s;\n\twhile (v->head) {\n\t\ts = v->head->next;\n\t\tfree(v->head);\n\t\tv->head = s;\n\t}\n\tfree(v);\n}\n\ninline size_t v_size(vlist v)\n{\n\treturn v->last_size * 2 - v->ofs - 2;\n}\n\nint* v_addr(vlist v, size_t idx)\n{\n\tsublist_t *s = v->head;\n\tsize_t top = v->last_size, i = idx + v->ofs;\n\n\tif (i + 2 >= (top << 1)) {\n\t\tfprintf(stderr, \"!: idx %d out of range\\n\", (int)idx);\n\t\tabort();\n\t}\n\twhile (s && i >= top) {\n\t\ts = s->next, i ^= top;\n\t\ttop >>= 1;\n\t}\n\treturn s->buf + i;\n}\n\ninline int v_elem(vlist v, size_t idx)\n{\n\treturn *v_addr(v, idx);\n}\n\nint* v_unshift(vlist v, int x)\n{\n\tsublist_t* s;\n\tint *p;\n\n\tif (!v->ofs) {\n\t\tif (!(s = sublist_new(v->last_size << 1))) {\n\t\t\tfprintf(stderr, \"?: alloc failure\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tv->ofs = (v->last_size <<= 1);\n\t\ts->next = v->head;\n\t\tv->head = s;\n\t}\n\t*(p = v->head->buf + --v->ofs) = x;\n\treturn p;\n}\n\nint v_shift(vlist v)\n{\n\tsublist_t* s;\n\tint x;\n\n\tif (v->last_size == 1 && v->ofs == 1) {\n\t\tfprintf(stderr, \"!: empty list\\n\");\n\t\tabort();\n\t}\n\tx = v->head->buf[v->ofs++];\n\n\tif (v->ofs == v->last_size) {\n\t\tv->ofs = 0;\n\t\tif (v->last_size > 1) {\n\t\t\ts = v->head, v->head = s->next;\n\t\t\tv->last_size >>= 1;\n\t\t\tfree(s);\n\t\t}\n\t}\n\treturn x;\n}\n\nint main()\n{\n\tint i;\n\n\tvlist v = v_new();\n\tfor (i = 0; i < 10; i++) v_unshift(v, i);\n\n\tprintf(\"size: %d\\n\", v_size(v));\n\tfor (i = 0; i < 10; i++) printf(\"v[%d] = %d\\n\", i, v_elem(v, i));\n\tfor (i = 0; i < 10; i++) printf(\"shift: %d\\n\", v_shift(v));\n\n\t \n\n\tv_del(v);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\" \n\ntype vList struct {\n    base   *vSeg\n    offset int\n}\n\ntype vSeg struct {\n    next *vSeg\n    ele  []vEle\n}\n\n\ntype vEle string\n    \n\nfunc (v vList) index(i int) (r vEle) {\n    if i >= 0 { \n        i += v.offset\n        for sg := v.base; sg != nil; sg = sg.next {\n            if i < len(sg.ele) {\n                return sg.ele[i]\n            }\n            i -= len(sg.ele)\n        }\n    }\n    \n    panic(\"index out of range\")\n}\n\n\nfunc (v vList) cons(a vEle) vList {\n    if v.base == nil {\n        return vList{base: &vSeg{ele: []vEle{a}}}\n    }\n    if v.offset == 0 {\n        l2 := len(v.base.ele) * 2 \n        ele := make([]vEle, l2)\n        ele[l2-1] = a\n        return vList{&vSeg{v.base, ele}, l2 - 1}\n    }\n    v.offset--\n    v.base.ele[v.offset] = a\n    return v\n}   \n\n\n\nfunc (v vList) cdr() vList {\n    if v.base == nil {\n        \n        panic(\"cdr on empty vList\")\n    }\n    v.offset++\n    if v.offset < len(v.base.ele) {\n        return v\n    }\n    return vList{v.base.next, 0}\n}\n\n\nfunc (v vList) length() int {\n    if v.base == nil {\n        return 0\n    }\n    return len(v.base.ele)*2 - v.offset - 1\n}\n\n\nfunc (v vList) String() string {\n    if v.base == nil {\n        return \"[]\"\n    }\n    r := fmt.Sprintf(\"[%v\", v.base.ele[v.offset])\n    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {\n        for _, e := range sl {\n            r = fmt.Sprintf(\"%s %v\", r, e)\n        }\n        sg = sg.next\n        if sg == nil {\n            break\n        }\n        sl = sg.ele\n    }\n    return r + \"]\"\n}\n\n\nfunc (v vList) printStructure() {\n    fmt.Println(\"offset:\", v.offset)\n    for sg := v.base; sg != nil; sg = sg.next {\n        fmt.Printf(\"  %q\\n\", sg.ele) \n    }\n    fmt.Println()\n}\n\n\nfunc main() {\n    var v vList\n    fmt.Println(\"zero value for type.  empty vList:\", v)\n    v.printStructure()\n\n    for a := '6'; a >= '1'; a-- {\n        v = v.cons(vEle(a))\n    }\n    fmt.Println(\"demonstrate cons. 6 elements added:\", v)\n    v.printStructure()\n    \n    v = v.cdr()\n    fmt.Println(\"demonstrate cdr. 1 element removed:\", v)\n    v.printStructure()\n\n    fmt.Println(\"demonstrate length. length =\", v.length())\n    fmt.Println()\n\n    fmt.Println(\"demonstrate element access. v[3] =\", v.index(3))\n    fmt.Println()\n\n    v = v.cdr().cdr()\n    fmt.Println(\"show cdr releasing segment. 2 elements removed:\", v)\n    v.printStructure()\n}\n"}
{"id": 52989, "name": "Stern-Brocot sequence", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n"}
{"id": 52990, "name": "Useless instructions", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nvoid uselessFunc(int uselessParam) { \n    auto int i; \n\n    if (true) {\n        \n    } else {\n        printf(\"Never called\\n\");\n    }\n\n    for (i = 0; i < 0; ++i) {\n        printf(\"Never called\\n\");\n    }\n\n    while (false) {\n        printf(\"Never called\\n\");\n    }\n\n    printf(\"\"); \n\n    return; \n}\n\nstruct UselessStruct {\n    \n};\n\nint main() {\n    uselessFunc(0);\n    printf(\"Working OK.\\n\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\ntype any = interface{}\n\nfunc uselessFunc(uselessParam any) { \n    if true {\n        \n    } else {\n        fmt.Println(\"Never called\")\n    }\n\n    for range []any{} {\n        fmt.Println(\"Never called\")\n    }\n\n    for false {\n        fmt.Println(\"Never called\")\n    }\n\n    fmt.Print(\"\") \n\n    return \n}\n\ntype NotCompletelyUseless struct {\n    \n}\n\nfunc main() {\n    uselessFunc(0)\n    set := make(map[int]NotCompletelyUseless)\n    set[0] = NotCompletelyUseless{}\n    set[0] = NotCompletelyUseless{} \n    fmt.Println(set)\n}\n"}
{"id": 52991, "name": "Numeric error propagation", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n"}
{"id": 52992, "name": "Soundex", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n"}
{"id": 52993, "name": "List rooted trees", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n"}
{"id": 52994, "name": "Documentation", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n"}
{"id": 52995, "name": "Table creation", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n"}
{"id": 52996, "name": "Table creation", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n"}
{"id": 52997, "name": "Problem of Apollonius", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n"}
{"id": 52998, "name": "Morpion solitaire", "C": "#include <ncurses.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <time.h>\n\n\nint line_len = 5;\n\n\nint disjoint = 0;\n\nint **board = 0, width, height;\n\n#define for_i for(i = 0; i < height; i++)\n#define for_j for(j = 0; j < width; j++)\nenum {\n\ts_blank\t\t= 0,\n\ts_occupied\t= 1 << 0,\n\ts_dir_ns\t= 1 << 1,\n\ts_dir_ew\t= 1 << 2,\n\ts_dir_ne_sw\t= 1 << 3,\n\ts_dir_nw_se\t= 1 << 4,\n\ts_newly_added\t= 1 << 5,\n\ts_current\t= 1 << 6,\n};\n\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / n);\n}\n\nint** alloc_board(int w, int h)\n{\n\tint i;\n\tint **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);\n\n\tbuf[0] = (int*)(buf + h);\n\tfor (i = 1; i < h; i++)\n\t\tbuf[i] = buf[i - 1] + w;\n\treturn buf;\n}\n\n\nvoid expand_board(int dw, int dh)\n{\n\tint i, j;\n\tint nw = width + !!dw, nh = height + !!dh;\n\n\t\n\tint **nbuf = alloc_board(nw, nh);\n\n\tdw = -(dw < 0), dh = -(dh < 0);\n\n\tfor (i = 0; i < nh; i++) {\n\t\tif (i + dh < 0 || i + dh >= height) continue;\n\t\tfor (j = 0; j < nw; j++) {\n\t\t\tif (j + dw < 0 || j + dw >= width) continue;\n\t\t\tnbuf[i][j] = board[i + dh][j + dw];\n\t\t}\n\t}\n\tfree(board);\n\n\tboard = nbuf;\n\twidth = nw;\n\theight = nh;\n}\n\nvoid array_set(int **buf, int v, int x0, int y0, int x1, int y1)\n{\n\tint i, j;\n\tfor (i = y0; i <= y1; i++)\n\t\tfor (j = x0; j <= x1; j++)\n\t\t\tbuf[i][j] = v;\n}\n\nvoid show_board()\n{\n\tint i, j;\n\tfor_i for_j mvprintw(i + 1, j * 2,\n\t\t\t(board[i][j] & s_current) ? \"X \"\n\t\t\t: (board[i][j] & s_newly_added) ? \"O \"\n\t\t\t: (board[i][j] & s_occupied) ? \"+ \" : \"  \");\n\trefresh();\n}\n\nvoid init_board()\n{\n\twidth = height = 3 * (line_len - 1);\n\tboard = alloc_board(width, height);\n\n\tarray_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);\n\tarray_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);\n\n\tarray_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);\n\tarray_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);\n}\n\nint ofs[4][3] = {\n\t{0, 1, s_dir_ns},\n\t{1, 0, s_dir_ew},\n\t{1, -1, s_dir_ne_sw},\n\t{1, 1, s_dir_nw_se}\n};\n\ntypedef struct { int m, s, seq, x, y; } move_t;\n\n\nvoid test_postion(int y, int x, move_t * rec)\n{\n\tint m, k, s, dx, dy, xx, yy, dir;\n\tif (board[y][x] & s_occupied) return;\n\n\tfor (m = 0; m < 4; m++) { \n\t\tdx = ofs[m][0];\n\t\tdy = ofs[m][1];\n\t\tdir = ofs[m][2];\n\n\t\tfor (s = 1 - line_len; s <= 0; s++) { \n\t\t\tfor (k = 0; k < line_len; k++) {\n\t\t\t\tif (s + k == 0) continue;\n\n\t\t\t\txx = x + dx * (s + k);\n\t\t\t\tyy = y + dy * (s + k);\n\t\t\t\tif (xx < 0 || xx >= width || yy < 0 || yy >= height)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\n\t\t\t\tif (!(board[yy][xx] & s_occupied)) break;\n\n\t\t\t\t\n\t\t\t\tif ((board[yy][xx] & dir)) break;\n\t\t\t}\n\t\t\tif (k != line_len) continue;\n\n\t\t\t\n\t\t\tif (! irand(++rec->seq))\n\t\t\t\trec->m = m, rec->s = s, rec->x = x, rec->y = y;\n\t\t}\n\t}\n}\n\nvoid add_piece(move_t *rec) {\n\tint dx = ofs[rec->m][0];\n\tint dy = ofs[rec->m][1];\n\tint dir= ofs[rec->m][2];\n\tint xx, yy, k;\n\n\tboard[rec->y][rec->x] |= (s_current | s_occupied);\n\n\tfor (k = 0; k < line_len; k++) {\n\t\txx = rec->x + dx * (k + rec->s);\n\t\tyy = rec->y + dy * (k + rec->s);\n\t\tboard[yy][xx] |= s_newly_added;\n\t\tif (k >= disjoint || k < line_len - disjoint)\n\t\t\tboard[yy][xx] |= dir;\n\t}\n}\n\nint next_move()\n{\n\tint i, j;\n\tmove_t rec;\n\trec.seq = 0;\n\n\t\n\tfor_i for_j board[i][j] &= ~(s_newly_added | s_current);\n\n\t\n\tfor_i for_j test_postion(i, j, &rec);\n\n\t\n\tif (!rec.seq) return 0;\n\n\tadd_piece(&rec);\n\n\trec.x = (rec.x == width  - 1) ? 1 : rec.x ? 0 : -1;\n\trec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;\n\n\tif (rec.x || rec.y) expand_board(rec.x, rec.y);\n\treturn 1;\n}\n\nint main()\n{\n\tint ch = 0;\n\tint move = 0;\n\tint wait_key = 1;\n\n\tinit_board();\n\tsrand(time(0));\n\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\n\tdo  {\n\t\tmvprintw(0, 0, \"Move %d\", move++);\n\t\tshow_board();\n\t\tif (!next_move()) {\n\t\t\tnext_move();\n\t\t\tshow_board();\n\t\t\tbreak;\n\t\t}\n\t\tif (!wait_key) usleep(100000);\n\t\tif ((ch = getch()) == ' ') {\n\t\t\twait_key = !wait_key;\n\t\t\tif (wait_key) timeout(-1);\n\t\t\telse timeout(0);\n\t\t}\n\t} while (ch != 'q');\n\n\ttimeout(-1);\n\tnocbreak();\n\techo();\n\n\tendwin();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nconst (\n    lineLen  = 5\n    disjoint = 0\n)\n\nvar (\n    board  [][]int\n    width  int\n    height int\n)\n\nconst (\n    blank    = 0\n    occupied = 1 << (iota - 1)\n    dirNS\n    dirEW\n    dirNESW\n    dirNWSE\n    newlyAdded\n    current\n)\n\nvar ofs = [4][3]int{\n    {0, 1, dirNS},\n    {1, 0, dirEW},\n    {1, -1, dirNESW},\n    {1, 1, dirNWSE},\n}\n\ntype move struct{ m, s, seq, x, y int }\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc allocBoard(w, h int) [][]int {\n    buf := make([][]int, h)\n    for i := 0; i < h; i++ {\n        buf[i] = make([]int, w)\n    }\n    return buf\n}\n\nfunc boardSet(v, x0, y0, x1, y1 int) {\n    for i := y0; i <= y1; i++ {\n        for j := x0; j <= x1; j++ {\n            board[i][j] = v\n        }\n    }\n}\n\nfunc initBoard() {\n    height = 3 * (lineLen - 1)\n    width = height\n    board = allocBoard(width, height)\n\n    boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)\n    boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)\n    boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)\n    boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)\n}\n\n\nfunc expandBoard(dw, dh int) {\n    dw2, dh2 := 1, 1\n    if dw == 0 {\n        dw2 = 0\n    }\n    if dh == 0 {\n        dh2 = 0\n    }\n    nw, nh := width+dw2, height+dh2\n    nbuf := allocBoard(nw, nh)\n    dw, dh = -btoi(dw < 0), -btoi(dh < 0)\n    for i := 0; i < nh; i++ {\n        if i+dh < 0 || i+dh >= height {\n            continue\n        }\n        for j := 0; j < nw; j++ {\n            if j+dw < 0 || j+dw >= width {\n                continue\n            }\n            nbuf[i][j] = board[i+dh][j+dw]\n        }\n    }\n    board = nbuf\n    width, height = nw, nh\n}\n\nfunc showBoard(scr *gc.Window) {\n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            var temp string\n            switch {\n            case (board[i][j] & current) != 0:\n                temp = \"X \"\n            case (board[i][j] & newlyAdded) != 0:\n                temp = \"0 \"\n            case (board[i][j] & occupied) != 0:\n                temp = \"+ \"\n            default:\n                temp = \"  \"\n            }\n            scr.MovePrintf(i+1, j*2, temp)\n        }\n    }\n    scr.Refresh()\n}\n\n\nfunc testPosition(y, x int, rec *move) {\n    if (board[y][x] & occupied) != 0 {\n        return\n    }\n    for m := 0; m < 4; m++ { \n        dx := ofs[m][0]\n        dy := ofs[m][1]\n        dir := ofs[m][2]\n        var k int\n        for s := 1 - lineLen; s <= 0; s++ { \n            for k = 0; k < lineLen; k++ {\n                if s+k == 0 {\n                    continue\n                }\n                xx := x + dx*(s+k)\n                yy := y + dy*(s+k)\n                if xx < 0 || xx >= width || yy < 0 || yy >= height {\n                    break\n                }\n\n                \n                if (board[yy][xx] & occupied) == 0 {\n                    break\n                }\n\n                \n                if (board[yy][xx] & dir) != 0 {\n                    break\n                }\n            }\n            if k != lineLen {\n                continue\n            }\n\n            \n            \n            rec.seq++\n            if rand.Intn(rec.seq) == 0 {\n                rec.m, rec.s, rec.x, rec.y = m, s, x, y\n            }\n        }\n    }\n}\n\nfunc addPiece(rec *move) {\n    dx := ofs[rec.m][0]\n    dy := ofs[rec.m][1]\n    dir := ofs[rec.m][2]\n    board[rec.y][rec.x] |= current | occupied\n    for k := 0; k < lineLen; k++ {\n        xx := rec.x + dx*(k+rec.s)\n        yy := rec.y + dy*(k+rec.s)\n        board[yy][xx] |= newlyAdded\n        if k >= disjoint || k < lineLen-disjoint {\n            board[yy][xx] |= dir\n        }\n    }\n}\n\nfunc nextMove() bool {\n    var rec move\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            board[i][j] &^= newlyAdded | current\n        }\n    }\n\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            testPosition(i, j, &rec)\n        }\n    }\n\n    \n    if rec.seq == 0 {\n        return false\n    }\n\n    addPiece(&rec)\n\n    if rec.x == width-1 {\n        rec.x = 1\n    } else if rec.x != 0 {\n        rec.x = 0\n    } else {\n        rec.x = -1\n    }\n\n    if rec.y == height-1 {\n        rec.y = 1\n    } else if rec.y != 0 {\n        rec.y = 0\n    } else {\n        rec.y = -1\n    }\n\n    if rec.x != 0 || rec.y != 0 {\n        expandBoard(rec.x, rec.y)\n    }\n    return true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initBoard()\n    scr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n    gc.Echo(false)\n    gc.CBreak(true)\n    ch := gc.Key(0)\n    move := 0\n    waitKey := true\n    for {\n        scr.MovePrintf(0, 0, \"Move %d\", move)\n        move++\n        showBoard(scr)\n        if !nextMove() {\n            nextMove()\n            showBoard(scr)\n            break\n        }\n        if !waitKey {\n            time.Sleep(100000 * time.Microsecond)\n        }\n        if ch = scr.GetChar(); ch == ' ' {\n            waitKey = !waitKey\n            if waitKey {\n                scr.Timeout(-1)\n            } else {\n                scr.Timeout(0)\n            }\n        }\n        if ch == 'q' {\n            break\n        }\n    }\n    scr.Timeout(-1)\n    gc.CBreak(false)\n    gc.Echo(true)\n}\n"}
{"id": 52999, "name": "Morpion solitaire", "C": "#include <ncurses.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <time.h>\n\n\nint line_len = 5;\n\n\nint disjoint = 0;\n\nint **board = 0, width, height;\n\n#define for_i for(i = 0; i < height; i++)\n#define for_j for(j = 0; j < width; j++)\nenum {\n\ts_blank\t\t= 0,\n\ts_occupied\t= 1 << 0,\n\ts_dir_ns\t= 1 << 1,\n\ts_dir_ew\t= 1 << 2,\n\ts_dir_ne_sw\t= 1 << 3,\n\ts_dir_nw_se\t= 1 << 4,\n\ts_newly_added\t= 1 << 5,\n\ts_current\t= 1 << 6,\n};\n\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / n);\n}\n\nint** alloc_board(int w, int h)\n{\n\tint i;\n\tint **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);\n\n\tbuf[0] = (int*)(buf + h);\n\tfor (i = 1; i < h; i++)\n\t\tbuf[i] = buf[i - 1] + w;\n\treturn buf;\n}\n\n\nvoid expand_board(int dw, int dh)\n{\n\tint i, j;\n\tint nw = width + !!dw, nh = height + !!dh;\n\n\t\n\tint **nbuf = alloc_board(nw, nh);\n\n\tdw = -(dw < 0), dh = -(dh < 0);\n\n\tfor (i = 0; i < nh; i++) {\n\t\tif (i + dh < 0 || i + dh >= height) continue;\n\t\tfor (j = 0; j < nw; j++) {\n\t\t\tif (j + dw < 0 || j + dw >= width) continue;\n\t\t\tnbuf[i][j] = board[i + dh][j + dw];\n\t\t}\n\t}\n\tfree(board);\n\n\tboard = nbuf;\n\twidth = nw;\n\theight = nh;\n}\n\nvoid array_set(int **buf, int v, int x0, int y0, int x1, int y1)\n{\n\tint i, j;\n\tfor (i = y0; i <= y1; i++)\n\t\tfor (j = x0; j <= x1; j++)\n\t\t\tbuf[i][j] = v;\n}\n\nvoid show_board()\n{\n\tint i, j;\n\tfor_i for_j mvprintw(i + 1, j * 2,\n\t\t\t(board[i][j] & s_current) ? \"X \"\n\t\t\t: (board[i][j] & s_newly_added) ? \"O \"\n\t\t\t: (board[i][j] & s_occupied) ? \"+ \" : \"  \");\n\trefresh();\n}\n\nvoid init_board()\n{\n\twidth = height = 3 * (line_len - 1);\n\tboard = alloc_board(width, height);\n\n\tarray_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);\n\tarray_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);\n\n\tarray_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);\n\tarray_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);\n}\n\nint ofs[4][3] = {\n\t{0, 1, s_dir_ns},\n\t{1, 0, s_dir_ew},\n\t{1, -1, s_dir_ne_sw},\n\t{1, 1, s_dir_nw_se}\n};\n\ntypedef struct { int m, s, seq, x, y; } move_t;\n\n\nvoid test_postion(int y, int x, move_t * rec)\n{\n\tint m, k, s, dx, dy, xx, yy, dir;\n\tif (board[y][x] & s_occupied) return;\n\n\tfor (m = 0; m < 4; m++) { \n\t\tdx = ofs[m][0];\n\t\tdy = ofs[m][1];\n\t\tdir = ofs[m][2];\n\n\t\tfor (s = 1 - line_len; s <= 0; s++) { \n\t\t\tfor (k = 0; k < line_len; k++) {\n\t\t\t\tif (s + k == 0) continue;\n\n\t\t\t\txx = x + dx * (s + k);\n\t\t\t\tyy = y + dy * (s + k);\n\t\t\t\tif (xx < 0 || xx >= width || yy < 0 || yy >= height)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\n\t\t\t\tif (!(board[yy][xx] & s_occupied)) break;\n\n\t\t\t\t\n\t\t\t\tif ((board[yy][xx] & dir)) break;\n\t\t\t}\n\t\t\tif (k != line_len) continue;\n\n\t\t\t\n\t\t\tif (! irand(++rec->seq))\n\t\t\t\trec->m = m, rec->s = s, rec->x = x, rec->y = y;\n\t\t}\n\t}\n}\n\nvoid add_piece(move_t *rec) {\n\tint dx = ofs[rec->m][0];\n\tint dy = ofs[rec->m][1];\n\tint dir= ofs[rec->m][2];\n\tint xx, yy, k;\n\n\tboard[rec->y][rec->x] |= (s_current | s_occupied);\n\n\tfor (k = 0; k < line_len; k++) {\n\t\txx = rec->x + dx * (k + rec->s);\n\t\tyy = rec->y + dy * (k + rec->s);\n\t\tboard[yy][xx] |= s_newly_added;\n\t\tif (k >= disjoint || k < line_len - disjoint)\n\t\t\tboard[yy][xx] |= dir;\n\t}\n}\n\nint next_move()\n{\n\tint i, j;\n\tmove_t rec;\n\trec.seq = 0;\n\n\t\n\tfor_i for_j board[i][j] &= ~(s_newly_added | s_current);\n\n\t\n\tfor_i for_j test_postion(i, j, &rec);\n\n\t\n\tif (!rec.seq) return 0;\n\n\tadd_piece(&rec);\n\n\trec.x = (rec.x == width  - 1) ? 1 : rec.x ? 0 : -1;\n\trec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;\n\n\tif (rec.x || rec.y) expand_board(rec.x, rec.y);\n\treturn 1;\n}\n\nint main()\n{\n\tint ch = 0;\n\tint move = 0;\n\tint wait_key = 1;\n\n\tinit_board();\n\tsrand(time(0));\n\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\n\tdo  {\n\t\tmvprintw(0, 0, \"Move %d\", move++);\n\t\tshow_board();\n\t\tif (!next_move()) {\n\t\t\tnext_move();\n\t\t\tshow_board();\n\t\t\tbreak;\n\t\t}\n\t\tif (!wait_key) usleep(100000);\n\t\tif ((ch = getch()) == ' ') {\n\t\t\twait_key = !wait_key;\n\t\t\tif (wait_key) timeout(-1);\n\t\t\telse timeout(0);\n\t\t}\n\t} while (ch != 'q');\n\n\ttimeout(-1);\n\tnocbreak();\n\techo();\n\n\tendwin();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nconst (\n    lineLen  = 5\n    disjoint = 0\n)\n\nvar (\n    board  [][]int\n    width  int\n    height int\n)\n\nconst (\n    blank    = 0\n    occupied = 1 << (iota - 1)\n    dirNS\n    dirEW\n    dirNESW\n    dirNWSE\n    newlyAdded\n    current\n)\n\nvar ofs = [4][3]int{\n    {0, 1, dirNS},\n    {1, 0, dirEW},\n    {1, -1, dirNESW},\n    {1, 1, dirNWSE},\n}\n\ntype move struct{ m, s, seq, x, y int }\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc allocBoard(w, h int) [][]int {\n    buf := make([][]int, h)\n    for i := 0; i < h; i++ {\n        buf[i] = make([]int, w)\n    }\n    return buf\n}\n\nfunc boardSet(v, x0, y0, x1, y1 int) {\n    for i := y0; i <= y1; i++ {\n        for j := x0; j <= x1; j++ {\n            board[i][j] = v\n        }\n    }\n}\n\nfunc initBoard() {\n    height = 3 * (lineLen - 1)\n    width = height\n    board = allocBoard(width, height)\n\n    boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)\n    boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)\n    boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)\n    boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)\n}\n\n\nfunc expandBoard(dw, dh int) {\n    dw2, dh2 := 1, 1\n    if dw == 0 {\n        dw2 = 0\n    }\n    if dh == 0 {\n        dh2 = 0\n    }\n    nw, nh := width+dw2, height+dh2\n    nbuf := allocBoard(nw, nh)\n    dw, dh = -btoi(dw < 0), -btoi(dh < 0)\n    for i := 0; i < nh; i++ {\n        if i+dh < 0 || i+dh >= height {\n            continue\n        }\n        for j := 0; j < nw; j++ {\n            if j+dw < 0 || j+dw >= width {\n                continue\n            }\n            nbuf[i][j] = board[i+dh][j+dw]\n        }\n    }\n    board = nbuf\n    width, height = nw, nh\n}\n\nfunc showBoard(scr *gc.Window) {\n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            var temp string\n            switch {\n            case (board[i][j] & current) != 0:\n                temp = \"X \"\n            case (board[i][j] & newlyAdded) != 0:\n                temp = \"0 \"\n            case (board[i][j] & occupied) != 0:\n                temp = \"+ \"\n            default:\n                temp = \"  \"\n            }\n            scr.MovePrintf(i+1, j*2, temp)\n        }\n    }\n    scr.Refresh()\n}\n\n\nfunc testPosition(y, x int, rec *move) {\n    if (board[y][x] & occupied) != 0 {\n        return\n    }\n    for m := 0; m < 4; m++ { \n        dx := ofs[m][0]\n        dy := ofs[m][1]\n        dir := ofs[m][2]\n        var k int\n        for s := 1 - lineLen; s <= 0; s++ { \n            for k = 0; k < lineLen; k++ {\n                if s+k == 0 {\n                    continue\n                }\n                xx := x + dx*(s+k)\n                yy := y + dy*(s+k)\n                if xx < 0 || xx >= width || yy < 0 || yy >= height {\n                    break\n                }\n\n                \n                if (board[yy][xx] & occupied) == 0 {\n                    break\n                }\n\n                \n                if (board[yy][xx] & dir) != 0 {\n                    break\n                }\n            }\n            if k != lineLen {\n                continue\n            }\n\n            \n            \n            rec.seq++\n            if rand.Intn(rec.seq) == 0 {\n                rec.m, rec.s, rec.x, rec.y = m, s, x, y\n            }\n        }\n    }\n}\n\nfunc addPiece(rec *move) {\n    dx := ofs[rec.m][0]\n    dy := ofs[rec.m][1]\n    dir := ofs[rec.m][2]\n    board[rec.y][rec.x] |= current | occupied\n    for k := 0; k < lineLen; k++ {\n        xx := rec.x + dx*(k+rec.s)\n        yy := rec.y + dy*(k+rec.s)\n        board[yy][xx] |= newlyAdded\n        if k >= disjoint || k < lineLen-disjoint {\n            board[yy][xx] |= dir\n        }\n    }\n}\n\nfunc nextMove() bool {\n    var rec move\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            board[i][j] &^= newlyAdded | current\n        }\n    }\n\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            testPosition(i, j, &rec)\n        }\n    }\n\n    \n    if rec.seq == 0 {\n        return false\n    }\n\n    addPiece(&rec)\n\n    if rec.x == width-1 {\n        rec.x = 1\n    } else if rec.x != 0 {\n        rec.x = 0\n    } else {\n        rec.x = -1\n    }\n\n    if rec.y == height-1 {\n        rec.y = 1\n    } else if rec.y != 0 {\n        rec.y = 0\n    } else {\n        rec.y = -1\n    }\n\n    if rec.x != 0 || rec.y != 0 {\n        expandBoard(rec.x, rec.y)\n    }\n    return true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initBoard()\n    scr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n    gc.Echo(false)\n    gc.CBreak(true)\n    ch := gc.Key(0)\n    move := 0\n    waitKey := true\n    for {\n        scr.MovePrintf(0, 0, \"Move %d\", move)\n        move++\n        showBoard(scr)\n        if !nextMove() {\n            nextMove()\n            showBoard(scr)\n            break\n        }\n        if !waitKey {\n            time.Sleep(100000 * time.Microsecond)\n        }\n        if ch = scr.GetChar(); ch == ' ' {\n            waitKey = !waitKey\n            if waitKey {\n                scr.Timeout(-1)\n            } else {\n                scr.Timeout(0)\n            }\n        }\n        if ch == 'q' {\n            break\n        }\n    }\n    scr.Timeout(-1)\n    gc.CBreak(false)\n    gc.Echo(true)\n}\n"}
{"id": 53000, "name": "Append numbers at same position in strings", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n"}
{"id": 53001, "name": "Append numbers at same position in strings", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n"}
{"id": 53002, "name": "Longest common suffix", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n"}
{"id": 53003, "name": "Chat server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n"}
{"id": 53004, "name": "Arena storage pool", "C": "#include <stdlib.h>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n"}
{"id": 53005, "name": "Arena storage pool", "C": "#include <stdlib.h>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n"}
{"id": 53006, "name": "Idiomatically determine all the lowercase and uppercase letters", "C": "#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n  putchar('\\n');\n  for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n  putchar('\\n');\n  return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n"}
{"id": 53007, "name": "Sum of elements below main diagonal of matrix", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n"}
{"id": 53008, "name": "Retrieve and search chat history", "C": "#include<curl/curl.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAX_LEN 1000\n\nvoid searchChatLogs(char* searchString){\n\tchar* baseURL = \"http:\n\ttime_t t;\n\tstruct tm* currentDate;\n\tchar dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];\n\tint i,flag;\n\tFILE *fp;\n\t\n\tCURL *curl;\n\tCURLcode res;\n\t\n\ttime(&t);\n\tcurrentDate = localtime(&t);\n\t\n\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\n\tprintf(\"Today is : %s\",dateString);\n\t\n\tif((curl = curl_easy_init())!=NULL){\n\t\tfor(i=0;i<=10;i++){\n\t\t\t\n\t\tflag = 0;\n\t\tsprintf(targetURL,\"%s%s.tcl\",baseURL,dateString);\n\t\t\n\t\tstrcpy(dateStringFile,dateString);\n\t\t\n\t\tprintf(\"\\nRetrieving chat logs from %s\\n\",targetURL);\n\t\t\n\t\tif((fp = fopen(\"nul\",\"w\"))==0){\n\t\t\tprintf(\"Cant's read from %s\",targetURL);\n\t\t}\n\t\telse{\n\t\t\tcurl_easy_setopt(curl, CURLOPT_URL, targetURL);\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);\n\t\t\n\t\tres = curl_easy_perform(curl);\n\t\t\n\t\tif(res == CURLE_OK){\n\t\t\twhile(fgets(lineData,MAX_LEN,fp)!=NULL){\n\t\t\t\tif(strstr(lineData,searchString)!=NULL){\n\t\t\t\t\tflag = 1;\n\t\t\t\t\tfputs(lineData,stdout);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(flag==0)\n\t\t\t\tprintf(\"\\nNo matching lines found.\");\n\t\t}\n\t\tfflush(fp);\n\t\tfclose(fp);\n\t\t}\n\t\t\n\t\tcurrentDate->tm_mday--;\n\t\tmktime(currentDate);\n\t\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\t\n\t\t\t\n\t}\n\tcurl_easy_cleanup(curl);\n\t\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <followed by search string, enclosed by \\\" if it contains spaces>\",argV[0]);\n\telse\n\t\tsearchChatLogs(argV[1]);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc get(url string) (res string, err error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n\nfunc grep(needle string, haystack string) (res []string) {\n\tfor _, line := range strings.Split(haystack, \"\\n\") {\n\t\tif strings.Contains(line, needle) {\n\t\t\tres = append(res, line)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc genUrl(i int, loc *time.Location) string {\n\tdate := time.Now().In(loc).AddDate(0, 0, i)\n\treturn date.Format(\"http:\n}\n\nfunc main() {\n\tneedle := os.Args[1]\n\tback := -10\n\tserverLoc, err := time.LoadLocation(\"Europe/Berlin\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor i := back; i <= 0; i++ {\n\t\turl := genUrl(i, serverLoc)\n\t\tcontents, err := get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfound := grep(needle, contents)\n\t\tif len(found) > 0 {\n\t\t\tfmt.Printf(\"%v\\n------\\n\", url)\n\t\t\tfor _, line := range found {\n\t\t\t\tfmt.Printf(\"%v\\n\", line)\n\t\t\t}\n\t\t\tfmt.Printf(\"------\\n\\n\")\n\t\t}\n\t}\n}\n"}
{"id": 53009, "name": "Spoof game", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n#define ESC 27\n#define TEST TRUE  \n\ntypedef int bool;\n\nint get_number(const char *prompt, int min, int max, bool show_mm) {\n    int n;\n    char *line = NULL;\n    size_t len = 0;\n    ssize_t read;\n    fflush(stdin);\n    do {\n        printf(\"%s\", prompt);\n        if (show_mm)\n            printf(\" from %d to %d : \", min, max);\n        else\n            printf(\" : \");\n        read = getline(&line, &len, stdin);\n        if (read < 2) continue;\n        n = atoi(line);\n    }\n    while (n < min || n > max);\n    printf(\"\\n\");\n    return n;\n}\n\nint compare_int(const void *a, const void* b) {\n    int i = *(int *)a;\n    int j = *(int *)b;\n    return i - j;\n}\n\nint main() {\n    int i, j, n, players, coins, first, round = 1, rem_size;\n    int min, max, guess, index, index2, total;\n    int remaining[9], hands[10], guesses[10];\n    bool found, eliminated;\n    char c;\n    players = get_number(\"Number of players\", 2, 9, TRUE);\n    coins = get_number(\"Number of coins per player\", 3, 6, TRUE);\n    for (i = 0; i < 9; ++i) remaining[i] = i + 1;\n    rem_size = players;\n    srand(time(NULL));\n    first = 1 + rand() % players;\n    printf(\"The number of coins in your hand will be randomly determined for\");\n    printf(\"\\neach round and displayed to you. However, when you press ENTER\");\n    printf(\"\\nit will be erased so that the other players, who should look\");\n    printf(\"\\naway until it's their turn, won't see it. When asked to guess\");\n    printf(\"\\nthe total, the computer won't allow a 'bum guess'.\\n\");\n    while(TRUE) {\n        printf(\"\\nROUND %d:\\n\", round);\n        n = first;\n        for (i = 0; i < 10; ++i) {\n            hands[i] = 0; guesses[i] = -1;\n        }\n        do {\n            printf(\"  PLAYER %d:\\n\", n);\n            printf(\"    Please come to the computer and press ENTER\\n\");\n            hands[n] = rand() % (coins + 1);\n            printf(\"      <There are %d coin(s) in your hand>\", hands[n]);\n            while (getchar() != '\\n');\n            if (!TEST) {\n                printf(\"%c[1A\", ESC);  \n                printf(\"%c[2K\", ESC);  \n                printf(\"\\r\\n\");        \n            }\n            else printf(\"\\n\");\n            while (TRUE) {\n                min = hands[n];\n                max = (rem_size - 1) * coins + hands[n];\n                guess = get_number(\"    Guess the total\", min, max, FALSE);\n                found = FALSE;\n                for (i = 1; i < 10; ++i) {\n                    if (guess == guesses[i]) {\n                        found = TRUE;\n                        break;\n                    }\n                }\n                if (!found) {\n                    guesses[n] = guess;\n                    break;\n                }\n                printf(\"    Already guessed by another player, try again\\n\");\n            }\n            index = -1;\n            for (i = 0; i < rem_size; ++i) {\n                if (remaining[i] == n) {\n                    index = i;\n                    break;\n                }\n            }\n            if (index < rem_size - 1)\n                n = remaining[index + 1];\n            else\n                n = remaining[0];\n        }\n        while (n != first);\n        total = 0;\n        for (i = 1; i < 10; ++i) total += hands[i];\n        printf(\"  Total coins held = %d\\n\", total);\n        eliminated = FALSE;\n        for (i = 0; i < rem_size; ++i) {\n            j = remaining[i];\n            if (guesses[j] == total) {\n                printf(\"  PLAYER %d guessed correctly and is eliminated\\n\", j);\n                remaining[i] = 10;\n                rem_size--;\n                qsort(remaining, players, sizeof(int), compare_int);\n                eliminated = TRUE;\n                break;\n            }\n        }\n        if (!eliminated)\n            printf(\"  No players guessed correctly in this round\\n\");\n        else if (rem_size == 1) {\n            printf(\"\\nPLAYER %d buys the drinks!\\n\", remaining[0]);\n            break;\n        }\n        index2 = -1;\n        for (i = 0; i < rem_size; ++i) {\n            if (remaining[i] == first) {\n                index2 = i;\n                break;\n            }\n        }\n        if (index2 < rem_size - 1)\n            first = remaining[index2 + 1];\n        else\n            first = remaining[0];\n        round++;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nconst (\n    esc  = \"\\033\"\n    test = true \n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc indexOf(s []int, el int) int {\n    for i, v := range s {\n        if v == el {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc getNumber(prompt string, min, max int, showMinMax bool) (int, error) {\n    for {\n        fmt.Print(prompt)\n        if showMinMax {\n            fmt.Printf(\" from %d to %d : \", min, max)\n        } else {\n            fmt.Printf(\" : \")\n        }\n        scanner.Scan()\n        if scerr := scanner.Err(); scerr != nil {\n            return 0, scerr\n        }\n        input, err := strconv.Atoi(scanner.Text())\n        if err == nil && input >= min && input <= max {\n            fmt.Println()\n            return input, nil\n        }\n    }\n}\n\nfunc check(err error, text string) {\n    if err != nil {\n        log.Fatalln(err, text)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    players, err := getNumber(\"Number of players\", 2, 9, true)\n    check(err, \"when getting players\")\n    coins, err2 := getNumber(\"Number of coins per player\", 3, 6, true)\n    check(err2, \"when getting coins\")\n    remaining := make([]int, players)\n    for i := range remaining {\n        remaining[i] = i + 1\n    }\n    first := 1 + rand.Intn(players)\n    fmt.Println(\"The number of coins in your hand will be randomly determined for\")\n    fmt.Println(\"each round and displayed to you. However, when you press ENTER\")\n    fmt.Println(\"it will be erased so that the other players, who should look\")\n    fmt.Println(\"away until it's their turn, won't see it. When asked to guess\")\n    fmt.Println(\"the total, the computer won't allow a 'bum guess'.\")\n    for round := 1; ; round++ {\n        fmt.Printf(\"\\nROUND %d:\\n\\n\", round)\n        n := first\n        hands := make([]int, players+1)\n        guesses := make([]int, players+1)\n        for i := range guesses {\n            guesses[i] = -1\n        }\n        for {\n            fmt.Printf(\"  PLAYER %d:\\n\", n)\n            fmt.Println(\"    Please come to the computer and press ENTER\")\n            hands[n] = rand.Intn(coins + 1)\n            fmt.Print(\"      <There are \", hands[n], \" coin(s) in your hand>\")\n            scanner.Scan()\n            check(scanner.Err(), \"when pressing ENTER\")\n            if !test {\n                fmt.Print(esc, \"[1A\") \n                fmt.Print(esc, \"[2K\") \n                fmt.Println(\"\\r\")     \n            } else {\n                fmt.Println()\n            }\n            for {\n                min := hands[n]\n                max := (len(remaining)-1)*coins + hands[n]\n                guess, err3 := getNumber(\"    Guess the total\", min, max, false)\n                check(err3, \"when guessing the total\")\n                if indexOf(guesses, guess) == -1 {\n                    guesses[n] = guess\n                    break\n                }\n                fmt.Println(\"    Already guessed by another player, try again\")\n            }\n            index := indexOf(remaining, n)\n            if index < len(remaining)-1 {\n                n = remaining[index+1]\n            } else {\n                n = remaining[0]\n            }\n            if n == first {\n                break\n            }\n        }\n        total := 0\n        for _, hand := range hands {\n            total += hand\n        }\n        fmt.Println(\"  Total coins held =\", total)\n        eliminated := false\n        for _, v := range remaining {\n            if guesses[v] == total {\n                fmt.Println(\"  PLAYER\", v, \"guessed correctly and is eliminated\")\n                r := indexOf(remaining, v)\n                remaining = append(remaining[:r], remaining[r+1:]...)\n                eliminated = true\n                break\n            }\n        }\n        if !eliminated {\n            fmt.Println(\"  No players guessed correctly in this round\")\n        } else if len(remaining) == 1 {\n            fmt.Println(\"\\nPLAYER\", remaining[0], \"buys the drinks!\")\n            return\n        }\n        index2 := indexOf(remaining, n)\n        if index2 < len(remaining)-1 {\n            first = remaining[index2+1]\n        } else {\n            first = remaining[0]\n        }\n    }\n}\n"}
{"id": 53010, "name": "Spoof game", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n#define ESC 27\n#define TEST TRUE  \n\ntypedef int bool;\n\nint get_number(const char *prompt, int min, int max, bool show_mm) {\n    int n;\n    char *line = NULL;\n    size_t len = 0;\n    ssize_t read;\n    fflush(stdin);\n    do {\n        printf(\"%s\", prompt);\n        if (show_mm)\n            printf(\" from %d to %d : \", min, max);\n        else\n            printf(\" : \");\n        read = getline(&line, &len, stdin);\n        if (read < 2) continue;\n        n = atoi(line);\n    }\n    while (n < min || n > max);\n    printf(\"\\n\");\n    return n;\n}\n\nint compare_int(const void *a, const void* b) {\n    int i = *(int *)a;\n    int j = *(int *)b;\n    return i - j;\n}\n\nint main() {\n    int i, j, n, players, coins, first, round = 1, rem_size;\n    int min, max, guess, index, index2, total;\n    int remaining[9], hands[10], guesses[10];\n    bool found, eliminated;\n    char c;\n    players = get_number(\"Number of players\", 2, 9, TRUE);\n    coins = get_number(\"Number of coins per player\", 3, 6, TRUE);\n    for (i = 0; i < 9; ++i) remaining[i] = i + 1;\n    rem_size = players;\n    srand(time(NULL));\n    first = 1 + rand() % players;\n    printf(\"The number of coins in your hand will be randomly determined for\");\n    printf(\"\\neach round and displayed to you. However, when you press ENTER\");\n    printf(\"\\nit will be erased so that the other players, who should look\");\n    printf(\"\\naway until it's their turn, won't see it. When asked to guess\");\n    printf(\"\\nthe total, the computer won't allow a 'bum guess'.\\n\");\n    while(TRUE) {\n        printf(\"\\nROUND %d:\\n\", round);\n        n = first;\n        for (i = 0; i < 10; ++i) {\n            hands[i] = 0; guesses[i] = -1;\n        }\n        do {\n            printf(\"  PLAYER %d:\\n\", n);\n            printf(\"    Please come to the computer and press ENTER\\n\");\n            hands[n] = rand() % (coins + 1);\n            printf(\"      <There are %d coin(s) in your hand>\", hands[n]);\n            while (getchar() != '\\n');\n            if (!TEST) {\n                printf(\"%c[1A\", ESC);  \n                printf(\"%c[2K\", ESC);  \n                printf(\"\\r\\n\");        \n            }\n            else printf(\"\\n\");\n            while (TRUE) {\n                min = hands[n];\n                max = (rem_size - 1) * coins + hands[n];\n                guess = get_number(\"    Guess the total\", min, max, FALSE);\n                found = FALSE;\n                for (i = 1; i < 10; ++i) {\n                    if (guess == guesses[i]) {\n                        found = TRUE;\n                        break;\n                    }\n                }\n                if (!found) {\n                    guesses[n] = guess;\n                    break;\n                }\n                printf(\"    Already guessed by another player, try again\\n\");\n            }\n            index = -1;\n            for (i = 0; i < rem_size; ++i) {\n                if (remaining[i] == n) {\n                    index = i;\n                    break;\n                }\n            }\n            if (index < rem_size - 1)\n                n = remaining[index + 1];\n            else\n                n = remaining[0];\n        }\n        while (n != first);\n        total = 0;\n        for (i = 1; i < 10; ++i) total += hands[i];\n        printf(\"  Total coins held = %d\\n\", total);\n        eliminated = FALSE;\n        for (i = 0; i < rem_size; ++i) {\n            j = remaining[i];\n            if (guesses[j] == total) {\n                printf(\"  PLAYER %d guessed correctly and is eliminated\\n\", j);\n                remaining[i] = 10;\n                rem_size--;\n                qsort(remaining, players, sizeof(int), compare_int);\n                eliminated = TRUE;\n                break;\n            }\n        }\n        if (!eliminated)\n            printf(\"  No players guessed correctly in this round\\n\");\n        else if (rem_size == 1) {\n            printf(\"\\nPLAYER %d buys the drinks!\\n\", remaining[0]);\n            break;\n        }\n        index2 = -1;\n        for (i = 0; i < rem_size; ++i) {\n            if (remaining[i] == first) {\n                index2 = i;\n                break;\n            }\n        }\n        if (index2 < rem_size - 1)\n            first = remaining[index2 + 1];\n        else\n            first = remaining[0];\n        round++;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nconst (\n    esc  = \"\\033\"\n    test = true \n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc indexOf(s []int, el int) int {\n    for i, v := range s {\n        if v == el {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc getNumber(prompt string, min, max int, showMinMax bool) (int, error) {\n    for {\n        fmt.Print(prompt)\n        if showMinMax {\n            fmt.Printf(\" from %d to %d : \", min, max)\n        } else {\n            fmt.Printf(\" : \")\n        }\n        scanner.Scan()\n        if scerr := scanner.Err(); scerr != nil {\n            return 0, scerr\n        }\n        input, err := strconv.Atoi(scanner.Text())\n        if err == nil && input >= min && input <= max {\n            fmt.Println()\n            return input, nil\n        }\n    }\n}\n\nfunc check(err error, text string) {\n    if err != nil {\n        log.Fatalln(err, text)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    players, err := getNumber(\"Number of players\", 2, 9, true)\n    check(err, \"when getting players\")\n    coins, err2 := getNumber(\"Number of coins per player\", 3, 6, true)\n    check(err2, \"when getting coins\")\n    remaining := make([]int, players)\n    for i := range remaining {\n        remaining[i] = i + 1\n    }\n    first := 1 + rand.Intn(players)\n    fmt.Println(\"The number of coins in your hand will be randomly determined for\")\n    fmt.Println(\"each round and displayed to you. However, when you press ENTER\")\n    fmt.Println(\"it will be erased so that the other players, who should look\")\n    fmt.Println(\"away until it's their turn, won't see it. When asked to guess\")\n    fmt.Println(\"the total, the computer won't allow a 'bum guess'.\")\n    for round := 1; ; round++ {\n        fmt.Printf(\"\\nROUND %d:\\n\\n\", round)\n        n := first\n        hands := make([]int, players+1)\n        guesses := make([]int, players+1)\n        for i := range guesses {\n            guesses[i] = -1\n        }\n        for {\n            fmt.Printf(\"  PLAYER %d:\\n\", n)\n            fmt.Println(\"    Please come to the computer and press ENTER\")\n            hands[n] = rand.Intn(coins + 1)\n            fmt.Print(\"      <There are \", hands[n], \" coin(s) in your hand>\")\n            scanner.Scan()\n            check(scanner.Err(), \"when pressing ENTER\")\n            if !test {\n                fmt.Print(esc, \"[1A\") \n                fmt.Print(esc, \"[2K\") \n                fmt.Println(\"\\r\")     \n            } else {\n                fmt.Println()\n            }\n            for {\n                min := hands[n]\n                max := (len(remaining)-1)*coins + hands[n]\n                guess, err3 := getNumber(\"    Guess the total\", min, max, false)\n                check(err3, \"when guessing the total\")\n                if indexOf(guesses, guess) == -1 {\n                    guesses[n] = guess\n                    break\n                }\n                fmt.Println(\"    Already guessed by another player, try again\")\n            }\n            index := indexOf(remaining, n)\n            if index < len(remaining)-1 {\n                n = remaining[index+1]\n            } else {\n                n = remaining[0]\n            }\n            if n == first {\n                break\n            }\n        }\n        total := 0\n        for _, hand := range hands {\n            total += hand\n        }\n        fmt.Println(\"  Total coins held =\", total)\n        eliminated := false\n        for _, v := range remaining {\n            if guesses[v] == total {\n                fmt.Println(\"  PLAYER\", v, \"guessed correctly and is eliminated\")\n                r := indexOf(remaining, v)\n                remaining = append(remaining[:r], remaining[r+1:]...)\n                eliminated = true\n                break\n            }\n        }\n        if !eliminated {\n            fmt.Println(\"  No players guessed correctly in this round\")\n        } else if len(remaining) == 1 {\n            fmt.Println(\"\\nPLAYER\", remaining[0], \"buys the drinks!\")\n            return\n        }\n        index2 := indexOf(remaining, n)\n        if index2 < len(remaining)-1 {\n            first = remaining[index2+1]\n        } else {\n            first = remaining[0]\n        }\n    }\n}\n"}
{"id": 53011, "name": "Rosetta Code_Rank languages by number of users", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n"}
{"id": 53012, "name": "Rosetta Code_Rank languages by number of users", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n"}
{"id": 53013, "name": "Addition-chain exponentiation", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    N    = 32\n    NMAX = 40000\n)\n\nvar (\n    u     = [N]int{0: 1, 1: 2} \n    l     = [N]int{0: 1, 1: 2} \n    out   = [N]int{}\n    sum   = [N]int{}\n    tail  = [N]int{}\n    cache = [NMAX + 1]int{2: 1}\n    known = 2\n    stack = 0\n    undo  = [N * N]save{}\n)\n\ntype save struct {\n    p *int\n    v int\n}\n\nfunc replace(x *[N]int, i, n int) {\n    undo[stack].p = &x[i]\n    undo[stack].v = x[i]\n    x[i] = n\n    stack++\n}\n\nfunc restore(n int) {\n    for stack > n {\n        stack--\n        *undo[stack].p = undo[stack].v\n    }\n}\n\n\nfunc lower(n int, up *int) int {\n    if n <= 2 || (n <= NMAX && cache[n] != 0) {\n        if up != nil {\n            *up = cache[n]\n        }\n        return cache[n]\n    }\n    i, o := -1, 0\n    for ; n != 0; n, i = n>>1, i+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    if up != nil {\n        i--\n        *up = o + i\n    }\n    for {\n        i++\n        o >>= 1\n        if o == 0 {\n            break\n        }\n    }\n    if up == nil {\n        return i\n    }\n    for o = 2; o*o < n; o++ {\n        if n%o != 0 {\n            continue\n        }\n        q := cache[o] + cache[n/o]\n        if q < *up {\n            *up = q\n            if q == i {\n                break\n            }\n        }\n    }\n    if n > 2 {\n        if *up > cache[n-2]+1 {\n            *up = cache[n-1] + 1\n        }\n        if *up > cache[n-2]+1 {\n            *up = cache[n-2] + 1\n        }\n    }\n    return i\n}\n\nfunc insert(x, pos int) bool {\n    save := stack\n    if l[pos] > x || u[pos] < x {\n        return false\n    }\n    if l[pos] == x {\n        goto replU\n    }\n    replace(&l, pos, x)\n    for i := pos - 1; u[i]*2 < u[i+1]; i-- {\n        t := l[i+1] + 1\n        if t*2 > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\n    for i := pos + 1; l[i] <= l[i-1]; i++ {\n        t := l[i-1] + 1\n        if t > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\nreplU:\n    if u[pos] == x {\n        return true\n    }\n    replace(&u, pos, x)\n    for i := pos - 1; u[i] >= u[i+1]; i-- {\n        t := u[i+1] - 1\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    for i := pos + 1; u[i] > u[i-1]*2; i++ {\n        t := u[i-1] * 2\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    return true\nbail:\n    restore(save)\n    return false\n}\n\nfunc try(p, q, le int) bool {\n    pl := cache[p]\n    if pl >= le {\n        return false\n    }\n    ql := cache[q]\n    if ql >= le {\n        return false\n    }\n    var pu, qu int\n    for pl < le && u[pl] < p {\n        pl++\n    }\n    for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {\n\n    }\n    for ql < le && u[ql] < q {\n        ql++\n    }\n    for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {\n\n    }\n    if p != q && pl <= ql {\n        pl = ql + 1\n    }\n    if pl > pu || ql > qu || ql > pu {\n        return false\n    }\n    if out[le] == 0 {\n        pu = le - 1\n        pl = pu\n    }\n    ps := stack\n    for ; pu >= pl; pu-- {\n        if !insert(p, pu) {\n            continue\n        }\n        out[pu]++\n        sum[pu] += le\n        if p != q {\n            qs := stack\n            j := qu\n            if j >= pu {\n                j = pu - 1\n            }\n            for ; j >= ql; j-- {\n                if !insert(q, j) {\n                    continue\n                }\n                out[j]++\n                sum[j] += le\n                tail[le] = q\n                if seqRecur(le - 1) {\n                    return true\n                }\n                restore(qs)\n                out[j]--\n                sum[j] -= le\n            }\n        } else {\n            out[pu]++\n            sum[pu] += le\n            tail[le] = p\n            if seqRecur(le - 1) {\n                return true\n            }\n            out[pu]--\n            sum[pu] -= le\n        }\n        out[pu]--\n        sum[pu] -= le\n        restore(ps)\n    }\n    return false\n}\n\nfunc seqRecur(le int) bool {\n    n := l[le]\n    if le < 2 {\n        return true\n    }\n    limit := n - 1\n    if out[le] == 1 {\n        limit = n - tail[sum[le]]\n    }\n    if limit > u[le-1] {\n        limit = u[le-1]\n    }\n    \n    \n    p := limit\n    for q := n - p; q <= p; q, p = q+1, p-1 {\n        if try(p, q, le) {\n            return true\n        }\n    }\n    return false\n}\n\nfunc seq(n, le int, buf []int) int {\n    if le == 0 {\n        le = seqLen(n)\n    }\n    stack = 0\n    l[le], u[le] = n, n\n    for i := 0; i <= le; i++ {\n        out[i], sum[i] = 0, 0\n    }\n    for i := 2; i < le; i++ {\n        l[i] = l[i-1] + 1\n        u[i] = u[i-1] * 2\n    }\n    for i := le - 1; i > 2; i-- {\n        if l[i]*2 < l[i+1] {\n            l[i] = (1 + l[i+1]) / 2\n        }\n        if u[i] >= u[i+1] {\n            u[i] = u[i+1] - 1\n        }\n    }\n    if !seqRecur(le) {\n        return 0\n    }\n    if buf != nil {\n        for i := 0; i <= le; i++ {\n            buf[i] = u[i]\n        }\n    }\n    return le\n}\n\nfunc seqLen(n int) int {\n    if n <= known {\n        return cache[n]\n    }\n    \n    for known+1 < n {\n        seqLen(known + 1)\n    }\n    var ub int\n    lb := lower(n, &ub)\n    for lb < ub && seq(n, lb, nil) == 0 {\n        lb++\n    }\n    known = n\n    if n&1023 == 0 {\n        fmt.Printf(\"Cached %d\\n\", known)\n    }\n    cache[n] = lb\n    return lb\n}\n\nfunc binLen(n int) int {\n    r, o := -1, -1\n    for ; n != 0; n, r = n>>1, r+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    return r + o\n}\n\ntype(\n    vector = []float64\n    matrix []vector\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m matrix) pow(n int, printout bool) matrix {\n    e := make([]int, N)\n    var v [N]matrix\n    le := seq(n, 0, e)\n    if printout {\n        fmt.Println(\"Addition chain:\")\n        for i := 0; i <= le; i++ {\n            c := ' '\n            if i == le {\n                c = '\\n'\n            }\n            fmt.Printf(\"%d%c\", e[i], c)\n        }\n    }\n    v[0] = m\n    v[1] = m.mul(m)\n    for i := 2; i <= le; i++ {\n        for j := i - 1; j != 0; j-- {\n            for k := j; k >= 0; k-- {\n                if e[k]+e[j] < e[i] {\n                    break\n                }\n                if e[k]+e[j] > e[i] {\n                    continue\n                }\n                v[i] = v[j].mul(v[k])\n                j = 1\n                break\n            }\n        }\n    }\n    return v[le]\n}\n\nfunc (m matrix) print() {\n    for _, v := range m {\n        fmt.Printf(\"% f\\n\", v)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    m := 27182\n    n := 31415\n    fmt.Println(\"Precompute chain lengths:\")\n    seqLen(n)\n    rh := math.Sqrt(0.5)\n    mx := matrix{\n        {rh, 0, rh, 0, 0, 0},\n        {0, rh, 0, rh, 0, 0},\n        {0, rh, 0, -rh, 0, 0},\n        {-rh, 0, rh, 0, 0, 0},\n        {0, 0, 0, 0, 0, 1},\n        {0, 0, 0, 0, 1, 0},\n    }\n    fmt.Println(\"\\nThe first 100 terms of A003313 are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%d \", seqLen(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n    exs := [2]int{m, n}\n    mxs := [2]matrix{}\n    for i, ex := range exs {\n        fmt.Println(\"\\nExponent:\", ex)\n        mxs[i] = mx.pow(ex, true)\n        fmt.Printf(\"A ^ %d:-\\n\\n\", ex)\n        mxs[i].print()\n        fmt.Println(\"Number of A/C multiplies:\", seqLen(ex))\n        fmt.Println(\"  c.f. Binary multiplies:\", binLen(ex))\n    }\n    fmt.Printf(\"\\nExponent: %d x %d = %d\\n\", m, n, m*n)\n    fmt.Printf(\"A ^ %d = (A ^ %d) ^ %d:-\\n\\n\", m*n, m, n)   \n    mx2 := mxs[0].pow(n, false)\n    mx2.print()\n}\n"}
{"id": 53014, "name": "Addition-chain exponentiation", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    N    = 32\n    NMAX = 40000\n)\n\nvar (\n    u     = [N]int{0: 1, 1: 2} \n    l     = [N]int{0: 1, 1: 2} \n    out   = [N]int{}\n    sum   = [N]int{}\n    tail  = [N]int{}\n    cache = [NMAX + 1]int{2: 1}\n    known = 2\n    stack = 0\n    undo  = [N * N]save{}\n)\n\ntype save struct {\n    p *int\n    v int\n}\n\nfunc replace(x *[N]int, i, n int) {\n    undo[stack].p = &x[i]\n    undo[stack].v = x[i]\n    x[i] = n\n    stack++\n}\n\nfunc restore(n int) {\n    for stack > n {\n        stack--\n        *undo[stack].p = undo[stack].v\n    }\n}\n\n\nfunc lower(n int, up *int) int {\n    if n <= 2 || (n <= NMAX && cache[n] != 0) {\n        if up != nil {\n            *up = cache[n]\n        }\n        return cache[n]\n    }\n    i, o := -1, 0\n    for ; n != 0; n, i = n>>1, i+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    if up != nil {\n        i--\n        *up = o + i\n    }\n    for {\n        i++\n        o >>= 1\n        if o == 0 {\n            break\n        }\n    }\n    if up == nil {\n        return i\n    }\n    for o = 2; o*o < n; o++ {\n        if n%o != 0 {\n            continue\n        }\n        q := cache[o] + cache[n/o]\n        if q < *up {\n            *up = q\n            if q == i {\n                break\n            }\n        }\n    }\n    if n > 2 {\n        if *up > cache[n-2]+1 {\n            *up = cache[n-1] + 1\n        }\n        if *up > cache[n-2]+1 {\n            *up = cache[n-2] + 1\n        }\n    }\n    return i\n}\n\nfunc insert(x, pos int) bool {\n    save := stack\n    if l[pos] > x || u[pos] < x {\n        return false\n    }\n    if l[pos] == x {\n        goto replU\n    }\n    replace(&l, pos, x)\n    for i := pos - 1; u[i]*2 < u[i+1]; i-- {\n        t := l[i+1] + 1\n        if t*2 > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\n    for i := pos + 1; l[i] <= l[i-1]; i++ {\n        t := l[i-1] + 1\n        if t > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\nreplU:\n    if u[pos] == x {\n        return true\n    }\n    replace(&u, pos, x)\n    for i := pos - 1; u[i] >= u[i+1]; i-- {\n        t := u[i+1] - 1\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    for i := pos + 1; u[i] > u[i-1]*2; i++ {\n        t := u[i-1] * 2\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    return true\nbail:\n    restore(save)\n    return false\n}\n\nfunc try(p, q, le int) bool {\n    pl := cache[p]\n    if pl >= le {\n        return false\n    }\n    ql := cache[q]\n    if ql >= le {\n        return false\n    }\n    var pu, qu int\n    for pl < le && u[pl] < p {\n        pl++\n    }\n    for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {\n\n    }\n    for ql < le && u[ql] < q {\n        ql++\n    }\n    for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {\n\n    }\n    if p != q && pl <= ql {\n        pl = ql + 1\n    }\n    if pl > pu || ql > qu || ql > pu {\n        return false\n    }\n    if out[le] == 0 {\n        pu = le - 1\n        pl = pu\n    }\n    ps := stack\n    for ; pu >= pl; pu-- {\n        if !insert(p, pu) {\n            continue\n        }\n        out[pu]++\n        sum[pu] += le\n        if p != q {\n            qs := stack\n            j := qu\n            if j >= pu {\n                j = pu - 1\n            }\n            for ; j >= ql; j-- {\n                if !insert(q, j) {\n                    continue\n                }\n                out[j]++\n                sum[j] += le\n                tail[le] = q\n                if seqRecur(le - 1) {\n                    return true\n                }\n                restore(qs)\n                out[j]--\n                sum[j] -= le\n            }\n        } else {\n            out[pu]++\n            sum[pu] += le\n            tail[le] = p\n            if seqRecur(le - 1) {\n                return true\n            }\n            out[pu]--\n            sum[pu] -= le\n        }\n        out[pu]--\n        sum[pu] -= le\n        restore(ps)\n    }\n    return false\n}\n\nfunc seqRecur(le int) bool {\n    n := l[le]\n    if le < 2 {\n        return true\n    }\n    limit := n - 1\n    if out[le] == 1 {\n        limit = n - tail[sum[le]]\n    }\n    if limit > u[le-1] {\n        limit = u[le-1]\n    }\n    \n    \n    p := limit\n    for q := n - p; q <= p; q, p = q+1, p-1 {\n        if try(p, q, le) {\n            return true\n        }\n    }\n    return false\n}\n\nfunc seq(n, le int, buf []int) int {\n    if le == 0 {\n        le = seqLen(n)\n    }\n    stack = 0\n    l[le], u[le] = n, n\n    for i := 0; i <= le; i++ {\n        out[i], sum[i] = 0, 0\n    }\n    for i := 2; i < le; i++ {\n        l[i] = l[i-1] + 1\n        u[i] = u[i-1] * 2\n    }\n    for i := le - 1; i > 2; i-- {\n        if l[i]*2 < l[i+1] {\n            l[i] = (1 + l[i+1]) / 2\n        }\n        if u[i] >= u[i+1] {\n            u[i] = u[i+1] - 1\n        }\n    }\n    if !seqRecur(le) {\n        return 0\n    }\n    if buf != nil {\n        for i := 0; i <= le; i++ {\n            buf[i] = u[i]\n        }\n    }\n    return le\n}\n\nfunc seqLen(n int) int {\n    if n <= known {\n        return cache[n]\n    }\n    \n    for known+1 < n {\n        seqLen(known + 1)\n    }\n    var ub int\n    lb := lower(n, &ub)\n    for lb < ub && seq(n, lb, nil) == 0 {\n        lb++\n    }\n    known = n\n    if n&1023 == 0 {\n        fmt.Printf(\"Cached %d\\n\", known)\n    }\n    cache[n] = lb\n    return lb\n}\n\nfunc binLen(n int) int {\n    r, o := -1, -1\n    for ; n != 0; n, r = n>>1, r+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    return r + o\n}\n\ntype(\n    vector = []float64\n    matrix []vector\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m matrix) pow(n int, printout bool) matrix {\n    e := make([]int, N)\n    var v [N]matrix\n    le := seq(n, 0, e)\n    if printout {\n        fmt.Println(\"Addition chain:\")\n        for i := 0; i <= le; i++ {\n            c := ' '\n            if i == le {\n                c = '\\n'\n            }\n            fmt.Printf(\"%d%c\", e[i], c)\n        }\n    }\n    v[0] = m\n    v[1] = m.mul(m)\n    for i := 2; i <= le; i++ {\n        for j := i - 1; j != 0; j-- {\n            for k := j; k >= 0; k-- {\n                if e[k]+e[j] < e[i] {\n                    break\n                }\n                if e[k]+e[j] > e[i] {\n                    continue\n                }\n                v[i] = v[j].mul(v[k])\n                j = 1\n                break\n            }\n        }\n    }\n    return v[le]\n}\n\nfunc (m matrix) print() {\n    for _, v := range m {\n        fmt.Printf(\"% f\\n\", v)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    m := 27182\n    n := 31415\n    fmt.Println(\"Precompute chain lengths:\")\n    seqLen(n)\n    rh := math.Sqrt(0.5)\n    mx := matrix{\n        {rh, 0, rh, 0, 0, 0},\n        {0, rh, 0, rh, 0, 0},\n        {0, rh, 0, -rh, 0, 0},\n        {-rh, 0, rh, 0, 0, 0},\n        {0, 0, 0, 0, 0, 1},\n        {0, 0, 0, 0, 1, 0},\n    }\n    fmt.Println(\"\\nThe first 100 terms of A003313 are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%d \", seqLen(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n    exs := [2]int{m, n}\n    mxs := [2]matrix{}\n    for i, ex := range exs {\n        fmt.Println(\"\\nExponent:\", ex)\n        mxs[i] = mx.pow(ex, true)\n        fmt.Printf(\"A ^ %d:-\\n\\n\", ex)\n        mxs[i].print()\n        fmt.Println(\"Number of A/C multiplies:\", seqLen(ex))\n        fmt.Println(\"  c.f. Binary multiplies:\", binLen(ex))\n    }\n    fmt.Printf(\"\\nExponent: %d x %d = %d\\n\", m, n, m*n)\n    fmt.Printf(\"A ^ %d = (A ^ %d) ^ %d:-\\n\\n\", m*n, m, n)   \n    mx2 := mxs[0].pow(n, false)\n    mx2.print()\n}\n"}
{"id": 53015, "name": "Multiline shebang", "C": "\n", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n"}
{"id": 53016, "name": "Multiline shebang", "C": "\n", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n"}
{"id": 53017, "name": "Terminal control_Unicode output", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n"}
{"id": 53018, "name": "Terminal control_Unicode output", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n"}
{"id": 53019, "name": "Sorting algorithms_Tree sort on a linked list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n"}
{"id": 53020, "name": "Sorting algorithms_Tree sort on a linked list", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n"}
{"id": 53021, "name": "Find adjacent primes which differ by a square integer", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n"}
{"id": 53022, "name": "Find adjacent primes which differ by a square integer", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n"}
{"id": 53023, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 53024, "name": "Truncate a file", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 53025, "name": "Video display modes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53026, "name": "Video display modes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53027, "name": "Keyboard input_Flush the keyboard buffer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char* argv[])\n{\n    \n    \n    char text[256];\n    getchar();\n\n    \n    \n    \n    \n\n    \n    \n    fseek(stdin, 0, SEEK_END);\n\n    \n    \n    \n\n    \n    \n    fgets(text, sizeof(text), stdin);\n    puts(text);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    _, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    gc.FlushInput()\n}\n"}
{"id": 53028, "name": "Numerical integration_Adaptive Simpson's method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 53029, "name": "Numerical integration_Adaptive Simpson's method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 53030, "name": "FASTA format", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n"}
{"id": 53031, "name": "Cousin primes", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n"}
{"id": 53032, "name": "Cousin primes", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n"}
{"id": 53033, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 53034, "name": "Find palindromic numbers in both binary and ternary bases", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 53035, "name": "Check input device is a terminal", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n"}
{"id": 53036, "name": "Check input device is a terminal", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n"}
{"id": 53037, "name": "Window creation_X11", "C": "'--- added a flush to exit cleanly   \nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n \n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n \n'---pointer to X Display structure\nDECLARE d TYPE  Display*\n \n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n \n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n \nDECLARE msg TYPE char*\n \n'--- number of screen to place the window on\nDECLARE s TYPE int\n \n \n \n  msg = \"Hello, World!\"\n \n \n   d = DISPLAY(NULL)\n   IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n   END IF\n \n   s = SCREEN(d)\n   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n \n   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n   MAP_EVENT(d, w)\n \n   WHILE  (1) \n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t    BREAK\n\t END IF   \n   WEND\n   FLUSH(d)\n   CLOSE_DISPLAY(d)\n", "Go": "package main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"github.com/jezek/xgb\"\n    \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n    \n    X, err := xgb.NewConn()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    points := []xproto.Point{\n        {10, 10},\n        {10, 20},\n        {20, 10},\n        {20, 20}};\n\n    polyline := []xproto.Point{\n        {50, 10},\n        { 5, 20},     \n        {25,-20},\n        {10, 10}};\n\n    segments := []xproto.Segment{\n        {100, 10, 140, 30},\n        {110, 25, 130, 60}};\n\n    rectangles := []xproto.Rectangle{\n        { 10, 50, 40, 20},\n        { 80, 50, 10, 40}};\n\n    arcs := []xproto.Arc{\n        {10, 100, 60, 40, 0, 90 << 6},\n        {90, 100, 55, 40, 0, 270 << 6}};\n\n    setup := xproto.Setup(X)\n    \n    screen := setup.DefaultScreen(X)\n\n    \n    foreground, _ := xproto.NewGcontextId(X)\n    mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n    values := []uint32{screen.BlackPixel, 0}\n    xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n    \n    win, _ := xproto.NewWindowId(X)\n    winDrawable := xproto.Drawable(win)\n\n    \n    mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n    values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n    xproto.CreateWindow(X,                  \n            screen.RootDepth,               \n            win,                            \n            screen.Root,                    \n            0, 0,                           \n            150, 150,                       \n            10,                             \n            xproto.WindowClassInputOutput,  \n            screen.RootVisual,              \n            mask, values)                   \n\n    \n    xproto.MapWindow(X, win)\n\n    for {\n        evt, err := X.WaitForEvent()\n        switch evt.(type) {\n            case xproto.ExposeEvent:\n                \n                xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n                \n                xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n                \n                xproto.PolySegment(X, winDrawable, foreground, segments)\n\n                \n                xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n                \n                xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n            default:\n                \n        }\n\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    return\n}\n"}
{"id": 53038, "name": "Elementary cellular automaton_Random number generator", "C": "#include <stdio.h>\n#include <limits.h>\n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n"}
{"id": 53039, "name": "Terminal control_Dimensions", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n"}
{"id": 53040, "name": "Finite state machine", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n"}
{"id": 53041, "name": "Vibrating rectangles", "C": "\n\n#include<graphics.h>\n\nvoid vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)\n{\n\tint color = 1,i,x = winWidth/2, y = winHeight/2;\n\t\n\twhile(!kbhit()){\n\t\tsetcolor(color++);\n\t\tfor(i=num;i>0;i--){\n\t\t\trectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);\n\t\t\tdelay(msec);\n\t\t}\n\n\t\tif(color>MAXCOLORS){\n\t\t\tcolor = 1;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Vibrating Rectangles...\");\n\t\n\tvibratingRectangles(1000,1000,30,15,20,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n"}
{"id": 53042, "name": "Last list item", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint compare(const void *a, const void *b) {\n    int aa = *(const int *)a;\n    int bb = *(const int *)b;\n    if (aa < bb) return -1;\n    if (aa > bb) return 1;\n    return 0;\n}\n\nint main() {\n    int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};\n    int isize = sizeof(int);\n    int asize = sizeof(a) / isize;\n    int i, sum;\n    while (asize > 1) {\n        qsort(a, asize, isize, compare);\n        printf(\"Sorted list: \");\n        for (i = 0; i < asize; ++i) printf(\"%d \", a[i]);\n        printf(\"\\n\");\n        sum = a[0] + a[1];\n        printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum);\n        for (i = 2; i < asize; ++i) a[i-2] = a[i];\n        a[asize - 2] = sum;\n        asize--;\n    }\n    printf(\"Last item is %d.\\n\", a[0]);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}\n    for len(a) > 1 {\n        sort.Ints(a)\n        fmt.Println(\"Sorted list:\", a)\n        sum := a[0] + a[1]\n        fmt.Printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum)\n        a = append(a, sum)\n        a = a[2:]\n    }\n    fmt.Println(\"Last item is\", a[0], \"\\b.\")\n}\n"}
{"id": 53043, "name": "Audio frequency generator", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_frequency_generator.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\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    freq := 0\n    for freq < 40 || freq > 10000 {\n        fmt.Print(\"Enter frequency in Hz (40 to 10000) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        freq, _ = strconv.Atoi(input)\n    }\n    freqS := strconv.Itoa(freq)\n\n    vol := 0\n    for vol < 1 || vol > 50 {\n        fmt.Print(\"Enter volume in dB (1 to 50) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        vol, _ = strconv.Atoi(input)\n    }\n    volS := strconv.Itoa(vol)\n\n    dur := 0.0\n    for dur < 2 || dur > 10 {\n        fmt.Print(\"Enter duration in seconds (2 to 10) : \")\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    kind := 0\n    for kind < 1 || kind > 3 {\n        fmt.Print(\"Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        kind, _ = strconv.Atoi(input)\n    }\n    kindS := \"sine\"\n    if kind == 2 {\n        kindS = \"square\"\n    } else if kind == 3 {\n        kindS = \"sawtooth\"\n    }\n\n    args := []string{\"-n\", \"synth\", durS, kindS, freqS, \"vol\", volS, \"dB\"}\n    cmd := exec.Command(\"play\", args...)\n    err := cmd.Run()\n    check(err)\n}\n"}
{"id": 53044, "name": "Audio frequency generator", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_frequency_generator.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\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    freq := 0\n    for freq < 40 || freq > 10000 {\n        fmt.Print(\"Enter frequency in Hz (40 to 10000) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        freq, _ = strconv.Atoi(input)\n    }\n    freqS := strconv.Itoa(freq)\n\n    vol := 0\n    for vol < 1 || vol > 50 {\n        fmt.Print(\"Enter volume in dB (1 to 50) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        vol, _ = strconv.Atoi(input)\n    }\n    volS := strconv.Itoa(vol)\n\n    dur := 0.0\n    for dur < 2 || dur > 10 {\n        fmt.Print(\"Enter duration in seconds (2 to 10) : \")\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    kind := 0\n    for kind < 1 || kind > 3 {\n        fmt.Print(\"Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        kind, _ = strconv.Atoi(input)\n    }\n    kindS := \"sine\"\n    if kind == 2 {\n        kindS = \"square\"\n    } else if kind == 3 {\n        kindS = \"sawtooth\"\n    }\n\n    args := []string{\"-n\", \"synth\", durS, kindS, freqS, \"vol\", volS, \"dB\"}\n    cmd := exec.Command(\"play\", args...)\n    err := cmd.Run()\n    check(err)\n}\n"}
{"id": 53045, "name": "Piprimes", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( int n ) {\n\tint i;\n        if (n<2) return 0;\n\tfor(i=2; i*i<=n; i++) {\n\t\tif (n % i == 0) {return 0;}\n\t}\n\treturn 1;\n}\n\nint main(void)  {\n\tint n = 0, p = 1;\n\twhile (n<22) {\n\t\tprintf( \"%d   \", n );\n\t\tp++;\n\t\tif (isprime(p)) n+=1;\n        }\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(79) \n    ix := 0\n    n := 1\n    count := 0\n    var pi []int\n    for {\n        if primes[ix] <= n {\n            count++\n            if count == 22 {\n                break\n            }\n            ix++\n        }\n        n++\n        pi = append(pi, count)\n    }\n    fmt.Println(\"pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:\")\n    for i, n := range pi {\n        fmt.Printf(\"%2d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nHighest n for this range = %d.\\n\", len(pi))\n}\n"}
{"id": 53046, "name": "Piprimes", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( int n ) {\n\tint i;\n        if (n<2) return 0;\n\tfor(i=2; i*i<=n; i++) {\n\t\tif (n % i == 0) {return 0;}\n\t}\n\treturn 1;\n}\n\nint main(void)  {\n\tint n = 0, p = 1;\n\twhile (n<22) {\n\t\tprintf( \"%d   \", n );\n\t\tp++;\n\t\tif (isprime(p)) n+=1;\n        }\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(79) \n    ix := 0\n    n := 1\n    count := 0\n    var pi []int\n    for {\n        if primes[ix] <= n {\n            count++\n            if count == 22 {\n                break\n            }\n            ix++\n        }\n        n++\n        pi = append(pi, count)\n    }\n    fmt.Println(\"pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:\")\n    for i, n := range pi {\n        fmt.Printf(\"%2d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nHighest n for this range = %d.\\n\", len(pi))\n}\n"}
{"id": 53047, "name": "Minimum numbers of three lists", "C": "#include <stdio.h>\n\nint min(int a, int b) {\n    if (a < b) return a;\n    return b;\n}\n\nint main() {\n    int n;\n    int numbers1[5] = {5, 45, 23, 21, 67};\n    int numbers2[5] = {43, 22, 78, 46, 38};\n    int numbers3[5] = {9, 98, 12, 98, 53};\n    int numbers[5]  = {};\n    for (n = 0; n < 5; ++n) {\n        numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);\n        printf(\"%d \", numbers[n]);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 98, 53}\n    numbers := [5]int{}\n    for n := 0; n < 5; n++ {\n        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])\n    }\n    fmt.Println(numbers)\n}\n"}
{"id": 53048, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 53049, "name": "Cipolla's algorithm", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 53050, "name": "Pseudo-random numbers_PCG32", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 53051, "name": "Deconvolution_1D", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    h := []float64{-8, -9, -3, -1, -6, 7}\n    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n        96, 31, 55, 36, 29, -43, -7}\n    fmt.Println(h)\n    fmt.Println(deconv(g, f))\n    fmt.Println(f)\n    fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n    h := make([]float64, len(g)-len(f)+1)\n    for n := range h {\n        h[n] = g[n]\n        var lower int\n        if n >= len(f) {\n            lower = n - len(f) + 1\n        }\n        for i := lower; i < n; i++ {\n            h[n] -= h[i] * f[n-i]\n        }\n        h[n] /= f[0]\n    }\n    return h\n}\n"}
{"id": 53052, "name": "Bitmap_PPM conversion through a pipe", "C": "\nvoid print_jpg(image img, int qual);\n", "Go": "package main\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    b := raster.NewBitmap(400, 300)\n    \n    b.FillRgb(0xc08040)\n    for i := 0; i < 2000; i++ {\n        b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)\n    }\n    for x := 0; x < 400; x++ {\n        for y := 240; y < 245; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for y := 260; y < 265; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n    for y := 0; y < 300; y++ {\n        for x := 80; x < 85; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for x := 95; x < 100; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n\n    \n    c := exec.Command(\"cjpeg\", \"-outfile\", \"pipeout.jpg\")\n    pipe, err := c.StdinPipe()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = c.Start()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = b.WritePpmTo(pipe)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = pipe.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 53053, "name": "Bitcoin_public point to address", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n"}
{"id": 53054, "name": "Bitcoin_public point to address", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n"}
{"id": 53055, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 53056, "name": "NYSIIS", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 53057, "name": "OpenGL_Utah teapot", "C": "#include<gl/freeglut.h>\n\ndouble rot = 0;\nfloat matCol[] = {1,0,0,0};\n\nvoid display(){\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\tglPushMatrix();\n\tglRotatef(30,1,1,0);\n\tglRotatef(rot,0,1,1);\n\tglMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);\n\tglutWireTeapot(0.5);\n\tglPopMatrix();\n\tglFlush();\n}\n\n\nvoid onIdle(){\n\trot += 0.01;\n\tglutPostRedisplay();\n}\n\nvoid init(){\n\tfloat pos[] = {1,1,1,0};\n\tfloat white[] = {1,1,1,0};\n\tfloat shini[] = {70};\n\t\n\tglClearColor(.5,.5,.5,0);\n\tglShadeModel(GL_SMOOTH);\n\tglLightfv(GL_LIGHT0,GL_AMBIENT,white);\n\tglLightfv(GL_LIGHT0,GL_DIFFUSE,white);\n\tglMaterialfv(GL_FRONT,GL_SHININESS,shini);\n\tglEnable(GL_LIGHTING);\n\tglEnable(GL_LIGHT0);\n\tglEnable(GL_DEPTH_TEST);\n}\n\nint main(int argC, char* argV[])\n{\n\tglutInit(&argC,argV);\n\tglutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);\n\tglutInitWindowSize(900,700);\n\tglutCreateWindow(\"The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.\");\n\tinit();\n\tglutDisplayFunc(display);\n\tglutIdleFunc(onIdle);\n\tglutMainLoop();\n\treturn 0;\n}\n", "Go": "package main\n\n\nimport \"C\"\nimport \"unsafe\"\n\nvar rot = 0.0\nvar matCol = [4]C.float{1, 0, 0, 0}\n\n\nfunc display() {\n    C.glClear(C.GL_COLOR_BUFFER_BIT | C.GL_DEPTH_BUFFER_BIT)\n    C.glPushMatrix()\n    C.glRotatef(30, 1, 1, 0)\n    C.glRotatef(C.float(rot), 0, 1, 1)\n    C.glMaterialfv(C.GL_FRONT, C.GL_DIFFUSE, &matCol[0])\n    C.glutWireTeapot(0.5)\n    C.glPopMatrix()\n    C.glFlush()\n}\n\n\nfunc onIdle() {\n    rot += 0.01\n    C.glutPostRedisplay()\n}\n\nfunc initialize() {\n    white := [4]C.float{1, 1, 1, 0}\n    shini := [1]C.float{70}\n    C.glClearColor(0.5, 0.5, 0.5, 0)\n    C.glShadeModel(C.GL_SMOOTH)\n    C.glLightfv(C.GL_LIGHT0, C.GL_AMBIENT, &white[0])\n    C.glLightfv(C.GL_LIGHT0, C.GL_DIFFUSE, &white[0])\n    C.glMaterialfv(C.GL_FRONT, C.GL_SHININESS, &shini[0])\n    C.glEnable(C.GL_LIGHTING)\n    C.glEnable(C.GL_LIGHT0)\n    C.glEnable(C.GL_DEPTH_TEST)\n}\n\nfunc main() {\n    argc := C.int(0)\n    C.glutInit(&argc, nil)\n    C.glutInitDisplayMode(C.GLUT_SINGLE | C.GLUT_RGB | C.GLUT_DEPTH)\n    C.glutInitWindowSize(900, 700)\n    tl := \"The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.\"\n    tlc := C.CString(tl)\n    C.glutCreateWindow(tlc)\n    initialize()\n    C.glutDisplayFunc(C.displayFunc())\n    C.glutIdleFunc(C.idleFunc())\n    C.glutMainLoop()\n    C.free(unsafe.Pointer(tlc))\n}\n"}
{"id": 53058, "name": "Disarium numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 53059, "name": "Disarium numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 53060, "name": "Sierpinski pentagon", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n"}
{"id": 53061, "name": "Minimum primes", "C": "#include <stdio.h>\n\n#define TRUE 1\n#define FALSE 0\n\nint isPrime(int n) {\n    int d;\n    if (n < 2) return FALSE;\n    if (n%2 == 0) return n == 2;\n    if (n%3 == 0) 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\nint max(int a, int b) {\n    if (a > b) return a;\n    return b;\n}\n\nint main() {\n    int n, m;\n    int numbers1[5] = { 5, 45, 23, 21, 67};\n    int numbers2[5] = {43, 22, 78, 46, 38};\n    int numbers3[5] = { 9, 98, 12, 54, 53};\n    int primes[5]   = {};\n    for (n = 0; n < 5; ++n) {\n        m = max(max(numbers1[n], numbers2[n]), numbers3[n]);\n        if (!(m % 2)) m++;\n        while (!isPrime(m)) m += 2;\n        primes[n] = m;\n        printf(\"%d \", primes[n]);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 54, 53}\n    primes := [5]int{}\n    for n := 0; n < 5; n++ {\n        max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])\n        if max % 2 == 0 {\n            max++\n        }\n        for !rcu.IsPrime(max) {\n            max += 2\n        }\n        primes[n] = max\n    }\n    fmt.Println(primes)\n}\n"}
{"id": 53062, "name": "Bitmap_Histogram", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n"}
{"id": 53063, "name": "Padovan n-step number sequences", "C": "#include <stdio.h>\n\nvoid padovanN(int n, size_t t, int *p) {\n    int i, j;\n    if (n < 2 || t < 3) {\n        for (i = 0; i < t; ++i) p[i] = 1;\n        return;\n    }\n    padovanN(n-1, t, p);\n    for (i = n + 1; i < t; ++i) {\n        p[i] = 0;\n        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];\n    }\n}\n\nint main() {\n    int n, i;\n    const size_t t = 15;\n    int p[t];\n    printf(\"First %ld terms of the Padovan n-step number sequences:\\n\", t);\n    for (n = 2; n <= 8; ++n) {\n        for (i = 0; i < t; ++i) p[i] = 0;\n        padovanN(n, t, p);\n        printf(\"%d: \", n);\n        for (i = 0; i < t; ++i) printf(\"%3d \", p[i]);\n        printf(\"\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc padovanN(n, t int) []int {\n    if n < 2 || t < 3 {\n        ones := make([]int, t)\n        for i := 0; i < t; i++ {\n            ones[i] = 1\n        }\n        return ones\n    }\n    p := padovanN(n-1, t)\n    for i := n + 1; i < t; i++ {\n        p[i] = 0\n        for j := i - 2; j >= i-n-1; j-- {\n            p[i] += p[j]\n        }\n    }\n    return p\n}\n\nfunc main() {\n    t := 15\n    fmt.Println(\"First\", t, \"terms of the Padovan n-step number sequences:\")\n    for n := 2; n <= 8; n++ {\n        fmt.Printf(\"%d: %3d\\n\", n, padovanN(n, t))\n    }\n}\n"}
{"id": 53064, "name": "Mutex", "C": "HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n"}
{"id": 53065, "name": "Metronome", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/time.h>\n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); \n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec)   \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 \n\tvar bpb = 4    \n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}\n"}
{"id": 53066, "name": "Native shebang", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n"}
{"id": 53067, "name": "Native shebang", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n"}
{"id": 53068, "name": "EKG sequence convergence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n    int aa = *(int *)a;\n    int bb = *(int *)b;\n    return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n    int i;\n    for (i = 0; i < len; ++i) {\n        if (a[i] == b) return TRUE;\n    }\n    return FALSE;\n}\n\nint gcd(int a, int b) {\n    while (a != b) {\n        if (a > b)\n            a -= b;\n        else\n            b -= a;\n    }\n    return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n    int i;\n    qsort(s, len, sizeof(int), compareInts);    \n    qsort(t, len, sizeof(int), compareInts);\n    for (i = 0; i < len; ++i) {\n        if (s[i] != t[i]) return FALSE;\n    }\n    return TRUE;\n}\n\nint main() {\n    int s, n, i;\n    int starts[5] = {2, 5, 7, 9, 10};\n    int ekg[5][LIMIT];\n    for (s = 0; s < 5; ++s) {\n        ekg[s][0] = 1;\n        ekg[s][1] = starts[s];\n        for (n = 2; n < LIMIT; ++n) {\n            for (i = 2; ; ++i) {\n                \n                \n                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n                    ekg[s][n] = i;\n                    break;\n                }\n            }\n        }\n        printf(\"EKG(%2d): [\", starts[s]);\n        for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n        printf(\"\\b]\\n\");\n    }\n    \n    \n    for (i = 2; i < LIMIT; ++i) {\n        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n            printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n            return 0;\n        }\n    }\n    printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n    for _, j := range a {\n        if j == b {\n            return true\n        }\n    }\n    return false\n}\n\nfunc gcd(a, b int) int {\n    for a != b {\n        if a > b {\n            a -= b\n        } else {\n            b -= a\n        }\n    }\n    return a\n}\n\nfunc areSame(s, t []int) bool {\n    le := len(s)\n    if le != len(t) {\n        return false\n    }\n    sort.Ints(s)\n    sort.Ints(t)\n    for i := 0; i < le; i++ {\n        if s[i] != t[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100\n    starts := [5]int{2, 5, 7, 9, 10}\n    var ekg [5][limit]int\n\n    for s, start := range starts {\n        ekg[s][0] = 1\n        ekg[s][1] = start\n        for n := 2; n < limit; n++ {\n            for i := 2; ; i++ {\n                \n                \n                if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n                    ekg[s][n] = i\n                    break\n                }\n            }\n        }\n        fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n    }   \n\n    \n    for i := 2; i < limit; i++ {\n        if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n            fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n            return\n        }\n    }\n    fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}\n"}
{"id": 53069, "name": "Rep-string", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n"}
{"id": 53070, "name": "Terminal control_Preserve screen", "C": "#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n\tint i;\n\tprintf(\"\\033[?1049h\\033[H\");\n\tprintf(\"Alternate screen buffer\\n\");\n\tfor (i = 5; i; i--) {\n\t\tprintf(\"\\rgoing back in %d...\", i);\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tprintf(\"\\033[?1049l\");\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"\\033[?1049h\\033[H\")\n    fmt.Println(\"Alternate screen buffer\\n\")\n    s := \"s\"\n    for i := 5; i > 0; i-- {\n        if i == 1 {\n            s = \"\"\n        }\n        fmt.Printf(\"\\rgoing back in %d second%s...\", i, s)\n        time.Sleep(time.Second)\n    }\n    fmt.Print(\"\\033[?1049l\")\n}\n"}
{"id": 53071, "name": "Literals_String", "C": "char ch = 'z';\n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 53072, "name": "Changeable words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n"}
{"id": 53073, "name": "Window management", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 53074, "name": "Monads_List monad", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n    return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n    char buf[100];\n    char*str= malloc(1+sprintf(buf, \"%d\", *x));\n    sprintf(str, \"%d\", *x);\n    return (MONAD)(str);\n}\n\nvoid task(int y) {\n    char *z= INTBIND(boundInt2str, boundInt, &y);\n    printf(\"%s\\n\", z);\n    free(z);\n}\n\nint main() {\n    task(13);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n    return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n    return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = v + 1\n    }\n    return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = 2 * v\n    }\n    return unit(lst2)\n}\n\nfunc main() {\n    ml1 := unit([]int{3, 4, 5})\n    ml2 := ml1.bind(increment).bind(double)\n    fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}\n"}
{"id": 53075, "name": "Find squares n where n+1 is prime", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n"}
{"id": 53076, "name": "Find squares n where n+1 is prime", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n"}
{"id": 53077, "name": "Next special primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 53078, "name": "Next special primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 53079, "name": "Mayan numerals", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst (\n    ul = \"╔\"\n    uc = \"╦\"\n    ur = \"╗\"\n    ll = \"╚\"\n    lc = \"╩\"\n    lr = \"╝\"\n    hb = \"═\"\n    vb = \"║\"\n)\n\nvar mayan = [5]string{\n    \"    \",\n    \" ∙  \",\n    \" ∙∙ \",\n    \"∙∙∙ \",\n    \"∙∙∙∙\",\n}\n\nconst (\n    m0 = \" Θ  \"\n    m5 = \"────\"\n)\n\nfunc dec2vig(n uint64) []uint64 {\n    vig := strconv.FormatUint(n, 20)\n    res := make([]uint64, len(vig))\n    for i, d := range vig {\n        res[i], _ = strconv.ParseUint(string(d), 20, 64)\n    }\n    return res\n}\n\nfunc vig2quin(n uint64) [4]string {\n    if n >= 20 {\n        panic(\"Cant't convert a number >= 20\")\n    }\n    res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}\n    if n == 0 {\n        res[3] = m0\n        return res\n    }\n    fives := n / 5\n    rem := n % 5\n    res[3-fives] = mayan[rem]\n    for i := 3; i > 3-int(fives); i-- {\n        res[i] = m5\n    }\n    return res\n}\n\nfunc draw(mayans [][4]string) {\n    lm := len(mayans)\n    fmt.Print(ul)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(uc)\n        } else {\n            fmt.Println(ur)\n        }\n    }\n    for i := 1; i < 5; i++ {\n        fmt.Print(vb)\n        for j := 0; j < lm; j++ {\n            fmt.Print(mayans[j][i-1])\n            fmt.Print(vb)\n        }\n        fmt.Println()\n    }\n    fmt.Print(ll)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(lc)\n        } else {\n            fmt.Println(lr)\n        }\n    }\n}\n\nfunc main() {\n    numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}\n    for _, n := range numbers {\n        fmt.Printf(\"Converting %d to Mayan:\\n\", n)\n        vigs := dec2vig(n)\n        lv := len(vigs)\n        mayans := make([][4]string, lv)\n        for i, vig := range vigs {\n            mayans[i] = vig2quin(vig)\n        }\n        draw(mayans)\n        fmt.Println()\n    }\n}\n"}
{"id": 53080, "name": "Special factorials", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc sf(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    sfact := big.NewInt(1)\n    fact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        sfact.Mul(sfact, fact)\n    }\n    return sfact\n}\n\nfunc H(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    hfact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        bi := big.NewInt(int64(i))\n        hfact.Mul(hfact, bi.Exp(bi, bi, nil))\n    }\n    return hfact\n}\n\nfunc af(n int) *big.Int {\n    if n < 1 {\n        return new(big.Int)\n    }\n    afact := new(big.Int)\n    fact := big.NewInt(1)\n    sign := new(big.Int)\n    if n%2 == 0 {\n        sign.SetInt64(-1)\n    } else {\n        sign.SetInt64(1)\n    }\n    t := new(big.Int)\n    for i := 1; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        afact.Add(afact, t.Mul(fact, sign))\n        sign.Neg(sign)\n    }\n    return afact\n}\n\nfunc ef(n int) *big.Int {\n    if n < 1 {\n        return big.NewInt(1)\n    }\n    t := big.NewInt(int64(n))\n    return t.Exp(t, ef(n-1), nil)\n}\n\nfunc rf(n *big.Int) int {\n    i := 0\n    fact := big.NewInt(1)\n    for {\n        if fact.Cmp(n) == 0 {\n            return i\n        }\n        if fact.Cmp(n) > 0 {\n            return -1\n        }\n        i++\n        fact.Mul(fact, big.NewInt(int64(i)))\n    }\n}\n\nfunc main() {\n    fmt.Println(\"First 10 superfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sf(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 hyperfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(H(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 alternating factorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Print(af(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 exponential factorials:\")\n    for i := 0; i <= 4; i++ {\n        fmt.Print(ef(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nThe number of digits in 5$ is\", len(ef(5).String()))\n\n    fmt.Println(\"\\nReverse factorials:\")\n    facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}\n    for _, fact := range facts {\n        bfact := big.NewInt(fact)\n        rfact := rf(bfact)\n        srfact := fmt.Sprintf(\"%d\", rfact)\n        if rfact == -1 {\n            srfact = \"none\"\n        }\n        fmt.Printf(\"%4s <- rf(%d)\\n\", srfact, fact)\n    }\n}\n"}
{"id": 53081, "name": "Special neighbor primes", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n"}
{"id": 53082, "name": "Special neighbor primes", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n"}
{"id": 53083, "name": "Ramsey's theorem", "C": "#include <stdio.h>\n\nint a[17][17], idx[4];\n\nint find_group(int type, int min_n, int max_n, int depth)\n{\n\tint i, n;\n\tif (depth == 4) {\n\t\tprintf(\"totally %sconnected group:\", type ? \"\" : \"un\");\n\t\tfor (i = 0; i < 4; i++) printf(\" %d\", idx[i]);\n\t\tputchar('\\n');\n\t\treturn 1;\n\t}\n\n\tfor (i = min_n; i < max_n; i++) {\n\t\tfor (n = 0; n < depth; n++)\n\t\t\tif (a[idx[n]][i] != type) break;\n\n\t\tif (n == depth) {\n\t\t\tidx[n] = i;\n\t\t\tif (find_group(type, 1, max_n, depth + 1))\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tconst char *mark = \"01-\";\n\n\tfor (i = 0; i < 17; i++)\n\t\ta[i][i] = 2;\n\n\tfor (k = 1; k <= 8; k <<= 1) {\n\t\tfor (i = 0; i < 17; i++) {\n\t\t\tj = (i + k) % 17;\n\t\t\ta[i][j] = a[j][i] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < 17; i++) {\n\t\tfor (j = 0; j < 17; j++)\n\t\t\tprintf(\"%c \", mark[a[i][j]]);\n\t\tputchar('\\n');\n\t}\n\n\t\n\t\n\n\t\n\tfor (i = 0; i < 17; i++) {\n\t\tidx[0] = i;\n\t\tif (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {\n\t\t\tputs(\"no good\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"all good\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n"}
{"id": 53084, "name": "GUI_Maximum window dimensions", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n"}
{"id": 53085, "name": "Terminal control_Inverse video", "C": "#include <stdio.h>\n\nint main()\n{\n\tprintf(\"\\033[7mReversed\\033[m Normal\\n\");\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    tput(\"rev\")\n    fmt.Print(\"Rosetta\")\n    tput(\"sgr0\")\n    fmt.Println(\" Code\")\n}\n\nfunc tput(arg string) error {\n    cmd := exec.Command(\"tput\", arg)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n"}
{"id": 53086, "name": "Four is magic", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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": 53087, "name": "Using a speech engine to highlight words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nvoid C_espeak(WrenVM* vm) {\n    const char *arg = wrenGetSlotString(vm, 1);\n    char command[strlen(arg) + 10];\n    strcpy(command, \"espeak \\\"\");\n    strcat(command, arg);\n    strcat(command, \"\\\"\");\n    system(command);\n}\n\nvoid C_flushStdout(WrenVM* vm) {\n    fflush(stdout);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0)     return C_usleep;\n            if (isStatic && strcmp(signature, \"espeak(_)\") == 0)     return C_espeak;\n            if (isStatic && strcmp(signature, \"flushStdout()\") == 0) return C_flushStdout;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"speech_engine_highlight_words.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    s := \"Actions speak louder than words.\"\n    prev := \"\"\n    prevLen := 0\n    bs := \"\"\n    for _, word := range strings.Fields(s) {\n        cmd := exec.Command(\"espeak\", word)\n        if err := cmd.Run(); err != nil {\n            log.Fatal(err)\n        }\n        if prevLen > 0 {\n            bs = strings.Repeat(\"\\b\", prevLen)\n        }\n        fmt.Printf(\"%s%s%s \", bs, prev, strings.ToUpper(word))\n        prev = word + \" \"\n        prevLen = len(word) + 1\n    }\n    bs = strings.Repeat(\"\\b\", prevLen)\n    time.Sleep(time.Second)\n    fmt.Printf(\"%s%s\\n\", bs, prev)\n}\n"}
{"id": 53088, "name": "Using a speech engine to highlight words", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nvoid C_espeak(WrenVM* vm) {\n    const char *arg = wrenGetSlotString(vm, 1);\n    char command[strlen(arg) + 10];\n    strcpy(command, \"espeak \\\"\");\n    strcat(command, arg);\n    strcat(command, \"\\\"\");\n    system(command);\n}\n\nvoid C_flushStdout(WrenVM* vm) {\n    fflush(stdout);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0)     return C_usleep;\n            if (isStatic && strcmp(signature, \"espeak(_)\") == 0)     return C_espeak;\n            if (isStatic && strcmp(signature, \"flushStdout()\") == 0) return C_flushStdout;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"speech_engine_highlight_words.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    s := \"Actions speak louder than words.\"\n    prev := \"\"\n    prevLen := 0\n    bs := \"\"\n    for _, word := range strings.Fields(s) {\n        cmd := exec.Command(\"espeak\", word)\n        if err := cmd.Run(); err != nil {\n            log.Fatal(err)\n        }\n        if prevLen > 0 {\n            bs = strings.Repeat(\"\\b\", prevLen)\n        }\n        fmt.Printf(\"%s%s%s \", bs, prev, strings.ToUpper(word))\n        prev = word + \" \"\n        prevLen = len(word) + 1\n    }\n    bs = strings.Repeat(\"\\b\", prevLen)\n    time.Sleep(time.Second)\n    fmt.Printf(\"%s%s\\n\", bs, prev)\n}\n"}
{"id": 53089, "name": "Getting the number of decimals", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n"}
{"id": 53090, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 53091, "name": "Paraffins", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 53092, "name": "Paraffins", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 53093, "name": "Minimum number of cells after, before, above and below NxN squares", "C": "#include<stdio.h>\n#include<stdlib.h>\n\n#define min(a, b) (a<=b?a:b)\n\nvoid minab( unsigned int n ) {\n    int i, j;\n    for(i=0;i<n;i++) {\n        for(j=0;j<n;j++) {\n            printf( \"%2d  \", min( min(i, n-1-i), min(j, n-1-j) ));\n        }\n        printf( \"\\n\" );\n    }\n    return;\n}\n\nint main(void) {\n    minab(10);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc printMinCells(n int) {\n    fmt.Printf(\"Minimum number of cells after, before, above and below %d x %d square:\\n\", n, n)\n    p := 1\n    if n > 20 {\n        p = 2\n    }\n    for r := 0; r < n; r++ {\n        cells := make([]int, n)\n        for c := 0; c < n; c++ {\n            nums := []int{n - r - 1, r, c, n - c - 1}\n            min := n\n            for _, num := range nums {\n                if num < min {\n                    min = num\n                }\n            }\n            cells[c] = min\n        }\n        fmt.Printf(\"%*d \\n\", p, cells)\n    }\n}\n\nfunc main() {\n    for _, n := range []int{23, 10, 9, 2, 1} {\n        printMinCells(n)\n        fmt.Println()\n    }\n}\n"}
{"id": 53094, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 53095, "name": "Pentagram", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 53096, "name": "Parse an IP Address", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n"}
{"id": 53097, "name": "OpenGL pixel shader", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <GL/glew.h>\n#include <GL/glut.h>\n\nGLuint ps, vs, prog, r_mod;\nfloat angle = 0;\nvoid render(void)\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglUniform1f(r_mod, rand() / (float)RAND_MAX);\n\n\tglLoadIdentity();\n\tglRotatef(angle, angle * .1, 1, 0);\n\tglBegin(GL_TRIANGLES);\n\t\tglVertex3f(-1, -.5, 0);\n\t\tglVertex3f(0, 1, 0);\n\t\tglVertex3f(1, 0, 0);\n\tglEnd();\n\tangle += .02;\n\tglutSwapBuffers();\n}\n\nvoid set_shader()\n{\n\tconst char *f =\n\t\t\"varying float x, y, z;\"\n\t\t\"uniform float r_mod;\"\n\t\t\"float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }\"\n\t\t\"void main() {\"\n\t\t\"\tgl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);\"\n\t\t\"}\";\n\tconst char *v =\n\t\t\"varying float x, y, z;\"\n\t\t\"void main() {\"\n\t\t\"\tgl_Position = ftransform();\"\n\t\t\"\tx = gl_Position.x; y = gl_Position.y; z = gl_Position.z;\"\n\t\t\"\tx += y; y -= x; z += x - y;\"\n\t\t\"}\";\n\n\tvs = glCreateShader(GL_VERTEX_SHADER);\n\tps = glCreateShader(GL_FRAGMENT_SHADER);\n\tglShaderSource(ps, 1, &f, 0);\n\tglShaderSource(vs, 1, &v, 0);\n\n\tglCompileShader(vs);\n\tglCompileShader(ps);\n\n\tprog = glCreateProgram();\n\tglAttachShader(prog, ps);\n\tglAttachShader(prog, vs);\n\n\tglLinkProgram(prog);\n\tglUseProgram(prog);\n\tr_mod = glGetUniformLocation(prog, \"r_mod\");\n}\n\nint main(int argc, char **argv)\n{\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\tglutInitWindowSize(200, 200);\n\tglutCreateWindow(\"Stuff\");\n\tglutIdleFunc(render);\n\n\tglewInit();\n\tif (!glewIsSupported(\"GL_VERSION_2_0\")) {\n\t\tfprintf(stderr, \"GL 2.0 unsupported\\n\");\n\t\treturn 1;\n\t}\n\n\tset_shader();\n\tglutMainLoop();\n\n\treturn 0;\n}\n", "Go": "package main\n\n\nimport \"C\"\nimport \"log\"\nimport \"unsafe\"\n\nvar ps, vs, prog, r_mod C.GLuint\nvar angle = float32(0)\n\n\nfunc render() {\n    C.glClear(C.GL_COLOR_BUFFER_BIT)\n    C.glUniform1f_macro(C.GLint(r_mod), C.GLfloat(C.rand())/C.GLfloat(C.RAND_MAX))\n    C.glLoadIdentity()\n    C.glRotatef(C.float(angle), C.float(angle*0.1), 1, 0)\n    C.glBegin(C.GL_TRIANGLES)\n    C.glVertex3f(-1, -0.5, 0)\n    C.glVertex3f(0, 1, 0)\n    C.glVertex3f(1, 0, 0)\n    C.glEnd()\n    angle += 0.02\n    C.glutSwapBuffers()\n}\n\nfunc setShader() {\n    f := \"varying float x, y, z;\" +\n        \"uniform float r_mod;\" +\n        \"float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }\" +\n        \"void main() {\" +\n        \"    gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);\" +\n        \"}\"\n\n    v := \"varying float x, y, z;\" +\n        \"void main() {\" +\n        \"    gl_Position = ftransform();\" +\n        \"    x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;\" +\n        \"    x += y; y -= x; z += x - y;\" +\n        \"}\"\n\n    fc, vc := C.CString(f), C.CString(v)\n    defer C.free(unsafe.Pointer(fc))\n    defer C.free(unsafe.Pointer(vc))\n\n    vs = C.glCreateShader_macro(C.GL_VERTEX_SHADER)\n    ps = C.glCreateShader_macro(C.GL_FRAGMENT_SHADER)\n    C.glShaderSource_macro(ps, 1, &fc, nil)\n    C.glShaderSource_macro(vs, 1, &vc, nil)\n\n    C.glCompileShader_macro(vs)\n    C.glCompileShader_macro(ps)\n\n    prog = C.glCreateProgram_macro()\n    C.glAttachShader_macro(prog, ps)\n    C.glAttachShader_macro(prog, vs)\n\n    C.glLinkProgram_macro(prog)\n    C.glUseProgram_macro(prog)\n    rms := C.CString(\"r_mod\")\n    r_mod = C.GLuint(C.glGetUniformLocation_macro(prog, rms))\n    C.free(unsafe.Pointer(rms))\n}\n\nfunc main() {\n    argc := C.int(0)\n    C.glutInit(&argc, nil)\n    C.glutInitDisplayMode(C.GLUT_DOUBLE | C.GLUT_RGB)\n    C.glutInitWindowSize(200, 200)\n    tl := \"Pixel Shader\"\n    tlc := C.CString(tl)\n    C.glutCreateWindow(tlc)\n    defer C.free(unsafe.Pointer(tlc))\n    C.glutIdleFunc(C.idleFunc())\n\n    C.glewInit()\n    glv := C.CString(\"GL_VERSION_2_0\")\n    if C.glewIsSupported(glv) == 0 {\n        log.Fatal(\"GL 2.0 unsupported\")\n    }\n    defer C.free(unsafe.Pointer(glv))\n\n    setShader()\n    C.glutMainLoop()\n}\n"}
{"id": 53098, "name": "Matrix digital rain", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n"}
{"id": 53099, "name": "Matrix digital rain", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n"}
{"id": 53100, "name": "Audio overlap loop", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_overlap_loop.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\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    fileName := \"loop.wav\"\n    scanner := bufio.NewScanner(os.Stdin)\n    reps := 0\n    for reps < 1 || reps > 6 {\n        fmt.Print(\"Enter number of repetitions (1 to 6) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        reps, _ = strconv.Atoi(input)\n    }\n\n    delay := 0\n    for delay < 50 || delay > 500 {\n        fmt.Print(\"Enter delay between repetitions in microseconds (50 to 500) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        delay, _ = strconv.Atoi(input)\n    }\n\n    decay := 0.0\n    for decay < 0.2 || decay > 0.9 {\n        fmt.Print(\"Enter decay between repetitions (0.2 to 0.9) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        decay, _ = strconv.ParseFloat(input, 64)\n    }\n\n    args := []string{fileName, \"echo\", \"0.8\", \"0.7\"}\n    decay2 := 1.0    \n    for i := 1; i <= reps; i++ {\n        delayStr := strconv.Itoa(i * delay)\n        decay2 *= decay\n        decayStr := strconv.FormatFloat(decay2, 'f', -1, 64)        \n        args = append(args, delayStr, decayStr)        \n    }\n    cmd := exec.Command(\"play\", args...)    \n    err := cmd.Run()\n    check(err)\n}\n"}
{"id": 53101, "name": "Audio overlap loop", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_overlap_loop.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\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    fileName := \"loop.wav\"\n    scanner := bufio.NewScanner(os.Stdin)\n    reps := 0\n    for reps < 1 || reps > 6 {\n        fmt.Print(\"Enter number of repetitions (1 to 6) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        reps, _ = strconv.Atoi(input)\n    }\n\n    delay := 0\n    for delay < 50 || delay > 500 {\n        fmt.Print(\"Enter delay between repetitions in microseconds (50 to 500) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        delay, _ = strconv.Atoi(input)\n    }\n\n    decay := 0.0\n    for decay < 0.2 || decay > 0.9 {\n        fmt.Print(\"Enter decay between repetitions (0.2 to 0.9) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        decay, _ = strconv.ParseFloat(input, 64)\n    }\n\n    args := []string{fileName, \"echo\", \"0.8\", \"0.7\"}\n    decay2 := 1.0    \n    for i := 1; i <= reps; i++ {\n        delayStr := strconv.Itoa(i * delay)\n        decay2 *= decay\n        decayStr := strconv.FormatFloat(decay2, 'f', -1, 64)        \n        args = append(args, delayStr, decayStr)        \n    }\n    cmd := exec.Command(\"play\", args...)    \n    err := cmd.Run()\n    check(err)\n}\n"}
{"id": 53102, "name": "Knapsack problem_Unbounded", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n"}
{"id": 53103, "name": "Mind boggling card trick", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n"}
{"id": 53104, "name": "Mind boggling card trick", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n"}
{"id": 53105, "name": "Mind boggling card trick", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n"}
{"id": 53106, "name": "Textonyms", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n"}
{"id": 53107, "name": "Bitmap_Bézier curves_Quadratic", "C": "void quad_bezier(\n        image img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Go": "package raster\n\nconst b2Seg = 20\n\nfunc (b *Bitmap) Bézier2(x1, y1, x2, y2, x3, y3 int, p Pixel) {\n    var px, py [b2Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    for i := range px {\n        c := float64(i) / b2Seg\n        a := 1 - c\n        a, b, c := a*a, 2 * c * a, c*c\n        px[i] = int(a*fx1 + b*fx2 + c*fx3)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b2Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) {\n    b.Bézier2(x1, y1, x2, y2, x3, y3, c.Pixel())\n}\n"}
{"id": 53108, "name": "Waveform analysis_Top and tail", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_sox(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 4];\n    strcpy(command, \"sox \");\n    strcat(command, args);\n    system(command);\n}\n\nvoid C_removeFile(WrenVM* vm) {\n    const char *name = wrenGetSlotString(vm, 1);\n    if (remove(name) != 0) perror(\"Error deleting file.\");\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0)   return C_getInput;\n            if (isStatic && strcmp(signature, \"sox(_)\") == 0)        return C_sox;\n            if (isStatic && strcmp(signature, \"removeFile(_)\") == 0) return C_removeFile;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"waveform_analysis_top_and_tail.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\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    const sec = \"00:00:01\"\n    scanner := bufio.NewScanner(os.Stdin)\n    name := \"\"\n    for name == \"\" {\n        fmt.Print(\"Enter name of audio file to be trimmed : \")\n        scanner.Scan()\n        name = scanner.Text()\n        check(scanner.Err())\n    }\n\n    name2 := \"\"\n    for name2 == \"\" {\n        fmt.Print(\"Enter name of output file              : \")\n        scanner.Scan()\n        name2 = scanner.Text()\n        check(scanner.Err())\n    }    \n    \n    squelch := 0.0\n    for squelch < 1 || squelch > 10 {\n        fmt.Print(\"Enter squelch level % max (1 to 10)    : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        squelch, _ = strconv.ParseFloat(input, 64)\n    }\n    squelchS := strconv.FormatFloat(squelch, 'f', -1, 64) + \"%\"\n\n    tmp1 := \"tmp1_\" + name\n    tmp2 := \"tmp2_\" + name\n\n    \n    args := []string{name, tmp1, \"silence\", \"1\", sec, squelchS}\n    cmd := exec.Command(\"sox\", args...)\n    err := cmd.Run()\n    check(err) \n\n    \n    args = []string{tmp1, tmp2, \"reverse\"}     \n    cmd = exec.Command(\"sox\", args...)\n    err = cmd.Run()\n    check(err)\n\n    \n    args = []string{tmp2, tmp1, \"silence\", \"1\", sec, squelchS}\n    cmd  = exec.Command(\"sox\", args...)\n    err = cmd.Run()\n    check(err)\n\n    \n    args = []string{tmp1, name2, \"reverse\"}    \n    cmd = exec.Command(\"sox\", args...)\n    err = cmd.Run()\n    check(err)\n\n    \n    err = os.Remove(tmp1)\n    check(err)\n    err = os.Remove(tmp2)\n    check(err)\n}\n"}
{"id": 53109, "name": "A_ search algorithm", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 53110, "name": "A_ search algorithm", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 53111, "name": "A_ search algorithm", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 53112, "name": "Teacup rim text", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 53113, "name": "Increasing gaps between consecutive Niven numbers", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n"}
{"id": 53114, "name": "Print debugging statement", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n"}
{"id": 53115, "name": "Find prime n such that reversed n is also prime", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n"}
{"id": 53116, "name": "Find prime n such that reversed n is also prime", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n"}
{"id": 53117, "name": "Superellipse", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n"}
{"id": 53118, "name": "Permutations_Rank of a permutation", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n"}
{"id": 53119, "name": "Permutations_Rank of a permutation", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n"}
{"id": 53120, "name": "Banker's algorithm", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint main() {\n    int curr[5][5];\n    int max_claim[5][5];\n    int avl[5];\n    int alloc[5] = {0, 0, 0, 0, 0};\n    int max_res[5];\n    int running[5];\n\n    int i, j, exec, r, p;\n    int count = 0;\n    bool safe = false;\n\n    printf(\"\\nEnter the number of resources: \");\n    scanf(\"%d\", &r);\n\n    printf(\"\\nEnter the number of processes: \");\n    scanf(\"%d\", &p);\n    for (i = 0; i < p; i++) {\n        running[i] = 1;\n        count++;\n    }\n\n    printf(\"\\nEnter Claim Vector: \");\n    for (i = 0; i < r; i++)\n        scanf(\"%d\", &max_res[i]);\n\n    printf(\"\\nEnter Allocated Resource Table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &curr[i][j]);\n    }\n\n    printf(\"\\nEnter Maximum Claim table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &max_claim[i][j]);\n    }\n\n    printf(\"\\nThe Claim Vector is: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", max_res[i]);\n\n    printf(\"\\nThe Allocated Resource Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", curr[i][j]);\n        printf(\"\\n\");\n    }\n\n    printf(\"\\nThe Maximum Claim Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", max_claim[i][j]);\n        printf(\"\\n\");\n    }\n\n    for (i = 0; i < p; i++)\n        for (j = 0; j < r; j++)\n            alloc[j] += curr[i][j];\n\n    printf(\"\\nAllocated resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", alloc[i]);\n    for (i = 0; i < r; i++)\n        avl[i] = max_res[i] - alloc[i];\n\n    printf(\"\\nAvailable resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", avl[i]);\n    printf(\"\\n\");\n\n    while (count != 0) {\n        safe = false;\n        for (i = 0; i < p; i++) {\n            if (running[i]) {\n                exec = 1;\n                for (j = 0; j < r; j++) {\n                    if (max_claim[i][j] - curr[i][j] > avl[j]) {\n                        exec = 0;\n                        break;\n                    }\n                }\n\n                if (exec) {\n                    printf(\"\\nProcess%d is executing.\\n\", i + 1);\n                    running[i] = 0;\n                    count--;\n                    safe = true;\n                    for (j = 0; j < r; j++)\n                        avl[j] += curr[i][j];\n                    break;\n                }\n            }\n        }\n\n        if (!safe) {\n            printf(\"\\nThe processes are in unsafe state.\");\n            break;\n        }\n\n        if (safe)\n            printf(\"\\nThe process is in safe state.\");\n\n        printf(\"\\nAvailable vector: \");\n        for (i = 0; i < r; i++)\n            printf(\"%d \", avl[i]);\n    }\n\n    return 0;\n}\n", "Go": "package bank\n\nimport (\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n    \"sort\"\n    \"sync\"\n)\n\ntype PID string\ntype RID string\ntype RMap map[RID]int\n\n\nfunc (m RMap) String() string {\n    rs := make([]string, len(m))\n    i := 0\n    for r := range m {\n        rs[i] = string(r)\n        i++\n    }\n    sort.Strings(rs)\n    var b bytes.Buffer\n    b.WriteString(\"{\")\n    for _, r := range rs {\n        fmt.Fprintf(&b, \"%q: %d, \", r, m[RID(r)])\n    }\n    bb := b.Bytes()\n    if len(bb) > 1 {\n        bb[len(bb)-2] = '}'\n    }\n    return string(bb)\n}\n\ntype Bank struct {\n    available  RMap\n    max        map[PID]RMap\n    allocation map[PID]RMap\n    sync.Mutex\n}\n\nfunc (b *Bank) need(p PID, r RID) int {\n    return b.max[p][r] - b.allocation[p][r]\n}\n\nfunc New(available RMap) (b *Bank, err error) {\n    for r, a := range available {\n        if a < 0 {\n            return nil, fmt.Errorf(\"negative resource %s: %d\", r, a)\n        }\n    }\n    return &Bank{\n        available:  available,\n        max:        map[PID]RMap{},\n        allocation: map[PID]RMap{},\n    }, nil\n}\n\nfunc (b *Bank) NewProcess(p PID, max RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[p]; ok {\n        return fmt.Errorf(\"process %s already registered\", p)\n    }\n    for r, m := range max {\n        switch a, ok := b.available[r]; {\n        case !ok:\n            return fmt.Errorf(\"resource %s unknown\", r)\n        case m > a:\n            return fmt.Errorf(\"resource %s: process %s max %d > available %d\",\n                r, p, m, a)\n        }\n    }\n    b.max[p] = max\n    b.allocation[p] = RMap{}\n    return\n}\n\nfunc (b *Bank) Request(pid PID, change RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[pid]; !ok {\n        return fmt.Errorf(\"process %s unknown\", pid)\n    }\n    for r, c := range change {\n        if c < 0 {\n            return errors.New(\"decrease not allowed\")\n        }\n        if _, ok := b.available[r]; !ok {\n            return fmt.Errorf(\"resource %s unknown\", r)\n        }\n        if c > b.need(pid, r) {\n            return errors.New(\"increase exceeds declared max\")\n        }\n    }\n    \n    \n    for r, c := range change {\n        b.allocation[pid][r] += c \n    }\n    defer func() {\n        if err != nil { \n            for r, c := range change {\n                b.allocation[pid][r] -= c \n            }\n        }\n    }()\n    \n    \n    cash := RMap{}\n    for r, a := range b.available {\n        cash[r] = a\n    }\n    perm := make([]PID, len(b.allocation))\n    i := 1\n    for pr, a := range b.allocation {\n        if pr == pid {\n            perm[0] = pr\n        } else {\n            perm[i] = pr\n            i++\n        }\n        for r, a := range a {\n            cash[r] -= a\n        }\n    }\n    ret := RMap{}  \n    m := len(perm) \n    for {\n        \n        h := 0\n    h:\n        for ; ; h++ {\n            if h == m {\n                \n                return errors.New(\"request would make deadlock possible\")\n            }\n            for r := range b.available {\n                if b.need(perm[h], r) > cash[r]+ret[r] {\n                    \n                    continue h\n                }\n            }\n            \n            log.Println(\" \", perm[h], \"could terminate\")\n            \n            break\n        }\n        if h == 0 { \n            \n            \n            return nil\n        }\n        for r, a := range b.allocation[perm[h]] {\n            ret[r] += a\n        }\n        m--\n        perm[h] = perm[m]\n    }\n}\n"}
{"id": 53121, "name": "Range extraction", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n"}
{"id": 53122, "name": "Machine code", "C": "#include <stdio.h>\n#include <sys/mman.h>\n#include <string.h>\n\nint test (int a, int b)\n{\n  \n  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};\n  void *buf;\n  int c;\n  \n  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,\n             MAP_PRIVATE|MAP_ANON,-1,0);\n\n  memcpy (buf, code, sizeof(code));\n  \n  c = ((int (*) (int, int))buf)(a, b);\n  \n  munmap (buf, sizeof(code));\n  return c;\n}\n\nint main ()\n{\n  printf(\"%d\\n\", test(7,12));\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nimport \"C\"\n\nfunc main() {\n    code := []byte{\n        0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,\n        0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,\n        0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,\n        0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,\n    }\n    le := len(code)\n    buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,\n        C.MAP_PRIVATE|C.MAP_ANON, -1, 0)\n    codePtr := C.CBytes(code)\n    C.memcpy(buf, codePtr, C.size_t(le))\n    var a, b byte = 7, 12\n    fmt.Printf(\"%d + %d = \", a, b)\n    C.runMachineCode(buf, C.byte(a), C.byte(b))\n    C.munmap(buf, C.size_t(le))\n    C.free(codePtr)\n}\n"}
{"id": 53123, "name": "Type detection", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n"}
{"id": 53124, "name": "Maximum triangle path sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 53125, "name": "Zhang-Suen thinning algorithm", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n"}
{"id": 53126, "name": "Median filter", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef struct { unsigned char r, g, b; } rgb_t;\ntypedef struct {\n\tint w, h;\n\trgb_t **pix;\n} image_t, *image;\n\ntypedef struct {\n\tint r[256], g[256], b[256];\n\tint n;\n} color_histo_t;\n\nint write_ppm(image im, char *fn)\n{\n\tFILE *fp = fopen(fn, \"w\");\n\tif (!fp) return 0;\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", im->w, im->h);\n\tfwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);\n\tfclose(fp);\n\treturn 1;\n}\n\nimage img_new(int w, int h)\n{\n\tint i;\n\timage im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)\n\t\t\t+ sizeof(rgb_t) * w * h);\n\tim->w = w; im->h = h;\n\tim->pix = (rgb_t**)(im + 1);\n\tfor (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)\n\t\tim->pix[i] = im->pix[i - 1] + w;\n\treturn im;\n}\n\nint read_num(FILE *f)\n{\n\tint n;\n\twhile (!fscanf(f, \"%d \", &n)) {\n\t\tif ((n = fgetc(f)) == '#') {\n\t\t\twhile ((n = fgetc(f)) != '\\n')\n\t\t\t\tif (n == EOF) break;\n\t\t\tif (n == '\\n') continue;\n\t\t} else return 0;\n\t}\n\treturn n;\n}\n\nimage read_ppm(char *fn)\n{\n\tFILE *fp = fopen(fn, \"r\");\n\tint w, h, maxval;\n\timage im = 0;\n\tif (!fp) return 0;\n\n\tif (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))\n\t\tgoto bail;\n\n\tw = read_num(fp);\n\th = read_num(fp);\n\tmaxval = read_num(fp);\n\tif (!w || !h || !maxval) goto bail;\n\n\tim = img_new(w, h);\n\tfread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);\nbail:\n\tif (fp) fclose(fp);\n\treturn im;\n}\n\nvoid del_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]--;\n\t\th->g[pix->g]--;\n\t\th->b[pix->b]--;\n\t\th->n--;\n\t}\n}\n\nvoid add_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]++;\n\t\th->g[pix->g]++;\n\t\th->b[pix->b]++;\n\t\th->n++;\n\t}\n}\n\nvoid init_histo(image im, int row, int size, color_histo_t*h)\n{\n\tint j;\n\n\tmemset(h, 0, sizeof(color_histo_t));\n\n\tfor (j = 0; j < size && j < im->w; j++)\n\t\tadd_pixels(im, row, j, size, h);\n}\n\nint median(const int *x, int n)\n{\n\tint i;\n\tfor (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);\n\treturn i;\n}\n\nvoid median_color(rgb_t *pix, const color_histo_t *h)\n{\n\tpix->r = median(h->r, h->n);\n\tpix->g = median(h->g, h->n);\n\tpix->b = median(h->b, h->n);\n}\n\nimage median_filter(image in, int size)\n{\n\tint row, col;\n\timage out = img_new(in->w, in->h);\n\tcolor_histo_t h;\n\n\tfor (row = 0; row < in->h; row ++) {\n\t\tfor (col = 0; col < in->w; col++) {\n\t\t\tif (!col) init_histo(in, row, size, &h);\n\t\t\telse {\n\t\t\t\tdel_pixels(in, row, col - size, size, &h);\n\t\t\t\tadd_pixels(in, row, col + size, size, &h);\n\t\t\t}\n\t\t\tmedian_color(out->pix[row] + col, &h);\n\t\t}\n\t}\n\n\treturn out;\n}\n\nint main(int c, char **v)\n{\n\tint size;\n\timage in, out;\n\tif (c <= 3) {\n\t\tprintf(\"Usage: %s size ppm_in ppm_out\\n\", v[0]);\n\t\treturn 0;\n\t}\n\tsize = atoi(v[1]);\n\tprintf(\"filter size %d\\n\", size);\n\tif (size < 0) size = 1;\n\n\tin = read_ppm(v[2]);\n\tout = median_filter(in, size);\n\twrite_ppm(out, v[3]);\n\tfree(in);\n\tfree(out);\n\n\treturn 0;\n}\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"raster\"\n)\n\nvar g0, g1 *raster.Grmap\nvar ko [][]int\nvar kc []uint16\nvar mid int\n\nfunc init() {\n    \n    ko = [][]int{\n        {-1, -1}, {0, -1}, {1, -1},\n        {-1,  0}, {0,  0}, {1,  0},\n        {-1,  1}, {0,  1}, {1,  1}}\n    kc = make([]uint16, len(ko))\n    mid = len(ko) / 2\n}\n\nfunc main() {\n    \n    \n    \n    \n    \n    b, err := raster.ReadPpmFile(\"Lenna50.ppm\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    g0 = b.Grmap()\n    w, h := g0.Extent()\n    g1 = raster.NewGrmap(w, h)\n    for y := 0; y < h; y++ {\n        for x := 0; x < w; x++ {\n            g1.SetPx(x, y, median(x, y))\n        }\n    }\n    \n    \n    err = g1.Bitmap().WritePpmFile(\"median.ppm\")\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc median(x, y int) uint16 {\n    var n int\n    \n    \n    \n    for _, o := range ko {\n        \n        c, ok := g0.GetPx(x+o[0], y+o[1])\n        if !ok {\n            continue\n        }\n        \n        var i int\n        for ; i < n; i++ {\n            if c < kc[i] {\n                for j := n; j > i; j-- {\n                    kc[j] = kc[j-1]\n                }\n                break\n            }\n        }\n        kc[i] = c\n        n++\n    }\n    \n    switch {\n    case n == len(kc): \n        return kc[mid]\n    case n%2 == 1: \n        return kc[n/2]\n    }\n    \n    m := n / 2\n    return (kc[m-1] + kc[m]) / 2\n}\n"}
{"id": 53127, "name": "Run as a daemon or service", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n"}
{"id": 53128, "name": "Run as a daemon or service", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n"}
{"id": 53129, "name": "Compiler_Verifying syntax", "C": "\n\n\n\n\n#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <setjmp.h>\n\n#define AT(CHAR) ( *pos == CHAR && ++pos )\n#define TEST(STR) ( strncmp( pos, STR, strlen(STR) ) == 0 \\\n  && ! isalnum(pos[strlen(STR)]) && pos[strlen(STR)] != '_' )\n#define IS(STR) ( TEST(STR) && (pos += strlen(STR)) )\n\nstatic char *pos;                                 \nstatic char *startpos;                            \nstatic jmp_buf jmpenv;\n\nstatic int\nerror(char *message)\n  {\n  printf(\"false  %s\\n%*s^ %s\\n\", startpos, pos - startpos + 7, \"\", message);\n  longjmp( jmpenv, 1 );\n  }\n\nstatic int\nexpr(int level)\n  {\n  while( isspace(*pos) ) ++pos;                     \n  if( AT('(') )                                     \n    {\n    if( expr(0) && ! AT(')') ) error(\"missing close paren\");\n    }\n  else if( level <= 4 && IS(\"not\") && expr(6) ) { }\n  else if( TEST(\"or\") || TEST(\"and\") || TEST(\"not\") )\n    {\n    error(\"expected a primary, found an operator\");\n    }\n  else if( isdigit(*pos) ) pos += strspn( pos, \"0123456789\" );\n  else if( isalpha(*pos) ) pos += strspn( pos, \"0123456789_\"\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" );\n  else error(\"expected a primary\");\n\n  do                    \n    {\n    while( isspace(*pos) ) ++pos;\n    }\n  while(\n    level <= 2 && IS(\"or\") ? expr(3) :\n    level <= 3 && IS(\"and\") ? expr(4) :\n    level <= 4 && (AT('=') || AT('<')) ? expr(5) :\n    level == 5 && (*pos == '=' || *pos == '<') ? error(\"non-associative\") :\n    level <= 6 && (AT('+') || AT('-')) ? expr(7) :\n    level <= 7 && (AT('*') || AT('/')) ? expr(8) :\n    0 );\n  return 1;\n  }\n\nstatic void\nparse(char *source)\n  {\n  startpos = pos = source;\n  if( setjmp(jmpenv) ) return; \n  expr(0);\n  if( *pos ) error(\"unexpected character following valid parse\");\n  printf(\" true  %s\\n\", source);\n  }\n\nstatic char *tests[] = {\n  \"3 + not 5\",\n  \"3 + (not 5)\",\n  \"(42 + 3\",\n  \"(42 + 3 some_other_syntax_error\",\n  \"not 3 < 4 or (true or 3/4+8*5-5*2 < 56) and 4*3 < 12 or not true\",\n  \"and 3 < 2\",\n  \"not 7 < 2\",\n  \"2 < 3 < 4\",\n  \"2 < foobar - 3 < 4\",\n  \"2 < foobar and 3 < 4\",\n  \"4 * (32 - 16) + 9 = 73\",\n  \"235 76 + 1\",\n  \"a + b = not c and false\",\n  \"a + b = (not c) and false\",\n  \"a + b = (not c and false)\",\n  \"ab_c / bd2 or < e_f7\",\n  \"g not = h\",\n  \"i++\",\n  \"j & k\",\n  \"l or _m\",\n  \"wombat\",\n  \"WOMBAT or monotreme\",\n  \"a + b - c * d / e < f and not ( g = h )\",\n  \"$\",\n  };\n\nint\nmain(int argc, char *argv[])\n  {\n  for( int i = 0; i < sizeof(tests)/sizeof(*tests); i++ ) parse(tests[i]);\n  }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/parser\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar (\n    re1 = regexp.MustCompile(`[^_a-zA-Z0-9\\+\\-\\*/=<\\(\\)\\s]`)\n    re2 = regexp.MustCompile(`\\b_\\w*\\b`)\n    re3 = regexp.MustCompile(`[=<+*/-]\\s*not`)\n    re4 = regexp.MustCompile(`(=|<)\\s*[^(=< ]+\\s*([=<+*/-])`)\n)\n\nvar subs = [][2]string{\n    {\"=\", \"==\"}, {\" not \", \" ! \"}, {\"(not \", \"(! \"}, {\" or \", \" || \"}, {\" and \", \" && \"},\n}\n\nfunc possiblyValid(expr string) error {\n    matches := re1.FindStringSubmatch(expr)\n    if matches != nil {\n        return fmt.Errorf(\"invalid character %q found\", []rune(matches[0])[0])\n    }\n    if re2.MatchString(expr) {\n        return fmt.Errorf(\"identifier cannot begin with an underscore\")\n    }\n    if re3.MatchString(expr) {\n        return fmt.Errorf(\"expected operand, found 'not'\")\n    }\n    matches = re4.FindStringSubmatch(expr)\n    if matches != nil {\n        return fmt.Errorf(\"operator %q is non-associative\", []rune(matches[1])[0])\n    }\n    return nil\n}\n\nfunc modify(err error) string {\n    e := err.Error()\n    for _, sub := range subs {\n        e = strings.ReplaceAll(e, strings.TrimSpace(sub[1]), strings.TrimSpace(sub[0]))\n    }\n    return strings.Split(e, \":\")[2][1:] \n}\n\nfunc main() {\n    exprs := []string{\n        \"$\",\n        \"one\",\n        \"either or both\",\n        \"a + 1\",\n        \"a + b < c\",\n        \"a = b\",\n        \"a or b = c\",\n        \"3 + not 5\",\n        \"3 + (not 5)\",\n        \"(42 + 3\",\n        \"(42 + 3)\",\n        \" not 3 < 4 or (true or 3 /  4 + 8 *  5 - 5 * 2 < 56) and 4 * 3  < 12 or not true\",\n        \" and 3 < 2\",\n        \"not 7 < 2\",\n        \"2 < 3 < 4\",\n        \"2 < (3 < 4)\",\n        \"2 < foobar - 3 < 4\",\n        \"2 < foobar and 3 < 4\",\n        \"4 * (32 - 16) + 9 = 73\",\n        \"235 76 + 1\",\n        \"true or false = not true\",\n        \"true or false = (not true)\",\n        \"not true or false = false\",\n        \"not true = false\",\n        \"a + b = not c and false\",\n        \"a + b = (not c) and false\",\n        \"a + b = (not c and false)\",\n        \"ab_c / bd2 or < e_f7\",\n        \"g not = h\",\n        \"été = false\",\n        \"i++\",\n        \"j & k\",\n        \"l or _m\",\n    } \n   \n    for _, expr := range exprs {\n        fmt.Printf(\"Statement to verify: %q\\n\", expr)\n        if err := possiblyValid(expr); err != nil {\n            fmt.Printf(\"\\\"false\\\" -> %s\\n\\n\", err.Error())\n            continue\n        }\n        expr = fmt.Sprintf(\" %s \", expr) \n        for _, sub := range subs {\n            expr = strings.ReplaceAll(expr, sub[0], sub[1])\n        }\n        _, err := parser.ParseExpr(expr)\n        if err != nil {\n            fmt.Println(`\"false\" ->`, modify(err))\n        } else {\n            fmt.Println(`\"true\"`)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 53130, "name": "Coprime triplets", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n"}
{"id": 53131, "name": "Coprime triplets", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n"}
{"id": 53132, "name": "Coprime triplets", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n"}
{"id": 53133, "name": "Variable declaration reset", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n"}
{"id": 53134, "name": "SOAP", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n"}
{"id": 53135, "name": "Pragmatic directives", "C": "\n#include<stdio.h> \n\n\n#define Hi printf(\"Hi There.\");\n\n\n\n#define start int main(){\n#define end return 0;}\n\nstart\n\nHi\n\n\n#warning \"Don't you have anything better to do ?\"\n\n#ifdef __unix__\n#warning \"What are you doing still working on Unix ?\"\nprintf(\"\\nThis is an Unix system.\");\n#elif _WIN32\n#warning \"You couldn't afford a 64 bit ?\"\nprintf(\"\\nThis is a 32 bit Windows system.\");\n#elif _WIN64\n#warning \"You couldn't afford an Apple ?\"\nprintf(\"\\nThis is a 64 bit Windows system.\");\n#endif\n\nend\n\n\n", "Go": "\n"}
{"id": 53136, "name": "Find first and last set bit of a long integer", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n"}
{"id": 53137, "name": "Find first and last set bit of a long integer", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n"}
{"id": 53138, "name": "Numbers with equal rises and falls", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n"}
{"id": 53139, "name": "Terminal control_Cursor movement", "C": "#include<conio.h>\n#include<dos.h>\n\nchar *strings[] = {\"The cursor will move one position to the left\", \n  \t\t   \"The cursor will move one position to the right\",\n \t\t   \"The cursor will move vetically up one line\", \n \t\t   \"The cursor will move vertically down one line\", \n \t\t   \"The cursor will move to the beginning of the line\", \n \t\t   \"The cursor will move to the end of the line\", \n \t\t   \"The cursor will move to the top left corner of the screen\", \n \t\t   \"The cursor will move to the bottom right corner of the screen\"};\n \t\t             \nint main()\n{\n\tint i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\t\n\tclrscr();\n\tcprintf(\"This is a demonstration of cursor control using gotoxy(). Press any key to continue.\");\n\tgetch();\n\t\n\tfor(i=0;i<8;i++)\n\t{\n\t\tclrscr();\n\t\tgotoxy(5,MAXROW/2);\n\t\t\n\t\tcprintf(\"%s\",strings[i]);\n\t\tgetch();\n\t\t\n\t\tswitch(i){\n\t\t\tcase 0:gotoxy(wherex()-1,wherey());\n\t\t\tbreak;\n\t\t\tcase 1:gotoxy(wherex()+1,wherey());\n\t\t\tbreak;\n\t\t\tcase 2:gotoxy(wherex(),wherey()-1);\n\t\t\tbreak;\n\t\t\tcase 3:gotoxy(wherex(),wherey()+1);\n\t\t\tbreak;\n\t\t\tcase 4:for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()-1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 5:gotoxy(wherex()-strlen(strings[i]),wherey());\n\t\t\t       for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()+1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 6:while(wherex()!=1)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()-1,wherey());\n\t\t\t\t     delay(100);\n\t\t               }\n\t\t\t       while(wherey()!=1)\n\t\t\t       {\n\t\t\t             gotoxy(wherex(),wherey()-1);\n\t\t\t             delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 7:while(wherex()!=MAXCOL)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()+1,wherey());\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\t       while(wherey()!=MAXROW)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex(),wherey()+1);\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\t};\n\t\t\tgetch();\n\t}\n\t\n\tclrscr();\n\tcprintf(\"End of demonstration.\");\n\tgetch();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc main() {\n    tput(\"clear\") \n    tput(\"cup\", \"6\", \"3\") \n    time.Sleep(1 * time.Second)\n    tput(\"cub1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuf1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuu1\") \n    time.Sleep(1 * time.Second)\n    \n    tput(\"cud\", \"1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cr\") \n    time.Sleep(1 * time.Second)\n    \n    var h, w int\n    cmd := exec.Command(\"stty\", \"size\")\n    cmd.Stdin = os.Stdin\n    d, _ := cmd.Output()\n    fmt.Sscan(string(d), &h, &w)\n    \n    tput(\"hpa\", strconv.Itoa(w-1))\n    time.Sleep(2 * time.Second)\n    \n    tput(\"home\")\n    time.Sleep(2 * time.Second)\n    \n    tput(\"cup\", strconv.Itoa(h-1), strconv.Itoa(w-1))\n    time.Sleep(3 * time.Second)\n}\n\nfunc tput(args ...string) error {\n    cmd := exec.Command(\"tput\", args...)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n"}
{"id": 53140, "name": "Simulated annealing", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <unistd.h>\n\n#define VECSZ 100\n#define STATESZ 64\n\ntypedef float floating_pt;\n#define EXP expf\n#define SQRT sqrtf\n\nstatic floating_pt\nrandnum (void)\n{\n  return (floating_pt)\n    ((double) (random () & 2147483647) / 2147483648.0);\n}\n\nstatic void\nshuffle (uint8_t vec[], size_t i, size_t n)\n{\n  \n  for (size_t j = 0; j != n; j += 1)\n    {\n      size_t k = i + j + (random () % (n - j));\n      uint8_t xi = vec[i];\n      uint8_t xk = vec[k];\n      vec[i] = xk;\n      vec[k] = xi;\n    }\n}\n\nstatic void\ninit_s (uint8_t vec[VECSZ])\n{\n  for (uint8_t j = 0; j != VECSZ; j += 1)\n    vec[j] = j;\n  shuffle (vec, 1, VECSZ - 1);\n}\n\nstatic inline void\nadd_neighbor (uint8_t neigh[8],\n              unsigned int *neigh_size,\n              uint8_t neighbor)\n{\n  if (neighbor != 0)\n    {\n      neigh[*neigh_size] = neighbor;\n      *neigh_size += 1;\n    }\n}\n\nstatic void\nneighborhood (uint8_t neigh[8],\n              unsigned int *neigh_size,\n              uint8_t city)\n{\n  \n\n  const uint8_t i = city / 10;\n  const uint8_t j = city % 10;\n\n  uint8_t c0 = 0;\n  uint8_t c1 = 0;\n  uint8_t c2 = 0;\n  uint8_t c3 = 0;\n  uint8_t c4 = 0;\n  uint8_t c5 = 0;\n  uint8_t c6 = 0;\n  uint8_t c7 = 0;\n\n  if (i < 9)\n    {\n      c0 = (10 * (i + 1)) + j;\n      if (j < 9)\n        c1 = (10 * (i + 1)) + (j + 1);\n      if (0 < j)\n        c2 = (10 * (i + 1)) + (j - 1);\n    }\n  if (0 < i)\n    {\n      c3 = (10 * (i - 1)) + j;\n      if (j < 9)\n        c4 = (10 * (i - 1)) + (j + 1);\n      if (0 < j)\n        c5 = (10 * (i - 1)) + (j - 1);\n    }\n  if (j < 9)\n    c6 = (10 * i) + (j + 1);\n  if (0 < j)\n    c7 = (10 * i) + (j - 1);\n\n  *neigh_size = 0;\n  add_neighbor (neigh, neigh_size, c0);\n  add_neighbor (neigh, neigh_size, c1);\n  add_neighbor (neigh, neigh_size, c2);\n  add_neighbor (neigh, neigh_size, c3);\n  add_neighbor (neigh, neigh_size, c4);\n  add_neighbor (neigh, neigh_size, c5);\n  add_neighbor (neigh, neigh_size, c6);\n  add_neighbor (neigh, neigh_size, c7);\n}\n\nstatic floating_pt\ndistance (uint8_t m, uint8_t n)\n{\n  const uint8_t im = m / 10;\n  const uint8_t jm = m % 10;\n  const uint8_t in = n / 10;\n  const uint8_t jn = n % 10;\n  const int di = (int) im - (int) in;\n  const int dj = (int) jm - (int) jn;\n  return SQRT ((di * di) + (dj * dj));\n}\n\nstatic floating_pt\npath_length (uint8_t vec[VECSZ])\n{\n  floating_pt len = distance (vec[0], vec[VECSZ - 1]);\n  for (size_t j = 0; j != VECSZ - 1; j += 1)\n    len += distance (vec[j], vec[j + 1]);\n  return len;\n}\n\nstatic void\nswap_s_elements (uint8_t vec[], uint8_t u, uint8_t v)\n{\n  size_t j = 1;\n  size_t iu = 0;\n  size_t iv = 0;\n  while (iu == 0 || iv == 0)\n    {\n      if (vec[j] == u)\n        iu = j;\n      else if (vec[j] == v)\n        iv = j;\n      j += 1;\n    }\n  vec[iu] = v;\n  vec[iv] = u;\n}\n\nstatic void\nupdate_s (uint8_t vec[])\n{\n  const uint8_t u = 1 + (random () % (VECSZ - 1));\n  uint8_t neighbors[8];\n  unsigned int num_neighbors;\n  neighborhood (neighbors, &num_neighbors, u);\n  const uint8_t v = neighbors[random () % num_neighbors];\n  swap_s_elements (vec, u, v);\n}\n\nstatic inline void\ncopy_s (uint8_t dst[VECSZ], uint8_t src[VECSZ])\n{\n  memcpy (dst, src, VECSZ * (sizeof src[0]));\n}\n\nstatic void\ntrial_s (uint8_t trial[VECSZ], uint8_t vec[VECSZ])\n{\n  copy_s (trial, vec);\n  update_s (trial);\n}\n\nstatic floating_pt\ntemperature (floating_pt kT, unsigned int kmax, unsigned int k)\n{\n  return kT * (1 - ((floating_pt) k / (floating_pt) kmax));\n}\n\nstatic floating_pt\nprobability (floating_pt delta_E, floating_pt T)\n{\n  floating_pt prob;\n  if (delta_E < 0)\n    prob = 1;\n  else if (T == 0)\n    prob = 0;\n  else\n    prob = EXP (-(delta_E / T));\n  return prob;\n}\n\nstatic void\nshow (unsigned int k, floating_pt T, floating_pt E)\n{\n  printf (\" %7u %7.1f %13.5f\\n\", k, (double) T, (double) E);\n}\n\nstatic void\nsimulate_annealing (floating_pt kT,\n                    unsigned int kmax,\n                    uint8_t s[VECSZ])\n{\n  uint8_t trial[VECSZ];\n\n  unsigned int kshow = kmax / 10;\n  floating_pt E = path_length (s);\n  for (unsigned int k = 0; k != kmax + 1; k += 1)\n    {\n      const floating_pt T = temperature (kT, kmax, k);\n      if (k % kshow == 0)\n        show (k, T, E);\n      trial_s (trial, s);\n      const floating_pt E_trial = path_length (trial);\n      const floating_pt delta_E = E_trial - E;\n      const floating_pt P = probability (delta_E, T);\n      if (P == 1 || randnum () <= P)\n        {\n          copy_s (s, trial);\n          E = E_trial;\n        }\n    }\n}\n\nstatic void\ndisplay_path (uint8_t vec[VECSZ])\n{\n  for (size_t i = 0; i != VECSZ; i += 1)\n    {\n      const uint8_t x = vec[i];\n      printf (\"%2u ->\", (unsigned int) x);\n      if ((i % 8) == 7)\n        printf (\"\\n\");\n      else\n        printf (\" \");\n    }\n  printf (\"%2u\\n\", vec[0]);\n}\n\nint\nmain (void)\n{\n  char state[STATESZ];\n  uint32_t seed[1];\n  int status = getentropy (&seed[0], sizeof seed[0]);\n  if (status < 0)\n    seed[0] = 1;\n  initstate (seed[0], state, STATESZ);\n\n  floating_pt kT = 1.0;\n  unsigned int kmax = 1000000;\n\n  uint8_t s[VECSZ];\n  init_s (s);\n\n  printf (\"\\n\");\n  printf (\"   kT: %f\\n\", (double) kT);\n  printf (\"   kmax: %u\\n\", kmax);\n  printf (\"\\n\");\n  printf (\"       k       T          E(s)\\n\");\n  printf (\" -----------------------------\\n\");\n  simulate_annealing (kT, kmax, s);\n  printf (\"\\n\");\n  display_path (s);\n  printf (\"\\n\");\n  printf (\"Final E(s): %.5f\\n\", (double) path_length (s));\n  printf (\"\\n\");\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar (\n    dists = calcDists()\n    dirs  = [8]int{1, -1, 10, -10, 9, 11, -11, -9} \n)\n\n\nfunc calcDists() []float64 {\n    dists := make([]float64, 10000)\n    for i := 0; i < 10000; i++ {\n        ab, cd := math.Floor(float64(i)/100), float64(i%100)\n        a, b := math.Floor(ab/10), float64(int(ab)%10)\n        c, d := math.Floor(cd/10), float64(int(cd)%10)\n        dists[i] = math.Hypot(a-c, b-d)\n    }\n    return dists\n}\n\n\nfunc dist(ci, cj int) float64 {\n    return dists[cj*100+ci]\n}\n\n\nfunc Es(path []int) float64 {\n    d := 0.0\n    for i := 0; i < len(path)-1; i++ {\n        d += dist(path[i], path[i+1])\n    }\n    return d\n}\n\n\nfunc T(k, kmax, kT int) float64 {\n    return (1 - float64(k)/float64(kmax)) * float64(kT)\n}\n\n\nfunc dE(s []int, u, v int) float64 {\n    su, sv := s[u], s[v]\n    \n    a, b, c, d := dist(s[u-1], su), dist(s[u+1], su), dist(s[v-1], sv), dist(s[v+1], sv)\n    \n    na, nb, nc, nd := dist(s[u-1], sv), dist(s[u+1], sv), dist(s[v-1], su), dist(s[v+1], su)\n    if v == u+1 {\n        return (na + nd) - (a + d)\n    } else if u == v+1 {\n        return (nc + nb) - (c + b)\n    } else {\n        return (na + nb + nc + nd) - (a + b + c + d)\n    }\n}\n\n\nfunc P(deltaE float64, k, kmax, kT int) float64 {\n    return math.Exp(-deltaE / T(k, kmax, kT))\n}\n\nfunc sa(kmax, kT int) {\n    rand.Seed(time.Now().UnixNano())\n    temp := make([]int, 99)\n    for i := 0; i < 99; i++ {\n        temp[i] = i + 1\n    }\n    rand.Shuffle(len(temp), func(i, j int) {\n        temp[i], temp[j] = temp[j], temp[i]\n    })\n    s := make([]int, 101) \n    copy(s[1:], temp)     \n    fmt.Println(\"kT =\", kT)\n    fmt.Printf(\"E(s0) %f\\n\\n\", Es(s)) \n    Emin := Es(s)                     \n    for k := 0; k <= kmax; k++ {\n        if k%(kmax/10) == 0 {\n            fmt.Printf(\"k:%10d   T: %8.4f   Es: %8.4f\\n\", k, T(k, kmax, kT), Es(s))\n        }\n        u := 1 + rand.Intn(99)          \n        cv := s[u] + dirs[rand.Intn(8)] \n        if cv <= 0 || cv >= 100 {       \n            continue\n        }\n        if dist(s[u], cv) > 5 { \n            continue\n        }\n        v := s[cv] \n        deltae := dE(s, u, v)\n        if deltae < 0 || \n            P(deltae, k, kmax, kT) >= rand.Float64() {\n            s[u], s[v] = s[v], s[u]\n            Emin += deltae\n        }\n    }\n    fmt.Printf(\"\\nE(s_final) %f\\n\", Emin)\n    fmt.Println(\"Path:\")\n    \n    for i := 0; i < len(s); i++ {\n        if i > 0 && i%10 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", s[i])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    sa(1e6, 1)\n}\n"}
{"id": 53141, "name": "Start from a main routine", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n"}
{"id": 53142, "name": "Start from a main routine", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n"}
{"id": 53143, "name": "Summation of primes", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n    int p;\n    long int s = 2;\n    for(p=3;p<2000000;p+=2) {\n        if(isprime(p)) s+=p;\n    }\n    printf( \"%ld\\n\", s );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    sum := 0\n    for _, p := range rcu.Primes(2e6 - 1) {\n        sum += p\n    }\n    fmt.Printf(\"The sum of all primes below 2 million is %s.\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 53144, "name": "Koch curve", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n"}
{"id": 53145, "name": "Draw pixel 2", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<time.h>\n\nint main()\n{\n\tsrand(time(NULL));\n\t\n\tinitwindow(640,480,\"Yellow Random Pixel\");\n\t\n\tputpixel(rand()%640,rand()%480,YELLOW);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 640, 480)\n    img := image.NewRGBA(rect)\n\n    \n    blue := color.RGBA{0, 0, 255, 255}\n    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)\n\n    \n    yellow := color.RGBA{255, 255, 0, 255}\n    width := img.Bounds().Dx()\n    height := img.Bounds().Dy()\n    rand.Seed(time.Now().UnixNano())\n    x := rand.Intn(width)\n    y := rand.Intn(height)\n    img.Set(x, y, yellow)\n\n    \n    cmap := map[color.Color]string{blue: \"blue\", yellow: \"yellow\"}\n    for i := 0; i < width; i++ {\n        for j := 0; j < height; j++ {\n            c := img.At(i, j)\n            if cmap[c] == \"yellow\" {\n                fmt.Printf(\"The color of the pixel at (%d, %d) is yellow\\n\", i, j)\n            }\n        }\n    }\n}\n"}
{"id": 53146, "name": "Count how many vowels and consonants occur in a string", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n"}
{"id": 53147, "name": "Count how many vowels and consonants occur in a string", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n"}
{"id": 53148, "name": "Compiler_syntax analyzer", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n"}
{"id": 53149, "name": "Compiler_syntax analyzer", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n"}
{"id": 53150, "name": "Draw a pixel", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n"}
{"id": 53151, "name": "Numbers whose binary and ternary digit sums are prime", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n"}
{"id": 53152, "name": "Numbers whose binary and ternary digit sums are prime", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n"}
{"id": 53153, "name": "Words from neighbour ones", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\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    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n"}
{"id": 53154, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "C": "#include <stdio.h>\n\nint divisible(int n) {\n    int p = 1;\n    int c, d;\n    \n    for (c=n; c; c /= 10) {\n        d = c % 10;\n        if (!d || n % d) return 0;\n        p *= d;\n    }\n    \n    return n % p;\n}\n\nint main() {\n    int n, c=0;\n    \n    for (n=1; n<1000; n++) {\n        if (divisible(n)) {\n            printf(\"%5d\", n);\n            if (!(++c % 10)) printf(\"\\n\");\n        }\n    }\n    printf(\"\\n\");\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var res []int\n    for n := 1; n < 1000; n++ {\n        digits := rcu.Digits(n, 10)\n        var all = true\n        for _, d := range digits {\n            if d == 0 || n%d != 0 {\n                all = false\n                break\n            }\n        }\n        if all {\n            prod := 1\n            for _, d := range digits {\n                prod *= d\n            }\n            if prod > 0 && n%prod != 0 {\n                res = append(res, n)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 1000 divisible by their digits, but not by the product thereof:\")\n    for i, n := range res {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such numbers found\\n\", len(res))\n}\n"}
{"id": 53155, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 53156, "name": "Four bit adder", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 53157, "name": "Magic squares of singly even order", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n"}
{"id": 53158, "name": "Scope_Function names and labels", "C": "#include <stdio.h>\n\n#define sqr(x) ((x) * (x))\n#define greet printf(\"Hello There!\\n\")\n\nint twice(int x)\n{\n\treturn 2 * x;\n}\n\nint main(void)\n{\n\tint x;\n\n\tprintf(\"This will demonstrate function and label scopes.\\n\");\n\tprintf(\"All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\\n\");\n\tprintf(\"Enter a number: \");\n\tif (scanf(\"%d\", &x) != 1)\n\t\treturn 0;\n\t\n\tswitch (x % 2) {\n\tdefault:\n\t\tprintf(\"Case labels in switch statements have scope local to the switch block.\\n\");\n\tcase 0:\n\t\tprintf(\"You entered an even number.\\n\");\n\t\tprintf(\"Its square is %d, which was computed by a macro. It has global scope within the translation unit.\\n\", sqr(x));\n\t\tbreak;\n\tcase 1:\n\t\tprintf(\"You entered an odd number.\\n\");\n\t\tgoto sayhello;\n\tjumpin:\n\t\tprintf(\"2 times %d is %d, which was computed by a function defined in this file. It has global scope within the translation unit.\\n\", x, twice(x));\n\t\tprintf(\"Since you jumped in, you will now be greeted, again!\\n\"); \n\tsayhello:\n\t\tgreet;\n\t\tif (x == -1)\n\t\t\tgoto scram;   \n\t\tbreak;\n\t}\n\n\tprintf(\"We now come to goto, it's extremely powerful but it's also prone to misuse. Its use is discouraged and it wasn't even adopted by Java and later languages.\\n\");\n\n\tif (x != -1) {\n\t\tx = -1;   \n\t \tgoto jumpin;  \n\t}\n\nscram:\n\tprintf(\"If you are trying to figure out what happened, you now understand goto.\\n\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n\n    \"ex\"\n)\n\nfunc main() {\n    \n\n    \n    f := func() {\n        \n        \n        pc, _, _, _ := runtime.Caller(0)\n        fmt.Println(runtime.FuncForPC(pc).Name(), \"here!\")\n    }\n\n    ex.X(f) \n\n    \n}\n"}
{"id": 53159, "name": "Generate Chess960 starting position", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n"}
{"id": 53160, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 53161, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 53162, "name": "Modulinos", "C": "int meaning_of_life();\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 53163, "name": "Modulinos", "C": "int meaning_of_life();\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 53164, "name": "Perlin noise", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n    X := int(math.Floor(x)) & 255\n    Y := int(math.Floor(y)) & 255\n    Z := int(math.Floor(z)) & 255\n    x -= math.Floor(x)\n    y -= math.Floor(y)\n    z -= math.Floor(z)\n    u := fade(x)\n    v := fade(y)\n    w := fade(z)\n    A := p[X] + Y\n    AA := p[A] + Z\n    AB := p[A+1] + Z\n    B := p[X+1] + Y\n    BA := p[B] + Z\n    BB := p[B+1] + Z\n    return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n        grad(p[BA], x-1, y, z)),\n        lerp(u, grad(p[AB], x, y-1, z),\n            grad(p[BB], x-1, y-1, z))),\n        lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n            grad(p[BA+1], x-1, y, z-1)),\n            lerp(u, grad(p[AB+1], x, y-1, z-1),\n                grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n    \n    \n    \n    switch hash & 15 {\n    case 0, 12:\n        return x + y\n    case 1, 14:\n        return y - x\n    case 2:\n        return x - y\n    case 3:\n        return -x - y\n    case 4:\n        return x + z\n    case 5:\n        return z - x\n    case 6:\n        return x - z\n    case 7:\n        return -x - z\n    case 8:\n        return y + z\n    case 9, 13:\n        return z - y\n    case 10:\n        return y - z\n    }\n    \n    return -y - z\n}\n\nvar permutation = []int{\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n    140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n    247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n    57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n    74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n    60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n    65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n    200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n    52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n    207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n    119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n    129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n    218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n    81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n    184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n    222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)\n"}
{"id": 53165, "name": "File size distribution", "C": "#include<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc commatize(n int64) 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 fileSizeDistribution(root string) {\n    var sizes [12]int\n    files := 0\n    directories := 0\n    totalSize := int64(0)\n    walkFunc := func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        files++\n        if info.IsDir() {\n            directories++\n        }\n        size := info.Size()\n        if size == 0 {\n            sizes[0]++\n            return nil\n        }\n        totalSize += size\n        logSize := math.Log10(float64(size))\n        index := int(math.Floor(logSize))\n        sizes[index+1]++\n        return nil\n    }\n    err := filepath.Walk(root, walkFunc)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n    for i := 0; i < len(sizes); i++ {\n        if i == 0 {\n            fmt.Print(\"  \")\n        } else {\n            fmt.Print(\"+ \")\n        }\n        fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n    }\n    fmt.Println(\"                                  -----\")\n    fmt.Printf(\"= Total number of files         : %5d\\n\", files)\n    fmt.Printf(\"  including directories         : %5d\\n\", directories)\n    c := commatize(totalSize)\n    fmt.Println(\"\\n  Total size of files           :\", c, \"bytes\")\n}\n\nfunc main() {\n    fileSizeDistribution(\"./\")\n}\n"}
{"id": 53166, "name": "Unix_ls", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 53167, "name": "Rendezvous", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <pthread.h>\n\n\n\n\ntypedef struct rendezvous {\n    pthread_mutex_t lock;        \n    pthread_cond_t cv_entering;  \n    pthread_cond_t cv_accepting; \n    pthread_cond_t cv_done;      \n    int (*accept_func)(void*);   \n    int entering;                \n    int accepting;               \n    int done;                    \n} rendezvous_t;\n\n\n#define RENDEZVOUS_INITILIZER(accept_function) {   \\\n        .lock         = PTHREAD_MUTEX_INITIALIZER, \\\n        .cv_entering  = PTHREAD_COND_INITIALIZER,  \\\n        .cv_accepting = PTHREAD_COND_INITIALIZER,  \\\n        .cv_done      = PTHREAD_COND_INITIALIZER,  \\\n        .accept_func  = accept_function,           \\\n        .entering     = 0,                         \\\n        .accepting    = 0,                         \\\n        .done         = 0,                         \\\n    }\n\nint enter_rendezvous(rendezvous_t *rv, void* data)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n\n    rv->entering++;\n    pthread_cond_signal(&rv->cv_entering);\n\n    while (!rv->accepting) {\n        \n        pthread_cond_wait(&rv->cv_accepting, &rv->lock);\n    }\n\n    \n    int ret = rv->accept_func(data);\n\n    \n    rv->done = 1;\n    pthread_cond_signal(&rv->cv_done);\n\n    rv->entering--;\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n\n    return ret;\n}\n\nvoid accept_rendezvous(rendezvous_t *rv)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n    rv->accepting = 1;\n\n    while (!rv->entering) {\n        \n        pthread_cond_wait(&rv->cv_entering, &rv->lock);\n    }\n\n    pthread_cond_signal(&rv->cv_accepting);\n\n    while (!rv->done) {\n        \n        pthread_cond_wait(&rv->cv_done, &rv->lock);\n    }\n    rv->done = 0;\n\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n}\n\n\n\ntypedef struct printer {\n    rendezvous_t rv;\n    struct printer *backup;\n    int id;\n    int remaining_lines;\n} printer_t;\n\ntypedef struct print_args {\n    struct printer *printer;\n    const char* line;\n} print_args_t;\n\nint print_line(printer_t *printer, const char* line) {\n    print_args_t args;\n    args.printer = printer;\n    args.line = line;\n    return enter_rendezvous(&printer->rv, &args);\n}\n\nint accept_print(void* data) {\n    \n    print_args_t *args = (print_args_t*)data;\n    printer_t *printer = args->printer;\n    const char* line = args->line;\n\n    if (printer->remaining_lines) {\n        \n        printf(\"%d: \", printer->id);\n        while (*line != '\\0') {\n            putchar(*line++);\n        }\n        putchar('\\n');\n        printer->remaining_lines--;\n        return 1;\n    }\n    else if (printer->backup) {\n        \n        return print_line(printer->backup, line);\n    }\n    else {\n        \n        return -1;\n    }\n}\n\nprinter_t backup_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = NULL,\n    .id = 2,\n    .remaining_lines = 5,\n};\n\nprinter_t main_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = &backup_printer,\n    .id = 1,\n    .remaining_lines = 5,\n};\n\nvoid* printer_thread(void* thread_data) {\n    printer_t *printer = (printer_t*) thread_data;\n    while (1) {\n        accept_rendezvous(&printer->rv);\n    }\n}\n\ntypedef struct poem {\n    char* name;\n    char* lines[];\n} poem_t;\n\npoem_t humpty_dumpty = {\n    .name = \"Humpty Dumpty\",\n    .lines = {\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men\",\n        \"Couldn't put Humpty together again.\",\n        \"\"\n    },\n};\n\npoem_t mother_goose = {\n    .name = \"Mother Goose\",\n    .lines = {\n        \"Old Mother Goose\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n        \"\"\n    },\n};\n\nvoid* poem_thread(void* thread_data) {\n    poem_t *poem = (poem_t*)thread_data;\n\n    for (unsigned i = 0; poem->lines[i] != \"\"; i++) {\n        int ret = print_line(&main_printer, poem->lines[i]);\n        if (ret < 0) {\n            printf(\"      %s out of ink!\\n\", poem->name);\n            exit(1);\n        }\n    }\n    return NULL;\n}\n\nint main(void)\n{\n    pthread_t threads[4];\n\n    pthread_create(&threads[0], NULL, poem_thread,    &humpty_dumpty);\n    pthread_create(&threads[1], NULL, poem_thread,    &mother_goose);\n    pthread_create(&threads[2], NULL, printer_thread, &main_printer);\n    pthread_create(&threads[3], NULL, printer_thread, &backup_printer);\n\n    pthread_join(threads[0], NULL);\n    pthread_join(threads[1], NULL);\n    pthread_cancel(threads[2]);\n    pthread_cancel(threads[3]);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n    \"sync\"\n)\n\nvar hdText = `Humpty Dumpty sat on a wall.\nHumpty Dumpty had a great fall.\nAll the king's horses and all the king's men,\nCouldn't put Humpty together again.`\n\nvar mgText = `Old Mother Goose,\nWhen she wanted to wander,\nWould ride through the air,\nOn a very fine gander.\nJack's mother came in,\nAnd caught the goose soon,\nAnd mounting its back,\nFlew up to the moon.`\n\nfunc main() {\n    reservePrinter := startMonitor(newPrinter(5), nil)\n    mainPrinter := startMonitor(newPrinter(5), reservePrinter)\n    var busy sync.WaitGroup\n    busy.Add(2)\n    go writer(mainPrinter, \"hd\", hdText, &busy)\n    go writer(mainPrinter, \"mg\", mgText, &busy)\n    busy.Wait()\n}\n\n\n\n\ntype printer func(string) error\n\n\n\n\n\nfunc newPrinter(ink int) printer {\n    return func(line string) error {\n        if ink == 0 {\n            return eOutOfInk\n        }\n        for _, c := range line {\n            fmt.Printf(\"%c\", c)\n        }\n        fmt.Println()\n        ink--\n        return nil\n    }\n}\n\nvar eOutOfInk = errors.New(\"out of ink\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype rSync struct {\n    call     chan string\n    response chan error\n}\n\n\n\n\n\n\nfunc (r *rSync) print(data string) error {\n    r.call <- data      \n    return <-r.response \n}\n\n\n\n\nfunc monitor(hardPrint printer, entry, reserve *rSync) {\n    for {\n        \n        \n        data := <-entry.call\n        \n        \n        \n\n        \n        switch err := hardPrint(data); {\n\n        \n        case err == nil:\n            entry.response <- nil \n\n        case err == eOutOfInk && reserve != nil:\n            \n            \n            \n            \n            entry.response <- reserve.print(data)\n\n        default:\n            entry.response <- err \n        }\n        \n    }\n}\n\n\n\n\n\n\nfunc startMonitor(p printer, reservePrinter *rSync) *rSync {\n    entry := &rSync{make(chan string), make(chan error)}\n    go monitor(p, entry, reservePrinter)\n    return entry\n}\n\n\n\n\n\n\nfunc writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {\n    for _, line := range strings.Split(text, \"\\n\") {\n        if err := printMonitor.print(line); err != nil {\n            fmt.Printf(\"**** writer task %q terminated: %v ****\\n\", id, err)\n            break\n        }\n    }\n    busy.Done()\n}\n"}
{"id": 53168, "name": "Primes whose first and last number is 3", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main(void) {\n    int np = 1, d, i, n;\n    printf( \"3  \" );\n    for(d=1; d<6; d++) {\n        for(i=3; i<pow(10,d)-1; i+=10) {\n            n = i + 3*pow(10,d);\n            if(isprime(n)) {\n                ++np;\n                if(n<4009) {\n                    printf(\"%d  \",n);\n                    if(!(np%10)) printf(\"\\n\");\n                }\n            }\n        }\n    }\n    printf( \"\\n\\nThere were %d primes of the form 3x3 below one million.\\n\", np );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var primes []int\n    candidates := []int{3, 33}\n    for i := 303; i <= 393; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for i := 3003; i <= 3993; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for _, cand := range candidates {\n        if rcu.IsPrime(cand) {\n            primes = append(primes, cand)\n        }\n    }\n    fmt.Println(\"Primes under 4,000 which begin and end in 3:\")\n    for i, p := range primes {\n        fmt.Printf(\"%5s \", rcu.Commatize(p))\n        if (i+1)%11 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(primes), \"Such primes.\")\n    pc := len(primes)\n    for i := 30003; i <= 39993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    for i := 300003; i <= 399993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    pcc := rcu.Commatize(pc)\n    fmt.Println(\"\\nFound\", pcc, \"primes under 1,000,000 which begin and end with 3.\")\n}\n"}
{"id": 53169, "name": "Primes whose first and last number is 3", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main(void) {\n    int np = 1, d, i, n;\n    printf( \"3  \" );\n    for(d=1; d<6; d++) {\n        for(i=3; i<pow(10,d)-1; i+=10) {\n            n = i + 3*pow(10,d);\n            if(isprime(n)) {\n                ++np;\n                if(n<4009) {\n                    printf(\"%d  \",n);\n                    if(!(np%10)) printf(\"\\n\");\n                }\n            }\n        }\n    }\n    printf( \"\\n\\nThere were %d primes of the form 3x3 below one million.\\n\", np );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var primes []int\n    candidates := []int{3, 33}\n    for i := 303; i <= 393; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for i := 3003; i <= 3993; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for _, cand := range candidates {\n        if rcu.IsPrime(cand) {\n            primes = append(primes, cand)\n        }\n    }\n    fmt.Println(\"Primes under 4,000 which begin and end in 3:\")\n    for i, p := range primes {\n        fmt.Printf(\"%5s \", rcu.Commatize(p))\n        if (i+1)%11 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(primes), \"Such primes.\")\n    pc := len(primes)\n    for i := 30003; i <= 39993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    for i := 300003; i <= 399993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    pcc := rcu.Commatize(pc)\n    fmt.Println(\"\\nFound\", pcc, \"primes under 1,000,000 which begin and end with 3.\")\n}\n"}
{"id": 53170, "name": "Primes whose first and last number is 3", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main(void) {\n    int np = 1, d, i, n;\n    printf( \"3  \" );\n    for(d=1; d<6; d++) {\n        for(i=3; i<pow(10,d)-1; i+=10) {\n            n = i + 3*pow(10,d);\n            if(isprime(n)) {\n                ++np;\n                if(n<4009) {\n                    printf(\"%d  \",n);\n                    if(!(np%10)) printf(\"\\n\");\n                }\n            }\n        }\n    }\n    printf( \"\\n\\nThere were %d primes of the form 3x3 below one million.\\n\", np );\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var primes []int\n    candidates := []int{3, 33}\n    for i := 303; i <= 393; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for i := 3003; i <= 3993; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for _, cand := range candidates {\n        if rcu.IsPrime(cand) {\n            primes = append(primes, cand)\n        }\n    }\n    fmt.Println(\"Primes under 4,000 which begin and end in 3:\")\n    for i, p := range primes {\n        fmt.Printf(\"%5s \", rcu.Commatize(p))\n        if (i+1)%11 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(primes), \"Such primes.\")\n    pc := len(primes)\n    for i := 30003; i <= 39993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    for i := 300003; i <= 399993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    pcc := rcu.Commatize(pc)\n    fmt.Println(\"\\nFound\", pcc, \"primes under 1,000,000 which begin and end with 3.\")\n}\n"}
{"id": 53171, "name": "First class environments", "C": "#include <stdio.h>\n\n#define JOBS 12\n#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf(\"\\n\"); switch_to(++a))\ntypedef struct { int seq, cnt; } env_t;\n\nenv_t env[JOBS] = {{0, 0}};\nint *seq, *cnt;\n\nvoid hail()\n{\n\tprintf(\"% 4d\", *seq);\n\tif (*seq == 1) return;\n\t++*cnt;\n\t*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;\n}\n\nvoid switch_to(int id)\n{\n\tseq = &env[id].seq;\n\tcnt = &env[id].cnt;\n}\n\nint main()\n{\n\tint i;\n\tjobs(i) { env[i].seq = i + 1; }\n\nagain:\tjobs(i) { hail(); }\n\tjobs(i) { if (1 != *seq) goto again; }\n\n\tprintf(\"COUNTS:\\n\");\n\tjobs(i) { printf(\"% 4d\", *cnt); }\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst jobs = 12\n\ntype environment struct{ seq, cnt int }\n\nvar (\n    env      [jobs]environment\n    seq, cnt *int\n)\n\nfunc hail() {\n    fmt.Printf(\"% 4d\", *seq)\n    if *seq == 1 {\n        return\n    }\n    (*cnt)++\n    if *seq&1 != 0 {\n        *seq = 3*(*seq) + 1\n    } else {\n        *seq /= 2\n    }\n}\n\nfunc switchTo(id int) {\n    seq = &env[id].seq\n    cnt = &env[id].cnt\n}\n\nfunc main() {\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        env[i].seq = i + 1\n    }\n\nagain:\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        hail()\n    }\n    fmt.Println()\n\n    for j := 0; j < jobs; j++ {\n        switchTo(j)\n        if *seq != 1 {\n            goto again\n        }\n    }\n    fmt.Println()\n\n    fmt.Println(\"COUNTS:\")\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        fmt.Printf(\"% 4d\", *cnt)\n    }\n    fmt.Println()\n}\n"}
{"id": 53172, "name": "UTF-8 encode and decode", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n"}
{"id": 53173, "name": "Xiaolin Wu's line algorithm", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Go": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n    return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n    return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n    return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n    return 1 - fpart(x)\n}\n\n\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n    \n    dx := x2 - x1\n    dy := y2 - y1\n    ax := dx\n    if ax < 0 {\n        ax = -ax\n    }\n    ay := dy\n    if ay < 0 {\n        ay = -ay\n    }\n    \n    var plot func(int, int, float64)\n    if ax < ay {\n        x1, y1 = y1, x1\n        x2, y2 = y2, x2\n        dx, dy = dy, dx\n        plot = func(x, y int, c float64) {\n            g.SetPx(y, x, uint16(c*math.MaxUint16))\n        }\n    } else {\n        plot = func(x, y int, c float64) {\n            g.SetPx(x, y, uint16(c*math.MaxUint16))\n        }\n    }\n    if x2 < x1 {\n        x1, x2 = x2, x1\n        y1, y2 = y2, y1\n    }\n    gradient := dy / dx\n\n    \n    xend := round(x1)\n    yend := y1 + gradient*(xend-x1)\n    xgap := rfpart(x1 + .5)\n    xpxl1 := int(xend) \n    ypxl1 := int(ipart(yend))\n    plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n    intery := yend + gradient \n\n    \n    xend = round(x2)\n    yend = y2 + gradient*(xend-x2)\n    xgap = fpart(x2 + 0.5)\n    xpxl2 := int(xend) \n    ypxl2 := int(ipart(yend))\n    plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n    \n    for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n        plot(x, int(ipart(intery)), rfpart(intery))\n        plot(x, int(ipart(intery))+1, fpart(intery))\n        intery = intery + gradient\n    }\n}\n"}
{"id": 53174, "name": "Keyboard macros", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/keysym.h>\n\nint main()\n{\n  Display *d;\n  XEvent event;\n  \n  d = XOpenDisplay(NULL);\n  if ( d != NULL ) {\n                \n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), \n\t     Mod1Mask,  \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), \n\t     Mod1Mask, \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n\n    for(;;)\n    {\n      XNextEvent(d, &event);\n      if ( event.type == KeyPress ) {\n\tKeySym s = XLookupKeysym(&event.xkey, 0);\n\tif ( s == XK_F7 ) {\n\t  printf(\"something's happened\\n\");\n\t} else if ( s == XK_F6 ) {\n\t  break;\n\t}\n      }\n    }\n\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), Mod1Mask, DefaultRootWindow(d));\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), Mod1Mask, DefaultRootWindow(d));\n  }\n  return EXIT_SUCCESS;\n}\n", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"unsafe\"\n\nfunc main() {\n    d := C.XOpenDisplay(nil)\n    f7, f6 := C.CString(\"F7\"), C.CString(\"F6\")\n    defer C.free(unsafe.Pointer(f7))\n    defer C.free(unsafe.Pointer(f6))\n\n    if d != nil {\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),\n            C.Mod1Mask, \n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),\n            C.Mod1Mask,\n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n\n        var event C.XEvent\n        for {\n            C.XNextEvent(d, &event)\n            if C.getXEvent_type(event) == C.KeyPress {\n                xkeyEvent := C.getXEvent_xkey(event)\n                s := C.XLookupKeysym(&xkeyEvent, 0)\n                if s == C.XK_F7 {\n                    fmt.Println(\"something's happened\")\n                } else if s == C.XK_F6 {\n                    break\n                }\n            }\n        }\n\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n    } else {\n        fmt.Println(\"XOpenDisplay did not succeed\")\n    }\n}\n"}
{"id": 53175, "name": "McNuggets problem", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n    sv := make([]bool, limit+1) \n    for s := 0; s <= limit; s += 6 {\n        for n := s; n <= limit; n += 9 {\n            for t := n; t <= limit; t += 20 {\n                sv[t] = true\n            }\n        }\n    }\n    for i := limit; i >= 0; i-- {\n        if !sv[i] {\n            fmt.Println(\"Maximum non-McNuggets number is\", i)\n            return\n        }\n    }\n}\n\nfunc main() {\n    mcnugget(100)\n}\n"}
{"id": 53176, "name": "Magic squares of doubly even order", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 53177, "name": "Extreme floating point values", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 53178, "name": "Extreme floating point values", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 53179, "name": "Pseudo-random numbers_Xorshift star", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 53180, "name": "Four is the number of letters in the ...", "C": "#include <ctype.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\ntypedef struct word_tag {\n    size_t offset;\n    size_t length;\n} word_t;\n\ntypedef struct word_list_tag {\n    GArray* words;\n    GString* str;\n} word_list;\n\nvoid word_list_create(word_list* words) {\n    words->words = g_array_new(FALSE, FALSE, sizeof(word_t));\n    words->str = g_string_new(NULL);\n}\n\nvoid word_list_destroy(word_list* words) {\n    g_string_free(words->str, TRUE);\n    g_array_free(words->words, TRUE);\n}\n\nvoid word_list_clear(word_list* words) {\n    g_string_truncate(words->str, 0);\n    g_array_set_size(words->words, 0);\n}\n\nvoid word_list_append(word_list* words, const char* str) {\n    size_t offset = words->str->len;\n    size_t len = strlen(str);\n    g_string_append_len(words->str, str, len);\n    word_t word;\n    word.offset = offset;\n    word.length = len;\n    g_array_append_val(words->words, word);\n}\n\nword_t* word_list_get(word_list* words, size_t index) {\n    return &g_array_index(words->words, word_t, index);\n}\n\nvoid word_list_extend(word_list* words, const char* str) {\n    word_t* word = word_list_get(words, words->words->len - 1);\n    size_t len = strlen(str);\n    word->length += len;\n    g_string_append_len(words->str, str, len);\n}\n\nsize_t append_number_name(word_list* words, integer n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        word_list_append(words, get_small_name(&small[n], ordinal));\n        count = 1;\n    } else if (n < 100) {\n        if (n % 10 == 0) {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], false));\n            word_list_extend(words, \"-\");\n            word_list_extend(words, get_small_name(&small[n % 10], ordinal));\n        }\n        count = 1;\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        count += append_number_name(words, n/p, false);\n        if (n % p == 0) {\n            word_list_append(words, get_big_name(num, ordinal));\n            ++count;\n        } else {\n            word_list_append(words, get_big_name(num, false));\n            ++count;\n            count += append_number_name(words, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(word_list* words, size_t index) {\n    const word_t* word = word_list_get(words, index);\n    size_t letters = 0;\n    const char* s = words->str->str + word->offset;\n    for (size_t i = 0, n = word->length; i < n; ++i) {\n        if (isalpha((unsigned char)s[i]))\n            ++letters;\n    }\n    return letters;\n}\n\nvoid sentence(word_list* result, size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    word_list_clear(result);\n    size_t n = sizeof(words)/sizeof(words[0]);\n    for (size_t i = 0; i < n; ++i)\n        word_list_append(result, words[i]);\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result, i), false);\n        word_list_append(result, \"in\");\n        word_list_append(result, \"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        \n        word_list_extend(result, \",\");\n    }\n}\n\nsize_t sentence_length(const word_list* words) {\n    size_t n = words->words->len;\n    if (n == 0)\n        return 0;\n    return words->str->len + n - 1;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    size_t n = 201;\n    word_list result = { 0 };\n    word_list_create(&result);\n    sentence(&result, n);\n    printf(\"Number of letters in first %'lu words in the sequence:\\n\", n);\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            printf(\"%c\", i % 25 == 0 ? '\\n' : ' ');\n        printf(\"%'2lu\", count_letters(&result, i));\n    }\n    printf(\"\\nSentence length: %'lu\\n\", sentence_length(&result));\n    for (n = 1000; n <= 10000000; n *= 10) {\n        sentence(&result, n);\n        const word_t* word = word_list_get(&result, n - 1);\n        const char* s = result.str->str + word->offset;\n        printf(\"The %'luth word is '%.*s' and has %lu letters. \", n,\n               (int)word->length, s, count_letters(&result, n - 1));\n        printf(\"Sentence length: %'lu\\n\" , sentence_length(&result));\n    }\n    word_list_destroy(&result);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n"}
{"id": 53181, "name": "Calendar - for _REAL_ programmers", "C": "\n\n\n\n\n\nINT PUTCHAR(INT);\n\nINT WIDTH = 80, YEAR = 1969;\nINT COLS, LEAD, GAP;\n \nCONST CHAR *WDAYS[] = { \"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\" };\nSTRUCT MONTHS {\n    CONST CHAR *NAME;\n    INT DAYS, START_WDAY, AT;\n} MONTHS[12] = {\n    { \"JANUARY\",    31, 0, 0 },\n    { \"FEBRUARY\",    28, 0, 0 },\n    { \"MARCH\",    31, 0, 0 },\n    { \"APRIL\",    30, 0, 0 },\n    { \"MAY\",    31, 0, 0 },\n    { \"JUNE\",    30, 0, 0 },\n    { \"JULY\",    31, 0, 0 },\n    { \"AUGUST\",    31, 0, 0 },\n    { \"SEPTEMBER\",    30, 0, 0 },\n    { \"OCTOBER\",    31, 0, 0 },\n    { \"NOVEMBER\",    30, 0, 0 },\n    { \"DECEMBER\",    31, 0, 0 }\n};\n \nVOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }\nVOID PRINT(CONST CHAR * S){ WHILE (*S != '\\0') { PUTCHAR(*S++); } }\nINT  STRLEN(CONST CHAR * S)\n{\n   INT L = 0;\n   WHILE (*S++ != '\\0') { L ++; };\nRETURN L;\n}\nINT ATOI(CONST CHAR * S)\n{\n    INT I = 0;\n    INT SIGN = 1;\n    CHAR C;\n    WHILE ((C = *S++) != '\\0') {\n        IF (C == '-')\n            SIGN *= -1;\n        ELSE {\n            I *= 10;\n            I += (C - '0');\n        }\n    }\nRETURN I * SIGN;\n}\n\nVOID INIT_MONTHS(VOID)\n{\n    INT I;\n \n    IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))\n        MONTHS[1].DAYS = 29;\n \n    YEAR--;\n    MONTHS[0].START_WDAY\n        = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;\n \n    FOR (I = 1; I < 12; I++)\n        MONTHS[I].START_WDAY =\n            (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;\n \n    COLS = (WIDTH + 2) / 22;\n    WHILE (12 % COLS) COLS--;\n    GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;\n    IF (GAP > 4) GAP = 4;\n    LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;\n        YEAR++;\n}\n \nVOID PRINT_ROW(INT ROW)\n{\n    INT C, I, FROM = ROW * COLS, TO = FROM + COLS;\n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        I = STRLEN(MONTHS[C].NAME);\n        SPACE((20 - I)/2);\n        PRINT(MONTHS[C].NAME);\n        SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));\n    }\n    PUTCHAR('\\012');\n \n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        FOR (I = 0; I < 7; I++) {\n            PRINT(WDAYS[I]);\n            PRINT(I == 6 ? \"\" : \" \");\n        }\n        IF (C < TO - 1) SPACE(GAP);\n        ELSE PUTCHAR('\\012');\n    }\n \n    WHILE (1) {\n        FOR (C = FROM; C < TO; C++)\n            IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;\n        IF (C == TO) BREAK;\n \n        SPACE(LEAD);\n        FOR (C = FROM; C < TO; C++) {\n            FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);\n            WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {\n                INT MM = ++MONTHS[C].AT;\n                PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));\n                PUTCHAR('0' + (MM %10));\n                IF (I < 7 || C < TO - 1) PUTCHAR(' ');\n            }\n            WHILE (I++ <= 7 && C < TO - 1) SPACE(3);\n            IF (C < TO - 1) SPACE(GAP - 1);\n            MONTHS[C].START_WDAY = 0;\n        }\n        PUTCHAR('\\012');\n    }\n    PUTCHAR('\\012');\n}\n \nVOID PRINT_YEAR(VOID)\n{\n    INT Y = YEAR;\n    INT ROW;\n    CHAR BUF[32];\n    CHAR * B = &(BUF[31]);\n    *B-- = '\\0';\n    DO {\n        *B-- = '0' + (Y % 10);\n        Y /= 10;\n    } WHILE (Y > 0);\n    B++;\n    SPACE((WIDTH - STRLEN(B)) / 2);\n    PRINT(B);PUTCHAR('\\012');PUTCHAR('\\012');\n    FOR (ROW = 0; ROW * COLS < 12; ROW++)\n        PRINT_ROW(ROW);\n}\n \nINT MAIN(INT C, CHAR **V)\n{\n    INT I, YEAR_SET = 0, RESULT = 0;\n    FOR (I = 1; I < C && RESULT == 0; I++) {\n        IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\\0') {\n            IF (++I == C || (WIDTH = ATOI(V[I])) < 20)\n                RESULT = 1;\n        } ELSE IF (!YEAR_SET) {\n            YEAR = ATOI(V[I]);\n            IF (YEAR <= 0)\n                YEAR = 1969;\n            YEAR_SET = 1;\n        } ELSE\n            RESULT = 1;\n    }\n \n    IF (RESULT == 0) {\n        INIT_MONTHS();\n        PRINT_YEAR();\n    } ELSE {\n        PRINT(\"BAD ARGS\\012USAGE: \");\n        PRINT(V[0]);\n        PRINT(\" YEAR [-W WIDTH (>= 20)]\\012\");\n    }\nRETURN RESULT;\n}\n", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n"}
{"id": 53182, "name": "ASCII art diagram converter", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n"}
{"id": 53183, "name": "Levenshtein distance_Alignment", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"github.com/biogo/biogo/align\"\n    ab \"github.com/biogo/biogo/alphabet\"\n    \"github.com/biogo/biogo/feat\"\n    \"github.com/biogo/biogo/seq/linear\"\n)\n\nfunc main() {\n    \n    \n    lc := ab.Must(ab.NewAlphabet(\"-abcdefghijklmnopqrstuvwxyz\",\n        feat.Undefined, '-', 0, true))\n    \n    \n    \n    \n    nw := make(align.NW, lc.Len())\n    for i := range nw {\n        r := make([]int, lc.Len())\n        nw[i] = r\n        for j := range r {\n            if j != i {\n                r[j] = -1\n            }\n        }\n    }\n    \n    a := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"rosettacode\"))}\n    a.Alpha = lc\n    b := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"raisethysword\"))}\n    b.Alpha = lc\n    \n    aln, err := nw.Align(a, b)\n    \n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fa := align.Format(a, b, aln, '-')\n    fmt.Printf(\"%s\\n%s\\n\", fa[0], fa[1])\n    aa := fmt.Sprint(fa[0])\n    ba := fmt.Sprint(fa[1])\n    ma := make([]byte, len(aa))\n    for i := range ma {\n        if aa[i] == ba[i] {\n            ma[i] = ' '\n        } else {\n            ma[i] = '|'\n        }\n    }\n    fmt.Println(string(ma))\n}\n"}
{"id": 53184, "name": "Compare sorting algorithms' performance", "C": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"math/rand\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/gonum/plot\"\n    \"github.com/gonum/plot/plotter\"\n    \"github.com/gonum/plot/plotutil\"\n    \"github.com/gonum/plot/vg\"\n)\n\n\n\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\nfunc insertionsort(a []int) {\n    for i := 1; i < len(a); i++ {\n        value := a[i]\n        j := i - 1\n        for j >= 0 && a[j] > value {\n            a[j+1] = a[j]\n            j = j - 1\n        }\n        a[j+1] = value\n    }\n}\n\nfunc quicksort(a []int) {\n    var pex func(int, int)\n    pex = func(lower, upper int) {\n        for {\n            switch upper - lower {\n            case -1, 0:\n                return\n            case 1:\n                if a[upper] < a[lower] {\n                    a[upper], a[lower] = a[lower], a[upper]\n                }\n                return\n            }\n            bx := (upper + lower) / 2\n            b := a[bx]\n            lp := lower\n            up := upper\n        outer:\n            for {\n                for lp < upper && !(b < a[lp]) {\n                    lp++\n                }\n                for {\n                    if lp > up {\n                        break outer\n                    }\n                    if a[up] < b {\n                        break\n                    }\n                    up--\n                }\n                a[lp], a[up] = a[up], a[lp]\n                lp++\n                up--\n            }\n            if bx < lp {\n                if bx < lp-1 {\n                    a[bx], a[lp-1] = a[lp-1], b\n                }\n                up = lp - 2\n            } else {\n                if bx > lp {\n                    a[bx], a[lp] = a[lp], b\n                }\n                up = lp - 1\n                lp++\n            }\n            if up-lower < upper-lp {\n                pex(lower, up)\n                lower = lp\n            } else {\n                pex(lp, upper)\n                upper = up\n            }\n        }\n    }\n    pex(0, len(a)-1)\n}\n\n\n\nfunc ones(n int) []int {\n    s := make([]int, n)\n    for i := range s {\n        s[i] = 1\n    }\n    return s\n}\n\nfunc ascending(n int) []int {\n    s := make([]int, n)\n    v := 1\n    for i := 0; i < n; {\n        if rand.Intn(3) == 0 {\n            s[i] = v\n            i++\n        }\n        v++\n    }\n    return s\n}\n\nfunc shuffled(n int) []int {\n    return rand.Perm(n)\n}\n\n\n\n\n\n\nconst (\n    nPts = 7    \n    inc  = 1000 \n)\n\nvar (\n    p        *plot.Plot\n    sortName = []string{\"Bubble sort\", \"Insertion sort\", \"Quicksort\"}\n    sortFunc = []func([]int){bubblesort, insertionsort, quicksort}\n    dataName = []string{\"Ones\", \"Ascending\", \"Shuffled\"}\n    dataFunc = []func(int) []int{ones, ascending, shuffled}\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    var err error\n    p, err = plot.New()\n    if err != nil {\n        log.Fatal(err)\n    }\n    p.X.Label.Text = \"Data size\"\n    p.Y.Label.Text = \"microseconds\"\n    p.Y.Scale = plot.LogScale{}\n    p.Y.Tick.Marker = plot.LogTicks{}\n    p.Y.Min = .5 \n\n    for dx, name := range dataName {\n        s, err := plotter.NewScatter(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        s.Shape = plotutil.DefaultGlyphShapes[dx]\n        p.Legend.Add(name, s)\n    }\n    for sx, name := range sortName {\n        l, err := plotter.NewLine(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        l.Color = plotutil.DarkColors[sx]\n        p.Legend.Add(name, l)\n    }\n    for sx := range sortFunc {\n        bench(sx, 0, 1) \n        bench(sx, 1, 5) \n        bench(sx, 2, 5) \n    }\n\n    if err := p.Save(5*vg.Inch, 5*vg.Inch, \"comp.png\"); err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc bench(sx, dx, rep int) {\n    log.Println(\"bench\", sortName[sx], dataName[dx], \"x\", rep)\n    pts := make(plotter.XYs, nPts)\n    sf := sortFunc[sx]\n    for i := range pts {\n        x := (i + 1) * inc\n        \n        \n        \n        s0 := dataFunc[dx](x) \n        s := make([]int, x)   \n        var tSort int64\n        for j := 0; j < rep; j++ {\n            tSort += testing.Benchmark(func(b *testing.B) {\n                for i := 0; i < b.N; i++ {\n                    copy(s, s0)\n                    sf(s)\n                }\n            }).NsPerOp()\n        }\n        tSort /= int64(rep)\n        log.Println(x, \"items\", tSort, \"ns\") \n        pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001}\n    }\n    pl, ps, err := plotter.NewLinePoints(pts) \n    if err != nil {\n        log.Fatal(err)\n    }\n    pl.Color = plotutil.DarkColors[sx]\n    ps.Color = plotutil.DarkColors[sx]\n    ps.Shape = plotutil.DefaultGlyphShapes[dx]\n    p.Add(pl, ps)\n}\n"}
{"id": 53185, "name": "Same fringe", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n"}
{"id": 53186, "name": "Parse command-line arguments", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n"}
{"id": 53187, "name": "Parse command-line arguments", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n"}
{"id": 53188, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n"}
{"id": 53189, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n"}
{"id": 53190, "name": "Simulate input_Keyboard", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n\nint main(int argc, char *argv[])\n{\n  Display *dpy;\n  Window win;\n  GC gc;\n  int scr;\n  Atom WM_DELETE_WINDOW;\n  XEvent ev;\n  XEvent ev2;\n  KeySym keysym;\n  int loop;\n\n  \n  dpy = XOpenDisplay(NULL);\n  if (dpy == NULL) {\n    fputs(\"Cannot open display\", stderr);\n    exit(1);\n  }\n  scr = XDefaultScreen(dpy);\n\n  \n  win = XCreateSimpleWindow(dpy,\n          XRootWindow(dpy, scr),\n          \n          10, 10, 300, 200, 1,\n          \n          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));\n\n  \n  XStoreName(dpy, win, argv[0]);\n\n  \n  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);\n\n  \n  XMapWindow(dpy, win);\n  XFlush(dpy);\n\n  \n  gc = XDefaultGC(dpy, scr);\n\n  \n  WM_DELETE_WINDOW = XInternAtom(dpy, \"WM_DELETE_WINDOW\", True);\n  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);\n\n  \n  loop = 1;\n  while (loop) {\n    XNextEvent(dpy, &ev);\n    switch (ev.type)\n    {\n      case Expose:\n        \n        {\n          char msg1[] = \"Clic in the window to generate\";\n          char msg2[] = \"a key press event\";\n          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);\n          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);\n        }\n        break;\n\n      case ButtonPress:\n        puts(\"ButtonPress event received\");\n        \n        ev2.type = KeyPress;\n        ev2.xkey.state = ShiftMask;\n        ev2.xkey.keycode = 24 + (rand() % 33);\n        ev2.xkey.same_screen = True;\n        XSendEvent(dpy, win, True, KeyPressMask, &ev2);\n        break;\n   \n      case ClientMessage:\n        \n        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)\n          loop = 0;\n        break;\n   \n      case KeyPress:\n        \n        puts(\"KeyPress event received\");\n        printf(\"> keycode: %d\\n\", ev.xkey.keycode);\n        \n        keysym = XLookupKeysym(&(ev.xkey), 0);\n        if (keysym == XK_q ||\n            keysym == XK_Escape) {\n          loop = 0;\n        } else {\n          char buffer[] = \"  \";\n          int nchars = XLookupString(\n                &(ev.xkey),\n                buffer,\n                2,  \n                &keysym,\n                NULL );\n          if (nchars == 1)\n            printf(\"> Key '%c' pressed\\n\", buffer[0]);\n        }\n        break;\n    }\n  }\n  XDestroyWindow(dpy, win);\n  \n  XCloseDisplay(dpy);\n  return 1;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/micmonay/keybd_event\"\n    \"log\"\n    \"runtime\"\n    \"time\"\n)\n\nfunc main() {\n    kb, err := keybd_event.NewKeyBonding()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    if runtime.GOOS == \"linux\" {\n        time.Sleep(2 * time.Second)\n    }\n\n    \n    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)\n\n    \n    err = kb.Launching()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53191, "name": "Peaceful chess queen armies", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n"}
{"id": 53192, "name": "Loops_Infinite", "C": "while(1) puts(\"SPAM\");\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 53193, "name": "Metaprogramming", "C": "\n#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]\n\n#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)\n#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)\n#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)\n\nCOMPILE_TIME_ASSERT(sizeof(long)==8); \nint main()\n{\n    COMPILE_TIME_ASSERT(sizeof(int)==4); \n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype person struct{\n    name string\n    age int\n}\n\nfunc copy(p person) person {\n    return person{p.name, p.age}\n}\n\nfunc main() {\n    p := person{\"Dave\", 40}\n    fmt.Println(p)\n    q := copy(p)\n    fmt.Println(q)\n     \n}\n"}
{"id": 53194, "name": "Numbers with same digit set in base 10 and base 16", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n"}
{"id": 53195, "name": "Largest prime factor", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( long int n ) {\n    int i=3;\n    if(!(n%2)) return 0;\n    while( i*i < n ) {\n        if(!(n%i)) return 0;\n        i+=2;\n    }\n    return 1;\n}\n\nint main(void) {\n    long int n=600851475143, j=3;\n\n    while(!isprime(n)) {\n        if(!(n%j)) n/=j;\n        j+=2;\n    }\n    printf( \"%ld\\n\", n );\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestPrimeFactor(n uint64) uint64 {\n    if n < 2 {\n        return 1\n    }\n    inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}\n    max := uint64(1)\n    for n%2 == 0 {\n        max = 2\n        n /= 2\n    }\n    for n%3 == 0 {\n        max = 3\n        n /= 3\n    }\n    for n%5 == 0 {\n        max = 5\n        n /= 5\n    }\n    k := uint64(7)\n    i := 0\n    for k*k <= n {\n        if n%k == 0 {\n            max = k\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        return n\n    }\n    return max\n}\n\nfunc main() {\n    n := uint64(600851475143)\n    fmt.Println(\"The largest prime factor of\", n, \"is\", largestPrimeFactor(n), \"\\b.\")\n}\n"}
{"id": 53196, "name": "Largest proper divisor of n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            return n / i\n        }\n    }\n    return 1\n}\n\nfunc main() {\n    fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n    fmt.Print(\" 1  \")\n    for n := 2; n <= 100; n++ {\n        if n%2 == 0 {\n            fmt.Printf(\"%2d  \", n/2)\n        } else {\n            fmt.Printf(\"%2d  \", largestProperDivisor(n))\n        }\n        if n%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 53197, "name": "Three word location", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef long long int64;\n \nvoid to_word(char *ws, int64 w) {\n    sprintf(ws, \"W%05lld\", w);\n}\n\nint64 from_word(char *ws) {\n    return atoi(++ws);\n}\n\nint main() {\n    double lat, lon;\n    int64 latlon, ilat, ilon, w1, w2, w3;\n    char w1s[7], w2s[7], w3s[7];\n    printf(\"Starting figures:\\n\");\n    lat = 28.3852;\n    lon = -81.5638;\n    printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon);\n \n    \n    ilat = (int64)(lat*10000 + 900000);\n    ilon = (int64)(lon*10000 + 1800000);\n \n    \n    latlon = (ilat << 22) + ilon;\n\n    \n    w1 = (latlon >> 28) & 0x7fff;\n    w2 = (latlon >> 14) & 0x3fff;\n    w3 = latlon & 0x3fff;\n\n    \n    to_word(w1s, w1);\n    to_word(w2s, w2);\n    to_word(w3s, w3);\n \n    \n    printf(\"\\nThree word location is:\\n\");\n    printf(\"  %s %s %s\\n\", w1s, w2s, w3s);\n\n    \n    w1 = from_word(w1s);\n    w2 = from_word(w2s);\n    w3 = from_word(w3s);\n\n    latlon = (w1 << 28) | (w2 << 14) | w3;\n    ilat = latlon >> 22;\n    ilon = latlon & 0x3fffff;\n    lat = (double)(ilat-900000) / 10000;\n    lon = (double)(ilon-1800000) / 10000;\n\n    \n    printf(\"\\nAfter reversing the procedure:\\n\");\n    printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc toWord(w int64) string { return fmt.Sprintf(\"W%05d\", w) }\n\nfunc fromWord(ws string) int64 {\n    var u, _ = strconv.ParseUint(ws[1:], 10, 64)\n    return int64(u)\n}\n\nfunc main() {\n    fmt.Println(\"Starting figures:\")\n    lat := 28.3852\n    lon := -81.5638\n    fmt.Printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon)\n\n    \n    ilat := int64(lat*10000 + 900000)\n    ilon := int64(lon*10000 + 1800000)\n\n    \n    latlon := (ilat << 22) + ilon\n\n    \n    w1 := (latlon >> 28) & 0x7fff\n    w2 := (latlon >> 14) & 0x3fff\n    w3 := latlon & 0x3fff\n\n    \n    w1s := toWord(w1)\n    w2s := toWord(w2)\n    w3s := toWord(w3)\n\n    \n    fmt.Println(\"\\nThree word location is:\")\n    fmt.Printf(\"  %s %s %s\\n\", w1s, w2s, w3s)\n\n    \n    w1 = fromWord(w1s)\n    w2 = fromWord(w2s)\n    w3 = fromWord(w3s)\n\n    latlon = (w1 << 28) | (w2 << 14) | w3\n    ilat = latlon >> 22\n    ilon = latlon & 0x3fffff\n    lat = float64(ilat-900000) / 10000\n    lon = float64(ilon-1800000) / 10000\n\n    \n    fmt.Println(\"\\nAfter reversing the procedure:\")\n    fmt.Printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon)\n}\n"}
{"id": 53198, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 53199, "name": "Active Directory_Search for a user", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n"}
{"id": 53200, "name": "Singular value decomposition", "C": "#include <stdio.h>\n#include <gsl/gsl_linalg.h>\n\n\nvoid gsl_matrix_print(const gsl_matrix *M) {\n    int rows = M->size1;\n    int cols = M->size2;\n    for (int i = 0; i < rows; i++) {\n        printf(\"|\");\n        for (int j = 0; j < cols; j++) {\n            printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n        }\n        printf(\"\\b|\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main(){\n    double a[] = {3, 0, 4, 5};\n    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n    gsl_matrix *V = gsl_matrix_alloc(2, 2);\n    gsl_vector *S = gsl_vector_alloc(2);\n    gsl_vector *work = gsl_vector_alloc(2);\n\n    \n    gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n    gsl_matrix_transpose(V);\n    double s[] = {S->data[0], 0, 0, S->data[1]};\n    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n    printf(\"U:\\n\");\n    gsl_matrix_print(&A.matrix);\n\n    printf(\"S:\\n\");\n    gsl_matrix_print(&SM.matrix);\n\n    printf(\"VT:\\n\");\n    gsl_matrix_print(V);\n    \n    gsl_matrix_free(V);\n    gsl_vector_free(S);\n    gsl_vector_free(work);\n    return 0;\n}\n", "Go": "<package main\n\nimport (\n    \"fmt\"\n    \"gonum.org/v1/gonum/mat\"\n    \"log\"\n)\n\nfunc matPrint(m mat.Matrix) {\n    fa := mat.Formatted(m, mat.Prefix(\"\"), mat.Squeeze())\n    fmt.Printf(\"%13.10f\\n\", fa)\n}\n\nfunc main() {\n    var svd mat.SVD\n    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})\n    ok := svd.Factorize(a, mat.SVDFull)\n    if !ok {\n        log.Fatal(\"Something went wrong!\")\n    }\n    u := mat.NewDense(2, 2, nil)\n    svd.UTo(u)\n    fmt.Println(\"U:\")\n    matPrint(u)\n    values := svd.Values(nil)\n    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})\n    fmt.Println(\"\\nΣ:\")\n    matPrint(sigma)\n    vt := mat.NewDense(2, 2, nil)\n    svd.VTo(vt)\n    fmt.Println(\"\\nVT:\")\n    matPrint(vt)\n}\n"}
{"id": 53201, "name": "Sum of first n cubes", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n"}
{"id": 53202, "name": "IPC via named pipe", "C": "#include <stdio.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <limits.h>\n#include <pthread.h>\n\n\n\n#define WILL_BLOCK_EVERYTHING\t0\n\n#if WILL_BLOCK_EVERYTHING\n#include <poll.h>\n#endif\n\nsize_t tally = 0;\n\nvoid* write_loop(void *a)\n{\n\tint fd;\n\tchar buf[32];\n\twhile (1) {\n#if WILL_BLOCK_EVERYTHING\n\t\t\n\t\tfd = open(\"out\", O_WRONLY|O_NONBLOCK);\n\t\tif (fd < 0) { \n\t\t\tusleep(200000);\n\t\t\tcontinue;\n\t\t}\n#else\n\t\t\n\t\tfd = open(\"out\", O_WRONLY);\n#endif\n\t\twrite(fd, buf, snprintf(buf, 32, \"%d\\n\", tally));\n\t\tclose(fd);\n\n\t\t\n\t\tusleep(10000);\n\t}\n}\n\nvoid read_loop()\n{\n\tint fd;\n\tsize_t len;\n\tchar buf[PIPE_BUF];\n#if WILL_BLOCK_EVERYTHING\n\tstruct pollfd pfd;\n\tpfd.events = POLLIN;\n#endif\n\twhile (1) {\n#if WILL_BLOCK_EVERYTHING\n\t\tfd = pfd.fd = open(\"in\", O_RDONLY|O_NONBLOCK);\n\t\tfcntl(fd, F_SETFL, 0);  \n\t\tpoll(&pfd, 1, INFTIM);  \n#else\n\t\tfd = open(\"in\", O_RDONLY);\n#endif\n\t\twhile ((len = read(fd, buf, PIPE_BUF)) > 0) tally += len;\n\t\tclose(fd);\n\t}\n}\n\nint main()\n{\n\tpthread_t pid;\n\n\t\n\tmkfifo(\"in\", 0666);\n\tmkfifo(\"out\", 0666);\n\n\t\n\tpthread_create(&pid, 0, write_loop, 0);\n\tread_loop();\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"sync/atomic\"\n        \"syscall\"\n)\n\nconst (\n        inputFifo  = \"/tmp/in.fifo\"\n        outputFifo = \"/tmp/out.fifo\"\n        readsize   = 64 << 10\n)\n\nfunc openFifo(path string, oflag int) (f *os.File, err error) {\n        err = syscall.Mkfifo(path, 0660)\n        \n        if err != nil && !os.IsExist(err) {\n                return\n        }\n        f, err = os.OpenFile(path, oflag, 0660)\n        if err != nil {\n                return\n        }\n        \n        fi, err := f.Stat()\n        if err != nil {\n                f.Close()\n                return nil, err\n        }\n        if fi.Mode()&os.ModeType != os.ModeNamedPipe {\n                f.Close()\n                return nil, os.ErrExist\n        }\n        return\n}\n\nfunc main() {\n        var byteCount int64\n        go func() {\n                var delta int\n                var err error\n                buf := make([]byte, readsize)\n                for {\n                        input, err := openFifo(inputFifo, os.O_RDONLY)\n                        if err != nil {\n                                break\n                        }\n                        for err == nil {\n                                delta, err = input.Read(buf)\n                                atomic.AddInt64(&byteCount, int64(delta))\n                        }\n                        input.Close()\n                        if err != io.EOF {\n                                break\n                        }\n                }\n                log.Fatal(err)\n        }()\n\n        for {\n                output, err := openFifo(outputFifo, os.O_WRONLY)\n                if err != nil {\n                        log.Fatal(err)\n                }\n                cnt := atomic.LoadInt64(&byteCount)\n                fmt.Fprintln(output, cnt)\n                output.Close()\n        }\n}\n"}
{"id": 53203, "name": "Test integerness", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n"}
{"id": 53204, "name": "Execute a system command", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53205, "name": "Rodrigues’ rotation formula", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct {\n    double x, y, z;\n} vector;\n\ntypedef struct {\n    vector i, j, k;\n} matrix;\n\ndouble norm(vector v) {\n    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);\n}\n\nvector normalize(vector v){\n    double length = norm(v);\n    vector n = {v.x / length, v.y / length, v.z / length};\n    return n;\n}\n\ndouble dotProduct(vector v1, vector v2) {\n    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;\n}\n\nvector crossProduct(vector v1, vector v2) {\n    vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x};\n    return cp;\n}\n\ndouble getAngle(vector v1, vector v2) {\n    return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2)));\n}\n\nvector matrixMultiply(matrix m ,vector v) {\n    vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)};\n    return mm;\n}\n\nvector aRotate(vector p, vector v, double a) {\n    double ca = cos(a), sa = sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    matrix r = {\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}\n    };\n    return matrixMultiply(r, p);\n}\n\nint main() {\n    vector v1 = {5, -6, 4}, v2 = {8, 5, -30};\n    double a = getAngle(v1, v2);\n    vector cp = crossProduct(v1, v2);\n    vector ncp = normalize(cp);\n    vector np = aRotate(v1, ncp, a);\n    printf(\"[%.13f, %.13f, %.13f]\\n\", np.x, np.y, np.z);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector [3]float64\ntype matrix [3]vector\n\nfunc norm(v vector) float64 {\n    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])\n}\n\nfunc normalize(v vector) vector {\n    length := norm(v)\n    return vector{v[0] / length, v[1] / length, v[2] / length}\n}\n\nfunc dotProduct(v1, v2 vector) float64 {\n    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n}\n\nfunc crossProduct(v1, v2 vector) vector {\n    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}\n}\n\nfunc getAngle(v1, v2 vector) float64 {\n    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))\n}\n\nfunc matrixMultiply(m matrix, v vector) vector {\n    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}\n}\n\nfunc aRotate(p, v vector, a float64) vector {\n    ca, sa := math.Cos(a), math.Sin(a)\n    t := 1 - ca\n    x, y, z := v[0], v[1], v[2]\n    r := matrix{\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},\n    }\n    return matrixMultiply(r, p)\n}\n\nfunc main() {\n    v1 := vector{5, -6, 4}\n    v2 := vector{8, 5, -30}\n    a := getAngle(v1, v2)\n    cp := crossProduct(v1, v2)\n    ncp := normalize(cp)\n    np := aRotate(v1, ncp, a)\n    fmt.Println(np)\n}\n"}
{"id": 53206, "name": "XML validation", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 53207, "name": "Longest increasing subsequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 53208, "name": "Death Star", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": 53209, "name": "Death Star", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": 53210, "name": "Hough transform", "C": "#include \"SL_Generated.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nint main( int argc, char** argv )\n{\n    string fileName = \"Pentagon.bmp\";\n    if(argc > 1) fileName = argv[1];\n    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);\n    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);\n    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);\n    int threads = 0; if(argc > 5) threads = atoi(argv[5]);\n    char titleBuffer[200];\n    SLTimer t;\n\n    CImg<int> image(fileName.c_str());\n    int imageDimensions[] = {image.height(), image.width(), 0};\n    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);\n    Sequence< Sequence<int> > result;\n\n    sl_init(threads);\n\n    t.start();\n    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);\n    t.stop();\n    \n    CImg<int> resultImage(result[1].size(), result.size());\n    for(int y = 0; y < result.size(); y++)\n        for(int x = 0; x < result[y+1].size(); x++)\n            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];\n    \n    sprintf(titleBuffer, \"SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\\0\", \n                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());\n    resultImage.display(titleBuffer);\n\n    sl_done();\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\"\n    \"os\"\n)\n\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 53211, "name": "Verify distribution uniformity_Chi-squared test", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n"}
{"id": 53212, "name": "Verify distribution uniformity_Chi-squared test", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n"}
{"id": 53213, "name": "Topological sort_Extracted top item", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n"}
{"id": 53214, "name": "Topological sort_Extracted top item", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n"}
{"id": 53215, "name": "Brace expansion", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 53216, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 53217, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 53218, "name": "Call a function", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 53219, "name": "Superpermutation minimisation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n"}
{"id": 53220, "name": "GUI component interaction", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 53221, "name": "GUI component interaction", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 53222, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 53223, "name": "One of n lines in a file", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 53224, "name": "Summarize and say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n"}
{"id": 53225, "name": "Spelling of ordinal numbers", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": 53226, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 53227, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 53228, "name": "Addition chains", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n"}
{"id": 53229, "name": "Numeric separator syntax", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n"}
{"id": 53230, "name": "Numeric separator syntax", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n"}
{"id": 53231, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 53232, "name": "Repeat", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 53233, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n"}
{"id": 53234, "name": "Sparkline in unicode", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n"}
{"id": 53235, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 53236, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 53237, "name": "Compiler_AST interpreter", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 53238, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 53239, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 53240, "name": "Simulate input_Mouse", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n"}
{"id": 53241, "name": "Simulate input_Mouse", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n"}
{"id": 53242, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 53243, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 53244, "name": "Sunflower fractal", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n"}
{"id": 53245, "name": "Vogel's approximation method", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 53246, "name": "Air mass", "C": "#include <math.h>\n#include <stdio.h>\n\n#define DEG 0.017453292519943295769236907684886127134  \n#define RE 6371000.0 \n#define DD 0.001 \n#define FIN 10000000.0 \n\nstatic double rho(double a) {\n    \n    return exp(-a / 8500.0);\n}\n\nstatic double height(double a, double z, double d) {\n    \n    \n    \n    double aa = RE + a;\n    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));\n    return hh - RE;\n}\n\nstatic double column_density(double a, double z) {\n    \n    double sum = 0.0, d = 0.0;\n    while (d < FIN) {\n        \n        double delta = DD * d;\n        if (delta < DD)\n            delta = DD;\n        sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n        d += delta;\n    }\n    return sum;\n}\n\nstatic double airmass(double a, double z) {\n    return column_density(a, z) / column_density(a, 0.0);\n}\n\nint main() {\n    puts(\"Angle     0 m              13700 m\");\n    puts(\"------------------------------------\");\n    for (double z = 0; z <= 90; z+= 5) {\n        printf(\"%2.0f      %11.8f      %11.8f\\n\",\n               z, airmass(0.0, z), airmass(13700.0, z));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    RE  = 6371000 \n    DD  = 0.001   \n    FIN = 1e7     \n)\n\n\nfunc rho(a float64) float64 { return math.Exp(-a / 8500) }\n\n\nfunc radians(degrees float64) float64 { return degrees * math.Pi / 180 }\n\n\n\n\nfunc height(a, z, d float64) float64 {\n    aa := RE + a\n    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))\n    return hh - RE\n}\n\n\nfunc columnDensity(a, z float64) float64 {\n    sum := 0.0\n    d := 0.0\n    for d < FIN {\n        delta := math.Max(DD, DD*d) \n        sum += rho(height(a, z, d+0.5*delta)) * delta\n        d += delta\n    }\n    return sum\n}\n\nfunc airmass(a, z float64) float64 {\n    return columnDensity(a, z) / columnDensity(a, 0)\n}\n\nfunc main() {\n    fmt.Println(\"Angle     0 m              13700 m\")\n    fmt.Println(\"------------------------------------\")\n    for z := 0; z <= 90; z += 5 {\n        fz := float64(z)\n        fmt.Printf(\"%2d      %11.8f      %11.8f\\n\", z, airmass(0, fz), airmass(13700, fz))\n    }\n}\n"}
{"id": 53247, "name": "Formal power series", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h> \n\nenum fps_type {\n        FPS_CONST = 0,\n        FPS_ADD,\n        FPS_SUB,\n        FPS_MUL,\n        FPS_DIV,\n        FPS_DERIV,\n        FPS_INT,\n};\n\ntypedef struct fps_t *fps;\ntypedef struct fps_t {\n        int type;\n        fps s1, s2;\n        double a0;\n} fps_t;\n\nfps fps_new()\n{\n        fps x = malloc(sizeof(fps_t));\n        x->a0 = 0;\n        x->s1 = x->s2 = 0;\n        x->type = 0;\n        return x;\n}\n\n\nvoid fps_redefine(fps x, int op, fps y, fps z)\n{\n        x->type = op;\n        x->s1 = y;\n        x->s2 = z;\n}\n\nfps _binary(fps x, fps y, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->s2 = y;\n        s->type = op;\n        return s;\n}\n\nfps _unary(fps x, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->type = op;\n        return s;\n}\n\n\ndouble term(fps x, int n)\n{\n        double ret = 0;\n        int i;\n\n        switch (x->type) {\n        case FPS_CONST: return n > 0 ? 0 : x->a0;\n        case FPS_ADD:\n                ret = term(x->s1, n) + term(x->s2, n); break;\n\n        case FPS_SUB:\n                ret = term(x->s1, n) - term(x->s2, n); break;\n\n        case FPS_MUL:\n                for (i = 0; i <= n; i++)\n                        ret += term(x->s1, i) * term(x->s2, n - i);\n                break;\n\n        case FPS_DIV:\n                if (! term(x->s2, 0)) return NAN;\n\n                ret = term(x->s1, n);\n                for (i = 1; i <= n; i++)\n                        ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0);\n                break;\n\n        case FPS_DERIV:\n                ret = n * term(x->s1, n + 1);\n                break;\n\n        case FPS_INT:\n                if (!n) return x->a0;\n                ret = term(x->s1, n - 1) / n;\n                break;\n\n        default:\n                fprintf(stderr, \"Unknown operator %d\\n\", x->type);\n                exit(1);\n        }\n\n        return ret;\n}\n\n#define _add(x, y) _binary(x, y, FPS_ADD)\n#define _sub(x, y) _binary(x, y, FPS_SUB)\n#define _mul(x, y) _binary(x, y, FPS_MUL)\n#define _div(x, y) _binary(x, y, FPS_DIV)\n#define _integ(x)  _unary(x, FPS_INT)\n#define _deriv(x)  _unary(x, FPS_DERIV)\n\nfps fps_const(double a0)\n{\n        fps x = fps_new();\n        x->type = FPS_CONST;\n        x->a0 = a0;\n        return x;\n}\n\nint main()\n{\n        int i;\n        fps one = fps_const(1);\n        fps fcos = fps_new();           \n        fps fsin = _integ(fcos);        \n        fps ftan = _div(fsin, fcos);    \n\n        \n        fps_redefine(fcos, FPS_SUB, one, _integ(fsin));\n\n        fps fexp = fps_const(1);        \n        \n        fps_redefine(fexp, FPS_INT, fexp, 0);\n\n        printf(\"Sin:\");   for (i = 0; i < 10; i++) printf(\" %g\", term(fsin, i));\n        printf(\"\\nCos:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fcos, i));\n        printf(\"\\nTan:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(ftan, i));\n        printf(\"\\nExp:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fexp, i));\n\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype fps interface {\n    extract(int) float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc one() fps {\n    return &oneFps{}\n}\n\nfunc add(s1, s2 fps) fps {\n    return &sum{s1: s1, s2: s2}\n}\n\nfunc sub(s1, s2 fps) fps {\n    return &diff{s1: s1, s2: s2}\n}\n\nfunc mul(s1, s2 fps) fps {\n    return &prod{s1: s1, s2: s2}\n}\n\nfunc div(s1, s2 fps) fps {\n    return &quo{s1: s1, s2: s2}\n}\n\nfunc differentiate(s1 fps) fps {\n    return &deriv{s1: s1}\n}\n\nfunc integrate(s1 fps) fps {\n    return &integ{s1: s1}\n}\n\n\n\n\n\n\n\nfunc sinCos() (fps, fps) {\n    sin := &integ{}\n    cos := sub(one(), integrate(sin))\n    sin.s1 = cos\n    return sin, cos\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype oneFps struct{}\n\n\n\nfunc (*oneFps) extract(n int) float64 {\n    if n == 0 {\n        return 1\n    }\n    return 0\n}\n\n\n\ntype sum struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *sum) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\n\n\n\n\ntype diff struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *diff) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\ntype prod struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *prod) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 0; k <= i; k++ {\n            c += s.s1.extract(k) * s.s1.extract(n-k)\n        }\n        s.s = append(s.s, c)\n    }\n    return s.s[n]\n}\n\n\n\ntype quo struct {\n    s1, s2 fps\n    inv    float64   \n    c      []float64 \n    s      []float64\n}\n\n\n\n\nfunc (s *quo) extract(n int) float64 {\n    switch {\n    case len(s.s) > 0:\n    case !math.IsInf(s.inv, 1):\n        a0 := s.s2.extract(0)\n        s.inv = 1 / a0\n        if a0 != 0 {\n            break\n        }\n        fallthrough\n    default:\n        return math.NaN()\n    }\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 1; k <= i; k++ {\n            c += s.s2.extract(k) * s.c[n-k]\n        }\n        c = s.s1.extract(i) - c*s.inv\n        s.c = append(s.c, c)\n        s.s = append(s.s, c*s.inv)\n    }\n    return s.s[n]\n}\n\n\n\n\ntype deriv struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *deriv) extract(n int) float64 {\n    for i := len(s.s); i <= n; {\n        i++\n        s.s = append(s.s, float64(i)*s.s1.extract(i))\n    }\n    return s.s[n]\n}\n\ntype integ struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *integ) extract(n int) float64 {\n    if n == 0 {\n        return 0 \n    }\n    \n    for i := len(s.s) + 1; i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i-1)/float64(i))\n    }\n    return s.s[n-1]\n}\n\n\nfunc main() {\n    \n    partialSeries := func(f fps) (s string) {\n        for i := 0; i < 6; i++ {\n            s = fmt.Sprintf(\"%s %8.5f \", s, f.extract(i))\n        }\n        return\n    }\n    sin, cos := sinCos()\n    fmt.Println(\"sin:\", partialSeries(sin))\n    fmt.Println(\"cos:\", partialSeries(cos))\n}\n"}
{"id": 53248, "name": "Own digits power sum", "C": "#include <stdio.h>\n#include <math.h>\n\n#define MAX_DIGITS 9\n\nint digits[MAX_DIGITS];\n\nvoid getDigits(int i) {\n    int ix = 0;\n    while (i > 0) {\n        digits[ix++] = i % 10;\n        i /= 10;\n    }\n}\n\nint main() {\n    int n, d, i, max, lastDigit, sum, dp;\n    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};\n    printf(\"Own digits power sums for N = 3 to 9 inclusive:\\n\");\n    for (n = 3; n < 10; ++n) {\n        for (d = 2; d < 10; ++d) powers[d] *= d;\n        i = (int)pow(10, n-1);\n        max = i * 10;\n        lastDigit = 0;\n        while (i < max) {\n            if (!lastDigit) {\n                getDigits(i);\n                sum = 0;\n                for (d = 0; d < n; ++d) {\n                    dp = digits[d];\n                    sum += powers[dp];\n                }\n            } else if (lastDigit == 1) {\n                sum++;\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1];\n            }\n            if (sum == i) {\n                printf(\"%d\\n\", i);\n                if (lastDigit == 0) printf(\"%d\\n\", i + 1);\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (sum > i) {\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (lastDigit < 9) {\n                i++;\n                lastDigit++;\n            } else {\n                i++;\n                lastDigit = 0;\n            }\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n    fmt.Println(\"Own digits power sums for N = 3 to 9 inclusive:\")\n    for n := 3; n < 10; n++ {\n        for d := 2; d < 10; d++ {\n            powers[d] *= d\n        }\n        i := int(math.Pow(10, float64(n-1)))\n        max := i * 10\n        lastDigit := 0\n        sum := 0\n        var digits []int\n        for i < max {\n            if lastDigit == 0 {\n                digits = rcu.Digits(i, 10)\n                sum = 0\n                for _, d := range digits {\n                    sum += powers[d]\n                }\n            } else if lastDigit == 1 {\n                sum++\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1]\n            }\n            if sum == i {\n                fmt.Println(i)\n                if lastDigit == 0 {\n                    fmt.Println(i + 1)\n                }\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if sum > i {\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if lastDigit < 9 {\n                i++\n                lastDigit++\n            } else {\n                i++\n                lastDigit = 0\n            }\n        }\n    }\n}\n"}
{"id": 53249, "name": "Bitmap_Bézier curves_Cubic", "C": "void cubic_bezier(\n       \timage img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        unsigned int x4, unsigned int y4,\n        color_component r,\n        color_component g,\n        color_component b );\n", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n"}
{"id": 53250, "name": "Sorting algorithms_Pancake sort", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n"}
{"id": 53251, "name": "Largest five adjacent number", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\n#define DIGITS 1000\n#define NUMSIZE 5\n\nuint8_t randomDigit() {\n    uint8_t d;\n    do {d = rand() & 0xF;} while (d >= 10);\n    return d;\n}\n\nint numberAt(uint8_t *d, int size) {\n    int acc = 0;\n    while (size--) acc = 10*acc + *d++;\n    return acc;\n}\n\nint main() {\n    uint8_t digits[DIGITS];\n    int i, largest = 0;\n    \n    srand(time(NULL));\n    \n    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();\n    for (i=0; i<DIGITS-NUMSIZE; i++) {\n        int here = numberAt(&digits[i], NUMSIZE);\n        if (here > largest) largest = here;\n    }\n\n    printf(\"%d\\n\", largest);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"rcu\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var sb strings.Builder\n    for i := 0; i < 1000; i++ {\n        sb.WriteByte(byte(rand.Intn(10) + 48))\n    }\n    number := sb.String()\n    for i := 99999; i >= 0; i-- {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The largest  number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            break\n        }\n    }\n    for i := 0; i <= 99999; i++ {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The smallest number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            return\n        }\n    }\n}\n"}
{"id": 53252, "name": "Largest five adjacent number", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\n#define DIGITS 1000\n#define NUMSIZE 5\n\nuint8_t randomDigit() {\n    uint8_t d;\n    do {d = rand() & 0xF;} while (d >= 10);\n    return d;\n}\n\nint numberAt(uint8_t *d, int size) {\n    int acc = 0;\n    while (size--) acc = 10*acc + *d++;\n    return acc;\n}\n\nint main() {\n    uint8_t digits[DIGITS];\n    int i, largest = 0;\n    \n    srand(time(NULL));\n    \n    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();\n    for (i=0; i<DIGITS-NUMSIZE; i++) {\n        int here = numberAt(&digits[i], NUMSIZE);\n        if (here > largest) largest = here;\n    }\n\n    printf(\"%d\\n\", largest);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"rcu\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var sb strings.Builder\n    for i := 0; i < 1000; i++ {\n        sb.WriteByte(byte(rand.Intn(10) + 48))\n    }\n    number := sb.String()\n    for i := 99999; i >= 0; i-- {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The largest  number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            break\n        }\n    }\n    for i := 0; i <= 99999; i++ {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The smallest number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            return\n        }\n    }\n}\n"}
{"id": 53253, "name": "Sum of square and cube digits of an integer are primes", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint digit_sum(int n) {\n    int sum;\n    for (sum = 0; n; n /= 10) sum += n % 10;\n    return sum;\n}\n\n\nbool prime(int n) {\n    if (n<4) return n>=2;\n    for (int d=2; d*d <= n; d++)\n        if (n%d == 0) return false;\n    return true;\n}\n\nint main() {\n    for (int i=1; i<100; i++)\n        if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i)))\n            printf(\"%d \", i);\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    for i := 1; i < 100; i++ {\n        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {\n            continue\n        }\n        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {\n            fmt.Printf(\"%d \", i)\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 53254, "name": "The sieve of Sundaram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\nint main(void) {\n    int nprimes =  1000000;\n    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  \n      \n      \n    int i, j, m, k; int *a;\n    k = (nmax-2)/2; \n    a = (int *)calloc(k + 1, sizeof(int));\n    for(i = 0; i <= k; i++)a[i] = 2*i+1; \n    for (i = 1; (i+1)*i*2 <= k; i++)\n        for (j = i; j <= (k-i)/(2*i+1); j++) {\n            m = i + j + 2*i*j;\n            if(a[m]) a[m] = 0;\n            }            \n        \n    for (i = 1, j = 0; i <= k; i++) \n       if (a[i]) {\n           if(j%10 == 0 && j <= 100)printf(\"\\n\");\n           j++; \n           if(j <= 100)printf(\"%3d \", a[i]);\n           else if(j == nprimes){\n               printf(\"\\n%d th prime is %d\\n\",j,a[i]);\n               break;\n               }\n           }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nfunc sos(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        p := 2*i + 3\n        s := (p*p - 3) / 2\n        for j := s; j < k; j += p {\n            marked[j] = true\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\n\nfunc soe(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        if !marked[i] {\n            p := 2*i + 3\n            s := (p*p - 3) / 2\n            for j := s; j < k; j += p {\n                marked[j] = true\n            }\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\nfunc main() {\n    const limit = int(16e6) \n    start := time.Now()\n    primes := sos(limit)\n    elapsed := int(time.Since(start).Milliseconds())\n    climit := rcu.Commatize(limit)\n    celapsed := rcu.Commatize(elapsed)\n    million := rcu.Commatize(1e6)\n    millionth := rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"Using the Sieve of Sundaram generated primes up to %s in %s ms.\\n\\n\", climit, celapsed)\n    fmt.Println(\"First 100 odd primes generated by the Sieve of Sundaram:\")\n    for i, p := range primes[0:100] {\n        fmt.Printf(\"%3d \", p)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThe %s Sundaram prime is %s\\n\", million, millionth)\n\n    start = time.Now()\n    primes = soe(limit)\n    elapsed = int(time.Since(start).Milliseconds())\n    celapsed = rcu.Commatize(elapsed)\n    millionth = rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"\\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\\n\", celapsed)\n    fmt.Printf(\"\\nAs a check, the %s Sundaram prime would again have been %s\\n\", million, millionth)\n}\n"}
{"id": 53255, "name": "Active Directory_Connect", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n"}
{"id": 53256, "name": "Exactly three adjacent 3 in lists", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool three_3s(const int *items, size_t len) {\n    int threes = 0;    \n    while (len--) \n        if (*items++ == 3)\n            if (threes<3) threes++;\n            else return false;\n        else if (threes != 0 && threes != 3) \n            return false;\n    return true;\n}\n\nvoid print_list(const int *items, size_t len) {\n    while (len--) printf(\"%d \", *items++);\n}\n\nint main() {\n    int lists[][9] = {\n        {9,3,3,3,2,1,7,8,5},\n        {5,2,9,3,3,6,8,4,1},\n        {1,4,3,6,7,3,8,3,2},\n        {1,2,3,4,5,6,7,8,9},\n        {4,6,8,7,2,3,3,3,1}\n    };\n    \n    size_t list_length = sizeof(lists[0]) / sizeof(int);\n    size_t n_lists = sizeof(lists) / sizeof(lists[0]);\n    \n    for (size_t i=0; i<n_lists; i++) {\n        print_list(lists[i], list_length);\n        printf(\"-> %s\\n\", three_3s(lists[i], list_length) ? \"true\" : \"false\");\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    lists := [][]int{\n        {9, 3, 3, 3, 2, 1, 7, 8, 5},\n        {5, 2, 9, 3, 3, 7, 8, 4, 1},\n        {1, 4, 3, 6, 7, 3, 8, 3, 2},\n        {1, 2, 3, 4, 5, 6, 7, 8, 9},\n        {4, 6, 8, 7, 2, 3, 3, 3, 1},\n        {3, 3, 3, 1, 2, 4, 5, 1, 3},\n        {0, 3, 3, 3, 3, 7, 2, 2, 6},\n        {3, 3, 3, 3, 3, 4, 4, 4, 4},\n    }\n    for d := 1; d <= 4; d++ {\n        fmt.Printf(\"Exactly %d adjacent %d's:\\n\", d, d)\n        for _, list := range lists {\n            var indices []int\n            for i, e := range list {\n                if e == d {\n                    indices = append(indices, i)\n                }\n            }\n            adjacent := false\n            if len(indices) == d {\n                adjacent = true\n                for i := 1; i < len(indices); i++ {\n                    if indices[i]-indices[i-1] != 1 {\n                        adjacent = false\n                        break\n                    }\n                }\n            }\n            fmt.Printf(\"%v -> %t\\n\", list, adjacent)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 53257, "name": "Permutations by swapping", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n"}
{"id": 53258, "name": "Minimum multiple of m where digital sum equals m", "C": "#include <stdio.h>\n\nunsigned digit_sum(unsigned n) {\n    unsigned sum = 0;\n    do { sum += n % 10; }\n    while(n /= 10);\n    return sum;\n}\n\nunsigned a131382(unsigned n) {\n    unsigned m;\n    for (m = 1; n != digit_sum(m*n); m++);\n    return m;\n}\n\nint main() {\n    unsigned n;\n    for (n = 1; n <= 70; n++) {\n        printf(\"%9u\", a131382(n));\n        if (n % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n"}
{"id": 53259, "name": "Pythagorean quadruples", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n"}
{"id": 53260, "name": "Verhoeff algorithm", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic const int d[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n};\n\nstatic const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};\n\nstatic const int p[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n};\n\nint verhoeff(const char* s, bool validate, bool verbose) {\n    if (verbose) {\n        const char* t = validate ? \"Validation\" : \"Check digit\";\n        printf(\"%s calculations for '%s':\\n\\n\", t, s);\n        puts(u8\" i  n\\xE1\\xB5\\xA2  p[i,n\\xE1\\xB5\\xA2]  c\");\n        puts(\"------------------\");\n    }\n    int len = strlen(s);\n    if (validate)\n        --len;\n    int c = 0;\n    for (int i = len; i >= 0; --i) {\n        int ni = (i == len && !validate) ? 0 : s[i] - '0';\n        assert(ni >= 0 && ni < 10);\n        int pi = p[(len - i) % 8][ni];\n        c = d[c][pi];\n        if (verbose)\n            printf(\"%2d  %d      %d     %d\\n\", len - i, ni, pi, c);\n    }\n    if (verbose && !validate)\n        printf(\"\\ninv[%d] = %d\\n\", c, inv[c]);\n    return validate ? c == 0 : inv[c];\n}\n\nint main() {\n    const char* ss[3] = {\"236\", \"12345\", \"123456789012\"};\n    for (int i = 0; i < 3; ++i) {\n        const char* s = ss[i];\n        bool verbose = i < 2;\n        int c = verhoeff(s, false, verbose);\n        printf(\"\\nThe check digit for '%s' is '%d'.\\n\", s, c);\n        int len = strlen(s);\n        char sc[len + 2];\n        strncpy(sc, s, len + 2);\n        for (int j = 0; j < 2; ++j) {\n            sc[len] = (j == 0) ? c + '0' : '9';\n            int v = verhoeff(sc, true, verbose);\n            printf(\"\\nThe validation for '%s' is %s.\\n\", sc,\n                   v ? \"correct\" : \"incorrect\");\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar d = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},\n    {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},\n    {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},\n    {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},\n    {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n}\n\nvar inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}\n\nvar p = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},\n    {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},\n    {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},\n    {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n}\n\nfunc verhoeff(s string, validate, table bool) interface{} {\n    if table {\n        t := \"Check digit\"\n        if validate {\n            t = \"Validation\"\n        }\n        fmt.Printf(\"%s calculations for '%s':\\n\\n\", t, s)\n        fmt.Println(\" i  nᵢ  p[i,nᵢ]  c\")\n        fmt.Println(\"------------------\")\n    }\n    if !validate {\n        s = s + \"0\"\n    }\n    c := 0\n    le := len(s) - 1\n    for i := le; i >= 0; i-- {\n        ni := int(s[i] - 48)\n        pi := p[(le-i)%8][ni]\n        c = d[c][pi]\n        if table {\n            fmt.Printf(\"%2d  %d      %d     %d\\n\", le-i, ni, pi, c)\n        }\n    }\n    if table && !validate {\n        fmt.Printf(\"\\ninv[%d] = %d\\n\", c, inv[c])\n    }\n    if !validate {\n        return inv[c]\n    }\n    return c == 0\n}\n\nfunc main() {\n    ss := []string{\"236\", \"12345\", \"123456789012\"}\n    ts := []bool{true, true, false, true}\n    for i, s := range ss {\n        c := verhoeff(s, false, ts[i]).(int)\n        fmt.Printf(\"\\nThe check digit for '%s' is '%d'\\n\\n\", s, c)\n        for _, sc := range []string{s + string(c+48), s + \"9\"} {\n            v := verhoeff(sc, true, ts[i]).(bool)\n            ans := \"correct\"\n            if !v {\n                ans = \"incorrect\"\n            }\n            fmt.Printf(\"\\nThe validation for '%s' is %s\\n\\n\", sc, ans)\n        }\n    }\n}\n"}
{"id": 53261, "name": "Steady squares", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc contains(list []int, s int) bool {\n    for _, e := range list {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"Steady squares under 10,000:\")\n    finalDigits := []int{1, 5, 6}\n    for i := 1; i < 10000; i++ {\n        if !contains(finalDigits, i%10) {\n            continue\n        }\n        sq := i * i\n        sqs := strconv.Itoa(sq)\n        is := strconv.Itoa(i)\n        if strings.HasSuffix(sqs, is) {\n            fmt.Printf(\"%5s -> %10s\\n\", rcu.Commatize(i), rcu.Commatize(sq))\n        }\n    }\n}\n"}
{"id": 53262, "name": "Numbers in base 10 that are palindromic in bases 2, 4, and 16", "C": "#include <stdio.h>\n#define MAXIMUM 25000\n\nint reverse(int n, int base) {\n    int r;\n    for (r = 0; n; n /= base)\n        r = r*base + n%base;\n    return r;\n}\n\nint palindrome(int n, int base) {\n    return n == reverse(n, base);\n}\n\nint main() {\n    int i, c = 0;\n    \n    for (i = 0; i < MAXIMUM; i++) {\n        if (palindrome(i, 2) &&\n            palindrome(i, 4) &&\n            palindrome(i, 16)) {\n            printf(\"%5d%c\", i, ++c % 12 ? ' ' : '\\n');\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc reverse(s string) string {\n    chars := []rune(s)\n    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n        chars[i], chars[j] = chars[j], chars[i]\n    }\n    return string(chars)\n}\n\nfunc main() {\n    fmt.Println(\"Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:\")\n    var numbers []int\n    for i := int64(0); i < 25000; i++ {\n        b2 := strconv.FormatInt(i, 2)\n        if b2 == reverse(b2) {\n            b4 := strconv.FormatInt(i, 4)\n            if b4 == reverse(b4) {\n                b16 := strconv.FormatInt(i, 16)\n                if b16 == reverse(b16) {\n                    numbers = append(numbers, int(i))\n                }\n            }\n        }\n    }\n    for i, n := range numbers {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(numbers), \"such numbers.\")\n}\n"}
{"id": 53263, "name": "Long stairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n    int trial, secs_tot=0, steps_tot=0;     \n    int sbeh, slen, wiz, secs;              \n    time_t t;\n    srand((unsigned) time(&t));             \n    printf( \"Seconds    steps behind    steps ahead\\n\" );\n    for( trial=1;trial<=10000;trial++ ) {   \n        sbeh = 0; slen = 100; secs = 0;     \n        while(sbeh<slen) {                  \n            sbeh+=1;                        \n            for(wiz=1;wiz<=5;wiz++) {       \n                if(rand()%slen < sbeh)\n                    sbeh+=1;                \n                slen+=1;                    \n            }\n            secs+=1;                        \n            if(trial==1&&599<secs&&secs<610)\n                printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh );\n            \n        }\n        secs_tot+=secs;\n        steps_tot+=slen;\n    }\n    printf( \"Average secs taken: %f\\n\", secs_tot/10000.0 );\n    printf( \"Average final length of staircase: %f\\n\", steps_tot/10000.0 ); \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    totalSecs := 0\n    totalSteps := 0\n    fmt.Println(\"Seconds    steps behind    steps ahead\")\n    fmt.Println(\"-------    ------------    -----------\")\n    for trial := 1; trial < 10000; trial++ {\n        sbeh := 0\n        slen := 100\n        secs := 0\n        for sbeh < slen {\n            sbeh++\n            for wiz := 1; wiz < 6; wiz++ {\n                if rand.Intn(slen) < sbeh {\n                    sbeh++\n                }\n                slen++\n            }\n            secs++\n            if trial == 1 && secs > 599 && secs < 610 {\n                fmt.Printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh)\n            }\n        }\n        totalSecs += secs\n        totalSteps += slen\n    }\n    fmt.Println(\"\\nAverage secs taken:\", float64(totalSecs)/10000)\n    fmt.Println(\"Average final length of staircase:\", float64(totalSteps)/10000)\n}\n"}
{"id": 53264, "name": "Terminal control_Positional read", "C": "#include <windows.h>\n#include <wchar.h>\n\nint\nmain()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n\tCOORD pos;\n\tHANDLE conout;\n\tlong len;\n\twchar_t c;\n\n\t\n\tconout = CreateFileW(L\"CONOUT$\", GENERIC_READ | GENERIC_WRITE,\n\t    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t    0, NULL);\n\tif (conout == INVALID_HANDLE_VALUE)\n\t\treturn 1;\n\n\t\n\tif (GetConsoleScreenBufferInfo(conout, &info) == 0)\n\t\treturn 1;\n\n\t\n\tpos.X = info.srWindow.Left + 3;  \n\tpos.Y = info.srWindow.Top  + 6;  \n\tif (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||\n\t    len <= 0)\n\t\treturn 1;\n\n\twprintf(L\"Character at (3, 6) had been '%lc'\\n\", c);\n\treturn 0;\n}\n", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i < 80*25; i++ {\n        fmt.Print(\"A\")  \n    }\n    fmt.Println()\n    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)\n    info := C.CONSOLE_SCREEN_BUFFER_INFO{}\n    pos := C.COORD{}\n    C.GetConsoleScreenBufferInfo(conOut, &info)\n    pos.X = info.srWindow.Left + 3 \n    pos.Y = info.srWindow.Top + 6  \n    var c C.wchar_t\n    var le C.ulong\n    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)\n    if ret == 0 || le <= 0 {\n        fmt.Println(\"Something went wrong!\")\n        return\n    }\n    fmt.Printf(\"The character at column 3, row 6 is '%c'\\n\", c) \n}\n"}
{"id": 53265, "name": "Terminal control_Positional read", "C": "#include <windows.h>\n#include <wchar.h>\n\nint\nmain()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n\tCOORD pos;\n\tHANDLE conout;\n\tlong len;\n\twchar_t c;\n\n\t\n\tconout = CreateFileW(L\"CONOUT$\", GENERIC_READ | GENERIC_WRITE,\n\t    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t    0, NULL);\n\tif (conout == INVALID_HANDLE_VALUE)\n\t\treturn 1;\n\n\t\n\tif (GetConsoleScreenBufferInfo(conout, &info) == 0)\n\t\treturn 1;\n\n\t\n\tpos.X = info.srWindow.Left + 3;  \n\tpos.Y = info.srWindow.Top  + 6;  \n\tif (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||\n\t    len <= 0)\n\t\treturn 1;\n\n\twprintf(L\"Character at (3, 6) had been '%lc'\\n\", c);\n\treturn 0;\n}\n", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i < 80*25; i++ {\n        fmt.Print(\"A\")  \n    }\n    fmt.Println()\n    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)\n    info := C.CONSOLE_SCREEN_BUFFER_INFO{}\n    pos := C.COORD{}\n    C.GetConsoleScreenBufferInfo(conOut, &info)\n    pos.X = info.srWindow.Left + 3 \n    pos.Y = info.srWindow.Top + 6  \n    var c C.wchar_t\n    var le C.ulong\n    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)\n    if ret == 0 || le <= 0 {\n        fmt.Println(\"Something went wrong!\")\n        return\n    }\n    fmt.Printf(\"The character at column 3, row 6 is '%c'\\n\", c) \n}\n"}
{"id": 53266, "name": "Pseudo-random numbers_Middle-square method", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 53267, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 53268, "name": "Image convolution", "C": "image filter(image img, double *K, int Ks, double, double);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/jpeg\"\n    \"math\"\n    \"os\"\n)\n\n\n\nfunc kf3(k *[9]float64, src, dst *image.Gray) {\n    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {\n        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {\n            var sum float64\n            var i int\n            for yo := y - 1; yo <= y+1; yo++ {\n                for xo := x - 1; xo <= x+1; xo++ {\n                    if (image.Point{xo, yo}).In(src.Rect) {\n                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)\n                    } else {\n                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)\n                    }\n                    i++\n                }\n            }\n            dst.SetGray(x, y,\n                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})\n        }\n    }\n}\n\nvar blur = [9]float64{\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9}\n\n\n\nfunc blurY(src *image.YCbCr) *image.YCbCr {\n    dst := *src\n\n    \n    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {\n        return &dst\n    }\n\n    \n    srcGray := image.Gray{src.Y, src.YStride, src.Rect}\n    dstGray := srcGray\n    dstGray.Pix = make([]uint8, len(src.Y))\n    kf3(&blur, &srcGray, &dstGray) \n\n    \n    dst.Y = dstGray.Pix                   \n    dst.Cb = append([]uint8{}, src.Cb...) \n    dst.Cr = append([]uint8{}, src.Cr...)\n    return &dst\n}\n\nfunc main() {\n    \n    \n    f, err := os.Open(\"Lenna100.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    img, err := jpeg.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n    y, ok := img.(*image.YCbCr)\n    if !ok {\n        fmt.Println(\"expected color jpeg\")\n        return\n    }\n    f, err = os.Create(\"blur.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 53269, "name": "Dice game probabilities", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n"}
{"id": 53270, "name": "Rosetta Code_Find unimplemented tasks", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n"}
{"id": 53271, "name": "Halt and catch fire", "C": "int main(){int a=0, b=0, c=a/b;}\n", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n"}
{"id": 53272, "name": "Plasma effect", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n"}
{"id": 53273, "name": "Wordle comparison", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid wordle(const char *answer, const char *guess, int *result) {\n    int i, ix, n = strlen(guess);\n    char *ptr;\n    if (n != strlen(answer)) {\n        printf(\"The words must be of the same length.\\n\");\n        exit(1);\n    }\n    char answer2[n+1];\n    strcpy(answer2, answer);\n    for (i = 0; i < n; ++i) {\n        if (guess[i] == answer2[i]) {\n            answer2[i] = '\\v';\n            result[i] = 2;\n        }\n    }\n    for (i = 0; i < n; ++i) {\n        if ((ptr = strchr(answer2, guess[i])) != NULL) {\n            ix = ptr - answer2;\n            answer2[ix] = '\\v';\n            result[i] = 1;\n        }\n    }\n}\n\nint main() {\n    int i, j;\n    const char *answer, *guess;\n    int res[5];\n    const char *res2[5];\n    const char *colors[3] = {\"grey\", \"yellow\", \"green\"};\n    const char *pairs[5][2] = {\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"}\n    };\n    for (i = 0; i < 5; ++i) {\n        answer = pairs[i][0];\n        guess  = pairs[i][1];\n        for (j = 0; j < 5; ++j) res[j] = 0;\n        wordle(answer, guess, res);\n        for (j = 0; j < 5; ++j) res2[j] = colors[res[j]];\n        printf(\"%s v %s => { \", answer, guess);\n        for (j = 0; j < 5; ++j) printf(\"%d \", res[j]);\n        printf(\"} => { \");\n        for (j = 0; j < 5; ++j) printf(\"%s \", res2[j]);\n        printf(\"}\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc wordle(answer, guess string) []int {\n    n := len(guess)\n    if n != len(answer) {\n        log.Fatal(\"The words must be of the same length.\")\n    }\n    answerBytes := []byte(answer)\n    result := make([]int, n) \n    for i := 0; i < n; i++ {\n        if guess[i] == answerBytes[i] {\n            answerBytes[i] = '\\000'\n            result[i] = 2\n        }\n    }\n    for i := 0; i < n; i++ {\n        ix := bytes.IndexByte(answerBytes, guess[i])\n        if ix >= 0 {\n            answerBytes[ix] = '\\000'\n            result[i] = 1\n        }\n    }\n    return result\n}\n\nfunc main() {\n    colors := []string{\"grey\", \"yellow\", \"green\"}\n    pairs := [][]string{\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"},\n    }\n    for _, pair := range pairs {\n        res := wordle(pair[0], pair[1])\n        res2 := make([]string, len(res))\n        for i := 0; i < len(res); i++ {\n            res2[i] = colors[res[i]]\n        }\n        fmt.Printf(\"%s v %s => %v => %v\\n\", pair[0], pair[1], res, res2)\n    }\n}\n"}
{"id": 53274, "name": "Color quantization", "C": "typedef struct oct_node_t oct_node_t, *oct_node;\nstruct oct_node_t{\n\t\n\tuint64_t r, g, b;\n\tint count, heap_idx;\n\toct_node kids[8], parent;\n\tunsigned char n_kids, kid_idx, flags, depth;\n};\n\n\ninline int cmp_node(oct_node a, oct_node b)\n{\n\tif (a->n_kids < b->n_kids) return -1;\n\tif (a->n_kids > b->n_kids) return 1;\n\n\tint ac = a->count * (1 + a->kid_idx) >> a->depth;\n\tint bc = b->count * (1 + b->kid_idx) >> b->depth;\n\treturn ac < bc ? -1 : ac > bc;\n}\n\n\noct_node node_insert(oct_node root, unsigned char *pix)\n{\n#\tdefine OCT_DEPTH 8\n\t\n\n\tunsigned char i, bit, depth = 0;\n\tfor (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i])\n\t\t\troot->kids[i] = node_new(i, depth, root);\n\n\t\troot = root->kids[i];\n\t}\n\n\troot->r += pix[0];\n\troot->g += pix[1];\n\troot->b += pix[2];\n\troot->count++;\n\treturn root;\n}\n\n\noct_node node_fold(oct_node p)\n{\n\tif (p->n_kids) abort();\n\toct_node q = p->parent;\n\tq->count += p->count;\n\n\tq->r += p->r;\n\tq->g += p->g;\n\tq->b += p->b;\n\tq->n_kids --;\n\tq->kids[p->kid_idx] = 0;\n\treturn q;\n}\n\n\nvoid color_replace(oct_node root, unsigned char *pix)\n{\n\tunsigned char i, bit;\n\n\tfor (bit = 1 << 7; bit; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i]) break;\n\t\troot = root->kids[i];\n\t}\n\n\tpix[0] = root->r;\n\tpix[1] = root->g;\n\tpix[2] = root->b;\n}\n\n\nvoid color_quant(image im, int n_colors)\n{\n\tint i;\n\tunsigned char *pix = im->pix;\n\tnode_heap heap = { 0, 0, 0 };\n\n\toct_node root = node_new(0, 0, 0), got;\n\tfor (i = 0; i < im->w * im->h; i++, pix += 3)\n\t\theap_add(&heap, node_insert(root, pix));\n\n\twhile (heap.n > n_colors + 1)\n\t\theap_add(&heap, node_fold(pop_heap(&heap)));\n\n\tdouble c;\n\tfor (i = 1; i < heap.n; i++) {\n\t\tgot = heap.buf[i];\n\t\tc = got->count;\n\t\tgot->r = got->r / c + .5;\n\t\tgot->g = got->g / c + .5;\n\t\tgot->b = got->b / c + .5;\n\t\tprintf(\"%2d | %3llu %3llu %3llu (%d pixels)\\n\",\n\t\t\ti, got->r, got->g, got->b, got->count);\n\t}\n\n\tfor (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)\n\t\tcolor_replace(root, pix);\n\n\tnode_free();\n\tfree(heap.buf);\n}\n", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    f, err := os.Open(\"Quantum_frog.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    img, err := png.Decode(f)\n    if ec := f.Close(); err != nil {\n        log.Fatal(err)\n    } else if ec != nil {\n        log.Fatal(ec)\n    }\n    fq, err := os.Create(\"frog16.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = png.Encode(fq, quant(img, 16)); err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc quant(img image.Image, nq int) image.Image {\n    qz := newQuantizer(img, nq) \n    qz.cluster()                \n    return qz.Paletted()        \n}\n\n\ntype quantizer struct {\n    img image.Image \n    cs  []cluster   \n    px  []point     \n    ch  chValues    \n    eq  []point     \n}\n\ntype cluster struct {\n    px       []point \n    widestCh int     \n    chRange  uint32  \n}\n\ntype point struct{ x, y int }\ntype chValues []uint32\ntype queue []*cluster\n\nconst (\n    rx = iota\n    gx\n    bx\n)\n\nfunc newQuantizer(img image.Image, nq int) *quantizer {\n    b := img.Bounds()\n    npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)\n    \n    qz := &quantizer{\n        img: img,\n        ch:  make(chValues, npx),\n        cs:  make([]cluster, nq),\n    }\n    \n    c := &qz.cs[0]\n    px := make([]point, npx)\n    c.px = px\n    i := 0\n    for y := b.Min.Y; y < b.Max.Y; y++ {\n        for x := b.Min.X; x < b.Max.X; x++ {\n            px[i].x = x\n            px[i].y = y\n            i++\n        }\n    }\n    return qz\n}\n\nfunc (qz *quantizer) cluster() {\n    \n    \n    \n    \n    \n    pq := new(queue)\n    \n    c := &qz.cs[0]\n    for i := 1; ; {\n        qz.setColorRange(c)\n        \n        \n        if c.chRange > 0 {\n            heap.Push(pq, c) \n        }\n        \n        \n        if len(*pq) == 0 {\n            qz.cs = qz.cs[:i]\n            break\n        }\n        s := heap.Pop(pq).(*cluster) \n        c = &qz.cs[i]                \n        i++\n        m := qz.Median(s)\n        qz.Split(s, c, m) \n        \n        if i == len(qz.cs) {\n            break\n        }\n        qz.setColorRange(s)\n        if s.chRange > 0 {\n            heap.Push(pq, s) \n        }\n    }\n}\n    \nfunc (q *quantizer) setColorRange(c *cluster) {\n    \n    var maxR, maxG, maxB uint32\n    minR := uint32(math.MaxUint32)\n    minG := uint32(math.MaxUint32)\n    minB := uint32(math.MaxUint32) \n    for _, p := range c.px {\n        r, g, b, _ := q.img.At(p.x, p.y).RGBA()\n        if r < minR { \n            minR = r\n        }\n        if r > maxR {\n            maxR = r\n        }\n        if g < minG {\n            minG = g \n        }\n        if g > maxG {\n            maxG = g\n        }\n        if b < minB {\n            minB = b\n        }\n        if b > maxB {\n            maxB = b\n        }\n    }\n    \n    s := gx\n    min := minG\n    max := maxG\n    if maxR-minR > max-min {\n        s = rx\n        min = minR\n        max = maxR\n    }\n    if maxB-minB > max-min {\n        s = bx\n        min = minB\n        max = maxB\n    }\n    c.widestCh = s\n    c.chRange = max - min \n}\n\nfunc (q *quantizer) Median(c *cluster) uint32 {\n    px := c.px\n    ch := q.ch[:len(px)]\n    \n    switch c.widestCh {\n    case rx:\n        for i, p := range c.px {\n            ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case gx:\n        for i, p := range c.px {\n            _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case bx:\n        for i, p := range c.px {\n            _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA()\n        }\n    }\n    \n    sort.Sort(ch)\n    half := len(ch) / 2\n    m := ch[half]\n    if len(ch)%2 == 0 {\n        m = (m + ch[half-1]) / 2\n    }\n    return m\n}\n\nfunc (q *quantizer) Split(s, c *cluster, m uint32) {\n    px := s.px\n    var v uint32\n    i := 0\n    lt := 0\n    gt := len(px) - 1\n    eq := q.eq[:0] \n    for i <= gt {\n        \n        r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA()\n        switch s.widestCh {\n        case rx:\n            v = r\n        case gx:\n            v = g\n        case bx:\n            v = b\n        } \n        \n        switch {\n        case v < m:\n            px[lt] = px[i]\n            lt++\n            i++\n        case v > m:\n            px[gt], px[i] = px[i], px[gt]\n            gt--\n        default:\n            eq = append(eq, px[i])\n            i++\n        }\n    }\n    \n    if len(eq) > 0 {\n        copy(px[lt:], eq) \n        \n        \n        \n        if len(px)-i < lt {\n            i = lt\n        }\n        q.eq = eq \n    }\n    \n    s.px = px[:i]\n    c.px = px[i:]\n}   \n    \nfunc (qz *quantizer) Paletted() *image.Paletted {\n    cp := make(color.Palette, len(qz.cs))\n    pi := image.NewPaletted(qz.img.Bounds(), cp)\n    for i := range qz.cs {\n        px := qz.cs[i].px\n        \n        var rsum, gsum, bsum int64\n        for _, p := range px {\n            r, g, b, _ := qz.img.At(p.x, p.y).RGBA()\n            rsum += int64(r)\n            gsum += int64(g)\n            bsum += int64(b)\n        } \n        n64 := int64(len(px))\n        cp[i] = color.NRGBA64{\n            uint16(rsum / n64),\n            uint16(gsum / n64),\n            uint16(bsum / n64),\n            0xffff,\n        }\n        \n        for _, p := range px {\n            pi.SetColorIndex(p.x, p.y, uint8(i))\n        }\n    }\n    return pi\n}\n\n\nfunc (c chValues) Len() int           { return len(c) }\nfunc (c chValues) Less(i, j int) bool { return c[i] < c[j] }\nfunc (c chValues) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\n\n\nfunc (q queue) Len() int { return len(q) }\n\n\nfunc (q queue) Less(i, j int) bool {\n    return len(q[j].px) < len(q[i].px)\n}\n\nfunc (q queue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n}\nfunc (pq *queue) Push(x interface{}) {\n    c := x.(*cluster)\n    *pq = append(*pq, c)\n}\nfunc (pq *queue) Pop() interface{} {\n    q := *pq\n    n := len(q) - 1\n    c := q[n]\n    *pq = q[:n]\n    return c\n}\n"}
{"id": 53275, "name": "Function frequency", "C": "#define _POSIX_SOURCE\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <stddef.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\nstruct functionInfo {\n    char* name;\n    int timesCalled;\n    char marked;\n};\nvoid addToList(struct functionInfo** list, struct functionInfo toAdd, \\\n               size_t* numElements, size_t* allocatedSize)\n{\n    static const char* keywords[32] = {\"auto\", \"break\", \"case\", \"char\", \"const\", \\\n                                       \"continue\", \"default\", \"do\", \"double\", \\\n                                       \"else\", \"enum\", \"extern\", \"float\", \"for\", \\\n                                       \"goto\", \"if\", \"int\", \"long\", \"register\", \\\n                                       \"return\", \"short\", \"signed\", \"sizeof\", \\\n                                       \"static\", \"struct\", \"switch\", \"typedef\", \\\n                                       \"union\", \"unsigned\", \"void\", \"volatile\", \\\n                                       \"while\"\n                                      };\n    int i;\n    \n    for (i = 0; i < 32; i++) {\n        if (!strcmp(toAdd.name, keywords[i])) {\n            return;\n        }\n    }\n    if (!*list) {\n        *allocatedSize = 10;\n        *list = calloc(*allocatedSize, sizeof(struct functionInfo));\n        if (!*list) {\n            printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                   *allocatedSize, sizeof(struct functionInfo));\n            abort();\n        }\n        (*list)[0].name = malloc(strlen(toAdd.name)+1);\n        if (!(*list)[0].name) {\n            printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n            abort();\n        }\n        strcpy((*list)[0].name, toAdd.name);\n        (*list)[0].timesCalled = 1;\n        (*list)[0].marked = 0;\n        *numElements = 1;\n    } else {\n        char found = 0;\n        unsigned int i;\n        for (i = 0; i < *numElements; i++) {\n            if (!strcmp((*list)[i].name, toAdd.name)) {\n                found = 1;\n                (*list)[i].timesCalled++;\n                break;\n            }\n        }\n        if (!found) {\n            struct functionInfo* newList = calloc((*allocatedSize)+10, \\\n                                                  sizeof(struct functionInfo));\n            if (!newList) {\n                printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                       (*allocatedSize)+10, sizeof(struct functionInfo));\n                abort();\n            }\n            memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo));\n            free(*list);\n            *allocatedSize += 10;\n            *list = newList;\n            (*list)[*numElements].name = malloc(strlen(toAdd.name)+1);\n            if (!(*list)[*numElements].name) {\n                printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n                abort();\n            }\n            strcpy((*list)[*numElements].name, toAdd.name);\n            (*list)[*numElements].timesCalled = 1;\n            (*list)[*numElements].marked = 0;\n            (*numElements)++;\n        }\n    }\n}\nvoid printList(struct functionInfo** list, size_t numElements)\n{\n    char maxSet = 0;\n    unsigned int i;\n    size_t maxIndex = 0;\n    for (i = 0; i<10; i++) {\n        maxSet = 0;\n        size_t j;\n        for (j = 0; j<numElements; j++) {\n            if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) {\n                if (!(*list)[j].marked) {\n                    maxSet = 1;\n                    maxIndex = j;\n                }\n            }\n        }\n        (*list)[maxIndex].marked = 1;\n        printf(\"%s() called %d times.\\n\", (*list)[maxIndex].name, \\\n               (*list)[maxIndex].timesCalled);\n    }\n}\nvoid freeList(struct functionInfo** list, size_t numElements)\n{\n    size_t i;\n    for (i = 0; i<numElements; i++) {\n        free((*list)[i].name);\n    }\n    free(*list);\n}\nchar* extractFunctionName(char* readHead)\n{\n    char* identifier = readHead;\n    if (isalpha(*identifier) || *identifier == '_') {\n        while (isalnum(*identifier) || *identifier == '_') {\n            identifier++;\n        }\n    }\n    \n    char* toParen = identifier;\n    if (toParen == readHead) return NULL;\n    while (isspace(*toParen)) {\n        toParen++;\n    }\n    if (*toParen != '(') return NULL;\n    \n    ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \\\n                     - ((ptrdiff_t)readHead)+1;\n    char* const name = malloc(size);\n    if (!name) {\n        printf(\"Failed to allocate %lu bytes.\\n\", size);\n        abort();\n    }\n    name[size-1] = '\\0';\n    memcpy(name, readHead, size-1);\n    \n    if (strcmp(name, \"\")) {\n        return name;\n    }\n    free(name);\n    return NULL;\n}\nint main(int argc, char** argv)\n{\n    int i;\n    for (i = 1; i<argc; i++) {\n        errno = 0;\n        FILE* file = fopen(argv[i], \"r\");\n        if (errno || !file) {\n            printf(\"fopen() failed with error code \\\"%s\\\"\\n\", \\\n                   strerror(errno));\n            abort();\n        }\n        char comment = 0;\n#define DOUBLEQUOTE 1\n#define SINGLEQUOTE 2\n        int string = 0;\n        struct functionInfo* functions = NULL;\n        struct functionInfo toAdd;\n        size_t numElements = 0;\n        size_t allocatedSize = 0;\n        struct stat metaData;\n        errno = 0;\n        if (fstat(fileno(file), &metaData) < 0) {\n            printf(\"fstat() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \\\n                                          MAP_PRIVATE, fileno(file), 0);\n        if (errno) {\n            printf(\"mmap() failed with error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        if (!mmappedSource) {\n            printf(\"mmap() returned NULL.\\n\");\n            abort();\n        }\n        char* readHead = mmappedSource;\n        while (readHead < mmappedSource + metaData.st_size) {\n            while (*readHead) {\n                \n                if (!string) {\n                    if (*readHead == '/' && !strncmp(readHead, \"\", 2)) {\n                        comment = 0;\n                    }\n                }\n                \n                if (!comment) {\n                    if (*readHead == '\"') {\n                        if (!string) {\n                            string = DOUBLEQUOTE;\n                        } else if (string == DOUBLEQUOTE) {\n                            \n                            if (strncmp((readHead-1), \"\\\\\\\"\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                    if (*readHead == '\\'') {\n                        if (!string) {\n                            string = SINGLEQUOTE;\n                        } else if (string == SINGLEQUOTE) {\n                            if (strncmp((readHead-1), \"\\\\\\'\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                }\n                \n                if (!comment && !string) {\n                    char* name = extractFunctionName(readHead);\n                    \n                    if (name) {\n                        toAdd.name = name;\n                        addToList(&functions, toAdd, &numElements, &allocatedSize);\n                        readHead += strlen(name);\n                    }\n                    free(name);\n                }\n                readHead++;\n            }\n        }\n        errno = 0;\n        munmap(mmappedSource, metaData.st_size);\n        if (errno) {\n            printf(\"munmap() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        errno = 0;\n        fclose(file);\n        if (errno) {\n            printf(\"fclose() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        printList(&functions, numElements);\n        freeList(&functions, numElements);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"go/token\"\n    \"io/ioutil\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    if len(os.Args) != 2 {\n        fmt.Println(\"usage ff <go source filename>\")\n        return\n    }\n    src, err := ioutil.ReadFile(os.Args[1])\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fs := token.NewFileSet()\n    a, err := parser.ParseFile(fs, os.Args[1], src, 0)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f := fs.File(a.Pos())\n    m := make(map[string]int)\n    ast.Inspect(a, func(n ast.Node) bool {\n        if ce, ok := n.(*ast.CallExpr); ok {\n            start := f.Offset(ce.Pos())\n            end := f.Offset(ce.Lparen)\n            m[string(src[start:end])]++\n        }\n        return true\n    })\n    cs := make(calls, 0, len(m))\n    for k, v := range m {\n        cs = append(cs, &call{k, v})\n    }\n    sort.Sort(cs)\n    for i, c := range cs {\n        fmt.Printf(\"%-20s %4d\\n\", c.expr, c.count)\n        if i == 9 {\n            break\n        }\n    }\n}\n\ntype call struct {\n    expr  string\n    count int\n}\ntype calls []*call\n\nfunc (c calls) Len() int           { return len(c) }\nfunc (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c calls) Less(i, j int) bool { return c[i].count > c[j].count }\n"}
{"id": 53276, "name": "Function frequency", "C": "#define _POSIX_SOURCE\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <stddef.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\nstruct functionInfo {\n    char* name;\n    int timesCalled;\n    char marked;\n};\nvoid addToList(struct functionInfo** list, struct functionInfo toAdd, \\\n               size_t* numElements, size_t* allocatedSize)\n{\n    static const char* keywords[32] = {\"auto\", \"break\", \"case\", \"char\", \"const\", \\\n                                       \"continue\", \"default\", \"do\", \"double\", \\\n                                       \"else\", \"enum\", \"extern\", \"float\", \"for\", \\\n                                       \"goto\", \"if\", \"int\", \"long\", \"register\", \\\n                                       \"return\", \"short\", \"signed\", \"sizeof\", \\\n                                       \"static\", \"struct\", \"switch\", \"typedef\", \\\n                                       \"union\", \"unsigned\", \"void\", \"volatile\", \\\n                                       \"while\"\n                                      };\n    int i;\n    \n    for (i = 0; i < 32; i++) {\n        if (!strcmp(toAdd.name, keywords[i])) {\n            return;\n        }\n    }\n    if (!*list) {\n        *allocatedSize = 10;\n        *list = calloc(*allocatedSize, sizeof(struct functionInfo));\n        if (!*list) {\n            printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                   *allocatedSize, sizeof(struct functionInfo));\n            abort();\n        }\n        (*list)[0].name = malloc(strlen(toAdd.name)+1);\n        if (!(*list)[0].name) {\n            printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n            abort();\n        }\n        strcpy((*list)[0].name, toAdd.name);\n        (*list)[0].timesCalled = 1;\n        (*list)[0].marked = 0;\n        *numElements = 1;\n    } else {\n        char found = 0;\n        unsigned int i;\n        for (i = 0; i < *numElements; i++) {\n            if (!strcmp((*list)[i].name, toAdd.name)) {\n                found = 1;\n                (*list)[i].timesCalled++;\n                break;\n            }\n        }\n        if (!found) {\n            struct functionInfo* newList = calloc((*allocatedSize)+10, \\\n                                                  sizeof(struct functionInfo));\n            if (!newList) {\n                printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                       (*allocatedSize)+10, sizeof(struct functionInfo));\n                abort();\n            }\n            memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo));\n            free(*list);\n            *allocatedSize += 10;\n            *list = newList;\n            (*list)[*numElements].name = malloc(strlen(toAdd.name)+1);\n            if (!(*list)[*numElements].name) {\n                printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n                abort();\n            }\n            strcpy((*list)[*numElements].name, toAdd.name);\n            (*list)[*numElements].timesCalled = 1;\n            (*list)[*numElements].marked = 0;\n            (*numElements)++;\n        }\n    }\n}\nvoid printList(struct functionInfo** list, size_t numElements)\n{\n    char maxSet = 0;\n    unsigned int i;\n    size_t maxIndex = 0;\n    for (i = 0; i<10; i++) {\n        maxSet = 0;\n        size_t j;\n        for (j = 0; j<numElements; j++) {\n            if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) {\n                if (!(*list)[j].marked) {\n                    maxSet = 1;\n                    maxIndex = j;\n                }\n            }\n        }\n        (*list)[maxIndex].marked = 1;\n        printf(\"%s() called %d times.\\n\", (*list)[maxIndex].name, \\\n               (*list)[maxIndex].timesCalled);\n    }\n}\nvoid freeList(struct functionInfo** list, size_t numElements)\n{\n    size_t i;\n    for (i = 0; i<numElements; i++) {\n        free((*list)[i].name);\n    }\n    free(*list);\n}\nchar* extractFunctionName(char* readHead)\n{\n    char* identifier = readHead;\n    if (isalpha(*identifier) || *identifier == '_') {\n        while (isalnum(*identifier) || *identifier == '_') {\n            identifier++;\n        }\n    }\n    \n    char* toParen = identifier;\n    if (toParen == readHead) return NULL;\n    while (isspace(*toParen)) {\n        toParen++;\n    }\n    if (*toParen != '(') return NULL;\n    \n    ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \\\n                     - ((ptrdiff_t)readHead)+1;\n    char* const name = malloc(size);\n    if (!name) {\n        printf(\"Failed to allocate %lu bytes.\\n\", size);\n        abort();\n    }\n    name[size-1] = '\\0';\n    memcpy(name, readHead, size-1);\n    \n    if (strcmp(name, \"\")) {\n        return name;\n    }\n    free(name);\n    return NULL;\n}\nint main(int argc, char** argv)\n{\n    int i;\n    for (i = 1; i<argc; i++) {\n        errno = 0;\n        FILE* file = fopen(argv[i], \"r\");\n        if (errno || !file) {\n            printf(\"fopen() failed with error code \\\"%s\\\"\\n\", \\\n                   strerror(errno));\n            abort();\n        }\n        char comment = 0;\n#define DOUBLEQUOTE 1\n#define SINGLEQUOTE 2\n        int string = 0;\n        struct functionInfo* functions = NULL;\n        struct functionInfo toAdd;\n        size_t numElements = 0;\n        size_t allocatedSize = 0;\n        struct stat metaData;\n        errno = 0;\n        if (fstat(fileno(file), &metaData) < 0) {\n            printf(\"fstat() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \\\n                                          MAP_PRIVATE, fileno(file), 0);\n        if (errno) {\n            printf(\"mmap() failed with error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        if (!mmappedSource) {\n            printf(\"mmap() returned NULL.\\n\");\n            abort();\n        }\n        char* readHead = mmappedSource;\n        while (readHead < mmappedSource + metaData.st_size) {\n            while (*readHead) {\n                \n                if (!string) {\n                    if (*readHead == '/' && !strncmp(readHead, \"\", 2)) {\n                        comment = 0;\n                    }\n                }\n                \n                if (!comment) {\n                    if (*readHead == '\"') {\n                        if (!string) {\n                            string = DOUBLEQUOTE;\n                        } else if (string == DOUBLEQUOTE) {\n                            \n                            if (strncmp((readHead-1), \"\\\\\\\"\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                    if (*readHead == '\\'') {\n                        if (!string) {\n                            string = SINGLEQUOTE;\n                        } else if (string == SINGLEQUOTE) {\n                            if (strncmp((readHead-1), \"\\\\\\'\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                }\n                \n                if (!comment && !string) {\n                    char* name = extractFunctionName(readHead);\n                    \n                    if (name) {\n                        toAdd.name = name;\n                        addToList(&functions, toAdd, &numElements, &allocatedSize);\n                        readHead += strlen(name);\n                    }\n                    free(name);\n                }\n                readHead++;\n            }\n        }\n        errno = 0;\n        munmap(mmappedSource, metaData.st_size);\n        if (errno) {\n            printf(\"munmap() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        errno = 0;\n        fclose(file);\n        if (errno) {\n            printf(\"fclose() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        printList(&functions, numElements);\n        freeList(&functions, numElements);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"go/token\"\n    \"io/ioutil\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    if len(os.Args) != 2 {\n        fmt.Println(\"usage ff <go source filename>\")\n        return\n    }\n    src, err := ioutil.ReadFile(os.Args[1])\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fs := token.NewFileSet()\n    a, err := parser.ParseFile(fs, os.Args[1], src, 0)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f := fs.File(a.Pos())\n    m := make(map[string]int)\n    ast.Inspect(a, func(n ast.Node) bool {\n        if ce, ok := n.(*ast.CallExpr); ok {\n            start := f.Offset(ce.Pos())\n            end := f.Offset(ce.Lparen)\n            m[string(src[start:end])]++\n        }\n        return true\n    })\n    cs := make(calls, 0, len(m))\n    for k, v := range m {\n        cs = append(cs, &call{k, v})\n    }\n    sort.Sort(cs)\n    for i, c := range cs {\n        fmt.Printf(\"%-20s %4d\\n\", c.expr, c.count)\n        if i == 9 {\n            break\n        }\n    }\n}\n\ntype call struct {\n    expr  string\n    count int\n}\ntype calls []*call\n\nfunc (c calls) Len() int           { return len(c) }\nfunc (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c calls) Less(i, j int) bool { return c[i].count > c[j].count }\n"}
{"id": 53277, "name": "Unicode strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n", "Go": "    var i int\n    var u rune\n    for i, u = range \"voilà\" {\n        fmt.Println(i, u)\n    }\n"}
{"id": 53278, "name": "Unicode strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n", "Go": "    var i int\n    var u rune\n    for i, u = range \"voilà\" {\n        fmt.Println(i, u)\n    }\n"}
{"id": 53279, "name": "Bitmap_Read an image through a pipe", "C": "image read_image(const char *name);\n", "Go": "package main\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    c := exec.Command(\"convert\", \"Unfilledcirc.png\", \"-depth\", \"1\", \"ppm:-\")\n    pipe, err := c.StdoutPipe()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = c.Start(); err != nil {\n        log.Fatal(err)\n    }\n    b, err := raster.ReadPpmFrom(pipe)\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = b.WritePpmFile(\"Unfilledcirc.ppm\"); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53280, "name": "Starting a web browser", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\n\n\nvoid C_fileAllocate(WrenVM* vm) {\n    FILE** pfp = (FILE**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(FILE*));\n    const char *filename = wrenGetSlotString(vm, 1);\n    const char *mode = wrenGetSlotString(vm, 2);\n    *pfp = fopen(filename, mode);\n}\n\nvoid C_write(WrenVM* vm) {\n    FILE* fp = *(FILE**)wrenGetSlotForeign(vm, 0);\n    const char *s = wrenGetSlotString(vm, 1);\n    fputs(s, fp);\n}\n\nvoid C_close(WrenVM* vm) {\n    FILE* fp = *(FILE**)wrenGetSlotForeign(vm, 0);\n    fclose(fp);\n}\n\nvoid C_remove(WrenVM* vm) {\n    const char *filename = wrenGetSlotString(vm, 1);\n    remove(filename);\n}\n\nvoid C_flushAll(WrenVM* vm) {\n    fflush(NULL);\n}\n\nvoid C_system(WrenVM* vm) {\n    const char *s = wrenGetSlotString(vm, 1);\n    system(s);\n}\n\nvoid C_sleep(WrenVM* vm) {\n    int seconds = (int)wrenGetSlotDouble(vm, 1);\n    sleep(seconds);\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"File\") == 0) {\n            methods.allocate = C_fileAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"File\") == 0) {\n            if (!isStatic && strcmp(signature, \"write(_)\") == 0)   return C_write;\n            if (!isStatic && strcmp(signature, \"close()\") == 0)    return C_close;\n            if ( isStatic && strcmp(signature, \"remove(_)\") == 0)  return C_remove;\n            if ( isStatic && strcmp(signature, \"flushAll()\") == 0) return C_flushAll;\n        } else if (strcmp(className, \"C\") == 0) {\n            if ( isStatic && strcmp(signature, \"system(_)\") == 0)  return C_system;\n            if ( isStatic && strcmp(signature, \"sleep(_)\") == 0)   return C_sleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"starting_web_browser.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"html/template\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strings\"\n    \"time\"\n)\n\ntype row struct {\n    Address, Street, House, Color string\n}\n\nfunc isDigit(b byte) bool {\n    return '0' <= b && b <= '9'\n}\n\nfunc separateHouseNumber(address string) (street string, house string) {\n    length := len(address)\n    fields := strings.Fields(address)\n    size := len(fields)\n    last := fields[size-1]\n    penult := fields[size-2]\n    if isDigit(last[0]) {\n        isdig := isDigit(penult[0])\n        if size > 2 && isdig && !strings.HasPrefix(penult, \"194\") {\n            house = fmt.Sprintf(\"%s %s\", penult, last)\n        } else {\n            house = last\n        }\n    } else if size > 2 {\n        house = fmt.Sprintf(\"%s %s\", penult, last)\n    }\n    street = strings.TrimRight(address[:length-len(house)], \" \")\n    return\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nvar tmpl = `\n<head>\n  <title>Rosetta Code - Start a Web Browser</title>\n  <meta charset=\"UTF-8\">\n</head>\n<body bgcolor=\"#d8dcd6\">\n  <table border=\"2\">\n    <p align=\"center\">\n      <font face=\"Arial, sans-serif\" size=\"5\">Split the house number from the street name</font>    \n      <tr bgcolor=\"#02ccfe\"><th>Address</th><th>Street</th><th>House Number</th></tr>\n      {{range $row := .}}\n      <tr bgcolor={{$row.Color}}>         \n        <td>{{$row.Address}}</td>\n        <td>{{$row.Street}}</td>\n        <td>{{$row.House}}</td>\n      </tr>\n      {{end}}\n    </p>\n  </table>\n</body>\n`\nfunc main() {\n    addresses := []string{\n        \"Plataanstraat 5\",\n        \"Straat 12\",\n        \"Straat 12 II\",\n        \"Dr. J. Straat   12\",\n        \"Dr. J. Straat 12 a\",\n        \"Dr. J. Straat 12-14\",\n        \"Laan 1940 - 1945 37\",\n        \"Plein 1940 2\",\n        \"1213-laan 11\",\n        \"16 april 1944 Pad 1\",\n        \"1e Kruisweg 36\",\n        \"Laan 1940-'45 66\",\n        \"Laan '40-'45\",\n        \"Langeloërduinen 3 46\",\n        \"Marienwaerdt 2e Dreef 2\",\n        \"Provincialeweg N205 1\",\n        \"Rivium 2e Straat 59.\",\n        \"Nieuwe gracht 20rd\",\n        \"Nieuwe gracht 20rd 2\",\n        \"Nieuwe gracht 20zw /2\",\n        \"Nieuwe gracht 20zw/3\",\n        \"Nieuwe gracht 20 zw/4\",\n        \"Bahnhofstr. 4\",\n        \"Wertstr. 10\",\n        \"Lindenhof 1\",\n        \"Nordesch 20\",\n        \"Weilstr. 6\",\n        \"Harthauer Weg 2\",\n        \"Mainaustr. 49\",\n        \"August-Horch-Str. 3\",\n        \"Marktplatz 31\",\n        \"Schmidener Weg 3\",\n        \"Karl-Weysser-Str. 6\",\n    }\n    browser := \"firefox\" \n    colors := [2]string{\"#d7fffe\", \"#9dbcd4\"}\n    fileName := \"addresses_table.html\"\n    ct := template.Must(template.New(\"\").Parse(tmpl))\n    file, err := os.Create(fileName)\n    check(err)\n    rows := make([]row, len(addresses))\n    for i, address := range addresses {\n        street, house := separateHouseNumber(address)\n        if house == \"\" {\n            house = \"(none)\"\n        }\n        color := colors[i%2]\n        rows[i] = row{address, street, house, color}\n    }   \n    err = ct.Execute(file, rows)\n    check(err)\n    cmd := exec.Command(browser, fileName)\n    err = cmd.Run()\n    check(err)\n    file.Close()\n    time.Sleep(5 * time.Second) \n    err = os.Remove(fileName)\n    check(err)\n}\n"}
{"id": 53281, "name": "Memory layout of a data structure", "C": "struct RS232_data\n{\n  unsigned carrier_detect        : 1;\n  unsigned received_data         : 1;\n  unsigned transmitted_data      : 1;\n  unsigned data_terminal_ready   : 1;\n  unsigned signal_ground         : 1;\n  unsigned data_set_ready        : 1;\n  unsigned request_to_send       : 1;\n  unsigned clear_to_send         : 1;\n  unsigned ring_indicator        : 1;\n};\n", "Go": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9  rs232p9 = 1 << iota \n\tRD9                      \n\tTD9                      \n\tDTR9                     \n\tSG9                      \n\tDSR9                     \n\tRTS9                     \n\tCTS9                     \n\tRI9                      \n)\n\nfunc main() {\n\t\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}\n"}
{"id": 53282, "name": "Sum of primes in odd positions is prime", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n   int s=0, p, i=1;\n   for(p=2;p<=999;p++) {\n       if(isprime(p)) {\n           if(i%2) {\n               s+=p;\n               if(isprime(s)) printf( \"%d       %d       %d\\n\", i, p, s );\n           }\n           i+=1;\n       }\n   }\n   return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum := 0\n    fmt.Println(\" i   p[i]  Σp[i]\")\n    fmt.Println(\"----------------\")\n    for i := 0; i < len(primes); i += 2 {\n        sum += primes[i]\n        if rcu.IsPrime(sum) {\n            fmt.Printf(\"%3d  %3d  %6s\\n\", i+1, primes[i], rcu.Commatize(sum))\n        }\n    }\n}\n"}
{"id": 53283, "name": "Sum of primes in odd positions is prime", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n   int s=0, p, i=1;\n   for(p=2;p<=999;p++) {\n       if(isprime(p)) {\n           if(i%2) {\n               s+=p;\n               if(isprime(s)) printf( \"%d       %d       %d\\n\", i, p, s );\n           }\n           i+=1;\n       }\n   }\n   return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum := 0\n    fmt.Println(\" i   p[i]  Σp[i]\")\n    fmt.Println(\"----------------\")\n    for i := 0; i < len(primes); i += 2 {\n        sum += primes[i]\n        if rcu.IsPrime(sum) {\n            fmt.Printf(\"%3d  %3d  %6s\\n\", i+1, primes[i], rcu.Commatize(sum))\n        }\n    }\n}\n"}
{"id": 53284, "name": "Sum of primes in odd positions is prime", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n   int s=0, p, i=1;\n   for(p=2;p<=999;p++) {\n       if(isprime(p)) {\n           if(i%2) {\n               s+=p;\n               if(isprime(s)) printf( \"%d       %d       %d\\n\", i, p, s );\n           }\n           i+=1;\n       }\n   }\n   return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum := 0\n    fmt.Println(\" i   p[i]  Σp[i]\")\n    fmt.Println(\"----------------\")\n    for i := 0; i < len(primes); i += 2 {\n        sum += primes[i]\n        if rcu.IsPrime(sum) {\n            fmt.Printf(\"%3d  %3d  %6s\\n\", i+1, primes[i], rcu.Commatize(sum))\n        }\n    }\n}\n"}
{"id": 53285, "name": "Sum of two adjacent numbers are primes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nvoid primeSieve(int *c, int limit, bool processEven, bool primesOnly) {\n    int i, ix, p, p2;\n    limit++;\n    c[0] = TRUE;\n    c[1] = TRUE;\n    if (processEven) {\n        for (i = 4; i < limit; i +=2) c[i] = TRUE;\n    }\n    p = 3;\n    while (TRUE) {\n        p2 = p * p;\n        if (p2 >= limit) break;\n        for (i = p2; i < limit; i += 2*p) c[i] = TRUE;\n        while (TRUE) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    if (primesOnly) {\n        \n        c[0] = 2;\n        for (i = 3, ix = 1; i < limit; i += 2) {\n            if (!c[i]) c[ix++] = i;\n        }\n    }\n}\n\nint main() {\n    int i, p, hp, n = 10000000;\n    int limit = (int)(log(n) * (double)n * 1.2);  \n    int *primes = (int *)calloc(limit, sizeof(int));\n    primeSieve(primes, limit-1, FALSE, TRUE);\n    printf(\"The first 20 pairs of natural numbers whose sum is prime are:\\n\");\n    for (i = 1; i <= 20; ++i) {\n        p = primes[i];\n        hp = p / 2;\n        printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    }\n    printf(\"\\nThe 10 millionth such pair is:\\n\");\n    p = primes[n];\n    hp = p / 2;\n    printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    free(primes);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(math.Log(1e7) * 1e7 * 1.2) \n    primes := rcu.Primes(limit)\n    fmt.Println(\"The first 20 pairs of natural numbers whose sum is prime are:\")\n    for i := 1; i <= 20; i++ {\n        p := primes[i]\n        hp := p / 2\n        fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n    }\n    fmt.Println(\"\\nThe 10 millionth such pair is:\")\n    p := primes[1e7]\n    hp := p / 2\n    fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n}\n"}
{"id": 53286, "name": "Square form factorization", "C": "#include <math.h>\n#include <stdio.h>\n\n#define nelems(x) (sizeof(x) / sizeof((x)[0]))\n\nconst unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11};\n\nunsigned long long gcd(unsigned long long a, unsigned long long b)\n{\n    while (b != 0)\n    {\n        a %= b;\n        a ^= b;\n        b ^= a;\n        a ^= b;\n    }\n\n    return a;\n}\n\nunsigned long long SQUFOF( unsigned long long N )\n{\n    unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s;\n    unsigned long L, B, i;\n    s = (unsigned long long)(sqrtl(N)+0.5);\n    if (s*s == N) return s;\n    for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) {\n        D = multiplier[k]*N;\n        Po = Pprev = P = sqrtl(D);\n        Qprev = 1;\n        Q = D - Po*Po;\n        L = 2 * sqrtl( 2*s );\n        B = 3 * L;\n        for (i = 2 ; i < B ; i++) {\n            b = (unsigned long long)((Po + P)/Q);\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            r = (unsigned long long)(sqrtl(Q)+0.5);\n            if (!(i & 1) && r*r == Q) break;\n            Qprev = q;\n            Pprev = P;\n        };\n        if (i >= B) continue;\n        b = (unsigned long long)((Po - P)/r);\n        Pprev = P = b*r + P;\n        Qprev = r;\n        Q = (D - Pprev*Pprev)/Qprev;\n        i = 0;\n        do {\n            b = (unsigned long long)((Po + P)/Q);\n            Pprev = P;\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            Qprev = q;\n            i++;\n        } while (P != Pprev);\n        r = gcd(N, Qprev);\n        if (r != 1 && r != N) return r;\n    }\n    return 0;\n}\n\nint main(int argc, char *argv[]) {\n    int i;\n    const unsigned long long data[] = {\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877};\n\n    for(int i = 0; i < nelems(data); i++) {\n        unsigned long long example, factor, quotient;\n        example = data[i];\n        factor = SQUFOF(example);\n        if(factor == 0) {\n            printf(\"%llu was not factored.\\n\", example);\n        }\n        else {\n            quotient = example / factor;\n            printf(\"Integer %llu has factors %llu and %llu\\n\",\n               example, factor, quotient); \n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc isqrt(x uint64) uint64 {\n    x0 := x >> 1\n    x1 := (x0 + x/x0) >> 1\n    for x1 < x0 {\n        x0 = x1\n        x1 = (x0 + x/x0) >> 1\n    }\n    return x0\n}\n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nvar multiplier = []uint64{\n    1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11,\n}\n\nfunc squfof(N uint64) uint64 {\n    s := uint64(math.Sqrt(float64(N)) + 0.5)\n    if s*s == N {\n        return s\n    }\n    for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ {\n        D := multiplier[k] * N\n        P := isqrt(D)\n        Pprev := P\n        Po := Pprev\n        Qprev := uint64(1)\n        Q := D - Po*Po\n        L := uint32(isqrt(8 * s))\n        B := 3 * L\n        i := uint32(2)\n        var b, q, r uint64\n        for ; i < B; i++ {\n            b = uint64((Po + P) / Q)\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            r = uint64(math.Sqrt(float64(Q)) + 0.5)\n            if (i&1) == 0 && r*r == Q {\n                break\n            }\n            Qprev = q\n            Pprev = P\n        }\n        if i >= B {\n            continue\n        }\n        b = uint64((Po - P) / r)\n        P = b*r + P\n        Pprev = P\n        Qprev = r\n        Q = (D - Pprev*Pprev) / Qprev\n        i = 0\n        for {\n            b = uint64((Po + P) / Q)\n            Pprev = P\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            Qprev = q\n            i++\n            if P == Pprev {\n                break\n            }\n        }\n        r = gcd(N, Qprev)\n        if r != 1 && r != N {\n            return r\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    examples := []uint64{\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877,\n    }\n    fmt.Println(\"Integer              Factor     Quotient\")\n    fmt.Println(\"------------------------------------------\")\n    for _, N := range examples {\n        fact := squfof(N)\n        quot := \"fail\"\n        if fact > 0 {\n            quot = fmt.Sprintf(\"%d\", N/fact)\n        }\n        fmt.Printf(\"%-20d %-10d %s\\n\", N, fact, quot)\n    }\n}\n"}
{"id": 53287, "name": "Square form factorization", "C": "#include <math.h>\n#include <stdio.h>\n\n#define nelems(x) (sizeof(x) / sizeof((x)[0]))\n\nconst unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11};\n\nunsigned long long gcd(unsigned long long a, unsigned long long b)\n{\n    while (b != 0)\n    {\n        a %= b;\n        a ^= b;\n        b ^= a;\n        a ^= b;\n    }\n\n    return a;\n}\n\nunsigned long long SQUFOF( unsigned long long N )\n{\n    unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s;\n    unsigned long L, B, i;\n    s = (unsigned long long)(sqrtl(N)+0.5);\n    if (s*s == N) return s;\n    for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) {\n        D = multiplier[k]*N;\n        Po = Pprev = P = sqrtl(D);\n        Qprev = 1;\n        Q = D - Po*Po;\n        L = 2 * sqrtl( 2*s );\n        B = 3 * L;\n        for (i = 2 ; i < B ; i++) {\n            b = (unsigned long long)((Po + P)/Q);\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            r = (unsigned long long)(sqrtl(Q)+0.5);\n            if (!(i & 1) && r*r == Q) break;\n            Qprev = q;\n            Pprev = P;\n        };\n        if (i >= B) continue;\n        b = (unsigned long long)((Po - P)/r);\n        Pprev = P = b*r + P;\n        Qprev = r;\n        Q = (D - Pprev*Pprev)/Qprev;\n        i = 0;\n        do {\n            b = (unsigned long long)((Po + P)/Q);\n            Pprev = P;\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            Qprev = q;\n            i++;\n        } while (P != Pprev);\n        r = gcd(N, Qprev);\n        if (r != 1 && r != N) return r;\n    }\n    return 0;\n}\n\nint main(int argc, char *argv[]) {\n    int i;\n    const unsigned long long data[] = {\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877};\n\n    for(int i = 0; i < nelems(data); i++) {\n        unsigned long long example, factor, quotient;\n        example = data[i];\n        factor = SQUFOF(example);\n        if(factor == 0) {\n            printf(\"%llu was not factored.\\n\", example);\n        }\n        else {\n            quotient = example / factor;\n            printf(\"Integer %llu has factors %llu and %llu\\n\",\n               example, factor, quotient); \n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc isqrt(x uint64) uint64 {\n    x0 := x >> 1\n    x1 := (x0 + x/x0) >> 1\n    for x1 < x0 {\n        x0 = x1\n        x1 = (x0 + x/x0) >> 1\n    }\n    return x0\n}\n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nvar multiplier = []uint64{\n    1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11,\n}\n\nfunc squfof(N uint64) uint64 {\n    s := uint64(math.Sqrt(float64(N)) + 0.5)\n    if s*s == N {\n        return s\n    }\n    for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ {\n        D := multiplier[k] * N\n        P := isqrt(D)\n        Pprev := P\n        Po := Pprev\n        Qprev := uint64(1)\n        Q := D - Po*Po\n        L := uint32(isqrt(8 * s))\n        B := 3 * L\n        i := uint32(2)\n        var b, q, r uint64\n        for ; i < B; i++ {\n            b = uint64((Po + P) / Q)\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            r = uint64(math.Sqrt(float64(Q)) + 0.5)\n            if (i&1) == 0 && r*r == Q {\n                break\n            }\n            Qprev = q\n            Pprev = P\n        }\n        if i >= B {\n            continue\n        }\n        b = uint64((Po - P) / r)\n        P = b*r + P\n        Pprev = P\n        Qprev = r\n        Q = (D - Pprev*Pprev) / Qprev\n        i = 0\n        for {\n            b = uint64((Po + P) / Q)\n            Pprev = P\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            Qprev = q\n            i++\n            if P == Pprev {\n                break\n            }\n        }\n        r = gcd(N, Qprev)\n        if r != 1 && r != N {\n            return r\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    examples := []uint64{\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877,\n    }\n    fmt.Println(\"Integer              Factor     Quotient\")\n    fmt.Println(\"------------------------------------------\")\n    for _, N := range examples {\n        fact := squfof(N)\n        quot := \"fail\"\n        if fact > 0 {\n            quot = fmt.Sprintf(\"%d\", N/fact)\n        }\n        fmt.Printf(\"%-20d %-10d %s\\n\", N, fact, quot)\n    }\n}\n"}
{"id": 53288, "name": "Pinstripe_Printer", "C": "\n\n#include <stdlib.h>\n#include <string.h>\n#include \"dome.h\"\n\nstatic DOME_API_v0* core;\nstatic WREN_API_v0* wren;\n\nstatic const char* source =  \"\"\n\"class Printer {\\n\" \n  \"foreign static printFile(name) \\n\"\n\"} \\n\";\n\nvoid C_printFile(WrenVM* vm) {\n    const char *arg = wren->getSlotString(vm, 1);\n    char command[strlen(arg) + 4];\n    strcpy(command, \"lp \");\n    strcat(command, arg);\n    int res = system(command);\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) {\n    core = DOME_getAPI(API_DOME, DOME_API_VERSION);\n    wren = DOME_getAPI(API_WREN, WREN_API_VERSION);\n    core->registerModule(ctx, \"printer\", source);\n    core->registerClass(ctx, \"printer\", \"Printer\", NULL, NULL);\n    core->registerFn(ctx, \"printer\", \"static Printer.printFile(_)\", C_printFile);\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n", "Go": "package main\n \nimport (\n    \"github.com/fogleman/gg\"\n    \"log\"\n    \"os/exec\"\n    \"runtime\"\n)\n\nvar palette = [2]string{\n    \"FFFFFF\", \n    \"000000\", \n}\n \nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 7\n    for b := 1; b <= 11; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%2])\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(842, 595)\n    pinstripe(dc)\n    fileName := \"w_pinstripe.png\"\n    dc.SavePNG(fileName)\n    var cmd *exec.Cmd\n    if runtime.GOOS == \"windows\" {\n        cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n    } else {\n        cmd = exec.Command(\"lp\", fileName)\n    }\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53289, "name": "Pinstripe_Printer", "C": "\n\n#include <stdlib.h>\n#include <string.h>\n#include \"dome.h\"\n\nstatic DOME_API_v0* core;\nstatic WREN_API_v0* wren;\n\nstatic const char* source =  \"\"\n\"class Printer {\\n\" \n  \"foreign static printFile(name) \\n\"\n\"} \\n\";\n\nvoid C_printFile(WrenVM* vm) {\n    const char *arg = wren->getSlotString(vm, 1);\n    char command[strlen(arg) + 4];\n    strcpy(command, \"lp \");\n    strcat(command, arg);\n    int res = system(command);\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) {\n    core = DOME_getAPI(API_DOME, DOME_API_VERSION);\n    wren = DOME_getAPI(API_WREN, WREN_API_VERSION);\n    core->registerModule(ctx, \"printer\", source);\n    core->registerClass(ctx, \"printer\", \"Printer\", NULL, NULL);\n    core->registerFn(ctx, \"printer\", \"static Printer.printFile(_)\", C_printFile);\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n", "Go": "package main\n \nimport (\n    \"github.com/fogleman/gg\"\n    \"log\"\n    \"os/exec\"\n    \"runtime\"\n)\n\nvar palette = [2]string{\n    \"FFFFFF\", \n    \"000000\", \n}\n \nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 7\n    for b := 1; b <= 11; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%2])\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(842, 595)\n    pinstripe(dc)\n    fileName := \"w_pinstripe.png\"\n    dc.SavePNG(fileName)\n    var cmd *exec.Cmd\n    if runtime.GOOS == \"windows\" {\n        cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n    } else {\n        cmd = exec.Command(\"lp\", fileName)\n    }\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 53290, "name": "Catmull–Clark subdivision surface", "C": "vertex face_point(face f)\n{\n\tint i;\n\tvertex v;\n\n\tif (!f->avg) {\n\t\tf->avg = vertex_new();\n\t\tforeach(i, v, f->v)\n\t\t\tif (!i) f->avg->pos = v->pos;\n\t\t\telse    vadd(f->avg->pos, v->pos);\n\n\t\tvdiv(f->avg->pos, len(f->v));\n\t}\n\treturn f->avg;\n}\n\n#define hole_edge(e) (len(e->f)==1)\nvertex edge_point(edge e)\n{\n\tint i;\n\tface f;\n\n\tif (!e->e_pt) {\n\t\te->e_pt = vertex_new();\n\t\te->avg = e->v[0]->pos;\n\t\tvadd(e->avg, e->v[1]->pos);\n\t\te->e_pt->pos = e->avg;\n\n\t\tif (!hole_edge(e)) {\n\t\t\tforeach (i, f, e->f)\n\t\t\t\tvadd(e->e_pt->pos, face_point(f)->pos);\n\t\t\tvdiv(e->e_pt->pos, 4);\n\t\t} else\n\t\t\tvdiv(e->e_pt->pos, 2);\n\n\t\tvdiv(e->avg, 2);\n\t}\n\n\treturn e->e_pt;\n}\n\n#define hole_vertex(v) (len((v)->f) != len((v)->e))\nvertex updated_point(vertex v)\n{\n\tint i, n = 0;\n\tedge e;\n\tface f;\n\tcoord_t sum = {0, 0, 0};\n\n\tif (v->v_new) return v->v_new;\n\n\tv->v_new = vertex_new();\n\tif (hole_vertex(v)) {\n\t\tv->v_new->pos = v->pos;\n\t\tforeach(i, e, v->e) {\n\t\t\tif (!hole_edge(e)) continue;\n\t\t\tvadd(v->v_new->pos, edge_point(e)->pos);\n\t\t\tn++;\n\t\t}\n\t\tvdiv(v->v_new->pos, n + 1);\n\t} else {\n\t\tn = len(v->f);\n\t\tforeach(i, f, v->f)\n\t\t\tvadd(sum, face_point(f)->pos);\n\t\tforeach(i, e, v->e)\n\t\t\tvmadd(sum, edge_point(e)->pos, 2, sum);\n\t\tvdiv(sum, n);\n\t\tvmadd(sum, v->pos, n - 3, sum);\n\t\tvdiv(sum, n);\n\t\tv->v_new->pos = sum;\n\t}\n\n\treturn v->v_new;\n}\n\nmodel catmull(model m)\n{\n\tint i, j, a, b, c, d;\n\tface f;\n\tvertex v, x;\n\n\tmodel nm = model_new();\n\tforeach (i, f, m->f) {\n\t\tforeach(j, v, f->v) {\n\t\t\t_get_idx(a, updated_point(v));\n\t\t\t_get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e))));\n\t\t\t_get_idx(c, face_point(f));\n\t\t\t_get_idx(d, edge_point(elem(f->e, j)));\n\t\t\tmodel_add_face(nm, 4, a, b, c, d);\n\t\t}\n\t}\n\treturn nm;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype (\n    Point [3]float64\n    Face  []int\n\n    Edge struct {\n        pn1 int   \n        pn2 int   \n        fn1 int   \n        fn2 int   \n        cp  Point \n    }\n\n    PointEx struct {\n        p Point\n        n int\n    }\n)\n\nfunc sumPoint(p1, p2 Point) Point {\n    sp := Point{}\n    for i := 0; i < 3; i++ {\n        sp[i] = p1[i] + p2[i]\n    }\n    return sp\n}\n\nfunc mulPoint(p Point, m float64) Point {\n    mp := Point{}\n    for i := 0; i < 3; i++ {\n        mp[i] = p[i] * m\n    }\n    return mp\n}\n\nfunc divPoint(p Point, d float64) Point {\n    return mulPoint(p, 1.0/d)\n}\n\nfunc centerPoint(p1, p2 Point) Point {\n    return divPoint(sumPoint(p1, p2), 2)\n}\n\nfunc getFacePoints(inputPoints []Point, inputFaces []Face) []Point {\n    facePoints := make([]Point, len(inputFaces))\n    for i, currFace := range inputFaces {\n        facePoint := Point{}\n        for _, cpi := range currFace {\n            currPoint := inputPoints[cpi]\n            facePoint = sumPoint(facePoint, currPoint)\n        }\n        facePoint = divPoint(facePoint, float64(len(currFace)))\n        facePoints[i] = facePoint\n    }\n    return facePoints\n}\n\nfunc getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge {\n    var edges [][3]int\n    for faceNum, face := range inputFaces {\n        numPoints := len(face)\n        for pointIndex := 0; pointIndex < numPoints; pointIndex++ {\n            pointNum1 := face[pointIndex]\n            var pointNum2 int\n            if pointIndex < numPoints-1 {\n                pointNum2 = face[pointIndex+1]\n            } else {\n                pointNum2 = face[0]\n            }\n            if pointNum1 > pointNum2 {\n                pointNum1, pointNum2 = pointNum2, pointNum1\n            }\n            edges = append(edges, [3]int{pointNum1, pointNum2, faceNum})\n        }\n    }\n    sort.Slice(edges, func(i, j int) bool {\n        if edges[i][0] == edges[j][0] {\n            if edges[i][1] == edges[j][1] {\n                return edges[i][2] < edges[j][2]\n            }\n            return edges[i][1] < edges[j][1]\n        }\n        return edges[i][0] < edges[j][0]\n    })\n    numEdges := len(edges)\n    eIndex := 0\n    var mergedEdges [][4]int\n    for eIndex < numEdges {\n        e1 := edges[eIndex]\n        if eIndex < numEdges-1 {\n            e2 := edges[eIndex+1]\n            if e1[0] == e2[0] && e1[1] == e2[1] {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]})\n                eIndex += 2\n            } else {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n                eIndex++\n            }\n        } else {\n            mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n            eIndex++\n        }\n    }\n    var edgesCenters []Edge\n    for _, me := range mergedEdges {\n        p1 := inputPoints[me[0]]\n        p2 := inputPoints[me[1]]\n        cp := centerPoint(p1, p2)\n        edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp})\n    }\n    return edgesCenters\n}\n\nfunc getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point {\n    edgePoints := make([]Point, len(edgesFaces))\n    for i, edge := range edgesFaces {\n        cp := edge.cp\n        fp1 := facePoints[edge.fn1]\n        var fp2 Point\n        if edge.fn2 == -1 {\n            fp2 = fp1\n        } else {\n            fp2 = facePoints[edge.fn2]\n        }\n        cfp := centerPoint(fp1, fp2)\n        edgePoints[i] = centerPoint(cp, cfp)\n    }\n    return edgePoints\n}\n\nfunc getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for faceNum := range inputFaces {\n        fp := facePoints[faceNum]\n        for _, pointNum := range inputFaces[faceNum] {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, fp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgFacePoints := make([]Point, numPoints)\n    for i, tp := range tempPoints {\n        avgFacePoints[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgFacePoints\n}\n\nfunc getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for _, edge := range edgesFaces {\n        cp := edge.cp\n        for _, pointNum := range []int{edge.pn1, edge.pn2} {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, cp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgMidEdges := make([]Point, len(tempPoints))\n    for i, tp := range tempPoints {\n        avgMidEdges[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgMidEdges\n}\n\nfunc getPointsFaces(inputPoints []Point, inputFaces []Face) []int {\n    numPoints := len(inputPoints)\n    pointsFaces := make([]int, numPoints)\n    for faceNum := range inputFaces {\n        for _, pointNum := range inputFaces[faceNum] {\n            pointsFaces[pointNum]++\n        }\n    }\n    return pointsFaces\n}\n\nfunc getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point {\n    newPoints := make([]Point, len(inputPoints))\n    for pointNum := range inputPoints {\n        n := float64(pointsFaces[pointNum])\n        m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n\n        oldCoords := inputPoints[pointNum]\n        p1 := mulPoint(oldCoords, m1)\n        afp := avgFacePoints[pointNum]\n        p2 := mulPoint(afp, m2)\n        ame := avgMidEdges[pointNum]\n        p3 := mulPoint(ame, m3)\n        p4 := sumPoint(p1, p2)\n        newPoints[pointNum] = sumPoint(p4, p3)\n    }\n    return newPoints\n}\n\nfunc switchNums(pointNums [2]int) [2]int {\n    if pointNums[0] < pointNums[1] {\n        return pointNums\n    }\n    return [2]int{pointNums[1], pointNums[0]}\n}\n\nfunc cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) {\n    facePoints := getFacePoints(inputPoints, inputFaces)\n    edgesFaces := getEdgesFaces(inputPoints, inputFaces)\n    edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints)\n    avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints)\n    avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces)\n    pointsFaces := getPointsFaces(inputPoints, inputFaces)\n    newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n    var facePointNums []int\n    nextPointNum := len(newPoints)\n    for _, facePoint := range facePoints {\n        newPoints = append(newPoints, facePoint)\n        facePointNums = append(facePointNums, nextPointNum)\n        nextPointNum++\n    }\n    edgePointNums := make(map[[2]int]int)\n    for edgeNum := range edgesFaces {\n        pointNum1 := edgesFaces[edgeNum].pn1\n        pointNum2 := edgesFaces[edgeNum].pn2\n        edgePoint := edgePoints[edgeNum]\n        newPoints = append(newPoints, edgePoint)\n        edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum\n        nextPointNum++\n    }\n    var newFaces []Face\n    for oldFaceNum, oldFace := range inputFaces {\n        if len(oldFace) == 4 {\n            a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3]\n            facePointAbcd := facePointNums[oldFaceNum]\n            edgePointAb := edgePointNums[switchNums([2]int{a, b})]\n            edgePointDa := edgePointNums[switchNums([2]int{d, a})]\n            edgePointBc := edgePointNums[switchNums([2]int{b, c})]\n            edgePointCd := edgePointNums[switchNums([2]int{c, d})]\n            newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa})\n            newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb})\n            newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc})\n            newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd})\n        }\n    }\n    return newPoints, newFaces\n}\n\nfunc main() {\n    inputPoints := []Point{\n        {-1.0, 1.0, 1.0},\n        {-1.0, -1.0, 1.0},\n        {1.0, -1.0, 1.0},\n        {1.0, 1.0, 1.0},\n        {1.0, -1.0, -1.0},\n        {1.0, 1.0, -1.0},\n        {-1.0, -1.0, -1.0},\n        {-1.0, 1.0, -1.0},\n    }\n\n    inputFaces := []Face{\n        {0, 1, 2, 3},\n        {3, 2, 4, 5},\n        {5, 4, 6, 7},\n        {7, 0, 3, 5},\n        {7, 6, 1, 0},\n        {6, 1, 2, 4},\n    }\n\n    outputPoints := make([]Point, len(inputPoints))\n    outputFaces := make([]Face, len(inputFaces))\n    copy(outputPoints, inputPoints)\n    copy(outputFaces, inputFaces)\n    iterations := 1\n    for i := 0; i < iterations; i++ {\n        outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces)\n    }\n    for _, p := range outputPoints {\n        fmt.Printf(\"% .4f\\n\", p)\n    }\n    fmt.Println()\n    for _, f := range outputFaces {\n        fmt.Printf(\"%2d\\n\", f)\n    }\n}\n"}
{"id": 53291, "name": "Catmull–Clark subdivision surface", "C": "vertex face_point(face f)\n{\n\tint i;\n\tvertex v;\n\n\tif (!f->avg) {\n\t\tf->avg = vertex_new();\n\t\tforeach(i, v, f->v)\n\t\t\tif (!i) f->avg->pos = v->pos;\n\t\t\telse    vadd(f->avg->pos, v->pos);\n\n\t\tvdiv(f->avg->pos, len(f->v));\n\t}\n\treturn f->avg;\n}\n\n#define hole_edge(e) (len(e->f)==1)\nvertex edge_point(edge e)\n{\n\tint i;\n\tface f;\n\n\tif (!e->e_pt) {\n\t\te->e_pt = vertex_new();\n\t\te->avg = e->v[0]->pos;\n\t\tvadd(e->avg, e->v[1]->pos);\n\t\te->e_pt->pos = e->avg;\n\n\t\tif (!hole_edge(e)) {\n\t\t\tforeach (i, f, e->f)\n\t\t\t\tvadd(e->e_pt->pos, face_point(f)->pos);\n\t\t\tvdiv(e->e_pt->pos, 4);\n\t\t} else\n\t\t\tvdiv(e->e_pt->pos, 2);\n\n\t\tvdiv(e->avg, 2);\n\t}\n\n\treturn e->e_pt;\n}\n\n#define hole_vertex(v) (len((v)->f) != len((v)->e))\nvertex updated_point(vertex v)\n{\n\tint i, n = 0;\n\tedge e;\n\tface f;\n\tcoord_t sum = {0, 0, 0};\n\n\tif (v->v_new) return v->v_new;\n\n\tv->v_new = vertex_new();\n\tif (hole_vertex(v)) {\n\t\tv->v_new->pos = v->pos;\n\t\tforeach(i, e, v->e) {\n\t\t\tif (!hole_edge(e)) continue;\n\t\t\tvadd(v->v_new->pos, edge_point(e)->pos);\n\t\t\tn++;\n\t\t}\n\t\tvdiv(v->v_new->pos, n + 1);\n\t} else {\n\t\tn = len(v->f);\n\t\tforeach(i, f, v->f)\n\t\t\tvadd(sum, face_point(f)->pos);\n\t\tforeach(i, e, v->e)\n\t\t\tvmadd(sum, edge_point(e)->pos, 2, sum);\n\t\tvdiv(sum, n);\n\t\tvmadd(sum, v->pos, n - 3, sum);\n\t\tvdiv(sum, n);\n\t\tv->v_new->pos = sum;\n\t}\n\n\treturn v->v_new;\n}\n\nmodel catmull(model m)\n{\n\tint i, j, a, b, c, d;\n\tface f;\n\tvertex v, x;\n\n\tmodel nm = model_new();\n\tforeach (i, f, m->f) {\n\t\tforeach(j, v, f->v) {\n\t\t\t_get_idx(a, updated_point(v));\n\t\t\t_get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e))));\n\t\t\t_get_idx(c, face_point(f));\n\t\t\t_get_idx(d, edge_point(elem(f->e, j)));\n\t\t\tmodel_add_face(nm, 4, a, b, c, d);\n\t\t}\n\t}\n\treturn nm;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype (\n    Point [3]float64\n    Face  []int\n\n    Edge struct {\n        pn1 int   \n        pn2 int   \n        fn1 int   \n        fn2 int   \n        cp  Point \n    }\n\n    PointEx struct {\n        p Point\n        n int\n    }\n)\n\nfunc sumPoint(p1, p2 Point) Point {\n    sp := Point{}\n    for i := 0; i < 3; i++ {\n        sp[i] = p1[i] + p2[i]\n    }\n    return sp\n}\n\nfunc mulPoint(p Point, m float64) Point {\n    mp := Point{}\n    for i := 0; i < 3; i++ {\n        mp[i] = p[i] * m\n    }\n    return mp\n}\n\nfunc divPoint(p Point, d float64) Point {\n    return mulPoint(p, 1.0/d)\n}\n\nfunc centerPoint(p1, p2 Point) Point {\n    return divPoint(sumPoint(p1, p2), 2)\n}\n\nfunc getFacePoints(inputPoints []Point, inputFaces []Face) []Point {\n    facePoints := make([]Point, len(inputFaces))\n    for i, currFace := range inputFaces {\n        facePoint := Point{}\n        for _, cpi := range currFace {\n            currPoint := inputPoints[cpi]\n            facePoint = sumPoint(facePoint, currPoint)\n        }\n        facePoint = divPoint(facePoint, float64(len(currFace)))\n        facePoints[i] = facePoint\n    }\n    return facePoints\n}\n\nfunc getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge {\n    var edges [][3]int\n    for faceNum, face := range inputFaces {\n        numPoints := len(face)\n        for pointIndex := 0; pointIndex < numPoints; pointIndex++ {\n            pointNum1 := face[pointIndex]\n            var pointNum2 int\n            if pointIndex < numPoints-1 {\n                pointNum2 = face[pointIndex+1]\n            } else {\n                pointNum2 = face[0]\n            }\n            if pointNum1 > pointNum2 {\n                pointNum1, pointNum2 = pointNum2, pointNum1\n            }\n            edges = append(edges, [3]int{pointNum1, pointNum2, faceNum})\n        }\n    }\n    sort.Slice(edges, func(i, j int) bool {\n        if edges[i][0] == edges[j][0] {\n            if edges[i][1] == edges[j][1] {\n                return edges[i][2] < edges[j][2]\n            }\n            return edges[i][1] < edges[j][1]\n        }\n        return edges[i][0] < edges[j][0]\n    })\n    numEdges := len(edges)\n    eIndex := 0\n    var mergedEdges [][4]int\n    for eIndex < numEdges {\n        e1 := edges[eIndex]\n        if eIndex < numEdges-1 {\n            e2 := edges[eIndex+1]\n            if e1[0] == e2[0] && e1[1] == e2[1] {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]})\n                eIndex += 2\n            } else {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n                eIndex++\n            }\n        } else {\n            mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n            eIndex++\n        }\n    }\n    var edgesCenters []Edge\n    for _, me := range mergedEdges {\n        p1 := inputPoints[me[0]]\n        p2 := inputPoints[me[1]]\n        cp := centerPoint(p1, p2)\n        edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp})\n    }\n    return edgesCenters\n}\n\nfunc getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point {\n    edgePoints := make([]Point, len(edgesFaces))\n    for i, edge := range edgesFaces {\n        cp := edge.cp\n        fp1 := facePoints[edge.fn1]\n        var fp2 Point\n        if edge.fn2 == -1 {\n            fp2 = fp1\n        } else {\n            fp2 = facePoints[edge.fn2]\n        }\n        cfp := centerPoint(fp1, fp2)\n        edgePoints[i] = centerPoint(cp, cfp)\n    }\n    return edgePoints\n}\n\nfunc getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for faceNum := range inputFaces {\n        fp := facePoints[faceNum]\n        for _, pointNum := range inputFaces[faceNum] {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, fp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgFacePoints := make([]Point, numPoints)\n    for i, tp := range tempPoints {\n        avgFacePoints[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgFacePoints\n}\n\nfunc getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for _, edge := range edgesFaces {\n        cp := edge.cp\n        for _, pointNum := range []int{edge.pn1, edge.pn2} {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, cp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgMidEdges := make([]Point, len(tempPoints))\n    for i, tp := range tempPoints {\n        avgMidEdges[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgMidEdges\n}\n\nfunc getPointsFaces(inputPoints []Point, inputFaces []Face) []int {\n    numPoints := len(inputPoints)\n    pointsFaces := make([]int, numPoints)\n    for faceNum := range inputFaces {\n        for _, pointNum := range inputFaces[faceNum] {\n            pointsFaces[pointNum]++\n        }\n    }\n    return pointsFaces\n}\n\nfunc getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point {\n    newPoints := make([]Point, len(inputPoints))\n    for pointNum := range inputPoints {\n        n := float64(pointsFaces[pointNum])\n        m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n\n        oldCoords := inputPoints[pointNum]\n        p1 := mulPoint(oldCoords, m1)\n        afp := avgFacePoints[pointNum]\n        p2 := mulPoint(afp, m2)\n        ame := avgMidEdges[pointNum]\n        p3 := mulPoint(ame, m3)\n        p4 := sumPoint(p1, p2)\n        newPoints[pointNum] = sumPoint(p4, p3)\n    }\n    return newPoints\n}\n\nfunc switchNums(pointNums [2]int) [2]int {\n    if pointNums[0] < pointNums[1] {\n        return pointNums\n    }\n    return [2]int{pointNums[1], pointNums[0]}\n}\n\nfunc cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) {\n    facePoints := getFacePoints(inputPoints, inputFaces)\n    edgesFaces := getEdgesFaces(inputPoints, inputFaces)\n    edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints)\n    avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints)\n    avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces)\n    pointsFaces := getPointsFaces(inputPoints, inputFaces)\n    newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n    var facePointNums []int\n    nextPointNum := len(newPoints)\n    for _, facePoint := range facePoints {\n        newPoints = append(newPoints, facePoint)\n        facePointNums = append(facePointNums, nextPointNum)\n        nextPointNum++\n    }\n    edgePointNums := make(map[[2]int]int)\n    for edgeNum := range edgesFaces {\n        pointNum1 := edgesFaces[edgeNum].pn1\n        pointNum2 := edgesFaces[edgeNum].pn2\n        edgePoint := edgePoints[edgeNum]\n        newPoints = append(newPoints, edgePoint)\n        edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum\n        nextPointNum++\n    }\n    var newFaces []Face\n    for oldFaceNum, oldFace := range inputFaces {\n        if len(oldFace) == 4 {\n            a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3]\n            facePointAbcd := facePointNums[oldFaceNum]\n            edgePointAb := edgePointNums[switchNums([2]int{a, b})]\n            edgePointDa := edgePointNums[switchNums([2]int{d, a})]\n            edgePointBc := edgePointNums[switchNums([2]int{b, c})]\n            edgePointCd := edgePointNums[switchNums([2]int{c, d})]\n            newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa})\n            newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb})\n            newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc})\n            newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd})\n        }\n    }\n    return newPoints, newFaces\n}\n\nfunc main() {\n    inputPoints := []Point{\n        {-1.0, 1.0, 1.0},\n        {-1.0, -1.0, 1.0},\n        {1.0, -1.0, 1.0},\n        {1.0, 1.0, 1.0},\n        {1.0, -1.0, -1.0},\n        {1.0, 1.0, -1.0},\n        {-1.0, -1.0, -1.0},\n        {-1.0, 1.0, -1.0},\n    }\n\n    inputFaces := []Face{\n        {0, 1, 2, 3},\n        {3, 2, 4, 5},\n        {5, 4, 6, 7},\n        {7, 0, 3, 5},\n        {7, 6, 1, 0},\n        {6, 1, 2, 4},\n    }\n\n    outputPoints := make([]Point, len(inputPoints))\n    outputFaces := make([]Face, len(inputFaces))\n    copy(outputPoints, inputPoints)\n    copy(outputFaces, inputFaces)\n    iterations := 1\n    for i := 0; i < iterations; i++ {\n        outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces)\n    }\n    for _, p := range outputPoints {\n        fmt.Printf(\"% .4f\\n\", p)\n    }\n    fmt.Println()\n    for _, f := range outputFaces {\n        fmt.Printf(\"%2d\\n\", f)\n    }\n}\n"}
{"id": 53292, "name": "Rosetta Code_List authors of task descriptions", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_list_authors_of_task_descriptions.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strings\"\n)\n\ntype authorNumber struct {\n    author string\n    number int\n}\n\nfunc main() {\n    ex1 := `<li><a href=\"/wiki/(.*?)\"`\n    ex2 := `a href=\"/(wiki/User:|mw/index\\.php\\?title=User:|wiki/Special:Contributions/)([^\"&]+)`\n    re1 := regexp.MustCompile(ex1)\n    re2 := regexp.MustCompile(ex2)\n    url1 := \"http:\n    url2 := \"http:\n    urls := []string{url1, url2}\n    var tasks []string\n    for _, url := range urls {\n        resp, _ := http.Get(url)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re1.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        for _, match := range matches {\n            \n            if !strings.HasPrefix(match[1], \"Category:\") {\n                tasks = append(tasks, match[1])\n            }\n        }\n    }\n    authors := make(map[string]int)\n    for _, task := range tasks {\n        \n        page := fmt.Sprintf(\"http:\n        resp, _ := http.Get(page)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re2.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        \n        author := matches[len(matches)-1][2]\n        author = strings.ReplaceAll(author, \"_\", \" \")\n        \n        authors[author]++\n    }\n    \n    authorNumbers := make([]authorNumber, 0, len(authors))\n    for k, v := range authors {\n        authorNumbers = append(authorNumbers, authorNumber{k, v})\n    }\n    sort.Slice(authorNumbers, func(i, j int) bool {\n        return authorNumbers[i].number > authorNumbers[j].number\n    })\n    \n    fmt.Println(\"Total tasks   :\", len(tasks))\n    fmt.Println(\"Total authors :\", len(authors))\n    fmt.Println(\"\\nThe top 20 authors by number of tasks created are:\\n\")\n    fmt.Println(\"Pos  Tasks  Author\")\n    fmt.Println(\"===  =====  ======\")\n    lastNumber, lastIndex := 0, -1\n    for i, authorNumber := range authorNumbers[0:20] {\n        j := i\n        if authorNumber.number == lastNumber {\n            j = lastIndex\n        } else {\n            lastIndex = i\n            lastNumber = authorNumber.number\n        }\n        fmt.Printf(\"%2d:   %3d   %s\\n\", j+1, authorNumber.number, authorNumber.author)\n    }\n}\n"}
{"id": 53293, "name": "Rosetta Code_List authors of task descriptions", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_list_authors_of_task_descriptions.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strings\"\n)\n\ntype authorNumber struct {\n    author string\n    number int\n}\n\nfunc main() {\n    ex1 := `<li><a href=\"/wiki/(.*?)\"`\n    ex2 := `a href=\"/(wiki/User:|mw/index\\.php\\?title=User:|wiki/Special:Contributions/)([^\"&]+)`\n    re1 := regexp.MustCompile(ex1)\n    re2 := regexp.MustCompile(ex2)\n    url1 := \"http:\n    url2 := \"http:\n    urls := []string{url1, url2}\n    var tasks []string\n    for _, url := range urls {\n        resp, _ := http.Get(url)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re1.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        for _, match := range matches {\n            \n            if !strings.HasPrefix(match[1], \"Category:\") {\n                tasks = append(tasks, match[1])\n            }\n        }\n    }\n    authors := make(map[string]int)\n    for _, task := range tasks {\n        \n        page := fmt.Sprintf(\"http:\n        resp, _ := http.Get(page)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re2.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        \n        author := matches[len(matches)-1][2]\n        author = strings.ReplaceAll(author, \"_\", \" \")\n        \n        authors[author]++\n    }\n    \n    authorNumbers := make([]authorNumber, 0, len(authors))\n    for k, v := range authors {\n        authorNumbers = append(authorNumbers, authorNumber{k, v})\n    }\n    sort.Slice(authorNumbers, func(i, j int) bool {\n        return authorNumbers[i].number > authorNumbers[j].number\n    })\n    \n    fmt.Println(\"Total tasks   :\", len(tasks))\n    fmt.Println(\"Total authors :\", len(authors))\n    fmt.Println(\"\\nThe top 20 authors by number of tasks created are:\\n\")\n    fmt.Println(\"Pos  Tasks  Author\")\n    fmt.Println(\"===  =====  ======\")\n    lastNumber, lastIndex := 0, -1\n    for i, authorNumber := range authorNumbers[0:20] {\n        j := i\n        if authorNumber.number == lastNumber {\n            j = lastIndex\n        } else {\n            lastIndex = i\n            lastNumber = authorNumber.number\n        }\n        fmt.Printf(\"%2d:   %3d   %s\\n\", j+1, authorNumber.number, authorNumber.author)\n    }\n}\n"}
{"id": 53294, "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", "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": 53295, "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": "#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": 53296, "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": "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": 53297, "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": "#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": 53298, "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": "#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": 53299, "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": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n"}
{"id": 53300, "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": "#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": 53301, "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": "#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": 53302, "name": "Euler's constant 0.5772...", "C++": "#include <array>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\ndouble ByVaccaSeries(int numTerms)\n{\n    \n    \n    \n    \n    \n    \n    \n    double gamma = 0;\n    size_t next = 4;\n    \n    for(double numerator = 1; numerator < numTerms; ++numerator)\n    {\n        double delta = 0;\n        for(size_t denominator = next/2; denominator < next; denominator+=2)\n        {\n            \n            delta += 1.0/denominator - 1.0/(denominator + 1);\n        }\n\n        gamma += numerator * delta;\n        next *= 2;\n    }\n    return gamma;\n}\n\n\ndouble ByEulersMethod()\n{\n    \n    const std::array<double, 8> B2 {1.0, 1.0/6, -1.0/30, 1.0/42, -1.0/30,\n        5.0/66, -691.0/2730, 7.0/6};\n    \n    const int n = 10;\n\n    \n    const double h = [] \n    {\n        double sum = 1;\n        for (int k = 2; k <= n; k++) { sum += 1.0 / k; }\n        return sum - log(n);\n    }();\n\n    \n    double a = -1.0 / (2*n);\n    double r = 1;\n    for (int k = 1; k < ssize(B2); k++)\n    {\n        r *= n * n;\n        a += B2[k] / (2*k * r);\n    }\n\n    return h + a;\n}\n\n\nint main()\n{\n    std::cout << std::setprecision(16) << \"Vacca series:  \" << ByVaccaSeries(32);\n    std::cout << std::setprecision(16) << \"\\nEulers method: \" << ByEulersMethod();\n}\n", "C": "\n#include <math.h>\n#include <stdio.h>\n\n#define eps 1e-6\n\nint main(void) {\ndouble a, b, h, n2, r, u, v;\nint k, k2, m, n;\n\nprintf(\"From the definition, err. 3e-10\\n\");\n\nn = 400;\n\nh = 1;\nfor (k = 2; k <= n; k++) {\n   h += 1.0 / k;\n}\n\na = log(n +.5 + 1.0 / (24*n));\n\nprintf(\"Hn    %.16f\\n\", h);\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", h - a, n);\n\n\nprintf(\"Sweeney, 1963, err. idem\\n\");\n\nn = 21;\n\ndouble s[] = {0, n};\nr = n;\nk = 1;\ndo {\n   k += 1;\n   r *= (double) n / k;\n   s[k & 1] += r / k;\n} while (r > eps);\n\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", s[1] - s[0] - log(n), k);\n\n\nprintf(\"Bailey, 1988\\n\");\n\nn = 5;\n\na = 1;\nh = 1;\nn2 = pow(2,n);\nr = 1;\nk = 1;\ndo {\n   k += 1;\n   r *= n2 / k;\n   h += 1.0 / k;\n   b = a; a += r * h;\n} while (fabs(b - a) > eps);\na *= n2 / exp(n2);\n\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", a - n * log(2), k);\n\n\nprintf(\"Brent-McMillan, 1980\\n\");\n\nn = 13;\n\na = -log(n);\nb = 1;\nu = a;\nv = b;\nn2 = n * n;\nk2 = 0;\nk = 0;\ndo {\n   k2 += 2*k + 1;\n   k += 1;\n   a *= n2 / k;\n   b *= n2 / k2;\n   a = (a + b) / k;\n   u += a;\n   v += b;\n} while (fabs(a) > eps);\n\nprintf(\"gamma %.16f\\nk = %d\\n\\n\", u / v, k);\n\n\nprintf(\"How Euler did it in 1735\\n\");\n\ndouble B2[] = {1.0,1.0/6,-1.0/30,1.0/42,-1.0/30,\\\n 5.0/66,-691.0/2730,7.0/6,-3617.0/510,43867.0/798};\nm = 7;\nif (m > 9) return(0);\n\nn = 10;\n\n\nh = 1;\nfor (k = 2; k <= n; k++) {\n   h += 1.0 / k;\n}\nprintf(\"Hn    %.16f\\n\", h);\n\nh -= log(n);\nprintf(\"  -ln %.16f\\n\", h);\n\n\na = -1.0 / (2*n);\nn2 = n * n;\nr = 1;\nfor (k = 1; k <= m; k++) {\n   r *= n2;\n   a += B2[k] / (2*k * r);\n}\n\nprintf(\"err  %.16f\\ngamma %.16f\\nk = %d\", a, h + a, n + m);\n\nprintf(\"\\n\\nC  =  0.57721566490153286...\\n\");\n}\n"}
{"id": 53303, "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": "#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": 53304, "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", "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": 53305, "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", "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": 53306, "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", "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": 53307, "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", "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": 53308, "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", "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": 53309, "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", "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": 53310, "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": "#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": 53311, "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": "#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": 53312, "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": "#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": 53313, "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": "#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": 53314, "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", "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": 53315, "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", "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": 53316, "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", "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": 53317, "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", "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": 53318, "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", "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": 53319, "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", "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": 53320, "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", "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": 53321, "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", "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": 53322, "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": "#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": 53323, "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", "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": 53324, "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", "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": 53325, "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", "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": 53326, "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", "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": 53327, "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", "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": 53328, "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", "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": 53329, "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": "#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": 53330, "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": "#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": 53331, "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", "C": "\nif (strcmp(a,b)) action_on_equality();\n"}
{"id": 53332, "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", "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": 53333, "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", "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": 53334, "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", "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": 53335, "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", "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": 53336, "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", "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": 53337, "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", "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": 53338, "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", "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": 53339, "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", "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": 53340, "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", "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": 53341, "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", "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": 53342, "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", "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": 53343, "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", "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": 53344, "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", "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": 53345, "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", "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": 53346, "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", "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": 53347, "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", "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": 53348, "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", "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": 53349, "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", "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": 53350, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\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": 53351, "name": "Peano curve", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\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": 53352, "name": "Seven-sided dice from five-sided dice", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\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": 53353, "name": "Solve the no connection puzzle", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 1);\n    return 0;\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": 53354, "name": "Magnanimous numbers", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\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": 53355, "name": "Extensible prime generator", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\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": 53356, "name": "Rock-paper-scissors", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\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": 53357, "name": "Create a two-dimensional array at runtime", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\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": 53358, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\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": 53359, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\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": 53360, "name": "Vigenère cipher_Cryptanalysis", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\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": 53361, "name": "Pi", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \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": 53362, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\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": 53363, "name": "Hofstadter Q sequence", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\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": 53364, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\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": 53365, "name": "Return multiple values", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\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": 53366, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 53367, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 53368, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\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": 53369, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\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": 53370, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\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": 53371, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\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": 53372, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 53373, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\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": 53374, "name": "LU decomposition", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\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"}
{"id": 53375, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 53376, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 53377, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 53378, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 53379, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 53380, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 53381, "name": "24 game_Solve", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 53382, "name": "Checkpoint synchronization", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n"}
{"id": 53383, "name": "Variable-length quantity", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53384, "name": "Record sound", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\nusing namespace std;\n\nclass recorder\n{\npublic:\n    void start()\n    {\n\tpaused = rec = false; action = \"IDLE\";\n\twhile( true )\n\t{\n\t    cout << endl << \"==\" << action << \"==\" << endl << endl;\n\t    cout << \"1) Record\" << endl << \"2) Play\" << endl << \"3) Pause\" << endl << \"4) Stop\" << endl << \"5) Quit\" << endl;\n\t    char c; cin >> c;\n\t    if( c > '0' && c < '6' )\n\t    {\n\t\tswitch( c )\n\t\t{\n\t\t    case '1': record(); break;\n\t\t    case '2': play();   break;\n\t\t    case '3': pause();  break;\n\t\t    case '4': stop();   break;\n\t\t    case '5': stop();   return;\n\t\t}\n\t    }\n\t}\n    }\nprivate:\n    void record()\n    {\n\tif( mciExecute( \"open new type waveaudio alias my_sound\") )\n\t{ \n\t    mciExecute( \"record my_sound\" ); \n\t    action = \"RECORDING\"; rec = true; \n\t}\n    }\n    void play()\n    {\n\tif( paused )\n\t    mciExecute( \"play my_sound\" );\n\telse\n\t    if( mciExecute( \"open tmp.wav alias my_sound\" ) )\n\t\tmciExecute( \"play my_sound\" );\n\n\taction = \"PLAYING\";\n\tpaused = false;\n    }\n    void pause()\n    {\n\tif( rec ) return;\n\tmciExecute( \"pause my_sound\" );\n\tpaused = true; action = \"PAUSED\";\n    }\n    void stop()\n    {\n\tif( rec )\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"save my_sound tmp.wav\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\"; rec = false;\n\t}\n\telse\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\";\n\t}\n    }\n    bool mciExecute( string cmd )\n    {\n\tif( mciSendString( cmd.c_str(), NULL, 0, NULL ) )\n\t{\n\t    cout << \"Can't do this: \" << cmd << endl;\n\t    return false;\n\t}\n\treturn true;\n    }\n\n    bool paused, rec;\n    string action;\n};\n\nint main( int argc, char* argv[] )\n{\n    recorder r; r.start();\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <fcntl.h>\n\nvoid * record(size_t bytes)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_RDONLY))) return 0;\n\tvoid *a = malloc(bytes);\n\tread(fd, a, bytes);\n\tclose(fd);\n\treturn a;\n}\n\nint play(void *buf, size_t len)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_WRONLY))) return 0;\n\twrite(fd, buf, len);\n\tclose(fd);\n\treturn 1;\n}\n\nint main()\n{\n\tvoid *p = record(65536);\n\tplay(p, 65536);\n\treturn 0;\n}\n"}
{"id": 53385, "name": "SHA-256 Merkle tree", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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 <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53386, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 53387, "name": "User input_Graphical", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n"}
{"id": 53388, "name": "Sierpinski arrowhead curve", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\n", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53389, "name": "Text processing_1", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n"}
{"id": 53390, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 53391, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 53392, "name": "Aliquot sequence classifications", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 53393, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 53394, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 53395, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 53396, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 53397, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 53398, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 53399, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53400, "name": "Stack", "C++": "#include <stack>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 53401, "name": "Totient function", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 53402, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 53403, "name": "Random number generator (included)", "C++": "#include <iostream>\n#include <string>\n#include <random>\n \nint main()\n{\n    std::random_device rd;\n    std::uniform_int_distribution<int> dist(1, 10);\n    std::mt19937 mt(rd());\n    \n    std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n    std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}\n"}
{"id": 53404, "name": "Random number generator (included)", "C++": "#include <iostream>\n#include <string>\n#include <random>\n \nint main()\n{\n    std::random_device rd;\n    std::uniform_int_distribution<int> dist(1, 10);\n    std::mt19937 mt(rd());\n    \n    std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n    std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}\n"}
{"id": 53405, "name": "Random number generator (included)", "C++": "#include <iostream>\n#include <string>\n#include <random>\n \nint main()\n{\n    std::random_device rd;\n    std::uniform_int_distribution<int> dist(1, 10);\n    std::mt19937 mt(rd());\n    \n    std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n    std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint\nmain()\n{\n\tint i;\n\tsrand(time(NULL));\n\tfor (i = 0; i < 10; i++)\n\t\tputs((rand() % 2) ? \"heads\" : \"tails\");\n\treturn 0;\n}\n"}
{"id": 53406, "name": "Fractran", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n"}
{"id": 53407, "name": "Sorting algorithms_Stooge sort", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n"}
{"id": 53408, "name": "Galton box animation", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\n"}
{"id": 53409, "name": "Sorting Algorithms_Circle Sort", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\n"}
{"id": 53410, "name": "Kronecker product based fractals", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n"}
{"id": 53411, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 53412, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 53413, "name": "Circular primes", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 53414, "name": "Animation", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 53415, "name": "Sorting algorithms_Radix sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n"}
{"id": 53416, "name": "List comprehensions", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 53417, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 53418, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 53419, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 53420, "name": "Jacobi symbol", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 53421, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 53422, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 53423, "name": "K-d tree", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 53424, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 53425, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n"}
{"id": 53426, "name": "Safe addition", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n"}
{"id": 53427, "name": "Case-sensitivity of identifiers", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n"}
{"id": 53428, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 53429, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 53430, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 53431, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 53432, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 53433, "name": "Palindromic gapful numbers", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 53434, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 53435, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 53436, "name": "Sierpinski triangle_Graphical", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 53437, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 53438, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 53439, "name": "Summarize primes", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 53440, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 53441, "name": "Common sorted list", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 53442, "name": "Non-continuous subsequences", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53443, "name": "Fibonacci word_fractal", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\n", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\n"}
{"id": 53444, "name": "Twin primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 53445, "name": "15 puzzle solver", "C++": "\nclass fifteenSolver{\n  const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};\n  int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};\n  unsigned long N2[100]{};\n  const bool fY(){\n    if (N4[n]<_n) return fN();\n    if (N2[n]==0x123456789abcdef0) {std::cout<<\"Solution found in \"<<n<<\" moves :\"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};\n    if (N4[n]==_n) return fN(); else return false;\n  }\n  const bool                     fN(){\n    if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}\n    return false;\n  }\n  void fI(){\n    const int           g = (11-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);\n  } \n  void fG(){\n    const int           g = (19-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);\n  } \n  void fE(){\n    const int           g = (14-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);\n  } \n  void fL(){\n    const int           g = (16-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);\n  }\npublic:\n  fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}\n  void Solve(){for(;not fY();++_n);}\n};\n", "C": " \n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\ntypedef unsigned char u8t;\ntypedef unsigned short u16t;\nenum { NR=4, NC=4, NCELLS = NR*NC };\nenum { UP, DOWN, LEFT, RIGHT, NDIRS };\nenum { OK = 1<<8, XX = 1<<9, FOUND = 1<<10, zz=0x80 };\nenum { MAX_INT=0x7E, MAX_NODES=(16*65536)*90};\nenum { BIT_HDR=1<<0, BIT_GRID=1<<1, BIT_OTHER=1<<2 };\nenum { PHASE1,PHASE2 };  \n\ntypedef struct { u16t dn; u16t hn; }HSORT_T;\n\ntypedef struct {\n   u8t data[NCELLS]; unsigned id; unsigned src;\n   u8t h; u8t g; u8t udlr;\n}NODE_T;  \n\nNODE_T goal44={\n   {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,0},0,0,0,0,0};\nNODE_T work; \n\nNODE_T G34={ \n {13,9,5,4, 15,6,1,8, 0,10,2,11, 14,3,7,12},0,0,0,0,0};\n\nNODE_T G52={ \n   {15,13,9,5, 14,6,1,4,  10,12,0,8, 3,7,11,2},0,0,0,0,0};\n\nNODE_T G99={ \n   {15,14,1,6, 9,11,4,12, 0,10,7,3, 13,8,5,2},0,0,0,0,0};\n\nstruct {\n   unsigned nodes;\n   unsigned gfound;\n   unsigned root_visits;\n   unsigned verbose;\n   unsigned locks;\n   unsigned phase;\n}my;\n\nu16t  HybridIDA_star(NODE_T *pNode);\nu16t  make_node(NODE_T *pNode, NODE_T *pNew, u8t udlr );\nu16t  search(NODE_T *pNode, u16t bound);\nu16t  taxi_dist( NODE_T *pNode);\nu16t  tile_home( NODE_T *p44);\nvoid  print_node( NODE_T *pN, const char *pMsg, short force );\nu16t  goal_found(NODE_T *pNode);\nchar  udlr_to_char( char udlr );\nvoid  idx_to_rc( u16t idx, u16t *row, u16t *col );\nvoid  sort_nodes(HSORT_T *p);\n\nint main( )\n{\n   my.verbose = 0;\t\t\n   \n   \n   \n   memcpy(&work,  &G99, sizeof(NODE_T));  \n   if(1){   \n      printf(\"Phase1: IDA* search for 1234 permutation..\\n\");\n      my.phase = PHASE1;\n      (void) HybridIDA_star(&work);\n   }\n   printf(\"Phase2: IDA* search phase1 seed..\\n\");\n   my.phase = PHASE2;\n   (void)HybridIDA_star(&work);\n   return 0;\n}\n\n\nu16t HybridIDA_star(NODE_T *pN){\n   my.nodes = 1;\n   my.gfound = 0;\n   my.root_visits = 0;\n   pN->udlr = NDIRS;\n   pN->g = 0;\n   pN->h = taxi_dist(pN);\n   pN->id = my.nodes;\n   pN->src = 0;\n   const char *pr = {\"Start\"}; \n   print_node( pN,pr,1 );\n   u16t depth = pN->h;\n   while(1){\n      depth = search(pN,depth);\n      if( depth & FOUND){\n         return FOUND;  \n      }\n      if( depth & 0xFF00 ){\n\t printf(\"..error %x\\n\",depth);\n\t return XX;\n      }\n      my.root_visits++;\n      printf(\"[root visits: %u, depth %u]\\n\",my.root_visits,depth);\n   }\n   return 0;\n}\n\n\nu16t search(NODE_T *pN, u16t bound){ \n   if(bound & 0xff00){ return bound; }\n   u16t f = pN->g + pN->h;\n   if( f > bound){ return f; }\n   if(goal_found(pN)){\n      my.gfound = pN->g;\n      memcpy(&work,pN,sizeof(NODE_T));\n      printf(\"total nodes=%d, g=%u \\n\", my.nodes, my.gfound);\n      const char *pr = {\"Found..\"}; \n      print_node( &work,pr,1 );\n      return FOUND;\n   }\n   NODE_T news;\n   \n   \n   \n   HSORT_T hlist[NDIRS];\n   for( short i=0; i<NDIRS; i++ ){\n      u16t rv = make_node(pN,&news, i );\n      hlist[i].dn = i;\n      if( rv & OK ){\n\t hlist[i].hn = news.h;\n\t continue;\n      }\n      hlist[i].hn = XX;\n   }\n   sort_nodes(&hlist[0]);\n   \n   u16t temp, min = MAX_INT; \n   for( short i=0; i<NDIRS; i++ ){\n      if( hlist[i].hn > 0xff ) continue;\n      temp = make_node(pN,&news, hlist[i].dn );\n      if( temp & XX ) return XX;\n      if( temp & OK ){\n\t news.id = my.nodes++;\n\t print_node(&news,\" succ\",0 );\n\t temp = search(&news, bound);\n\t if(temp & 0xff00){  return temp;}\n\t if(temp < min){ min = temp; }\n      }\n   }\n   return min;\n}\n\n\nvoid sort_nodes(HSORT_T *p){\n   for( short s=0; s<NDIRS-1; s++ ){\n      HSORT_T tmp = p[0];\n      if( p[1].hn < p[0].hn ){tmp=p[0]; p[0]=p[1]; p[1]=tmp; }\n      if( p[2].hn < p[1].hn ){tmp=p[1]; p[1]=p[2]; p[2]=tmp; }\n      if( p[3].hn < p[2].hn ){tmp=p[2]; p[2]=p[3]; p[3]=tmp; }\n   }\n}\n\n\nu16t tile_home(NODE_T *pN ){\n   for( short i=0; i<NCELLS; i++ ){\n      if( pN->data[i] == 0 ) return i;\n   }\n   return XX;\n}\n\n\nvoid print_node( NODE_T *pN, const char *pMsg, short force ){\n   const int tp1 = 0;\n   if( my.verbose & BIT_HDR || force || tp1){\n      char ch = udlr_to_char(pN->udlr);\n      printf(\"id:%u src:%u; h=%d, g=%u, udlr=%c, %s\\n\",\n\t     pN->id, pN->src, pN->h, pN->g, ch, pMsg);\n   }\n   if(my.verbose & BIT_GRID || force || tp1){\n      for(u16t i=0; i<NR; i++ ){\n\t for( u16t j=0; j<NC; j++ ){\n\t    printf(\"%3d\",pN->data[i*NR+j]);\n\t }\n\t printf(\"\\n\");\n      }\n      printf(\"\\n\");\n   }\n   \n}\n\n\nu16t goal_found(NODE_T *pN) {\n   if(my.phase==PHASE1){\n      short tags = 0;\n      for( short i=0; i<(NC); i++ ){\n\t if( pN->data[i] == i+1 ) tags++;\n      }\n      if( tags==4 ) return 1;  \n   }\n   \n   for( short i=0; i<(NR*NC); i++ ){\n      if( pN->data[i] != goal44.data[i] ) return 0;\n   }\n   return 1;\n}\n\n\nchar udlr_to_char( char udlr ){\n   char ch = '?';\n   switch(udlr){\n   case UP:    ch = 'U'; break;\n   case DOWN:  ch = 'D'; break;\n   case LEFT:  ch = 'L'; break;\n   case RIGHT: ch = 'R'; break;\n   default: break;\n   }\n   return ch;\n}\n\n\nvoid idx_to_rc( u16t idx, u16t *row, u16t *col ){\n   *row = idx/NR; *col = abs( idx - (*row * NR));\n}\n\n\n\nu16t make_node(NODE_T *pSrc, NODE_T *pNew, u8t udlr ){\n   u16t row,col,home_idx,idx2;\n   if(udlr>=NDIRS||udlr<0 ){ printf(\"invalid udlr %u\\n\",udlr); return XX; }\n   if(my.nodes > MAX_NODES ){ printf(\"excessive nodes %u\\n\",my.nodes);\n      return XX; }\n   memcpy(pNew,pSrc,sizeof(NODE_T));\n   home_idx = tile_home(pNew);\n   idx_to_rc(home_idx, &row, &col );\n\n   if( udlr == LEFT)  { if( col < 1 ) return 0; col--; }\n   if( udlr == RIGHT ){ if( col >= (NC-1) ) return 0; col++; }\n   if( udlr == DOWN ) { if(row >= (NR-1)) return 0; row++; }\n   if( udlr == UP ){\t if(row < 1) return 0; row--; }\n   idx2 = row * NR + col;\n   if( idx2 < NCELLS ){\n      u8t *p = &pNew->data[0];\n      p[home_idx] = p[idx2];\n      p[idx2]     = 0; \n      pNew->src   = pSrc->id;\n      pNew->g     = pSrc->g + 1;\n      pNew->h     = taxi_dist(pNew);\n      pNew->udlr  = udlr; \n      return OK;\n   }\n   return 0;\n}\n\n\nu16t taxi_dist( NODE_T *pN){\n   u16t tile,sum = 0, r1,c1,r2,c2;\n   u8t *p44 = &pN->data[0];\n   for( short i=0; i<(NR*NC); i++ ){\n      tile = p44[i];\n      if( tile==0 ) continue;\n      idx_to_rc(i, &r2, &c2 );\n      idx_to_rc(tile-1, &r1, &c1 );\n      sum += abs(r1-r2) + abs(c1-c2);\n   }\n   }\n   return sum;\n}\n"}
{"id": 53446, "name": "Roots of unity", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53447, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 53448, "name": "Pell's equation", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 53449, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 53450, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 53451, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 53452, "name": "Product of divisors", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 53453, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 53454, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 53455, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 53456, "name": "Man or boy test", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 53457, "name": "Short-circuit evaluation", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 53458, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 53459, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 53460, "name": "Carmichael 3 strong pseudoprimes", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n"}
{"id": 53461, "name": "Arithmetic numbers", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 53462, "name": "Arithmetic numbers", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 53463, "name": "Image noise", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 53464, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53465, "name": "Keyboard input_Obtain a Y or N response", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53466, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 53467, "name": "Conjugate transpose", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n"}
{"id": 53468, "name": "Conjugate transpose", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n"}
{"id": 53469, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 53470, "name": "Jacobsthal numbers", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 53471, "name": "Sorting algorithms_Bead sort", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 53472, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 53473, "name": "Cistercian numerals", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 53474, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 53475, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\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 *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 53476, "name": "Draw a sphere", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\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 *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 53477, "name": "Inverted index", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 53478, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 53479, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 53480, "name": "Fermat numbers", "C++": "#include <iostream>\n#include <vector>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntypedef boost::multiprecision::cpp_int integer;\n\ninteger fermat(unsigned int n) {\n    unsigned int p = 1;\n    for (unsigned int i = 0; i < n; ++i)\n        p *= 2;\n    return 1 + pow(integer(2), p);\n}\n\ninline void g(integer& x, const integer& n) {\n    x *= x;\n    x += 1;\n    x %= n;\n}\n\ninteger pollard_rho(const integer& n) {\n    integer x = 2, y = 2, d = 1, z = 1;\n    int count = 0;\n    for (;;) {\n        g(x, n);\n        g(y, n);\n        g(y, n);\n        d = abs(x - y);\n        z = (z * d) % n;\n        ++count;\n        if (count == 100) {\n            d = gcd(z, n);\n            if (d != 1)\n                break;\n            z = 1;\n            count = 0;\n        }\n    }\n    if (d == n)\n        return 0;\n    return d;\n}\n\nstd::vector<integer> get_prime_factors(integer n) {\n    std::vector<integer> factors;\n    for (;;) {\n        if (miller_rabin_test(n, 25)) {\n            factors.push_back(n);\n            break;\n        }\n        integer f = pollard_rho(n);\n        if (f == 0) {\n            factors.push_back(n);\n            break;\n        }\n        factors.push_back(f);\n        n /= f;\n    }\n    return factors;\n}\n\nvoid print_vector(const std::vector<integer>& factors) {\n    if (factors.empty())\n        return;\n    auto i = factors.begin();\n    std::cout << *i++;\n    for (; i != factors.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout << \"First 10 Fermat numbers:\\n\";\n    for (unsigned int i = 0; i < 10; ++i)\n        std::cout << \"F(\" << i << \") = \" << fermat(i) << '\\n';\n    std::cout << \"\\nPrime factors:\\n\";\n    for (unsigned int i = 0; i < 9; ++i) {\n        std::cout << \"F(\" << i << \"): \";\n        print_vector(get_prime_factors(fermat(i)));\n    }\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <gmp.h>\n\nvoid mpz_factors(mpz_t n) {\n  int factors = 0;\n  mpz_t s, m, p;\n  mpz_init(s), mpz_init(m), mpz_init(p);\n\n  mpz_set_ui(m, 3);\n  mpz_set(p, n);\n  mpz_sqrt(s, p);\n\n  while (mpz_cmp(m, s) < 0) {\n    if (mpz_divisible_p(p, m)) {\n      gmp_printf(\"%Zd \", m);\n      mpz_fdiv_q(p, p, m);\n      mpz_sqrt(s, p);\n      factors ++;\n    }\n    mpz_add_ui(m, m, 2);\n  }\n\n  if (factors == 0) printf(\"PRIME\\n\");\n  else gmp_printf(\"%Zd\\n\", p);\n}\n\nint main(int argc, char const *argv[]) {\n  mpz_t fermat;\n  mpz_init_set_ui(fermat, 3);\n  printf(\"F(0) = 3 -> PRIME\\n\");\n  for (unsigned i = 1; i < 10; i ++) {\n    mpz_sub_ui(fermat, fermat, 1);\n    mpz_mul(fermat, fermat, fermat);\n    mpz_add_ui(fermat, fermat, 1);\n    gmp_printf(\"F(%d) = %Zd -> \", i, fermat);\n    mpz_factors(fermat);\n  }\n\n  return 0;\n}\n"}
{"id": 53481, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 53482, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 53483, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 53484, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 53485, "name": "Descending primes", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 53486, "name": "Square-free integers", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 53487, "name": "Jaro similarity", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n"}
{"id": 53488, "name": "Sum and product puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n"}
{"id": 53489, "name": "Fairshare between two and more", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 53490, "name": "Two bullet roulette", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <sstream>\n\nclass Roulette {\nprivate:\n    std::array<bool, 6> cylinder;\n\n    std::mt19937 gen;\n    std::uniform_int_distribution<> distrib;\n\n    int next_int() {\n        return distrib(gen);\n    }\n\n    void rshift() {\n        std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n    }\n\n    void unload() {\n        std::fill(cylinder.begin(), cylinder.end(), false);\n    }\n\n    void load() {\n        while (cylinder[0]) {\n            rshift();\n        }\n        cylinder[0] = true;\n        rshift();\n    }\n\n    void spin() {\n        int lim = next_int();\n        for (int i = 1; i < lim; i++) {\n            rshift();\n        }\n    }\n\n    bool fire() {\n        auto shot = cylinder[0];\n        rshift();\n        return shot;\n    }\n\npublic:\n    Roulette() {\n        std::random_device rd;\n        gen = std::mt19937(rd());\n        distrib = std::uniform_int_distribution<>(1, 6);\n\n        unload();\n    }\n\n    int method(const std::string &s) {\n        unload();\n        for (auto c : s) {\n            switch (c) {\n            case 'L':\n                load();\n                break;\n            case 'S':\n                spin();\n                break;\n            case 'F':\n                if (fire()) {\n                    return 1;\n                }\n                break;\n            }\n        }\n        return 0;\n    }\n};\n\nstd::string mstring(const std::string &s) {\n    std::stringstream ss;\n    bool first = true;\n\n    auto append = [&ss, &first](const std::string s) {\n        if (first) {\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << s;\n    };\n\n    for (auto c : s) {\n        switch (c) {\n        case 'L':\n            append(\"load\");\n            break;\n        case 'S':\n            append(\"spin\");\n            break;\n        case 'F':\n            append(\"fire\");\n            break;\n        }\n    }\n\n    return ss.str();\n}\n\nvoid test(const std::string &src) {\n    const int tests = 100000;\n    int sum = 0;\n\n    Roulette r;\n    for (int t = 0; t < tests; t++) {\n        sum += r.method(src);\n    }\n\n    double pc = 100.0 * sum / tests;\n\n    std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstatic int nextInt(int size) {\n    return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n    bool t = cylinder[5];\n    int i;\n    for (i = 4; i >= 0; i--) {\n        cylinder[i + 1] = cylinder[i];\n    }\n    cylinder[0] = t;\n}\n\nstatic void unload() {\n    int i;\n    for (i = 0; i < 6; i++) {\n        cylinder[i] = false;\n    }\n}\n\nstatic void load() {\n    while (cylinder[0]) {\n        rshift();\n    }\n    cylinder[0] = true;\n    rshift();\n}\n\nstatic void spin() {\n    int lim = nextInt(6) + 1;\n    int i;\n    for (i = 1; i < lim; i++) {\n        rshift();\n    }\n}\n\nstatic bool fire() {\n    bool shot = cylinder[0];\n    rshift();\n    return shot;\n}\n\nstatic int method(const char *s) {\n    unload();\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            load();\n            break;\n        case 'S':\n            spin();\n            break;\n        case 'F':\n            if (fire()) {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n    if (*out != '\\0') {\n        strcat(out, \", \");\n    }\n    strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            append(out, \"load\");\n            break;\n        case 'S':\n            append(out, \"spin\");\n            break;\n        case 'F':\n            append(out, \"fire\");\n            break;\n        }\n    }\n}\n\nstatic void test(char *src) {\n    char buffer[41] = \"\";\n    const int tests = 100000;\n    int sum = 0;\n    int t;\n    double pc;\n\n    for (t = 0; t < tests; t++) {\n        sum += method(src);\n    }\n\n    mstring(src, buffer);\n    pc = 100.0 * sum / tests;\n\n    printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n    srand(time(0));\n\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n"}
{"id": 53491, "name": "Parsing_Shunting-yard algorithm", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53492, "name": "Prime triangle", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n"}
{"id": 53493, "name": "Trabb Pardo–Knuth algorithm", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n"}
{"id": 53494, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 53495, "name": "Sequence_ nth number with exactly n divisors", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 53496, "name": "Sequence_ smallest number with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 53497, "name": "Pancake numbers", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 53498, "name": "Generate random chess position", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n"}
{"id": 53499, "name": "Esthetic numbers", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n"}
{"id": 53500, "name": "Topswops", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53501, "name": "Old Russian measure of length", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 53502, "name": "Rate counter", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n"}
{"id": 53503, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 53504, "name": "Padovan sequence", "C++": "#include <iostream>\n#include <map>\n#include <cmath>\n\n\n\nint pRec(int n) {\n    static std::map<int,int> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n\n    if (n <= 2) memo[n] = 1;\n    else memo[n] = pRec(n-2) + pRec(n-3);\n    return memo[n];\n}\n\n\n\nint pFloor(int n) {\n    long const double p = 1.324717957244746025960908854;\n    long const double s = 1.0453567932525329623;\n    return std::pow(p, n-1)/s + 0.5;\n}\n\n\nstd::string& lSystem(int n) {\n    static std::map<int,std::string> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n    \n    if (n == 0) memo[n] = \"A\";\n    else {\n        memo[n] = \"\";\n        for (char ch : memo[n-1]) {\n            switch(ch) {\n                case 'A': memo[n].push_back('B'); break;\n                case 'B': memo[n].push_back('C'); break;\n                case 'C': memo[n].append(\"AB\"); break;\n            }\n        }\n    }\n    return memo[n];\n}\n\n\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n    std::cout << \"The \" << descr << \" functions \";\n    int i;\n    for (i=0; i<stop; i++) {\n        int n1 = f1(i);\n        int n2 = f2(i);\n        if (n1 != n2) {\n            std::cout << \"do not match at \" << i\n                      << \": \" << n1 << \" != \" << n2 << \".\\n\";\n            break;\n        }\n    }\n    if (i == stop) {\n        std::cout << \"match from P_0 to P_\" << stop << \".\\n\";\n    }\n}\n\nint main() {\n    \n    std::cout << \"P_0 .. P_19: \";\n    for (int i=0; i<20; i++) std::cout << pRec(i) << \" \";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, pRec, \"floor- and recurrence-based\", 64);\n    \n    \n    std::cout << \"\\nThe first 10 L-system strings are:\\n\";\n    for (int i=0; i<10; i++) std::cout << lSystem(i) << \"\\n\";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, [](int n){return (int)lSystem(n).length();}, \n                            \"floor- and L-system-based\", 32);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n"}
{"id": 53505, "name": "Pythagoras tree", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n"}
{"id": 53506, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 53507, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 53508, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 53509, "name": "Numeric error propagation", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n"}
{"id": 53510, "name": "Numeric error propagation", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n"}
{"id": 53511, "name": "List rooted trees", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n"}
{"id": 53512, "name": "List rooted trees", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n"}
{"id": 53513, "name": "Longest common suffix", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n"}
{"id": 53514, "name": "Sum of elements below main diagonal of matrix", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n"}
{"id": 53515, "name": "FASTA format", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n"}
{"id": 53516, "name": "Elementary cellular automaton_Random number generator", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}\n"}
{"id": 53517, "name": "Pseudo-random numbers_PCG32", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 53518, "name": "Sierpinski pentagon", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 53519, "name": "Rep-string", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 53520, "name": "Changeable words", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53521, "name": "Monads_List monad", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate <typename T>\nauto operator>>(const vector<T>& monad, auto f)\n{\n    \n    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;\n    for(auto& item : monad)\n    {\n        \n        \n        const auto r = f(item);\n        \n        result.insert(result.end(), begin(r), end(r));\n    }\n    \n    return result;\n}\n\n\nauto Pure(auto t)\n{\n    return vector{t};\n}\n\n\nauto Double(int i)\n{\n    return Pure(2 * i);\n}\n\n\nauto Increment(int i)\n{\n    return Pure(i + 1);\n}\n\n\nauto NiceNumber(int i)\n{\n    return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n\n\nauto UpperSequence = [](auto startingVal)\n{\n    const int MaxValue = 500;\n    vector<decltype(startingVal)> sequence;\n    while(startingVal <= MaxValue) \n        sequence.push_back(startingVal++);\n    return sequence;\n};\n\n\nvoid PrintVector(const auto& vec)\n{\n    cout << \" \";\n    for(auto value : vec)\n    {\n        cout << value << \" \";\n    }\n    cout << \"\\n\";\n}\n\n\nvoid PrintTriples(const auto& vec)\n{\n    cout << \"Pythagorean triples:\\n\";\n    for(auto it = vec.begin(); it != vec.end();)\n    {\n        auto x = *it++;\n        auto y = *it++;\n        auto z = *it++;\n        \n        cout << x << \", \" << y << \", \" << z << \"\\n\";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    \n    auto listMonad = \n        vector<int> {2, 3, 4} >> \n        Increment >> \n        Double >>\n        NiceNumber;\n        \n    PrintVector(listMonad);\n    \n    \n    \n    \n    \n    auto pythagoreanTriples = UpperSequence(1) >> \n        [](int x){return UpperSequence(x) >>\n        [x](int y){return UpperSequence(y) >>\n        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};\n    \n    PrintTriples(pythagoreanTriples);\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n    return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n    char buf[100];\n    char*str= malloc(1+sprintf(buf, \"%d\", *x));\n    sprintf(str, \"%d\", *x);\n    return (MONAD)(str);\n}\n\nvoid task(int y) {\n    char *z= INTBIND(boundInt2str, boundInt, &y);\n    printf(\"%s\\n\", z);\n    free(z);\n}\n\nint main() {\n    task(13);\n}\n"}
{"id": 53522, "name": "Special factorials", "C++": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 53523, "name": "Four is magic", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 53524, "name": "Getting the number of decimals", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 53525, "name": "Parse an IP Address", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"}
{"id": 53526, "name": "Parse an IP Address", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"}
{"id": 53527, "name": "Textonyms", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53528, "name": "Textonyms", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53529, "name": "Teacup rim text", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\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#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53530, "name": "Teacup rim text", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\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#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53531, "name": "Increasing gaps between consecutive Niven numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 53532, "name": "Increasing gaps between consecutive Niven numbers", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 53533, "name": "Print debugging statement", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n"}
{"id": 53534, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 53535, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 53536, "name": "Type detection", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n"}
{"id": 53537, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 53538, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 53539, "name": "Variable declaration reset", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n"}
{"id": 53540, "name": "Variable declaration reset", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n"}
{"id": 53541, "name": "Numbers with equal rises and falls", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n"}
{"id": 53542, "name": "Koch curve", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 53543, "name": "Words from neighbour ones", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53544, "name": "Magic squares of singly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n"}
{"id": 53545, "name": "Generate Chess960 starting position", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 53546, "name": "File size distribution", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\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<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n"}
{"id": 53547, "name": "File size distribution", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\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<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n"}
{"id": 53548, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n"}
{"id": 53549, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 53550, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 53551, "name": "Pseudo-random numbers_Xorshift star", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 53552, "name": "ASCII art diagram converter", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n"}
{"id": 53553, "name": "Same fringe", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 53554, "name": "Same fringe", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 53555, "name": "Peaceful chess queen armies", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 53556, "name": "Numbers with same digit set in base 10 and base 16", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 53557, "name": "Largest proper divisor of n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 53558, "name": "Largest proper divisor of n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 53559, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 53560, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 53561, "name": "Sum of first n cubes", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n"}
{"id": 53562, "name": "Test integerness", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n"}
{"id": 53563, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n"}
{"id": 53564, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n"}
{"id": 53565, "name": "Superpermutation minimisation", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53566, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 53567, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 53568, "name": "Summarize and say sequence", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53569, "name": "Summarize and say sequence", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 53570, "name": "Spelling of ordinal numbers", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 53571, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 53572, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 53573, "name": "Addition chains", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 53574, "name": "Numeric separator syntax", "C++": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n"}
{"id": 53575, "name": "Repeat", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 53576, "name": "Sparkline in unicode", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 53577, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 53578, "name": "Sunflower fractal", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 53579, "name": "Vogel's approximation method", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 53580, "name": "Vogel's approximation method", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 53581, "name": "Permutations by swapping", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n"}
{"id": 53582, "name": "Minimum multiple of m where digital sum equals m", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nunsigned digit_sum(unsigned n) {\n    unsigned sum = 0;\n    do { sum += n % 10; }\n    while(n /= 10);\n    return sum;\n}\n\nunsigned a131382(unsigned n) {\n    unsigned m;\n    for (m = 1; n != digit_sum(m*n); m++);\n    return m;\n}\n\nint main() {\n    unsigned n;\n    for (n = 1; n <= 70; n++) {\n        printf(\"%9u\", a131382(n));\n        if (n % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 53583, "name": "Pythagorean quadruples", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 53584, "name": "Steady squares", "C++": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n"}
{"id": 53585, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 53586, "name": "Pseudo-random numbers_Middle-square method", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 53587, "name": "Dice game probabilities", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n"}
{"id": 53588, "name": "Dice game probabilities", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n"}
{"id": 53589, "name": "Halt and catch fire", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n", "C": "int main(){int a=0, b=0, c=a/b;}\n"}
{"id": 53590, "name": "Plasma effect", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n"}
{"id": 53591, "name": "Plasma effect", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n"}
{"id": 53592, "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", "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": 53593, "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", "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": 53594, "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", "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": 53595, "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", "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": 53596, "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", "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": 53597, "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", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 53598, "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", "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": 53599, "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", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 53600, "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", "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": 53601, "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", "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": 53602, "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", "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": 53603, "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", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 53604, "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", "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": 53605, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 53606, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 53607, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 53608, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 53609, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 53610, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 53611, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 53612, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 53613, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 53614, "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", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 53615, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 53616, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 53617, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 53618, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 53619, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 53620, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 53621, "name": "General FizzBuzz", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 53622, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 53623, "name": "Read a specific line from a file", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 53624, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 53625, "name": "File extension is in extensions list", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 53626, "name": "String case", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 53627, "name": "MD5", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 53628, "name": "Date manipulation", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 53629, "name": "Sorting algorithms_Sleep sort", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 53630, "name": "Loops_Nested", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 53631, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 53632, "name": "Pythagorean triples", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 53633, "name": "Remove duplicate elements", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 53634, "name": "Look-and-say sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 53635, "name": "Stack", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 53636, "name": "Conditional structures", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 53637, "name": "Sorting algorithms_Stooge sort", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 53638, "name": "Read a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 53639, "name": "Sort using a custom comparator", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 53640, "name": "Sorting algorithms_Selection sort", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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 selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 53641, "name": "Apply a callback to an array", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 53642, "name": "Singleton", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 53643, "name": "Case-sensitivity of identifiers", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 53644, "name": "Loops_Downward for", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 53645, "name": "Write entire file", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 53646, "name": "Loops_For", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 53647, "name": "Long multiplication", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 53648, "name": "Bulls and cows", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 53649, "name": "Sorting algorithms_Bubble sort", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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 bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 53650, "name": "File input_output", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 53651, "name": "Arithmetic_Integer", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 53652, "name": "Matrix transposition", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 53653, "name": "Man or boy test", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 53654, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 53655, "name": "Find limit of recursion", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 53656, "name": "Perfect numbers", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 53657, "name": "Sorting algorithms_Bead sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 53658, "name": "Arbitrary-precision integers (included)", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 53659, "name": "Inverted index", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 53660, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 53661, "name": "Least common multiple", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 53662, "name": "Loops_Break", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 53663, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 53664, "name": "Hello world_Line printer", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 53665, "name": "Trabb Pardo–Knuth algorithm", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 53666, "name": "Middle three digits", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 53667, "name": "Odd word problem", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 53668, "name": "Table creation_Postal addresses", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 53669, "name": "Soundex", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 53670, "name": "Bitmap_Histogram", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 53671, "name": "Literals_String", "C": "char ch = 'z';\n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 53672, "name": "Enumerations", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 53673, "name": "SOAP", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n"}
{"id": 53674, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 53675, "name": "Execute Brain____", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 53676, "name": "Modulinos", "C": "int meaning_of_life();\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 53677, "name": "Modulinos", "C": "int meaning_of_life();\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 53678, "name": "Unix_ls", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 53679, "name": "Calendar - for _REAL_ programmers", "C": "\n\n\n\n\n\nINT PUTCHAR(INT);\n\nINT WIDTH = 80, YEAR = 1969;\nINT COLS, LEAD, GAP;\n \nCONST CHAR *WDAYS[] = { \"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\" };\nSTRUCT MONTHS {\n    CONST CHAR *NAME;\n    INT DAYS, START_WDAY, AT;\n} MONTHS[12] = {\n    { \"JANUARY\",    31, 0, 0 },\n    { \"FEBRUARY\",    28, 0, 0 },\n    { \"MARCH\",    31, 0, 0 },\n    { \"APRIL\",    30, 0, 0 },\n    { \"MAY\",    31, 0, 0 },\n    { \"JUNE\",    30, 0, 0 },\n    { \"JULY\",    31, 0, 0 },\n    { \"AUGUST\",    31, 0, 0 },\n    { \"SEPTEMBER\",    30, 0, 0 },\n    { \"OCTOBER\",    31, 0, 0 },\n    { \"NOVEMBER\",    30, 0, 0 },\n    { \"DECEMBER\",    31, 0, 0 }\n};\n \nVOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }\nVOID PRINT(CONST CHAR * S){ WHILE (*S != '\\0') { PUTCHAR(*S++); } }\nINT  STRLEN(CONST CHAR * S)\n{\n   INT L = 0;\n   WHILE (*S++ != '\\0') { L ++; };\nRETURN L;\n}\nINT ATOI(CONST CHAR * S)\n{\n    INT I = 0;\n    INT SIGN = 1;\n    CHAR C;\n    WHILE ((C = *S++) != '\\0') {\n        IF (C == '-')\n            SIGN *= -1;\n        ELSE {\n            I *= 10;\n            I += (C - '0');\n        }\n    }\nRETURN I * SIGN;\n}\n\nVOID INIT_MONTHS(VOID)\n{\n    INT I;\n \n    IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))\n        MONTHS[1].DAYS = 29;\n \n    YEAR--;\n    MONTHS[0].START_WDAY\n        = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;\n \n    FOR (I = 1; I < 12; I++)\n        MONTHS[I].START_WDAY =\n            (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;\n \n    COLS = (WIDTH + 2) / 22;\n    WHILE (12 % COLS) COLS--;\n    GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;\n    IF (GAP > 4) GAP = 4;\n    LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;\n        YEAR++;\n}\n \nVOID PRINT_ROW(INT ROW)\n{\n    INT C, I, FROM = ROW * COLS, TO = FROM + COLS;\n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        I = STRLEN(MONTHS[C].NAME);\n        SPACE((20 - I)/2);\n        PRINT(MONTHS[C].NAME);\n        SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));\n    }\n    PUTCHAR('\\012');\n \n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        FOR (I = 0; I < 7; I++) {\n            PRINT(WDAYS[I]);\n            PRINT(I == 6 ? \"\" : \" \");\n        }\n        IF (C < TO - 1) SPACE(GAP);\n        ELSE PUTCHAR('\\012');\n    }\n \n    WHILE (1) {\n        FOR (C = FROM; C < TO; C++)\n            IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;\n        IF (C == TO) BREAK;\n \n        SPACE(LEAD);\n        FOR (C = FROM; C < TO; C++) {\n            FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);\n            WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {\n                INT MM = ++MONTHS[C].AT;\n                PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));\n                PUTCHAR('0' + (MM %10));\n                IF (I < 7 || C < TO - 1) PUTCHAR(' ');\n            }\n            WHILE (I++ <= 7 && C < TO - 1) SPACE(3);\n            IF (C < TO - 1) SPACE(GAP - 1);\n            MONTHS[C].START_WDAY = 0;\n        }\n        PUTCHAR('\\012');\n    }\n    PUTCHAR('\\012');\n}\n \nVOID PRINT_YEAR(VOID)\n{\n    INT Y = YEAR;\n    INT ROW;\n    CHAR BUF[32];\n    CHAR * B = &(BUF[31]);\n    *B-- = '\\0';\n    DO {\n        *B-- = '0' + (Y % 10);\n        Y /= 10;\n    } WHILE (Y > 0);\n    B++;\n    SPACE((WIDTH - STRLEN(B)) / 2);\n    PRINT(B);PUTCHAR('\\012');PUTCHAR('\\012');\n    FOR (ROW = 0; ROW * COLS < 12; ROW++)\n        PRINT_ROW(ROW);\n}\n \nINT MAIN(INT C, CHAR **V)\n{\n    INT I, YEAR_SET = 0, RESULT = 0;\n    FOR (I = 1; I < C && RESULT == 0; I++) {\n        IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\\0') {\n            IF (++I == C || (WIDTH = ATOI(V[I])) < 20)\n                RESULT = 1;\n        } ELSE IF (!YEAR_SET) {\n            YEAR = ATOI(V[I]);\n            IF (YEAR <= 0)\n                YEAR = 1969;\n            YEAR_SET = 1;\n        } ELSE\n            RESULT = 1;\n    }\n \n    IF (RESULT == 0) {\n        INIT_MONTHS();\n        PRINT_YEAR();\n    } ELSE {\n        PRINT(\"BAD ARGS\\012USAGE: \");\n        PRINT(V[0]);\n        PRINT(\" YEAR [-W WIDTH (>= 20)]\\012\");\n    }\nRETURN RESULT;\n}\n", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n"}
{"id": 53680, "name": "Move-to-front algorithm", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 53681, "name": "Active Directory_Search for a user", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 53682, "name": "Execute a system command", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 53683, "name": "XML validation", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 53684, "name": "Longest increasing subsequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 53685, "name": "Brace expansion", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 53686, "name": "Self-describing numbers", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 53687, "name": "Modular inverse", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 53688, "name": "Hello world_Web server", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 53689, "name": "Bitmap_Bézier curves_Cubic", "C": "void cubic_bezier(\n       \timage img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        unsigned int x4, unsigned int y4,\n        color_component r,\n        color_component g,\n        color_component b );\n", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n"}
{"id": 53690, "name": "Active Directory_Connect", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 53691, "name": "Update a configuration file", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 53692, "name": "Variables", "C": "int j;\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 53693, "name": "Periodic table", "C": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\n\nGD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );\nint select_box_chemical_elem( RDS(MT_CELL, Elements) );\nvoid put_information(RDS( MT_CELL, elem), int i);\n\nMain\n   \n   GD_VIDEO table;\n   \n   Resize_terminal(42,135);\n   Init_video( &table );\n   \n   Gpm_Connect conn;\n\n   if ( ! Init_mouse(&conn)){\n        Msg_red(\"No se puede conectar al servidor del ratón\\n\");\n        Stop(1);\n   }  \n   Enable_raw_mode();\n   Hide_cursor;\n\n   \n   New multitype Elements;\n   Elements = load_chem_elements( pSDS(Elements) );\n   Throw( load_fail );\n   \n  \n   New objects Btn_exit;\n   Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, \"  Terminar  \", 6,44, 15, 0);\n\n  \n   table = put_chemical_cell( table, SDS(Elements) );\n\n  \n   Refresh(table);\n   Put object Btn_exit;\n  \n  \n   int c;\n   Waiting_some_clic(c)\n   {\n       if( select_box_chemical_elem(SDS(Elements)) ){\n           Waiting_some_clic(c) break;\n       }\n       if (Object_mouse( Btn_exit)) break;\n       \n       Refresh(table);\n       Put object Btn_exit;\n   }\n\n   Free object Btn_exit;\n   Free multitype Elements;\n   \n   Exception( load_fail ){\n      Msg_red(\"No es un archivo matriciable\");\n   }\n\n   Free video table;\n   Disable_raw_mode();\n   Close_mouse();\n   Show_cursor;\n   \n   At SIZE_TERM_ROWS,0;\n   Prnl;\nEnd\n\nvoid put_information(RDS(MT_CELL, elem), int i)\n{\n    At 2,19;\n    Box_solid(11,64,67,17);\n    Color(15,17);\n    At 4,22; Print \"Elemento (%s) = %s\", (char*)$s-elem[i,5],(char*)$s-elem[i,6];\n    if (Cell_type(elem,i,7) == double_TYPE ){\n        At 5,22; Print \"Peso atómico  = %f\", $d-elem[i,7];\n    }else{\n        At 5,22; Print \"Peso atómico  = (%ld)\", $l-elem[i,7];\n    }\n    At 6,22; Print \"Posición      = (%ld, %ld)\",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;\n    At 8,22; Print \"1ª energía de\";\n    if (Cell_type(elem,i,12) == double_TYPE ){\n        At 9,22; Print \"ionización (kJ/mol) = %.*f\",2,$d-elem[i,12];\n    }else{\n        At 9,22; Print \"ionización (kJ/mol) = ---\";\n    }\n    if (Cell_type(elem,i,13) == double_TYPE ){\n        At 10,22; Print \"Electronegatividad  = %.*f\",2,$d-elem[i,13];\n    }else{\n        At 10,22; Print \"Electronegatividad  = ---\";\n    }\n    At 4,56; Print \"Conf. electrónica:\";\n    At 5,56; Print \"       %s\", (char*)$s-elem[i,14];\n    At 7,56; Print \"Estados de oxidación:\";\n    if ( Cell_type(elem,i,15) == string_TYPE ){\n        At 8,56; Print \"       %s\", (char*)$s-elem[i,15];\n    }else{\n       \n        At 8,56; Print \"       %ld\", $l-elem[i,15];\n    }\n    At 10,56; Print \"Número Atómico: %ld\",$l-elem[i,4];\n    Reset_color;\n}\n\nint select_box_chemical_elem( RDS(MT_CELL, elem) )\n{\n   int i;\n   Iterator up i [0:1:Rows(elem)]{\n       if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){\n           Gotoxy( $l-elem[i,8], $l-elem[i,9] );\n           Color_fore( 15 ); Color_back( 0 );\n           Box( 4,5, DOUB_ALL );\n\n           Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print \"%ld\",$l-elem[i,4];\n           Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print \"%s\",(char*)$s-elem[i,5];\n           Flush_out;\n           Reset_color;\n           put_information(SDS(elem),i);\n           return 1;\n       }\n   }\n   return 0;\n}\n\nGD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)\n{\n   int i;\n   \n   \n   Iterator up i [0:1:Rows(elem)]{\n       long rx = 2+($l-elem[i,0]*4);\n       long cx = 3+($l-elem[i,1]*7);\n       long offr = rx+3;\n       long offc = cx+6;\n\n       Gotoxy(table, rx, cx);\n\n       Color_fore(table, $l-elem[i,2]);\n       Color_back(table,$l-elem[i,3]);\n\n       Box(table, 4,5, SING_ALL );\n\n       char Atnum[50], Elem[50];\n       sprintf(Atnum,\"\\x1b[3m%ld\\x1b[23m\",$l-elem[i,4]);\n       sprintf(Elem, \"\\x1b[1m%s\\x1b[22m\",(char*)$s-elem[i,5]);\n\n       Outvid(table,rx+1, cx+2, Atnum);\n       Outvid(table,rx+2, cx+2, Elem);\n\n       Reset_text(table);\n       \n       $l-elem[i,8] = rx;\n       $l-elem[i,9] = cx;\n       $l-elem[i,10] = offr;\n       $l-elem[i,11] = offc;\n       \n   }\n   \n   Iterator up i [ 1: 1: 19 ]{\n       Gotoxy(table, 31, 5+(i-1)*7);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Iterator up i [ 1: 1: 8 ]{\n       Gotoxy(table, 3+(i-1)*4, 130);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Outvid( table, 35,116, \"8\");\n   Outvid( table, 39,116, \"9\");\n   \n   \n   Color_fore(table, 15);\n   Color_back(table, 0);\n   Outvid(table,35,2,\"Lantánidos ->\");\n   Outvid(table,39,2,\"Actínidos  ->\");\n   Reset_text(table);\n   return table;\n}\n\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )\n{\n   F_STAT dataFile = Stat_file(\"chem_table.txt\");\n   if( dataFile.is_matrix ){\n       \n       Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n       E = Load_matrix_mt( SDS(E), \"chem_table.txt\", dataFile, DET_LONG);\n   }else{\n       Is_ok=0;\n   }\n   return E;\n}\n", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n"}
{"id": 53694, "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", "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": 53695, "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", "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": 53696, "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", "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": 53697, "name": "Bitmap_Write a PPM file", "C++": "#include <fstream>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    std::ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\\n\" << dimx << ' ' << dimy << \"\\n255\\n\";\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << static_cast<char>(i % 256) \n                << static_cast<char>(j % 256)\n                << static_cast<char>((i * j) % 256);\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": 53698, "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", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 53699, "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", "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": 53700, "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", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 53701, "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", "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": 53702, "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", "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": 53703, "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", "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": 53704, "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", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 53705, "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", "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": 53706, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 53707, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 53708, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 53709, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 53710, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 53711, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 53712, "name": "DNS query", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 53713, "name": "Rock-paper-scissors", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\n\n", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 53714, "name": "Y combinator", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 53715, "name": "Return multiple values", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 53716, "name": "FTP", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 53717, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 53718, "name": "24 game", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 53719, "name": "Loops_Continue", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 53720, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 53721, "name": "Colour bars_Display", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 53722, "name": "General FizzBuzz", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 53723, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 53724, "name": "Read a specific line from a file", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 53725, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 53726, "name": "File extension is in extensions list", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 53727, "name": "String case", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 53728, "name": "MD5", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 53729, "name": "Date manipulation", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 53730, "name": "Sorting algorithms_Sleep sort", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 53731, "name": "Loops_Nested", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 53732, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 53733, "name": "Pythagorean triples", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 53734, "name": "Remove duplicate elements", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 53735, "name": "Look-and-say sequence", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 53736, "name": "Stack", "C++": "#include <stack>\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 53737, "name": "Conditional structures", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 53738, "name": "Sorting algorithms_Stooge sort", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 53739, "name": "Read a configuration file", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 53740, "name": "Sort using a custom comparator", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 53741, "name": "Sorting algorithms_Selection sort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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 selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 53742, "name": "Apply a callback to an array", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 53743, "name": "Singleton", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 53744, "name": "Case-sensitivity of identifiers", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 53745, "name": "Loops_Downward for", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 53746, "name": "Write entire file", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 53747, "name": "Loops_For", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 53748, "name": "Long multiplication", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 53749, "name": "Bulls and cows", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 53750, "name": "Sorting algorithms_Bubble sort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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 bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 53751, "name": "File input_output", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 53752, "name": "Arithmetic_Integer", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 53753, "name": "Matrix transposition", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 53754, "name": "Man or boy test", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 53755, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 53756, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 53757, "name": "Perfect numbers", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 53758, "name": "Sorting algorithms_Bead sort", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 53759, "name": "Arbitrary-precision integers (included)", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 53760, "name": "Inverted index", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 53761, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 53762, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 53763, "name": "Loops_Break", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 53764, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 53765, "name": "Hello world_Line printer", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 53766, "name": "Trabb Pardo–Knuth algorithm", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 53767, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 53768, "name": "Odd word problem", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 53769, "name": "Literals_String", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 53770, "name": "Enumerations", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 53771, "name": "Modulinos", "C++": "int meaning_of_life();\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 53772, "name": "Modulinos", "C++": "int meaning_of_life();\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 53773, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 53774, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 53775, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 53776, "name": "Brace expansion", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 53777, "name": "Self-describing numbers", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 53778, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 53779, "name": "Literals_Floating point", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 53780, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 53781, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 53782, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 53783, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 53784, "name": "Object serialization", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 53785, "name": "Long year", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 53786, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 53787, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 53788, "name": "Markov chain text generator", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 53789, "name": "Dijkstra's algorithm", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 53790, "name": "Associative array_Iteration", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 53791, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 53792, "name": "Here document", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 53793, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 53794, "name": "Respond to an unknown method call", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 53795, "name": "Inheritance_Single", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 53796, "name": "Associative array_Creation", "C++": "#include <map>\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 53797, "name": "Polymorphism", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 53798, "name": "Variables", "C++": "int a;\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 53799, "name": "Monads_Writer monad", "C++": "#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct LoggingMonad\n{\n    double Value;\n    string Log;\n};\n\n\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n    auto result = f(monad.Value);\n    return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n\nauto MakeWriter = [](auto f, string message)\n{\n    return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n    \n    auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n    cout << result.Log << \"\\nResult: \" << result.Value;\n}\n", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n"}
{"id": 53800, "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", "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": 53801, "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", "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": 53802, "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", "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": 53803, "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", "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": 53804, "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", "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": 53805, "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", "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": 53806, "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", "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": 53807, "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", "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": 53808, "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", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 53809, "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", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 53810, "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", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 53811, "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", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 53812, "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", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 53813, "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", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 53814, "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", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 53815, "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", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 53816, "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", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\n"}
{"id": 53817, "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", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 53818, "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", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n"}
{"id": 53819, "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", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\n"}
{"id": 53820, "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", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n"}
{"id": 53821, "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", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 53822, "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", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 53823, "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", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 53824, "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", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 53825, "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", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 53826, "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", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 53827, "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", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 53828, "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", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 53829, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 53830, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 53831, "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", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 53832, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 53833, "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", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 53834, "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", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 53835, "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", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 53836, "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", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n"}
{"id": 53837, "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", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 53838, "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", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 53839, "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", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n"}
{"id": 53840, "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", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\n"}
{"id": 53841, "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", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\n"}
{"id": 53842, "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", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 53843, "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", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 53844, "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", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 53845, "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", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n"}
{"id": 53846, "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", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 53847, "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", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n"}
{"id": 53848, "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", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n"}
{"id": 53849, "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", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 53850, "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", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 53851, "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", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 53852, "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", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 53853, "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", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 53854, "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", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 53855, "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", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 53856, "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", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n"}
{"id": 53857, "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", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 53858, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 53859, "name": "Write entire file", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 53860, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 53861, "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", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 53862, "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", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 53863, "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", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 53864, "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", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 53865, "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", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n"}
{"id": 53866, "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", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 53867, "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", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 53868, "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", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 53869, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 53870, "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", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 53871, "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", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 53872, "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", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 53873, "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", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 53874, "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", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 53875, "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", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 53876, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 53877, "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", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 53878, "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", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 53879, "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", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 53880, "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", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 53881, "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", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 53882, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 53883, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 53884, "name": "Carmichael 3 strong pseudoprimes", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 53885, "name": "Image noise", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 53886, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 53887, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 53888, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 53889, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 53890, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 53891, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 53892, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 53893, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 53894, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 53895, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 53896, "name": "Fermat numbers", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class FermatNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 Fermat numbers:\");\n        for ( int i = 0 ; i < 10 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, fermat(i));\n        }\n        System.out.printf(\"%nFirst 12 Fermat numbers factored:%n\");\n        for ( int i = 0 ; i < 13 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, getString(getFactors(i, fermat(i))));\n        }\n    }\n    \n    private static String getString(List<BigInteger> factors) {\n        if ( factors.size() == 1 ) {\n            return factors.get(0) + \" (PRIME)\";\n        }\n        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith(\"-\") ? \"(C\" + v.replace(\"-\", \"\") + \")\" : v).collect(Collectors.joining(\" * \"));\n    }\n\n    private static Map<Integer, String> COMPOSITE = new HashMap<>();\n    static {\n        COMPOSITE.put(9, \"5529\");\n        COMPOSITE.put(10, \"6078\");\n        COMPOSITE.put(11, \"1037\");\n        COMPOSITE.put(12, \"5488\");\n        COMPOSITE.put(13, \"2884\");\n    }\n\n    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {\n        List<BigInteger> factors = new ArrayList<>();\n        BigInteger factor = BigInteger.ONE;\n        while ( true ) {\n            if ( n.isProbablePrime(100) ) {\n                factors.add(n);\n                break;\n            }\n            else {\n                if ( COMPOSITE.containsKey(fermatIndex) ) {\n                    String stop = COMPOSITE.get(fermatIndex);\n                    if ( n.toString().startsWith(stop) ) {\n                        factors.add(new BigInteger(\"-\" + n.toString().length()));\n                        break;\n                    }\n                }\n                factor = pollardRhoFast(n);\n                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {\n                    factors.add(n);\n                    break;\n                }\n                else {\n                    factors.add(factor);\n                    n = n.divide(factor);\n                }\n            }\n        }\n        return factors;\n    }\n    \n    private static final BigInteger TWO = BigInteger.valueOf(2);\n    \n    private static BigInteger fermat(int n) {\n        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);\n    }\n        \n    \n    @SuppressWarnings(\"unused\")\n    private static BigInteger pollardRho(BigInteger n) {\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        while ( d.compareTo(BigInteger.ONE) == 0 ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs().gcd(n);\n        }\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n    \n    \n    \n    \n    \n    \n    private static BigInteger pollardRhoFast(BigInteger n) {\n        long start = System.currentTimeMillis();\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        int count = 0;\n        BigInteger z = BigInteger.ONE;\n        while ( true ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs();\n            z = z.multiply(d).mod(n);\n            count++;\n            if ( count == 100 ) {\n                d = z.gcd(n);\n                if ( d.compareTo(BigInteger.ONE) != 0 ) {\n                    break;\n                }\n                z = BigInteger.ONE;\n                count = 0;\n            }\n        }\n        long end = System.currentTimeMillis();\n        System.out.printf(\"    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n\", n, (end-start), d);\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n\n    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {\n        return x.multiply(x).add(BigInteger.ONE).mod(n);\n    }\n\n}\n"}
{"id": 53897, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 53898, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 53899, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 53900, "name": "Water collected between towers", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n"}
{"id": 53901, "name": "Square-free integers", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 53902, "name": "Jaro similarity", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n"}
{"id": 53903, "name": "Sum and product puzzle", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n"}
{"id": 53904, "name": "Fairshare between two and more", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 53905, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 53906, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 53907, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 53908, "name": "Sequence_ nth number with exactly n divisors", "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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n"}
{"id": 53909, "name": "Sequence_ smallest number with exactly n divisors", "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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n"}
{"id": 53910, "name": "Pancake numbers", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 53911, "name": "Generate random chess position", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n"}
{"id": 53912, "name": "Esthetic numbers", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n"}
{"id": 53913, "name": "Topswops", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n"}
{"id": 53914, "name": "Old Russian measure of length", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n"}
{"id": 53915, "name": "Rate counter", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n"}
{"id": 53916, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 53917, "name": "Pythagoras tree", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 53918, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 53919, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 53920, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 53921, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 53922, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 53923, "name": "Sine wave", "Python": "\n\nimport os\nfrom math import pi, sin\n\n\nau_header = bytearray(\n            [46, 115, 110, 100,   \n              0,   0,   0,  24,   \n            255, 255, 255, 255,   \n              0,   0,   0,   3,   \n              0,   0, 172,  68,   \n              0,   0,   0,   1])  \n\ndef f(x, freq):\n    \"Compute sine wave as 16-bit integer\"\n    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536\n\ndef play_sine(freq=440, duration=5, oname=\"pysine.au\"):\n    \"Play a sine wave for `duration` seconds\"\n    out = open(oname, 'wb')\n    out.write(au_header)\n    v = [f(x, freq) for x in range(duration * 44100 + 1)]\n    s = []\n    for i in v:\n        s.append(i >> 8)\n        s.append(i % 256)\n    out.write(bytearray(s))\n    out.close()\n    os.system(\"vlc \" + oname)   \n\nplay_sine()\n", "Java": "import processing.sound.*;\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\nsine.freq(500);\nsine.play();\n\ndelay(5000);\n"}
{"id": 53924, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n"}
{"id": 53925, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n"}
{"id": 53926, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n"}
{"id": 53927, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n"}
{"id": 53928, "name": "Numeric error propagation", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n"}
{"id": 53929, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n"}
{"id": 53930, "name": "List rooted trees", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n"}
{"id": 53931, "name": "Documentation", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n"}
{"id": 53932, "name": "Problem of Apollonius", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n"}
{"id": 53933, "name": "Longest common suffix", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n"}
{"id": 53934, "name": "Chat server", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 53935, "name": "Idiomatically determine all the lowercase and uppercase letters", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n"}
{"id": 53936, "name": "Idiomatically determine all the lowercase and uppercase letters", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n"}
{"id": 53937, "name": "Sum of elements below main diagonal of matrix", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n"}
{"id": 53938, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 53939, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 53940, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n"}
{"id": 53941, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n"}
{"id": 53942, "name": "FASTA format", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 53943, "name": "FASTA format", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 53944, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 53945, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 53946, "name": "Window creation_X11", "Python": "from Xlib import X, display\n\nclass Window:\n    def __init__(self, display, msg):\n        self.display = display\n        self.msg = msg\n        \n        self.screen = self.display.screen()\n        self.window = self.screen.root.create_window(\n            10, 10, 100, 100, 1,\n            self.screen.root_depth,\n            background_pixel=self.screen.white_pixel,\n            event_mask=X.ExposureMask | X.KeyPressMask,\n            )\n        self.gc = self.window.create_gc(\n            foreground = self.screen.black_pixel,\n            background = self.screen.white_pixel,\n            )\n\n        self.window.map()\n\n    def loop(self):\n        while True:\n            e = self.display.next_event()\n                \n            if e.type == X.Expose:\n                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n                self.window.draw_text(self.gc, 10, 50, self.msg)\n            elif e.type == X.KeyPress:\n                raise SystemExit\n\n                \nif __name__ == \"__main__\":\n    Window(display.Display(), \"Hello, World!\").loop()\n", "Java": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n  public static void main(String[] args) {\n    Runnable runnable = new Runnable() {\n      public void run() {\n\tcreateAndShow();\n      }\n    };\n    SwingUtilities.invokeLater(runnable);\n  }\n\t\n  static void createAndShow() {\n    JFrame frame = new JFrame(\"Hello World\");\n    frame.setSize(640,480);\n    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n}\n"}
{"id": 53947, "name": "Finite state machine", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n"}
{"id": 53948, "name": "Vibrating rectangles", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n", "Java": "\n\nint counter = 100;\n\nvoid setup(){\n  size(1000,1000);\n}\n\nvoid draw(){\n  \n  for(int i=0;i<20;i++){\n    fill(counter - 5*i);\n    rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);\n  }\n  counter++;\n  \n  if(counter > 255)\n    counter = 100;\n  \n  delay(100);\n}\n"}
{"id": 53949, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 53950, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 53951, "name": "Pseudo-random numbers_PCG32", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 53952, "name": "Deconvolution_1D", "Python": "def ToReducedRowEchelonForm( M ):\n    if not M: return\n    lead = 0\n    rowCount = len(M)\n    columnCount = len(M[0])\n    for r in range(rowCount):\n        if lead >= columnCount:\n            return\n        i = r\n        while M[i][lead] == 0:\n            i += 1\n            if i == rowCount:\n                i = r\n                lead += 1\n                if columnCount == lead:\n                    return\n        M[i],M[r] = M[r],M[i]\n        lv = M[r][lead]\n        M[r] = [ mrx / lv for mrx in M[r]]\n        for i in range(rowCount):\n            if i != r:\n                lv = M[i][lead]\n                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n        lead += 1\n    return M\n \ndef pmtx(mtx):\n    print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n \ndef convolve(f, h):\n    g = [0] * (len(f) + len(h) - 1)\n    for hindex, hval in enumerate(h):\n        for findex, fval in enumerate(f):\n            g[hindex + findex] += fval * hval\n    return g\n\ndef deconvolve(g, f):\n    lenh = len(g) - len(f) + 1\n    mtx = [[0 for x in range(lenh+1)] for y in g]\n    for hindex in range(lenh):\n        for findex, fval in enumerate(f):\n            gindex = hindex + findex\n            mtx[gindex][hindex] = fval\n    for gindex, gval in enumerate(g):        \n        mtx[gindex][lenh] = gval\n    ToReducedRowEchelonForm( mtx )\n    return [mtx[i][lenh] for i in range(lenh)]  \n\nif __name__ == '__main__':\n    h = [-8,-9,-3,-1,-6,7]\n    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n    assert convolve(f,h) == g\n    assert deconvolve(g, f) == h\n", "Java": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n    public static int[] deconv(int[] g, int[] f) {\n        int[] h = new int[g.length - f.length + 1];\n        for (int n = 0; n < h.length; n++) {\n            h[n] = g[n];\n            int lower = Math.max(n - f.length + 1, 0);\n            for (int i = lower; i < n; i++)\n                h[n] -= h[i] * f[n - i];\n            h[n] /= f[0];\n        }\n        return h;\n    }\n\n    public static void main(String[] args) {\n        int[] h = { -8, -9, -3, -1, -6, 7 };\n        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n                96, 31, 55, 36, 29, -43, -7 };\n\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n        sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n        sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n        sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n        System.out.println(sb.toString());\n    }\n}\n"}
{"id": 53953, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 53954, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 53955, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 53956, "name": "Disarium numbers", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n"}
{"id": 53957, "name": "Disarium numbers", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n"}
{"id": 53958, "name": "Sierpinski pentagon", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n"}
{"id": 53959, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n"}
{"id": 53960, "name": "Mutex", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n", "Java": "import java.util.concurrent.Semaphore;\n\npublic class VolatileClass{\n   public Semaphore mutex = new Semaphore(1); \n                                              \n   public void needsToBeSynched(){\n      \n   }\n   \n}\n"}
{"id": 53961, "name": "Metronome", "Python": "\nimport time\n\ndef main(bpm = 72, bpb = 4):\n    sleep = 60.0 / bpm\n    counter = 0\n    while True:\n        counter += 1\n        if counter % bpb:\n            print 'tick'\n        else:\n            print 'TICK'\n        time.sleep(sleep)\n        \n\n\nmain()\n", "Java": "class Metronome{\n\tdouble bpm;\n\tint measure, counter;\n\tpublic Metronome(double bpm, int measure){\n\t\tthis.bpm = bpm;\n\t\tthis.measure = measure;\t\n\t}\n\tpublic void start(){\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tThread.sleep((long)(1000*(60.0/bpm)));\n\t\t\t}catch(InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tcounter++;\n\t\t\tif (counter%measure==0){\n\t\t\t\t System.out.println(\"TICK\");\n\t\t\t}else{\n\t\t\t\t System.out.println(\"TOCK\");\n\t\t\t}\n\t\t}\n\t}\n}\npublic class test {\n\tpublic static void main(String[] args) {\n\t\tMetronome metronome1 = new Metronome(120,4);\n\t\tmetronome1.start();\n\t}\n}\n"}
{"id": 53962, "name": "EKG sequence convergence", "Python": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n    \n    c = count(start + 1)\n    last, so_far = start, list(range(2, start))\n    yield 1, []\n    yield last, []\n    while True:\n        for index, sf in enumerate(so_far):\n            if gcd(last, sf) > 1:\n                last = so_far.pop(index)\n                yield last, so_far[::]\n                break\n        else:\n            so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n    \"Returns the convergence point or zero if not found within the limit\"\n    ekg = [EKG_gen(n) for n in ekgs]\n    for e in ekg:\n        next(e)    \n    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),\n                                  zip(*ekg))))\n\nif __name__ == '__main__':\n    for start in 2, 5, 7, 9, 10:\n        print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n    print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n    public static void main(String[] args) {\n        System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n        for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n            System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n        }\n        System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n        List<Integer> ekg5 = ekg(5, 100);\n        List<Integer> ekg7 = ekg(7, 100);\n        for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n            if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n                System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n                break;\n            }\n        }\n    }\n    \n    \n    private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {\n        List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));\n        Collections.sort(list1);\n        List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));\n        Collections.sort(list2);\n        for ( int i = 0 ; i < n ; i++ ) {\n            if ( list1.get(i) != list2.get(i) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    \n    \n    private static List<Integer> ekg(int two, int maxN) {\n        List<Integer> result = new ArrayList<>();\n        result.add(1);\n        result.add(two);\n        Map<Integer,Integer> seen = new HashMap<>();\n        seen.put(1, 1);\n        seen.put(two, 1);\n        int minUnseen = two == 2 ? 3 : 2;\n        int prev = two;\n        for ( int n = 3 ; n <= maxN ; n++ ) {\n            int test = minUnseen - 1;\n            while ( true ) {\n                test++;\n                if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n                    \n                    result.add(test);\n                    seen.put(test, n);\n                    prev = test;\n                    if ( minUnseen == test ) {\n                        do {\n                            minUnseen++;\n                        } while ( seen.containsKey(minUnseen) );\n                    }\n                    break;\n                }\n            }\n        }\n        return result;\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": 53963, "name": "Rep-string", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n"}
{"id": 53964, "name": "Terminal control_Preserve screen", "Python": "\n\nimport time\n\nprint \"\\033[?1049h\\033[H\"\nprint \"Alternate buffer!\"\n\nfor i in xrange(5, 0, -1):\n    print \"Going back in:\", i\n    time.sleep(1)\n\nprint \"\\033[?1049l\"\n", "Java": "public class PreserveScreen\n{\n    public static void main(String[] args) throws InterruptedException {\n        System.out.print(\"\\033[?1049h\\033[H\");\n        System.out.println(\"Alternate screen buffer\\n\");\n        for (int i = 5; i > 0; i--) {\n            String s = (i > 1) ? \"s\" : \"\";\n            System.out.printf(\"\\rgoing back in %d second%s...\", i, s);\n            Thread.sleep(1000);\n        }\n        System.out.print(\"\\033[?1049l\");\n    }\n}\n"}
{"id": 53965, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 53966, "name": "Changeable words", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n"}
{"id": 53967, "name": "Window management", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n"}
{"id": 53968, "name": "Window management", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n"}
{"id": 53969, "name": "Next special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 53970, "name": "Next special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 53971, "name": "Mayan numerals", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.math.BigInteger;\n\npublic class MayanNumerals {\n\n    public static void main(String[] args) {\n        for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {\n            displayMyan(BigInteger.valueOf(base10));\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static char[] digits = \"0123456789ABCDEFGHJK\".toCharArray();\n    private static BigInteger TWENTY = BigInteger.valueOf(20);\n    \n    private static void displayMyan(BigInteger numBase10) {\n        System.out.printf(\"As base 10:  %s%n\", numBase10);\n        String numBase20 = \"\";\n        while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {\n            numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;\n            numBase10 = numBase10.divide(TWENTY);\n        }\n        System.out.printf(\"As base 20:  %s%nAs Mayan:%n\", numBase20);\n        displayMyanLine1(numBase20);\n        displayMyanLine2(numBase20);\n        displayMyanLine3(numBase20);\n        displayMyanLine4(numBase20);\n        displayMyanLine5(numBase20);\n        displayMyanLine6(numBase20);\n    }\n \n    private static char boxUL = Character.toChars(9556)[0];\n    private static char boxTeeUp = Character.toChars(9574)[0];\n    private static char boxUR = Character.toChars(9559)[0];\n    private static char boxHorz = Character.toChars(9552)[0];\n    private static char boxVert = Character.toChars(9553)[0];\n    private static char theta = Character.toChars(952)[0];\n    private static char boxLL = Character.toChars(9562)[0];\n    private static char boxLR = Character.toChars(9565)[0];\n    private static char boxTeeLow = Character.toChars(9577)[0];\n    private static char bullet = Character.toChars(8729)[0];\n    private static char dash = Character.toChars(9472)[0];\n    \n    private static void displayMyanLine1(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxUL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeUp : boxUR);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String getBullet(int count) {\n        StringBuilder sb = new StringBuilder();\n        switch ( count ) {\n        case 1:  sb.append(\" \" + bullet + \"  \"); break;\n        case 2:  sb.append(\" \" + bullet + bullet + \" \"); break;\n        case 3:  sb.append(\"\" + bullet + bullet + bullet + \" \"); break;\n        case 4:  sb.append(\"\" + bullet + bullet + bullet + bullet); break;\n        default:  throw new IllegalArgumentException(\"Must be 1-4:  \" + count);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine2(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'G':  sb.append(getBullet(1)); break;\n            case 'H':  sb.append(getBullet(2)); break;\n            case 'J':  sb.append(getBullet(3)); break;\n            case 'K':  sb.append(getBullet(4)); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String DASH = getDash();\n    \n    private static String getDash() {\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < 4 ; i++ ) {\n            sb.append(dash);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine3(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'B':  sb.append(getBullet(1)); break;\n            case 'C':  sb.append(getBullet(2)); break;\n            case 'D':  sb.append(getBullet(3)); break;\n            case 'E':  sb.append(getBullet(4)); break;\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine4(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '6':  sb.append(getBullet(1)); break;\n            case '7':  sb.append(getBullet(2)); break;\n            case '8':  sb.append(getBullet(3)); break;\n            case '9':  sb.append(getBullet(4)); break;\n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine5(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '0':  sb.append(\" \" + theta + \"  \"); break;\n            case '1':  sb.append(getBullet(1)); break;\n            case '2':  sb.append(getBullet(2)); break;\n            case '3':  sb.append(getBullet(3)); break;\n            case '4':  sb.append(getBullet(4)); break;\n            case '5': case '6': case '7': case '8': case '9': \n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine6(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxLL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeLow : boxLR);\n        }\n        System.out.println(sb.toString());\n    }\n\n}\n"}
{"id": 53972, "name": "Ramsey's theorem", "Python": "range17 = range(17)\na = [['0'] * 17 for i in range17]\nidx = [0] * 4\n\n\ndef find_group(mark, min_n, max_n, depth=1):\n    if (depth == 4):\n        prefix = \"\" if (mark == '1') else \"un\"\n        print(\"Fail, found totally {}connected group:\".format(prefix))\n        for i in range(4):\n            print(idx[i])\n        return True\n\n    for i in range(min_n, max_n):\n        n = 0\n        while (n < depth):\n            if (a[idx[n]][i] != mark):\n                break\n            n += 1\n\n        if (n == depth):\n            idx[n] = i\n            if (find_group(mark, 1, max_n, depth + 1)):\n                return True\n\n    return False\n\n\nif __name__ == '__main__':\n    for i in range17:\n        a[i][i] = '-'\n    for k in range(4):\n        for i in range17:\n            j = (i + pow(2, k)) % 17\n            a[i][j] = a[j][i] = '1'\n\n    \n    \n\n    for row in a:\n        print(' '.join(row))\n\n    for i in range17:\n        idx[0] = i\n        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):\n            print(\"no good\")\n            exit()\n\n    print(\"all good\")\n", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n"}
{"id": 53973, "name": "GUI_Maximum window dimensions", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n"}
{"id": 53974, "name": "Four is magic", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 53975, "name": "Getting the number of decimals", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n"}
{"id": 53976, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 53977, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 53978, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 53979, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 53980, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 53981, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 53982, "name": "Parse an IP Address", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n"}
{"id": 53983, "name": "Textonyms", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n"}
{"id": 53984, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 53985, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 53986, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 53987, "name": "Teacup rim text", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n"}
{"id": 53988, "name": "Increasing gaps between consecutive Niven numbers", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n"}
{"id": 53989, "name": "Print debugging statement", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n"}
{"id": 53990, "name": "Superellipse", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 53991, "name": "Permutations_Rank of a permutation", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n"}
{"id": 53992, "name": "Permutations_Rank of a permutation", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n"}
{"id": 53993, "name": "Range extraction", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 53994, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n"}
{"id": 53995, "name": "Zhang-Suen thinning algorithm", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n"}
{"id": 53996, "name": "Variable declaration reset", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n"}
{"id": 53997, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 53998, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 53999, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 54000, "name": "Numbers with equal rises and falls", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n"}
{"id": 54001, "name": "Koch curve", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n"}
{"id": 54002, "name": "Draw pixel 2", "Python": "import Tkinter,random\ndef draw_pixel_2 ( sizex=640,sizey=480 ):\n    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )\n    root = Tkinter.Tk()\n    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )\n    can.create_rectangle( pos*2,outline='yellow' )\n    can.pack()\n    root.title('press ESCAPE to quit')\n    root.bind('<Escape>',lambda e : root.quit())\n    root.mainloop()\n\ndraw_pixel_2()\n", "Java": "\n\nsize(640,480);\n\nstroke(#ffff00);\n\nellipse(random(640),random(480),1,1);\n"}
{"id": 54003, "name": "Draw a pixel", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n"}
{"id": 54004, "name": "Words from neighbour ones", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n"}
{"id": 54005, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 54006, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 54007, "name": "Magic squares of singly even order", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n"}
{"id": 54008, "name": "Generate Chess960 starting position", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n"}
{"id": 54009, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 54010, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 54011, "name": "Perlin noise", "Python": "import math\n\ndef perlin_noise(x, y, z):\n    X = math.floor(x) & 255                  \n    Y = math.floor(y) & 255                  \n    Z = math.floor(z) & 255\n    x -= math.floor(x)                                \n    y -= math.floor(y)                                \n    z -= math.floor(z)\n    u = fade(x)                                \n    v = fade(y)                                \n    w = fade(z)\n    A = p[X  ]+Y; AA = p[A]+Z; AB = p[A+1]+Z      \n    B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z      \n \n    return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                   grad(p[BA  ], x-1, y  , z   )), \n                           lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                   grad(p[BB  ], x-1, y-1, z   ))),\n                   lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                   grad(p[BA+1], x-1, y  , z-1 )), \n                           lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                   grad(p[BB+1], x-1, y-1, z-1 ))))\n                                   \ndef fade(t): \n    return t ** 3 * (t * (t * 6 - 15) + 10)\n    \ndef lerp(t, a, b):\n    return a + t * (b - a)\n    \ndef grad(hash, x, y, z):\n    h = hash & 15                      \n    u = x if h<8 else y                \n    v = y if h<4 else (x if h in (12, 14) else z)\n    return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n    p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n    print(\"%1.17f\" % perlin_noise(3.14, 42, 7))\n", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n"}
{"id": 54012, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 54013, "name": "UTF-8 encode and decode", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n"}
{"id": 54014, "name": "Xiaolin Wu's line algorithm", "Python": "\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n    return x - int(x)\n\ndef _rfpart(x):\n    return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n    \n    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n    c = compose_color(img.getpixel(xy), color)\n    img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n    \n    x1, y1 = p1\n    x2, y2 = p2\n    dx, dy = x2-x1, y2-y1\n    steep = abs(dx) < abs(dy)\n    p = lambda px, py: ((px,py), (py,px))[steep]\n\n    if steep:\n        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n    if x2 < x1:\n        x1, x2, y1, y2 = x2, x1, y2, y1\n\n    grad = dy/dx\n    intery = y1 + _rfpart(x1) * grad\n    def draw_endpoint(pt):\n        x, y = pt\n        xend = round(x)\n        yend = y + grad * (xend - x)\n        xgap = _rfpart(x + 0.5)\n        px, py = int(xend), int(yend)\n        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n        return px\n\n    xstart = draw_endpoint(p(*p1)) + 1\n    xend = draw_endpoint(p(*p2))\n\n    for x in range(xstart, xend):\n        y = int(intery)\n        putpixel(img, p(x, y), color, _rfpart(intery))\n        putpixel(img, p(x, y+1), color, _fpart(intery))\n        intery += grad\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print 'usage: python xiaolinwu.py [output-file]'\n        sys.exit(-1)\n\n    blue = (0, 0, 255)\n    yellow = (255, 255, 0)\n    img = Image.new(\"RGB\", (500,500), blue)\n    for a in range(10, 431, 60):\n        draw_line(img, (10, 10), (490, a), yellow)\n        draw_line(img, (10, 10), (a, 490), yellow)\n    draw_line(img, (10, 10), (490, 490), yellow)\n    filename = sys.argv[1]\n    img.save(filename)\n    print 'image saved to', filename\n", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 54015, "name": "Keyboard macros", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n"}
{"id": 54016, "name": "Keyboard macros", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n"}
{"id": 54017, "name": "McNuggets problem", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n", "Java": "public class McNuggets {\n\n    public static void main(String... args) {\n        int[] SIZES = new int[] { 6, 9, 20 };\n        int MAX_TOTAL = 100;\n        \n        int numSizes = SIZES.length;\n        int[] counts = new int[numSizes];\n        int maxFound = MAX_TOTAL + 1;\n        boolean[] found = new boolean[maxFound];\n        int numFound = 0;\n        int total = 0;\n        boolean advancedState = false;\n        do {\n            if (!found[total]) {\n                found[total] = true;\n                numFound++;\n            }\n            \n            \n            advancedState = false;\n            for (int i = 0; i < numSizes; i++) {\n                int curSize = SIZES[i];\n                if ((total + curSize) > MAX_TOTAL) {\n                    \n                    total -= counts[i] * curSize;\n                    counts[i] = 0;\n                }\n                else {\n                    \n                    counts[i]++;\n                    total += curSize;\n                    advancedState = true;\n                    break;\n                }\n            }\n            \n        } while ((numFound < maxFound) && advancedState);\n        \n        if (numFound < maxFound) {\n            \n            for (int i = MAX_TOTAL; i >= 0; i--) {\n                if (!found[i]) {\n                    System.out.println(\"Largest non-McNugget number in the search space is \" + i);\n                    break;\n                }\n            }\n        }\n        else {\n            System.out.println(\"All numbers in the search space are McNugget numbers\");\n        }\n        \n        return;\n    }\n}\n"}
{"id": 54018, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 54019, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 54020, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 54021, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 54022, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 54023, "name": "Pseudo-random numbers_Xorshift star", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 54024, "name": "Four is the number of letters in the ...", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class FourIsTheNumberOfLetters {\n\n    public static void main(String[] args) {\n        String [] words = neverEndingSentence(201);\n        System.out.printf(\"Display the first 201 numbers in the sequence:%n%3d: \", 1);\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            System.out.printf(\"%2d \", numberOfLetters(words[i]));\n            if ( (i+1) % 25 == 0 ) {\n                System.out.printf(\"%n%3d: \", i+2);\n            }\n        }\n        System.out.printf(\"%nTotal number of characters in the sentence is %d%n\", characterCount(words));\n        for ( int i = 3 ; i <= 7 ; i++ ) {\n            int index = (int) Math.pow(10, i);\n            words = neverEndingSentence(index);\n            String last = words[words.length-1].replace(\",\", \"\");\n            System.out.printf(\"Number of letters of the %s word is %d. The word is \\\"%s\\\".  The sentence length is %,d characters.%n\", toOrdinal(index), numberOfLetters(last), last, characterCount(words));\n        }\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static void displaySentence(String[] words, int lineLength) {\n        int currentLength = 0;\n        for ( String word : words ) {\n            if ( word.length() + currentLength > lineLength ) {\n                String first = word.substring(0, lineLength-currentLength);\n                String second = word.substring(lineLength-currentLength);\n                System.out.println(first);\n                System.out.print(second);\n                currentLength = second.length();\n            }\n            else {\n                System.out.print(word);\n                currentLength += word.length();\n            }\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n            System.out.print(\" \");\n            currentLength++;\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n        }\n        System.out.println();\n    }\n    \n    private static int numberOfLetters(String word) {\n        return word.replace(\",\",\"\").replace(\"-\",\"\").length();\n    }\n    \n    private static long characterCount(String[] words) {\n        int characterCount = 0;\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            characterCount += words[i].length() + 1;\n        }        \n        \n        characterCount--;\n        return characterCount;\n    }\n    \n    private static String[] startSentence = new String[] {\"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\", \"first\", \"word\", \"of\", \"this\", \"sentence,\"};\n    \n    private static String[] neverEndingSentence(int wordCount) {\n        String[] words = new String[wordCount];\n        int index;\n        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {\n            words[index] = startSentence[index];\n        }\n        int sentencePosition = 1;\n        while ( index < wordCount ) {\n            \n            \n            sentencePosition++;\n            String word = words[sentencePosition-1];\n            for ( String wordLoop : numToString(numberOfLetters(word)).split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n            \n            words[index] = \"in\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            words[index] = \"the\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            for ( String wordLoop : (toOrdinal(sentencePosition) + \",\").split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n        }\n        return words;\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n    \n}\n"}
{"id": 54025, "name": "ASCII art diagram converter", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n"}
{"id": 54026, "name": "Levenshtein distance_Alignment", "Python": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n    result = \"\"\n    pos, removed = 0, 0\n    for x in ndiff(str1, str2):\n        if pos<len(str1) and str1[pos] == x[2]:\n          pos += 1\n          result += x[2]\n          if x[0] == \"-\":\n              removed += 1\n          continue\n        else:\n          if removed > 0:\n            removed -=1\n          else:\n            result += \"-\"\n    print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")\n", "Java": "public class LevenshteinAlignment {\n\n    public static String[] alignment(String a, String b) {\n        a = a.toLowerCase();\n        b = b.toLowerCase();\n        \n        int[][] costs = new int[a.length()+1][b.length()+1];\n        for (int j = 0; j <= b.length(); j++)\n            costs[0][j] = j;\n        for (int i = 1; i <= a.length(); i++) {\n            costs[i][0] = i;\n            for (int j = 1; j <= b.length(); j++) {\n                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);\n            }\n        }\n\n\t\n\tStringBuilder aPathRev = new StringBuilder();\n\tStringBuilder bPathRev = new StringBuilder();\n\tfor (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {\n\t    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append(b.charAt(--j));\n\t    } else if (costs[i][j] == 1 + costs[i-1][j]) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append('-');\n\t    } else if (costs[i][j] == 1 + costs[i][j-1]) {\n\t\taPathRev.append('-');\n\t\tbPathRev.append(b.charAt(--j));\n\t    }\n\t}\n        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};\n    }\n\n    public static void main(String[] args) {\n\tString[] result = alignment(\"rosettacode\", \"raisethysword\");\n\tSystem.out.println(result[0]);\n\tSystem.out.println(result[1]);\n    }\n}\n"}
{"id": 54027, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n"}
{"id": 54028, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n"}
{"id": 54029, "name": "Simulate input_Keyboard", "Python": "import autopy\nautopy.key.type_string(\"Hello, world!\") \nautopy.key.type_string(\"Hello, world!\", wpm=60) \nautopy.key.tap(autopy.key.Code.RETURN)\nautopy.key.tap(autopy.key.Code.F1)\nautopy.key.tap(autopy.key.Code.LEFT_ARROW)\n", "Java": "import java.awt.Robot\npublic static void type(String str){\n   Robot robot = new Robot();\n   for(char ch:str.toCharArray()){\n      if(Character.isUpperCase(ch)){\n         robot.keyPress(KeyEvent.VK_SHIFT);\n         robot.keyPress((int)ch);\n         robot.keyRelease((int)ch);\n         robot.keyRelease(KeyEvent.VK_SHIFT);\n      }else{\n         char upCh = Character.toUpperCase(ch);\n         robot.keyPress((int)upCh);\n         robot.keyRelease((int)upCh);\n      }\n   }\n}\n"}
{"id": 54030, "name": "Peaceful chess queen armies", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 54031, "name": "Peaceful chess queen armies", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 54032, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 54033, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 54034, "name": "Active Directory_Search for a user", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n"}
{"id": 54035, "name": "Singular value decomposition", "Python": "from numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n", "Java": "import Jama.Matrix;\npublic class SingularValueDecomposition {\n    public static void main(String[] args) {\n        double[][] matrixArray = {{3, 0}, {4, 5}};\n        var matrix = new Matrix(matrixArray);\n        var svd = matrix.svd();\n        svd.getU().print(0, 10); \n        svd.getS().print(0, 10);\n        svd.getV().print(0, 10);\n    }\n}\n"}
{"id": 54036, "name": "Test integerness", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n"}
{"id": 54037, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 54038, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 54039, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 54040, "name": "Death Star", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n"}
{"id": 54041, "name": "Lucky and even lucky numbers", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n"}
{"id": 54042, "name": "Scope modifiers", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n"}
{"id": 54043, "name": "Scope modifiers", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n"}
{"id": 54044, "name": "Simple database", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n"}
{"id": 54045, "name": "Simple database", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n"}
{"id": 54046, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n"}
{"id": 54047, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n"}
{"id": 54048, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n"}
{"id": 54049, "name": "Hough transform", "Python": "from math import hypot, pi, cos, sin\nfrom PIL import Image\n\n\ndef hough(im, ntx=460, mry=360):\n    \"Calculate Hough transform.\"\n    pim = im.load()\n    nimx, mimy = im.size\n    mry = int(mry/2)*2          \n    him = Image.new(\"L\", (ntx, mry), 255)\n    phim = him.load()\n\n    rmax = hypot(nimx, mimy)\n    dr = rmax / (mry/2)\n    dth = pi / ntx\n\n    for jx in xrange(nimx):\n        for iy in xrange(mimy):\n            col = pim[jx, iy]\n            if col == 255: continue\n            for jtx in xrange(ntx):\n                th = dth * jtx\n                r = jx*cos(th) + iy*sin(th)\n                iry = mry/2 + int(r/dr+0.5)\n                phim[jtx, iry] -= 1\n    return him\n\n\ndef test():\n    \"Test Hough transform with pentagon.\"\n    im = Image.open(\"pentagon.png\").convert(\"L\")\n    him = hough(im)\n    him.save(\"ho5.bmp\")\n\n\nif __name__ == \"__main__\": test()\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\n  }\n}\n"}
{"id": 54050, "name": "Verify distribution uniformity_Chi-squared test", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n"}
{"id": 54051, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 54052, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 54053, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 54054, "name": "Topological sort_Extracted top item", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n"}
{"id": 54055, "name": "Topological sort_Extracted top item", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n"}
{"id": 54056, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 54057, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 54058, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 54059, "name": "Superpermutation minimisation", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54060, "name": "GUI component interaction", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n"}
{"id": 54061, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n"}
{"id": 54062, "name": "Summarize and say sequence", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n"}
{"id": 54063, "name": "Spelling of ordinal numbers", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 54064, "name": "Spelling of ordinal numbers", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 54065, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 54066, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 54067, "name": "Addition chains", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 54068, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n"}
{"id": 54069, "name": "Sparkline in unicode", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n"}
{"id": 54070, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 54071, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 54072, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 54073, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 54074, "name": "Simulate input_Mouse", "Python": "import ctypes\n\ndef click():\n    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    \n    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    \n\nclick()\n", "Java": "Point p = component.getLocation();\nRobot robot = new Robot();\nrobot.mouseMove(p.getX(), p.getY()); \nrobot.mousePress(InputEvent.BUTTON1_MASK); \n                                       \nrobot.mouseRelease(InputEvent.BUTTON1_MASK);\n"}
{"id": 54075, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 54076, "name": "Terminal control_Clear the screen", "Python": "import os\nos.system(\"clear\")\n", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n"}
{"id": 54077, "name": "Sunflower fractal", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n"}
{"id": 54078, "name": "Vogel's approximation method", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n"}
{"id": 54079, "name": "Air mass", "Python": "\n\nfrom math import sqrt, cos, exp\n\nDEG = 0.017453292519943295769236907684886127134  \nRE = 6371000                                     \ndd = 0.001      \nFIN = 10000000  \n \ndef rho(a):\n    \n    return exp(-a / 8500.0)\n \ndef height(a, z, d):\n     \n    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE\n \ndef column_density(a, z):\n    \n    dsum, d = 0.0, 0.0\n    while d < FIN:\n        delta = max(dd, (dd)*d)  \n        dsum += rho(height(a, z, d + 0.5 * delta)) * delta\n        d += delta\n    return dsum\n\ndef airmass(a, z):\n    return column_density(a, z) / column_density(a, 0)\n\nprint('Angle           0 m          13700 m\\n', '-' * 36)\nfor z in range(0, 91, 5):\n    print(f\"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}\")\n", "Java": "public class AirMass {\n    public static void main(String[] args) {\n        System.out.println(\"Angle     0 m              13700 m\");\n        System.out.println(\"------------------------------------\");\n        for (double z = 0; z <= 90; z+= 5) {\n            System.out.printf(\"%2.0f      %11.8f      %11.8f\\n\",\n                            z, airmass(0.0, z), airmass(13700.0, z));\n        }\n    }\n\n    private static double rho(double a) {\n        \n        return Math.exp(-a / 8500.0);\n    }\n\n    private static double height(double a, double z, double d) {\n        \n        \n        \n        double aa = RE + a;\n        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));\n        return hh - RE;\n    }\n\n    private static double columnDensity(double a, double z) {\n        \n        double sum = 0.0, d = 0.0;\n        while (d < FIN) {\n            \n            double delta = Math.max(DD * d, DD);\n            sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n            d += delta;\n        }\n        return sum;\n    }\n     \n    private static double airmass(double a, double z) {\n        return columnDensity(a, z) / columnDensity(a, 0.0);\n    }\n\n    private static final double RE = 6371000.0; \n    private static final double DD = 0.001; \n    private static final double FIN = 10000000.0; \n}\n"}
{"id": 54080, "name": "Sorting algorithms_Pancake sort", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n"}
{"id": 54081, "name": "Sorting algorithms_Pancake sort", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n"}
{"id": 54082, "name": "Chemical calculator", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n", "Java": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\npublic class ChemicalCalculator {\n    private static final Map<String, Double> atomicMass = new HashMap<>();\n\n    static {\n        atomicMass.put(\"H\", 1.008);\n        atomicMass.put(\"He\", 4.002602);\n        atomicMass.put(\"Li\", 6.94);\n        atomicMass.put(\"Be\", 9.0121831);\n        atomicMass.put(\"B\", 10.81);\n        atomicMass.put(\"C\", 12.011);\n        atomicMass.put(\"N\", 14.007);\n        atomicMass.put(\"O\", 15.999);\n        atomicMass.put(\"F\", 18.998403163);\n        atomicMass.put(\"Ne\", 20.1797);\n        atomicMass.put(\"Na\", 22.98976928);\n        atomicMass.put(\"Mg\", 24.305);\n        atomicMass.put(\"Al\", 26.9815385);\n        atomicMass.put(\"Si\", 28.085);\n        atomicMass.put(\"P\", 30.973761998);\n        atomicMass.put(\"S\", 32.06);\n        atomicMass.put(\"Cl\", 35.45);\n        atomicMass.put(\"Ar\", 39.948);\n        atomicMass.put(\"K\", 39.0983);\n        atomicMass.put(\"Ca\", 40.078);\n        atomicMass.put(\"Sc\", 44.955908);\n        atomicMass.put(\"Ti\", 47.867);\n        atomicMass.put(\"V\", 50.9415);\n        atomicMass.put(\"Cr\", 51.9961);\n        atomicMass.put(\"Mn\", 54.938044);\n        atomicMass.put(\"Fe\", 55.845);\n        atomicMass.put(\"Co\", 58.933194);\n        atomicMass.put(\"Ni\", 58.6934);\n        atomicMass.put(\"Cu\", 63.546);\n        atomicMass.put(\"Zn\", 65.38);\n        atomicMass.put(\"Ga\", 69.723);\n        atomicMass.put(\"Ge\", 72.630);\n        atomicMass.put(\"As\", 74.921595);\n        atomicMass.put(\"Se\", 78.971);\n        atomicMass.put(\"Br\", 79.904);\n        atomicMass.put(\"Kr\", 83.798);\n        atomicMass.put(\"Rb\", 85.4678);\n        atomicMass.put(\"Sr\", 87.62);\n        atomicMass.put(\"Y\", 88.90584);\n        atomicMass.put(\"Zr\", 91.224);\n        atomicMass.put(\"Nb\", 92.90637);\n        atomicMass.put(\"Mo\", 95.95);\n        atomicMass.put(\"Ru\", 101.07);\n        atomicMass.put(\"Rh\", 102.90550);\n        atomicMass.put(\"Pd\", 106.42);\n        atomicMass.put(\"Ag\", 107.8682);\n        atomicMass.put(\"Cd\", 112.414);\n        atomicMass.put(\"In\", 114.818);\n        atomicMass.put(\"Sn\", 118.710);\n        atomicMass.put(\"Sb\", 121.760);\n        atomicMass.put(\"Te\", 127.60);\n        atomicMass.put(\"I\", 126.90447);\n        atomicMass.put(\"Xe\", 131.293);\n        atomicMass.put(\"Cs\", 132.90545196);\n        atomicMass.put(\"Ba\", 137.327);\n        atomicMass.put(\"La\", 138.90547);\n        atomicMass.put(\"Ce\", 140.116);\n        atomicMass.put(\"Pr\", 140.90766);\n        atomicMass.put(\"Nd\", 144.242);\n        atomicMass.put(\"Pm\", 145.0);\n        atomicMass.put(\"Sm\", 150.36);\n        atomicMass.put(\"Eu\", 151.964);\n        atomicMass.put(\"Gd\", 157.25);\n        atomicMass.put(\"Tb\", 158.92535);\n        atomicMass.put(\"Dy\", 162.500);\n        atomicMass.put(\"Ho\", 164.93033);\n        atomicMass.put(\"Er\", 167.259);\n        atomicMass.put(\"Tm\", 168.93422);\n        atomicMass.put(\"Yb\", 173.054);\n        atomicMass.put(\"Lu\", 174.9668);\n        atomicMass.put(\"Hf\", 178.49);\n        atomicMass.put(\"Ta\", 180.94788);\n        atomicMass.put(\"W\", 183.84);\n        atomicMass.put(\"Re\", 186.207);\n        atomicMass.put(\"Os\", 190.23);\n        atomicMass.put(\"Ir\", 192.217);\n        atomicMass.put(\"Pt\", 195.084);\n        atomicMass.put(\"Au\", 196.966569);\n        atomicMass.put(\"Hg\", 200.592);\n        atomicMass.put(\"Tl\", 204.38);\n        atomicMass.put(\"Pb\", 207.2);\n        atomicMass.put(\"Bi\", 208.98040);\n        atomicMass.put(\"Po\", 209.0);\n        atomicMass.put(\"At\", 210.0);\n        atomicMass.put(\"Rn\", 222.0);\n        atomicMass.put(\"Fr\", 223.0);\n        atomicMass.put(\"Ra\", 226.0);\n        atomicMass.put(\"Ac\", 227.0);\n        atomicMass.put(\"Th\", 232.0377);\n        atomicMass.put(\"Pa\", 231.03588);\n        atomicMass.put(\"U\", 238.02891);\n        atomicMass.put(\"Np\", 237.0);\n        atomicMass.put(\"Pu\", 244.0);\n        atomicMass.put(\"Am\", 243.0);\n        atomicMass.put(\"Cm\", 247.0);\n        atomicMass.put(\"Bk\", 247.0);\n        atomicMass.put(\"Cf\", 251.0);\n        atomicMass.put(\"Es\", 252.0);\n        atomicMass.put(\"Fm\", 257.0);\n        atomicMass.put(\"Uue\", 315.0);\n        atomicMass.put(\"Ubn\", 299.0);\n    }\n\n    private static double evaluate(String s) {\n        String sym = s + \"[\";\n        double sum = 0.0;\n        StringBuilder symbol = new StringBuilder();\n        String number = \"\";\n        for (int i = 0; i < sym.length(); ++i) {\n            char c = sym.charAt(i);\n            if ('@' <= c && c <= '[') {\n                \n                int n = 1;\n                if (!number.isEmpty()) {\n                    n = Integer.parseInt(number);\n                }\n                if (symbol.length() > 0) {\n                    sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;\n                }\n                if (c == '[') {\n                    break;\n                }\n                symbol = new StringBuilder(String.valueOf(c));\n                number = \"\";\n            } else if ('a' <= c && c <= 'z') {\n                symbol.append(c);\n            } else if ('0' <= c && c <= '9') {\n                number += c;\n            } else {\n                throw new RuntimeException(\"Unexpected symbol \" + c + \" in molecule\");\n            }\n        }\n        return sum;\n    }\n\n    private static String replaceParens(String s) {\n        char letter = 'a';\n        String si = s;\n        while (true) {\n            int start = si.indexOf('(');\n            if (start == -1) {\n                break;\n            }\n\n            for (int i = start + 1; i < si.length(); ++i) {\n                if (si.charAt(i) == ')') {\n                    String expr = si.substring(start + 1, i);\n                    String symbol = \"@\" + letter;\n                    String pattern = Pattern.quote(si.substring(start, i + 1));\n                    si = si.replaceFirst(pattern, symbol);\n                    atomicMass.put(symbol, evaluate(expr));\n                    letter++;\n                    break;\n                }\n                if (si.charAt(i) == '(') {\n                    start = i;\n                }\n            }\n        }\n        return si;\n    }\n\n    public static void main(String[] args) {\n        List<String> molecules = List.of(\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        );\n        for (String molecule : molecules) {\n            double mass = evaluate(replaceParens(molecule));\n            System.out.printf(\"%17s -> %7.3f\\n\", molecule, mass);\n        }\n    }\n}\n"}
{"id": 54083, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n"}
{"id": 54084, "name": "Permutations by swapping", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 54085, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 54086, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 54087, "name": "Image convolution", "Python": "\nfrom PIL import Image, ImageFilter\n\nif __name__==\"__main__\":\n\tim = Image.open(\"test.jpg\")\n\n\tkernelValues = [-2,-1,0,-1,1,1,0,1,2] \n\tkernel = ImageFilter.Kernel((3,3), kernelValues)\n\n\tim2 = im.filter(kernel)\n\n\tim2.show()\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class ImageConvolution\n{\n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n  }\n  \n  private static int bound(int value, int endIndex)\n  {\n    if (value < 0)\n      return 0;\n    if (value < endIndex)\n      return value;\n    return endIndex - 1;\n  }\n  \n  public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)\n  {\n    int inputWidth = inputData.width;\n    int inputHeight = inputData.height;\n    int kernelWidth = kernel.width;\n    int kernelHeight = kernel.height;\n    if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd width\");\n    if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd height\");\n    int kernelWidthRadius = kernelWidth >>> 1;\n    int kernelHeightRadius = kernelHeight >>> 1;\n    \n    ArrayData outputData = new ArrayData(inputWidth, inputHeight);\n    for (int i = inputWidth - 1; i >= 0; i--)\n    {\n      for (int j = inputHeight - 1; j >= 0; j--)\n      {\n        double newValue = 0.0;\n        for (int kw = kernelWidth - 1; kw >= 0; kw--)\n          for (int kh = kernelHeight - 1; kh >= 0; kh--)\n            newValue += kernel.get(kw, kh) * inputData.get(\n                          bound(i + kw - kernelWidthRadius, inputWidth),\n                          bound(j + kh - kernelHeightRadius, inputHeight));\n        outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));\n      }\n    }\n    return outputData;\n  }\n  \n  public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData reds = new ArrayData(width, height);\n    ArrayData greens = new ArrayData(width, height);\n    ArrayData blues = new ArrayData(width, height);\n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        reds.set(x, y, (rgbValue >>> 16) & 0xFF);\n        greens.set(x, y, (rgbValue >>> 8) & 0xFF);\n        blues.set(x, y, rgbValue & 0xFF);\n      }\n    }\n    return new ArrayData[] { reds, greens, blues };\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException\n  {\n    ArrayData reds = redGreenBlue[0];\n    ArrayData greens = redGreenBlue[1];\n    ArrayData blues = redGreenBlue[2];\n    BufferedImage outputImage = new BufferedImage(reds.width, reds.height,\n                                                  BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < reds.height; y++)\n    {\n      for (int x = 0; x < reds.width; x++)\n      {\n        int red = bound(reds.get(x, y), 256);\n        int green = bound(greens.get(x, y), 256);\n        int blue = bound(blues.get(x, y), 256);\n        outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    int kernelWidth = Integer.parseInt(args[2]);\n    int kernelHeight = Integer.parseInt(args[3]);\n    int kernelDivisor = Integer.parseInt(args[4]);\n    System.out.println(\"Kernel size: \" + kernelWidth + \"x\" + kernelHeight +\n                       \", divisor=\" + kernelDivisor);\n    int y = 5;\n    ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);\n    for (int i = 0; i < kernelHeight; i++)\n    {\n      System.out.print(\"[\");\n      for (int j = 0; j < kernelWidth; j++)\n      {\n        kernel.set(j, i, Integer.parseInt(args[y++]));\n        System.out.print(\" \" + kernel.get(j, i) + \" \");\n      }\n      System.out.println(\"]\");\n    }\n    \n    ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);\n    for (int i = 0; i < dataArrays.length; i++)\n      dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);\n    writeOutputImage(args[1], dataArrays);\n    return;\n  }\n}\n"}
{"id": 54088, "name": "Dice game probabilities", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n"}
{"id": 54089, "name": "Sokoban", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n"}
{"id": 54090, "name": "Practical numbers", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n"}
{"id": 54091, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 54092, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 54093, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54094, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54095, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 54096, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 54097, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54098, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54099, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 54100, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 54101, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 54102, "name": "Word search", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n"}
{"id": 54103, "name": "Word search", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n"}
{"id": 54104, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 54105, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 54106, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 54107, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 54108, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 54109, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 54110, "name": "Zumkeller numbers", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n"}
{"id": 54111, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 54112, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 54113, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 54114, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 54115, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n"}
{"id": 54116, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 54117, "name": "Geometric algebra", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n"}
{"id": 54118, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 54119, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 54120, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 54121, "name": "Define a primitive data type", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 54122, "name": "Penrose tiling", "Python": "def penrose(depth):\n    print(\t<g id=\"A{d+1}\" transform=\"translate(100, 0) scale(0.6180339887498949)\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n\t<g id=\"B{d+1}\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\t<g id=\"G\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n  </defs>\n  <g transform=\"scale(2, 2)\">\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n  </g>\n</svg>''')\n\npenrose(6)\n", "Java": "import java.awt.*;\nimport java.util.List;\nimport java.awt.geom.Path2D;\nimport java.util.*;\nimport javax.swing.*;\nimport static java.lang.Math.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class PenroseTiling extends JPanel {\n    \n    class Tile {\n        double x, y, angle, size;\n        Type type;\n\n        Tile(Type t, double x, double y, double a, double s) {\n            type = t;\n            this.x = x;\n            this.y = y;\n            angle = a;\n            size = s;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Tile) {\n                Tile t = (Tile) o;\n                return type == t.type && x == t.x && y == t.y && angle == t.angle;\n            }\n            return false;\n        }\n    }\n\n    enum Type {\n        Kite, Dart\n    }\n\n    static final double G = (1 + sqrt(5)) / 2; \n    static final double T = toRadians(36); \n\n    List<Tile> tiles = new ArrayList<>();\n\n    public PenroseTiling() {\n        int w = 700, h = 450;\n        setPreferredSize(new Dimension(w, h));\n        setBackground(Color.white);\n\n        tiles = deflateTiles(setupPrototiles(w, h), 5);\n    }\n\n    List<Tile> setupPrototiles(int w, int h) {\n        List<Tile> proto = new ArrayList<>();\n\n        \n        for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)\n            proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));\n\n        return proto;\n    }\n\n    List<Tile> deflateTiles(List<Tile> tls, int generation) {\n        if (generation <= 0)\n            return tls;\n\n        List<Tile> next = new ArrayList<>();\n\n        for (Tile tile : tls) {\n            double x = tile.x, y = tile.y, a = tile.angle, nx, ny;\n            double size = tile.size / G;\n\n            if (tile.type == Type.Dart) {\n                next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    nx = x + cos(a - 4 * T * sign) * G * tile.size;\n                    ny = y - sin(a - 4 * T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));\n                }\n\n            } else {\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));\n\n                    nx = x + cos(a - T * sign) * G * tile.size;\n                    ny = y - sin(a - T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));\n                }\n            }\n        }\n        \n        tls = next.stream().distinct().collect(toList());\n\n        return deflateTiles(tls, generation - 1);\n    }\n\n    void drawTiles(Graphics2D g) {\n        double[][] dist = {{G, G, G}, {-G, -1, -G}};\n        for (Tile tile : tiles) {\n            double angle = tile.angle - T;\n            Path2D path = new Path2D.Double();\n            path.moveTo(tile.x, tile.y);\n\n            int ord = tile.type.ordinal();\n            for (int i = 0; i < 3; i++) {\n                double x = tile.x + dist[ord][i] * tile.size * cos(angle);\n                double y = tile.y - dist[ord][i] * tile.size * sin(angle);\n                path.lineTo(x, y);\n                angle += T;\n            }\n            path.closePath();\n            g.setColor(ord == 0 ? Color.orange : Color.yellow);\n            g.fill(path);\n            g.setColor(Color.darkGray);\n            g.draw(path);\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics og) {\n        super.paintComponent(og);\n        Graphics2D g = (Graphics2D) og;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        drawTiles(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(\"Penrose Tiling\");\n            f.setResizable(false);\n            f.add(new PenroseTiling(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 54123, "name": "Sphenic numbers", "Python": "\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n    d = factorint(i)\n    if len(d) == 3 and sum(d.values()) == 3:\n        sphenics1m.append(i)\n        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n            sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n    if n < 1000:\n        print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n    else:\n        break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n    if n < 10_000:\n        print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else '  ')\n    else:\n        break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n      'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n", "Java": "import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SphenicNumbers {\n    public static void main(String[] args) {\n        final int limit = 1000000;\n        final int imax = limit / 6;\n        boolean[] sieve = primeSieve(imax + 1);\n        boolean[] sphenic = new boolean[limit + 1];\n        for (int i = 0; i <= imax; ++i) {\n            if (!sieve[i])\n                continue;\n            int jmax = Math.min(imax, limit / (i * i));\n            if (jmax <= i)\n                break;\n            for (int j = i + 1; j <= jmax; ++j) {\n                if (!sieve[j])\n                    continue;\n                int p = i * j;\n                int kmax = Math.min(imax, limit / p);\n                if (kmax <= j)\n                    break;\n                for (int k = j + 1; k <= kmax; ++k) {\n                    if (!sieve[k])\n                        continue;\n                    assert(p * k <= limit);\n                    sphenic[p * k] = true;\n                }\n            }\n        }\n    \n        System.out.println(\"Sphenic numbers < 1000:\");\n        for (int i = 0, n = 0; i < 1000; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++n;\n            System.out.printf(\"%3d%c\", i, n % 15 == 0 ? '\\n' : ' ');\n        }\n    \n        System.out.println(\"\\nSphenic triplets < 10,000:\");\n        for (int i = 0, n = 0; i < 10000; ++i) {\n            if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n                ++n;\n                System.out.printf(\"(%d, %d, %d)%c\",\n                                  i - 2, i - 1, i, n % 3 == 0 ? '\\n' : ' ');\n            }\n        }\n    \n        int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n        for (int i = 0; i < limit; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++count;\n            if (count == 200000)\n                s200000 = i;\n            if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n                ++triplets;\n                if (triplets == 5000)\n                    t5000 = i;\n            }\n        }\n    \n        System.out.printf(\"\\nNumber of sphenic numbers < 1,000,000: %d\\n\", count);\n        System.out.printf(\"Number of sphenic triplets < 1,000,000: %d\\n\", triplets);\n    \n        List<Integer> factors = primeFactors(s200000);\n        assert(factors.size() == 3);\n        System.out.printf(\"The 200,000th sphenic number: %d = %d * %d * %d\\n\",\n                          s200000, factors.get(0), factors.get(1),\n                          factors.get(2));\n        System.out.printf(\"The 5,000th sphenic triplet: (%d, %d, %d)\\n\",\n                          t5000 - 2, t5000 - 1, t5000);\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3, sq = 9; sq < limit; p += 2) {\n            if (sieve[p]) {\n                for (int q = sq; q < limit; q += p << 1)\n                    sieve[q] = false;\n            }\n            sq += (p + 1) << 2;\n        }\n        return sieve;\n    }\n    \n    private static List<Integer> primeFactors(int n) {\n        List<Integer> factors = new ArrayList<>();\n        if (n > 1 && (n & 1) == 0) {\n            factors.add(2);\n            while ((n & 1) == 0)\n                n >>= 1;\n        }\n        for (int p = 3; p * p <= n; p += 2) {\n            if (n % p == 0) {\n                factors.add(p);\n                while (n % p == 0)\n                    n /= p;\n            }\n        }\n        if (n > 1)\n            factors.add(n);\n        return factors;\n    }\n}\n"}
{"id": 54124, "name": "Find duplicate files", "Python": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n    knownFiles = {}\n\n    \n    for root, dirs, files in os.walk(pth):\n        for fina in files:\n            fullFina = os.path.join(root, fina)\n            isSymLink = os.path.islink(fullFina)\n            if isSymLink:\n                continue \n            si = os.path.getsize(fullFina)\n            if si < minSize:\n                continue\n            if si not in knownFiles:\n                knownFiles[si] = {}\n            h = hashlib.new(hashName)\n            h.update(open(fullFina, \"rb\").read())\n            hashed = h.digest()\n            if hashed in knownFiles[si]:\n                fileRec = knownFiles[si][hashed]\n                fileRec.append(fullFina)\n            else:\n                knownFiles[si][hashed] = [fullFina]\n\n    \n    sizeList = list(knownFiles.keys())\n    sizeList.sort(reverse=True)\n    for si in sizeList:\n        filesAtThisSize = knownFiles[si]\n        for hashVal in filesAtThisSize:\n            if len(filesAtThisSize[hashVal]) < 2:\n                continue\n            fullFinaLi = filesAtThisSize[hashVal]\n            print (\"=======Duplicate=======\")\n            for fullFina in fullFinaLi:\n                st = os.stat(fullFina)\n                isHardLink = st.st_nlink > 1 \n                infoStr = []\n                if isHardLink:\n                    infoStr.append(\"(Hard linked)\")\n                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n                print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n", "Java": "import java.io.*;\nimport java.nio.*;\nimport java.nio.file.*;\nimport java.nio.file.attribute.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class DuplicateFiles {\n    public static void main(String[] args) {\n        if (args.length != 2) {\n            System.err.println(\"Directory name and minimum file size are required.\");\n            System.exit(1);\n        }\n        try {\n            findDuplicateFiles(args[0], Long.parseLong(args[1]));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void findDuplicateFiles(String directory, long minimumSize)\n        throws IOException, NoSuchAlgorithmException {\n        System.out.println(\"Directory: '\" + directory + \"', minimum size: \" + minimumSize + \" bytes.\");\n        Path path = FileSystems.getDefault().getPath(directory);\n        FileVisitor visitor = new FileVisitor(path, minimumSize);\n        Files.walkFileTree(path, visitor);\n        System.out.println(\"The following sets of files have the same size and checksum:\");\n        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {\n            Map<Object, List<String>> map = e.getValue();\n            if (!containsDuplicates(map))\n                continue;\n            List<List<String>> fileSets = new ArrayList<>(map.values());\n            for (List<String> files : fileSets)\n                Collections.sort(files);\n            Collections.sort(fileSets, new StringListComparator());\n            FileKey key = e.getKey();\n            System.out.println();\n            System.out.println(\"Size: \" + key.size_ + \" bytes\");\n            for (List<String> files : fileSets) {\n                for (int i = 0, n = files.size(); i < n; ++i) {\n                    if (i > 0)\n                        System.out.print(\" = \");\n                    System.out.print(files.get(i));\n                }\n                System.out.println();\n            }\n        }\n    }\n\n    private static class StringListComparator implements Comparator<List<String>> {\n        public int compare(List<String> a, List<String> b) {\n            int len1 = a.size(), len2 = b.size();\n            for (int i = 0; i < len1 && i < len2; ++i) {\n                int c = a.get(i).compareTo(b.get(i));\n                if (c != 0)\n                    return c;\n            }\n            return Integer.compare(len1, len2);\n        }\n    }\n\n    private static boolean containsDuplicates(Map<Object, List<String>> map) {\n        if (map.size() > 1)\n            return true;\n        for (List<String> files : map.values()) {\n            if (files.size() > 1)\n                return true;\n        }\n        return false;\n    }\n\n    private static class FileVisitor extends SimpleFileVisitor<Path> {\n        private MessageDigest digest_;\n        private Path directory_;\n        private long minimumSize_;\n        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();\n\n        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {\n            directory_ = directory;\n            minimumSize_ = minimumSize;\n            digest_ = MessageDigest.getInstance(\"MD5\");\n        }\n\n        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n            if (attrs.size() >= minimumSize_) {\n                FileKey key = new FileKey(file, attrs, getMD5Sum(file));\n                Map<Object, List<String>> map = fileMap_.get(key);\n                if (map == null)\n                    fileMap_.put(key, map = new HashMap<>());\n                List<String> files = map.get(attrs.fileKey());\n                if (files == null)\n                    map.put(attrs.fileKey(), files = new ArrayList<>());\n                Path relative = directory_.relativize(file);\n                files.add(relative.toString());\n            }\n            return FileVisitResult.CONTINUE;\n        }\n\n        private byte[] getMD5Sum(Path file) throws IOException {\n            digest_.reset();\n            try (InputStream in = new FileInputStream(file.toString())) {\n                byte[] buffer = new byte[8192];\n                int bytes;\n                while ((bytes = in.read(buffer)) != -1) {\n                    digest_.update(buffer, 0, bytes);\n                }\n            }\n            return digest_.digest();\n        }\n    }\n\n    private static class FileKey implements Comparable<FileKey> {\n        private byte[] hash_;\n        private long size_;\n\n        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {\n            size_ = attrs.size();\n            hash_ = hash;\n        }\n\n        public int compareTo(FileKey other) {\n            int c = Long.compare(other.size_, size_);\n            if (c == 0)\n                c = hashCompare(hash_, other.hash_);\n            return c;\n        }\n    }\n\n    private static int hashCompare(byte[] a, byte[] b) {\n        int len1 = a.length, len2 = b.length;\n        for (int i = 0; i < len1 && i < len2; ++i) {\n            int c = Byte.compare(a[i], b[i]);\n            if (c != 0)\n                return c;\n        }\n        return Integer.compare(len1, len2);\n    }\n}\n"}
{"id": 54125, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54126, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54127, "name": "Order disjoint list items", "Python": "from __future__ import print_function\n\ndef order_disjoint_list_items(data, items):\n    \n    itemindices = []\n    for item in set(items):\n        itemcount = items.count(item)\n        \n        lastindex = [-1]\n        for i in range(itemcount):\n            lastindex.append(data.index(item, lastindex[-1] + 1))\n        itemindices += lastindex[1:]\n    itemindices.sort()\n    for index, item in zip(itemindices, items):\n        data[index] = item\n\nif __name__ == '__main__':\n    tostring = ' '.join\n    for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),\n                         (str.split('the cat sat on the mat'), str.split('cat mat')),\n                         (list('ABCABCABC'), list('CACA')),\n                         (list('ABCABDABE'), list('EADA')),\n                         (list('AB'), list('B')),\n                         (list('AB'), list('BA')),\n                         (list('ABBA'), list('BA')),\n                         (list(''), list('')),\n                         (list('A'), list('A')),\n                         (list('AB'), list('')),\n                         (list('ABBA'), list('AB')),\n                         (list('ABAB'), list('AB')),\n                         (list('ABAB'), list('BABA')),\n                         (list('ABCCBA'), list('ACAC')),\n                         (list('ABCCBA'), list('CACA')),\n                       ]:\n        print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')\n        order_disjoint_list_items(data, items)\n        print(\"-> M' %r\" % tostring(data))\n", "Java": "import java.util.Arrays;\nimport java.util.BitSet;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class OrderDisjointItems {\n\n    public static void main(String[] args) {\n        final String[][] MNs = {{\"the cat sat on the mat\", \"mat cat\"},\n        {\"the cat sat on the mat\", \"cat mat\"},\n        {\"A B C A B C A B C\", \"C A C A\"}, {\"A B C A B D A B E\", \"E A D A\"},\n        {\"A B\", \"B\"}, {\"A B\", \"B A\"}, {\"A B B A\", \"B A\"}, {\"X X Y\", \"X\"}};\n\n        for (String[] a : MNs) {\n            String[] r = orderDisjointItems(a[0].split(\" \"), a[1].split(\" \"));\n            System.out.printf(\"%s | %s -> %s%n\", a[0], a[1], Arrays.toString(r));\n        }\n    }\n\n    \n    static String[] orderDisjointItems(String[] m, String[] n) {\n        for (String e : n) {\n            int idx = ArrayUtils.indexOf(m, e);\n            if (idx != -1)\n                m[idx] = null;\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (m[i] == null)\n                m[i] = n[j++];\n        }\n        return m;\n    }\n\n    \n    static String[] orderDisjointItems2(String[] m, String[] n) {\n        BitSet bitSet = new BitSet(m.length);\n        for (String e : n) {\n            int idx = -1;\n            do {\n                idx = ArrayUtils.indexOf(m, e, idx + 1);\n            } while (idx != -1 && bitSet.get(idx));\n            if (idx != -1)\n                bitSet.set(idx);\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (bitSet.get(i))\n                m[i] = n[j++];\n        }\n        return m;\n    }\n}\n"}
{"id": 54128, "name": "Here document", "Python": "print()\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 54129, "name": "Here document", "Python": "print()\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 54130, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 54131, "name": "Sierpinski curve", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 54132, "name": "Sierpinski curve", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 54133, "name": "Most frequent k chars distance", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n", "Java": "import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class SDF {\n\n    \n    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {\n\n        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();\n\n        for (char element : array) {\n            Integer count = countMap.get(element);\n            count = (count == null) ? 1 : count + 1;\n            countMap.put(element, count);\n        }\n\n        return countMap;\n    }\n    \n    \n    private static <K, V extends Comparable<? super V>>\n            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { \n\tList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());\n\t\n\tCollections.sort(list, new Comparator<Map.Entry<K, V>>() {\n\t\tpublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n\t\t    return o2.getValue().compareTo(o1.getValue());\n\t\t}\n\t    });\n\n\t\n\t\n\tHashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();\n\tfor (Map.Entry<K, V> entry : list) {\n\t    sortedHashMap.put(entry.getKey(), entry.getValue());\n\t} \n\treturn sortedHashMap;\n    }\n    \n    public static String mostOcurrencesElement(char[] array, int k) {\n        HashMap<Character, Integer> countMap = countElementOcurrences(array);\n        System.out.println(countMap);\n        Map<Character, Integer> map = descendingSortByValues(countMap); \n        System.out.println(map);\n        int i = 0;\n        String output = \"\";\n        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {\n\t    if (i++ >= k)\n\t\tbreak;\n            output += \"\" + pairs.getKey() + pairs.getValue();\n        }\n        return output;\n    }\n    \n    public static int getDiff(String str1, String str2, int limit) {\n        int similarity = 0;\n\tint k = 0;\n\tfor (int i = 0; i < str1.length() ; i = k) {\n\t    k ++;\n\t    if (Character.isLetter(str1.charAt(i))) {\n\t\tint pos = str2.indexOf(str1.charAt(i));\n\t\t\t\t\n\t\tif (pos >= 0) {\t\n\t\t    String digitStr1 = \"\";\n\t\t    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {\n\t\t\tdigitStr1 += str1.charAt(k);\n\t\t\tk++;\n\t\t    }\n\t\t\t\t\t\n\t\t    int k2 = pos+1;\n\t\t    String digitStr2 = \"\";\n\t\t    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {\n\t\t\tdigitStr2 += str2.charAt(k2);\n\t\t\tk2++;\n\t\t    }\n\t\t\t\t\t\n\t\t    similarity += Integer.parseInt(digitStr2)\n\t\t\t+ Integer.parseInt(digitStr1);\n\t\t\t\t\t\n\t\t} \n\t    }\n\t}\n\treturn Math.abs(limit - similarity);\n    }\n    \n    public static int SDFfunc(String str1, String str2, int limit) {\n        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);\n    }\n\n    public static void main(String[] args) {\n        String input1 = \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\";\n        String input2 = \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\";\n        System.out.println(SDF.SDFfunc(input1,input2,100));\n\n    }\n\n}\n"}
{"id": 54134, "name": "Pig the dice game_Player", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 54135, "name": "Pig the dice game_Player", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 54136, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n"}
{"id": 54137, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n"}
{"id": 54138, "name": "Sierpinski square curve", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n"}
{"id": 54139, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 54140, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 54141, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 54142, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 54143, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 54144, "name": "Odd words", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class OddWords {\n    public static void main(String[] args) {\n        try {\n            Set<String> dictionary = new TreeSet<>();\n            final int minLength = 5;\n            String fileName = \"unixdict.txt\";\n            if (args.length != 0)\n                fileName = args[0];\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        dictionary.add(line);\n                }\n            }\n            StringBuilder word1 = new StringBuilder();\n            StringBuilder word2 = new StringBuilder();\n            List<StringPair> evenWords = new ArrayList<>();\n            List<StringPair> oddWords = new ArrayList<>();\n            for (String word : dictionary) {\n                int length = word.length();\n                if (length < minLength + 2 * (minLength/2))\n                    continue;\n                word1.setLength(0);\n                word2.setLength(0);\n                for (int i = 0; i < length; ++i) {\n                    if ((i & 1) == 0)\n                        word1.append(word.charAt(i));\n                    else\n                        word2.append(word.charAt(i));\n                }\n                String oddWord = word1.toString();\n                String evenWord = word2.toString();\n                if (dictionary.contains(oddWord))\n                    oddWords.add(new StringPair(word, oddWord));\n                if (dictionary.contains(evenWord))\n                    evenWords.add(new StringPair(word, evenWord));\n            }\n            System.out.println(\"Odd words:\");\n            printWords(oddWords);\n            System.out.println(\"\\nEven words:\");\n            printWords(evenWords);\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n\n    private static void printWords(List<StringPair> strings) {\n        int n = 1;\n        for (StringPair pair : strings) {\n            System.out.printf(\"%2d: %-14s%s\\n\", n++,\n                                    pair.string1, pair.string2);\n        }\n    }\n\n    private static class StringPair {\n        private String string1;\n        private String string2;\n        private StringPair(String s1, String s2) {\n            string1 = s1;\n            string2 = s2;\n        }\n    }\n}\n"}
{"id": 54145, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n"}
{"id": 54146, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n"}
{"id": 54147, "name": "Word break problem", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n"}
{"id": 54148, "name": "Word break problem", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n"}
{"id": 54149, "name": "Brilliant numbers", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n"}
{"id": 54150, "name": "Brilliant numbers", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n"}
{"id": 54151, "name": "Word ladder", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n"}
{"id": 54152, "name": "Word ladder", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n"}
{"id": 54153, "name": "Earliest difference between prime gaps", "Python": "\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n    if pri[i] - pri[i - 1] not in gapstarts:\n        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n    while GAP1 not in gapstarts:\n        GAP1 += 2\n    start1 = gapstarts[GAP1]\n    GAP2 = GAP1 + 2\n    if GAP2 not in gapstarts:\n        GAP1 = GAP2 + 2\n        continue\n    start2 = gapstarts[GAP2]\n    diff = abs(start2 - start1)\n    if diff > PM:\n        print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n        print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n        if PM == LIMIT:\n            break\n        PM *= 10\n    else:\n        GAP1 = GAP2\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n"}
{"id": 54154, "name": "Latin Squares in reduced form", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n"}
{"id": 54155, "name": "UPC", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n"}
{"id": 54156, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 54157, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 54158, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n"}
{"id": 54159, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "Java": "public class Animal{\n   \n}\n"}
{"id": 54160, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 54161, "name": "Color wheel", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n"}
{"id": 54162, "name": "Plasma effect", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 54163, "name": "Plasma effect", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 54164, "name": "Hello world_Newbie", "Python": "print \"Goodbye, World!\"\n", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n"}
{"id": 54165, "name": "Hello world_Newbie", "Python": "print \"Goodbye, World!\"\n", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n"}
{"id": 54166, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n"}
{"id": 54167, "name": "Wagstaff primes", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n"}
{"id": 54168, "name": "Wagstaff primes", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n"}
{"id": 54169, "name": "Wagstaff primes", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n"}
{"id": 54170, "name": "Create an object_Native demonstration", "Python": "from collections import UserDict\nimport copy\n\nclass Dict(UserDict):\n    \n    def __init__(self, dict=None, **kwargs):\n        self.__init = True\n        super().__init__(dict, **kwargs)\n        self.default = copy.deepcopy(self.data)\n        self.__init = False\n    \n    def __delitem__(self, key):\n        if key in self.default:\n            self.data[key] = self.default[key]\n        else:\n            raise NotImplementedError\n\n    def __setitem__(self, key, item):\n        if self.__init:\n            super().__setitem__(key, item)\n        elif key in self.data:\n            self.data[key] = item\n        else:\n            raise KeyError\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, super().__repr__())\n    \n    def fromkeys(cls, iterable, value=None):\n        if self.__init:\n            super().fromkeys(cls, iterable, value)\n        else:\n            for key in iterable:\n                if key in self.data:\n                    self.data[key] = value\n                else:\n                    raise KeyError\n\n    def clear(self):\n        self.data.update(copy.deepcopy(self.default))\n\n    def pop(self, key, default=None):\n        raise NotImplementedError\n\n    def popitem(self):\n        raise NotImplementedError\n\n    def update(self, E, **F):\n        if self.__init:\n            super().update(E, **F)\n        else:\n            haskeys = False\n            try:\n                keys = E.keys()\n                haskeys = Ture\n            except AttributeError:\n                pass\n            if haskeys:\n                for key in keys:\n                    self[key] = E[key]\n            else:\n                for key, val in E:\n                    self[key] = val\n            for key in F:\n                self[key] = F[key]\n\n    def setdefault(self, key, default=None):\n        if key not in self.data:\n            raise KeyError\n        else:\n            return super().setdefault(key, default)\n", "Java": "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\npublic class ImmutableMap {\n\n    public static void main(String[] args) {\n        Map<String,Integer> hashMap = getImmutableMap();\n        try {\n            hashMap.put(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put new value.\");\n        }\n        try {\n            hashMap.clear();\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to clear map.\");\n        }\n        try {\n            hashMap.putIfAbsent(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put if absent.\");\n        }\n        \n        for ( String key : hashMap.keySet() ) {\n            System.out.printf(\"key = %s, value = %s%n\", key, hashMap.get(key));\n        }\n    }\n    \n    private static Map<String,Integer> getImmutableMap() {\n        Map<String,Integer> hashMap = new HashMap<>();\n        hashMap.put(\"Key 1\", 34);\n        hashMap.put(\"Key 2\", 105);\n        hashMap.put(\"Key 3\", 144);\n\n        return Collections.unmodifiableMap(hashMap);\n    }\n    \n}\n"}
{"id": 54171, "name": "Rare numbers", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n", "Java": "import java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\n\npublic class RareNumbers {\n    public interface Consumer5<A, B, C, D, E> {\n        void apply(A a, B b, C c, D d, E e);\n    }\n\n    public interface Consumer7<A, B, C, D, E, F, G> {\n        void apply(A a, B b, C c, D d, E e, F f, G g);\n    }\n\n    public interface Recursable5<A, B, C, D, E> {\n        void apply(A a, B b, C c, D d, E e, Recursable5<A, B, C, D, E> r);\n    }\n\n    public interface Recursable7<A, B, C, D, E, F, G> {\n        void apply(A a, B b, C c, D d, E e, F f, G g, Recursable7<A, B, C, D, E, F, G> r);\n    }\n\n    public static <A, B, C, D, E> Consumer5<A, B, C, D, E> recurse(Recursable5<A, B, C, D, E> r) {\n        return (a, b, c, d, e) -> r.apply(a, b, c, d, e, r);\n    }\n\n    public static <A, B, C, D, E, F, G> Consumer7<A, B, C, D, E, F, G> recurse(Recursable7<A, B, C, D, E, F, G> r) {\n        return (a, b, c, d, e, f, g) -> r.apply(a, b, c, d, e, f, g, r);\n    }\n\n    private static class Term {\n        long coeff;\n        byte ix1, ix2;\n\n        public Term(long coeff, byte ix1, byte ix2) {\n            this.coeff = coeff;\n            this.ix1 = ix1;\n            this.ix2 = ix2;\n        }\n    }\n\n    private static final int MAX_DIGITS = 16;\n\n    private static long toLong(List<Byte> digits, boolean reverse) {\n        long sum = 0;\n        if (reverse) {\n            for (int i = digits.size() - 1; i >= 0; --i) {\n                sum = sum * 10 + digits.get(i);\n            }\n        } else {\n            for (Byte digit : digits) {\n                sum = sum * 10 + digit;\n            }\n        }\n        return sum;\n    }\n\n    private static boolean isNotSquare(long n) {\n        long root = (long) Math.sqrt(n);\n        return root * root != n;\n    }\n\n    private static List<Byte> seq(byte from, byte to, byte step) {\n        List<Byte> res = new ArrayList<>();\n        for (byte i = from; i <= to; i += step) {\n            res.add(i);\n        }\n        return res;\n    }\n\n    private static String commatize(long n) {\n        String s = String.valueOf(n);\n        int le = s.length();\n        int i = le - 3;\n        while (i >= 1) {\n            s = s.substring(0, i) + \",\" + s.substring(i);\n            i -= 3;\n        }\n        return s;\n    }\n\n    public static void main(String[] args) {\n        final LocalDateTime startTime = LocalDateTime.now();\n        long pow = 1L;\n        System.out.println(\"Aggregate timings to process all numbers up to:\");\n        \n        List<List<Term>> allTerms = new ArrayList<>();\n        for (int i = 0; i < MAX_DIGITS - 1; ++i) {\n            allTerms.add(new ArrayList<>());\n        }\n        for (int r = 2; r <= MAX_DIGITS; ++r) {\n            List<Term> terms = new ArrayList<>();\n            pow *= 10;\n            long pow1 = pow;\n            long pow2 = 1;\n            byte i1 = 0;\n            byte i2 = (byte) (r - 1);\n            while (i1 < i2) {\n                terms.add(new Term(pow1 - pow2, i1, i2));\n\n                pow1 /= 10;\n                pow2 *= 10;\n\n                i1++;\n                i2--;\n            }\n            allTerms.set(r - 2, terms);\n        }\n        \n        Map<Byte, List<List<Byte>>> fml = Map.of(\n            (byte) 0, List.of(List.of((byte) 2, (byte) 2), List.of((byte) 8, (byte) 8)),\n            (byte) 1, List.of(List.of((byte) 6, (byte) 5), List.of((byte) 8, (byte) 7)),\n            (byte) 4, List.of(List.of((byte) 4, (byte) 0)),\n            (byte) 6, List.of(List.of((byte) 6, (byte) 0), List.of((byte) 8, (byte) 2))\n        );\n        \n        Map<Byte, List<List<Byte>>> dmd = new HashMap<>();\n        for (int i = 0; i < 100; ++i) {\n            List<Byte> a = List.of((byte) (i / 10), (byte) (i % 10));\n\n            int d = a.get(0) - a.get(1);\n            dmd.computeIfAbsent((byte) d, k -> new ArrayList<>()).add(a);\n        }\n        List<Byte> fl = List.of((byte) 0, (byte) 1, (byte) 4, (byte) 6);\n        List<Byte> dl = seq((byte) -9, (byte) 9, (byte) 1); \n        List<Byte> zl = List.of((byte) 0);                  \n        List<Byte> el = seq((byte) -8, (byte) 8, (byte) 2); \n        List<Byte> ol = seq((byte) -9, (byte) 9, (byte) 2); \n        List<Byte> il = seq((byte) 0, (byte) 9, (byte) 1);\n        List<Long> rares = new ArrayList<>();\n        List<List<List<Byte>>> lists = new ArrayList<>();\n        for (int i = 0; i < 4; ++i) {\n            lists.add(new ArrayList<>());\n        }\n        for (int i = 0; i < fl.size(); ++i) {\n            List<List<Byte>> temp1 = new ArrayList<>();\n            List<Byte> temp2 = new ArrayList<>();\n            temp2.add(fl.get(i));\n            temp1.add(temp2);\n            lists.set(i, temp1);\n        }\n        final AtomicReference<List<Byte>> digits = new AtomicReference<>(new ArrayList<>());\n        AtomicInteger count = new AtomicInteger();\n\n        \n        \n        Consumer7<List<Byte>, List<Byte>, List<List<Byte>>, List<List<Byte>>, Long, Integer, Integer> fnpr = recurse((cand, di, dis, indicies, nmr, nd, level, func) -> {\n            if (level == dis.size()) {\n                digits.get().set(indicies.get(0).get(0), fml.get(cand.get(0)).get(di.get(0)).get(0));\n                digits.get().set(indicies.get(0).get(1), fml.get(cand.get(0)).get(di.get(0)).get(1));\n                int le = di.size();\n                if (nd % 2 == 1) {\n                    le--;\n                    digits.get().set(nd / 2, di.get(le));\n                }\n                for (int i = 1; i < le; ++i) {\n                    digits.get().set(indicies.get(i).get(0), dmd.get(cand.get(i)).get(di.get(i)).get(0));\n                    digits.get().set(indicies.get(i).get(1), dmd.get(cand.get(i)).get(di.get(i)).get(1));\n                }\n                long r = toLong(digits.get(), true);\n                long npr = nmr + 2 * r;\n                if (isNotSquare(npr)) {\n                    return;\n                }\n                count.getAndIncrement();\n                System.out.printf(\"     R/N %2d:\", count.get());\n                LocalDateTime checkPoint = LocalDateTime.now();\n                long elapsed = Duration.between(startTime, checkPoint).toMillis();\n                System.out.printf(\"  %9sms\", elapsed);\n                long n = toLong(digits.get(), false);\n                System.out.printf(\"  (%s)\\n\", commatize(n));\n                rares.add(n);\n            } else {\n                for (Byte num : dis.get(level)) {\n                    di.set(level, num);\n                    func.apply(cand, di, dis, indicies, nmr, nd, level + 1, func);\n                }\n            }\n        });\n\n        \n        Consumer5<List<Byte>, List<List<Byte>>, List<List<Byte>>, Integer, Integer> fnmr = recurse((cand, list, indicies, nd, level, func) -> {\n            if (level == list.size()) {\n                long nmr = 0;\n                long nmr2 = 0;\n                List<Term> terms = allTerms.get(nd - 2);\n                for (int i = 0; i < terms.size(); ++i) {\n                    Term t = terms.get(i);\n                    if (cand.get(i) >= 0) {\n                        nmr += t.coeff * cand.get(i);\n                    } else {\n                        nmr2 += t.coeff * -cand.get(i);\n                        if (nmr >= nmr2) {\n                            nmr -= nmr2;\n                            nmr2 = 0;\n                        } else {\n                            nmr2 -= nmr;\n                            nmr = 0;\n                        }\n                    }\n                }\n                if (nmr2 >= nmr) {\n                    return;\n                }\n                nmr -= nmr2;\n                if (isNotSquare(nmr)) {\n                    return;\n                }\n                List<List<Byte>> dis = new ArrayList<>();\n                dis.add(seq((byte) 0, (byte) (fml.get(cand.get(0)).size() - 1), (byte) 1));\n                for (int i = 1; i < cand.size(); ++i) {\n                    dis.add(seq((byte) 0, (byte) (dmd.get(cand.get(i)).size() - 1), (byte) 1));\n                }\n                if (nd % 2 == 1) {\n                    dis.add(il);\n                }\n                List<Byte> di = new ArrayList<>();\n                for (int i = 0; i < dis.size(); ++i) {\n                    di.add((byte) 0);\n                }\n                fnpr.apply(cand, di, dis, indicies, nmr, nd, 0);\n            } else {\n                for (Byte num : list.get(level)) {\n                    cand.set(level, num);\n                    func.apply(cand, list, indicies, nd, level + 1, func);\n                }\n            }\n        });\n\n        for (int nd = 2; nd <= MAX_DIGITS; ++nd) {\n            digits.set(new ArrayList<>());\n            for (int i = 0; i < nd; ++i) {\n                digits.get().add((byte) 0);\n            }\n            if (nd == 4) {\n                lists.get(0).add(zl);\n                lists.get(1).add(ol);\n                lists.get(2).add(el);\n                lists.get(3).add(ol);\n            } else if (allTerms.get(nd - 2).size() > lists.get(0).size()) {\n                for (int i = 0; i < 4; ++i) {\n                    lists.get(i).add(dl);\n                }\n            }\n            List<List<Byte>> indicies = new ArrayList<>();\n            for (Term t : allTerms.get(nd - 2)) {\n                indicies.add(List.of(t.ix1, t.ix2));\n            }\n            for (List<List<Byte>> list : lists) {\n                List<Byte> cand = new ArrayList<>();\n                for (int i = 0; i < list.size(); ++i) {\n                    cand.add((byte) 0);\n                }\n                fnmr.apply(cand, list, indicies, nd, 0);\n            }\n            LocalDateTime checkPoint = LocalDateTime.now();\n            long elapsed = Duration.between(startTime, checkPoint).toMillis();\n            System.out.printf(\"  %2d digits:  %9sms\\n\", nd, elapsed);\n        }\n\n        Collections.sort(rares);\n        System.out.printf(\"\\nThe rare numbers with up to %d digits are:\\n\", MAX_DIGITS);\n        for (int i = 0; i < rares.size(); ++i) {\n            System.out.printf(\"  %2d:  %25s\\n\", i + 1, commatize(rares.get(i)));\n        }\n    }\n}\n"}
{"id": 54172, "name": "Arithmetic evaluation", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n"}
{"id": 54173, "name": "Arithmetic evaluation", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n"}
{"id": 54174, "name": "Special variables", "Python": "names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))\nprint( '\\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )\n", "Java": "import java.util.Arrays;\n\npublic class SpecialVariables {\n\n    public static void main(String[] args) {\n\n        \n        \n        System.out.println(Arrays.toString(args));\n\n        \n        \n        System.out.println(SpecialVariables.class);\n\n\n        \n\n        \n        System.out.println(System.getenv());\n\n        \n        \n        System.out.println(System.getProperties());\n\n        \n        \n        System.out.println(Runtime.getRuntime().availableProcessors());\n\n    }\n}\n"}
{"id": 54175, "name": "Execute CopyPasta Language", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n", "Java": "import java.io.File;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class Copypasta\n{\n\t\n\tpublic static void fatal_error(String errtext)\n\t{\n\t\tStackTraceElement[] stack = Thread.currentThread().getStackTrace();\n\t\tStackTraceElement main = stack[stack.length - 1];\n\t\tString mainClass = main.getClassName();\n\t\tSystem.out.println(\"%\" + errtext);\n\t\tSystem.out.println(\"usage: \" + mainClass + \" [filename.cp]\");\n\t\tSystem.exit(1);\n\t}\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tString fname = null;\n\t\tString source = null;\n\t\ttry\n\t\t{\n\t\t\tfname = args[0];\n\t\t\tsource = new String(Files.readAllBytes(new File(fname).toPath()));\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tfatal_error(\"error while trying to read from specified file\");\n\t\t}\n\n\t\t\n\t\tArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split(\"\\n\")));\n\t\t\n\t\t\n\t\tString clipboard = \"\";\n\t\t\n\t\t\n\t\tint loc = 0;\n\t\twhile(loc < lines.size())\n\t\t{\n\t\t\t\n\t\t\tString command = lines.get(loc).trim();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(command.equals(\"Copy\"))\n\t\t\t\t\tclipboard += lines.get(loc + 1);\n\t\t\t\telse if(command.equals(\"CopyFile\"))\n\t\t\t\t{\n\t\t\t\t\tif(lines.get(loc + 1).equals(\"TheF*ckingCode\"))\n\t\t\t\t\t\tclipboard += source;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tString filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));\n\t\t\t\t\t\tclipboard += filetext;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Duplicate\"))\n\t\t\t\t{\n\t\t\t\t\tString origClipboard = clipboard;\n\n\t\t\t\t\tint amount = Integer.parseInt(lines.get(loc + 1)) - 1;\n\t\t\t\t\tfor(int i = 0; i < amount; i++)\n\t\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Pasta!\"))\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(clipboard);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\n\t\t\t\n\t\t\tloc += 2;\n\t\t}\n\t}\n}\n"}
{"id": 54176, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n"}
{"id": 54177, "name": "Minimal steps down to 1", "Python": "from functools import lru_cache\n\n\n\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n    \"Recursive, memoised minimised steps to 1\"\n\n    def __init__(self, divs=DIVS, subs=SUBS):\n        self.divs, self.subs = divs, subs\n\n    @lru_cache(maxsize=None)\n    def _minrec(self, n):\n        \"Recursive, memoised\"\n        if n == 1:\n            return 0, ['=1']\n        possibles = {}\n        for d in self.divs:\n            if n % d == 0:\n                possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n        for s in self.subs:\n            if n > s:\n                possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n        thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n        ret = 1 + count, [thiskind] + otherkinds\n        return ret\n\n    def __call__(self, n):\n        \"Recursive, memoised\"\n        ans = self._minrec(n)[1][:-1]\n        return len(ans), ans\n\n\nif __name__ == '__main__':\n    for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n        minrec = Minrec(DIVS, SUBS)\n        print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n        print('  Possible divisors:  ', DIVS)\n        print('  Possible decrements:', SUBS)\n        for n in range(1, 11):\n            steps, how = minrec(n)\n            print(f'    minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n        upto = 2000\n        print(f'\\n    Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n        stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n        mx = stepn[-1][0]\n        ans = [x[1] for x in stepn if x[0] == mx]\n        print('      Taking', mx, f'steps is/are the {len(ans)} numbers:',\n              ', '.join(str(n) for n in sorted(ans)))\n        \n        print()\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MinimalStepsDownToOne {\n\n    public static void main(String[] args) {\n        runTasks(getFunctions1());\n        runTasks(getFunctions2());\n        runTasks(getFunctions3());\n    }\n    \n    private static void runTasks(List<Function> functions) {\n        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);\n\n        \n        int max = 10;\n        populateMap(minPath, functions, max);\n        System.out.printf(\"%nWith functions:  %s%n\", functions);\n        System.out.printf(\"  Minimum steps to 1:%n\");\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int steps = minPath.get(n).size();\n            System.out.printf(\"    %2d: %d step%1s: %s%n\", n, steps, steps == 1 ? \"\" : \"s\", minPath.get(n));\n        }\n        \n        \n        displayMaxMin(minPath, functions, 2000);\n\n        \n        displayMaxMin(minPath, functions, 20000);\n\n        \n        displayMaxMin(minPath, functions, 100000);\n    }\n    \n    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        populateMap(minPath, functions, max);\n        List<Integer> maxIntegers = getMaxMin(minPath, max);\n        int maxSteps = maxIntegers.remove(0);\n        int numCount = maxIntegers.size();\n        System.out.printf(\"  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n\", numCount == 1 ? \"is\" : \"are\", numCount, numCount == 1 ? \"\" : \"s\", max, maxSteps, maxIntegers);\n        \n    }\n    \n    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {\n        int maxSteps = Integer.MIN_VALUE;\n        List<Integer> maxIntegers = new ArrayList<Integer>();\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int len = minPath.get(n).size();\n            if ( len > maxSteps ) {\n                maxSteps = len;\n                maxIntegers.clear();\n                maxIntegers.add(n);\n            }\n            else if ( len == maxSteps ) {\n                maxIntegers.add(n);\n            }\n        }\n        maxIntegers.add(0, maxSteps);\n        return maxIntegers;\n    }\n\n    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        for ( int n = 2 ; n <= max ; n++ ) {\n            if ( minPath.containsKey(n) ) {\n                continue;\n            }\n            Function minFunction = null;\n            int minSteps = Integer.MAX_VALUE;\n            for ( Function f : functions ) {\n                if ( f.actionOk(n) ) {\n                    int result = f.action(n);\n                    int steps = 1 + minPath.get(result).size();\n                    if ( steps < minSteps ) {\n                        minFunction = f;\n                        minSteps = steps;\n                    }\n                }\n            }\n            int result = minFunction.action(n);\n            List<String> path = new ArrayList<String>();\n            path.add(minFunction.toString(n));\n            path.addAll(minPath.get(result));\n            minPath.put(n, path);\n        }\n        \n    }\n\n    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {\n        Map<Integer,List<String>> minPath = new HashMap<>();\n        for ( int i = 2 ; i <= max ; i++ ) {\n            for ( Function f : functions ) {\n                if ( f.actionOk(i) ) {\n                    int result = f.action(i);\n                    if ( result == 1 ) {\n                        List<String> path = new ArrayList<String>();\n                        path.add(f.toString(i));\n                        minPath.put(i, path);\n                    }\n                }\n            }\n        }\n        return minPath;\n    }\n\n    private static List<Function> getFunctions3() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide2Function());\n        functions.add(new Divide3Function());\n        functions.add(new Subtract2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions2() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract2Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions1() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n    \n    public abstract static class Function {\n        abstract public int action(int n);\n        abstract public boolean actionOk(int n);\n        abstract public String toString(int n);\n    }\n    \n    public static class Divide2Function extends Function {\n        @Override public int action(int n) {\n            return n/2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 2 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/2 -> \" + n/2;\n        }\n        \n        @Override public String toString() {\n            return \"Divisor 2\";\n        }\n        \n    }\n\n    public static class Divide3Function extends Function {\n        @Override public int action(int n) {\n            return n/3;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 3 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/3 -> \" + n/3;\n        }\n\n        @Override public String toString() {\n            return \"Divisor 3\";\n        }\n\n    }\n\n    public static class Subtract1Function extends Function {\n        @Override public int action(int n) {\n            return n-1;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return true;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-1 -> \" + (n-1);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 1\";\n        }\n\n    }\n\n    public static class Subtract2Function extends Function {\n        @Override public int action(int n) {\n            return n-2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n > 2;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-2 -> \" + (n-2);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 2\";\n        }\n\n    }\n\n}\n"}
{"id": 54178, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n"}
{"id": 54179, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 54180, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 54181, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 54182, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 54183, "name": "Dynamic variable names", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n"}
{"id": 54184, "name": "Data Encryption Standard", "Python": "\n\n\n\nIP = (\n    58, 50, 42, 34, 26, 18, 10, 2,\n    60, 52, 44, 36, 28, 20, 12, 4,\n    62, 54, 46, 38, 30, 22, 14, 6,\n    64, 56, 48, 40, 32, 24, 16, 8,\n    57, 49, 41, 33, 25, 17, 9,  1,\n    59, 51, 43, 35, 27, 19, 11, 3,\n    61, 53, 45, 37, 29, 21, 13, 5,\n    63, 55, 47, 39, 31, 23, 15, 7\n)\nIP_INV = (\n    40,  8, 48, 16, 56, 24, 64, 32,\n    39,  7, 47, 15, 55, 23, 63, 31,\n    38,  6, 46, 14, 54, 22, 62, 30,\n    37,  5, 45, 13, 53, 21, 61, 29,\n    36,  4, 44, 12, 52, 20, 60, 28,\n    35,  3, 43, 11, 51, 19, 59, 27,\n    34,  2, 42, 10, 50, 18, 58, 26,\n    33,  1, 41,  9, 49, 17, 57, 25\n)\nPC1 = (\n    57, 49, 41, 33, 25, 17, 9,\n    1,  58, 50, 42, 34, 26, 18,\n    10, 2,  59, 51, 43, 35, 27,\n    19, 11, 3,  60, 52, 44, 36,\n    63, 55, 47, 39, 31, 23, 15,\n    7,  62, 54, 46, 38, 30, 22,\n    14, 6,  61, 53, 45, 37, 29,\n    21, 13, 5,  28, 20, 12, 4\n)\nPC2 = (\n    14, 17, 11, 24, 1,  5,\n    3,  28, 15, 6,  21, 10,\n    23, 19, 12, 4,  26, 8,\n    16, 7,  27, 20, 13, 2,\n    41, 52, 31, 37, 47, 55,\n    30, 40, 51, 45, 33, 48,\n    44, 49, 39, 56, 34, 53,\n    46, 42, 50, 36, 29, 32\n)\n\nE  = (\n    32, 1,  2,  3,  4,  5,\n    4,  5,  6,  7,  8,  9,\n    8,  9,  10, 11, 12, 13,\n    12, 13, 14, 15, 16, 17,\n    16, 17, 18, 19, 20, 21,\n    20, 21, 22, 23, 24, 25,\n    24, 25, 26, 27, 28, 29,\n    28, 29, 30, 31, 32, 1\n)\n\nSboxes = {\n    0: (\n        14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7,\n        0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8,\n        4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0,\n        15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13\n    ),\n    1: (\n        15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10,\n        3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5,\n        0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15,\n        13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9 \n    ),\n    2: (\n        10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8,\n        13,  7,  0,  9,  3,  4,  6, 10,  2,  8,  5, 14, 12, 11, 15,  1,\n        13,  6,  4,  9,  8, 15,  3,  0, 11,  1,  2, 12,  5, 10, 14,  7,\n        1, 10, 13,  0,  6,  9,  8,  7,  4, 15, 14,  3, 11,  5,  2, 12 \n    ),\n    3: (\n        7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15,\n        13,  8, 11,  5,  6, 15,  0,  3,  4,  7,  2, 12,  1, 10, 14,  9,\n        10,  6,  9,  0, 12, 11,  7, 13, 15,  1,  3, 14,  5,  2,  8,  4,\n        3, 15,  0,  6, 10,  1, 13,  8,  9,  4,  5, 11, 12,  7,  2, 14\n    ),\n    4: (\n        2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9,\n        14, 11,  2, 12,  4,  7, 13,  1,  5,  0, 15, 10,  3,  9,  8,  6,\n        4,  2,  1, 11, 10, 13,  7,  8, 15,  9, 12,  5,  6,  3,  0, 14,\n        11,  8, 12,  7,  1, 14,  2, 13,  6, 15,  0,  9, 10,  4,  5,  3\n    ),\n    5: (\n        12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11,\n        10, 15,  4,  2,  7, 12,  9,  5,  6,  1, 13, 14,  0, 11,  3,  8,\n        9, 14, 15,  5,  2,  8, 12,  3,  7,  0,  4, 10,  1, 13, 11,  6,\n        4,  3,  2, 12,  9,  5, 15, 10, 11, 14,  1,  7,  6,  0,  8, 13\n    ),\n    6: (\n        4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1,\n        13,  0, 11,  7,  4,  9,  1, 10, 14,  3,  5, 12,  2, 15,  8,  6,\n        1,  4, 11, 13, 12,  3,  7, 14, 10, 15,  6,  8,  0,  5,  9,  2,\n        6, 11, 13,  8,  1,  4, 10,  7,  9,  5,  0, 15, 14,  2,  3, 12\n    ),\n    7: (\n        13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7,\n        1, 15, 13,  8, 10,  3,  7,  4, 12,  5,  6, 11,  0, 14,  9,  2,\n        7, 11,  4,  1,  9, 12, 14,  2,  0,  6, 10, 13, 15,  3,  5,  8,\n        2,  1, 14,  7,  4, 10,  8, 13, 15, 12,  9,  0,  3,  5,  6, 11\n    )\n}\n\nP = (\n    16,  7, 20, 21,\n    29, 12, 28, 17,\n    1, 15, 23, 26,\n    5, 18, 31, 10,\n    2,  8, 24, 14,\n    32, 27,  3,  9,\n    19, 13, 30,  6,\n    22, 11, 4,  25\n)\n    \ndef encrypt(msg, key, decrypt=False):\n    \n    assert isinstance(msg, int) and isinstance(key, int)\n    assert not msg.bit_length() > 64\n    assert not key.bit_length() > 64\n\n    \n    key = permutation_by_table(key, 64, PC1) \n\n    \n    \n    C0 = key >> 28\n    D0 = key & (2**28-1)\n    round_keys = generate_round_keys(C0, D0) \n\n    msg_block = permutation_by_table(msg, 64, IP)\n    L0 = msg_block >> 32\n    R0 = msg_block & (2**32-1)\n\n    \n    L_last = L0\n    R_last = R0\n    for i in range(1,17):\n        if decrypt: \n            i = 17-i\n        L_round = R_last\n        R_round = L_last ^ round_function(R_last, round_keys[i])\n        L_last = L_round\n        R_last = R_round\n\n    \n    cipher_block = (R_round<<32) + L_round\n\n    \n    cipher_block = permutation_by_table(cipher_block, 64, IP_INV)\n\n    return cipher_block\n\ndef round_function(Ri, Ki):\n    \n    Ri = permutation_by_table(Ri, 32, E)\n\n    \n    Ri ^= Ki\n\n    \n    Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)]\n\n    \n    for i, block in enumerate(Ri_blocks):\n        \n        row = ((0b100000 & block) >> 4) + (0b1 & block)\n        col = (0b011110 & block) >> 1\n        \n        Ri_blocks[i] = Sboxes[i][16*row+col]\n\n    \n    Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0))\n    Ri = 0\n    for block, lshift_val in Ri_blocks:\n        Ri += (block << lshift_val)\n\n    \n    Ri = permutation_by_table(Ri, 32, P)\n\n    return Ri\n\ndef permutation_by_table(block, block_len, table):\n    \n    block_str = bin(block)[2:].zfill(block_len)\n    perm = []\n    for pos in range(len(table)):\n        perm.append(block_str[table[pos]-1])\n    return int(''.join(perm), 2)\n\ndef generate_round_keys(C0, D0):\n    \n\n    round_keys = dict.fromkeys(range(0,17))\n    lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1)\n\n    \n    lrot = lambda val, r_bits, max_bits: \\\n    (val << r_bits%max_bits) & (2**max_bits-1) | \\\n    ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))\n\n    \n    C0 = lrot(C0, 0, 28)\n    D0 = lrot(D0, 0, 28)\n    round_keys[0] = (C0, D0)\n\n    \n    for i, rot_val in enumerate(lrot_values):\n        i+=1\n        Ci = lrot(round_keys[i-1][0], rot_val, 28)\n        Di = lrot(round_keys[i-1][1], rot_val, 28)\n        round_keys[i] = (Ci, Di)\n\n    \n    \n    \n    del round_keys[0]\n\n    \n    for i, (Ci, Di) in round_keys.items():\n        Ki = (Ci << 28) + Di\n        round_keys[i] = permutation_by_table(Ki, 56, PC2) \n\n    return round_keys\n\nk = 0x0e329232ea6d0d73 \nk2 = 0x133457799BBCDFF1\nm = 0x8787878787878787\nm2 = 0x0123456789ABCDEF\n\ndef prove(key, msg):\n    print('key:       {:x}'.format(key))\n    print('message:   {:x}'.format(msg))\n    cipher_text = encrypt(msg, key)\n    print('encrypted: {:x}'.format(cipher_text))\n    plain_text = encrypt(cipher_text, key, decrypt=True)\n    print('decrypted: {:x}'.format(plain_text))\n\nprove(k, m)\nprint('----------')\nprove(k2, m2)\n", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n"}
{"id": 54185, "name": "Fibonacci matrix-exponentiation", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 54186, "name": "Fibonacci matrix-exponentiation", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 54187, "name": "Commatizing numbers", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n"}
{"id": 54188, "name": "Arithmetic coding_As a generalized change of radix", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n"}
{"id": 54189, "name": "Kosaraju", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n"}
{"id": 54190, "name": "Reflection_List methods", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n"}
{"id": 54191, "name": "Comments", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n", "Java": "\nInt i = 0;     \n"}
{"id": 54192, "name": "Pentomino tiling", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n", "Java": "package pentominotiling;\n\nimport java.util.*;\n\npublic class PentominoTiling {\n\n    static final char[] symbols = \"FILNPTUVWXYZ-\".toCharArray();\n    static final Random rand = new Random();\n\n    static final int nRows = 8;\n    static final int nCols = 8;\n    static final int blank = 12;\n\n    static int[][] grid = new int[nRows][nCols];\n    static boolean[] placed = new boolean[symbols.length - 1];\n\n    public static void main(String[] args) {\n        shuffleShapes();\n\n        for (int r = 0; r < nRows; r++)\n            Arrays.fill(grid[r], -1);\n\n        for (int i = 0; i < 4; i++) {\n            int randRow, randCol;\n            do {\n                randRow = rand.nextInt(nRows);\n                randCol = rand.nextInt(nCols);\n            } while (grid[randRow][randCol] == blank);\n            grid[randRow][randCol] = blank;\n        }\n\n        if (solve(0, 0)) {\n            printResult();\n        } else {\n            System.out.println(\"no solution\");\n        }\n    }\n\n    static void shuffleShapes() {\n        int n = shapes.length;\n        while (n > 1) {\n            int r = rand.nextInt(n--);\n\n            int[][] tmp = shapes[r];\n            shapes[r] = shapes[n];\n            shapes[n] = tmp;\n\n            char tmpSymbol = symbols[r];\n            symbols[r] = symbols[n];\n            symbols[n] = tmpSymbol;\n        }\n    }\n\n    static void printResult() {\n        for (int[] r : grid) {\n            for (int i : r)\n                System.out.printf(\"%c \", symbols[i]);\n            System.out.println();\n        }\n    }\n\n    static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {\n\n        for (int i = 0; i < o.length; i += 2) {\n            int x = c + o[i + 1];\n            int y = r + o[i];\n            if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                return false;\n        }\n\n        grid[r][c] = shapeIndex;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = shapeIndex;\n\n        return true;\n    }\n\n    static void removeOrientation(int[] o, int r, int c) {\n        grid[r][c] = -1;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = -1;\n    }\n\n    static boolean solve(int pos, int numPlaced) {\n        if (numPlaced == shapes.length)\n            return true;\n\n        int row = pos / nCols;\n        int col = pos % nCols;\n\n        if (grid[row][col] != -1)\n            return solve(pos + 1, numPlaced);\n\n        for (int i = 0; i < shapes.length; i++) {\n            if (!placed[i]) {\n                for (int[] orientation : shapes[i]) {\n\n                    if (!tryPlaceOrientation(orientation, row, col, i))\n                        continue;\n\n                    placed[i] = true;\n\n                    if (solve(pos + 1, numPlaced + 1))\n                        return true;\n\n                    removeOrientation(orientation, row, col);\n                    placed[i] = false;\n                }\n            }\n        }\n        return false;\n    }\n\n    static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};\n\n    static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};\n\n    static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};\n\n    static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};\n\n    static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};\n\n    static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};\n\n    static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};\n\n    static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};\n\n    static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};\n}\n"}
{"id": 54193, "name": "Pentomino tiling", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n", "Java": "package pentominotiling;\n\nimport java.util.*;\n\npublic class PentominoTiling {\n\n    static final char[] symbols = \"FILNPTUVWXYZ-\".toCharArray();\n    static final Random rand = new Random();\n\n    static final int nRows = 8;\n    static final int nCols = 8;\n    static final int blank = 12;\n\n    static int[][] grid = new int[nRows][nCols];\n    static boolean[] placed = new boolean[symbols.length - 1];\n\n    public static void main(String[] args) {\n        shuffleShapes();\n\n        for (int r = 0; r < nRows; r++)\n            Arrays.fill(grid[r], -1);\n\n        for (int i = 0; i < 4; i++) {\n            int randRow, randCol;\n            do {\n                randRow = rand.nextInt(nRows);\n                randCol = rand.nextInt(nCols);\n            } while (grid[randRow][randCol] == blank);\n            grid[randRow][randCol] = blank;\n        }\n\n        if (solve(0, 0)) {\n            printResult();\n        } else {\n            System.out.println(\"no solution\");\n        }\n    }\n\n    static void shuffleShapes() {\n        int n = shapes.length;\n        while (n > 1) {\n            int r = rand.nextInt(n--);\n\n            int[][] tmp = shapes[r];\n            shapes[r] = shapes[n];\n            shapes[n] = tmp;\n\n            char tmpSymbol = symbols[r];\n            symbols[r] = symbols[n];\n            symbols[n] = tmpSymbol;\n        }\n    }\n\n    static void printResult() {\n        for (int[] r : grid) {\n            for (int i : r)\n                System.out.printf(\"%c \", symbols[i]);\n            System.out.println();\n        }\n    }\n\n    static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {\n\n        for (int i = 0; i < o.length; i += 2) {\n            int x = c + o[i + 1];\n            int y = r + o[i];\n            if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                return false;\n        }\n\n        grid[r][c] = shapeIndex;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = shapeIndex;\n\n        return true;\n    }\n\n    static void removeOrientation(int[] o, int r, int c) {\n        grid[r][c] = -1;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = -1;\n    }\n\n    static boolean solve(int pos, int numPlaced) {\n        if (numPlaced == shapes.length)\n            return true;\n\n        int row = pos / nCols;\n        int col = pos % nCols;\n\n        if (grid[row][col] != -1)\n            return solve(pos + 1, numPlaced);\n\n        for (int i = 0; i < shapes.length; i++) {\n            if (!placed[i]) {\n                for (int[] orientation : shapes[i]) {\n\n                    if (!tryPlaceOrientation(orientation, row, col, i))\n                        continue;\n\n                    placed[i] = true;\n\n                    if (solve(pos + 1, numPlaced + 1))\n                        return true;\n\n                    removeOrientation(orientation, row, col);\n                    placed[i] = false;\n                }\n            }\n        }\n        return false;\n    }\n\n    static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};\n\n    static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};\n\n    static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};\n\n    static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};\n\n    static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};\n\n    static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};\n\n    static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};\n\n    static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};\n\n    static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};\n}\n"}
{"id": 54194, "name": "Send an unknown method call", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n"}
{"id": 54195, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "Java": "int a;\ndouble b;\nAClassNameHere c;\n"}
{"id": 54196, "name": "Particle swarm optimization", "Python": "import math\nimport random\n\nINFINITY = 1 << 127\nMAX_INT = 1 << 31\n\nclass Parameters:\n    def __init__(self, omega, phip, phig):\n        self.omega = omega\n        self.phip = phip\n        self.phig = phig\n\nclass State:\n    def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):\n        self.iter = iter\n        self.gbpos = gbpos\n        self.gbval = gbval\n        self.min = min\n        self.max = max\n        self.parameters = parameters\n        self.pos = pos\n        self.vel = vel\n        self.bpos = bpos\n        self.bval = bval\n        self.nParticles = nParticles\n        self.nDims = nDims\n\n    def report(self, testfunc):\n        print \"Test Function :\", testfunc\n        print \"Iterations    :\", self.iter\n        print \"Global Best Position :\", self.gbpos\n        print \"Global Best Value    : %.16f\" % self.gbval\n\ndef uniform01():\n    v = random.random()\n    assert 0.0 <= v and v < 1.0\n    return v\n\ndef psoInit(min, max, parameters, nParticles):\n    nDims = len(min)\n    pos = [min[:]] * nParticles\n    vel = [[0.0] * nDims] * nParticles\n    bpos = [min[:]] * nParticles\n    bval = [INFINITY] * nParticles\n    iter = 0\n    gbpos = [INFINITY] * nDims\n    gbval = INFINITY\n    return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n\ndef pso(fn, y):\n    p = y.parameters\n    v = [0.0] * (y.nParticles)\n    bpos = [y.min[:]] * (y.nParticles)\n    bval = [0.0] * (y.nParticles)\n    gbpos = [0.0] * (y.nDims)\n    gbval = INFINITY\n    for j in xrange(0, y.nParticles):\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j]:\n            bpos[j] = y.pos[j][:]\n            bval[j] = v[j]\n        else:\n            bpos[j] = y.bpos[j][:]\n            bval[j] = y.bval[j]\n        if bval[j] < gbval:\n            gbval = bval[j]\n            gbpos = bpos[j][:]\n    rg = uniform01()\n    pos = [[None] * (y.nDims)] * (y.nParticles)\n    vel = [[None] * (y.nDims)] * (y.nParticles)\n    for j in xrange(0, y.nParticles):\n        \n        rp = uniform01()\n        ok = True\n        vel[j] = [0.0] * (len(vel[j]))\n        pos[j] = [0.0] * (len(pos[j]))\n        for k in xrange(0, y.nDims):\n            vel[j][k] = p.omega * y.vel[j][k] \\\n                      + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \\\n                      + p.phig * rg * (gbpos[k] - y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]\n        if not ok:\n            for k in xrange(0, y.nDims):\n                pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()\n    iter = 1 + y.iter\n    return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n\ndef iterate(fn, n, y):\n    r = y\n    old = y\n    if n == MAX_INT:\n        while True:\n            r = pso(fn, r)\n            if r == old:\n                break\n            old = r\n    else:\n        for _ in xrange(0, n):\n            r = pso(fn, r)\n    return r\n\ndef mccormick(x):\n    (a, b) = x\n    return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a\n\ndef michalewicz(x):\n    m = 10\n    d = len(x)\n    sum = 0.0\n    for i in xrange(1, d):\n        j = x[i - 1]\n        k = math.sin(i * j * j / math.pi)\n        sum += math.sin(j) * k ** (2.0 * m)\n    return -sum\n\ndef main():\n    state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)\n    state = iterate(mccormick, 40, state)\n    state.report(\"McCormick\")\n    print \"f(-.54719, -1.54719) : %.16f\" % (mccormick([-.54719, -1.54719]))\n\n    print\n\n    state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)\n    state = iterate(michalewicz, 30, state)\n    state.report(\"Michalewicz (2D)\")\n    print \"f(2.20, 1.57)        : %.16f\" % (michalewicz([2.2, 1.57]))\n\nmain()\n", "Java": "import java.util.Arrays;\nimport java.util.Objects;\nimport java.util.Random;\nimport java.util.function.Function;\n\npublic class App {\n    static class Parameters {\n        double omega;\n        double phip;\n        double phig;\n\n        Parameters(double omega, double phip, double phig) {\n            this.omega = omega;\n            this.phip = phip;\n            this.phig = phig;\n        }\n    }\n\n    static class State {\n        int iter;\n        double[] gbpos;\n        double gbval;\n        double[] min;\n        double[] max;\n        Parameters parameters;\n        double[][] pos;\n        double[][] vel;\n        double[][] bpos;\n        double[] bval;\n        int nParticles;\n        int nDims;\n\n        State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) {\n            this.iter = iter;\n            this.gbpos = gbpos;\n            this.gbval = gbval;\n            this.min = min;\n            this.max = max;\n            this.parameters = parameters;\n            this.pos = pos;\n            this.vel = vel;\n            this.bpos = bpos;\n            this.bval = bval;\n            this.nParticles = nParticles;\n            this.nDims = nDims;\n        }\n\n        void report(String testfunc) {\n            System.out.printf(\"Test Function        : %s\\n\", testfunc);\n            System.out.printf(\"Iterations           : %d\\n\", iter);\n            System.out.printf(\"Global Best Position : %s\\n\", Arrays.toString(gbpos));\n            System.out.printf(\"Global Best value    : %.15f\\n\", gbval);\n        }\n    }\n\n    private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) {\n        int nDims = min.length;\n        double[][] pos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            pos[i] = min.clone();\n        }\n        double[][] vel = new double[nParticles][nDims];\n        double[][] bpos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            bpos[i] = min.clone();\n        }\n        double[] bval = new double[nParticles];\n        for (int i = 0; i < bval.length; ++i) {\n            bval[i] = Double.POSITIVE_INFINITY;\n        }\n        int iter = 0;\n        double[] gbpos = new double[nDims];\n        for (int i = 0; i < gbpos.length; ++i) {\n            gbpos[i] = Double.POSITIVE_INFINITY;\n        }\n        double gbval = Double.POSITIVE_INFINITY;\n        return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n    }\n\n    private static Random r = new Random();\n\n    private static State pso(Function<double[], Double> fn, State y) {\n        Parameters p = y.parameters;\n        double[] v = new double[y.nParticles];\n        double[][] bpos = new double[y.nParticles][];\n        for (int i = 0; i < y.nParticles; ++i) {\n            bpos[i] = y.min.clone();\n        }\n        double[] bval = new double[y.nParticles];\n        double[] gbpos = new double[y.nDims];\n        double gbval = Double.POSITIVE_INFINITY;\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            v[j] = fn.apply(y.pos[j]);\n            \n            if (v[j] < y.bval[j]) {\n                bpos[j] = y.pos[j];\n                bval[j] = v[j];\n            } else {\n                bpos[j] = y.bpos[j];\n                bval[j] = y.bval[j];\n            }\n            if (bval[j] < gbval) {\n                gbval = bval[j];\n                gbpos = bpos[j];\n            }\n        }\n        double rg = r.nextDouble();\n        double[][] pos = new double[y.nParticles][y.nDims];\n        double[][] vel = new double[y.nParticles][y.nDims];\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            double rp = r.nextDouble();\n            boolean ok = true;\n            Arrays.fill(vel[j], 0.0);\n            Arrays.fill(pos[j], 0.0);\n            for (int k = 0; k < y.nDims; ++k) {\n                vel[j][k] = p.omega * y.vel[j][k] +\n                    p.phip * rp * (bpos[j][k] - y.pos[j][k]) +\n                    p.phig * rg * (gbpos[k] - y.pos[j][k]);\n                pos[j][k] = y.pos[j][k] + vel[j][k];\n                ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];\n            }\n            if (!ok) {\n                for (int k = 0; k < y.nDims; ++k) {\n                    pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble();\n                }\n            }\n        }\n        int iter = 1 + y.iter;\n        return new State(\n            iter, gbpos, gbval, y.min, y.max, y.parameters,\n            pos, vel, bpos, bval, y.nParticles, y.nDims\n        );\n    }\n\n    private static State iterate(Function<double[], Double> fn, int n, State y) {\n        State r = y;\n        if (n == Integer.MAX_VALUE) {\n            State old = y;\n            while (true) {\n                r = pso(fn, r);\n                if (Objects.equals(r, old)) break;\n                old = r;\n            }\n        } else {\n            for (int i = 0; i < n; ++i) {\n                r = pso(fn, r);\n            }\n        }\n        return r;\n    }\n\n    private static double mccormick(double[] x) {\n        double a = x[0];\n        double b = x[1];\n        return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;\n    }\n\n    private static double michalewicz(double[] x) {\n        int m = 10;\n        int d = x.length;\n        double sum = 0.0;\n        for (int i = 1; i < d; ++i) {\n            double j = x[i - 1];\n            double k = Math.sin(i * j * j / Math.PI);\n            sum += Math.sin(j) * Math.pow(k, 2.0 * m);\n        }\n        return -sum;\n    }\n\n    public static void main(String[] args) {\n        State state = psoInit(\n            new double[]{-1.5, -3.0},\n            new double[]{4.0, 4.0},\n            new Parameters(0.0, 0.6, 0.3),\n            100\n        );\n        state = iterate(App::mccormick, 40, state);\n        state.report(\"McCormick\");\n        System.out.printf(\"f(-.54719, -1.54719) : %.15f\\n\", mccormick(new double[]{-.54719, -1.54719}));\n        System.out.println();\n\n        state = psoInit(\n            new double[]{0.0, 0.0},\n            new double[]{Math.PI, Math.PI},\n            new Parameters(0.3, 3.0, 0.3),\n            1000\n        );\n        state = iterate(App::michalewicz, 30, state);\n        state.report(\"Michalewicz (2D)\");\n        System.out.printf(\"f(2.20, 1.57)        : %.15f\\n\", michalewicz(new double[]{2.20, 1.57}));\n    }\n}\n"}
{"id": 54197, "name": "Interactive programming (repl)", "Python": "python\nPython 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(string1, string2, separator):\n\treturn separator.join([string1, '', string2])\n\n>>> f('Rosetta', 'Code', ':')\n'Rosetta::Code'\n>>>\n", "Java": "public static void main(String[] args) {\n    System.out.println(concat(\"Rosetta\", \"Code\", \":\"));\n}\n\npublic static String concat(String a, String b, String c) {\n   return a + c + c + b;\n}\n\nRosetta::Code\n"}
{"id": 54198, "name": "Index finite lists of positive integers", "Python": "def rank(x): return int('a'.join(map(str, [1] + x)), 11)\n\ndef unrank(n):\n\ts = ''\n\twhile n: s,n = \"0123456789a\"[n%11] + s, n//11\n\treturn map(int, s.split('a'))[1:]\n\nl = [1, 2, 3, 10, 100, 987654321]\nprint l\nn = rank(l)\nprint n\nl = unrank(n)\nprint l\n", "Java": "import java.math.BigInteger;\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.Collectors.*;\n\npublic class Test3 {\n    static BigInteger rank(int[] x) {\n        String s = stream(x).mapToObj(String::valueOf).collect(joining(\"F\"));\n        return new BigInteger(s, 16);\n    }\n\n    static List<BigInteger> unrank(BigInteger n) {\n        BigInteger sixteen = BigInteger.valueOf(16);\n        String s = \"\";\n        while (!n.equals(BigInteger.ZERO)) {\n            s = \"0123456789ABCDEF\".charAt(n.mod(sixteen).intValue()) + s;\n            n = n.divide(sixteen);\n        }\n        return stream(s.split(\"F\")).map(x -> new BigInteger(x)).collect(toList());\n    }\n\n    public static void main(String[] args) {\n        int[] s = {1, 2, 3, 10, 100, 987654321};\n        System.out.println(Arrays.toString(s));\n        System.out.println(rank(s));\n        System.out.println(unrank(rank(s)));\n    }\n}\n"}
{"id": 54199, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n"}
{"id": 54200, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n"}
{"id": 54201, "name": "Reverse the gender of a string", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n"}
{"id": 54202, "name": "Reverse the gender of a string", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n"}
{"id": 54203, "name": "Audio alarm", "Python": "import time\nimport os\n\nseconds = input(\"Enter a number of seconds: \")\nsound = input(\"Enter an mp3 filename: \")\n\ntime.sleep(float(seconds))\nos.startfile(sound + \".mp3\")\n", "Java": "import com.sun.javafx.application.PlatformImpl;\nimport java.io.File;\nimport java.util.Scanner;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport javafx.scene.media.Media;\nimport javafx.scene.media.MediaPlayer;\n\npublic class AudioAlarm {\n\n    public static void main(String[] args) throws InterruptedException {\n        Scanner input = new Scanner(System.in);\n\n        System.out.print(\"Enter a number of seconds: \");\n        int seconds = Integer.parseInt(input.nextLine());\n\n        System.out.print(\"Enter a filename (must end with .mp3 or .wav): \");\n        String audio = input.nextLine();\n\n        TimeUnit.SECONDS.sleep(seconds);\n\n        Media media = new Media(new File(audio).toURI().toString());\n        AtomicBoolean stop = new AtomicBoolean();\n        Runnable onEnd = () -> stop.set(true);\n\n        PlatformImpl.startup(() -> {}); \n\n        MediaPlayer player = new MediaPlayer(media);\n        player.setOnEndOfMedia(onEnd);\n        player.setOnError(onEnd);\n        player.setOnHalted(onEnd);\n        player.play();\n\n        while (!stop.get()) {\n            Thread.sleep(100);\n        }\n        System.exit(0); \n    }\n}\n"}
{"id": 54204, "name": "Decimal floating point number to binary", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n"}
{"id": 54205, "name": "Decimal floating point number to binary", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n"}
{"id": 54206, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 54207, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 54208, "name": "Check Machin-like formulas", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n"}
{"id": 54209, "name": "Check Machin-like formulas", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n"}
{"id": 54210, "name": "MD5_Implementation", "Python": "import math\n\nrotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\nconstants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]\n\ninit_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]\n\nfunctions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \\\n            16*[lambda b, c, d: (d & b) | (~d & c)] + \\\n            16*[lambda b, c, d: b ^ c ^ d] + \\\n            16*[lambda b, c, d: c ^ (b | ~d)]\n\nindex_functions = 16*[lambda i: i] + \\\n                  16*[lambda i: (5*i + 1)%16] + \\\n                  16*[lambda i: (3*i + 5)%16] + \\\n                  16*[lambda i: (7*i)%16]\n\ndef left_rotate(x, amount):\n    x &= 0xFFFFFFFF\n    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF\n\ndef md5(message):\n\n    message = bytearray(message) \n    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff\n    message.append(0x80)\n    while len(message)%64 != 56:\n        message.append(0)\n    message += orig_len_in_bits.to_bytes(8, byteorder='little')\n\n    hash_pieces = init_values[:]\n\n    for chunk_ofst in range(0, len(message), 64):\n        a, b, c, d = hash_pieces\n        chunk = message[chunk_ofst:chunk_ofst+64]\n        for i in range(64):\n            f = functions[i](b, c, d)\n            g = index_functions[i](i)\n            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')\n            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF\n            a, b, c, d = d, new_b, b, c\n        for i, val in enumerate([a, b, c, d]):\n            hash_pieces[i] += val\n            hash_pieces[i] &= 0xFFFFFFFF\n    \n    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))\n        \ndef md5_to_hex(digest):\n    raw = digest.to_bytes(16, byteorder='little')\n    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))\n\nif __name__=='__main__':\n    demo = [b\"\", b\"a\", b\"abc\", b\"message digest\", b\"abcdefghijklmnopqrstuvwxyz\",\n            b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n            b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"]\n    for message in demo:\n        print(md5_to_hex(md5(message)),' <= \"',message.decode('ascii'),'\"', sep='')\n", "Java": "class MD5\n{\n\n  private static final int INIT_A = 0x67452301;\n  private static final int INIT_B = (int)0xEFCDAB89L;\n  private static final int INIT_C = (int)0x98BADCFEL;\n  private static final int INIT_D = 0x10325476;\n  \n  private static final int[] SHIFT_AMTS = {\n    7, 12, 17, 22,\n    5,  9, 14, 20,\n    4, 11, 16, 23,\n    6, 10, 15, 21\n  };\n  \n  private static final int[] TABLE_T = new int[64];\n  static\n  {\n    for (int i = 0; i < 64; i++)\n      TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));\n  }\n  \n  public static byte[] computeMD5(byte[] message)\n  {\n    int messageLenBytes = message.length;\n    int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;\n    int totalLen = numBlocks << 6;\n    byte[] paddingBytes = new byte[totalLen - messageLenBytes];\n    paddingBytes[0] = (byte)0x80;\n    \n    long messageLenBits = (long)messageLenBytes << 3;\n    for (int i = 0; i < 8; i++)\n    {\n      paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;\n      messageLenBits >>>= 8;\n    }\n    \n    int a = INIT_A;\n    int b = INIT_B;\n    int c = INIT_C;\n    int d = INIT_D;\n    int[] buffer = new int[16];\n    for (int i = 0; i < numBlocks; i ++)\n    {\n      int index = i << 6;\n      for (int j = 0; j < 64; j++, index++)\n        buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);\n      int originalA = a;\n      int originalB = b;\n      int originalC = c;\n      int originalD = d;\n      for (int j = 0; j < 64; j++)\n      {\n        int div16 = j >>> 4;\n        int f = 0;\n        int bufferIndex = j;\n        switch (div16)\n        {\n          case 0:\n            f = (b & c) | (~b & d);\n            break;\n            \n          case 1:\n            f = (b & d) | (c & ~d);\n            bufferIndex = (bufferIndex * 5 + 1) & 0x0F;\n            break;\n            \n          case 2:\n            f = b ^ c ^ d;\n            bufferIndex = (bufferIndex * 3 + 5) & 0x0F;\n            break;\n            \n          case 3:\n            f = c ^ (b | ~d);\n            bufferIndex = (bufferIndex * 7) & 0x0F;\n            break;\n        }\n        int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);\n        a = d;\n        d = c;\n        c = b;\n        b = temp;\n      }\n      \n      a += originalA;\n      b += originalB;\n      c += originalC;\n      d += originalD;\n    }\n    \n    byte[] md5 = new byte[16];\n    int count = 0;\n    for (int i = 0; i < 4; i++)\n    {\n      int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));\n      for (int j = 0; j < 4; j++)\n      {\n        md5[count++] = (byte)n;\n        n >>>= 8;\n      }\n    }\n    return md5;\n  }\n  \n  public static String toHexString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      sb.append(String.format(\"%02X\", b[i] & 0xFF));\n    }\n    return sb.toString();\n  }\n\n  public static void main(String[] args)\n  {\n    String[] testStrings = { \"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" };\n    for (String s : testStrings)\n      System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\");\n    return;\n  }\n  \n}\n"}
{"id": 54211, "name": "K-means++ clustering", "Python": "from math import pi, sin, cos\nfrom collections import namedtuple\nfrom random import random, choice\nfrom copy import copy\n\ntry:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\n\nFLOAT_MAX = 1e100\n\n\nclass Point:\n    __slots__ = [\"x\", \"y\", \"group\"]\n    def __init__(self, x=0.0, y=0.0, group=0):\n        self.x, self.y, self.group = x, y, group\n\n\ndef generate_points(npoints, radius):\n    points = [Point() for _ in xrange(npoints)]\n\n    \n    for p in points:\n        r = random() * radius\n        ang = random() * 2 * pi\n        p.x = r * cos(ang)\n        p.y = r * sin(ang)\n\n    return points\n\n\ndef nearest_cluster_center(point, cluster_centers):\n    \n    def sqr_distance_2D(a, b):\n        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2\n\n    min_index = point.group\n    min_dist = FLOAT_MAX\n\n    for i, cc in enumerate(cluster_centers):\n        d = sqr_distance_2D(cc, point)\n        if min_dist > d:\n            min_dist = d\n            min_index = i\n\n    return (min_index, min_dist)\n\n\ndef kpp(points, cluster_centers):\n    cluster_centers[0] = copy(choice(points))\n    d = [0.0 for _ in xrange(len(points))]\n\n    for i in xrange(1, len(cluster_centers)):\n        sum = 0\n        for j, p in enumerate(points):\n            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]\n            sum += d[j]\n\n        sum *= random()\n\n        for j, di in enumerate(d):\n            sum -= di\n            if sum > 0:\n                continue\n            cluster_centers[i] = copy(points[j])\n            break\n\n    for p in points:\n        p.group = nearest_cluster_center(p, cluster_centers)[0]\n\n\ndef lloyd(points, nclusters):\n    cluster_centers = [Point() for _ in xrange(nclusters)]\n\n    \n    kpp(points, cluster_centers)\n\n    lenpts10 = len(points) >> 10\n\n    changed = 0\n    while True:\n        \n        for cc in cluster_centers:\n            cc.x = 0\n            cc.y = 0\n            cc.group = 0\n\n        for p in points:\n            cluster_centers[p.group].group += 1\n            cluster_centers[p.group].x += p.x\n            cluster_centers[p.group].y += p.y\n\n        for cc in cluster_centers:\n            cc.x /= cc.group\n            cc.y /= cc.group\n\n        \n        changed = 0\n        for p in points:\n            min_i = nearest_cluster_center(p, cluster_centers)[0]\n            if min_i != p.group:\n                changed += 1\n                p.group = min_i\n\n        \n        if changed <= lenpts10:\n            break\n\n    for i, cc in enumerate(cluster_centers):\n        cc.group = i\n\n    return cluster_centers\n\n\ndef print_eps(points, cluster_centers, W=400, H=400):\n    Color = namedtuple(\"Color\", \"r g b\");\n\n    colors = []\n    for i in xrange(len(cluster_centers)):\n        colors.append(Color((3 * (i + 1) % 11) / 11.0,\n                            (7 * i % 11) / 11.0,\n                            (9 * i % 11) / 11.0))\n\n    max_x = max_y = -FLOAT_MAX\n    min_x = min_y = FLOAT_MAX\n\n    for p in points:\n        if max_x < p.x: max_x = p.x\n        if min_x > p.x: min_x = p.x\n        if max_y < p.y: max_y = p.y\n        if min_y > p.y: min_y = p.y\n\n    scale = min(W / (max_x - min_x),\n                H / (max_y - min_y))\n    cx = (max_x + min_x) / 2\n    cy = (max_y + min_y) / 2\n\n    print \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: -5 -5 %d %d\" % (W + 10, H + 10)\n\n    print (\"/l {rlineto} def /m {rmoveto} def\\n\" +\n           \"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\\n\" +\n           \"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath \" +\n           \"   gsave 1 setgray fill grestore gsave 3 setlinewidth\" +\n           \" 1 setgray stroke grestore 0 setgray stroke }def\")\n\n    for i, cc in enumerate(cluster_centers):\n        print (\"%g %g %g setrgbcolor\" %\n               (colors[i].r, colors[i].g, colors[i].b))\n\n        for p in points:\n            if p.group != i:\n                continue\n            print (\"%.3f %.3f c\" % ((p.x - cx) * scale + W / 2,\n                                    (p.y - cy) * scale + H / 2))\n\n        print (\"\\n0 setgray %g %g s\" % ((cc.x - cx) * scale + W / 2,\n                                        (cc.y - cy) * scale + H / 2))\n\n    print \"\\n%%%%EOF\"\n\n\ndef main():\n    npoints = 30000\n    k = 7 \n\n    points = generate_points(npoints, 10)\n    cluster_centers = lloyd(points, k)\n    print_eps(points, cluster_centers)\n\n\nmain()\n", "Java": "import java.util.Random;\n\npublic class KMeansWithKpp{\n\t\t\n\t\tpublic Point[] points;\n\t\tpublic Point[] centroids;\n\t\tRandom rand;\n\t\tpublic int n;\n\t\tpublic int k;\n\n\t\t\n\t\tprivate KMeansWithKpp(){\n\t\t}\n\n\t\tKMeansWithKpp(Point[] p, int clusters){\n\t\t\t\tpoints = p;\n\t\t\t\tn = p.length;\n\t\t\t\tk = Math.max(1, clusters);\n\t\t\t\tcentroids = new Point[k];\n\t\t\t\trand = new Random();\n\t\t}\n\n\n\t\tprivate static double distance(Point a, Point b){\n\t\t\t\treturn (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n\t\t}\n\n\t\tprivate static int nearest(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tint index = pt.group;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn index;\n\t\t}\n\n\t\tprivate static double nearestDistance(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn minD;\n\t\t}\n\n\t\tprivate void kpp(){\n\t\t\t\tcentroids[0] = points[rand.nextInt(n)];\n\t\t\t\tdouble[] dist = new double[n];\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor (int i = 1; i < k; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tdist[j] = nearestDistance(points[j], centroids, i);\n\t\t\t\t\t\t\t\tsum += dist[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tif ((sum -= dist[j]) > 0)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tcentroids[i].x = points[j].x;\n\t\t\t\t\t\t\t\tcentroids[i].y = points[j].y;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tpoints[i].group = nearest(points[i], centroids, k);\n\t\t\t\t}\n\t\t}\n\n\t\tpublic void kMeans(int maxTimes){\n\t\t\t\tif (k == 1 || n <= 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(k >= n){\n\t\t\t\t\t\tfor(int i =0; i < n; i++){\n\t\t\t\t\t\t\t\tpoints[i].group = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxTimes = Math.max(1, maxTimes);\n\t\t\t\tint changed;\n\t\t\t\tint bestPercent = n/1000;\n\t\t\t\tint minIndex;\n\t\t\t\tkpp();\n\t\t\t\tdo {\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x = 0.0;\n\t\t\t\t\t\t\t\tc.y = 0.0;\n\t\t\t\t\t\t\t\tc.group = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tif(pt.group < 0 || pt.group > centroids.length){\n\t\t\t\t\t\t\t\t\t\tpt.group = rand.nextInt(centroids.length);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcentroids[pt.group].x += pt.x;\n\t\t\t\t\t\t\t\tcentroids[pt.group].y = pt.y;\n\t\t\t\t\t\t\t\tcentroids[pt.group].group++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x /= c.group;\n\t\t\t\t\t\t\t\tc.y /= c.group;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tminIndex = nearest(pt, centroids, k);\n\t\t\t\t\t\t\t\tif (k != pt.group) {\n\t\t\t\t\t\t\t\t\t\tchanged++;\n\t\t\t\t\t\t\t\t\t\tpt.group = minIndex;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxTimes--;\n\t\t\t\t} while (changed > bestPercent && maxTimes > 0);\n\t\t}\n}\n\n\n\n\nclass Point{\n\t\tpublic double x;\n\t\tpublic double y;\n\t\tpublic int group;\n\n\t\tPoint(){\n\t\t\t\tx = y = 0.0;\n\t\t\t\tgroup = 0;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){\n\t\t\t\tif (size <= 0)\n\t\t\t\t\t\treturn null;\n\t\t\t\tdouble xdiff, ydiff;\n\t\t\t\txdiff = maxX - minX;\n\t\t\t\tydiff = maxY - minY;\n\t\t\t\tif (minX > maxX) {\n\t\t\t\t\t\txdiff = minX - maxX;\n\t\t\t\t\t\tminX = maxX;\n\t\t\t\t}\n\t\t\t\tif (maxY < minY) {\n\t\t\t\t\t\tydiff = minY - maxY;\n\t\t\t\t\t\tminY = maxY;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tdata[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPolarData(double radius, int size){\n\t\t\t\tif (size <= 0) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tdouble radi, arg;\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tradi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\targ = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].x = radi * Math.cos(arg);\n\t\t\t\t\t\tdata[i].y = radi * Math.sin(arg);\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\t\t\n}\n"}
{"id": 54212, "name": "K-means++ clustering", "Python": "from math import pi, sin, cos\nfrom collections import namedtuple\nfrom random import random, choice\nfrom copy import copy\n\ntry:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\n\nFLOAT_MAX = 1e100\n\n\nclass Point:\n    __slots__ = [\"x\", \"y\", \"group\"]\n    def __init__(self, x=0.0, y=0.0, group=0):\n        self.x, self.y, self.group = x, y, group\n\n\ndef generate_points(npoints, radius):\n    points = [Point() for _ in xrange(npoints)]\n\n    \n    for p in points:\n        r = random() * radius\n        ang = random() * 2 * pi\n        p.x = r * cos(ang)\n        p.y = r * sin(ang)\n\n    return points\n\n\ndef nearest_cluster_center(point, cluster_centers):\n    \n    def sqr_distance_2D(a, b):\n        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2\n\n    min_index = point.group\n    min_dist = FLOAT_MAX\n\n    for i, cc in enumerate(cluster_centers):\n        d = sqr_distance_2D(cc, point)\n        if min_dist > d:\n            min_dist = d\n            min_index = i\n\n    return (min_index, min_dist)\n\n\ndef kpp(points, cluster_centers):\n    cluster_centers[0] = copy(choice(points))\n    d = [0.0 for _ in xrange(len(points))]\n\n    for i in xrange(1, len(cluster_centers)):\n        sum = 0\n        for j, p in enumerate(points):\n            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]\n            sum += d[j]\n\n        sum *= random()\n\n        for j, di in enumerate(d):\n            sum -= di\n            if sum > 0:\n                continue\n            cluster_centers[i] = copy(points[j])\n            break\n\n    for p in points:\n        p.group = nearest_cluster_center(p, cluster_centers)[0]\n\n\ndef lloyd(points, nclusters):\n    cluster_centers = [Point() for _ in xrange(nclusters)]\n\n    \n    kpp(points, cluster_centers)\n\n    lenpts10 = len(points) >> 10\n\n    changed = 0\n    while True:\n        \n        for cc in cluster_centers:\n            cc.x = 0\n            cc.y = 0\n            cc.group = 0\n\n        for p in points:\n            cluster_centers[p.group].group += 1\n            cluster_centers[p.group].x += p.x\n            cluster_centers[p.group].y += p.y\n\n        for cc in cluster_centers:\n            cc.x /= cc.group\n            cc.y /= cc.group\n\n        \n        changed = 0\n        for p in points:\n            min_i = nearest_cluster_center(p, cluster_centers)[0]\n            if min_i != p.group:\n                changed += 1\n                p.group = min_i\n\n        \n        if changed <= lenpts10:\n            break\n\n    for i, cc in enumerate(cluster_centers):\n        cc.group = i\n\n    return cluster_centers\n\n\ndef print_eps(points, cluster_centers, W=400, H=400):\n    Color = namedtuple(\"Color\", \"r g b\");\n\n    colors = []\n    for i in xrange(len(cluster_centers)):\n        colors.append(Color((3 * (i + 1) % 11) / 11.0,\n                            (7 * i % 11) / 11.0,\n                            (9 * i % 11) / 11.0))\n\n    max_x = max_y = -FLOAT_MAX\n    min_x = min_y = FLOAT_MAX\n\n    for p in points:\n        if max_x < p.x: max_x = p.x\n        if min_x > p.x: min_x = p.x\n        if max_y < p.y: max_y = p.y\n        if min_y > p.y: min_y = p.y\n\n    scale = min(W / (max_x - min_x),\n                H / (max_y - min_y))\n    cx = (max_x + min_x) / 2\n    cy = (max_y + min_y) / 2\n\n    print \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: -5 -5 %d %d\" % (W + 10, H + 10)\n\n    print (\"/l {rlineto} def /m {rmoveto} def\\n\" +\n           \"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\\n\" +\n           \"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath \" +\n           \"   gsave 1 setgray fill grestore gsave 3 setlinewidth\" +\n           \" 1 setgray stroke grestore 0 setgray stroke }def\")\n\n    for i, cc in enumerate(cluster_centers):\n        print (\"%g %g %g setrgbcolor\" %\n               (colors[i].r, colors[i].g, colors[i].b))\n\n        for p in points:\n            if p.group != i:\n                continue\n            print (\"%.3f %.3f c\" % ((p.x - cx) * scale + W / 2,\n                                    (p.y - cy) * scale + H / 2))\n\n        print (\"\\n0 setgray %g %g s\" % ((cc.x - cx) * scale + W / 2,\n                                        (cc.y - cy) * scale + H / 2))\n\n    print \"\\n%%%%EOF\"\n\n\ndef main():\n    npoints = 30000\n    k = 7 \n\n    points = generate_points(npoints, 10)\n    cluster_centers = lloyd(points, k)\n    print_eps(points, cluster_centers)\n\n\nmain()\n", "Java": "import java.util.Random;\n\npublic class KMeansWithKpp{\n\t\t\n\t\tpublic Point[] points;\n\t\tpublic Point[] centroids;\n\t\tRandom rand;\n\t\tpublic int n;\n\t\tpublic int k;\n\n\t\t\n\t\tprivate KMeansWithKpp(){\n\t\t}\n\n\t\tKMeansWithKpp(Point[] p, int clusters){\n\t\t\t\tpoints = p;\n\t\t\t\tn = p.length;\n\t\t\t\tk = Math.max(1, clusters);\n\t\t\t\tcentroids = new Point[k];\n\t\t\t\trand = new Random();\n\t\t}\n\n\n\t\tprivate static double distance(Point a, Point b){\n\t\t\t\treturn (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n\t\t}\n\n\t\tprivate static int nearest(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tint index = pt.group;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn index;\n\t\t}\n\n\t\tprivate static double nearestDistance(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn minD;\n\t\t}\n\n\t\tprivate void kpp(){\n\t\t\t\tcentroids[0] = points[rand.nextInt(n)];\n\t\t\t\tdouble[] dist = new double[n];\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor (int i = 1; i < k; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tdist[j] = nearestDistance(points[j], centroids, i);\n\t\t\t\t\t\t\t\tsum += dist[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tif ((sum -= dist[j]) > 0)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tcentroids[i].x = points[j].x;\n\t\t\t\t\t\t\t\tcentroids[i].y = points[j].y;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tpoints[i].group = nearest(points[i], centroids, k);\n\t\t\t\t}\n\t\t}\n\n\t\tpublic void kMeans(int maxTimes){\n\t\t\t\tif (k == 1 || n <= 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(k >= n){\n\t\t\t\t\t\tfor(int i =0; i < n; i++){\n\t\t\t\t\t\t\t\tpoints[i].group = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxTimes = Math.max(1, maxTimes);\n\t\t\t\tint changed;\n\t\t\t\tint bestPercent = n/1000;\n\t\t\t\tint minIndex;\n\t\t\t\tkpp();\n\t\t\t\tdo {\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x = 0.0;\n\t\t\t\t\t\t\t\tc.y = 0.0;\n\t\t\t\t\t\t\t\tc.group = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tif(pt.group < 0 || pt.group > centroids.length){\n\t\t\t\t\t\t\t\t\t\tpt.group = rand.nextInt(centroids.length);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcentroids[pt.group].x += pt.x;\n\t\t\t\t\t\t\t\tcentroids[pt.group].y = pt.y;\n\t\t\t\t\t\t\t\tcentroids[pt.group].group++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x /= c.group;\n\t\t\t\t\t\t\t\tc.y /= c.group;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tminIndex = nearest(pt, centroids, k);\n\t\t\t\t\t\t\t\tif (k != pt.group) {\n\t\t\t\t\t\t\t\t\t\tchanged++;\n\t\t\t\t\t\t\t\t\t\tpt.group = minIndex;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxTimes--;\n\t\t\t\t} while (changed > bestPercent && maxTimes > 0);\n\t\t}\n}\n\n\n\n\nclass Point{\n\t\tpublic double x;\n\t\tpublic double y;\n\t\tpublic int group;\n\n\t\tPoint(){\n\t\t\t\tx = y = 0.0;\n\t\t\t\tgroup = 0;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){\n\t\t\t\tif (size <= 0)\n\t\t\t\t\t\treturn null;\n\t\t\t\tdouble xdiff, ydiff;\n\t\t\t\txdiff = maxX - minX;\n\t\t\t\tydiff = maxY - minY;\n\t\t\t\tif (minX > maxX) {\n\t\t\t\t\t\txdiff = minX - maxX;\n\t\t\t\t\t\tminX = maxX;\n\t\t\t\t}\n\t\t\t\tif (maxY < minY) {\n\t\t\t\t\t\tydiff = minY - maxY;\n\t\t\t\t\t\tminY = maxY;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tdata[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPolarData(double radius, int size){\n\t\t\t\tif (size <= 0) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tdouble radi, arg;\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tradi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\targ = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].x = radi * Math.cos(arg);\n\t\t\t\t\t\tdata[i].y = radi * Math.sin(arg);\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\t\t\n}\n"}
{"id": 54213, "name": "Maze solving", "Python": "\n\ndef Dijkstra(Graph, source):\n    \n    \n    infinity = float('infinity')\n    n = len(graph)\n    dist = [infinity]*n   \n    previous = [infinity]*n \n    dist[source] = 0        \n    Q = list(range(n)) \n    while Q:           \n        u = min(Q, key=lambda n:dist[n])                 \n        Q.remove(u)\n        if dist[u] == infinity:\n            break \n        for v in range(n):               \n            if Graph[u][v] and (v in Q): \n                alt = dist[u] + Graph[u][v]\n                if alt < dist[v]:       \n                    dist[v] = alt\n                    previous[v] = u\n    return dist,previous\n\ndef display_solution(predecessor):\n    cell = len(predecessor)-1\n    while cell:\n        print(cell,end='<')\n        cell = predecessor[cell]\n    print(0)\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class MazeSolver\n{\n    \n    private static String[] readLines (InputStream f) throws IOException\n    {\n        BufferedReader r =\n            new BufferedReader (new InputStreamReader (f, \"US-ASCII\"));\n        ArrayList<String> lines = new ArrayList<String>();\n        String line;\n        while ((line = r.readLine()) != null)\n            lines.add (line);\n        return lines.toArray(new String[0]);\n    }\n\n    \n    private static char[][] decimateHorizontally (String[] lines)\n    {\n        final int width = (lines[0].length() + 1) / 2;\n        char[][] c = new char[lines.length][width];\n        for (int i = 0  ;  i < lines.length  ;  i++)\n            for (int j = 0  ;  j < width  ;  j++)\n                c[i][j] = lines[i].charAt (j * 2);\n        return c;\n    }\n\n    \n    private static boolean solveMazeRecursively (char[][] maze,\n                                                 int x, int y, int d)\n    {\n        boolean ok = false;\n        for (int i = 0  ;  i < 4  &&  !ok  ;  i++)\n            if (i != d)\n                switch (i)\n                    {\n                        \n                    case 0:\n                        if (maze[y-1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y - 2, 2);\n                        break;\n                    case 1:\n                        if (maze[y][x+1] == ' ')\n                            ok = solveMazeRecursively (maze, x + 2, y, 3);\n                        break;\n                    case 2:\n                        if (maze[y+1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y + 2, 0);\n                        break;\n                    case 3:\n                        if (maze[y][x-1] == ' ')\n                            ok = solveMazeRecursively (maze, x - 2, y, 1);\n                        break;\n                    }\n        \n        if (x == 1  &&  y == 1)\n            ok = true;\n        \n        if (ok)\n            {\n                maze[y][x] = '*';\n                switch (d)\n                    {\n                    case 0:\n                        maze[y-1][x] = '*';\n                        break;\n                    case 1:\n                        maze[y][x+1] = '*';\n                        break;\n                    case 2:\n                        maze[y+1][x] = '*';\n                        break;\n                    case 3:\n                        maze[y][x-1] = '*';\n                        break;\n                    }\n            }\n        return ok;\n    }\n\n    \n    private static void solveMaze (char[][] maze)\n    {\n        solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1);\n    }\n\n    \n    private static String[] expandHorizontally (char[][] maze)\n    {\n        char[] tmp = new char[3];\n        String[] lines = new String[maze.length];\n        for (int i = 0  ;  i < maze.length  ;  i++)\n            {\n                StringBuilder sb = new StringBuilder(maze[i].length * 2);\n                for (int j = 0  ;  j < maze[i].length  ;  j++)\n                    if (j % 2 == 0)\n                        sb.append (maze[i][j]);\n                    else\n                        {\n                            tmp[0] = tmp[1] = tmp[2] = maze[i][j];\n                            if (tmp[1] == '*')\n                                tmp[0] = tmp[2] = ' ';\n                            sb.append (tmp);\n                        }\n                lines[i] = sb.toString();\n            }\n        return lines;\n    }\n\n    \n    public static void main (String[] args) throws IOException\n    {\n        InputStream f = (args.length > 0\n                         ?  new FileInputStream (args[0])\n                         :  System.in);\n        String[] lines = readLines (f);\n        char[][] maze = decimateHorizontally (lines);\n        solveMaze (maze);\n        String[] solvedLines = expandHorizontally (maze);\n        for (int i = 0  ;  i < solvedLines.length  ;  i++)\n            System.out.println (solvedLines[i]);\n    }\n}\n"}
{"id": 54214, "name": "Generate random numbers without repeating a value", "Python": "import random\n\nprint(random.sample(range(1, 21), 20))\n", "Java": "import java.util.*;\n\npublic class RandomShuffle {\n    public static void main(String[] args) {\n        Random rand = new Random();\n        List<Integer> list = new ArrayList<>();\n        for (int j = 1; j <= 20; ++j)\n            list.add(j);\n        Collections.shuffle(list, rand);\n        System.out.println(list);\n    }\n}\n"}
{"id": 54215, "name": "Solve triangle solitare puzzle", "Python": "\n\n\ndef DrawBoard(board):\n  peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n  for n in xrange(1,16):\n    peg[n] = '.'\n    if n in board:\n      peg[n] = \"%X\" % n\n  print \"     %s\" % peg[1]\n  print \"    %s %s\" % (peg[2],peg[3])\n  print \"   %s %s %s\" % (peg[4],peg[5],peg[6])\n  print \"  %s %s %s %s\" % (peg[7],peg[8],peg[9],peg[10])\n  print \" %s %s %s %s %s\" % (peg[11],peg[12],peg[13],peg[14],peg[15])\n\n\n\ndef RemovePeg(board,n):\n  board.remove(n)\n\n\ndef AddPeg(board,n):\n  board.append(n)\n\n\ndef IsPeg(board,n):\n  return n in board\n\n\n\nJumpMoves = { 1: [ (2,4),(3,6) ],  \n              2: [ (4,7),(5,9)  ],\n              3: [ (5,8),(6,10) ],\n              4: [ (2,1),(5,6),(7,11),(8,13) ],\n              5: [ (8,12),(9,14) ],\n              6: [ (3,1),(5,4),(9,13),(10,15) ],\n              7: [ (4,2),(8,9)  ],\n              8: [ (5,3),(9,10) ],\n              9: [ (5,2),(8,7)  ],\n             10: [ (9,8) ],\n             11: [ (12,13) ],\n             12: [ (8,5),(13,14) ],\n             13: [ (8,4),(9,6),(12,11),(14,15) ],\n             14: [ (9,5),(13,12)  ],\n             15: [ (10,6),(14,13) ]\n            }\n\nSolution = []\n\n\n\ndef Solve(board):\n  \n  if len(board) == 1:\n    return board \n  \n  for peg in xrange(1,16): \n    if IsPeg(board,peg):\n      movelist = JumpMoves[peg]\n      for over,land in movelist:\n        if IsPeg(board,over) and not IsPeg(board,land):\n          saveboard = board[:] \n          RemovePeg(board,peg)\n          RemovePeg(board,over)\n          AddPeg(board,land) \n\n          Solution.append((peg,over,land))\n\n          board = Solve(board)\n          if len(board) == 1:\n            return board\n        \n          board = saveboard[:] \n          del Solution[-1] \n  return board\n\n\n\n\ndef InitSolve(empty):\n  board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n  RemovePeg(board,empty_start)\n  Solve(board)\n\n\nempty_start = 1\nInitSolve(empty_start)\n\nboard = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nRemovePeg(board,empty_start)\nfor peg,over,land in Solution:\n  RemovePeg(board,peg)\n  RemovePeg(board,over)\n  AddPeg(board,land) \n  DrawBoard(board)\n  print \"Peg %X jumped over %X to land on %X\\n\" % (peg,over,land)\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\n\npublic class IQPuzzle {\n\n    public static void main(String[] args) {\n        System.out.printf(\"  \");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"  %,6d\", start);\n        }\n        System.out.printf(\"%n\");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"%2d\", start);\n            Map<Integer,Integer> solutions = solve(start);    \n            for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {\n                System.out.printf(\"  %,6d\", solutions.containsKey(end) ? solutions.get(end) : 0);\n            }\n            System.out.printf(\"%n\");\n        }\n        int moveNum = 0;\n        System.out.printf(\"%nOne Solution:%n\");\n        for ( Move m : oneSolution ) {\n            moveNum++;\n            System.out.printf(\"Move %d = %s%n\", moveNum, m);\n        }\n    }\n    \n    private static List<Move> oneSolution = null;\n    \n    private static Map<Integer, Integer> solve(int emptyPeg) {\n        Puzzle puzzle = new Puzzle(emptyPeg);\n        Map<Integer,Integer> solutions = new HashMap<>();\n        Stack<Puzzle> stack = new Stack<Puzzle>();\n        stack.push(puzzle);\n        while ( ! stack.isEmpty() ) {\n            Puzzle p = stack.pop();\n            if ( p.solved() ) {\n                solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);\n                if ( oneSolution == null ) {\n                    oneSolution = p.moves;\n                }\n                continue;\n            }\n            for ( Move move : p.getValidMoves() ) {\n                Puzzle pMove = p.move(move);\n                stack.add(pMove);\n            }\n        }\n        \n        return solutions;\n    }\n    \n    private static class Puzzle {\n        \n        public static int MAX_PEGS = 16;\n        private boolean[] pegs = new boolean[MAX_PEGS];  \n        \n        private List<Move> moves;\n\n        public Puzzle(int emptyPeg) {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            pegs[emptyPeg] = false;\n            moves = new ArrayList<>();\n        }\n\n        public Puzzle() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            moves = new ArrayList<>();\n        }\n\n        private static Map<Integer,List<Move>> validMoves = new HashMap<>(); \n        static {\n            validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));\n            validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));\n            validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));\n            validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));\n            validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));\n            validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));\n            validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));\n            validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));\n            validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));\n            validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));\n            validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));\n            validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));\n            validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));\n            validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));\n            validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));\n        }\n        \n        public List<Move> getValidMoves() {\n            List<Move> moves = new ArrayList<Move>();\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    for ( Move testMove : validMoves.get(i) ) {\n                        if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {\n                            moves.add(testMove);\n                        }\n                    }\n                }\n            }\n            return moves;\n        }\n\n        public boolean solved() {\n            boolean foundFirstPeg = false;\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    if ( foundFirstPeg ) {\n                        return false;\n                    }\n                    foundFirstPeg = true;\n                }\n            }\n            return true;\n        }\n        \n        public Puzzle move(Move move) {\n            Puzzle p = new Puzzle();\n            if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {\n                throw new RuntimeException(\"Invalid move.\");\n            }\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                p.pegs[i] = pegs[i];\n            }\n            p.pegs[move.start] = false;\n            p.pegs[move.jump] = false;\n            p.pegs[move.end] = true;\n            for ( Move m : moves ) {\n                p.moves.add(new Move(m.start, m.jump, m.end));\n            }\n            p.moves.add(new Move(move.start, move.jump, move.end));\n            return p;\n        }\n        \n        public int getLastPeg() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    return i;\n                }\n            }\n            throw new RuntimeException(\"ERROR:  Illegal position.\");\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"[\");\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                sb.append(pegs[i] ? 1 : 0);\n                sb.append(\",\");\n            }\n            sb.setLength(sb.length()-1);            \n            sb.append(\"]\");\n            return sb.toString();\n        }\n    }\n    \n    private static class Move {\n        int start;\n        int jump;\n        int end;\n        \n        public Move(int s, int j, int e) {\n            start = s; jump = j; end = e;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"{\");\n            sb.append(\"s=\" + start);\n            sb.append(\", j=\" + jump);\n            sb.append(\", e=\" + end);\n            sb.append(\"}\");\n            return sb.toString();\n        }\n    }\n\n}\n"}
{"id": 54216, "name": "Non-transitive dice", "Python": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n    dice = list(cmbr(faces, n))\n \n    succ = [set(j for j, b in enumerate(dice)\n                    if sum((x>y) - (x<y) for x in a for y in b) > 0)\n                for a in dice]\n \n    def loops(seq):\n        s = succ[seq[-1]]\n\n        if len(seq) == m:\n            if seq[0] in s: yield seq\n            return\n\n        for d in (x for x in s if x > seq[0] and not x in seq):\n            yield from loops(seq + (d,))\n \n    yield from (tuple(''.join(dice[s]) for s in x)\n                    for i, v in enumerate(succ)\n                    for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n    print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n    t, t0 = time(), t\n    print(f'\\ttime: {t - t0:.4f} seconds\\n')\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n    private static List<List<Integer>> fourFaceCombos() {\n        List<List<Integer>> res = new ArrayList<>();\n        Set<Integer> found = new HashSet<>();\n\n        for (int i = 1; i <= 4; i++) {\n            for (int j = 1; j <= 4; j++) {\n                for (int k = 1; k <= 4; k++) {\n                    for (int l = 1; l <= 4; l++) {\n                        List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());\n\n                        int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);\n                        if (found.add(key)) {\n                            res.add(c);\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static int cmp(List<Integer> x, List<Integer> y) {\n        int xw = 0;\n        int yw = 0;\n        for (int i = 0; i < 4; i++) {\n            for (int j = 0; j < 4; j++) {\n                if (x.get(i) > y.get(j)) {\n                    xw++;\n                } else if (x.get(i) < y.get(j)) {\n                    yw++;\n                }\n            }\n        }\n        return Integer.compare(xw, yw);\n    }\n\n    private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (List<Integer> kl : cs) {\n                        if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {\n                            res.add(List.of(cs.get(i), cs.get(j), kl));\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (int k = 0; k < cs.size(); k++) {\n                        if (cmp(cs.get(j), cs.get(k)) == -1) {\n                            for (List<Integer> ll : cs) {\n                                if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {\n                                    res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> combos = fourFaceCombos();\n        System.out.printf(\"Number of eligible 4-faced dice: %d%n\", combos.size());\n        System.out.println();\n\n        List<List<List<Integer>>> it3 = findIntransitive3(combos);\n        System.out.printf(\"%d ordered lists of 3 non-transitive dice found, namely:%n\", it3.size());\n        for (List<List<Integer>> a : it3) {\n            System.out.println(a);\n        }\n        System.out.println();\n\n        List<List<List<Integer>>> it4 = findIntransitive4(combos);\n        System.out.printf(\"%d ordered lists of 4 non-transitive dice found, namely:%n\", it4.size());\n        for (List<List<Integer>> a : it4) {\n            System.out.println(a);\n        }\n    }\n}\n"}
{"id": 54217, "name": "History variables", "Python": "import sys\n\nHIST = {}\n\ndef trace(frame, event, arg):\n    for name,val in frame.f_locals.items():\n        if name not in HIST:\n            HIST[name] = []\n        else:\n            if HIST[name][-1] is val:\n                continue\n        HIST[name].append(val)\n    return trace\n\ndef undo(name):\n    HIST[name].pop(-1)\n    return HIST[name][-1]\n\ndef main():\n    a = 10\n    a = 20\n\n    for i in range(5):\n        c = i\n\n    print \"c:\", c, \"-> undo x3 ->\",\n    c = undo('c')\n    c = undo('c')\n    c = undo('c')\n    print c\n    print 'HIST:', HIST\n\nsys.settrace(trace)\nmain()\n", "Java": "public class HistoryVariable\n{\n    private Object value;\n\n    public HistoryVariable(Object v)\n    {\n        value = v;\n    }\n\n    public void update(Object v)\n    {\n        value = v;\n    }\n\n    public Object undo()\n    {\n        return value;\n    }\n\n    @Override\n    public String toString()\n    {\n        return value.toString();\n    }\n\n    public void dispose()\n    {\n    }\n}\n"}
{"id": 54218, "name": "Perceptron", "Python": "import random\n\nTRAINING_LENGTH = 2000\n\nclass Perceptron:\n    \n    def __init__(self,n):\n        self.c = .01\n        self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)]\n\n    def feed_forward(self, inputs):\n        vars = []\n        for i in range(len(inputs)):\n            vars.append(inputs[i] * self.weights[i])\n        return self.activate(sum(vars))\n\n    def activate(self, value):\n        return 1 if value > 0 else -1\n\n    def train(self, inputs, desired):\n        guess = self.feed_forward(inputs)\n        error = desired - guess\n        for i in range(len(inputs)):\n            self.weights[i] += self.c * error * inputs[i]\n        \nclass Trainer():\n    \n    def __init__(self, x, y, a):\n        self.inputs = [x, y, 1]\n        self.answer = a\n\ndef F(x):\n    return 2 * x + 1\n\nif __name__ == \"__main__\":\n    ptron = Perceptron(3)\n    training = []\n    for i in range(TRAINING_LENGTH):\n        x = random.uniform(-10,10)\n        y = random.uniform(-10,10)\n        answer = 1\n        if y < F(x): answer = -1\n        training.append(Trainer(x,y,answer))\n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Untrained')\n    for row in result:\n        print(''.join(v for v in row))\n\n    for t in training:\n        ptron.train(t.inputs, t.answer)\n    \n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Trained')\n    for row in result:\n        print(''.join(v for v in row))\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.util.*;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class Perceptron extends JPanel {\n\n    class Trainer {\n        double[] inputs;\n        int answer;\n\n        Trainer(double x, double y, int a) {\n            inputs = new double[]{x, y, 1};\n            answer = a;\n        }\n    }\n\n    Trainer[] training = new Trainer[2000];\n    double[] weights;\n    double c = 0.00001;\n    int count;\n\n    public Perceptron(int n) {\n        Random r = new Random();\n        Dimension dim = new Dimension(640, 360);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        weights = new double[n];\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] = r.nextDouble() * 2 - 1;\n        }\n\n        for (int i = 0; i < training.length; i++) {\n            double x = r.nextDouble() * dim.width;\n            double y = r.nextDouble() * dim.height;\n\n            int answer = y < f(x) ? -1 : 1;\n\n            training[i] = new Trainer(x, y, answer);\n        }\n\n        new Timer(10, (ActionEvent e) -> {\n            repaint();\n        }).start();\n    }\n\n    private double f(double x) {\n        return x * 0.7 + 40;\n    }\n\n    int feedForward(double[] inputs) {\n        assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n        double sum = 0;\n        for (int i = 0; i < weights.length; i++) {\n            sum += inputs[i] * weights[i];\n        }\n        return activate(sum);\n    }\n\n    int activate(double s) {\n        return s > 0 ? 1 : -1;\n    }\n\n    void train(double[] inputs, int desired) {\n        int guess = feedForward(inputs);\n        double error = desired - guess;\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] += c * error * inputs[i];\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        \n        int x = getWidth();\n        int y = (int) f(x);\n        g.setStroke(new BasicStroke(2));\n        g.setColor(Color.orange);\n        g.drawLine(0, (int) f(0), x, y);\n\n        train(training[count].inputs, training[count].answer);\n        count = (count + 1) % training.length;\n\n        g.setStroke(new BasicStroke(1));\n        g.setColor(Color.black);\n        for (int i = 0; i < count; i++) {\n            int guess = feedForward(training[i].inputs);\n\n            x = (int) training[i].inputs[0] - 4;\n            y = (int) training[i].inputs[1] - 4;\n\n            if (guess > 0)\n                g.drawOval(x, y, 8, 8);\n            else\n                g.fillOval(x, y, 8, 8);\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(\"Perceptron\");\n            f.setResizable(false);\n            f.add(new Perceptron(3), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 54219, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 54220, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 54221, "name": "Pisano period", "Python": "from sympy import isprime, lcm, factorint, primerange\nfrom functools import reduce\n\n\ndef pisano1(m):\n    \"Simple definition\"\n    if m < 2:\n        return 1\n    lastn, n = 0, 1\n    for i in range(m ** 2):\n        lastn, n = n, (lastn + n) % m\n        if lastn == 0 and n == 1:\n            return i + 1\n    return 1\n\ndef pisanoprime(p, k):\n    \"Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1\"\n    assert isprime(p) and k > 0\n    return p ** (k - 1) * pisano1(p)\n\ndef pisano_mult(m, n):\n    \"pisano(m*n) where m and n assumed coprime integers\"\n    return lcm(pisano1(m), pisano1(n))\n\ndef pisano2(m):\n    \"Uses prime factorization of m\"\n    return reduce(lcm, (pisanoprime(prime, mult)\n                        for prime, mult in factorint(m).items()), 1)\n\n\nif __name__ == '__main__':\n    for n in range(1, 181):\n        assert pisano1(n) == pisano2(n), \"Wall-Sun-Sun prime exists??!!\"\n    print(\"\\nPisano period (p, 2) for primes less than 50\\n \",\n          [pisanoprime(prime, 2) for prime in primerange(1, 50)])\n    print(\"\\nPisano period (p, 1) for primes less than 180\\n \",\n          [pisanoprime(prime, 1) for prime in primerange(1, 180)])\n    print(\"\\nPisano period (p) for integers 1 to 180\")\n    for i in range(1, 181):\n        print(\" %3d\" % pisano2(i), end=\"\" if i % 10 else \"\\n\")\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class PisanoPeriod {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Print pisano(p^2) for every prime p lower than 15%n\");\n        for ( long i = 2 ; i < 15 ; i++ ) { \n            if ( isPrime(i) ) {\n                long n = i*i; \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(p) for every prime p lower than 180%n\");\n        for ( long n = 2 ; n < 180 ; n++ ) { \n            if ( isPrime(n) ) { \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(n) for every integer from 1 to 180%n\");\n        for ( long n = 1 ; n <= 180 ; n++ ) { \n            System.out.printf(\"%3d  \", pisano(n));\n            if ( n % 10 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n\n        \n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\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    \n    private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();\n    static {\n        PERIOD_MEMO.put(2L, 3L);\n        PERIOD_MEMO.put(3L, 8L);\n        PERIOD_MEMO.put(5L, 20L);        \n    }\n    \n    \n    private static long pisano(long n) {\n        if ( PERIOD_MEMO.containsKey(n) ) {\n            return PERIOD_MEMO.get(n);\n        }\n        if ( n == 1 ) {\n            return 1;\n        }\n        Map<Long,Long> factors = getFactors(n);\n        \n        \n        \n        if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {\n            long result = 3 * n / 2;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 4*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 6*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        List<Long> primes = new ArrayList<>(factors.keySet());\n        long prime = primes.get(0);\n        if ( factors.size() == 1 && factors.get(prime) == 1 ) {\n            List<Long> divisors = new ArrayList<>();\n            if ( n % 10 == 1 || n % 10 == 9 ) {\n                for ( long divisor : getDivisors(prime-1) ) {\n                    if ( divisor % 2 == 0 ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            else {\n                List<Long> pPlus1Divisors = getDivisors(prime+1);\n                for ( long divisor : getDivisors(2*prime+2) ) {\n                    if ( !  pPlus1Divisors.contains(divisor) ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            Collections.sort(divisors);\n            for ( long divisor : divisors ) {\n                if ( fibModIdentity(divisor, prime) ) {\n                    PERIOD_MEMO.put(prime, divisor);\n                    return divisor;\n                }\n            }\n            throw new RuntimeException(\"ERROR 144: Divisor not found.\");\n        }\n        long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);\n        for ( int i = 1 ; i < primes.size() ; i++ ) {\n            prime = primes.get(i);\n            period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));\n        }\n        PERIOD_MEMO.put(n, period);\n        return period;\n    }\n    \n    \n    private static boolean fibModIdentity(long n, long mod) {\n        long aRes = 0;\n        long bRes = 1;\n        long cRes = 1;\n        long aBase = 0;\n        long bBase = 1;\n        long cBase = 1;\n        while ( n > 0 ) {\n            if ( n % 2 == 1 ) {\n                long temp1 = 0, temp2 = 0, temp3 = 0;\n                if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {\n                    temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;\n                    temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;\n                    temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;\n                }\n                else {\n                    temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;\n                    temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;\n                    temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;\n                }\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            n >>= 1L;\n            long temp1 = 0, temp2 = 0, temp3 = 0; \n            if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {\n                temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;\n                temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;\n                temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;\n            }\n            else {\n                temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;\n                temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;\n                temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;\n            }\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;\n    }\n\n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        \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        \n        return x % modulus;\n    }\n\n    private static final List<Long> getDivisors(long number) {\n        List<Long> divisors = new ArrayList<>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                long div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n    public static long lcm(long a, long b) {\n        return a*b/gcd(a,b);\n    }\n\n    public 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 final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();\n    static {\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        factors.put(2L, 1L);\n        allFactors.put(2L, factors);\n    }\n\n    public static Long MAX_ALL_FACTORS = 100000L;\n\n    public static final Map<Long,Long> getFactors(Long number) {\n        if ( allFactors.containsKey(number) ) {\n            return allFactors.get(number);\n        }\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        if ( number % 2 == 0 ) {\n            Map<Long,Long> factorsdDivTwo = getFactors(number/2);\n            factors.putAll(factorsdDivTwo);\n            factors.merge(2L, 1L, (v1, v2) -> v1 + v2);\n            if ( number < MAX_ALL_FACTORS ) {\n                allFactors.put(number, factors);\n            }\n            return factors;\n        }\n        boolean prime = true;\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 3 ; i <= sqrt ; i += 2 ) {\n            if ( number % i == 0 ) {\n                prime = false;\n                factors.putAll(getFactors(number/i));\n                factors.merge(i, 1L, (v1, v2) -> v1 + v2);\n                if ( number < MAX_ALL_FACTORS ) {\n                    allFactors.put(number, factors);\n                }\n                return factors;\n            }\n        }\n        if ( prime ) {\n            factors.put(number, 1L);\n            if ( number < MAX_ALL_FACTORS ) { \n                allFactors.put(number, factors);\n            }\n        }\n        return factors;\n    }\n\n}\n"}
{"id": 54222, "name": "Railway circuit", "Python": "from itertools import count, islice\nimport numpy as np\nfrom numpy import sin, cos, pi\n\n\nANGDIV = 12\nANG = 2*pi/ANGDIV\n\ndef draw_all(sols):\n    import matplotlib.pyplot as plt\n\n    def draw_track(ax, s):\n        turn, xend, yend = 0, [0], [0]\n\n        for d in s:\n            x0, y0 = xend[-1], yend[-1]\n            a = turn*ANG\n            cs, sn = cos(a), sin(a)\n            ang = a + d*pi/2\n            cx, cy = x0 + cos(ang), y0 + sin(ang)\n\n            da = np.linspace(ang, ang + d*ANG, 10)\n            xs = cx - cos(da)\n            ys = cy - sin(da)\n            ax.plot(xs, ys, 'green' if d == -1 else 'orange')\n\n            xend.append(xs[-1])\n            yend.append(ys[-1])\n            turn += d\n\n        ax.plot(xend, yend, 'k.', markersize=1)\n        ax.set_aspect(1)\n\n    ls = len(sols)\n    if ls == 0: return\n\n    w, h = min((abs(w*2 - h*3) + w*h - ls, w, h)\n        for w, h in ((w, (ls + w - 1)//w)\n            for w in range(1, ls + 1)))[1:]\n\n    fig, ax = plt.subplots(h, w, squeeze=False)\n    for a in ax.ravel(): a.set_axis_off()\n\n    for i, s in enumerate(sols):\n        draw_track(ax[i//w, i%w], s)\n\n    plt.show()\n\n\ndef match_up(this, that, equal_lr, seen):\n    if not this or not that: return\n\n    n = len(this[0][-1])\n    n2 = n*2\n\n    l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0\n\n    def record(m):\n        for _ in range(n2):\n            seen[m] = True\n            m = (m&1) << (n2 - 1) | (m >> 1)\n\n        if equal_lr:\n            m ^= (1<<n2) - 1\n            for _ in range(n2):\n                seen[m] = True\n                m = (m&1) << (n2 - 1) | (m >> 1)\n\n    l_n, r_n = len(this), len(that)\n    tol = 1e-3\n\n    while l_lo < l_n:\n        while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol:\n            l_hi += 1\n\n        while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol:\n            r_lo += 1\n\n        r_hi = r_lo\n        while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol:\n            r_hi += 1\n\n        for a in this[l_lo:l_hi]:\n            m_left = a[-2]<<n\n            for b in that[r_lo:r_hi]:\n                if (m := m_left | b[-2]) not in seen:\n                    if np.abs(a[1] + b[2]) < tol:\n                        record(m)\n                        record(int(f'{m:b}'[::-1], base=2))\n                        yield(a[-1] + b[-1])\n\n        l_lo, r_lo = l_hi, r_hi\n\ndef track_combo(left, right):\n    n = (left + right)//2\n    n1 = left + right - n\n\n    alphas = np.exp(1j*ANG*np.arange(ANGDIV))\n    def half_track(m, n):\n        turns = tuple(1 - 2*(m>>i & 1) for i in range(n))\n        rcnt = np.cumsum(turns)%ANGDIV\n        asum = np.sum(alphas[rcnt])\n        want = asum/alphas[rcnt[-1]]\n        return np.abs(asum), asum, want, m, turns\n\n    res = [[] for _ in range(right + 1)]\n    for i in range(1<<n):\n        b = i.bit_count()\n        if b <= right:\n            res[b].append(half_track(i, n))\n\n    for v in res: v.sort()\n    if n1 == n:\n        return res, res\n\n    res1 = [[] for _ in range(right + 1)]\n    for i in range(1<<n1):\n        b = i.bit_count()\n        if b <= right:\n            res1[b].append(half_track(i, n1))\n\n    for v in res: v.sort()\n    return res, res1\n\ndef railway(n):\n    seen = {}\n\n    for l in range(n//2, n + 1):\n        r = n - l\n        if not l >= r: continue\n\n        if (l - r)%ANGDIV == 0:\n            res_l, res_r = track_combo(l, r)\n\n            for i, this in enumerate(res_l):\n                if 2*i < r: continue\n                that = res_r[r - i]\n                for s in match_up(this, that, l == r, seen):\n                    yield s\n\nsols = []\nfor i, s in enumerate(railway(30)):\n    \n    print(i + 1, s)\n    sols.append(s)\n\ndraw_all(sols[:40])\n", "Java": "package railwaycircuit;\n\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.IntStream.range;\n\npublic class RailwayCircuit {\n    final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0;\n\n    static String normalize(int[] tracks) {\n        char[] a = new char[tracks.length];\n        for (int i = 0; i < a.length; i++)\n            a[i] = \"abc\".charAt(tracks[i] + 1);\n\n        \n        String norm = new String(a);\n        for (int i = 0, len = a.length; i < len; i++) {\n\n            String s = new String(a);\n            if (s.compareTo(norm) < 0)\n                norm = s;\n\n            char tmp = a[0];\n            for (int j = 1; j < a.length; j++)\n                a[j - 1] = a[j];\n            a[len - 1] = tmp;\n        }\n        return norm;\n    }\n\n    static boolean fullCircleStraight(int[] tracks, int nStraight) {\n        if (nStraight == 0)\n            return true;\n\n        \n        if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight)\n            return false;\n\n        \n        int[] straight = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == STRAIGHT)\n                straight[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6])\n                && range(0, 8).anyMatch(i -> straight[i] != straight[i + 4]));\n    }\n\n    static boolean fullCircleRight(int[] tracks) {\n\n        \n        if (stream(tracks).map(i -> i * 30).sum() % 360 != 0)\n            return false;\n\n        \n        int[] rTurns = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == RIGHT)\n                rTurns[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6])\n                && range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4]));\n    }\n\n    static void circuits(int nCurved, int nStraight) {\n        Map<String, int[]> solutions = new HashMap<>();\n\n        PermutationsGen gen = getPermutationsGen(nCurved, nStraight);\n        while (gen.hasNext()) {\n\n            int[] tracks = gen.next();\n\n            if (!fullCircleStraight(tracks, nStraight))\n                continue;\n\n            if (!fullCircleRight(tracks))\n                continue;\n\n            solutions.put(normalize(tracks), tracks.clone());\n        }\n        report(solutions, nCurved, nStraight);\n    }\n\n    static PermutationsGen getPermutationsGen(int nCurved, int nStraight) {\n        assert (nCurved + nStraight - 12) % 4 == 0 : \"input must be 12 + k * 4\";\n\n        int[] trackTypes = new int[]{RIGHT, LEFT};\n\n        if (nStraight != 0) {\n            if (nCurved == 12)\n                trackTypes = new int[]{RIGHT, STRAIGHT};\n            else\n                trackTypes = new int[]{RIGHT, LEFT, STRAIGHT};\n        }\n\n        return new PermutationsGen(nCurved + nStraight, trackTypes);\n    }\n\n    static void report(Map<String, int[]> sol, int numC, int numS) {\n\n        int size = sol.size();\n        System.out.printf(\"%n%d solution(s) for C%d,%d %n\", size, numC, numS);\n\n        if (size < 10)\n            sol.values().stream().forEach(tracks -> {\n                stream(tracks).forEach(i -> System.out.printf(\"%2d \", i));\n                System.out.println();\n            });\n    }\n\n    public static void main(String[] args) {\n        circuits(12, 0);\n        circuits(16, 0);\n        circuits(20, 0);\n        circuits(24, 0);\n        circuits(12, 4);\n    }\n}\n\nclass PermutationsGen {\n    \n    private int[] indices;\n    private int[] choices;\n    private int[] sequence;\n    private int carry;\n\n    PermutationsGen(int numPositions, int[] choices) {\n        indices = new int[numPositions];\n        sequence = new int[numPositions];\n        this.choices = choices;\n    }\n\n    int[] next() {\n        carry = 1;\n        \n        for (int i = 1; i < indices.length && carry > 0; i++) {\n            indices[i] += carry;\n            carry = 0;\n\n            if (indices[i] == choices.length) {\n                carry = 1;\n                indices[i] = 0;\n            }\n        }\n\n        for (int i = 0; i < indices.length; i++)\n            sequence[i] = choices[indices[i]];\n\n        return sequence;\n    }\n\n    boolean hasNext() {\n        return carry != 1;\n    }\n}\n"}
{"id": 54223, "name": "Distance and Bearing", "Python": "\n\nfrom math import radians, degrees, sin, cos, asin, atan2, sqrt\nfrom pandas import read_csv\n\n\nEARTH_RADIUS_KM = 6372.8\nTASK_CONVERT_NM =  0.0094174\nAIRPORT_DATA_FILE = 'airports.dat.txt'\n\nQUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n    \n    rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]\n    dlat = rlat2 - rlat1\n    dlon = rlon2 - rlon1\n    arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2\n    clen = 2.0 * degrees(asin(sqrt(arc)))\n    theta = atan2(sin(dlon) * cos(rlat2),\n                  cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))\n    theta = (degrees(theta) + 360) % 360\n    return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta\n\n\ndef find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):\n    \n    airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[\n                        'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])\n    airports['Distance'] = 0.0\n    airports['Bearing'] = 0\n    for (idx, row) in enumerate(airports.itertuples()):\n        distance, bearing = haversine(\n            latitude, longitude, row.Latitude, row.Longitude)\n        airports.at[idx, 'Distance'] = round(distance, ndigits=1)\n        airports.at[idx, 'Bearing'] = int(round(bearing))\n\n    airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)\n    return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]\n\n\nprint(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))\n", "Java": "\npackage distanceAndBearing;\npublic class Airport {\n\tprivate String airport;\n\tprivate String country;\n\tprivate String icao;\n\tprivate double lat;\n\tprivate double lon;\n\tpublic String getAirportName() {\treturn this.airport;\t}\n\tpublic void setAirportName(String airport) {\tthis.airport = airport; }\n\tpublic String getCountry() {\treturn this.country;\t}\n\tpublic void setCountry(String country) {\tthis.country = country;\t}\n\tpublic String getIcao() { return this.icao; }\n\tpublic void setIcao(String icao) { this.icao = icao;\t}\n\tpublic double getLat() {\treturn this.lat; }\n\tpublic void setLat(double lat) {\tthis.lat = lat;\t}\n\tpublic double getLon() {\treturn this.lon; }\n\tpublic void setLon(double lon) {\tthis.lon = lon;\t}\n\t@Override\n\tpublic String toString() {return \"Airport: \" + getAirportName() + \": ICAO: \" + getIcao();}\n}\n\n\npackage distanceAndBearing;\nimport java.io.File;\nimport java.text.DecimalFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.stream.Collectors;\npublic class DistanceAndBearing {\n\tprivate final double earthRadius = 6371;\n\tprivate File datFile;\n\tprivate List<Airport> airports;\n\tpublic DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }\n\tpublic boolean readFile(String filename) {\n\t\tthis.datFile = new File(filename);\n\t\ttry {\n\t\t\tScanner fileScanner = new Scanner(datFile);\n\t\t\tString line;\n\t\t\twhile (fileScanner.hasNextLine()) {\n\t\t\t\tline = fileScanner.nextLine();\n\t\t\t\tline = line.replace(\", \", \"; \"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tline = line.replace(\",\\\",\\\"\", \"\\\",\\\"\"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tString[] parts = line.split(\",\");\n\t\t\t\tAirport airport = new Airport();\n\t\t\t\tairport.setAirportName(parts[1].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setCountry(parts[3].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setIcao(parts[5].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setLat(Double.valueOf(parts[6]));\n\t\t\t\tairport.setLon(Double.valueOf(parts[7]));\n\t\t\t\tthis.airports.add(airport);\n\t\t\t}\n\t\t\tfileScanner.close();\n\t\t\treturn true; \n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false; \n\t\t}}\n\tpublic double[] calculate(double lat1, double lon1, double lat2, double lon2) {\n\t\tdouble[] results = new double[2];\n\t\tdouble dLat = Math.toRadians(lat2 - lat1);\n\t\tdouble dLon = Math.toRadians(lon2 - lon1);\n\t\tdouble rlat1 = Math.toRadians(lat1);\n\t\tdouble rlat2 = Math.toRadians(lat2);\n\t\tdouble a = Math.pow(Math.sin(dLat / 2), 2)\n\t\t\t\t+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);\n\t\tdouble c = 2 * Math.asin(Math.sqrt(a));\n\t\tdouble distance = earthRadius * c;\n\t\tDecimalFormat df = new DecimalFormat(\"#0.00\");\n\t\tdistance = Double.valueOf(df.format(distance));\n\t\tresults[0] = distance;\n\t\tdouble X = Math.cos(rlat2) * Math.sin(dLon);\n\t\tdouble Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);\n\t\tdouble heading = Math.atan2(X, Y);\n\t\theading = Math.toDegrees(heading);\n\t\tresults[1] = heading;\n\t\treturn results;\n\t}\n\tpublic Airport searchByName(final String name) {\n\t\tAirport airport = new Airport();\n\t\tList<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))\n\t\t\t\t.collect(Collectors.toList());\n\t\tairport = results.get(0);\n\t\treturn airport;\n\t}\n\tpublic List<Airport> findClosestAirports(double lat, double lon) {\n\t\t\n\t\tMap<Double, Airport> airportDistances = new HashMap<>();\n\t\tMap<Double, Airport> airportHeading = new HashMap<>();\n\t\tList<Airport> closestAirports = new ArrayList<Airport>();\n\t\t\n\t\t\n\t\tfor (Airport ap : this.airports) {\n\t\t\tdouble[] result = calculate(lat, lon, ap.getLat(), ap.getLon());\n\t\t\tairportDistances.put(result[0], ap);\n\t\t\tairportHeading.put(result[1], ap);\n\t\t}\n\t\t\n\t\tArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());\n\t\tCollections.sort(distances);\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tfor (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}\n\t\t\n\t\tMap<String, Double> distanceMap = new HashMap<>();\n\t\tfor (Double d : airportDistances.keySet()) {\tdistanceMap.put(airportDistances.get(d).getAirportName(), d);}\n\t\tMap<String, Double> headingMap = new HashMap<>();\n\t\tfor (Double d : airportHeading.keySet()) { \n            double d2 = d;\n            if(d2<0){d2+=360'}\n            headingMap.put(airportHeading.get(d).getAirportName(), d2); }\n\n\t\t\n\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12s %15s\\n\", \"Num\", \"Airport\", \"Country\", \"ICAO\", \"Distance\", \"Bearing\");\n\t\tSystem.out.println(\"-----------------------------------------------------------------------------------------------------------\");\n\t\tint i = 0;\n\t\tfor (Airport a : closestAirports) {\n\t\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12.1f %15.0f\\n\", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));\n\t\t}\n\t\treturn closestAirports;\n\t}\n}\n"}
{"id": 54224, "name": "Distance and Bearing", "Python": "\n\nfrom math import radians, degrees, sin, cos, asin, atan2, sqrt\nfrom pandas import read_csv\n\n\nEARTH_RADIUS_KM = 6372.8\nTASK_CONVERT_NM =  0.0094174\nAIRPORT_DATA_FILE = 'airports.dat.txt'\n\nQUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n    \n    rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]\n    dlat = rlat2 - rlat1\n    dlon = rlon2 - rlon1\n    arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2\n    clen = 2.0 * degrees(asin(sqrt(arc)))\n    theta = atan2(sin(dlon) * cos(rlat2),\n                  cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))\n    theta = (degrees(theta) + 360) % 360\n    return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta\n\n\ndef find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):\n    \n    airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[\n                        'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])\n    airports['Distance'] = 0.0\n    airports['Bearing'] = 0\n    for (idx, row) in enumerate(airports.itertuples()):\n        distance, bearing = haversine(\n            latitude, longitude, row.Latitude, row.Longitude)\n        airports.at[idx, 'Distance'] = round(distance, ndigits=1)\n        airports.at[idx, 'Bearing'] = int(round(bearing))\n\n    airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)\n    return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]\n\n\nprint(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))\n", "Java": "\npackage distanceAndBearing;\npublic class Airport {\n\tprivate String airport;\n\tprivate String country;\n\tprivate String icao;\n\tprivate double lat;\n\tprivate double lon;\n\tpublic String getAirportName() {\treturn this.airport;\t}\n\tpublic void setAirportName(String airport) {\tthis.airport = airport; }\n\tpublic String getCountry() {\treturn this.country;\t}\n\tpublic void setCountry(String country) {\tthis.country = country;\t}\n\tpublic String getIcao() { return this.icao; }\n\tpublic void setIcao(String icao) { this.icao = icao;\t}\n\tpublic double getLat() {\treturn this.lat; }\n\tpublic void setLat(double lat) {\tthis.lat = lat;\t}\n\tpublic double getLon() {\treturn this.lon; }\n\tpublic void setLon(double lon) {\tthis.lon = lon;\t}\n\t@Override\n\tpublic String toString() {return \"Airport: \" + getAirportName() + \": ICAO: \" + getIcao();}\n}\n\n\npackage distanceAndBearing;\nimport java.io.File;\nimport java.text.DecimalFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.stream.Collectors;\npublic class DistanceAndBearing {\n\tprivate final double earthRadius = 6371;\n\tprivate File datFile;\n\tprivate List<Airport> airports;\n\tpublic DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }\n\tpublic boolean readFile(String filename) {\n\t\tthis.datFile = new File(filename);\n\t\ttry {\n\t\t\tScanner fileScanner = new Scanner(datFile);\n\t\t\tString line;\n\t\t\twhile (fileScanner.hasNextLine()) {\n\t\t\t\tline = fileScanner.nextLine();\n\t\t\t\tline = line.replace(\", \", \"; \"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tline = line.replace(\",\\\",\\\"\", \"\\\",\\\"\"); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tString[] parts = line.split(\",\");\n\t\t\t\tAirport airport = new Airport();\n\t\t\t\tairport.setAirportName(parts[1].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setCountry(parts[3].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setIcao(parts[5].replace(\"\\\"\", \"\")); \n\t\t\t\tairport.setLat(Double.valueOf(parts[6]));\n\t\t\t\tairport.setLon(Double.valueOf(parts[7]));\n\t\t\t\tthis.airports.add(airport);\n\t\t\t}\n\t\t\tfileScanner.close();\n\t\t\treturn true; \n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false; \n\t\t}}\n\tpublic double[] calculate(double lat1, double lon1, double lat2, double lon2) {\n\t\tdouble[] results = new double[2];\n\t\tdouble dLat = Math.toRadians(lat2 - lat1);\n\t\tdouble dLon = Math.toRadians(lon2 - lon1);\n\t\tdouble rlat1 = Math.toRadians(lat1);\n\t\tdouble rlat2 = Math.toRadians(lat2);\n\t\tdouble a = Math.pow(Math.sin(dLat / 2), 2)\n\t\t\t\t+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);\n\t\tdouble c = 2 * Math.asin(Math.sqrt(a));\n\t\tdouble distance = earthRadius * c;\n\t\tDecimalFormat df = new DecimalFormat(\"#0.00\");\n\t\tdistance = Double.valueOf(df.format(distance));\n\t\tresults[0] = distance;\n\t\tdouble X = Math.cos(rlat2) * Math.sin(dLon);\n\t\tdouble Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);\n\t\tdouble heading = Math.atan2(X, Y);\n\t\theading = Math.toDegrees(heading);\n\t\tresults[1] = heading;\n\t\treturn results;\n\t}\n\tpublic Airport searchByName(final String name) {\n\t\tAirport airport = new Airport();\n\t\tList<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))\n\t\t\t\t.collect(Collectors.toList());\n\t\tairport = results.get(0);\n\t\treturn airport;\n\t}\n\tpublic List<Airport> findClosestAirports(double lat, double lon) {\n\t\t\n\t\tMap<Double, Airport> airportDistances = new HashMap<>();\n\t\tMap<Double, Airport> airportHeading = new HashMap<>();\n\t\tList<Airport> closestAirports = new ArrayList<Airport>();\n\t\t\n\t\t\n\t\tfor (Airport ap : this.airports) {\n\t\t\tdouble[] result = calculate(lat, lon, ap.getLat(), ap.getLon());\n\t\t\tairportDistances.put(result[0], ap);\n\t\t\tairportHeading.put(result[1], ap);\n\t\t}\n\t\t\n\t\tArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());\n\t\tCollections.sort(distances);\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tfor (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}\n\t\t\n\t\tMap<String, Double> distanceMap = new HashMap<>();\n\t\tfor (Double d : airportDistances.keySet()) {\tdistanceMap.put(airportDistances.get(d).getAirportName(), d);}\n\t\tMap<String, Double> headingMap = new HashMap<>();\n\t\tfor (Double d : airportHeading.keySet()) { \n            double d2 = d;\n            if(d2<0){d2+=360'}\n            headingMap.put(airportHeading.get(d).getAirportName(), d2); }\n\n\t\t\n\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12s %15s\\n\", \"Num\", \"Airport\", \"Country\", \"ICAO\", \"Distance\", \"Bearing\");\n\t\tSystem.out.println(\"-----------------------------------------------------------------------------------------------------------\");\n\t\tint i = 0;\n\t\tfor (Airport a : closestAirports) {\n\t\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12.1f %15.0f\\n\", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));\n\t\t}\n\t\treturn closestAirports;\n\t}\n}\n"}
{"id": 54225, "name": "Free polyominoes enumeration", "Python": "from itertools import imap, imap, groupby, chain, imap\nfrom operator import itemgetter\nfrom sys import argv\nfrom array import array\n\ndef concat_map(func, it):\n    return list(chain.from_iterable(imap(func, it)))\n\ndef minima(poly):\n    \n    return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))\n\ndef translate_to_origin(poly):\n    (minx, miny) = minima(poly)\n    return [(x - minx, y - miny) for (x, y) in poly]\n\nrotate90   = lambda (x, y): ( y, -x)\nrotate180  = lambda (x, y): (-x, -y)\nrotate270  = lambda (x, y): (-y,  x)\nreflect    = lambda (x, y): (-x,  y)\n\ndef rotations_and_reflections(poly):\n    \n    return (poly,\n            map(rotate90, poly),\n            map(rotate180, poly),\n            map(rotate270, poly),\n            map(reflect, poly),\n            [reflect(rotate90(pt)) for pt in poly],\n            [reflect(rotate180(pt)) for pt in poly],\n            [reflect(rotate270(pt)) for pt in poly])\n\ndef canonical(poly):\n    return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly))\n\ndef unique(lst):\n    lst.sort()\n    return map(next, imap(itemgetter(1), groupby(lst)))\n\n\ncontiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]\n\ndef new_points(poly):\n    \n    return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly])\n\ndef new_polys(poly):\n    return unique([canonical(poly + [pt]) for pt in new_points(poly)])\n\nmonomino = [(0, 0)]\nmonominoes = [monomino]\n\ndef rank(n):\n    \n    assert n >= 0\n    if n == 0: return []\n    if n == 1: return monominoes\n    return unique(concat_map(new_polys, rank(n - 1)))\n\ndef text_representation(poly):\n    \n    min_pt = minima(poly)\n    max_pt = (max(p[0] for p in poly), max(p[1] for p in poly))\n    table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1)\n             for _ in xrange(max_pt[0] - min_pt[0] + 1)]\n    for pt in poly:\n        table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = '\n    return \"\\n\".join(row.tostring() for row in table)\n\ndef main():\n    print [len(rank(n)) for n in xrange(1, 11)]\n\n    n = int(argv[1]) if (len(argv) == 2) else 5\n    print \"\\nAll free polyominoes of rank %d:\" % n\n\n    for poly in rank(n):\n        print text_representation(poly), \"\\n\"\n\nmain()\n", "Java": "import java.awt.Point;\nimport java.util.*;\nimport static java.util.Arrays.asList;\nimport java.util.function.Function;\nimport static java.util.Comparator.comparing;\nimport static java.util.stream.Collectors.toList;\n\npublic class FreePolyominoesEnum {\n    static final List<Function<Point, Point>> transforms = new ArrayList<>();\n\n    static {\n        transforms.add(p -> new Point(p.y, -p.x));\n        transforms.add(p -> new Point(-p.x, -p.y));\n        transforms.add(p -> new Point(-p.y, p.x));\n        transforms.add(p -> new Point(-p.x, p.y));\n        transforms.add(p -> new Point(-p.y, -p.x));\n        transforms.add(p -> new Point(p.x, -p.y));\n        transforms.add(p -> new Point(p.y, p.x));\n    }\n\n    static Point findMinima(List<Point> poly) {\n        return new Point(\n                poly.stream().mapToInt(a -> a.x).min().getAsInt(),\n                poly.stream().mapToInt(a -> a.y).min().getAsInt());\n    }\n\n    static List<Point> translateToOrigin(List<Point> poly) {\n        final Point min = findMinima(poly);\n        poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));\n        return poly;\n    }\n\n    static List<List<Point>> rotationsAndReflections(List<Point> poly) {\n        List<List<Point>> lst = new ArrayList<>();\n        lst.add(poly);\n        for (Function<Point, Point> t : transforms)\n            lst.add(poly.stream().map(t).collect(toList()));\n        return lst;\n    }\n\n    static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)\n            .thenComparingInt(p -> p.y);\n\n    static List<Point> normalize(List<Point> poly) {\n        return rotationsAndReflections(poly).stream()\n                .map(lst -> translateToOrigin(lst))\n                .map(lst -> lst.stream().sorted(byCoords).collect(toList()))\n                .min(comparing(Object::toString)) \n                .get();\n    }\n\n    static List<Point> neighborhoods(Point p) {\n        return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),\n                new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));\n    }\n\n    static List<Point> concat(List<Point> lst, Point pt) {\n        List<Point> r = new ArrayList<>();\n        r.addAll(lst);\n        r.add(pt);\n        return r;\n    }\n\n    static List<Point> newPoints(List<Point> poly) {\n        return poly.stream()\n                .flatMap(p -> neighborhoods(p).stream())\n                .filter(p -> !poly.contains(p))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> constructNextRank(List<Point> poly) {\n        return newPoints(poly).stream()\n                .map(p -> normalize(concat(poly, p)))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> rank(int n) {\n        if (n < 0)\n            throw new IllegalArgumentException(\"n cannot be negative\");\n\n        if (n < 2) {\n            List<List<Point>> r = new ArrayList<>();\n            if (n == 1)\n                r.add(asList(new Point(0, 0)));\n            return r;\n        }\n\n        return rank(n - 1).stream()\n                .parallel()\n                .flatMap(lst -> constructNextRank(lst).stream())\n                .distinct()\n                .collect(toList());\n    }\n\n    public static void main(String[] args) {\n        for (List<Point> poly : rank(5)) {\n            for (Point p : poly)\n                System.out.printf(\"(%d,%d) \", p.x, p.y);\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 54226, "name": "Use a REST API", "Python": "\nimport requests\nimport json\n\ncity = None\ntopic = None\n\ndef getEvent(url_path, key) :\n    responseString = \"\"\n    \n    params = {'city':city, 'key':key,'topic':topic}\n    r = requests.get(url_path, params = params)    \n    print(r.url)    \n    responseString = r.text\n    return responseString\n\n\ndef getApiKey(key_path):\n    key = \"\"\n    f = open(key_path, 'r')\n    key = f.read()\n    return key\n\n\ndef submitEvent(url_path,params):\n    r = requests.post(url_path, data=json.dumps(params))        \n    print(r.text+\" : Event Submitted\")\n", "Java": "package src;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.net.URI;\n\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\n\n\n\npublic class EventGetter {\n\t\n\n\tString city = \"\";\n\tString topic = \"\";\n\t\n\tpublic String getEvent(String path_code,String key) throws Exception{\n\t\tString responseString = \"\";\n\t\t\n\t\tURI request = new URIBuilder()\t\t\t\n\t\t\t.setScheme(\"http\")\n\t\t\t.setHost(\"api.meetup.com\")\n\t\t\t.setPath(path_code)\n\t\t\t\n\t\t\t.setParameter(\"topic\", topic)\n\t\t\t.setParameter(\"city\", city)\n\t\t\t\n\t\t\t.setParameter(\"key\", key)\n\t\t\t.build();\n\t\t\n\t\tHttpGet get = new HttpGet(request);\t\t\t\n\t\tSystem.out.println(\"Get request : \"+get.toString());\n\t\t\n\t\tCloseableHttpClient client = HttpClients.createDefault();\n\t\tCloseableHttpResponse response = client.execute(get);\n\t\tresponseString = EntityUtils.toString(response.getEntity());\n\t\t\n\t\treturn responseString;\n\t}\n\t\n\tpublic String getApiKey(String key_path){\n\t\tString key = \"\";\n\t\t\n\t\ttry{\n\t\t\tBufferedReader reader = new BufferedReader(new FileReader(key_path));\t\n\t\t\tkey = reader.readLine().toString();\t\t\t\t\t\t\t\t\t\n\t\t\treader.close();\n\t\t}\n\t\tcatch(Exception e){System.out.println(e.toString());}\n\t\t\n\t\treturn key;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t}\n\t\n}\n"}
{"id": 54227, "name": "Twelve statements", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n"}
{"id": 54228, "name": "Deming's funnel", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n"}
{"id": 54229, "name": "Deming's funnel", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n"}
{"id": 54230, "name": "Rosetta Code_Fix code tags", "Python": "\n\nfrom re import sub\n\ntesttexts = [\n,\n    ,\n    ]\n\nfor txt in testtexts:\n    text2 = sub(r'<lang\\s+\\\"?([\\w\\d\\s]+)\\\"?\\s?>', r'<syntaxhighlight lang=\\1>', txt)\n    text2 = sub(r'<lang\\s*>', r'<syntaxhighlight lang=text>', text2)\n    text2 = sub(r'</lang\\s*>', r'\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\n\npublic class FixCodeTags \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tString sourcefile=args[0];\n\t\tString convertedfile=args[1];\n\t\tconvert(sourcefile,convertedfile);\n\t}\n\t\tstatic String[] languages = {\"abap\", \"actionscript\", \"actionscript3\",\n\t\t\t\"ada\", \"apache\", \"applescript\", \"apt_sources\", \"asm\", \"asp\",\n\t\t\t\"autoit\", \"avisynth\", \"bar\", \"bash\", \"basic4gl\", \"bf\",\n\t\t\t\"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\",\n\t\t\t\"cfm\", \"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\",\n\t\t\t\"d\", \"delphi\", \"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\",\n\t\t\t\"foo\", \"fortran\", \"freebasic\", \"genero\", \"gettext\", \"glsl\", \"gml\",\n\t\t\t\"gnuplot\", \"go\", \"groovy\", \"haskell\", \"hq9plus\", \"html4strict\",\n\t\t\t\"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\", \"java5\",\n\t\t\t\"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\",\n\t\t\t\"m68k\", \"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\",\n\t\t\t\"mysql\", \"nsis\", \"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\",\n\t\t\t\"oracle11\", \"oracle8\", \"pascal\", \"per\", \"perl\", \"php\", \"php-brief\",\n\t\t\t\"pic16\", \"pixelbender\", \"plsql\", \"povray\", \"powershell\",\n\t\t\t\"progress\", \"prolog\", \"providex\", \"python\", \"qbasic\", \"rails\",\n\t\t\t\"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\", \"scilab\",\n\t\t\t\"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\",\n\t\t\t\"verilog\", \"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\",\n\t\t\t\"whitespace\", \"winbatch\", \"xml\", \"xorg_conf\", \"xpp\", \"z80\"};\n\tstatic void convert(String sourcefile,String convertedfile)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedReader br=new BufferedReader(new FileReader(sourcefile));\n\t\t\t\n\t\t\tStringBuffer sb=new StringBuffer(\"\");\n\t\t\tString line;\n\t\t\twhile((line=br.readLine())!=null)\n\t\t\t{\n\t\t\t\tfor(int i=0;i<languages.length;i++)\n\t\t\t\t{\n\t\t\t\t\tString lang=languages[i];\n\t\t\t\t\tline=line.replaceAll(\"<\"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</\"+lang+\">\", \"</\"+\"lang>\");\n\t\t\t\t\tline=line.replaceAll(\"<code \"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</code>\", \"</\"+\"lang>\");\n\t\t\t\t}\n\t\t\t\tsb.append(line);\n\t\t\t}\n\t\t\tbr.close();\n\t\t\t\n\t\t\tFileWriter fw=new FileWriter(new File(convertedfile));\n\t\t\t\n\t\t\tfw.write(sb.toString());\n\t\t\tfw.close();\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tSystem.out.println(\"Something went horribly wrong: \"+e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 54231, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 54232, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 54233, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 54234, "name": "One-time pad", "Python": "\n\nimport argparse\nimport itertools\nimport pathlib\nimport re\nimport secrets\nimport sys\n\n\n\nMAGIC = \"\n\n\ndef make_keys(n, size):\n    \n    \n    \n    \n    return (secrets.token_hex(size) for _ in range(n))\n\n\ndef make_pad(name, pad_size, key_size):\n    \n    pad = [\n        MAGIC,\n        f\"\n        f\"\n        *make_keys(pad_size, key_size),\n    ]\n\n    return \"\\n\".join(pad)\n\n\ndef xor(message, key):\n    \n    return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))\n\n\ndef use_key(pad):\n    \n    match = re.search(r\"^[a-f0-9]+$\", pad, re.MULTILINE)\n    if not match:\n        error(\"pad is all used up\")\n\n    key = match.group()\n    pos = match.start()\n\n    return (f\"{pad[:pos]}-{pad[pos:]}\", key)\n\n\ndef log(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n\n\ndef error(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n    sys.exit(1)\n\n\ndef write_pad(path, pad_size, key_size):\n    \n    if path.exists():\n        error(f\"pad '{path}' already exists\")\n\n    with path.open(\"w\") as fd:\n        fd.write(make_pad(path.name, pad_size, key_size))\n\n    log(f\"New one-time pad written to {path}\")\n\n\ndef main(pad, message, outfile):\n    \n    if not pad.exists():\n        error(f\"no such pad '{pad}'\")\n\n    with pad.open(\"r\") as fd:\n        if fd.readline().strip() != MAGIC:\n            error(f\"file '{pad}' does not look like a one-time pad\")\n\n    \n    with pad.open(\"r+\") as fd:\n        updated, key = use_key(fd.read())\n\n        fd.seek(0)\n        fd.write(updated)\n\n    outfile.write(xor(message, bytes.fromhex(key)))\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description=\"One-time pad.\")\n\n    parser.add_argument(\n        \"pad\",\n        help=(\n            \"Path to one-time pad. If neither --encrypt or --decrypt \"\n            \"are given, will create a new pad.\"\n        ),\n    )\n\n    parser.add_argument(\n        \"--length\",\n        type=int,\n        default=10,\n        help=\"Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.\",\n    )\n\n    parser.add_argument(\n        \"--key-size\",\n        type=int,\n        default=64,\n        help=\"Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.\",\n    )\n\n    parser.add_argument(\n        \"-o\",\n        \"--outfile\",\n        type=argparse.FileType(\"wb\"),\n        default=sys.stdout.buffer,\n        help=(\n            \"Write encoded/decoded message to a file. Ignored if --encrypt or \"\n            \"--decrypt is not given. Defaults to stdout.\"\n        ),\n    )\n\n    group = parser.add_mutually_exclusive_group()\n\n    group.add_argument(\n        \"--encrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Encrypt FILE using the next available key from pad.\",\n    )\n    group.add_argument(\n        \"--decrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Decrypt FILE using the next available key from pad.\",\n    )\n\n    args = parser.parse_args()\n\n    if args.encrypt:\n        message = args.encrypt.read()\n    elif args.decrypt:\n        message = args.decrypt.read()\n    else:\n        message = None\n\n    \n    if isinstance(message, str):\n        message = message.encode()\n\n    pad = pathlib.Path(args.pad).with_suffix(\".1tp\")\n\n    if message:\n        main(pad, message, args.outfile)\n    else:\n        write_pad(pad, args.length, args.key_size)\n", "Java": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class OneTimePad {\n\n    public static void main(String[] args) {\n        String controlName = \"AtomicBlonde\";\n        generatePad(controlName, 5, 60, 65, 90);\n        String text = \"IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES\";\n        String encrypted = parse(true, controlName, text.replaceAll(\" \", \"\"));\n        String decrypted = parse(false, controlName, encrypted);\n        System.out.println(\"Input  text    = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n\n        controlName = \"AtomicBlondeCaseSensitive\";\n        generatePad(controlName, 5, 60, 32, 126);\n        text = \"It was the best of times, it was the worst of times.\";\n        encrypted = parse(true, controlName, text);\n        decrypted = parse(false, controlName, encrypted);\n        System.out.println();\n        System.out.println(\"Input text     = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n    }\n    \n    private static String parse(boolean encryptText, String controlName, String text) {\n        StringBuilder sb = new StringBuilder();\n        int minCh = 0;\n        int maxCh = 0;\n        Pattern minChPattern = Pattern.compile(\"^#  MIN_CH = ([\\\\d]+)$\");\n        Pattern maxChPattern = Pattern.compile(\"^#  MAX_CH = ([\\\\d]+)$\");\n        boolean validated = false;\n        try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {\n            String inLine = null;\n            while ( (inLine = in.readLine()) != null ) {\n                Matcher minMatcher = minChPattern.matcher(inLine);\n                if ( minMatcher.matches() ) {\n                    minCh = Integer.parseInt(minMatcher.group(1));\n                    continue;\n                }\n                Matcher maxMatcher = maxChPattern.matcher(inLine);\n                if ( maxMatcher.matches() ) {\n                    maxCh = Integer.parseInt(maxMatcher.group(1));\n                    continue;\n                }\n                if ( ! validated && minCh > 0 && maxCh > 0 ) {\n                    validateText(text, minCh, maxCh);\n                    validated = true;\n                }\n                \n                if ( inLine.startsWith(\"#\") || inLine.startsWith(\"-\") ) {\n                    continue;\n                }\n                \n                String key = inLine;\n                if ( encryptText ) {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));\n                    }\n                }\n                else {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        int decrypt = text.charAt(i) - key.charAt(i);\n                        if ( decrypt < 0 ) {\n                            decrypt += maxCh - minCh + 1;\n                        }\n                        decrypt += minCh;\n                        sb.append((char) decrypt);\n                    }\n                }\n                break;\n            }\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n        return sb.toString();\n    }\n\n    private static void validateText(String text, int minCh, int maxCh) {\n        \n        for ( char ch : text.toCharArray() ) {\n            if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {\n                throw new IllegalArgumentException(\"ERROR 103:  Invalid text.\");\n            }\n        }\n        \n    }\n    \n    private static String getFileName(String controlName) {\n        return controlName + \".1tp\";\n    }\n    \n    private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {\n        Random random = new Random();\n        try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {\n            writer.write(\"#  Lines starting with '#' are ignored.\");\n            writer.newLine();\n            writer.write(\"#  Lines starting with '-' are previously used.\");\n            writer.newLine();\n            writer.write(\"#  MIN_CH = \" + minCh);\n            writer.newLine();\n            writer.write(\"#  MAX_CH = \" + maxCh);\n            writer.newLine();\n            for ( int line = 0 ; line < keys ; line++ ) {\n                StringBuilder sb = new StringBuilder();\n                for ( int ch = 0 ; ch < keyLength ; ch++ ) {\n                    sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));\n                }\n                writer.write(sb.toString());\n                writer.newLine();\n            }\n            writer.write(\"#  EOF\");\n            writer.newLine();\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n}\n"}
{"id": 54235, "name": "One-time pad", "Python": "\n\nimport argparse\nimport itertools\nimport pathlib\nimport re\nimport secrets\nimport sys\n\n\n\nMAGIC = \"\n\n\ndef make_keys(n, size):\n    \n    \n    \n    \n    return (secrets.token_hex(size) for _ in range(n))\n\n\ndef make_pad(name, pad_size, key_size):\n    \n    pad = [\n        MAGIC,\n        f\"\n        f\"\n        *make_keys(pad_size, key_size),\n    ]\n\n    return \"\\n\".join(pad)\n\n\ndef xor(message, key):\n    \n    return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))\n\n\ndef use_key(pad):\n    \n    match = re.search(r\"^[a-f0-9]+$\", pad, re.MULTILINE)\n    if not match:\n        error(\"pad is all used up\")\n\n    key = match.group()\n    pos = match.start()\n\n    return (f\"{pad[:pos]}-{pad[pos:]}\", key)\n\n\ndef log(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n\n\ndef error(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n    sys.exit(1)\n\n\ndef write_pad(path, pad_size, key_size):\n    \n    if path.exists():\n        error(f\"pad '{path}' already exists\")\n\n    with path.open(\"w\") as fd:\n        fd.write(make_pad(path.name, pad_size, key_size))\n\n    log(f\"New one-time pad written to {path}\")\n\n\ndef main(pad, message, outfile):\n    \n    if not pad.exists():\n        error(f\"no such pad '{pad}'\")\n\n    with pad.open(\"r\") as fd:\n        if fd.readline().strip() != MAGIC:\n            error(f\"file '{pad}' does not look like a one-time pad\")\n\n    \n    with pad.open(\"r+\") as fd:\n        updated, key = use_key(fd.read())\n\n        fd.seek(0)\n        fd.write(updated)\n\n    outfile.write(xor(message, bytes.fromhex(key)))\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description=\"One-time pad.\")\n\n    parser.add_argument(\n        \"pad\",\n        help=(\n            \"Path to one-time pad. If neither --encrypt or --decrypt \"\n            \"are given, will create a new pad.\"\n        ),\n    )\n\n    parser.add_argument(\n        \"--length\",\n        type=int,\n        default=10,\n        help=\"Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.\",\n    )\n\n    parser.add_argument(\n        \"--key-size\",\n        type=int,\n        default=64,\n        help=\"Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.\",\n    )\n\n    parser.add_argument(\n        \"-o\",\n        \"--outfile\",\n        type=argparse.FileType(\"wb\"),\n        default=sys.stdout.buffer,\n        help=(\n            \"Write encoded/decoded message to a file. Ignored if --encrypt or \"\n            \"--decrypt is not given. Defaults to stdout.\"\n        ),\n    )\n\n    group = parser.add_mutually_exclusive_group()\n\n    group.add_argument(\n        \"--encrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Encrypt FILE using the next available key from pad.\",\n    )\n    group.add_argument(\n        \"--decrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Decrypt FILE using the next available key from pad.\",\n    )\n\n    args = parser.parse_args()\n\n    if args.encrypt:\n        message = args.encrypt.read()\n    elif args.decrypt:\n        message = args.decrypt.read()\n    else:\n        message = None\n\n    \n    if isinstance(message, str):\n        message = message.encode()\n\n    pad = pathlib.Path(args.pad).with_suffix(\".1tp\")\n\n    if message:\n        main(pad, message, args.outfile)\n    else:\n        write_pad(pad, args.length, args.key_size)\n", "Java": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class OneTimePad {\n\n    public static void main(String[] args) {\n        String controlName = \"AtomicBlonde\";\n        generatePad(controlName, 5, 60, 65, 90);\n        String text = \"IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES\";\n        String encrypted = parse(true, controlName, text.replaceAll(\" \", \"\"));\n        String decrypted = parse(false, controlName, encrypted);\n        System.out.println(\"Input  text    = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n\n        controlName = \"AtomicBlondeCaseSensitive\";\n        generatePad(controlName, 5, 60, 32, 126);\n        text = \"It was the best of times, it was the worst of times.\";\n        encrypted = parse(true, controlName, text);\n        decrypted = parse(false, controlName, encrypted);\n        System.out.println();\n        System.out.println(\"Input text     = \" + text);\n        System.out.println(\"Encrypted text = \" + encrypted);\n        System.out.println(\"Decrypted text = \" + decrypted);\n    }\n    \n    private static String parse(boolean encryptText, String controlName, String text) {\n        StringBuilder sb = new StringBuilder();\n        int minCh = 0;\n        int maxCh = 0;\n        Pattern minChPattern = Pattern.compile(\"^#  MIN_CH = ([\\\\d]+)$\");\n        Pattern maxChPattern = Pattern.compile(\"^#  MAX_CH = ([\\\\d]+)$\");\n        boolean validated = false;\n        try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {\n            String inLine = null;\n            while ( (inLine = in.readLine()) != null ) {\n                Matcher minMatcher = minChPattern.matcher(inLine);\n                if ( minMatcher.matches() ) {\n                    minCh = Integer.parseInt(minMatcher.group(1));\n                    continue;\n                }\n                Matcher maxMatcher = maxChPattern.matcher(inLine);\n                if ( maxMatcher.matches() ) {\n                    maxCh = Integer.parseInt(maxMatcher.group(1));\n                    continue;\n                }\n                if ( ! validated && minCh > 0 && maxCh > 0 ) {\n                    validateText(text, minCh, maxCh);\n                    validated = true;\n                }\n                \n                if ( inLine.startsWith(\"#\") || inLine.startsWith(\"-\") ) {\n                    continue;\n                }\n                \n                String key = inLine;\n                if ( encryptText ) {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));\n                    }\n                }\n                else {\n                    for ( int i = 0 ; i < text.length(); i++) {\n                        int decrypt = text.charAt(i) - key.charAt(i);\n                        if ( decrypt < 0 ) {\n                            decrypt += maxCh - minCh + 1;\n                        }\n                        decrypt += minCh;\n                        sb.append((char) decrypt);\n                    }\n                }\n                break;\n            }\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n        return sb.toString();\n    }\n\n    private static void validateText(String text, int minCh, int maxCh) {\n        \n        for ( char ch : text.toCharArray() ) {\n            if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {\n                throw new IllegalArgumentException(\"ERROR 103:  Invalid text.\");\n            }\n        }\n        \n    }\n    \n    private static String getFileName(String controlName) {\n        return controlName + \".1tp\";\n    }\n    \n    private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {\n        Random random = new Random();\n        try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {\n            writer.write(\"#  Lines starting with '#' are ignored.\");\n            writer.newLine();\n            writer.write(\"#  Lines starting with '-' are previously used.\");\n            writer.newLine();\n            writer.write(\"#  MIN_CH = \" + minCh);\n            writer.newLine();\n            writer.write(\"#  MAX_CH = \" + maxCh);\n            writer.newLine();\n            for ( int line = 0 ; line < keys ; line++ ) {\n                StringBuilder sb = new StringBuilder();\n                for ( int ch = 0 ; ch < keyLength ; ch++ ) {\n                    sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));\n                }\n                writer.write(sb.toString());\n                writer.newLine();\n            }\n            writer.write(\"#  EOF\");\n            writer.newLine();\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n}\n"}
{"id": 54236, "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": 54237, "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", "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": 54238, "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", "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": 54239, "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", "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": 54240, "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", "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": 54241, "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", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 54242, "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", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 54243, "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", "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": 54244, "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", "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": 54245, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 54246, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 54247, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 54248, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 54249, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 54250, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 54251, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 54252, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 54253, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 54254, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 54255, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 54256, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 54257, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 54258, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 54259, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 54260, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 54261, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 54262, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 54263, "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", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 54264, "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", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 54265, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 54266, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 54267, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 54268, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 54269, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 54270, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 54271, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 54272, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 54273, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 54274, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 54275, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 54276, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 54277, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 54278, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 54279, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 54280, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 54281, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 54282, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 54283, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 54284, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 54285, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 54286, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 54287, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 54288, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 54289, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 54290, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 54291, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 54292, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 54293, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 54294, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 54295, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 54296, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 54297, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 54298, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 54299, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 54300, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 54301, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 54302, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 54303, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 54304, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 54305, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 54306, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 54307, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 54308, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 54309, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 54310, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 54311, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 54312, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 54313, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 54314, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 54315, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 54316, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 54317, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 54318, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 54319, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 54320, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 54321, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 54322, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 54323, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 54324, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 54325, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 54326, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 54327, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 54328, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 54329, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 54330, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 54331, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 54332, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 54333, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 54334, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 54335, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 54336, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 54337, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 54338, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 54339, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 54340, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 54341, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 54342, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 54343, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 54344, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 54345, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 54346, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 54347, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 54348, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 54349, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 54350, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 54351, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 54352, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 54353, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 54354, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 54355, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 54356, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 54357, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 54358, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 54359, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 54360, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 54361, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 54362, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 54363, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 54364, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 54365, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 54366, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 54367, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 54368, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 54369, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 54370, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 54371, "name": "Soundex", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 54372, "name": "Soundex", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 54373, "name": "Bitmap_Histogram", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 54374, "name": "Bitmap_Histogram", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 54375, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 54376, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 54377, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 54378, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 54379, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 54380, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 54381, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 54382, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 54383, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 54384, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 54385, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 54386, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 54387, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 54388, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 54389, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 54390, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 54391, "name": "Active Directory_Search for a user", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 54392, "name": "Active Directory_Search for a user", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 54393, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 54394, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 54395, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 54396, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 54397, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 54398, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 54399, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 54400, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 54401, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 54402, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 54403, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 54404, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 54405, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 54406, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 54407, "name": "Active Directory_Connect", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 54408, "name": "Active Directory_Connect", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 54409, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 54410, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 54411, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 54412, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 54413, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 54414, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 54415, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 54416, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 54417, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 54418, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 54419, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 54420, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 54421, "name": "Object serialization", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 54422, "name": "Object serialization", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 54423, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 54424, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 54425, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 54426, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 54427, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 54428, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 54429, "name": "Markov chain text generator", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 54430, "name": "Markov chain text generator", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 54431, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 54432, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 54433, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 54434, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 54435, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 54436, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 54437, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 54438, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 54439, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 54440, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 54441, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 54442, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 54443, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 54444, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 54445, "name": "Polymorphism", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 54446, "name": "Polymorphism", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 54447, "name": "Reflection_List properties", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 54448, "name": "Reflection_List properties", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 54449, "name": "Align columns", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 54450, "name": "Align columns", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 54451, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 54452, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 54453, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 54454, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 54455, "name": "Dynamic variable names", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 54456, "name": "Dynamic variable names", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 54457, "name": "Reflection_List methods", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 54458, "name": "Reflection_List methods", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 54459, "name": "Send an unknown method call", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 54460, "name": "Send an unknown method call", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 54461, "name": "Variables", "Java": "int a;\ndouble b;\nAClassNameHere c;\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 54462, "name": "Variables", "Java": "int a;\ndouble b;\nAClassNameHere c;\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 54463, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 54464, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 54465, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 54466, "name": "Runtime evaluation_In an environment", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 54467, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 54468, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 54469, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 54470, "name": "Runtime evaluation", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 54471, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 54472, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 54473, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 54474, "name": "Permutations with repetitions", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 54475, "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": "#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": 54476, "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": "#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": 54477, "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": "#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": 54478, "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": "#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": 54479, "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": "#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": 54480, "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", "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": 54481, "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", "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": 54482, "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", "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": 54483, "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", "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": 54484, "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", "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": 54485, "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": "#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": 54486, "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": "#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": 54487, "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": "#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": 54488, "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": "#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": 54489, "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", "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": 54490, "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", "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": 54491, "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", "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": 54492, "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", "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": 54493, "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": "#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": 54494, "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": "#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": 54495, "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": "#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": 54496, "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", "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": 54497, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 54498, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 54499, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\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": 54500, "name": "Peano curve", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\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": 54501, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\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": 54502, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\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": 54503, "name": "Magnanimous numbers", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\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": 54504, "name": "Extensible prime generator", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\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": 54505, "name": "Create a two-dimensional array at runtime", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\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": 54506, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 54507, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 54508, "name": "Pi", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\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": 54509, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 54510, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 54511, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 54512, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 54513, "name": "Return multiple values", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\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": 54514, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 54515, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 54516, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 54517, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 54518, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\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": 54519, "name": "LU decomposition", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\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"}
{"id": 54520, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 54521, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 54522, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 54523, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54524, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54525, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 54526, "name": "Text processing_1", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n"}
{"id": 54527, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 54528, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 54529, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 54530, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 54531, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 54532, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 54533, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 54534, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 54535, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54536, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 54537, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 54538, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 54539, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 54540, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 54541, "name": "Fractran", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n"}
{"id": 54542, "name": "Read a configuration file", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 54543, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 54544, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 54545, "name": "List comprehensions", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 54546, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 54547, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 54548, "name": "Case-sensitivity of identifiers", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n"}
{"id": 54549, "name": "Loops_Downward for", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 54550, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 54551, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 54552, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 54553, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 54554, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54555, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 54556, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54557, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 54558, "name": "Pell's equation", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 54559, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 54560, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 54561, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 54562, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 54563, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 54564, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 54565, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 54566, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 54567, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 54568, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 54569, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 54570, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 54571, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 54572, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 54573, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 54574, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54575, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54576, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 54577, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 54578, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 54579, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 54580, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 54581, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 54582, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 54583, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 54584, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 54585, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 54586, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 54587, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 54588, "name": "Jaro similarity", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n"}
{"id": 54589, "name": "Jaro similarity", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n"}
{"id": 54590, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 54591, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54592, "name": "Prime triangle", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n"}
{"id": 54593, "name": "Prime triangle", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n"}
{"id": 54594, "name": "Trabb Pardo–Knuth algorithm", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n"}
{"id": 54595, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 54596, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 54597, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 54598, "name": "Biorhythms", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n"}
{"id": 54599, "name": "Biorhythms", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n"}
{"id": 54600, "name": "Table creation_Postal addresses", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 54601, "name": "Stern-Brocot sequence", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 54602, "name": "Soundex", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 54603, "name": "Chat server", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n"}
{"id": 54604, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 54605, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 54606, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 54607, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 54608, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 54609, "name": "Terminal control_Dimensions", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n"}
{"id": 54610, "name": "Finite state machine", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n"}
{"id": 54611, "name": "Finite state machine", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n"}
{"id": 54612, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 54613, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 54614, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 54615, "name": "Sierpinski pentagon", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 54616, "name": "Rep-string", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 54617, "name": "Rep-string", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 54618, "name": "GUI_Maximum window dimensions", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n"}
{"id": 54619, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 54620, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 54621, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 54622, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 54623, "name": "Parse an IP Address", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"}
{"id": 54624, "name": "Knapsack problem_Unbounded", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n"}
{"id": 54625, "name": "Textonyms", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54626, "name": "Range extraction", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 54627, "name": "Type detection", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n"}
{"id": 54628, "name": "Maximum triangle path sum", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 54629, "name": "Zhang-Suen thinning algorithm", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n"}
{"id": 54630, "name": "Variable declaration reset", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n"}
{"id": 54631, "name": "Start from a main routine", "VB": "SUB Main()\n  \nEND\n", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n"}
{"id": 54632, "name": "Start from a main routine", "VB": "SUB Main()\n  \nEND\n", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n"}
{"id": 54633, "name": "Koch 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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 54634, "name": "Draw a pixel", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 54635, "name": "Words from neighbour ones", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54636, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 54637, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 54638, "name": "UTF-8 encode and decode", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n"}
{"id": 54639, "name": "Magic squares of doubly even order", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 54640, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 54641, "name": "Execute a system command", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n"}
{"id": 54642, "name": "XML validation", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n"}
{"id": 54643, "name": "Death Star", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n"}
{"id": 54644, "name": "Verify distribution uniformity_Chi-squared test", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n"}
{"id": 54645, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\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\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n"}
{"id": 54646, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 54647, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 54648, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n"}
{"id": 54649, "name": "One of n lines in a file", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 54650, "name": "Spelling of ordinal numbers", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 54651, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 54652, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 54653, "name": "Repeat", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 54654, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 54655, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 54656, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 54657, "name": "Hello world_Web server", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 54658, "name": "Own digits power sum", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\n\n\n\nModule OwnDigitsPowerSum\n\n    Public Sub Main\n\n        \n        Dim used(9) As Integer\n        Dim check(9) As Integer\n        Dim power(9, 9) As Long\n        For i As Integer = 0 To 9\n            check(i) = 0\n        Next i\n        For i As Integer = 1 To 9\n            power(1,  i) = i\n        Next i\n        For j As Integer =  2 To 9\n            For i As Integer = 1 To 9\n                power(j, i) = power(j - 1, i) * i\n            Next i\n        Next j\n        \n        \n        Dim lowestDigit(9) As Integer\n        lowestDigit(1) = -1\n        lowestDigit(2) = -1\n        Dim p10 As Long = 100\n        For i As Integer = 3 To 9\n            For p As Integer = 2 To 9\n                Dim np As Long = power(i, p) * i\n                If Not ( np < p10) Then Exit For\n                lowestDigit(i) = p\n            Next p\n            p10 *= 10\n        Next i\n        \n        Dim maxZeros(9, 9) As Integer\n        For i As Integer = 1 To 9\n            For j As Integer = 1 To 9\n                maxZeros(i, j) = 0\n            Next j\n        Next i\n        p10 = 1000\n        For w As Integer = 3 To 9\n            For d As Integer = lowestDigit(w) To 9\n                Dim nz As Integer = 9\n                Do\n                    If nz < 0 Then\n                        Exit Do\n                    Else\n                        Dim np As Long = power(w, d) * nz\n                        IF Not ( np > p10) Then Exit Do\n                    End If\n                    nz -= 1\n                Loop\n                maxZeros(w, d) = If(nz > w, 0, w - nz)\n            Next d\n            p10 *= 10\n        Next w\n        \n        \n        Dim numbers(100) As Long     \n        Dim nCount As Integer = 0    \n        Dim tryCount As Integer = 0  \n        Dim digits(9) As Integer     \n        For d As Integer = 1 To 9\n             digits(d) = 9\n        Next d\n        For d As Integer = 0 To 8\n            used(d) = 0\n        Next d\n        used(9) = 9\n        Dim width As Integer = 9     \n        Dim last As Integer = width  \n        p10 = 100000000              \n        Do While width > 2\n            tryCount += 1\n            Dim dps As Long = 0      \n            check(0) = used(0)\n            For i As Integer = 1 To 9\n                check(i) = used(i)\n                If used(i) <> 0 Then\n                    dps += used(i) * power(width, i)\n                End If\n            Next i\n            \n            Dim n As Long = dps\n            Do\n                check(CInt(n Mod 10)) -= 1 \n                n \\= 10\n            Loop Until n <= 0\n            Dim reduceWidth As Boolean = dps <= p10\n            If Not reduceWidth Then\n                \n                \n                \n                Dim zCount As Integer = 0\n                For i As Integer = 0 To 9\n                    If check(i) <> 0 Then Exit For\n                    zCount+= 1\n                Next i\n                If zCount = 10 Then\n                    nCount += 1\n                    numbers(nCount) = dps\n                End If\n                \n                used(digits(last)) -= 1\n                digits(last) -= 1\n                If digits(last) = 0 Then\n                    \n                    If used(0) >= maxZeros(width, digits(1)) Then\n                        \n                        digits(last) = -1\n                    End If\n                End If\n                If digits(last) >= 0 Then\n                    \n                    used(digits(last)) += 1\n                Else\n                    \n                    Dim prev As Integer = last\n                    Do\n                        prev -= 1\n                        If prev < 1 Then\n                            Exit Do\n                        Else\n                            used(digits(prev)) -= 1\n                            digits(prev) -= 1\n                            IF digits(prev) >= 0 Then Exit Do\n                        End If\n                    Loop\n                    If prev > 0 Then\n                        \n                        If prev = 1 Then\n                            If digits(1) <= lowestDigit(width) Then\n                               \n                               prev = 0\n                            End If\n                        End If\n                        If prev <> 0 Then\n                           \n                            used(digits(prev)) += 1\n                            For i As Integer = prev + 1 To width\n                                digits(i) = digits(prev)\n                                used(digits(prev)) += 1\n                            Next i\n                        End If\n                    End If\n                    If prev <= 0 Then\n                        \n                        reduceWidth = True\n                    End If\n                End If\n            End If\n            If reduceWidth Then\n                \n                last -= 1\n                width = last\n                If last > 0 Then\n                    \n                    For d As Integer = 1 To last\n                        digits(d) = 9\n                    Next d\n                    For d As Integer = last + 1 To 9\n                        digits(d) = -1\n                    Next d\n                    For d As Integer = 0 To 8\n                        used(d) = 0\n                    Next d\n                    used(9) = last\n                    p10 \\= 10\n                End If\n            End If\n        Loop\n        \n        Console.Out.WriteLine(\"Own digits power sums for N = 3 to 9 inclusive:\")\n        For i As Integer = nCount To 1 Step -1\n            Console.Out.WriteLine(numbers(i))\n        Next i\n        Console.Out.WriteLine(\"Considered \" & tryCount & \" digit combinations\")\n\n    End Sub\n\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define MAX_DIGITS 9\n\nint digits[MAX_DIGITS];\n\nvoid getDigits(int i) {\n    int ix = 0;\n    while (i > 0) {\n        digits[ix++] = i % 10;\n        i /= 10;\n    }\n}\n\nint main() {\n    int n, d, i, max, lastDigit, sum, dp;\n    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};\n    printf(\"Own digits power sums for N = 3 to 9 inclusive:\\n\");\n    for (n = 3; n < 10; ++n) {\n        for (d = 2; d < 10; ++d) powers[d] *= d;\n        i = (int)pow(10, n-1);\n        max = i * 10;\n        lastDigit = 0;\n        while (i < max) {\n            if (!lastDigit) {\n                getDigits(i);\n                sum = 0;\n                for (d = 0; d < n; ++d) {\n                    dp = digits[d];\n                    sum += powers[dp];\n                }\n            } else if (lastDigit == 1) {\n                sum++;\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1];\n            }\n            if (sum == i) {\n                printf(\"%d\\n\", i);\n                if (lastDigit == 0) printf(\"%d\\n\", i + 1);\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (sum > i) {\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (lastDigit < 9) {\n                i++;\n                lastDigit++;\n            } else {\n                i++;\n                lastDigit = 0;\n            }\n        }\n    }\n    return 0;\n}\n"}
{"id": 54659, "name": "Klarner-Rado sequence", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n"}
{"id": 54660, "name": "Klarner-Rado sequence", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n"}
{"id": 54661, "name": "Sorting algorithms_Pancake sort", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n"}
{"id": 54662, "name": "Pythagorean quadruples", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 54663, "name": "Long stairs", "VB": "Option Explicit\nRandomize Timer\n\nFunction pad(s,n) \n  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If \nEnd Function\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\nFunction Rounds(maxsecs,wiz,a)\n  Dim mystep,maxstep,toend,j,i,x,d \n  If IsArray(a) Then d=True: print \"seconds behind pending\"   \n  maxstep=100\n  For j=1 To maxsecs\n    For i=1 To wiz\n      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1\n      maxstep=maxstep+1  \n    Next \n    mystep=mystep+1 \n    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function\n    If d Then\n      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)\n    End If     \n  Next \n  Rounds=Array(maxsecs,maxstep)\nEnd Function\n\n\nDim n,r,a,sumt,sums,ntests,t,maxsecs\nntests=10000\nmaxsecs=7000\nt=timer\na=Array(600,609)\nFor n=1 To ntests\n  r=Rounds(maxsecs,5,a)\n  If r(0)<>maxsecs Then \n    sumt=sumt+r(0)\n    sums=sums+r(1)\n  End if  \n  a=\"\"\nNext  \n\nprint vbcrlf & \"Done \" & ntests & \" tests in \" & Timer-t & \" seconds\" \nprint \"escaped in \" & sumt/ntests  & \" seconds with \" & sums/ntests & \" stairs\"\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n    int trial, secs_tot=0, steps_tot=0;     \n    int sbeh, slen, wiz, secs;              \n    time_t t;\n    srand((unsigned) time(&t));             \n    printf( \"Seconds    steps behind    steps ahead\\n\" );\n    for( trial=1;trial<=10000;trial++ ) {   \n        sbeh = 0; slen = 100; secs = 0;     \n        while(sbeh<slen) {                  \n            sbeh+=1;                        \n            for(wiz=1;wiz<=5;wiz++) {       \n                if(rand()%slen < sbeh)\n                    sbeh+=1;                \n                slen+=1;                    \n            }\n            secs+=1;                        \n            if(trial==1&&599<secs&&secs<610)\n                printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh );\n            \n        }\n        secs_tot+=secs;\n        steps_tot+=slen;\n    }\n    printf( \"Average secs taken: %f\\n\", secs_tot/10000.0 );\n    printf( \"Average final length of staircase: %f\\n\", steps_tot/10000.0 ); \n    return 0;\n}\n"}
{"id": 54664, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 54665, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 54666, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 54667, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 54668, "name": "Rosetta Code_Find unimplemented tasks", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 54669, "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": 54670, "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", "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": 54671, "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++": "#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": 54672, "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", "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": 54673, "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", "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": 54674, "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", "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": 54675, "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", "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": 54676, "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++": "#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": 54677, "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++": "#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": 54678, "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++": "#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": 54679, "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", "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": 54680, "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", "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": 54681, "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", "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": 54682, "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++": "#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": 54683, "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++": "#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": 54684, "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++": "#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": 54685, "name": "Memory allocation", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \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": 54686, "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++": "#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": 54687, "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++": "#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": 54688, "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++": "#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": 54689, "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", "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": 54690, "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", "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": 54691, "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++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 54692, "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", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\n}\n"}
{"id": 54693, "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++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n"}
{"id": 54694, "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", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 1);\n    return 0;\n}\n"}
{"id": 54695, "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++": "#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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 54696, "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", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54697, "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", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\n\n"}
{"id": 54698, "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++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n"}
{"id": 54699, "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", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 54700, "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", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 54701, "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", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\n}\n"}
{"id": 54702, "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", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 54703, "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", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 54704, "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", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 54705, "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", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 54706, "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", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 54707, "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", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n"}
{"id": 54708, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 54709, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 54710, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 54711, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 54712, "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", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 54713, "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", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 54714, "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", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 54715, "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", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 54716, "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", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 54717, "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", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 54718, "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", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 54719, "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", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\n}\n"}
{"id": 54720, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 54721, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 54722, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 54723, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 54724, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 54725, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 54726, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 54727, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 54728, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n"}
{"id": 54729, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n"}
{"id": 54730, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n"}
{"id": 54731, "name": "SHA-256 Merkle tree", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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": 54732, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 54733, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 54734, "name": "User input_Graphical", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n"}
{"id": 54735, "name": "User input_Graphical", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n"}
{"id": 54736, "name": "Sierpinski arrowhead curve", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54737, "name": "Text processing_1", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n"}
{"id": 54738, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 54739, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 54740, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 54741, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 54742, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 54743, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 54744, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 54745, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 54746, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 54747, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 54748, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 54749, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "C++": "#include <stack>\n"}
{"id": 54750, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "C++": "#include <stack>\n"}
{"id": 54751, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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 <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54752, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 54753, "name": "Fractran", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n"}
{"id": 54754, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n"}
{"id": 54755, "name": "Galton box animation", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n"}
{"id": 54756, "name": "Galton box animation", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n"}
{"id": 54757, "name": "Sorting Algorithms_Circle Sort", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\n", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\n"}
{"id": 54758, "name": "Kronecker product based fractals", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\n", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\n"}
{"id": 54759, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 54760, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 54761, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 54762, "name": "Circular primes", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 54763, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n"}
{"id": 54764, "name": "Sorting algorithms_Radix sort", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n"}
{"id": 54765, "name": "List comprehensions", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n"}
{"id": 54766, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 54767, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 54768, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 54769, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54770, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54771, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 54772, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 54773, "name": "Safe addition", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n"}
{"id": 54774, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n"}
{"id": 54775, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 54776, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 54777, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 54778, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 54779, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 54780, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 54781, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 54782, "name": "Non-continuous subsequences", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 54783, "name": "Fibonacci word_fractal", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\n"}
{"id": 54784, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n"}
{"id": 54785, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 54786, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 54787, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 54788, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 54789, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 54790, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 54791, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 54792, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 54793, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 54794, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 54795, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 54796, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 54797, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 54798, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 54799, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n"}
{"id": 54800, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n"}
{"id": 54801, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 54802, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 54803, "name": "Carmichael 3 strong pseudoprimes", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n"}
{"id": 54804, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 54805, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 54806, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 54807, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n"}
{"id": 54808, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54809, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54810, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54811, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 54812, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 54813, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 54814, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n"}
{"id": 54815, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 54816, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 54817, "name": "Fermat numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class FermatNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 Fermat numbers:\");\n        for ( int i = 0 ; i < 10 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, fermat(i));\n        }\n        System.out.printf(\"%nFirst 12 Fermat numbers factored:%n\");\n        for ( int i = 0 ; i < 13 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, getString(getFactors(i, fermat(i))));\n        }\n    }\n    \n    private static String getString(List<BigInteger> factors) {\n        if ( factors.size() == 1 ) {\n            return factors.get(0) + \" (PRIME)\";\n        }\n        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith(\"-\") ? \"(C\" + v.replace(\"-\", \"\") + \")\" : v).collect(Collectors.joining(\" * \"));\n    }\n\n    private static Map<Integer, String> COMPOSITE = new HashMap<>();\n    static {\n        COMPOSITE.put(9, \"5529\");\n        COMPOSITE.put(10, \"6078\");\n        COMPOSITE.put(11, \"1037\");\n        COMPOSITE.put(12, \"5488\");\n        COMPOSITE.put(13, \"2884\");\n    }\n\n    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {\n        List<BigInteger> factors = new ArrayList<>();\n        BigInteger factor = BigInteger.ONE;\n        while ( true ) {\n            if ( n.isProbablePrime(100) ) {\n                factors.add(n);\n                break;\n            }\n            else {\n                if ( COMPOSITE.containsKey(fermatIndex) ) {\n                    String stop = COMPOSITE.get(fermatIndex);\n                    if ( n.toString().startsWith(stop) ) {\n                        factors.add(new BigInteger(\"-\" + n.toString().length()));\n                        break;\n                    }\n                }\n                factor = pollardRhoFast(n);\n                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {\n                    factors.add(n);\n                    break;\n                }\n                else {\n                    factors.add(factor);\n                    n = n.divide(factor);\n                }\n            }\n        }\n        return factors;\n    }\n    \n    private static final BigInteger TWO = BigInteger.valueOf(2);\n    \n    private static BigInteger fermat(int n) {\n        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);\n    }\n        \n    \n    @SuppressWarnings(\"unused\")\n    private static BigInteger pollardRho(BigInteger n) {\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        while ( d.compareTo(BigInteger.ONE) == 0 ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs().gcd(n);\n        }\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n    \n    \n    \n    \n    \n    \n    private static BigInteger pollardRhoFast(BigInteger n) {\n        long start = System.currentTimeMillis();\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        int count = 0;\n        BigInteger z = BigInteger.ONE;\n        while ( true ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs();\n            z = z.multiply(d).mod(n);\n            count++;\n            if ( count == 100 ) {\n                d = z.gcd(n);\n                if ( d.compareTo(BigInteger.ONE) != 0 ) {\n                    break;\n                }\n                z = BigInteger.ONE;\n                count = 0;\n            }\n        }\n        long end = System.currentTimeMillis();\n        System.out.printf(\"    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n\", n, (end-start), d);\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n\n    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {\n        return x.multiply(x).add(BigInteger.ONE).mod(n);\n    }\n\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntypedef boost::multiprecision::cpp_int integer;\n\ninteger fermat(unsigned int n) {\n    unsigned int p = 1;\n    for (unsigned int i = 0; i < n; ++i)\n        p *= 2;\n    return 1 + pow(integer(2), p);\n}\n\ninline void g(integer& x, const integer& n) {\n    x *= x;\n    x += 1;\n    x %= n;\n}\n\ninteger pollard_rho(const integer& n) {\n    integer x = 2, y = 2, d = 1, z = 1;\n    int count = 0;\n    for (;;) {\n        g(x, n);\n        g(y, n);\n        g(y, n);\n        d = abs(x - y);\n        z = (z * d) % n;\n        ++count;\n        if (count == 100) {\n            d = gcd(z, n);\n            if (d != 1)\n                break;\n            z = 1;\n            count = 0;\n        }\n    }\n    if (d == n)\n        return 0;\n    return d;\n}\n\nstd::vector<integer> get_prime_factors(integer n) {\n    std::vector<integer> factors;\n    for (;;) {\n        if (miller_rabin_test(n, 25)) {\n            factors.push_back(n);\n            break;\n        }\n        integer f = pollard_rho(n);\n        if (f == 0) {\n            factors.push_back(n);\n            break;\n        }\n        factors.push_back(f);\n        n /= f;\n    }\n    return factors;\n}\n\nvoid print_vector(const std::vector<integer>& factors) {\n    if (factors.empty())\n        return;\n    auto i = factors.begin();\n    std::cout << *i++;\n    for (; i != factors.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout << \"First 10 Fermat numbers:\\n\";\n    for (unsigned int i = 0; i < 10; ++i)\n        std::cout << \"F(\" << i << \") = \" << fermat(i) << '\\n';\n    std::cout << \"\\nPrime factors:\\n\";\n    for (unsigned int i = 0; i < 9; ++i) {\n        std::cout << \"F(\" << i << \"): \";\n        print_vector(get_prime_factors(fermat(i)));\n    }\n    return 0;\n}\n"}
{"id": 54818, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 54819, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 54820, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 54821, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 54822, "name": "Water collected between towers", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 54823, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n"}
{"id": 54824, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n"}
{"id": 54825, "name": "Jaro similarity", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n"}
{"id": 54826, "name": "Sum and product puzzle", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n"}
{"id": 54827, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 54828, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n"}
{"id": 54829, "name": "Prime triangle", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 54830, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 54831, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 54832, "name": "Sequence_ nth number with exactly n divisors", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 54833, "name": "Sequence_ smallest number with exactly n divisors", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n"}
{"id": 54834, "name": "Sequence_ smallest number with exactly n divisors", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n"}
{"id": 54835, "name": "Pancake numbers", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54836, "name": "Pancake numbers", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54837, "name": "Generate random chess position", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n"}
{"id": 54838, "name": "Esthetic numbers", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n"}
{"id": 54839, "name": "Topswops", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n"}
{"id": 54840, "name": "Old Russian measure of length", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n"}
{"id": 54841, "name": "Rate counter", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n"}
{"id": 54842, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n"}
{"id": 54843, "name": "Pythagoras tree", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n"}
{"id": 54844, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 54845, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54846, "name": "Stern-Brocot sequence", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 54847, "name": "Numeric error propagation", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n"}
{"id": 54848, "name": "Numeric error propagation", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n"}
{"id": 54849, "name": "List rooted trees", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n"}
{"id": 54850, "name": "Longest common suffix", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n"}
{"id": 54851, "name": "Sum of elements below main diagonal of matrix", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n"}
{"id": 54852, "name": "FASTA format", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 54853, "name": "Pseudo-random numbers_PCG32", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54854, "name": "Sierpinski pentagon", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 54855, "name": "Sierpinski pentagon", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 54856, "name": "Rep-string", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 54857, "name": "Rep-string", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 54858, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n"}
{"id": 54859, "name": "Changeable words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54860, "name": "Four is magic", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 54861, "name": "Getting the number of decimals", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 54862, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 54863, "name": "Parse an IP Address", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n"}
{"id": 54864, "name": "Textonyms", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n"}
{"id": 54865, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 54866, "name": "A_ search algorithm", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 54867, "name": "Teacup rim text", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54868, "name": "Increasing gaps between consecutive Niven numbers", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 54869, "name": "Print debugging statement", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n"}
{"id": 54870, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 54871, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 54872, "name": "Type detection", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 54873, "name": "Maximum triangle path sum", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 54874, "name": "Zhang-Suen thinning algorithm", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <valarray>\nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n    friend class ZhangSuen;\n    using pixel_t = char;\n    static const pixel_t BLACK_PIX;\n    static const pixel_t WHITE_PIX;\n\n    Image(unsigned width = 1, unsigned height = 1) \n    : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n    {}\n    Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n    {}\n    Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n    {}\n    ~Image() = default;\n    Image& operator=(const Image& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = i.data_;\n        }\n        return *this;\n    }\n    Image& operator=(Image&& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = std::move(i.data_);\n        }\n        return *this;\n    }\n    size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n    bool operator()(unsigned x, unsigned y) {\n        return data_[idx(x, y)];\n    }\n    friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n        o << i.width_ << \" x \" << i.height_ << std::endl;\n        size_t px = 0;\n        for(const auto& e : i.data_) {\n            o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n            if (++px % i.width_ == 0)\n                o << std::endl;\n        }\n        return o << std::endl;\n    }\n    friend std::istream& operator>>(std::istream& in, Image& img) {\n        auto it = std::begin(img.data_);\n        const auto end = std::end(img.data_);\n        Image::pixel_t tmp;\n        while(in && it != end) {\n            in >> tmp;\n            if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n                throw \"Bad character found in image\";\n            *it = (tmp == Image::BLACK_PIX)?1:0;\n            ++it;\n        }\n        return in;\n    }\n    unsigned width() const noexcept { return width_; }\n    unsigned height() const noexcept { return height_; }\n    struct Neighbours {\n        \n        \n        \n        Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n        : img_{img}\n        , p1_{img.idx(p1_x, p1_y)}\n        , p2_{p1_ - img.width()}\n        , p3_{p2_ + 1}\n        , p4_{p1_ + 1}\n        , p5_{p4_ + img.width()}\n        , p6_{p5_ - 1}\n        , p7_{p6_ - 1}\n        , p8_{p1_ - 1}\n        , p9_{p2_ - 1} \n        {}\n        const Image& img_;\n        const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n        const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n        const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n        const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n        const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n        const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n        const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n        const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n        const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n        const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n    };\n    Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n    unsigned height_ { 0 };\n    unsigned width_ { 0 };\n    std::valarray<pixel_t> data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n    \n    unsigned transitions_white_black(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += (a.p9() == 0) && a.p2();\n        sum += (a.p2() == 0) && a.p3();\n        sum += (a.p3() == 0) && a.p4();\n        sum += (a.p8() == 0) && a.p9();\n        sum += (a.p4() == 0) && a.p5();\n        sum += (a.p7() == 0) && a.p8();\n        sum += (a.p6() == 0) && a.p7();\n        sum += (a.p5() == 0) && a.p6();\n        return sum;\n    }\n\n    \n    unsigned black_pixels(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += a.p9();\n        sum += a.p2();\n        sum += a.p3();\n        sum += a.p8();\n        sum += a.p4();\n        sum += a.p7();\n        sum += a.p6();\n        sum += a.p5();\n        return sum;\n    }\n    const Image& operator()(const Image& img) {\n        tmp_a_ = img;\n        size_t changed_pixels = 0;\n        do {\n            changed_pixels = 0;\n            \n            tmp_b_ = tmp_a_;\n            for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n                    if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n                        auto n = tmp_a_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p6() == 0)\n                                && (n.p4() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_b_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n            \n            tmp_a_ = tmp_b_;\n            for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n                    if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n                        auto n = tmp_b_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p8() == 0)\n                                && (n.p2() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_a_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n        } while(changed_pixels > 0);\n        return tmp_a_;\n    }\nprivate:\n    Image tmp_a_;\n    Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n    using namespace std;\n    Image img(32, 10);\n    istringstream iss{input};\n    iss >> img;\n    cout << img;\n    cout << \"ZhangSuen\" << endl;\n    ZhangSuen zs;\n    Image res = std::move(zs(img));\n    cout << res << endl;\n\n    Image img2(58,18);\n    istringstream iss2{input2};\n    iss2 >> img2;\n    cout << img2;\n    cout << \"ZhangSuen with big image\" << endl;\n    Image res2 = std::move(zs(img2));\n    cout << res2 << endl;\n    return 0;\n}\n"}
{"id": 54875, "name": "Variable declaration reset", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n"}
{"id": 54876, "name": "Numbers with equal rises and falls", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n"}
{"id": 54877, "name": "Koch curve", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54878, "name": "Words from neighbour ones", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54879, "name": "Magic squares of singly even order", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n"}
{"id": 54880, "name": "Generate Chess960 starting position", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n"}
{"id": 54881, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "C++": "int meaning_of_life();\n"}
{"id": 54882, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "C++": "int meaning_of_life();\n"}
{"id": 54883, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 54884, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 54885, "name": "Pseudo-random numbers_Xorshift star", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54886, "name": "Four is the number of letters in the ...", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class FourIsTheNumberOfLetters {\n\n    public static void main(String[] args) {\n        String [] words = neverEndingSentence(201);\n        System.out.printf(\"Display the first 201 numbers in the sequence:%n%3d: \", 1);\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            System.out.printf(\"%2d \", numberOfLetters(words[i]));\n            if ( (i+1) % 25 == 0 ) {\n                System.out.printf(\"%n%3d: \", i+2);\n            }\n        }\n        System.out.printf(\"%nTotal number of characters in the sentence is %d%n\", characterCount(words));\n        for ( int i = 3 ; i <= 7 ; i++ ) {\n            int index = (int) Math.pow(10, i);\n            words = neverEndingSentence(index);\n            String last = words[words.length-1].replace(\",\", \"\");\n            System.out.printf(\"Number of letters of the %s word is %d. The word is \\\"%s\\\".  The sentence length is %,d characters.%n\", toOrdinal(index), numberOfLetters(last), last, characterCount(words));\n        }\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static void displaySentence(String[] words, int lineLength) {\n        int currentLength = 0;\n        for ( String word : words ) {\n            if ( word.length() + currentLength > lineLength ) {\n                String first = word.substring(0, lineLength-currentLength);\n                String second = word.substring(lineLength-currentLength);\n                System.out.println(first);\n                System.out.print(second);\n                currentLength = second.length();\n            }\n            else {\n                System.out.print(word);\n                currentLength += word.length();\n            }\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n            System.out.print(\" \");\n            currentLength++;\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n        }\n        System.out.println();\n    }\n    \n    private static int numberOfLetters(String word) {\n        return word.replace(\",\",\"\").replace(\"-\",\"\").length();\n    }\n    \n    private static long characterCount(String[] words) {\n        int characterCount = 0;\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            characterCount += words[i].length() + 1;\n        }        \n        \n        characterCount--;\n        return characterCount;\n    }\n    \n    private static String[] startSentence = new String[] {\"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\", \"first\", \"word\", \"of\", \"this\", \"sentence,\"};\n    \n    private static String[] neverEndingSentence(int wordCount) {\n        String[] words = new String[wordCount];\n        int index;\n        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {\n            words[index] = startSentence[index];\n        }\n        int sentencePosition = 1;\n        while ( index < wordCount ) {\n            \n            \n            sentencePosition++;\n            String word = words[sentencePosition-1];\n            for ( String wordLoop : numToString(numberOfLetters(word)).split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n            \n            words[index] = \"in\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            words[index] = \"the\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            for ( String wordLoop : (toOrdinal(sentencePosition) + \",\").split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n        }\n        return words;\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n    \n}\n", "C++": "#include <cctype>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        result.push_back(get_name(small[n], ordinal));\n        count = 1;\n    }\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result.push_back(get_name(tens[n/10 - 2], ordinal));\n        } else {\n            std::string name(get_name(tens[n/10 - 2], false));\n            name += \"-\";\n            name += get_name(small[n % 10], ordinal);\n            result.push_back(name);\n        }\n        count = 1;\n    } else {\n        const named_number& num = get_named_number(n);\n        uint64_t p = num.number;\n        count += append_number_name(result, n/p, false);\n        if (n % p == 0) {\n            result.push_back(get_name(num, ordinal));\n            ++count;\n        } else {\n            result.push_back(get_name(num, false));\n            ++count;\n            count += append_number_name(result, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(const std::string& str) {\n    size_t letters = 0;\n    for (size_t i = 0, n = str.size(); i < n; ++i) {\n        if (isalpha(static_cast<unsigned char>(str[i])))\n            ++letters;\n    }\n    return letters;\n}\n\nstd::vector<std::string> sentence(size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    std::vector<std::string> result;\n    result.reserve(count + 10);\n    size_t n = std::size(words);\n    for (size_t i = 0; i < n && i < count; ++i) {\n        result.push_back(words[i]);\n    }\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result[i]), false);\n        result.push_back(\"in\");\n        result.push_back(\"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        result.back() += ',';\n    }\n    return result;\n}\n\nsize_t sentence_length(const std::vector<std::string>& words) {\n    size_t n = words.size();\n    if (n == 0)\n        return 0;\n    size_t length = n - 1;\n    for (size_t i = 0; i < n; ++i)\n        length += words[i].size();\n    return length;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    size_t n = 201;\n    auto result = sentence(n);\n    std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            std::cout << (i % 25 == 0 ? '\\n' : ' ');\n        std::cout << std::setw(2) << count_letters(result[i]);\n    }\n    std::cout << '\\n';\n    std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    for (n = 1000; n <= 10000000; n *= 10) {\n        result = sentence(n);\n        const std::string& word = result[n - 1];\n        std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n            << count_letters(word) << \" letters. \";\n        std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54887, "name": "ASCII art diagram converter", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n"}
{"id": 54888, "name": "Same fringe", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n"}
{"id": 54889, "name": "Peaceful chess queen armies", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 54890, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 54891, "name": "Test integerness", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n"}
{"id": 54892, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "C++": "system(\"pause\");\n"}
{"id": 54893, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 54894, "name": "Lucky and even lucky numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nconst int luckySize = 60000;\nstd::vector<int> luckyEven(luckySize);\nstd::vector<int> luckyOdd(luckySize);\n\nvoid init() {\n    for (int i = 0; i < luckySize; ++i) {\n        luckyEven[i] = i * 2 + 2;\n        luckyOdd[i] = i * 2 + 1;\n    }\n}\n\nvoid filterLuckyEven() {\n    for (size_t n = 2; n < luckyEven.size(); ++n) {\n        int m = luckyEven[n - 1];\n        int end = (luckyEven.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n            luckyEven.pop_back();\n        }\n    }\n}\n\nvoid filterLuckyOdd() {\n    for (size_t n = 2; n < luckyOdd.size(); ++n) {\n        int m = luckyOdd[n - 1];\n        int end = (luckyOdd.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n            luckyOdd.pop_back();\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n\n    if (even) {\n        size_t max = luckyEven.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    } else {\n        size_t max = luckyOdd.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    }\n    std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n    if (even) {\n        if (k >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n    } else {\n        if (k >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n    }\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (j >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n    } else {\n        if (j >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n    }\n}\n\nvoid help() {\n    std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"       argument(s)        |  what is displayed\\n\";\n    std::cout << \"==============================================\\n\";\n    std::cout << \"-j=m                      |  mth lucky number\\n\";\n    std::cout << \"-j=m  --lucky             |  mth lucky number\\n\";\n    std::cout << \"-j=m  --evenLucky         |  mth even lucky number\\n\";\n    std::cout << \"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\";\n    std::cout << \"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    \n    if (argc < 2) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    bool good = false;\n    for (int i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n            exit(EXIT_FAILURE);\n        }\n    }\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    init();\n    filterLuckyEven();\n    filterLuckyOdd();\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n\n    return 0;\n}\n"}
{"id": 54895, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 54896, "name": "Superpermutation minimisation", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54897, "name": "GUI component interaction", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n"}
{"id": 54898, "name": "One of n lines in a file", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 54899, "name": "Summarize and say sequence", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 54900, "name": "Spelling of ordinal numbers", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 54901, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 54902, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 54903, "name": "Numeric separator syntax", "Java": "public class NumericSeparatorSyntax {\n\n    public static void main(String[] args) {\n        runTask(\"Underscore allowed as seperator\", 1_000);\n        runTask(\"Multiple consecutive underscores allowed:\", 1__0_0_0);\n        runTask(\"Many multiple consecutive underscores allowed:\", 1________________________00);\n        runTask(\"Underscores allowed in multiple positions\", 1__4__4);\n        runTask(\"Underscores allowed in negative number\", -1__4__4);\n        runTask(\"Underscores allowed in floating point number\", 1__4__4e-5);\n        runTask(\"Underscores allowed in floating point exponent\", 1__4__440000e-1_2);\n        \n        \n        \n        \n    }\n    \n    private static void runTask(String description, long n) {\n        runTask(description, n, \"%d\");\n    }\n\n    private static void runTask(String description, double n) {\n        runTask(description, n, \"%3.7f\");\n    }\n\n    private static void runTask(String description, Number n, String format) {\n        System.out.printf(\"%s:  \" + format + \"%n\", description, n);\n    }\n\n}\n", "C++": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n"}
{"id": 54904, "name": "Repeat", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n"}
{"id": 54905, "name": "Sparkline in unicode", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n"}
{"id": 54906, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 54907, "name": "Sunflower fractal", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54908, "name": "Vogel's approximation method", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n"}
{"id": 54909, "name": "Permutations by swapping", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n"}
{"id": 54910, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n"}
{"id": 54911, "name": "Dice game probabilities", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n"}
{"id": 54912, "name": "Sokoban", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n"}
{"id": 54913, "name": "Practical numbers", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n"}
{"id": 54914, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n"}
{"id": 54915, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 54916, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 54917, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 54918, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 54919, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 54920, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 54921, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 54922, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 54923, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 54924, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 54925, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 54926, "name": "Word search", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n"}
{"id": 54927, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 54928, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 54929, "name": "Object serialization", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n"}
{"id": 54930, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 54931, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 54932, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n"}
{"id": 54933, "name": "Zumkeller numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n"}
{"id": 54934, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 54935, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 54936, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 54937, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 54938, "name": "Constrained genericity", "Java": "interface Eatable\n{\n    void eat();\n}\n", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n"}
{"id": 54939, "name": "Markov chain text generator", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n"}
{"id": 54940, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n"}
{"id": 54941, "name": "Geometric algebra", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n"}
{"id": 54942, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 54943, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 54944, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n"}
{"id": 54945, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n"}
{"id": 54946, "name": "AVL tree", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n"}
{"id": 54947, "name": "AVL tree", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n"}
{"id": 54948, "name": "Penrose tiling", "Java": "import java.awt.*;\nimport java.util.List;\nimport java.awt.geom.Path2D;\nimport java.util.*;\nimport javax.swing.*;\nimport static java.lang.Math.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class PenroseTiling extends JPanel {\n    \n    class Tile {\n        double x, y, angle, size;\n        Type type;\n\n        Tile(Type t, double x, double y, double a, double s) {\n            type = t;\n            this.x = x;\n            this.y = y;\n            angle = a;\n            size = s;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Tile) {\n                Tile t = (Tile) o;\n                return type == t.type && x == t.x && y == t.y && angle == t.angle;\n            }\n            return false;\n        }\n    }\n\n    enum Type {\n        Kite, Dart\n    }\n\n    static final double G = (1 + sqrt(5)) / 2; \n    static final double T = toRadians(36); \n\n    List<Tile> tiles = new ArrayList<>();\n\n    public PenroseTiling() {\n        int w = 700, h = 450;\n        setPreferredSize(new Dimension(w, h));\n        setBackground(Color.white);\n\n        tiles = deflateTiles(setupPrototiles(w, h), 5);\n    }\n\n    List<Tile> setupPrototiles(int w, int h) {\n        List<Tile> proto = new ArrayList<>();\n\n        \n        for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)\n            proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));\n\n        return proto;\n    }\n\n    List<Tile> deflateTiles(List<Tile> tls, int generation) {\n        if (generation <= 0)\n            return tls;\n\n        List<Tile> next = new ArrayList<>();\n\n        for (Tile tile : tls) {\n            double x = tile.x, y = tile.y, a = tile.angle, nx, ny;\n            double size = tile.size / G;\n\n            if (tile.type == Type.Dart) {\n                next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    nx = x + cos(a - 4 * T * sign) * G * tile.size;\n                    ny = y - sin(a - 4 * T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));\n                }\n\n            } else {\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));\n\n                    nx = x + cos(a - T * sign) * G * tile.size;\n                    ny = y - sin(a - T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));\n                }\n            }\n        }\n        \n        tls = next.stream().distinct().collect(toList());\n\n        return deflateTiles(tls, generation - 1);\n    }\n\n    void drawTiles(Graphics2D g) {\n        double[][] dist = {{G, G, G}, {-G, -1, -G}};\n        for (Tile tile : tiles) {\n            double angle = tile.angle - T;\n            Path2D path = new Path2D.Double();\n            path.moveTo(tile.x, tile.y);\n\n            int ord = tile.type.ordinal();\n            for (int i = 0; i < 3; i++) {\n                double x = tile.x + dist[ord][i] * tile.size * cos(angle);\n                double y = tile.y - dist[ord][i] * tile.size * sin(angle);\n                path.lineTo(x, y);\n                angle += T;\n            }\n            path.closePath();\n            g.setColor(ord == 0 ? Color.orange : Color.yellow);\n            g.fill(path);\n            g.setColor(Color.darkGray);\n            g.draw(path);\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics og) {\n        super.paintComponent(og);\n        Graphics2D g = (Graphics2D) og;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        drawTiles(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(\"Penrose Tiling\");\n            f.setResizable(false);\n            f.add(new PenroseTiling(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n\nint main() {\n    std::ofstream out(\"penrose_tiling.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string penrose(\"[N]++[N]++[N]++[N]++[N]\");\n    for (int i = 1; i <= 4; ++i) {\n        std::string next;\n        for (char ch : penrose) {\n            switch (ch) {\n            case 'A':\n                break;\n            case 'M':\n                next += \"OA++PA----NA[-OA----MA]++\";\n                break;\n            case 'N':\n                next += \"+OA--PA[---MA--NA]+\";\n                break;\n            case 'O':\n                next += \"-MA++NA[+++OA++PA]-\";\n                break;\n            case 'P':\n                next += \"--OA++++MA[+PA++++NA]--NA\";\n                break;\n            default:\n                next += ch;\n                break;\n            }\n        }\n        penrose = std::move(next);\n    }\n    const double r = 30;\n    const double pi5 = 0.628318530717959;\n    double x = r * 8, y = r * 8, theta = pi5;\n    std::set<std::string> svg;\n    std::stack<std::tuple<double, double, double>> stack;\n    for (char ch : penrose) {\n        switch (ch) {\n        case 'A': {\n            double nx = x + r * std::cos(theta);\n            double ny = y + r * std::sin(theta);\n            std::ostringstream line;\n            line << std::fixed << std::setprecision(3) << \"<line x1='\" << x\n                 << \"' y1='\" << y << \"' x2='\" << nx << \"' y2='\" << ny << \"'/>\";\n            svg.insert(line.str());\n            x = nx;\n            y = ny;\n        } break;\n        case '+':\n            theta += pi5;\n            break;\n        case '-':\n            theta -= pi5;\n            break;\n        case '[':\n            stack.push({x, y, theta});\n            break;\n        case ']':\n            std::tie(x, y, theta) = stack.top();\n            stack.pop();\n            break;\n        }\n    }\n    out << \"<svg xmlns='http:\n        << \"' width='\" << r * 16 << \"'>\\n\"\n        << \"<rect height='100%' width='100%' fill='black'/>\\n\"\n        << \"<g stroke='rgb(255,165,0)'>\\n\";\n    for (const auto& line : svg)\n        out << line << '\\n';\n    out << \"</g>\\n</svg>\\n\";\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54949, "name": "Sphenic numbers", "Java": "import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SphenicNumbers {\n    public static void main(String[] args) {\n        final int limit = 1000000;\n        final int imax = limit / 6;\n        boolean[] sieve = primeSieve(imax + 1);\n        boolean[] sphenic = new boolean[limit + 1];\n        for (int i = 0; i <= imax; ++i) {\n            if (!sieve[i])\n                continue;\n            int jmax = Math.min(imax, limit / (i * i));\n            if (jmax <= i)\n                break;\n            for (int j = i + 1; j <= jmax; ++j) {\n                if (!sieve[j])\n                    continue;\n                int p = i * j;\n                int kmax = Math.min(imax, limit / p);\n                if (kmax <= j)\n                    break;\n                for (int k = j + 1; k <= kmax; ++k) {\n                    if (!sieve[k])\n                        continue;\n                    assert(p * k <= limit);\n                    sphenic[p * k] = true;\n                }\n            }\n        }\n    \n        System.out.println(\"Sphenic numbers < 1000:\");\n        for (int i = 0, n = 0; i < 1000; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++n;\n            System.out.printf(\"%3d%c\", i, n % 15 == 0 ? '\\n' : ' ');\n        }\n    \n        System.out.println(\"\\nSphenic triplets < 10,000:\");\n        for (int i = 0, n = 0; i < 10000; ++i) {\n            if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n                ++n;\n                System.out.printf(\"(%d, %d, %d)%c\",\n                                  i - 2, i - 1, i, n % 3 == 0 ? '\\n' : ' ');\n            }\n        }\n    \n        int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n        for (int i = 0; i < limit; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++count;\n            if (count == 200000)\n                s200000 = i;\n            if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n                ++triplets;\n                if (triplets == 5000)\n                    t5000 = i;\n            }\n        }\n    \n        System.out.printf(\"\\nNumber of sphenic numbers < 1,000,000: %d\\n\", count);\n        System.out.printf(\"Number of sphenic triplets < 1,000,000: %d\\n\", triplets);\n    \n        List<Integer> factors = primeFactors(s200000);\n        assert(factors.size() == 3);\n        System.out.printf(\"The 200,000th sphenic number: %d = %d * %d * %d\\n\",\n                          s200000, factors.get(0), factors.get(1),\n                          factors.get(2));\n        System.out.printf(\"The 5,000th sphenic triplet: (%d, %d, %d)\\n\",\n                          t5000 - 2, t5000 - 1, t5000);\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3, sq = 9; sq < limit; p += 2) {\n            if (sieve[p]) {\n                for (int q = sq; q < limit; q += p << 1)\n                    sieve[q] = false;\n            }\n            sq += (p + 1) << 2;\n        }\n        return sieve;\n    }\n    \n    private static List<Integer> primeFactors(int n) {\n        List<Integer> factors = new ArrayList<>();\n        if (n > 1 && (n & 1) == 0) {\n            factors.add(2);\n            while ((n & 1) == 0)\n                n >>= 1;\n        }\n        for (int p = 3; p * p <= n; p += 2) {\n            if (n % p == 0) {\n                factors.add(p);\n                while (n % p == 0)\n                    n /= p;\n            }\n        }\n        if (n > 1)\n            factors.add(n);\n        return factors;\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nstd::vector<int> prime_factors(int n) {\n    std::vector<int> factors;\n    if (n > 1 && (n & 1) == 0) {\n        factors.push_back(2);\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            factors.push_back(p);\n            while (n % p == 0)\n                n /= p;\n        }\n    }\n    if (n > 1)\n        factors.push_back(n);\n    return factors;\n}\n\nint main() {\n    const int limit = 1000000;\n    const int imax = limit / 6;\n    std::vector<bool> sieve = prime_sieve(imax + 1);\n    std::vector<bool> sphenic(limit + 1, false);\n    for (int i = 0; i <= imax; ++i) {\n        if (!sieve[i])\n            continue;\n        int jmax = std::min(imax, limit / (i * i));\n        if (jmax <= i)\n            break;\n        for (int j = i + 1; j <= jmax; ++j) {\n            if (!sieve[j])\n                continue;\n            int p = i * j;\n            int kmax = std::min(imax, limit / p);\n            if (kmax <= j)\n                break;\n            for (int k = j + 1; k <= kmax; ++k) {\n                if (!sieve[k])\n                    continue;\n                assert(p * k <= limit);\n                sphenic[p * k] = true;\n            }\n        }\n    }\n\n    std::cout << \"Sphenic numbers < 1000:\\n\";\n    for (int i = 0, n = 0; i < 1000; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++n;\n        std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n    for (int i = 0, n = 0; i < 10000; ++i) {\n        if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n            ++n;\n            std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n                      << (n % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n\n    int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n    for (int i = 0; i < limit; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++count;\n        if (count == 200000)\n            s200000 = i;\n        if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n            ++triplets;\n            if (triplets == 5000)\n                t5000 = i;\n        }\n    }\n\n    std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n    std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n    auto factors = prime_factors(s200000);\n    assert(factors.size() == 3);\n    std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n              << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n              << '\\n';\n\n    std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n              << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}\n"}
{"id": 54950, "name": "Find duplicate files", "Java": "import java.io.*;\nimport java.nio.*;\nimport java.nio.file.*;\nimport java.nio.file.attribute.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class DuplicateFiles {\n    public static void main(String[] args) {\n        if (args.length != 2) {\n            System.err.println(\"Directory name and minimum file size are required.\");\n            System.exit(1);\n        }\n        try {\n            findDuplicateFiles(args[0], Long.parseLong(args[1]));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void findDuplicateFiles(String directory, long minimumSize)\n        throws IOException, NoSuchAlgorithmException {\n        System.out.println(\"Directory: '\" + directory + \"', minimum size: \" + minimumSize + \" bytes.\");\n        Path path = FileSystems.getDefault().getPath(directory);\n        FileVisitor visitor = new FileVisitor(path, minimumSize);\n        Files.walkFileTree(path, visitor);\n        System.out.println(\"The following sets of files have the same size and checksum:\");\n        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {\n            Map<Object, List<String>> map = e.getValue();\n            if (!containsDuplicates(map))\n                continue;\n            List<List<String>> fileSets = new ArrayList<>(map.values());\n            for (List<String> files : fileSets)\n                Collections.sort(files);\n            Collections.sort(fileSets, new StringListComparator());\n            FileKey key = e.getKey();\n            System.out.println();\n            System.out.println(\"Size: \" + key.size_ + \" bytes\");\n            for (List<String> files : fileSets) {\n                for (int i = 0, n = files.size(); i < n; ++i) {\n                    if (i > 0)\n                        System.out.print(\" = \");\n                    System.out.print(files.get(i));\n                }\n                System.out.println();\n            }\n        }\n    }\n\n    private static class StringListComparator implements Comparator<List<String>> {\n        public int compare(List<String> a, List<String> b) {\n            int len1 = a.size(), len2 = b.size();\n            for (int i = 0; i < len1 && i < len2; ++i) {\n                int c = a.get(i).compareTo(b.get(i));\n                if (c != 0)\n                    return c;\n            }\n            return Integer.compare(len1, len2);\n        }\n    }\n\n    private static boolean containsDuplicates(Map<Object, List<String>> map) {\n        if (map.size() > 1)\n            return true;\n        for (List<String> files : map.values()) {\n            if (files.size() > 1)\n                return true;\n        }\n        return false;\n    }\n\n    private static class FileVisitor extends SimpleFileVisitor<Path> {\n        private MessageDigest digest_;\n        private Path directory_;\n        private long minimumSize_;\n        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();\n\n        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {\n            directory_ = directory;\n            minimumSize_ = minimumSize;\n            digest_ = MessageDigest.getInstance(\"MD5\");\n        }\n\n        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n            if (attrs.size() >= minimumSize_) {\n                FileKey key = new FileKey(file, attrs, getMD5Sum(file));\n                Map<Object, List<String>> map = fileMap_.get(key);\n                if (map == null)\n                    fileMap_.put(key, map = new HashMap<>());\n                List<String> files = map.get(attrs.fileKey());\n                if (files == null)\n                    map.put(attrs.fileKey(), files = new ArrayList<>());\n                Path relative = directory_.relativize(file);\n                files.add(relative.toString());\n            }\n            return FileVisitResult.CONTINUE;\n        }\n\n        private byte[] getMD5Sum(Path file) throws IOException {\n            digest_.reset();\n            try (InputStream in = new FileInputStream(file.toString())) {\n                byte[] buffer = new byte[8192];\n                int bytes;\n                while ((bytes = in.read(buffer)) != -1) {\n                    digest_.update(buffer, 0, bytes);\n                }\n            }\n            return digest_.digest();\n        }\n    }\n\n    private static class FileKey implements Comparable<FileKey> {\n        private byte[] hash_;\n        private long size_;\n\n        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {\n            size_ = attrs.size();\n            hash_ = hash;\n        }\n\n        public int compareTo(FileKey other) {\n            int c = Long.compare(other.size_, size_);\n            if (c == 0)\n                c = hashCompare(hash_, other.hash_);\n            return c;\n        }\n    }\n\n    private static int hashCompare(byte[] a, byte[] b) {\n        int len1 = a.length, len2 = b.length;\n        for (int i = 0; i < len1 && i < len2; ++i) {\n            int c = Byte.compare(a[i], b[i]);\n            if (c != 0)\n                return c;\n        }\n        return Integer.compare(len1, len2);\n    }\n}\n", "C++": "#include<iostream>\n#include<string>\n#include<boost/filesystem.hpp>\n#include<boost/format.hpp>\n#include<boost/iostreams/device/mapped_file.hpp>\n#include<optional>\n#include<algorithm>\n#include<iterator>\n#include<execution>\n#include\"dependencies/xxhash.hpp\" \n\n\ntemplate<typename  T, typename V, typename F>\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n    size_t partitions = 0;\n    while (begin != end) {\n        auto const& value = getvalue(*begin);\n        auto current = begin;\n        while (++current != end && getvalue(*current) == value);\n        callback(begin, current, value);\n        ++partitions;\n        begin = current;\n    }\n    return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n    explicit file_entry(fs::directory_entry const & entry) \n        : path_{entry.path()}, size_{fs::file_size(entry)}\n    {}\n    auto size() const { return size_; }\n    auto const& path() const { return path_; }\n    auto get_hash() {\n        if (!hash_)\n            hash_ = compute_hash();\n        return *hash_;\n    }\nprivate:\n    xxh::hash64_t compute_hash() {\n        bi::mapped_file_source source;\n        source.open<fs::wpath>(this->path());\n        if (!source.is_open()) {\n            std::cerr << \"Cannot open \" << path() << std::endl;\n            throw std::runtime_error(\"Cannot open file\");\n        }\n        xxh::hash_state64_t hash_stream;\n        hash_stream.update(source.data(), size_);\n        return hash_stream.digest();\n    }\nprivate:\n    fs::wpath path_;\n    uintmax_t size_;\n    std::optional<xxh::hash64_t> hash_;\n};\n\nusing vector_type = std::vector<file_entry>;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n    size_t found = 0, ignored = 0;\n    if (!fs::is_directory(path)) {\n        std::cerr << path << \" is not a directory!\" << std::endl;\n    }\n    else {\n        std::cerr << \"Searching \" << path << std::endl;\n\n        for (auto& e : fs::recursive_directory_iterator(path)) {\n            ++found;\n            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n                file_vector.emplace_back(e);\n            else ++ignored;\n        }\n    }\n    return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n    vector_type files;\n    for (auto i = 1; i < argn; ++i) {\n        fs::wpath path(argv[i]);\n        auto [found, ignored] = find_files_in_dir(path, files);\n        std::cerr << boost::format{\n            \"  %1$6d files found\\n\"\n            \"  %2$6d files ignored\\n\"\n            \"  %3$6d files added\\n\" } % found % ignored % (found - ignored) \n            << std::endl;\n    }\n\n    std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n    \n    std::sort(std::execution::par_unseq, files.begin(), files.end()\n        , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n    );\n    for_each_adjacent_range(\n        std::begin(files)\n        , std::end(files)\n        , [](vector_type::value_type const& f) { return f.size(); }\n        , [](auto start, auto end, auto file_size) {\n            \n            size_t nr_of_files = std::distance(start, end);\n            if (nr_of_files > 1) {\n                \n                std::sort(start, end, [](auto& a, auto& b) { \n                    auto const& ha = a.get_hash();\n                    auto const& hb = b.get_hash();\n                    auto const& pa = a.path();\n                    auto const& pb = b.path();\n                    return std::tie(ha, pa) < std::tie(hb, pb); \n                    });\n                for_each_adjacent_range(\n                    start\n                    , end\n                    , [](vector_type::value_type& f) { return f.get_hash(); }\n                    , [file_size](auto hstart, auto hend, auto hash) {\n                        \n                        \n                        size_t hnr_of_files = std::distance(hstart, hend);\n                        if (hnr_of_files > 1) {\n                            std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n                                % hnr_of_files % file_size % hash;\n                            std::for_each(hstart, hend, [hash, file_size](auto& e) {\n                                std::cout << '\\t' << e.path() << '\\n';\n                                }\n                            );\n                        }\n                    }\n                );\n            }\n        }\n    );\n    \n    return 0;\n}\n"}
{"id": 54951, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 54952, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 54953, "name": "Order disjoint list items", "Java": "import java.util.Arrays;\nimport java.util.BitSet;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class OrderDisjointItems {\n\n    public static void main(String[] args) {\n        final String[][] MNs = {{\"the cat sat on the mat\", \"mat cat\"},\n        {\"the cat sat on the mat\", \"cat mat\"},\n        {\"A B C A B C A B C\", \"C A C A\"}, {\"A B C A B D A B E\", \"E A D A\"},\n        {\"A B\", \"B\"}, {\"A B\", \"B A\"}, {\"A B B A\", \"B A\"}, {\"X X Y\", \"X\"}};\n\n        for (String[] a : MNs) {\n            String[] r = orderDisjointItems(a[0].split(\" \"), a[1].split(\" \"));\n            System.out.printf(\"%s | %s -> %s%n\", a[0], a[1], Arrays.toString(r));\n        }\n    }\n\n    \n    static String[] orderDisjointItems(String[] m, String[] n) {\n        for (String e : n) {\n            int idx = ArrayUtils.indexOf(m, e);\n            if (idx != -1)\n                m[idx] = null;\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (m[i] == null)\n                m[i] = n[j++];\n        }\n        return m;\n    }\n\n    \n    static String[] orderDisjointItems2(String[] m, String[] n) {\n        BitSet bitSet = new BitSet(m.length);\n        for (String e : n) {\n            int idx = -1;\n            do {\n                idx = ArrayUtils.indexOf(m, e, idx + 1);\n            } while (idx != -1 && bitSet.get(idx));\n            if (idx != -1)\n                bitSet.set(idx);\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (bitSet.get(i))\n                m[i] = n[j++];\n        }\n        return m;\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\ntemplate <typename T>\nvoid print(const std::vector<T> v) {\n  std::cout << \"{ \";\n  for (const auto& e : v) {\n    std::cout << e << \" \";\n  }\n  std::cout << \"}\";\n}\n\ntemplate <typename T>\nauto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {\n  std::vector<T*> M_p(std::size(M));\n  for (auto i = 0; i < std::size(M_p); ++i) {\n    M_p[i] = &M[i];\n  }\n  for (auto e : N) {\n    auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {\n      if (c != nullptr) {\n        if (*c == e) return true;\n      }\n      return false;\n    });\n    if (i != std::end(M_p)) {\n      *i = nullptr;\n    }\n  }\n  for (auto i = 0; i < std::size(N); ++i) {\n    auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {\n      return c == nullptr;\n    });\n    if (j != std::end(M_p)) {\n      *j = &M[std::distance(std::begin(M_p), j)];\n      **j = N[i];\n    }\n  }\n  return M;\n}\n\nint main() {\n  std::vector<std::vector<std::vector<std::string>>> l = {\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" }, { \"mat\", \"cat\" } },\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" },{ \"cat\", \"mat\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"C\", \"A\", \"B\", \"C\" },{ \"C\", \"A\", \"C\", \"A\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"D\", \"A\", \"B\", \"E\" },{ \"E\", \"A\", \"D\", \"A\" } },\n    { { \"A\", \"B\" },{ \"B\" } },\n    { { \"A\", \"B\" },{ \"B\", \"A\" } },\n    { { \"A\", \"B\", \"B\", \"A\" },{ \"B\", \"A\" } }\n  };\n  for (const auto& e : l) {\n    std::cout << \"M: \";\n    print(e[0]);\n    std::cout << \", N: \";\n    print(e[1]);\n    std::cout << \", M': \";\n    auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);\n    print(res);\n    std::cout << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 54954, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 54955, "name": "Here document", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 54956, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 54957, "name": "Ramanujan primes", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n"}
{"id": 54958, "name": "Ramanujan primes", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n"}
{"id": 54959, "name": "Ramanujan primes", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n"}
{"id": 54960, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n"}
{"id": 54961, "name": "Sierpinski curve", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n"}
{"id": 54962, "name": "Most frequent k chars distance", "Java": "import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class SDF {\n\n    \n    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {\n\n        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();\n\n        for (char element : array) {\n            Integer count = countMap.get(element);\n            count = (count == null) ? 1 : count + 1;\n            countMap.put(element, count);\n        }\n\n        return countMap;\n    }\n    \n    \n    private static <K, V extends Comparable<? super V>>\n            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { \n\tList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());\n\t\n\tCollections.sort(list, new Comparator<Map.Entry<K, V>>() {\n\t\tpublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n\t\t    return o2.getValue().compareTo(o1.getValue());\n\t\t}\n\t    });\n\n\t\n\t\n\tHashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();\n\tfor (Map.Entry<K, V> entry : list) {\n\t    sortedHashMap.put(entry.getKey(), entry.getValue());\n\t} \n\treturn sortedHashMap;\n    }\n    \n    public static String mostOcurrencesElement(char[] array, int k) {\n        HashMap<Character, Integer> countMap = countElementOcurrences(array);\n        System.out.println(countMap);\n        Map<Character, Integer> map = descendingSortByValues(countMap); \n        System.out.println(map);\n        int i = 0;\n        String output = \"\";\n        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {\n\t    if (i++ >= k)\n\t\tbreak;\n            output += \"\" + pairs.getKey() + pairs.getValue();\n        }\n        return output;\n    }\n    \n    public static int getDiff(String str1, String str2, int limit) {\n        int similarity = 0;\n\tint k = 0;\n\tfor (int i = 0; i < str1.length() ; i = k) {\n\t    k ++;\n\t    if (Character.isLetter(str1.charAt(i))) {\n\t\tint pos = str2.indexOf(str1.charAt(i));\n\t\t\t\t\n\t\tif (pos >= 0) {\t\n\t\t    String digitStr1 = \"\";\n\t\t    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {\n\t\t\tdigitStr1 += str1.charAt(k);\n\t\t\tk++;\n\t\t    }\n\t\t\t\t\t\n\t\t    int k2 = pos+1;\n\t\t    String digitStr2 = \"\";\n\t\t    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {\n\t\t\tdigitStr2 += str2.charAt(k2);\n\t\t\tk2++;\n\t\t    }\n\t\t\t\t\t\n\t\t    similarity += Integer.parseInt(digitStr2)\n\t\t\t+ Integer.parseInt(digitStr1);\n\t\t\t\t\t\n\t\t} \n\t    }\n\t}\n\treturn Math.abs(limit - similarity);\n    }\n    \n    public static int SDFfunc(String str1, String str2, int limit) {\n        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);\n    }\n\n    public static void main(String[] args) {\n        String input1 = \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\";\n        String input2 = \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\";\n        System.out.println(SDF.SDFfunc(input1,input2,100));\n\n    }\n\n}\n", "C++": "#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <sstream>\n\nstd::string mostFreqKHashing ( const std::string & input , int k ) {\n   std::ostringstream oss ;\n   std::map<char, int> frequencies ;\n   for ( char c : input ) {\n      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;\n   }\n   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;\n   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,\n\t         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; \n\t         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }\n\t         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;\n   for ( int i = 0 ; i < letters.size( ) ; i++ ) {\n      oss << std::get<0>( letters[ i ] ) ;\n      oss << std::get<1>( letters[ i ] ) ;\n   }\n   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;\n   if ( letters.size( ) >= k ) {\n      return output ;\n   }\n   else {\n      return output.append( \"NULL0\" ) ;\n   }\n}\n\nint mostFreqKSimilarity ( const std::string & first , const std::string & second ) {\n   int i = 0 ;\n   while ( i < first.length( ) - 1  ) {\n      auto found = second.find_first_of( first.substr( i , 2 ) ) ;\n      if ( found != std::string::npos ) \n\t return std::stoi ( first.substr( i , 2 )) ;\n      else \n\t i += 2 ;\n   }\n   return 0 ;\n}\n\nint mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {\n   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;\n}\n\nint main( ) {\n   std::string s1(\"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\" ) ;\n   std::string s2( \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\" ) ;\n   std::cout << \"MostFreqKHashing( s1 , 2 ) = \" << mostFreqKHashing( s1 , 2 ) << '\\n' ;\n   std::cout << \"MostFreqKHashing( s2 , 2 ) = \" << mostFreqKHashing( s2 , 2 ) << '\\n' ;\n   return 0 ;\n}\n"}
{"id": 54963, "name": "Text completion", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\n\n\npublic class textCompletionConcept {\n    public static int correct = 0;\n    public static ArrayList<String> listed = new ArrayList<>();\n    public static void main(String[]args) throws IOException, URISyntaxException {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Input word: \");\n        String errorRode = input.next();\n        File file = new File(new \n        File(textCompletionConcept.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath() + File.separator + \"words.txt\");\n        Scanner reader = new Scanner(file);\n        while(reader.hasNext()){\n            double percent;\n            String compareToThis = reader.nextLine();\n                    char[] s1 = errorRode.toCharArray();\n                    char[] s2 = compareToThis.toCharArray();\n                    int maxlen = Math.min(s1.length, s2.length);\n                    for (int index = 0; index < maxlen; index++) {\n                        String x = String.valueOf(s1[index]);\n                        String y = String.valueOf(s2[index]);\n                        if (x.equals(y)) {\n                            correct++;\n                        }\n                    }\n                    double length = Math.max(s1.length, s2.length);\n                    percent = correct / length;\n                    percent *= 100;\n                    boolean perfect = false;\n                    if (percent >= 80 && compareToThis.charAt(0) == errorRode.charAt(0)) {\n                        if(String.valueOf(percent).equals(\"100.00\")){\n                            perfect = true;\n                        }\n                        String addtoit = compareToThis + \" : \" + String.format(\"%.2f\", percent) + \"% similar.\";\n                        listed.add(addtoit);\n                    }\n                    if(compareToThis.contains(errorRode) && !perfect && errorRode.length() * 2 > compareToThis.length()){\n                        String addtoit = compareToThis + \" : 80.00% similar.\";\n                        listed.add(addtoit);\n                    }\n            correct = 0;\n        }\n\n        for(String x : listed){\n            if(x.contains(\"100.00% similar.\")){\n                System.out.println(x);\n                listed.clear();\n                break;\n            }\n        }\n\n        for(String x : listed){\n            System.out.println(x);\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\n\nint levenshtein_distance(const std::string& str1, const std::string& str2) {\n    size_t m = str1.size(), n = str2.size();\n    std::vector<int> cost(n + 1);\n    std::iota(cost.begin(), cost.end(), 0);\n    for (size_t i = 0; i < m; ++i) {\n        cost[0] = i + 1;\n        int prev = i;\n        for (size_t j = 0; j < n; ++j) {\n            int c = (str1[i] == str2[j]) ? prev\n                : 1 + std::min(std::min(cost[j + 1], cost[j]), prev);\n            prev = cost[j + 1];\n            cost[j + 1] = c;\n        }\n    }\n    return cost[n];\n}\n\ntemplate <typename T>\nvoid print_vector(const std::vector<T>& vec) {\n    auto i = vec.begin();\n    if (i == vec.end())\n        return;\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 3) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary word\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1]);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << '\\n';\n        return EXIT_FAILURE;\n    }\n    std::string word(argv[2]);\n    if (word.empty()) {\n        std::cerr << \"Word must not be empty\\n\";\n        return EXIT_FAILURE;\n    }\n    constexpr size_t max_dist = 4;\n    std::vector<std::string> matches[max_dist + 1];\n    std::string match;\n    while (getline(in, match)) {\n        int distance = levenshtein_distance(word, match);\n        if (distance <= max_dist)\n            matches[distance].push_back(match);\n    }\n    for (size_t dist = 0; dist <= max_dist; ++dist) {\n        if (matches[dist].empty())\n            continue;\n        std::cout << \"Words at Levenshtein distance of \" << dist\n            << \" (\" << 100 - (100 * dist)/word.size()\n            << \"% similarity) from '\" << word << \"':\\n\";\n        print_vector(matches[dist]);\n        std::cout << \"\\n\\n\";\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54964, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 54965, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 54966, "name": "Pig the dice game_Player", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 54967, "name": "Lychrel numbers", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n"}
{"id": 54968, "name": "Lychrel numbers", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n"}
{"id": 54969, "name": "Erdös-Selfridge categorization of primes", "Java": "import java.util.*;\n\npublic class ErdosSelfridge {\n    private int[] primes;\n    private int[] category;\n\n    public static void main(String[] args) {\n        ErdosSelfridge es = new ErdosSelfridge(1000000);\n\n        System.out.println(\"First 200 primes:\");\n        for (var e : es.getPrimesByCategory(200).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %d:\\n\", category);\n            for (int i = 0, n = primes.size(); i != n; ++i)\n                System.out.printf(\"%4d%c\", primes.get(i), (i + 1) % 15 == 0 ? '\\n' : ' ');\n            System.out.printf(\"\\n\\n\");\n        }\n\n        System.out.println(\"First 1,000,000 primes:\");\n        for (var e : es.getPrimesByCategory(1000000).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %2d: first = %7d  last = %8d  count = %d\\n\", category,\n                              primes.get(0), primes.get(primes.size() - 1), primes.size());\n        }\n    }\n\n    private ErdosSelfridge(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);\n        List<Integer> primeList = new ArrayList<>();\n        for (int i = 0; i < limit; ++i)\n            primeList.add(primeGen.nextPrime());\n        primes = new int[primeList.size()];\n        for (int i = 0; i < primes.length; ++i)\n            primes[i] = primeList.get(i);\n        category = new int[primes.length];\n    }\n\n    private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {\n        Map<Integer, List<Integer>> result = new TreeMap<>();\n        for (int i = 0; i < limit; ++i) {\n            var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());\n            p.add(primes[i]);\n        }\n        return result;\n    }\n\n    private int getCategory(int index) {\n        if (category[index] != 0)\n            return category[index];\n        int maxCategory = 0;\n        int n = primes[index] + 1;\n        for (int i = 0; n > 1; ++i) {\n            int p = primes[i];\n            if (p * p > n)\n                break;\n            int count = 0;\n            for (; n % p == 0; ++count)\n                n /= p;\n            if (count != 0) {\n                int category = (p <= 3) ? 1 : 1 + getCategory(i);\n                maxCategory = Math.max(maxCategory, category);\n            }\n        }\n        if (n > 1) {\n            int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));\n            maxCategory = Math.max(maxCategory, category);\n        }\n        category[index] = maxCategory;\n        return maxCategory;\n    }\n\n    private int getIndex(int prime) {\n       return Arrays.binarySearch(primes, prime);\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <primesieve.hpp>\n\nclass erdos_selfridge {\npublic:\n    explicit erdos_selfridge(int limit);\n    uint64_t get_prime(int index) const { return primes_[index].first; }\n    int get_category(int index);\n\nprivate:\n    std::vector<std::pair<uint64_t, int>> primes_;\n    size_t get_index(uint64_t prime) const;\n};\n\nerdos_selfridge::erdos_selfridge(int limit) {\n    primesieve::iterator iter;\n    for (int i = 0; i < limit; ++i)\n        primes_.emplace_back(iter.next_prime(), 0);\n}\n\nint erdos_selfridge::get_category(int index) {\n    auto& pair = primes_[index];\n    if (pair.second != 0)\n        return pair.second;\n    int max_category = 0;\n    uint64_t n = pair.first + 1;\n    for (int i = 0; n > 1; ++i) {\n        uint64_t p = primes_[i].first;\n        if (p * p > n)\n            break;\n        int count = 0;\n        for (; n % p == 0; ++count)\n            n /= p;\n        if (count != 0) {\n            int category = (p <= 3) ? 1 : 1 + get_category(i);\n            max_category = std::max(max_category, category);\n        }\n    }\n    if (n > 1) {\n        int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));\n        max_category = std::max(max_category, category);\n    }\n    pair.second = max_category;\n    return max_category;\n}\n\nsize_t erdos_selfridge::get_index(uint64_t prime) const {\n    auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,\n                               [](const std::pair<uint64_t, int>& p,\n                                  uint64_t n) { return p.first < n; });\n    assert(it != primes_.end());\n    assert(it->first == prime);\n    return std::distance(primes_.begin(), it);\n}\n\nauto get_primes_by_category(erdos_selfridge& es, int limit) {\n    std::map<int, std::vector<uint64_t>> primes_by_category;\n    for (int i = 0; i < limit; ++i) {\n        uint64_t prime = es.get_prime(i);\n        int category = es.get_category(i);\n        primes_by_category[category].push_back(prime);\n    }\n    return primes_by_category;\n}\n\nint main() {\n    const int limit1 = 200, limit2 = 1000000;\n\n    erdos_selfridge es(limit2);\n\n    std::cout << \"First 200 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit1)) {\n        std::cout << \"Category \" << p.first << \":\\n\";\n        for (size_t i = 0, n = p.second.size(); i != n; ++i) {\n            std::cout << std::setw(4) << p.second[i]\n                      << ((i + 1) % 15 == 0 ? '\\n' : ' ');\n        }\n        std::cout << \"\\n\\n\";\n    }\n\n    std::cout << \"First 1,000,000 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit2)) {\n        const auto& v = p.second;\n        std::cout << \"Category \" << std::setw(2) << p.first << \": \"\n                  << \"first = \" << std::setw(7) << v.front()\n                  << \"  last = \" << std::setw(8) << v.back()\n                  << \"  count = \" << v.size() << '\\n';\n    }\n}\n"}
{"id": 54970, "name": "Sierpinski square curve", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n"}
{"id": 54971, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 54972, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 54973, "name": "Powerful numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 54974, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 54975, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 54976, "name": "Odd words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class OddWords {\n    public static void main(String[] args) {\n        try {\n            Set<String> dictionary = new TreeSet<>();\n            final int minLength = 5;\n            String fileName = \"unixdict.txt\";\n            if (args.length != 0)\n                fileName = args[0];\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        dictionary.add(line);\n                }\n            }\n            StringBuilder word1 = new StringBuilder();\n            StringBuilder word2 = new StringBuilder();\n            List<StringPair> evenWords = new ArrayList<>();\n            List<StringPair> oddWords = new ArrayList<>();\n            for (String word : dictionary) {\n                int length = word.length();\n                if (length < minLength + 2 * (minLength/2))\n                    continue;\n                word1.setLength(0);\n                word2.setLength(0);\n                for (int i = 0; i < length; ++i) {\n                    if ((i & 1) == 0)\n                        word1.append(word.charAt(i));\n                    else\n                        word2.append(word.charAt(i));\n                }\n                String oddWord = word1.toString();\n                String evenWord = word2.toString();\n                if (dictionary.contains(oddWord))\n                    oddWords.add(new StringPair(word, oddWord));\n                if (dictionary.contains(evenWord))\n                    evenWords.add(new StringPair(word, evenWord));\n            }\n            System.out.println(\"Odd words:\");\n            printWords(oddWords);\n            System.out.println(\"\\nEven words:\");\n            printWords(evenWords);\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n\n    private static void printWords(List<StringPair> strings) {\n        int n = 1;\n        for (StringPair pair : strings) {\n            System.out.printf(\"%2d: %-14s%s\\n\", n++,\n                                    pair.string1, pair.string2);\n        }\n    }\n\n    private static class StringPair {\n        private String string1;\n        private String string2;\n        private StringPair(String s1, String s2) {\n            string1 = s1;\n            string2 = s2;\n        }\n    }\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing word_list = std::vector<std::pair<std::string, std::string>>;\n\nvoid print_words(std::ostream& out, const word_list& words) {\n    int n = 1;\n    for (const auto& pair : words) {\n        out << std::right << std::setw(2) << n++ << \": \"\n            << std::left << std::setw(14) << pair.first\n            << pair.second << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    const int min_length = 5;\n    std::string line;\n    std::set<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            dictionary.insert(line);\n    }\n\n    word_list odd_words, even_words;\n\n    for (const std::string& word : dictionary) {\n        if (word.size() < min_length + 2*(min_length/2))\n            continue;\n        std::string odd_word, even_word;\n        for (auto w = word.begin(); w != word.end(); ++w) {\n            odd_word += *w;\n            if (++w == word.end())\n                break;\n            even_word += *w;\n        }\n\n        if (dictionary.find(odd_word) != dictionary.end())\n            odd_words.emplace_back(word, odd_word);\n\n        if (dictionary.find(even_word) != dictionary.end())\n            even_words.emplace_back(word, even_word);\n    }\n\n    std::cout << \"Odd words:\\n\";\n    print_words(std::cout, odd_words);\n\n    std::cout << \"\\nEven words:\\n\";\n    print_words(std::cout, even_words);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54977, "name": "Ramanujan's constant", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54978, "name": "Ramanujan's constant", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 54979, "name": "Word break problem", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n"}
{"id": 54980, "name": "Brilliant numbers", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 54981, "name": "Brilliant numbers", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 54982, "name": "Word ladder", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n\nbool one_away(const std::string& s1, const std::string& s2) {\n    if (s1.size() != s2.size())\n        return false;\n    bool result = false;\n    for (size_t i = 0, n = s1.size(); i != n; ++i) {\n        if (s1[i] != s2[i]) {\n            if (result)\n                return false;\n            result = true;\n        }\n    }\n    return result;\n}\n\n\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n                 separator_type separator) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += separator;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\n\n\n\nbool word_ladder(const word_map& words, const std::string& from,\n                 const std::string& to) {\n    auto w = words.find(from.size());\n    if (w != words.end()) {\n        auto poss = w->second;\n        std::vector<std::vector<std::string>> queue{{from}};\n        while (!queue.empty()) {\n            auto curr = queue.front();\n            queue.erase(queue.begin());\n            for (auto i = poss.begin(); i != poss.end();) {\n                if (!one_away(*i, curr.back())) {\n                    ++i;\n                    continue;\n                }\n                if (to == *i) {\n                    curr.push_back(to);\n                    std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n                    return true;\n                }\n                std::vector<std::string> temp(curr);\n                temp.push_back(*i);\n                queue.push_back(std::move(temp));\n                i = poss.erase(i);\n            }\n        }\n    }\n    std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n    return false;\n}\n\nint main() {\n    word_map words;\n    std::ifstream in(\"unixdict.txt\");\n    if (!in) {\n        std::cerr << \"Cannot open file unixdict.txt.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    while (getline(in, word))\n        words[word.size()].push_back(word);\n    word_ladder(words, \"boy\", \"man\");\n    word_ladder(words, \"girl\", \"lady\");\n    word_ladder(words, \"john\", \"jane\");\n    word_ladder(words, \"child\", \"adult\");\n    word_ladder(words, \"cat\", \"dog\");\n    word_ladder(words, \"lead\", \"gold\");\n    word_ladder(words, \"white\", \"black\");\n    word_ladder(words, \"bubble\", \"tickle\");\n    return EXIT_SUCCESS;\n}\n"}
{"id": 54983, "name": "Earliest difference between prime gaps", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <locale>\n#include <unordered_map>\n\n#include <primesieve.hpp>\n\nclass prime_gaps {\npublic:\n    prime_gaps() { last_prime_ = iterator_.next_prime(); }\n    uint64_t find_gap_start(uint64_t gap);\nprivate:\n    primesieve::iterator iterator_;\n    uint64_t last_prime_;\n    std::unordered_map<uint64_t, uint64_t> gap_starts_;\n};\n\nuint64_t prime_gaps::find_gap_start(uint64_t gap) {\n    auto i = gap_starts_.find(gap);\n    if (i != gap_starts_.end())\n        return i->second;\n    for (;;) {\n        uint64_t prev = last_prime_;\n        last_prime_ = iterator_.next_prime();\n        uint64_t diff = last_prime_ - prev;\n        gap_starts_.emplace(diff, prev);\n        if (gap == diff)\n            return prev;\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const uint64_t limit = 100000000000;\n    prime_gaps pg;\n    for (uint64_t pm = 10, gap1 = 2;;) {\n        uint64_t start1 = pg.find_gap_start(gap1);\n        uint64_t gap2 = gap1 + 2;\n        uint64_t start2 = pg.find_gap_start(gap2);\n        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;\n        if (diff > pm) {\n            std::cout << \"Earliest difference > \" << pm\n                      << \" between adjacent prime gap starting primes:\\n\"\n                      << \"Gap \" << gap1 << \" starts at \" << start1 << \", gap \"\n                      << gap2 << \" starts at \" << start2 << \", difference is \"\n                      << diff << \".\\n\\n\";\n            if (pm == limit)\n                break;\n            pm *= 10;\n        } else {\n            gap1 = gap2;\n        }\n    }\n}\n"}
{"id": 54984, "name": "Latin Squares in reduced form", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 54985, "name": "UPC", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n"}
{"id": 54986, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 54987, "name": "Playfair cipher", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 54988, "name": "Closest-pair problem", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n"}
{"id": 54989, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 54990, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 54991, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "C++": "#include <map>\n"}
{"id": 54992, "name": "Wilson primes of order n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class WilsonPrimes {\n    public static void main(String[] args) {\n        final int limit = 11000;\n        BigInteger[] f = new BigInteger[limit];\n        f[0] = BigInteger.ONE;\n        BigInteger factorial = BigInteger.ONE;\n        for (int i = 1; i < limit; ++i) {\n            factorial = factorial.multiply(BigInteger.valueOf(i));\n            f[i] = factorial;\n        }\n        List<Integer> primes = generatePrimes(limit);\n        System.out.printf(\" n | Wilson primes\\n--------------------\\n\");\n        BigInteger s = BigInteger.valueOf(-1);\n        for (int n = 1; n <= 11; ++n) {\n            System.out.printf(\"%2d |\", n);\n            for (int p : primes) {\n                if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)\n                        .mod(BigInteger.valueOf(p * p))\n                        .equals(BigInteger.ZERO))\n                    System.out.printf(\" %d\", p);\n            }\n            s = s.negate();\n            System.out.println();\n        }\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 <iomanip>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\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\nint main() {\n    using big_int = mpz_class;\n    const int limit = 11000;\n    std::vector<big_int> f{1};\n    f.reserve(limit);\n    big_int factorial = 1;\n    for (int i = 1; i < limit; ++i) {\n        factorial *= i;\n        f.push_back(factorial);\n    }\n    std::vector<int> primes = generate_primes(limit);\n    std::cout << \" n | Wilson primes\\n--------------------\\n\";\n    for (int n = 1, s = -1; n <= 11; ++n, s = -s) {\n        std::cout << std::setw(2) << n << \" |\";\n        for (int p : primes) {\n            if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)\n                std::cout << ' ' << p;\n        }\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 54993, "name": "Color wheel", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 54994, "name": "Color wheel", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 54995, "name": "Plasma effect", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n"}
{"id": 54996, "name": "Plasma effect", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n"}
{"id": 54997, "name": "Rhonda numbers", "Java": "public class RhondaNumbers {\n    public static void main(String[] args) {\n        final int limit = 15;\n        for (int base = 2; base <= 36; ++base) {\n            if (isPrime(base))\n                continue;\n            System.out.printf(\"First %d Rhonda numbers to base %d:\\n\", limit, base);\n            int numbers[] = new int[limit];\n            for (int n = 1, count = 0; count < limit; ++n) {\n                if (isRhonda(base, n))\n                    numbers[count++] = n;\n            }\n            System.out.printf(\"In base 10:\");\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %d\", numbers[i]);\n            System.out.printf(\"\\nIn base %d:\", base);\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %s\", Integer.toString(numbers[i], base));\n            System.out.printf(\"\\n\\n\");\n        }\n    }\n    \n    private static int digitProduct(int base, int n) {\n        int product = 1;\n        for (; n != 0; n /= base)\n            product *= n % base;\n        return product;\n    }\n     \n    private static int primeFactorSum(int n) {\n        int sum = 0;\n        for (; (n & 1) == 0; n >>= 1)\n            sum += 2;\n        for (int p = 3; p * p <= n; p += 2)\n            for (; n % p == 0; n /= p)\n                sum += p;\n        if (n > 1)\n            sum += n;\n        return sum;\n    }\n     \n    private static boolean isPrime(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 (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     \n    private static boolean isRhonda(int base, int n) {\n        return digitProduct(base, n) == base * primeFactorSum(n);\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint digit_product(int base, int n) {\n    int product = 1;\n    for (; n != 0; n /= base)\n        product *= n % base;\n    return product;\n}\n\nint prime_factor_sum(int n) {\n    int sum = 0;\n    for (; (n & 1) == 0; n >>= 1)\n        sum += 2;\n    for (int p = 3; p * p <= n; p += 2)\n        for (; n % p == 0; n /= p)\n            sum += p;\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nbool is_prime(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 (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\nbool is_rhonda(int base, int n) {\n    return digit_product(base, n) == base * prime_factor_sum(n);\n}\n\nstd::string to_string(int base, int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nint main() {\n    const int limit = 15;\n    for (int base = 2; base <= 36; ++base) {\n        if (is_prime(base))\n            continue;\n        std::cout << \"First \" << limit << \" Rhonda numbers to base \" << base\n                  << \":\\n\";\n        int numbers[limit];\n        for (int n = 1, count = 0; count < limit; ++n) {\n            if (is_rhonda(base, n))\n                numbers[count++] = n;\n        }\n        std::cout << \"In base 10:\";\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << numbers[i];\n        std::cout << \"\\nIn base \" << base << ':';\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << to_string(base, numbers[i]);\n        std::cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 54998, "name": "Hello world_Newbie", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n"}
{"id": 54999, "name": "Hello world_Newbie", "Java": "public class HelloWorld {\n    public static void main(String[] args) {\n        \n        System.out.println(\"Hello world!\");\n    }\n}\n", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n"}
{"id": 55000, "name": "Polymorphism", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55001, "name": "Wagstaff primes", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n"}
{"id": 55002, "name": "Wagstaff primes", "Java": "import java.math.BigInteger; \n\npublic class Main {\n  public static void main(String[] args) {\n    BigInteger d = new BigInteger(\"3\"), a;\n    int lmt = 25, sl, c = 0;\n    for (int i = 3; i < 5808; ) {\n      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n      if (a.isProbablePrime(1)) {\n        System.out.printf(\"%2d %4d \", ++c, i);\n        String s = a.toString(); sl = s.length();\n        if (sl < lmt) System.out.println(a);\n        else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n      }\n      i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n    }\n  }\n}\n", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n"}
{"id": 55003, "name": "Create an object_Native demonstration", "Java": "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\npublic class ImmutableMap {\n\n    public static void main(String[] args) {\n        Map<String,Integer> hashMap = getImmutableMap();\n        try {\n            hashMap.put(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put new value.\");\n        }\n        try {\n            hashMap.clear();\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to clear map.\");\n        }\n        try {\n            hashMap.putIfAbsent(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put if absent.\");\n        }\n        \n        for ( String key : hashMap.keySet() ) {\n            System.out.printf(\"key = %s, value = %s%n\", key, hashMap.get(key));\n        }\n    }\n    \n    private static Map<String,Integer> getImmutableMap() {\n        Map<String,Integer> hashMap = new HashMap<>();\n        hashMap.put(\"Key 1\", 34);\n        hashMap.put(\"Key 2\", 105);\n        hashMap.put(\"Key 3\", 144);\n\n        return Collections.unmodifiableMap(hashMap);\n    }\n    \n}\n", "C++": "#include <iostream>\n#include <map>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nclass FixedMap : private T\n{\n    \n    \n    \n    \n    \n    T m_defaultValues;\n    \npublic:\n    FixedMap(T map)\n    : T(map), m_defaultValues(move(map)){}\n    \n    \n    using T::cbegin;\n    using T::cend;\n    using T::empty;\n    using T::find;\n    using T::size;\n\n    \n    using T::at;\n    using T::begin;\n    using T::end;\n    \n    \n    \n    auto& operator[](typename T::key_type&& key)\n    {\n        \n        return this->at(forward<typename T::key_type>(key));\n    }\n    \n    \n    \n    void erase(typename T::key_type&& key)\n    {\n        T::operator[](key) = m_defaultValues.at(key);\n    }\n\n    \n    void clear()\n    {\n        \n        T::operator=(m_defaultValues);\n    }\n    \n};\n\n\nauto PrintMap = [](const auto &map)\n{\n    for(auto &[key, value] : map)\n    {\n        cout << \"{\" << key << \" : \" << value << \"} \";\n    }\n    cout << \"\\n\\n\";\n};\n\nint main(void) \n{\n    \n    cout << \"Map intialized with values\\n\";\n    FixedMap<map<string, int>> fixedMap ({\n        {\"a\", 1},\n        {\"b\", 2}});\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values of the keys\\n\";\n    fixedMap[\"a\"] = 55;\n    fixedMap[\"b\"] = 56;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset the 'a' key\\n\";\n    fixedMap.erase(\"a\");\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values the again\\n\";\n    fixedMap[\"a\"] = 88;\n    fixedMap[\"b\"] = 99;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset all keys\\n\";\n    fixedMap.clear();\n    PrintMap(fixedMap);\n  \n    try\n    {\n        \n        cout << \"Try to add a new key\\n\";\n        fixedMap[\"newKey\"] = 99;\n    }\n    catch (exception &ex)\n    {\n        cout << \"error: \" << ex.what();\n    }\n}\n"}
{"id": 55004, "name": "Factorial primes", "Java": "public class MainApp {\n    public static void main(String[] args) {\n        int countOfPrimes = 0;\n        final int targetCountOfPrimes = 10;\n        long f = 1;\n        while (countOfPrimes < targetCountOfPrimes) {\n            long factorialNum = getFactorial(f);\n            boolean primePlus = isPrime(factorialNum + 1);\n            boolean primeMinus = isPrime(factorialNum - 1);\n            if (primeMinus) {\n                countOfPrimes++;\n                System.out.println(countOfPrimes + \": \" + factorialNum + \"! - 1 = \" + (factorialNum - 1));\n\n            }\n            if (primePlus  && f > 1) {\n                countOfPrimes++;\n                System.out.println(countOfPrimes + \": \" + factorialNum + \"! + 1 = \" + (factorialNum + 1));\n            }\n            f++;\n        }\n    }\n\n    private static long getFactorial(long f) {\n        long factorial = 1;\n        for (long i = 1; i < f; i++) {\n            factorial *= i;\n        }\n        return factorial;\n    }\n\n    private static boolean isPrime(long num) {\n        if (num < 2) {return false;}\n        for (long i = 2; i < num; i++) {\n            if (num % i == 0) {return false;}\n        }\n        return true;\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    big_int f = 1;\n    for (int i = 0, n = 1; i < 31; ++n) {\n        f *= n;\n        if (is_probably_prime(f - 1)) {\n            ++i;\n            std::cout << std::setw(2) << i << \": \" << std::setw(3) << n\n                      << \"! - 1 = \" << to_string(f - 1, 40) << '\\n';\n        }\n        if (is_probably_prime(f + 1)) {\n            ++i;\n            std::cout << std::setw(2) << i << \": \" << std::setw(3) << n\n                      << \"! + 1 = \" << to_string(f + 1, 40) << '\\n';\n        }\n    }\n}\n"}
{"id": 55005, "name": "Arithmetic evaluation", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n"}
{"id": 55006, "name": "Arithmetic evaluation", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n"}
{"id": 55007, "name": "Arithmetic evaluation", "Java": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n    public interface Expression {\n        BigRational eval();\n    }\n\n    public enum Parentheses {LEFT}\n\n    public enum BinaryOperator {\n        ADD('+', 1),\n        SUB('-', 1),\n        MUL('*', 2),\n        DIV('/', 2);\n\n        public final char symbol;\n        public final int precedence;\n\n        BinaryOperator(char symbol, int precedence) {\n            this.symbol = symbol;\n            this.precedence = precedence;\n        }\n\n        public BigRational eval(BigRational leftValue, BigRational rightValue) {\n            switch (this) {\n                case ADD:\n                    return leftValue.add(rightValue);\n                case SUB:\n                    return leftValue.subtract(rightValue);\n                case MUL:\n                    return leftValue.multiply(rightValue);\n                case DIV:\n                    return leftValue.divide(rightValue);\n            }\n            throw new IllegalStateException();\n        }\n\n        public static BinaryOperator forSymbol(char symbol) {\n            for (BinaryOperator operator : values()) {\n                if (operator.symbol == symbol) {\n                    return operator;\n                }\n            }\n            throw new IllegalArgumentException(String.valueOf(symbol));\n        }\n    }\n\n    public static class Number implements Expression {\n        private final BigRational number;\n\n        public Number(BigRational number) {\n            this.number = number;\n        }\n\n        @Override\n        public BigRational eval() {\n            return number;\n        }\n\n        @Override\n        public String toString() {\n            return number.toString();\n        }\n    }\n\n    public static class BinaryExpression implements Expression {\n        public final Expression leftOperand;\n        public final BinaryOperator operator;\n        public final Expression rightOperand;\n\n        public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n            this.leftOperand = leftOperand;\n            this.operator = operator;\n            this.rightOperand = rightOperand;\n        }\n\n        @Override\n        public BigRational eval() {\n            BigRational leftValue = leftOperand.eval();\n            BigRational rightValue = rightOperand.eval();\n            return operator.eval(leftValue, rightValue);\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n        }\n    }\n\n    private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {\n        Expression rightOperand = operands.pop();\n        Expression leftOperand = operands.pop();\n        operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n    }\n\n    public static Expression parse(String input) {\n        int curIndex = 0;\n        boolean afterOperand = false;\n        Stack<Expression> operands = new Stack<>();\n        Stack<Object> operators = new Stack<>();\n        while (curIndex < input.length()) {\n            int startIndex = curIndex;\n            char c = input.charAt(curIndex++);\n\n            if (Character.isWhitespace(c))\n                continue;\n\n            if (afterOperand) {\n                if (c == ')') {\n                    Object operator;\n                    while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n                        createNewOperand((BinaryOperator) operator, operands);\n                    continue;\n                }\n                afterOperand = false;\n                BinaryOperator operator = BinaryOperator.forSymbol(c);\n                while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n                    createNewOperand((BinaryOperator) operators.pop(), operands);\n                operators.push(operator);\n                continue;\n            }\n\n            if (c == '(') {\n                operators.push(Parentheses.LEFT);\n                continue;\n            }\n\n            afterOperand = true;\n            while (curIndex < input.length()) {\n                c = input.charAt(curIndex);\n                if (((c < '0') || (c > '9')) && (c != '.'))\n                    break;\n                curIndex++;\n            }\n            operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n        }\n\n        while (!operators.isEmpty()) {\n            Object operator = operators.pop();\n            if (operator == Parentheses.LEFT)\n                throw new IllegalArgumentException();\n            createNewOperand((BinaryOperator) operator, operands);\n        }\n\n        Expression expression = operands.pop();\n        if (!operands.isEmpty())\n            throw new IllegalArgumentException();\n        return expression;\n    }\n\n    public static void main(String[] args) {\n        String[] testExpressions = {\n                \"2+3\",\n                \"2+3/4\",\n                \"2*3-4\",\n                \"2*(3+4)+5/6\",\n                \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n                \"2*-3--4+-.25\"};\n        for (String testExpression : testExpressions) {\n            Expression expression = parse(testExpression);\n            System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n        }\n    }\n}\n", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n"}
{"id": 55008, "name": "Special variables", "Java": "import java.util.Arrays;\n\npublic class SpecialVariables {\n\n    public static void main(String[] args) {\n\n        \n        \n        System.out.println(Arrays.toString(args));\n\n        \n        \n        System.out.println(SpecialVariables.class);\n\n\n        \n\n        \n        System.out.println(System.getenv());\n\n        \n        \n        System.out.println(System.getProperties());\n\n        \n        \n        System.out.println(Runtime.getRuntime().availableProcessors());\n\n    }\n}\n", "C++": "#include <iostream>\n\nstruct SpecialVariables\n{\n    int i = 0;\n\n    SpecialVariables& operator++()\n    {\n        \n        \n        \n        this->i++;  \n\n        \n        return *this;\n    }\n\n};\n\nint main()\n{\n    SpecialVariables sv;\n    auto sv2 = ++sv;     \n    std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}\n"}
{"id": 55009, "name": "Special variables", "Java": "import java.util.Arrays;\n\npublic class SpecialVariables {\n\n    public static void main(String[] args) {\n\n        \n        \n        System.out.println(Arrays.toString(args));\n\n        \n        \n        System.out.println(SpecialVariables.class);\n\n\n        \n\n        \n        System.out.println(System.getenv());\n\n        \n        \n        System.out.println(System.getProperties());\n\n        \n        \n        System.out.println(Runtime.getRuntime().availableProcessors());\n\n    }\n}\n", "C++": "#include <iostream>\n\nstruct SpecialVariables\n{\n    int i = 0;\n\n    SpecialVariables& operator++()\n    {\n        \n        \n        \n        this->i++;  \n\n        \n        return *this;\n    }\n\n};\n\nint main()\n{\n    SpecialVariables sv;\n    auto sv2 = ++sv;     \n    std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}\n"}
{"id": 55010, "name": "Execute CopyPasta Language", "Java": "import java.io.File;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class Copypasta\n{\n\t\n\tpublic static void fatal_error(String errtext)\n\t{\n\t\tStackTraceElement[] stack = Thread.currentThread().getStackTrace();\n\t\tStackTraceElement main = stack[stack.length - 1];\n\t\tString mainClass = main.getClassName();\n\t\tSystem.out.println(\"%\" + errtext);\n\t\tSystem.out.println(\"usage: \" + mainClass + \" [filename.cp]\");\n\t\tSystem.exit(1);\n\t}\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tString fname = null;\n\t\tString source = null;\n\t\ttry\n\t\t{\n\t\t\tfname = args[0];\n\t\t\tsource = new String(Files.readAllBytes(new File(fname).toPath()));\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tfatal_error(\"error while trying to read from specified file\");\n\t\t}\n\n\t\t\n\t\tArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split(\"\\n\")));\n\t\t\n\t\t\n\t\tString clipboard = \"\";\n\t\t\n\t\t\n\t\tint loc = 0;\n\t\twhile(loc < lines.size())\n\t\t{\n\t\t\t\n\t\t\tString command = lines.get(loc).trim();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(command.equals(\"Copy\"))\n\t\t\t\t\tclipboard += lines.get(loc + 1);\n\t\t\t\telse if(command.equals(\"CopyFile\"))\n\t\t\t\t{\n\t\t\t\t\tif(lines.get(loc + 1).equals(\"TheF*ckingCode\"))\n\t\t\t\t\t\tclipboard += source;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tString filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));\n\t\t\t\t\t\tclipboard += filetext;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Duplicate\"))\n\t\t\t\t{\n\t\t\t\t\tString origClipboard = clipboard;\n\n\t\t\t\t\tint amount = Integer.parseInt(lines.get(loc + 1)) - 1;\n\t\t\t\t\tfor(int i = 0; i < amount; i++)\n\t\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Pasta!\"))\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(clipboard);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\n\t\t\t\n\t\t\tloc += 2;\n\t\t}\n\t}\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n\n#include <stdlib.h>\n\nusing namespace std;\n\n\nvoid fatal_error(string errtext, char *argv[])\n{\n\tcout << \"%\" << errtext << endl;\n\tcout << \"usage: \" << argv[0] << \" [filename.cp]\" << endl;\n\texit(1);\n}\n\n\n\nstring& ltrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(0, str.find_first_not_of(chars));\n\treturn str;\n}\nstring& rtrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(str.find_last_not_of(chars) + 1);\n\treturn str;\n}\nstring& trim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\treturn ltrim(rtrim(str, chars), chars);\n}\n\nint main(int argc, char *argv[])\n{\n\t\n\tstring fname = \"\";\n\tstring source = \"\";\n\ttry\n\t{\n\t\tfname = argv[1];\n\t\tifstream t(fname);\n\n\t\tt.seekg(0, ios::end);\n\t\tsource.reserve(t.tellg());\n\t\tt.seekg(0, ios::beg);\n\n\t\tsource.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t}\n\tcatch(const exception& e)\n\t{\n\t\tfatal_error(\"error while trying to read from specified file\", argv);\n\t}\n\n\t\n\tstring clipboard = \"\";\n\n\t\n\tint loc = 0;\n\tstring remaining = source;\n\tstring line = \"\";\n\tstring command = \"\";\n\tstringstream ss;\n\twhile(remaining.find(\"\\n\") != string::npos)\n\t{\n\t\t\n\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\tcommand = trim(line);\n\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\n\t\ttry\n\t\t{\n\t\t\tif(line == \"Copy\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tclipboard += line;\n\t\t\t}\n\t\t\telse if(line == \"CopyFile\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tif(line == \"TheF*ckingCode\")\n\t\t\t\t\tclipboard += source;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring filetext = \"\";\n\t\t\t\t\tifstream t(line);\n\n\t\t\t\t\tt.seekg(0, ios::end);\n\t\t\t\t\tfiletext.reserve(t.tellg());\n\t\t\t\t\tt.seekg(0, ios::beg);\n\n\t\t\t\t\tfiletext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t\t\t\t\tclipboard += filetext;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Duplicate\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tint amount = stoi(line);\n\t\t\t\tstring origClipboard = clipboard;\n\t\t\t\tfor(int i = 0; i < amount - 1; i++) {\n\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Pasta!\")\n\t\t\t{\n\t\t\t\tcout << clipboard << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss << (loc + 1);\n\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encounter on line \" + ss.str(), argv);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception& e)\n\t\t{\n\t\t\tss << (loc + 1);\n\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + ss.str(), argv);\n\t\t}\n\n\t\t\n\t\tloc += 2;\n\t}\n\n\t\n\treturn 0;\n}\n"}
{"id": 55011, "name": "Kosaraju", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 55012, "name": "Special characters", "Java": "& | ^ ~ \n>> << \n>>> \n+ - * / = % \n", "C++": "std::cout << \"Tür\\n\";\nstd::cout << \"T\\u00FC\\n\";\n"}
{"id": 55013, "name": "Special characters", "Java": "& | ^ ~ \n>> << \n>>> \n+ - * / = % \n", "C++": "std::cout << \"Tür\\n\";\nstd::cout << \"T\\u00FC\\n\";\n"}
{"id": 55014, "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#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 55015, "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", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 55016, "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", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n"}
{"id": 55017, "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", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 55018, "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", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 55019, "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", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 55020, "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", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 55021, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 55022, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 55023, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 55024, "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", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 55025, "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", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 55026, "name": "Stack", "Go": "var intStack []int\n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 55027, "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", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 55028, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 55029, "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", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 55030, "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", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 55031, "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", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n"}
{"id": 55032, "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", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 55033, "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", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 55034, "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", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 55035, "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", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 55036, "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", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n"}
{"id": 55037, "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", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 55038, "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", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 55039, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 55040, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n"}
{"id": 55041, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 55042, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 55043, "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", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 55044, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n"}
{"id": 55045, "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", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 55046, "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", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n"}
{"id": 55047, "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", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 55048, "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", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 55049, "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", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 55050, "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", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 55051, "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", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 55052, "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", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n"}
{"id": 55053, "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", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 55054, "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", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 55055, "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", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 55056, "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", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 55057, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 55058, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 55059, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 55060, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n"}
{"id": 55061, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 55062, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 55063, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 55064, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 55065, "name": "Descending primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n"}
{"id": 55066, "name": "Sum and product puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n"}
{"id": 55067, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 55068, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 55069, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 55070, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "C#": "\n"}
{"id": 55071, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "C#": "\n"}
{"id": 55072, "name": "Stern-Brocot sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 55073, "name": "Documentation", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n"}
{"id": 55074, "name": "Problem of Apollonius", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n"}
{"id": 55075, "name": "Chat server", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 55076, "name": "FASTA format", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n"}
{"id": 55077, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 55078, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 55079, "name": "Terminal control_Dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n"}
{"id": 55080, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 55081, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 55082, "name": "Minimum primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 54, 53}\n    primes := [5]int{}\n    for n := 0; n < 5; n++ {\n        max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])\n        if max % 2 == 0 {\n            max++\n        }\n        for !rcu.IsPrime(max) {\n            max += 2\n        }\n        primes[n] = max\n    }\n    fmt.Println(primes)\n}\n", "C#": "using System;\nusing System.Linq;\nusing static System.Console;\n\nclass Program {\n\n  static int nxtPrime(int x) {\n    int j = 2; do {\n        if (x % j == 0) { j = 2; x++; }\n        else j += j < 3 ? 1 : 2;\n    } while (j * j <= x); return x; }\n\n  static void Main(string[] args) {\n    WriteLine(\"working...\");\n    int[] Num1 = new int[]{  5, 45, 23, 21, 67 },\n          Num2 = new int[]{ 43, 22, 78, 46, 38 },\n          Num3 = new int[]{  9, 98, 12, 54, 53 };\n    int n = Num1.Length; int[] Nums = new int[n];\n    for (int i = 0; i < n; i++)\n      Nums[i] = nxtPrime(new int[]{ Num1[i], Num2[i], Num3[i] }.Max());\n    WriteLine(\"The minimum prime numbers of three lists = [{0}]\", string.Join(\",\", Nums));\n    Write(\"done...\"); } }\n"}
{"id": 55083, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n"}
{"id": 55084, "name": "GUI_Maximum window dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n"}
{"id": 55085, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 55086, "name": "Knapsack problem_Unbounded", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n"}
{"id": 55087, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 55088, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 55089, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 55090, "name": "Range extraction", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 55091, "name": "Type detection", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n"}
{"id": 55092, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n"}
{"id": 55093, "name": "Terminal control_Cursor movement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc main() {\n    tput(\"clear\") \n    tput(\"cup\", \"6\", \"3\") \n    time.Sleep(1 * time.Second)\n    tput(\"cub1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuf1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuu1\") \n    time.Sleep(1 * time.Second)\n    \n    tput(\"cud\", \"1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cr\") \n    time.Sleep(1 * time.Second)\n    \n    var h, w int\n    cmd := exec.Command(\"stty\", \"size\")\n    cmd.Stdin = os.Stdin\n    d, _ := cmd.Output()\n    fmt.Sscan(string(d), &h, &w)\n    \n    tput(\"hpa\", strconv.Itoa(w-1))\n    time.Sleep(2 * time.Second)\n    \n    tput(\"home\")\n    time.Sleep(2 * time.Second)\n    \n    tput(\"cup\", strconv.Itoa(h-1), strconv.Itoa(w-1))\n    time.Sleep(3 * time.Second)\n}\n\nfunc tput(args ...string) error {\n    cmd := exec.Command(\"tput\", args...)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n"}
{"id": 55094, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 55095, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 55096, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 55097, "name": "UTF-8 encode and decode", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n"}
{"id": 55098, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n"}
{"id": 55099, "name": "Same fringe", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n"}
{"id": 55100, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n"}
{"id": 55101, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n"}
{"id": 55102, "name": "Peaceful chess queen armies", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 55103, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "C#": "while (true)\n{\n    Console.WriteLine(\"SPAM\");\n}\n"}
{"id": 55104, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 55105, "name": "Sum of first n cubes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n", "C#": "using System; using static System.Console;\nclass Program { static void Main(string[] args) {\n    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)\n      Write(\"{0,-7}{1}\",s, (i+=i==3?-4:1)==0?\"\\n\":\" \"); } }\n"}
{"id": 55106, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 55107, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n"}
{"id": 55108, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 55109, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n"}
{"id": 55110, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n"}
{"id": 55111, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 55112, "name": "Addition chains", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n"}
{"id": 55113, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 55114, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 55115, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 55116, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 55117, "name": "The sieve of Sundaram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nfunc sos(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        p := 2*i + 3\n        s := (p*p - 3) / 2\n        for j := s; j < k; j += p {\n            marked[j] = true\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\n\nfunc soe(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        if !marked[i] {\n            p := 2*i + 3\n            s := (p*p - 3) / 2\n            for j := s; j < k; j += p {\n                marked[j] = true\n            }\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\nfunc main() {\n    const limit = int(16e6) \n    start := time.Now()\n    primes := sos(limit)\n    elapsed := int(time.Since(start).Milliseconds())\n    climit := rcu.Commatize(limit)\n    celapsed := rcu.Commatize(elapsed)\n    million := rcu.Commatize(1e6)\n    millionth := rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"Using the Sieve of Sundaram generated primes up to %s in %s ms.\\n\\n\", climit, celapsed)\n    fmt.Println(\"First 100 odd primes generated by the Sieve of Sundaram:\")\n    for i, p := range primes[0:100] {\n        fmt.Printf(\"%3d \", p)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThe %s Sundaram prime is %s\\n\", million, millionth)\n\n    start = time.Now()\n    primes = soe(limit)\n    elapsed = int(time.Since(start).Milliseconds())\n    celapsed = rcu.Commatize(elapsed)\n    millionth = rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"\\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\\n\", celapsed)\n    fmt.Printf(\"\\nAs a check, the %s Sundaram prime would again have been %s\\n\", million, millionth)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n"}
{"id": 55118, "name": "Chemical calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n"}
{"id": 55119, "name": "Active Directory_Connect", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n"}
{"id": 55120, "name": "Pythagorean quadruples", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 55121, "name": "Zebra puzzle", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"log\"\n        \"strings\"\n)\n\n\n\ntype HouseSet [5]*House\ntype House struct {\n        n Nationality\n        c Colour\n        a Animal\n        d Drink\n        s Smoke\n}\ntype Nationality int8\ntype Colour int8\ntype Animal int8\ntype Drink int8\ntype Smoke int8\n\n\n\nconst (\n        English Nationality = iota\n        Swede\n        Dane\n        Norwegian\n        German\n)\nconst (\n        Red Colour = iota\n        Green\n        White\n        Yellow\n        Blue\n)\nconst (\n        Dog Animal = iota\n        Birds\n        Cats\n        Horse\n        Zebra\n)\nconst (\n        Tea Drink = iota\n        Coffee\n        Milk\n        Beer\n        Water\n)\nconst (\n        PallMall Smoke = iota\n        Dunhill\n        Blend\n        BlueMaster\n        Prince\n)\n\n\n\nvar nationalities = [...]string{\"English\", \"Swede\", \"Dane\", \"Norwegian\", \"German\"}\nvar colours = [...]string{\"red\", \"green\", \"white\", \"yellow\", \"blue\"}\nvar animals = [...]string{\"dog\", \"birds\", \"cats\", \"horse\", \"zebra\"}\nvar drinks = [...]string{\"tea\", \"coffee\", \"milk\", \"beer\", \"water\"}\nvar smokes = [...]string{\"Pall Mall\", \"Dunhill\", \"Blend\", \"Blue Master\", \"Prince\"}\n\nfunc (n Nationality) String() string { return nationalities[n] }\nfunc (c Colour) String() string      { return colours[c] }\nfunc (a Animal) String() string      { return animals[a] }\nfunc (d Drink) String() string       { return drinks[d] }\nfunc (s Smoke) String() string       { return smokes[s] }\nfunc (h House) String() string {\n        return fmt.Sprintf(\"%-9s  %-6s  %-5s  %-6s  %s\", h.n, h.c, h.a, h.d, h.s)\n}\nfunc (hs HouseSet) String() string {\n        lines := make([]string, 0, len(hs))\n        for i, h := range hs {\n                s := fmt.Sprintf(\"%d  %s\", i, h)\n                lines = append(lines, s)\n        }\n        return strings.Join(lines, \"\\n\")\n}\n\n\n\nfunc simpleBruteForce() (int, HouseSet) {\n        var v []House\n        for n := range nationalities {\n                for c := range colours {\n                        for a := range animals {\n                                for d := range drinks {\n                                        for s := range smokes {\n                                                h := House{\n                                                        n: Nationality(n),\n                                                        c: Colour(c),\n                                                        a: Animal(a),\n                                                        d: Drink(d),\n                                                        s: Smoke(s),\n                                                }\n                                                if !h.Valid() {\n                                                        continue\n                                                }\n                                                v = append(v, h)\n                                        }\n                                }\n                        }\n                }\n        }\n        n := len(v)\n        log.Println(\"Generated\", n, \"valid houses\")\n\n        combos := 0\n        first := 0\n        valid := 0\n        var validSet HouseSet\n        for a := 0; a < n; a++ {\n                if v[a].n != Norwegian { \n                        continue\n                }\n                for b := 0; b < n; b++ {\n                        if b == a {\n                                continue\n                        }\n                        if v[b].anyDups(&v[a]) {\n                                continue\n                        }\n                        for c := 0; c < n; c++ {\n                                if c == b || c == a {\n                                        continue\n                                }\n                                if v[c].d != Milk { \n                                        continue\n                                }\n                                if v[c].anyDups(&v[b], &v[a]) {\n                                        continue\n                                }\n                                for d := 0; d < n; d++ {\n                                        if d == c || d == b || d == a {\n                                                continue\n                                        }\n                                        if v[d].anyDups(&v[c], &v[b], &v[a]) {\n                                                continue\n                                        }\n                                        for e := 0; e < n; e++ {\n                                                if e == d || e == c || e == b || e == a {\n                                                        continue\n                                                }\n                                                if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {\n                                                        continue\n                                                }\n                                                combos++\n                                                set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}\n                                                if set.Valid() {\n                                                        valid++\n                                                        if valid == 1 {\n                                                                first = combos\n                                                        }\n                                                        validSet = set\n                                                        \n                                                }\n                                        }\n                                }\n                        }\n                }\n        }\n        log.Println(\"Tested\", first, \"different combinations of valid houses before finding solution\")\n        log.Println(\"Tested\", combos, \"different combinations of valid houses in total\")\n        return valid, validSet\n}\n\n\nfunc (h *House) anyDups(list ...*House) bool {\n        for _, b := range list {\n                if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {\n                        return true\n                }\n        }\n        return false\n}\n\nfunc (h *House) Valid() bool {\n        \n        if h.n == English && h.c != Red || h.n != English && h.c == Red {\n                return false\n        }\n        \n        if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {\n                return false\n        }\n        \n        if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {\n                return false\n        }\n        \n        if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {\n                return false\n        }\n        \n        if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {\n                return false\n        }\n        \n        if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {\n                return false\n        }\n        \n        if h.a == Cats && h.s == Blend {\n                return false\n        }\n        \n        if h.a == Horse && h.s == Dunhill {\n                return false\n        }\n        \n        if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {\n                return false\n        }\n        \n        if h.n == German && h.s != Prince || h.n != German && h.s == Prince {\n                return false\n        }\n        \n        if h.n == Norwegian && h.c == Blue {\n                return false\n        }\n        \n        if h.d == Water && h.s == Blend {\n                return false\n        }\n        return true\n}\n\nfunc (hs *HouseSet) Valid() bool {\n        ni := make(map[Nationality]int, 5)\n        ci := make(map[Colour]int, 5)\n        ai := make(map[Animal]int, 5)\n        di := make(map[Drink]int, 5)\n        si := make(map[Smoke]int, 5)\n        for i, h := range hs {\n                ni[h.n] = i\n                ci[h.c] = i\n                ai[h.a] = i\n                di[h.d] = i\n                si[h.s] = i\n        }\n        \n        if ci[Green]+1 != ci[White] {\n                return false\n        }\n        \n        if dist(ai[Cats], si[Blend]) != 1 {\n                return false\n        }\n        \n        if dist(ai[Horse], si[Dunhill]) != 1 {\n                return false\n        }\n        \n        if dist(ni[Norwegian], ci[Blue]) != 1 {\n                return false\n        }\n        \n        if dist(di[Water], si[Blend]) != 1 {\n                return false\n        }\n\n        \n        if hs[2].d != Milk {\n                return false\n        }\n        \n        if hs[0].n != Norwegian {\n                return false\n        }\n        return true\n}\n\nfunc dist(a, b int) int {\n        if a > b {\n                return a - b\n        }\n        return b - a\n}\n\nfunc main() {\n        log.SetFlags(0)\n        n, sol := simpleBruteForce()\n        fmt.Println(n, \"solution found\")\n        fmt.Println(sol)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n"}
{"id": 55122, "name": "Rosetta Code_Find unimplemented tasks", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n"}
{"id": 55123, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 55124, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 55125, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 55126, "name": "Sokoban", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n"}
{"id": 55127, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 55128, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 55129, "name": "Practical numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n"}
{"id": 55130, "name": "Consecutive primes with ascending or descending differences", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n    pd := 0\n    longSeqs := [][]int{{2}}\n    currSeq := []int{2}\n    for i := 1; i < len(primes); i++ {\n        d := primes[i] - primes[i-1]\n        if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n            if len(currSeq) > len(longSeqs[0]) {\n                longSeqs = [][]int{currSeq}\n            } else if len(currSeq) == len(longSeqs[0]) {\n                longSeqs = append(longSeqs, currSeq)\n            }\n            currSeq = []int{primes[i-1], primes[i]}\n        } else {\n            currSeq = append(currSeq, primes[i])\n        }\n        pd = d\n    }\n    if len(currSeq) > len(longSeqs[0]) {\n        longSeqs = [][]int{currSeq}\n    } else if len(currSeq) == len(longSeqs[0]) {\n        longSeqs = append(longSeqs, currSeq)\n    }\n    fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n    for _, ls := range longSeqs {\n        var diffs []int\n        for i := 1; i < len(ls); i++ {\n            diffs = append(diffs, ls[i]-ls[i-1])\n        }\n        for i := 0; i < len(ls)-1; i++ {\n            fmt.Print(ls[i], \" (\", diffs[i], \") \")\n        }\n        fmt.Println(ls[len(ls)-1])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    fmt.Println(\"For primes < 1 million:\\n\")\n    for _, dir := range []string{\"ascending\", \"descending\"} {\n        longestSeq(dir)\n    }\n}\n", "C#": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        const int mil = (int)1e6;\n        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n        {\n            int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n            var desc = new string[] { \"A\", \"\", \"De\" };\n            int[] mx = new int[] { 0, 0, 0 },\n                  bi = new int[] { 0, 0, 0 },\n                   c = new int[] { 2, 2, 2 };\n            WriteLine(\"For primes up to {0:n0}:\", lmt);\n            var pr = PG.Primes(lmt).ToArray();\n            for (int i = 0; i < pr.Length; i++)\n            {\n                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n                if (ld == d)\n                    c[2 - d]++;\n                else\n                {\n                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n                    c[d] = 2;\n                }\n                ld = d; lg = ng;\n            }\n            for (int r = 0; r <= 2; r += 2)\n            {\n                Write(\"{0}scending, found run of {1} consecutive primes:\\n  {2} \",\n                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n                    Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n            }\n        }\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<TG> Primes(int lim)\n    {\n        bool[] flags = new bool[lim + 1];\n        int j = 3, lj = 2;\n        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n            }\n        for (; j <= lim; j += 2)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n            }\n    }\n}\n"}
{"id": 55131, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 55132, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 55133, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 55134, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 55135, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 55136, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 55137, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 55138, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 55139, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 55140, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 55141, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 55142, "name": "Word search", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n"}
{"id": 55143, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 55144, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 55145, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n"}
{"id": 55146, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 55147, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 55148, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 55149, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 55150, "name": "Zumkeller numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 55151, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 55152, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 55153, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 55154, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 55155, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 55156, "name": "Halt and catch fire", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n", "C#": "int a=0,b=1/a;\n"}
{"id": 55157, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n"}
{"id": 55158, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n"}
{"id": 55159, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n"}
{"id": 55160, "name": "Geometric algebra", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n"}
{"id": 55161, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 55162, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 55163, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 55164, "name": "Define a primitive data type", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n"}
{"id": 55165, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 55166, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 55167, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n"}
{"id": 55168, "name": "Odd squarefree semiprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 55169, "name": "Odd squarefree semiprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 55170, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 55171, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 55172, "name": "Respond to an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n"}
{"id": 55173, "name": "Latin Squares in reduced form", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n"}
{"id": 55174, "name": "Closest-pair problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n"}
{"id": 55175, "name": "Address of a variable", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n", "C#": "int i = 5;\nint* p = &i;\n"}
{"id": 55176, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n"}
{"id": 55177, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n"}
{"id": 55178, "name": "Color wheel", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n"}
{"id": 55179, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 55180, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 55181, "name": "Square root by hand", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n"}
{"id": 55182, "name": "Square root by hand", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n"}
{"id": 55183, "name": "Pandigital prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\n\nfunc permutations(input []int) [][]int {\n    perms := [][]int{input}\n    a := make([]int, len(input))\n    copy(a, input)\n    var n = len(input) - 1\n    for c := 1; c < factorial(n+1); c++ {\n        i := n - 1\n        j := n\n        for a[i] > a[i+1] {\n            i--\n        }\n        for a[j] < a[i] {\n            j--\n        }\n        a[i], a[j] = a[j], a[i]\n        j = n\n        i += 1\n        for i < j {\n            a[i], a[j] = a[j], a[i]\n            i++\n            j--\n        }\n        b := make([]int, len(input))\n        copy(b, a)\n        perms = append(perms, b)\n    }\n    return perms\n}\n\nfunc main() {\nouter:\n    for _, start := range []int{1, 0} {\n        fmt.Printf(\"The largest pandigital decimal prime which uses all the digits %d..n once is:\\n\", start)\n        for _, n := range []int{7, 4} {\n            m := n + 1 - start\n            list := make([]int, m)\n            for i := 0; i < m; i++ {\n                list[i] = i + start\n            }\n            perms := permutations(list)\n            for i := len(perms) - 1; i >= 0; i-- {\n                le := len(perms[i])\n                if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {\n                    continue\n                }\n                p := 0\n                pow := 1\n                for j := le - 1; j >= 0; j-- {\n                    p += perms[i][j] * pow\n                    pow *= 10\n                }\n                if rcu.IsPrime(p) {\n                    fmt.Println(rcu.Commatize(p) + \"\\n\")\n                    continue outer\n                }\n            }\n        }\n    }\n}\n", "C#": "using System;\n \nclass Program {\n  \n \n  \n  \n \n  static void fun(char sp) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    \n    \n    \n \n    for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {\n \n      \n      \n      \n      var s = x.ToString();\n      for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;\n \n      \n      \n      if (x % 3 == 0) continue;\n      for (int i = 1; i * i < x; ) {\n        if (x % (i += 4) == 0) goto nxt;\n        if (x % (i += 2) == 0) goto nxt;\n      }\n      sw.Stop(); Console.WriteLine(\"{0}..7: {1,10:n0} {2} μs\", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;\n      nxt: ;\n    }\n  }\n\nstatic void Main(string[] args) {\n    fun('1');\n    fun('0');\n  }\n}\n"}
{"id": 55184, "name": "Pandigital prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\n\nfunc permutations(input []int) [][]int {\n    perms := [][]int{input}\n    a := make([]int, len(input))\n    copy(a, input)\n    var n = len(input) - 1\n    for c := 1; c < factorial(n+1); c++ {\n        i := n - 1\n        j := n\n        for a[i] > a[i+1] {\n            i--\n        }\n        for a[j] < a[i] {\n            j--\n        }\n        a[i], a[j] = a[j], a[i]\n        j = n\n        i += 1\n        for i < j {\n            a[i], a[j] = a[j], a[i]\n            i++\n            j--\n        }\n        b := make([]int, len(input))\n        copy(b, a)\n        perms = append(perms, b)\n    }\n    return perms\n}\n\nfunc main() {\nouter:\n    for _, start := range []int{1, 0} {\n        fmt.Printf(\"The largest pandigital decimal prime which uses all the digits %d..n once is:\\n\", start)\n        for _, n := range []int{7, 4} {\n            m := n + 1 - start\n            list := make([]int, m)\n            for i := 0; i < m; i++ {\n                list[i] = i + start\n            }\n            perms := permutations(list)\n            for i := len(perms) - 1; i >= 0; i-- {\n                le := len(perms[i])\n                if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {\n                    continue\n                }\n                p := 0\n                pow := 1\n                for j := le - 1; j >= 0; j-- {\n                    p += perms[i][j] * pow\n                    pow *= 10\n                }\n                if rcu.IsPrime(p) {\n                    fmt.Println(rcu.Commatize(p) + \"\\n\")\n                    continue outer\n                }\n            }\n        }\n    }\n}\n", "C#": "using System;\n \nclass Program {\n  \n \n  \n  \n \n  static void fun(char sp) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    \n    \n    \n \n    for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {\n \n      \n      \n      \n      var s = x.ToString();\n      for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;\n \n      \n      \n      if (x % 3 == 0) continue;\n      for (int i = 1; i * i < x; ) {\n        if (x % (i += 4) == 0) goto nxt;\n        if (x % (i += 2) == 0) goto nxt;\n      }\n      sw.Stop(); Console.WriteLine(\"{0}..7: {1,10:n0} {2} μs\", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;\n      nxt: ;\n    }\n  }\n\nstatic void Main(string[] args) {\n    fun('1');\n    fun('0');\n  }\n}\n"}
{"id": 55185, "name": "Primes with digits in nondecreasing order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 55186, "name": "Primes with digits in nondecreasing order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 55187, "name": "Numbers which are not the sum of distinct squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc contains(a []int, n int) bool {\n    for _, e := range a {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\n\nfunc soms(n int, f []int) bool {\n    if n <= 0 {\n        return false\n    }\n    if contains(f, n) {\n        return true\n    }\n    sum := rcu.SumInts(f)\n    if n > sum {\n        return false\n    }\n    if n == sum {\n        return true\n    }\n    rf := make([]int, len(f))\n    copy(rf, f)\n    for i, j := 0, len(rf)-1; i < j; i, j = i+1, j-1 {\n        rf[i], rf[j] = rf[j], rf[i]\n    }\n    rf = rf[1:]\n    return soms(n-f[len(f)-1], rf) || soms(n, rf)\n}\n\nfunc main() {\n    var s, a []int\n    sf := \"\\nStopped checking after finding %d sequential non-gaps after the final gap of %d\\n\"\n    i, g := 1, 1\n    for g >= (i >> 1) {\n        r := int(math.Sqrt(float64(i)))\n        if r*r == i {\n            s = append(s, i)\n        }\n        if !soms(i, s) {\n            g = i\n            a = append(a, g)\n        }\n        i++\n    }\n    fmt.Println(\"Numbers which are not the sum of distinct squares:\")\n    fmt.Println(a)\n    fmt.Printf(sf, i-g, g)\n    fmt.Printf(\"Found %d in total\\n\", len(a))\n}\n\nvar r int\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n \nclass Program {\n \n  \n  static bool soms(int n, IEnumerable<int> f) {\n    if (n <= 0) return false;\n    if (f.Contains(n)) return true;\n    switch(n.CompareTo(f.Sum())) {\n      case 1: return false;\n      case 0: return true;\n      case -1:\n        var rf = f.Reverse().Skip(1).ToList();\n        return soms(n - f.Last(), rf) || soms(n, rf);\n    }\n    return false;\n  }\n\n  static void Main() {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>();\n    var sf = \"stopped checking after finding {0} sequential non-gaps after the final gap of {1}\";\n    for (i = 1, g = 1; g >= (i >> 1); i++) {\n      if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i);\n      if (!soms(i, s)) a.Add(g = i);\n    }\n    sw.Stop();\n    Console.WriteLine(\"Numbers which are not the sum of distinct squares:\");\n    Console.WriteLine(string.Join(\", \", a));\n    Console.WriteLine(sf, i - g, g);\n    Console.Write(\"found {0} total in {1} ms\",\n      a.Count, sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 55188, "name": "Primes which contain only one odd digit", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc allButOneEven(prime int) bool {\n    digits := rcu.Digits(prime, 10)\n    digits = digits[:len(digits)-1]\n    allEven := true\n    for _, d := range digits {\n        if d&1 == 1 {\n            allEven = false\n            break\n        }\n    }\n    return allEven\n}\n\nfunc main() {\n    const (\n        LIMIT      = 999\n        LIMIT2     = 9999999999\n        MAX_DIGITS = 3\n    )\n    primes := rcu.Primes(LIMIT)\n    var results []int\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            results = append(results, prime)\n        }\n    }\n    fmt.Println(\"Primes under\", rcu.Commatize(LIMIT+1), \"which contain only one odd digit:\")\n    for i, p := range results {\n        fmt.Printf(\"%*s \", MAX_DIGITS, rcu.Commatize(p))\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(results), \"such primes.\\n\")\n\n    primes = rcu.Primes(LIMIT2)\n    count := 0\n    pow := 10\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            count++\n        }\n        if prime > pow {\n            fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n            pow *= 10\n        }\n    }\n    fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    \n    \n    static List<uint> sieve(uint max, bool ordinary = false)\n    {\n        uint k = ((max - 3) >> 1) + 1,\n           lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;\n        var pl = new List<uint> { };\n        var ic = new bool[k];\n        for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])\n                for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;\n        if (ordinary)\n        {\n            pl.Add(2);\n            for (uint i = 0, j = 3; i < k; i++, j += 2)\n                if (!ic[i]) pl.Add(j);\n        }\n        else\n            for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)\n                if (!ic[i])\n                {\n                    while ((t /= 10) > 0)\n                        if (((t % 10) & 1) == 1) goto skip;\n                    pl.Add(j);\n                skip:;\n                }\n        return pl;\n    }\n\n    static void Main(string[] args)\n    {\n        var pl = sieve((uint)1e9);\n        uint c = 0, l = 10, p = 1;\n        Console.WriteLine(\"List of one-odd-digit primes < 1,000:\");\n        for (int i = 0; pl[i] < 1000; i++)\n            Console.Write(\"{0,3}{1}\", pl[i], i % 9 == 8 ? \"\\n\" : \"  \");\n        string fmt = \"\\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})\";\n        foreach (var itm in pl)\n            if (itm < l) c++;\n            else Console.Write(fmt, c++, p++, l, l *= 10);\n        Console.Write(fmt, c++, p++, l);\n    }\n}\n"}
{"id": 55189, "name": "Primes which contain only one odd digit", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc allButOneEven(prime int) bool {\n    digits := rcu.Digits(prime, 10)\n    digits = digits[:len(digits)-1]\n    allEven := true\n    for _, d := range digits {\n        if d&1 == 1 {\n            allEven = false\n            break\n        }\n    }\n    return allEven\n}\n\nfunc main() {\n    const (\n        LIMIT      = 999\n        LIMIT2     = 9999999999\n        MAX_DIGITS = 3\n    )\n    primes := rcu.Primes(LIMIT)\n    var results []int\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            results = append(results, prime)\n        }\n    }\n    fmt.Println(\"Primes under\", rcu.Commatize(LIMIT+1), \"which contain only one odd digit:\")\n    for i, p := range results {\n        fmt.Printf(\"%*s \", MAX_DIGITS, rcu.Commatize(p))\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(results), \"such primes.\\n\")\n\n    primes = rcu.Primes(LIMIT2)\n    count := 0\n    pow := 10\n    for _, prime := range primes[1:] {\n        if allButOneEven(prime) {\n            count++\n        }\n        if prime > pow {\n            fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n            pow *= 10\n        }\n    }\n    fmt.Printf(\"There are %7s such primes under %s\\n\", rcu.Commatize(count), rcu.Commatize(pow))\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    \n    \n    static List<uint> sieve(uint max, bool ordinary = false)\n    {\n        uint k = ((max - 3) >> 1) + 1,\n           lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;\n        var pl = new List<uint> { };\n        var ic = new bool[k];\n        for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])\n                for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;\n        if (ordinary)\n        {\n            pl.Add(2);\n            for (uint i = 0, j = 3; i < k; i++, j += 2)\n                if (!ic[i]) pl.Add(j);\n        }\n        else\n            for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)\n                if (!ic[i])\n                {\n                    while ((t /= 10) > 0)\n                        if (((t % 10) & 1) == 1) goto skip;\n                    pl.Add(j);\n                skip:;\n                }\n        return pl;\n    }\n\n    static void Main(string[] args)\n    {\n        var pl = sieve((uint)1e9);\n        uint c = 0, l = 10, p = 1;\n        Console.WriteLine(\"List of one-odd-digit primes < 1,000:\");\n        for (int i = 0; pl[i] < 1000; i++)\n            Console.Write(\"{0,3}{1}\", pl[i], i % 9 == 8 ? \"\\n\" : \"  \");\n        string fmt = \"\\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})\";\n        foreach (var itm in pl)\n            if (itm < l) c++;\n            else Console.Write(fmt, c++, p++, l, l *= 10);\n        Console.Write(fmt, c++, p++, l);\n    }\n}\n"}
{"id": 55190, "name": "Reflection_List properties", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n"}
{"id": 55191, "name": "Minimal steps down to 1", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n    divs, subs []int\n    mins       [][]string\n)\n\n\nfunc minsteps(n int) {\n    if n == 1 {\n        mins[1] = []string{}\n        return\n    }\n    min := limit\n    var p, q int\n    var op byte\n    for _, div := range divs {\n        if n%div == 0 {\n            d := n / div\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, div, '/'\n            }\n        }\n    }\n    for _, sub := range subs {\n        if d := n - sub; d >= 1 {\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, sub, '-'\n            }\n        }\n    }\n    mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n    mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n    for r := 0; r < 2; r++ {\n        divs = []int{2, 3}\n        if r == 0 {\n            subs = []int{1}\n        } else {\n            subs = []int{2}\n        }\n        mins = make([][]string, limit+1)\n        fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n        fmt.Println(\"  Minimum number of steps to diminish the following numbers down to 1 is:\")\n        for i := 1; i <= limit; i++ {\n            minsteps(i)\n            if i <= 10 {\n                steps := len(mins[i])\n                plural := \"s\"\n                if steps == 1 {\n                    plural = \" \"\n                }\n                fmt.Printf(\"    %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n            }\n        }\n        for _, lim := range []int{2000, 20000, 50000} {\n            max := 0\n            for _, min := range mins[0 : lim+1] {\n                m := len(min)\n                if m > max {\n                    max = m\n                }\n            }\n            var maxs []int\n            for i, min := range mins[0 : lim+1] {\n                if len(min) == max {\n                    maxs = append(maxs, i)\n                }\n            }\n            nums := len(maxs)\n            verb, verb2, plural := \"are\", \"have\", \"s\"\n            if nums == 1 {\n                verb, verb2, plural = \"is\", \"has\", \"\"\n            }\n            fmt.Printf(\"  There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n            fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n            fmt.Println(\"   \", maxs)\n        }\n        fmt.Println()\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class MinimalSteps\n{\n    public static void Main() {\n        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });\n        var lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n        Console.WriteLine();\n\n        subtractors = new [] { 2 };\n        lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n    }\n\n    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {\n        for (int goal = 1; goal <= limit; goal++) {\n            var x = lookup[goal];\n            if (x.param == 0) {\n                Console.WriteLine($\"{goal} cannot be reached with these numbers.\");\n                continue;\n            }\n            Console.Write($\"{goal} takes {x.steps} {(x.steps == 1 ? \"step\" : \"steps\")}: \");\n            for (int n = goal; n > 1; ) {\n                Console.Write($\"{n},{x.op}{x.param}=> \");\n                n = x.op == '/' ? n / x.param : n - x.param;\n                x = lookup[n];\n            }\n            Console.WriteLine(\"1\");\n        }\n    }\n\n    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {\n        var maxSteps = lookup.Max(x => x.steps);\n        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();\n        Console.WriteLine(items.Count == 1\n            ? $\"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}\"\n            : $\"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}\"\n        );\n    }\n\n    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)\n    {\n        var lookup = new (char op, int param, int steps)[goal+1];\n        lookup[1] = ('/', 1, 0);\n        for (int n = 1; n < lookup.Length; n++) {\n            var ln = lookup[n];\n            if (ln.param == 0) continue;\n            for (int d = 0; d < divisors.Length; d++) {\n                int target = n * divisors[d];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);\n            }\n            for (int s = 0; s < subtractors.Length; s++) {\n                int target = n + subtractors[s];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);\n            }\n        }\n        return lookup;\n    }\n\n    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(\", \", source);\n}\n"}
{"id": 55192, "name": "Align columns", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n"}
{"id": 55193, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 55194, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 55195, "name": "Idoneal numbers", "Go": "package main\n\nimport \"rcu\"\n\nfunc isIdoneal(n int) bool {\n    for a := 1; a < n; a++ {\n        for b := a + 1; b < n; b++ {\n            if a*b+a+b > n {\n                break\n            }\n            for c := b + 1; c < n; c++ {\n                sum := a*b + b*c + a*c\n                if sum == n {\n                    return false\n                }\n                if sum > n {\n                    break\n                }\n            }\n        }\n    }\n    return true\n}\n\nfunc main() {\n    var idoneals []int\n    for n := 1; n <= 1850; n++ {\n        if isIdoneal(n) {\n            idoneals = append(idoneals, n)\n        }\n    }\n    rcu.PrintTable(idoneals, 13, 4, false)\n}\n", "C#": "using System;\n\nclass Program {\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int a, b, c, i, n, s3, ab; var res = new int[65];\n    for (n = 1, i = 0; n < 1850; n++) {\n      bool found = true;\n      for (a = 1; a < n; a++)\n         for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {\n            if (ab > n) break;\n            for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {\n                if (s3 == n) found = false;\n                if (s3 >= n) break;\n            }\n         }\n      if (found) res[i++] = n;\n    }\n    sw.Stop();\n    Console.WriteLine(\"The 65 known Idoneal numbers:\");\n    for (i = 0; i < res.Length; i++)\n      Console.Write(\"{0,5}{1}\", res[i], i % 13 == 12 ? \"\\n\" : \"\");\n    Console.Write(\"Calculations took {0} ms\", sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 55196, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 55197, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 55198, "name": "Dynamic variable names", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n"}
{"id": 55199, "name": "Data Encryption Standard", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace DES {\n    class Program {\n        \n        static string ByteArrayToString(byte[] ba) {\n            return BitConverter.ToString(ba).Replace(\"-\", \"\");\n        }\n\n        \n        \n        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(messageBytes, 0, messageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] encryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n\n            return encryptedMessageBytes;\n        }\n\n        \n        \n        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] decryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);\n\n            return decryptedMessageBytes;\n        }\n\n        static void Main(string[] args) {\n            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };\n            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };\n\n            byte[] encStr = Encrypt(plainBytes, keyBytes);\n            Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr));\n\n            byte[] decBytes = Decrypt(encStr, keyBytes);\n            Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decBytes));\n        }\n    }\n}\n"}
{"id": 55200, "name": "Multidimensional Newton-Raphson method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\ntype fun = func(vector) float64\ntype funs = []fun\ntype jacobian = []funs\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m1 matrix) sub(m2 matrix) matrix {\n    rows, cols := len(m1), len(m1[0])\n    if rows != len(m2) || cols != len(m2[0]) {\n        panic(\"Matrices cannot be subtracted.\")\n    }\n    result := make(matrix, rows)\n    for i := 0; i < rows; i++ {\n        result[i] = make(vector, cols)\n        for j := 0; j < cols; j++ {\n            result[i][j] = m1[i][j] - m2[i][j]\n        }\n    }\n    return result\n}\n\nfunc (m matrix) transpose() matrix {\n    rows, cols := len(m), len(m[0])\n    trans := make(matrix, cols)\n    for i := 0; i < cols; i++ {\n        trans[i] = make(vector, rows)\n        for j := 0; j < rows; j++ {\n            trans[i][j] = m[j][i]\n        }\n    }\n    return trans\n}\n\nfunc (m matrix) inverse() matrix {\n    le := len(m)\n    for _, v := range m {\n        if len(v) != le {\n            panic(\"Not a square matrix\")\n        }\n    }\n    aug := make(matrix, le)\n    for i := 0; i < le; i++ {\n        aug[i] = make(vector, 2*le)\n        copy(aug[i], m[i])\n        \n        aug[i][i+le] = 1\n    }\n    aug.toReducedRowEchelonForm()\n    inv := make(matrix, le)\n    \n    for i := 0; i < le; i++ {\n        inv[i] = make(vector, le)\n        copy(inv[i], aug[i][le:])\n    }\n    return inv\n}\n\n\nfunc (m matrix) toReducedRowEchelonForm() {\n    lead := 0\n    rowCount, colCount := len(m), len(m[0])\n    for r := 0; r < rowCount; r++ {\n        if colCount <= lead {\n            return\n        }\n        i := r\n\n        for m[i][lead] == 0 {\n            i++\n            if rowCount == i {\n                i = r\n                lead++\n                if colCount == lead {\n                    return\n                }\n            }\n        }\n\n        m[i], m[r] = m[r], m[i]\n        if div := m[r][lead]; div != 0 {\n            for j := 0; j < colCount; j++ {\n                m[r][j] /= div\n            }\n        }\n\n        for k := 0; k < rowCount; k++ {\n            if k != r {\n                mult := m[k][lead]\n                for j := 0; j < colCount; j++ {\n                    m[k][j] -= m[r][j] * mult\n                }\n            }\n        }\n        lead++\n    }\n}\n\nfunc solve(fs funs, jacob jacobian, guesses vector) vector {\n    size := len(fs)\n    var gu1 vector\n    gu2 := make(vector, len(guesses))\n    copy(gu2, guesses)\n    jac := make(matrix, size)\n    for i := 0; i < size; i++ {\n        jac[i] = make(vector, size)\n    }\n    tol := 1e-8\n    maxIter := 12\n    iter := 0\n    for {\n        gu1 = gu2\n        g := matrix{gu1}.transpose()\n        t := make(vector, size)\n        for i := 0; i < size; i++ {\n            t[i] = fs[i](gu1)\n        }\n        f := matrix{t}.transpose()\n        for i := 0; i < size; i++ {\n            for j := 0; j < size; j++ {\n                jac[i][j] = jacob[i][j](gu1)\n            }\n        }\n        g1 := g.sub(jac.inverse().mul(f))\n        gu2 = make(vector, size)\n        for i := 0; i < size; i++ {\n            gu2[i] = g1[i][0]\n        }\n        iter++\n        any := false\n        for i, v := range gu2 {\n            if math.Abs(v)-gu1[i] > tol {\n                any = true\n                break\n            }\n        }\n        if !any || iter >= maxIter {\n            break\n        }\n    }\n    return gu2\n}\n\nfunc main() {\n    \n    f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }\n    f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }\n    fs := funs{f1, f2}\n    jacob := jacobian{\n        funs{\n            func(x vector) float64 { return -2*x[0] + 1 },\n            func(x vector) float64 { return -1 },\n        },\n        funs{\n            func(x vector) float64 { return 5*x[1] - 2*x[0] },\n            func(x vector) float64 { return 1 + 5*x[0] },\n        },\n    }\n    guesses := vector{1.2, 1.2}\n    sol := solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f\\n\", sol[0], sol[1])\n\n    \n\n    fmt.Println()\n    f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }\n    f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }\n    f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }\n    fs = funs{f3, f4, f5}\n    jacob = jacobian{\n        funs{\n            func(x vector) float64 { return 18 * x[0] },\n            func(x vector) float64 { return 72 * x[1] },\n            func(x vector) float64 { return 8 * x[2] },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -4 * x[1] },\n            func(x vector) float64 { return -20 },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -2 * x[1] },\n            func(x vector) float64 { return 2 * x[2] },\n        },\n    }\n    guesses = vector{1, 1, 0}\n    sol = solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f,  z = %.7f\\n\", sol[0], sol[1], sol[2])\n}\n", "C#": "using System;\n\nnamespace Rosetta\n{\n    internal interface IFun\n    {\n        double F(int index, Vector x);\n        double df(int index, int derivative, Vector x);\n        double[] weights();\n    }\n\n    class Newton\n    {                \n        internal Vector Do(int size, IFun fun, Vector start)\n        {\n            Vector X = start.Clone();\n            Vector F = new Vector(size);\n            Matrix J = new Matrix(size, size);\n            Vector D;\n            do\n            {\n                for (int i = 0; i < size; i++)\n                    F[i] = fun.F(i, X);\n                for (int i = 0; i < size; i++)\n                    for (int j = 0; j < size; j++)\n                        J[i, j] = fun.df(i, j, X);\n                J.ElimPartial(F);\n                X -= F;\n                \n            } while (F.norm(fun.weights()) > 1e-12);\n            return X;\n        }       \n    }\n}\n"}
{"id": 55201, "name": "Multidimensional Newton-Raphson method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\ntype fun = func(vector) float64\ntype funs = []fun\ntype jacobian = []funs\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m1 matrix) sub(m2 matrix) matrix {\n    rows, cols := len(m1), len(m1[0])\n    if rows != len(m2) || cols != len(m2[0]) {\n        panic(\"Matrices cannot be subtracted.\")\n    }\n    result := make(matrix, rows)\n    for i := 0; i < rows; i++ {\n        result[i] = make(vector, cols)\n        for j := 0; j < cols; j++ {\n            result[i][j] = m1[i][j] - m2[i][j]\n        }\n    }\n    return result\n}\n\nfunc (m matrix) transpose() matrix {\n    rows, cols := len(m), len(m[0])\n    trans := make(matrix, cols)\n    for i := 0; i < cols; i++ {\n        trans[i] = make(vector, rows)\n        for j := 0; j < rows; j++ {\n            trans[i][j] = m[j][i]\n        }\n    }\n    return trans\n}\n\nfunc (m matrix) inverse() matrix {\n    le := len(m)\n    for _, v := range m {\n        if len(v) != le {\n            panic(\"Not a square matrix\")\n        }\n    }\n    aug := make(matrix, le)\n    for i := 0; i < le; i++ {\n        aug[i] = make(vector, 2*le)\n        copy(aug[i], m[i])\n        \n        aug[i][i+le] = 1\n    }\n    aug.toReducedRowEchelonForm()\n    inv := make(matrix, le)\n    \n    for i := 0; i < le; i++ {\n        inv[i] = make(vector, le)\n        copy(inv[i], aug[i][le:])\n    }\n    return inv\n}\n\n\nfunc (m matrix) toReducedRowEchelonForm() {\n    lead := 0\n    rowCount, colCount := len(m), len(m[0])\n    for r := 0; r < rowCount; r++ {\n        if colCount <= lead {\n            return\n        }\n        i := r\n\n        for m[i][lead] == 0 {\n            i++\n            if rowCount == i {\n                i = r\n                lead++\n                if colCount == lead {\n                    return\n                }\n            }\n        }\n\n        m[i], m[r] = m[r], m[i]\n        if div := m[r][lead]; div != 0 {\n            for j := 0; j < colCount; j++ {\n                m[r][j] /= div\n            }\n        }\n\n        for k := 0; k < rowCount; k++ {\n            if k != r {\n                mult := m[k][lead]\n                for j := 0; j < colCount; j++ {\n                    m[k][j] -= m[r][j] * mult\n                }\n            }\n        }\n        lead++\n    }\n}\n\nfunc solve(fs funs, jacob jacobian, guesses vector) vector {\n    size := len(fs)\n    var gu1 vector\n    gu2 := make(vector, len(guesses))\n    copy(gu2, guesses)\n    jac := make(matrix, size)\n    for i := 0; i < size; i++ {\n        jac[i] = make(vector, size)\n    }\n    tol := 1e-8\n    maxIter := 12\n    iter := 0\n    for {\n        gu1 = gu2\n        g := matrix{gu1}.transpose()\n        t := make(vector, size)\n        for i := 0; i < size; i++ {\n            t[i] = fs[i](gu1)\n        }\n        f := matrix{t}.transpose()\n        for i := 0; i < size; i++ {\n            for j := 0; j < size; j++ {\n                jac[i][j] = jacob[i][j](gu1)\n            }\n        }\n        g1 := g.sub(jac.inverse().mul(f))\n        gu2 = make(vector, size)\n        for i := 0; i < size; i++ {\n            gu2[i] = g1[i][0]\n        }\n        iter++\n        any := false\n        for i, v := range gu2 {\n            if math.Abs(v)-gu1[i] > tol {\n                any = true\n                break\n            }\n        }\n        if !any || iter >= maxIter {\n            break\n        }\n    }\n    return gu2\n}\n\nfunc main() {\n    \n    f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }\n    f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }\n    fs := funs{f1, f2}\n    jacob := jacobian{\n        funs{\n            func(x vector) float64 { return -2*x[0] + 1 },\n            func(x vector) float64 { return -1 },\n        },\n        funs{\n            func(x vector) float64 { return 5*x[1] - 2*x[0] },\n            func(x vector) float64 { return 1 + 5*x[0] },\n        },\n    }\n    guesses := vector{1.2, 1.2}\n    sol := solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f\\n\", sol[0], sol[1])\n\n    \n\n    fmt.Println()\n    f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }\n    f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }\n    f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }\n    fs = funs{f3, f4, f5}\n    jacob = jacobian{\n        funs{\n            func(x vector) float64 { return 18 * x[0] },\n            func(x vector) float64 { return 72 * x[1] },\n            func(x vector) float64 { return 8 * x[2] },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -4 * x[1] },\n            func(x vector) float64 { return -20 },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -2 * x[1] },\n            func(x vector) float64 { return 2 * x[2] },\n        },\n    }\n    guesses = vector{1, 1, 0}\n    sol = solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f,  z = %.7f\\n\", sol[0], sol[1], sol[2])\n}\n", "C#": "using System;\n\nnamespace Rosetta\n{\n    internal interface IFun\n    {\n        double F(int index, Vector x);\n        double df(int index, int derivative, Vector x);\n        double[] weights();\n    }\n\n    class Newton\n    {                \n        internal Vector Do(int size, IFun fun, Vector start)\n        {\n            Vector X = start.Clone();\n            Vector F = new Vector(size);\n            Matrix J = new Matrix(size, size);\n            Vector D;\n            do\n            {\n                for (int i = 0; i < size; i++)\n                    F[i] = fun.F(i, X);\n                for (int i = 0; i < size; i++)\n                    for (int j = 0; j < size; j++)\n                        J[i, j] = fun.df(i, j, X);\n                J.ElimPartial(F);\n                X -= F;\n                \n            } while (F.norm(fun.weights()) > 1e-12);\n            return X;\n        }       \n    }\n}\n"}
{"id": 55202, "name": "Multidimensional Newton-Raphson method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\ntype fun = func(vector) float64\ntype funs = []fun\ntype jacobian = []funs\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m1 matrix) sub(m2 matrix) matrix {\n    rows, cols := len(m1), len(m1[0])\n    if rows != len(m2) || cols != len(m2[0]) {\n        panic(\"Matrices cannot be subtracted.\")\n    }\n    result := make(matrix, rows)\n    for i := 0; i < rows; i++ {\n        result[i] = make(vector, cols)\n        for j := 0; j < cols; j++ {\n            result[i][j] = m1[i][j] - m2[i][j]\n        }\n    }\n    return result\n}\n\nfunc (m matrix) transpose() matrix {\n    rows, cols := len(m), len(m[0])\n    trans := make(matrix, cols)\n    for i := 0; i < cols; i++ {\n        trans[i] = make(vector, rows)\n        for j := 0; j < rows; j++ {\n            trans[i][j] = m[j][i]\n        }\n    }\n    return trans\n}\n\nfunc (m matrix) inverse() matrix {\n    le := len(m)\n    for _, v := range m {\n        if len(v) != le {\n            panic(\"Not a square matrix\")\n        }\n    }\n    aug := make(matrix, le)\n    for i := 0; i < le; i++ {\n        aug[i] = make(vector, 2*le)\n        copy(aug[i], m[i])\n        \n        aug[i][i+le] = 1\n    }\n    aug.toReducedRowEchelonForm()\n    inv := make(matrix, le)\n    \n    for i := 0; i < le; i++ {\n        inv[i] = make(vector, le)\n        copy(inv[i], aug[i][le:])\n    }\n    return inv\n}\n\n\nfunc (m matrix) toReducedRowEchelonForm() {\n    lead := 0\n    rowCount, colCount := len(m), len(m[0])\n    for r := 0; r < rowCount; r++ {\n        if colCount <= lead {\n            return\n        }\n        i := r\n\n        for m[i][lead] == 0 {\n            i++\n            if rowCount == i {\n                i = r\n                lead++\n                if colCount == lead {\n                    return\n                }\n            }\n        }\n\n        m[i], m[r] = m[r], m[i]\n        if div := m[r][lead]; div != 0 {\n            for j := 0; j < colCount; j++ {\n                m[r][j] /= div\n            }\n        }\n\n        for k := 0; k < rowCount; k++ {\n            if k != r {\n                mult := m[k][lead]\n                for j := 0; j < colCount; j++ {\n                    m[k][j] -= m[r][j] * mult\n                }\n            }\n        }\n        lead++\n    }\n}\n\nfunc solve(fs funs, jacob jacobian, guesses vector) vector {\n    size := len(fs)\n    var gu1 vector\n    gu2 := make(vector, len(guesses))\n    copy(gu2, guesses)\n    jac := make(matrix, size)\n    for i := 0; i < size; i++ {\n        jac[i] = make(vector, size)\n    }\n    tol := 1e-8\n    maxIter := 12\n    iter := 0\n    for {\n        gu1 = gu2\n        g := matrix{gu1}.transpose()\n        t := make(vector, size)\n        for i := 0; i < size; i++ {\n            t[i] = fs[i](gu1)\n        }\n        f := matrix{t}.transpose()\n        for i := 0; i < size; i++ {\n            for j := 0; j < size; j++ {\n                jac[i][j] = jacob[i][j](gu1)\n            }\n        }\n        g1 := g.sub(jac.inverse().mul(f))\n        gu2 = make(vector, size)\n        for i := 0; i < size; i++ {\n            gu2[i] = g1[i][0]\n        }\n        iter++\n        any := false\n        for i, v := range gu2 {\n            if math.Abs(v)-gu1[i] > tol {\n                any = true\n                break\n            }\n        }\n        if !any || iter >= maxIter {\n            break\n        }\n    }\n    return gu2\n}\n\nfunc main() {\n    \n    f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }\n    f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }\n    fs := funs{f1, f2}\n    jacob := jacobian{\n        funs{\n            func(x vector) float64 { return -2*x[0] + 1 },\n            func(x vector) float64 { return -1 },\n        },\n        funs{\n            func(x vector) float64 { return 5*x[1] - 2*x[0] },\n            func(x vector) float64 { return 1 + 5*x[0] },\n        },\n    }\n    guesses := vector{1.2, 1.2}\n    sol := solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f\\n\", sol[0], sol[1])\n\n    \n\n    fmt.Println()\n    f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }\n    f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }\n    f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }\n    fs = funs{f3, f4, f5}\n    jacob = jacobian{\n        funs{\n            func(x vector) float64 { return 18 * x[0] },\n            func(x vector) float64 { return 72 * x[1] },\n            func(x vector) float64 { return 8 * x[2] },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -4 * x[1] },\n            func(x vector) float64 { return -20 },\n        },\n        funs{\n            func(x vector) float64 { return 2 * x[0] },\n            func(x vector) float64 { return -2 * x[1] },\n            func(x vector) float64 { return 2 * x[2] },\n        },\n    }\n    guesses = vector{1, 1, 0}\n    sol = solve(fs, jacob, guesses)\n    fmt.Printf(\"Approximate solutions are x = %.7f,  y = %.7f,  z = %.7f\\n\", sol[0], sol[1], sol[2])\n}\n", "C#": "using System;\n\nnamespace Rosetta\n{\n    internal interface IFun\n    {\n        double F(int index, Vector x);\n        double df(int index, int derivative, Vector x);\n        double[] weights();\n    }\n\n    class Newton\n    {                \n        internal Vector Do(int size, IFun fun, Vector start)\n        {\n            Vector X = start.Clone();\n            Vector F = new Vector(size);\n            Matrix J = new Matrix(size, size);\n            Vector D;\n            do\n            {\n                for (int i = 0; i < size; i++)\n                    F[i] = fun.F(i, X);\n                for (int i = 0; i < size; i++)\n                    for (int j = 0; j < size; j++)\n                        J[i, j] = fun.df(i, j, X);\n                J.ElimPartial(F);\n                X -= F;\n                \n            } while (F.norm(fun.weights()) > 1e-12);\n            return X;\n        }       \n    }\n}\n"}
{"id": 55203, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n"}
{"id": 55204, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n"}
{"id": 55205, "name": "Largest palindrome product", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(n uint64) uint64 {\n    r := uint64(0)\n    for n > 0 {\n        r = n%10 + r*10\n        n /= 10\n    }\n    return r\n}\n\nfunc main() {\n    pow := uint64(10)\nnextN:\n    for n := 2; n < 10; n++ {\n        low := pow * 9\n        pow *= 10\n        high := pow - 1\n        fmt.Printf(\"Largest palindromic product of two %d-digit integers: \", n)\n        for i := high; i >= low; i-- {\n            j := reverse(i)\n            p := i*pow + j\n            \n            for k := high; k > low; k -= 2 {\n                if k % 10 == 5 {\n                    continue\n                }\n                l := p / k\n                if l > high {\n                    break\n                }\n                if p%k == 0 {\n                    fmt.Printf(\"%d x %d = %d\\n\", k, l, p)\n                    continue nextN\n                }\n            }\n        }\n    }\n}\n", "C#": "using System;\nclass Program {\n\n  static bool isPal(int n) {\n    int rev = 0, lr = -1, rem;\n    while (n > rev) {\n      n = Math.DivRem(n, 10, out rem);\n      if (lr < 0 && rem == 0) return false;\n      lr = rev; rev = 10 * rev + rem;\n      if (n == rev || n == lr) return true;\n    } return false; }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;\n    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = \"\";\n    y /= 11;\n    if ((y & 1) == 0) y--;\n    if (y % 5 == 0) y -= 2;\n    y *= 11;\n    while (y <= max) {\n      c = 0;\n      y10 = y * 10;\n      z = max9 + a[ld = y % 10];\n      p = y * z;\n      while (p >= bp) {\n        if (isPal(p)) {\n          if (p > bp) bp = p;\n          bs = string.Format(\"{0} x {1} = {2}\", y, z - c, bp);\n        }\n        p -= y10; c += 10;\n      }\n      y += ld == 3 ? 44 : 22;\n    }\n    sw.Stop();\n    Console.Write(\"{0} {1} μs\", bs, sw.Elapsed.TotalMilliseconds * 1000.0);\n  }\n}\n"}
{"id": 55206, "name": "Commatizing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n"}
{"id": 55207, "name": "Arithmetic coding_As a generalized change of radix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 55208, "name": "Kosaraju", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 55209, "name": "Kosaraju", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 55210, "name": "Reflection_List methods", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n"}
{"id": 55211, "name": "Send an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n"}
{"id": 55212, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n"}
{"id": 55213, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n"}
{"id": 55214, "name": "Add a variable to a class instance at runtime", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n", "C#": "\n\n\n\n\n\n\n\nusing System;\nusing System.Dynamic;\n\nnamespace DynamicClassVariable\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            \n            \n            dynamic sampleObj = new ExpandoObject();\n            \n            sampleObj.bar = 1;\n            Console.WriteLine( \"sampleObj.bar = {0}\", sampleObj.bar );\n\n            \n            \n            \n            \n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 55215, "name": "Time-based one-time password algorithm", "Go": "\n\n\npackage onetime\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"hash\"\n\t\"math\"\n\t\"time\"\n)\n\n\ntype OneTimePassword struct {\n\tDigit    int              \n\tTimeStep time.Duration    \n\tBaseTime time.Time        \n\tHash     func() hash.Hash \n}\n\n\nfunc (otp *OneTimePassword) HOTP(secret []byte, count uint64) uint {\n\ths := otp.hmacSum(secret, count)\n\treturn otp.truncate(hs)\n}\n\nfunc (otp *OneTimePassword) hmacSum(secret []byte, count uint64) []byte {\n\tmac := hmac.New(otp.Hash, secret)\n\tbinary.Write(mac, binary.BigEndian, count)\n\treturn mac.Sum(nil)\n}\n\nfunc (otp *OneTimePassword) truncate(hs []byte) uint {\n\tsbits := dt(hs)\n\tsnum := uint(sbits[3]) | uint(sbits[2])<<8\n\tsnum |= uint(sbits[1])<<16 | uint(sbits[0])<<24\n\treturn snum % uint(math.Pow(10, float64(otp.Digit)))\n}\n\n\n\n\nfunc Simple(digit int) (otp OneTimePassword, err error) {\n\tif digit < 6 {\n\t\terr = errors.New(\"minimum of 6 digits is required for a valid HTOP code\")\n\t\treturn\n\t} else if digit > 9 {\n\t\terr = errors.New(\"HTOP code cannot be longer than 9 digits\")\n\t\treturn\n\t}\n\tconst step = 30 * time.Second\n\totp = OneTimePassword{digit, step, time.Unix(0, 0), sha1.New}\n\treturn\n}\n\n\nfunc (otp *OneTimePassword) TOTP(secret []byte) uint {\n\treturn otp.HOTP(secret, otp.steps(time.Now()))\n}\n\nfunc (otp *OneTimePassword) steps(now time.Time) uint64 {\n\telapsed := now.Unix() - otp.BaseTime.Unix()\n\treturn uint64(float64(elapsed) / otp.TimeStep.Seconds())\n}\n\nfunc dt(hs []byte) []byte {\n\toffset := int(hs[len(hs)-1] & 0xf)\n\tp := hs[offset : offset+4]\n\tp[0] &= 0x7f\n\treturn p\n}\n", "C#": "using System;\nusing System.Security.Cryptography;\n\nnamespace RosettaTOTP\n{\n    public class TOTP_SHA1\n    {\n        private byte[] K;\n        public TOTP_SHA1()\n        {\n            GenerateKey();\n        }\n        public void GenerateKey()\n        {\n            using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())\n            {\n                \n                K = new byte[HMACSHA1.Create().HashSize / 8];\n                rng.GetBytes(K);\n            }\n        }\n        public int HOTP(UInt64 C, int digits = 6)\n        {\n            var hmac = HMACSHA1.Create();\n            hmac.Key = K;\n            hmac.ComputeHash(BitConverter.GetBytes(C));\n            return Truncate(hmac.Hash, digits);\n        }\n        public UInt64 CounterNow(int T1 = 30)\n        {\n            var secondsSinceEpoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;\n            return (UInt64)Math.Floor(secondsSinceEpoch / T1);\n        }\n        private int DT(byte[] hmac_result)\n        {\n            int offset = hmac_result[19] & 0xf;\n            int bin_code = (hmac_result[offset] & 0x7f) << 24\n               | (hmac_result[offset + 1] & 0xff) << 16\n               | (hmac_result[offset + 2] & 0xff) << 8\n               | (hmac_result[offset + 3] & 0xff);\n            return bin_code;\n        }\n\n        private int Truncate(byte[] hmac_result, int digits)\n        {\n            var Snum = DT(hmac_result);\n            return Snum % (int)Math.Pow(10, digits);\n        }\n    }\n\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var totp = new TOTP_SHA1();\n            Console.WriteLine(totp.HOTP(totp.CounterNow()));\n        }\n    }\n}\n"}
{"id": 55216, "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", "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": 55217, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\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": 55218, "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", "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": 55219, "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", "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": 55220, "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", "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": 55221, "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", "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": 55222, "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", "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": 55223, "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", "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": 55224, "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", "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": 55225, "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", "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": 55226, "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", "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"}
{"id": 55227, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 55228, "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", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 55229, "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", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 55230, "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", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 55231, "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", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 55232, "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", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 55233, "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", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 55234, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n"}
{"id": 55235, "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", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55236, "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", "C": "#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <fcntl.h>\n\nvoid * record(size_t bytes)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_RDONLY))) return 0;\n\tvoid *a = malloc(bytes);\n\tread(fd, a, bytes);\n\tclose(fd);\n\treturn a;\n}\n\nint play(void *buf, size_t len)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_WRONLY))) return 0;\n\twrite(fd, buf, len);\n\tclose(fd);\n\treturn 1;\n}\n\nint main()\n{\n\tvoid *p = record(65536);\n\tplay(p, 65536);\n\treturn 0;\n}\n"}
{"id": 55237, "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", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55238, "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", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 55239, "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", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n"}
{"id": 55240, "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", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55241, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n"}
{"id": 55242, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55243, "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", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 55244, "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", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 55245, "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", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 55246, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55247, "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", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 55248, "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", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55249, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 55250, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 55251, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 55252, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55253, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 55254, "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", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 55255, "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", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 55256, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n"}
{"id": 55257, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n"}
{"id": 55258, "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", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n"}
{"id": 55259, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\n"}
{"id": 55260, "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", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\n"}
{"id": 55261, "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", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n"}
{"id": 55262, "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", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n"}
{"id": 55263, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 55264, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 55265, "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", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 55266, "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", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 55267, "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", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 55268, "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", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 55269, "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", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n"}
{"id": 55270, "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", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 55271, "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", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 55272, "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", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 55273, "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", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 55274, "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", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 55275, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 55276, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 55277, "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", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 55278, "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", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n"}
{"id": 55279, "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", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n"}
{"id": 55280, "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", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n"}
{"id": 55281, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 55282, "name": "Write entire file", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 55283, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 55284, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 55285, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 55286, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 55287, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 55288, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 55289, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 55290, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 55291, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 55292, "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", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55293, "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", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\n"}
{"id": 55294, "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", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 55295, "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", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55296, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 55297, "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", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 55298, "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", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 55299, "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", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 55300, "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", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55301, "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", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55302, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 55303, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 55304, "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", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 55305, "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", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 55306, "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", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 55307, "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", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 55308, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 55309, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 55310, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 55311, "name": "Carmichael 3 strong pseudoprimes", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n"}
{"id": 55312, "name": "Image noise", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 55313, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55314, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55315, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55316, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 55317, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 55318, "name": "Conjugate transpose", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n"}
{"id": 55319, "name": "Conjugate transpose", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n"}
{"id": 55320, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55321, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55322, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 55323, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 55324, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 55325, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 55326, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 55327, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 55328, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 55329, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 55330, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 55331, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 55332, "name": "Fermat numbers", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <gmp.h>\n\nvoid mpz_factors(mpz_t n) {\n  int factors = 0;\n  mpz_t s, m, p;\n  mpz_init(s), mpz_init(m), mpz_init(p);\n\n  mpz_set_ui(m, 3);\n  mpz_set(p, n);\n  mpz_sqrt(s, p);\n\n  while (mpz_cmp(m, s) < 0) {\n    if (mpz_divisible_p(p, m)) {\n      gmp_printf(\"%Zd \", m);\n      mpz_fdiv_q(p, p, m);\n      mpz_sqrt(s, p);\n      factors ++;\n    }\n    mpz_add_ui(m, m, 2);\n  }\n\n  if (factors == 0) printf(\"PRIME\\n\");\n  else gmp_printf(\"%Zd\\n\", p);\n}\n\nint main(int argc, char const *argv[]) {\n  mpz_t fermat;\n  mpz_init_set_ui(fermat, 3);\n  printf(\"F(0) = 3 -> PRIME\\n\");\n  for (unsigned i = 1; i < 10; i ++) {\n    mpz_sub_ui(fermat, fermat, 1);\n    mpz_mul(fermat, fermat, fermat);\n    mpz_add_ui(fermat, fermat, 1);\n    gmp_printf(\"F(%d) = %Zd -> \", i, fermat);\n    mpz_factors(fermat);\n  }\n\n  return 0;\n}\n"}
{"id": 55333, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 55334, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 55335, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 55336, "name": "Water collected between towers", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55337, "name": "Descending primes", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 55338, "name": "Square-free integers", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 55339, "name": "Jaro similarity", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n"}
{"id": 55340, "name": "Sum and product puzzle", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n"}
{"id": 55341, "name": "Fairshare between two and more", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 55342, "name": "Two bullet roulette", "Python": "\nimport numpy as np\n\nclass Revolver:\n    \n\n    def __init__(self):\n        \n        self.cylinder = np.array([False] * 6)\n\n    def unload(self):\n        \n        self.cylinder[:] = False\n\n    def load(self):\n        \n        while self.cylinder[1]:\n            self.cylinder[:] = np.roll(self.cylinder, 1)\n        self.cylinder[1] = True\n\n    def spin(self):\n        \n        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n    def fire(self):\n        \n        shot = self.cylinder[0]\n        self.cylinder[:] = np.roll(self.cylinder, 1)\n        return shot\n\n    def LSLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LSLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n    def LLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n\nif __name__ == '__main__':\n\n    REV = Revolver()\n    TESTCOUNT = 100000\n    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n                           ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n        print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstatic int nextInt(int size) {\n    return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n    bool t = cylinder[5];\n    int i;\n    for (i = 4; i >= 0; i--) {\n        cylinder[i + 1] = cylinder[i];\n    }\n    cylinder[0] = t;\n}\n\nstatic void unload() {\n    int i;\n    for (i = 0; i < 6; i++) {\n        cylinder[i] = false;\n    }\n}\n\nstatic void load() {\n    while (cylinder[0]) {\n        rshift();\n    }\n    cylinder[0] = true;\n    rshift();\n}\n\nstatic void spin() {\n    int lim = nextInt(6) + 1;\n    int i;\n    for (i = 1; i < lim; i++) {\n        rshift();\n    }\n}\n\nstatic bool fire() {\n    bool shot = cylinder[0];\n    rshift();\n    return shot;\n}\n\nstatic int method(const char *s) {\n    unload();\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            load();\n            break;\n        case 'S':\n            spin();\n            break;\n        case 'F':\n            if (fire()) {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n    if (*out != '\\0') {\n        strcat(out, \", \");\n    }\n    strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            append(out, \"load\");\n            break;\n        case 'S':\n            append(out, \"spin\");\n            break;\n        case 'F':\n            append(out, \"fire\");\n            break;\n        }\n    }\n}\n\nstatic void test(char *src) {\n    char buffer[41] = \"\";\n    const int tests = 100000;\n    int sum = 0;\n    int t;\n    double pc;\n\n    for (t = 0; t < tests; t++) {\n        sum += method(src);\n    }\n\n    mstring(src, buffer);\n    pc = 100.0 * sum / tests;\n\n    printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n    srand(time(0));\n\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n"}
{"id": 55343, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55344, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n"}
{"id": 55345, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 55346, "name": "Sequence_ nth number with exactly n divisors", "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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55347, "name": "Sequence_ smallest number with exactly n divisors", "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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55348, "name": "Sequence_ smallest number with exactly n divisors", "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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55349, "name": "Pancake numbers", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55350, "name": "Generate random chess position", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n"}
{"id": 55351, "name": "Esthetic numbers", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n"}
{"id": 55352, "name": "Topswops", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55353, "name": "Old Russian measure of length", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55354, "name": "Rate counter", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n"}
{"id": 55355, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55356, "name": "Padovan sequence", "Python": "from math import floor\nfrom collections import deque\nfrom typing import Dict, Generator\n\n\ndef padovan_r() -> Generator[int, None, None]:\n    last = deque([1, 1, 1], 4)\n    while True:\n        last.append(last[-2] + last[-3])\n        yield last.popleft()\n\n_p, _s = 1.324717957244746025960908854, 1.0453567932525329623\n\ndef padovan_f(n: int) -> int:\n    return floor(_p**(n-1) / _s + .5)\n\ndef padovan_l(start: str='A',\n             rules: Dict[str, str]=dict(A='B', B='C', C='AB')\n             ) -> Generator[str, None, None]:\n    axiom = start\n    while True:\n        yield axiom\n        axiom = ''.join(rules[ch] for ch in axiom)\n\n\nif __name__ == \"__main__\":\n    from itertools import islice\n\n    print(\"The first twenty terms of the sequence.\")\n    print(str([padovan_f(n) for n in range(20)])[1:-1])\n\n    r_generator = padovan_r()\n    if all(next(r_generator) == padovan_f(n) for n in range(64)):\n        print(\"\\nThe recurrence and floor based algorithms match to n=63 .\")\n    else:\n        print(\"\\nThe recurrence and floor based algorithms DIFFER!\")\n\n    print(\"\\nThe first 10 L-system string-lengths and strings\")\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    print('\\n'.join(f\"  {len(string):3} {repr(string)}\"\n                    for string in islice(l_generator, 10)))\n\n    r_generator = padovan_r()\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)\n           for n in range(32)):\n        print(\"\\nThe L-system, recurrence and floor based algorithms match to n=31 .\")\n    else:\n        print(\"\\nThe L-system, recurrence and floor based algorithms DIFFER!\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n"}
{"id": 55357, "name": "Pythagoras tree", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n"}
{"id": 55358, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 55359, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55360, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 55361, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 55362, "name": "Biorhythms", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n"}
{"id": 55363, "name": "Biorhythms", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n"}
{"id": 55364, "name": "Table creation_Postal addresses", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55365, "name": "Sine wave", "Python": "\n\nimport os\nfrom math import pi, sin\n\n\nau_header = bytearray(\n            [46, 115, 110, 100,   \n              0,   0,   0,  24,   \n            255, 255, 255, 255,   \n              0,   0,   0,   3,   \n              0,   0, 172,  68,   \n              0,   0,   0,   1])  \n\ndef f(x, freq):\n    \"Compute sine wave as 16-bit integer\"\n    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536\n\ndef play_sine(freq=440, duration=5, oname=\"pysine.au\"):\n    \"Play a sine wave for `duration` seconds\"\n    out = open(oname, 'wb')\n    out.write(au_header)\n    v = [f(x, freq) for x in range(duration * 44100 + 1)]\n    s = []\n    for i in v:\n        s.append(i >> 8)\n        s.append(i % 256)\n    out.write(bytearray(s))\n    out.close()\n    os.system(\"vlc \" + oname)   \n\nplay_sine()\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n\nint header[] = {46, 115, 110, 100, 0, 0, 0, 24,\n                255, 255, 255, 255, 0, 0, 0, 3,\n                0, 0, 172, 68, 0, 0, 0, 1};\n\nint main(int argc, char *argv[]){\n        float freq, dur;\n        long i, v;\n\n        if (argc < 3) {\n                printf(\"Usage:\\n\");\n                printf(\"  csine <frequency> <duration>\\n\");\n                exit(1);\n        }\n        freq = atof(argv[1]);\n        dur = atof(argv[2]);\n        for (i = 0; i < 24; i++)\n                putchar(header[i]);\n        for (i = 0; i < dur * 44100; i++) {\n                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));\n                v = v % 65536;\n                putchar(v >> 8);\n                putchar(v % 256);\n        }\n}\n"}
{"id": 55366, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 55367, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 55368, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 55369, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 55370, "name": "Numeric error propagation", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n"}
{"id": 55371, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55372, "name": "List rooted trees", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n"}
{"id": 55373, "name": "Documentation", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n"}
{"id": 55374, "name": "Table creation", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n"}
{"id": 55375, "name": "Table creation", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n"}
{"id": 55376, "name": "Problem of Apollonius", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n"}
{"id": 55377, "name": "Append numbers at same position in strings", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n"}
{"id": 55378, "name": "Append numbers at same position in strings", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n"}
{"id": 55379, "name": "Append numbers at same position in strings", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n"}
{"id": 55380, "name": "Longest common suffix", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n"}
{"id": 55381, "name": "Longest common suffix", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n"}
{"id": 55382, "name": "Chat server", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n"}
{"id": 55383, "name": "Idiomatically determine all the lowercase and uppercase letters", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n", "C": "#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n  putchar('\\n');\n  for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n  putchar('\\n');\n  return 0;\n}\n"}
{"id": 55384, "name": "Sum of elements below main diagonal of matrix", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n"}
{"id": 55385, "name": "Retrieve and search chat history", "Python": "\nimport datetime\nimport re\nimport urllib.request\nimport sys\n\ndef get(url):\n    with urllib.request.urlopen(url) as response:\n       html = response.read().decode('utf-8')\n    if re.match(r'<!Doctype HTML[\\s\\S]*<Title>URL Not Found</Title>', html):\n        return None\n    return html\n\ndef main():\n    template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'\n    today = datetime.datetime.utcnow()\n    back = 10\n    needle = sys.argv[1]\n    \n    \n    \n    for i in range(-back, 2):\n        day = today + datetime.timedelta(days=i)\n        url = day.strftime(template)\n        haystack = get(url)\n        if haystack:\n            mentions = [x for x in haystack.split('\\n') if needle in x]\n            if mentions:\n                print('{}\\n------\\n{}\\n------\\n'\n                          .format(url, '\\n'.join(mentions)))\n\nmain()\n", "C": "#include<curl/curl.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAX_LEN 1000\n\nvoid searchChatLogs(char* searchString){\n\tchar* baseURL = \"http:\n\ttime_t t;\n\tstruct tm* currentDate;\n\tchar dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];\n\tint i,flag;\n\tFILE *fp;\n\t\n\tCURL *curl;\n\tCURLcode res;\n\t\n\ttime(&t);\n\tcurrentDate = localtime(&t);\n\t\n\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\n\tprintf(\"Today is : %s\",dateString);\n\t\n\tif((curl = curl_easy_init())!=NULL){\n\t\tfor(i=0;i<=10;i++){\n\t\t\t\n\t\tflag = 0;\n\t\tsprintf(targetURL,\"%s%s.tcl\",baseURL,dateString);\n\t\t\n\t\tstrcpy(dateStringFile,dateString);\n\t\t\n\t\tprintf(\"\\nRetrieving chat logs from %s\\n\",targetURL);\n\t\t\n\t\tif((fp = fopen(\"nul\",\"w\"))==0){\n\t\t\tprintf(\"Cant's read from %s\",targetURL);\n\t\t}\n\t\telse{\n\t\t\tcurl_easy_setopt(curl, CURLOPT_URL, targetURL);\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);\n\t\t\n\t\tres = curl_easy_perform(curl);\n\t\t\n\t\tif(res == CURLE_OK){\n\t\t\twhile(fgets(lineData,MAX_LEN,fp)!=NULL){\n\t\t\t\tif(strstr(lineData,searchString)!=NULL){\n\t\t\t\t\tflag = 1;\n\t\t\t\t\tfputs(lineData,stdout);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(flag==0)\n\t\t\t\tprintf(\"\\nNo matching lines found.\");\n\t\t}\n\t\tfflush(fp);\n\t\tfclose(fp);\n\t\t}\n\t\t\n\t\tcurrentDate->tm_mday--;\n\t\tmktime(currentDate);\n\t\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\t\n\t\t\t\n\t}\n\tcurl_easy_cleanup(curl);\n\t\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <followed by search string, enclosed by \\\" if it contains spaces>\",argV[0]);\n\telse\n\t\tsearchChatLogs(argV[1]);\n\treturn 0;\n}\n"}
{"id": 55386, "name": "Rosetta Code_Rank languages by number of users", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55387, "name": "Rosetta Code_Rank languages by number of users", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55388, "name": "Addition-chain exponentiation", "Python": "\n\nfrom math import sqrt\nfrom numpy import array\nfrom mpmath import mpf\n\n\nclass AdditionChains:\n    \n\n    def __init__(self):\n        \n        self.chains, self.idx, self.pos = [[1]], 0, 0\n        self.pat, self.lvl = {1: 0}, [[1]]\n\n    def add_chain(self):\n        \n        newchain = self.chains[self.idx].copy()\n        newchain.append(self.chains[self.idx][-1] +\n                        self.chains[self.idx][self.pos])\n        self.chains.append(newchain)\n        if self.pos == len(self.chains[self.idx])-1:\n            self.idx += 1\n            self.pos = 0\n        else:\n            self.pos += 1\n        return newchain\n\n    def find_chain(self, nexp):\n        \n        assert nexp > 0\n        if nexp == 1:\n            return [1]\n        chn = next((a for a in self.chains if a[-1] == nexp), None)\n        if chn is None:\n            while True:\n                chn = self.add_chain()\n                if chn[-1] == nexp:\n                    break\n\n        return chn\n\n    def knuth_path(self, ngoal):\n        \n        if ngoal < 1:\n            return []\n        while not ngoal in self.pat:\n            new_lvl = []\n            for i in self.lvl[0]:\n                for j in self.knuth_path(i):\n                    if not i + j in self.pat:\n                        self.pat[i + j] = i\n                        new_lvl.append(i + j)\n\n            self.lvl[0] = new_lvl\n\n        returnpath = self.knuth_path(self.pat[ngoal])\n        returnpath.append(ngoal)\n        return returnpath\n\n\ndef cpow(xbase, chain):\n    \n    pows, products = 0, {0: 1, 1: xbase}\n    for i in chain:\n        products[i] = products[pows] * products[i - pows]\n        pows = i\n    return products[chain[-1]]\n\n\nif __name__ == '__main__':\n    \n    acs = AdditionChains()\n    print('First one hundred addition chain lengths:')\n    for k in range(1, 101):\n        print(f'{len(acs.find_chain(k))-1:3}', end='\\n'if k % 10 == 0 else '')\n\n    print('\\nKnuth chains for addition chains of 31415 and 27182:')\n    chns = {m: acs.knuth_path(m) for m in [31415, 27182]}\n    for (num, cha) in chns.items():\n        print(f'Exponent: {num:10}\\n  Addition Chain: {cha[:-1]}')\n    print('\\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))\n    print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))\n    print('1.000025 + 0.000058i)^27182 =',\n          cpow(complex(1.000025, 0.000058), chns[27182]))\n    print('1.000022 + 0.000050i)^31415 =',\n          cpow(complex(1.000022, 0.000050), chns[31415]))\n    sq05 = mpf(sqrt(0.5))\n    mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],\n                 [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])\n    print('matrix A ^ 27182 =')\n    print(cpow(mat, chns[27182]))\n    print('matrix A ^ 31415 =')\n    print(cpow(mat, chns[31415]))\n    print('(matrix A ** 27182) ** 31415 =')\n    print(cpow(cpow(mat, chns[27182]), chns[31415]))\n", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n"}
{"id": 55389, "name": "Addition-chain exponentiation", "Python": "\n\nfrom math import sqrt\nfrom numpy import array\nfrom mpmath import mpf\n\n\nclass AdditionChains:\n    \n\n    def __init__(self):\n        \n        self.chains, self.idx, self.pos = [[1]], 0, 0\n        self.pat, self.lvl = {1: 0}, [[1]]\n\n    def add_chain(self):\n        \n        newchain = self.chains[self.idx].copy()\n        newchain.append(self.chains[self.idx][-1] +\n                        self.chains[self.idx][self.pos])\n        self.chains.append(newchain)\n        if self.pos == len(self.chains[self.idx])-1:\n            self.idx += 1\n            self.pos = 0\n        else:\n            self.pos += 1\n        return newchain\n\n    def find_chain(self, nexp):\n        \n        assert nexp > 0\n        if nexp == 1:\n            return [1]\n        chn = next((a for a in self.chains if a[-1] == nexp), None)\n        if chn is None:\n            while True:\n                chn = self.add_chain()\n                if chn[-1] == nexp:\n                    break\n\n        return chn\n\n    def knuth_path(self, ngoal):\n        \n        if ngoal < 1:\n            return []\n        while not ngoal in self.pat:\n            new_lvl = []\n            for i in self.lvl[0]:\n                for j in self.knuth_path(i):\n                    if not i + j in self.pat:\n                        self.pat[i + j] = i\n                        new_lvl.append(i + j)\n\n            self.lvl[0] = new_lvl\n\n        returnpath = self.knuth_path(self.pat[ngoal])\n        returnpath.append(ngoal)\n        return returnpath\n\n\ndef cpow(xbase, chain):\n    \n    pows, products = 0, {0: 1, 1: xbase}\n    for i in chain:\n        products[i] = products[pows] * products[i - pows]\n        pows = i\n    return products[chain[-1]]\n\n\nif __name__ == '__main__':\n    \n    acs = AdditionChains()\n    print('First one hundred addition chain lengths:')\n    for k in range(1, 101):\n        print(f'{len(acs.find_chain(k))-1:3}', end='\\n'if k % 10 == 0 else '')\n\n    print('\\nKnuth chains for addition chains of 31415 and 27182:')\n    chns = {m: acs.knuth_path(m) for m in [31415, 27182]}\n    for (num, cha) in chns.items():\n        print(f'Exponent: {num:10}\\n  Addition Chain: {cha[:-1]}')\n    print('\\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))\n    print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))\n    print('1.000025 + 0.000058i)^27182 =',\n          cpow(complex(1.000025, 0.000058), chns[27182]))\n    print('1.000022 + 0.000050i)^31415 =',\n          cpow(complex(1.000022, 0.000050), chns[31415]))\n    sq05 = mpf(sqrt(0.5))\n    mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],\n                 [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])\n    print('matrix A ^ 27182 =')\n    print(cpow(mat, chns[27182]))\n    print('matrix A ^ 31415 =')\n    print(cpow(mat, chns[31415]))\n    print('(matrix A ** 27182) ** 31415 =')\n    print(cpow(cpow(mat, chns[27182]), chns[31415]))\n", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n"}
{"id": 55390, "name": "Terminal control_Unicode output", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n"}
{"id": 55391, "name": "Terminal control_Unicode output", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n"}
{"id": 55392, "name": "Find adjacent primes which differ by a square integer", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n"}
{"id": 55393, "name": "Find adjacent primes which differ by a square integer", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n"}
{"id": 55394, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 55395, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 55396, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 55397, "name": "Video display modes", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55398, "name": "Video display modes", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55399, "name": "Keyboard input_Flush the keyboard buffer", "Python": "def flush_input():\n    try:\n        import msvcrt\n        while msvcrt.kbhit():\n            msvcrt.getch()\n    except ImportError:\n        import sys, termios\n        termios.tcflush(sys.stdin, termios.TCIOFLUSH)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char* argv[])\n{\n    \n    \n    char text[256];\n    getchar();\n\n    \n    \n    \n    \n\n    \n    \n    fseek(stdin, 0, SEEK_END);\n\n    \n    \n    \n\n    \n    \n    fgets(text, sizeof(text), stdin);\n    puts(text);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55400, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n"}
{"id": 55401, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n"}
{"id": 55402, "name": "FASTA format", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n"}
{"id": 55403, "name": "Cousin primes", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\n    return 0;\n}\n"}
{"id": 55404, "name": "Cousin primes", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\n    return 0;\n}\n"}
{"id": 55405, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55406, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55407, "name": "Check input device is a terminal", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n"}
{"id": 55408, "name": "Check input device is a terminal", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n"}
{"id": 55409, "name": "Window creation_X11", "Python": "from Xlib import X, display\n\nclass Window:\n    def __init__(self, display, msg):\n        self.display = display\n        self.msg = msg\n        \n        self.screen = self.display.screen()\n        self.window = self.screen.root.create_window(\n            10, 10, 100, 100, 1,\n            self.screen.root_depth,\n            background_pixel=self.screen.white_pixel,\n            event_mask=X.ExposureMask | X.KeyPressMask,\n            )\n        self.gc = self.window.create_gc(\n            foreground = self.screen.black_pixel,\n            background = self.screen.white_pixel,\n            )\n\n        self.window.map()\n\n    def loop(self):\n        while True:\n            e = self.display.next_event()\n                \n            if e.type == X.Expose:\n                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n                self.window.draw_text(self.gc, 10, 50, self.msg)\n            elif e.type == X.KeyPress:\n                raise SystemExit\n\n                \nif __name__ == \"__main__\":\n    Window(display.Display(), \"Hello, World!\").loop()\n", "C": "'--- added a flush to exit cleanly   \nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n \n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n \n'---pointer to X Display structure\nDECLARE d TYPE  Display*\n \n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n \n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n \nDECLARE msg TYPE char*\n \n'--- number of screen to place the window on\nDECLARE s TYPE int\n \n \n \n  msg = \"Hello, World!\"\n \n \n   d = DISPLAY(NULL)\n   IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n   END IF\n \n   s = SCREEN(d)\n   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n \n   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n   MAP_EVENT(d, w)\n \n   WHILE  (1) \n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t    BREAK\n\t END IF   \n   WEND\n   FLUSH(d)\n   CLOSE_DISPLAY(d)\n"}
{"id": 55410, "name": "Elementary cellular automaton_Random number generator", "Python": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n    cells = '1' + '0' * (lencells - 1)\n    gen = eca(cells, 30)\n    while True:\n        yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n    print([b for i,b in zip(range(10), rule30bytes())])\n", "C": "#include <stdio.h>\n#include <limits.h>\n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}\n"}
{"id": 55411, "name": "Terminal control_Dimensions", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n"}
{"id": 55412, "name": "Finite state machine", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n"}
{"id": 55413, "name": "Vibrating rectangles", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n", "C": "\n\n#include<graphics.h>\n\nvoid vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)\n{\n\tint color = 1,i,x = winWidth/2, y = winHeight/2;\n\t\n\twhile(!kbhit()){\n\t\tsetcolor(color++);\n\t\tfor(i=num;i>0;i--){\n\t\t\trectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);\n\t\t\tdelay(msec);\n\t\t}\n\n\t\tif(color>MAXCOLORS){\n\t\t\tcolor = 1;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Vibrating Rectangles...\");\n\t\n\tvibratingRectangles(1000,1000,30,15,20,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 55414, "name": "Last list item", "Python": "\n\ndef add_least_reduce(lis):\n    \n    while len(lis) > 1:\n        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))\n        print('Interim list:', lis)\n    return lis\n\nLIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]\n\nprint(LIST, ' ==> ', add_least_reduce(LIST.copy()))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint compare(const void *a, const void *b) {\n    int aa = *(const int *)a;\n    int bb = *(const int *)b;\n    if (aa < bb) return -1;\n    if (aa > bb) return 1;\n    return 0;\n}\n\nint main() {\n    int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};\n    int isize = sizeof(int);\n    int asize = sizeof(a) / isize;\n    int i, sum;\n    while (asize > 1) {\n        qsort(a, asize, isize, compare);\n        printf(\"Sorted list: \");\n        for (i = 0; i < asize; ++i) printf(\"%d \", a[i]);\n        printf(\"\\n\");\n        sum = a[0] + a[1];\n        printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum);\n        for (i = 2; i < asize; ++i) a[i-2] = a[i];\n        a[asize - 2] = sum;\n        asize--;\n    }\n    printf(\"Last item is %d.\\n\", a[0]);\n    return 0;\n}\n"}
{"id": 55415, "name": "Minimum numbers of three lists", "Python": "numbers1 = [5,45,23,21,67]\nnumbers2 = [43,22,78,46,38]\nnumbers3 = [9,98,12,98,53]\n\nnumbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]\n\nprint(numbers)\n", "C": "#include <stdio.h>\n\nint min(int a, int b) {\n    if (a < b) return a;\n    return b;\n}\n\nint main() {\n    int n;\n    int numbers1[5] = {5, 45, 23, 21, 67};\n    int numbers2[5] = {43, 22, 78, 46, 38};\n    int numbers3[5] = {9, 98, 12, 98, 53};\n    int numbers[5]  = {};\n    for (n = 0; n < 5; ++n) {\n        numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);\n        printf(\"%d \", numbers[n]);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55416, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 55417, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 55418, "name": "Pseudo-random numbers_PCG32", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55419, "name": "Deconvolution_1D", "Python": "def ToReducedRowEchelonForm( M ):\n    if not M: return\n    lead = 0\n    rowCount = len(M)\n    columnCount = len(M[0])\n    for r in range(rowCount):\n        if lead >= columnCount:\n            return\n        i = r\n        while M[i][lead] == 0:\n            i += 1\n            if i == rowCount:\n                i = r\n                lead += 1\n                if columnCount == lead:\n                    return\n        M[i],M[r] = M[r],M[i]\n        lv = M[r][lead]\n        M[r] = [ mrx / lv for mrx in M[r]]\n        for i in range(rowCount):\n            if i != r:\n                lv = M[i][lead]\n                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n        lead += 1\n    return M\n \ndef pmtx(mtx):\n    print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n \ndef convolve(f, h):\n    g = [0] * (len(f) + len(h) - 1)\n    for hindex, hval in enumerate(h):\n        for findex, fval in enumerate(f):\n            g[hindex + findex] += fval * hval\n    return g\n\ndef deconvolve(g, f):\n    lenh = len(g) - len(f) + 1\n    mtx = [[0 for x in range(lenh+1)] for y in g]\n    for hindex in range(lenh):\n        for findex, fval in enumerate(f):\n            gindex = hindex + findex\n            mtx[gindex][hindex] = fval\n    for gindex, gval in enumerate(g):        \n        mtx[gindex][lenh] = gval\n    ToReducedRowEchelonForm( mtx )\n    return [mtx[i][lenh] for i in range(lenh)]  \n\nif __name__ == '__main__':\n    h = [-8,-9,-3,-1,-6,7]\n    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n    assert convolve(f,h) == g\n    assert deconvolve(g, f) == h\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n"}
{"id": 55420, "name": "Bitmap_PPM conversion through a pipe", "Python": "\n\nfrom PIL import Image\n\nim = Image.open(\"boxes_1.ppm\")\nim.save(\"boxes_1.jpg\")\n", "C": "\nvoid print_jpg(image img, int qual);\n"}
{"id": 55421, "name": "Bitcoin_public point to address", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n"}
{"id": 55422, "name": "Bitcoin_public point to address", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n"}
{"id": 55423, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 55424, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 55425, "name": "Disarium numbers", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n"}
{"id": 55426, "name": "Disarium numbers", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n"}
{"id": 55427, "name": "Sierpinski pentagon", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 55428, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n"}
{"id": 55429, "name": "Padovan n-step number sequences", "Python": "def pad_like(max_n=8, t=15):\n    \n    start = [[], [1, 1, 1]]     \n    for n in range(2, max_n+1):\n        this = start[n-1][:n+1]     \n        while len(this) < t:\n            this.append(sum(this[i] for i in range(-2, -n - 2, -1)))\n        start.append(this)\n    return start[2:]\n\ndef pr(p):\n    print(.strip())\n    for n, seq in enumerate(p, 2):\n        print(f\"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\\n|-\")\n    print('|}')\n\nif __name__ == '__main__':\n    p = pad_like()\n    pr(p)\n", "C": "#include <stdio.h>\n\nvoid padovanN(int n, size_t t, int *p) {\n    int i, j;\n    if (n < 2 || t < 3) {\n        for (i = 0; i < t; ++i) p[i] = 1;\n        return;\n    }\n    padovanN(n-1, t, p);\n    for (i = n + 1; i < t; ++i) {\n        p[i] = 0;\n        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];\n    }\n}\n\nint main() {\n    int n, i;\n    const size_t t = 15;\n    int p[t];\n    printf(\"First %ld terms of the Padovan n-step number sequences:\\n\", t);\n    for (n = 2; n <= 8; ++n) {\n        for (i = 0; i < t; ++i) p[i] = 0;\n        padovanN(n, t, p);\n        printf(\"%d: \", n);\n        for (i = 0; i < t; ++i) printf(\"%3d \", p[i]);\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55430, "name": "Mutex", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n", "C": "HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);\n"}
{"id": 55431, "name": "Metronome", "Python": "\nimport time\n\ndef main(bpm = 72, bpb = 4):\n    sleep = 60.0 / bpm\n    counter = 0\n    while True:\n        counter += 1\n        if counter % bpb:\n            print 'tick'\n        else:\n            print 'TICK'\n        time.sleep(sleep)\n        \n\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/time.h>\n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); \n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec)   \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}\n"}
{"id": 55432, "name": "Native shebang", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n"}
{"id": 55433, "name": "Native shebang", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n"}
{"id": 55434, "name": "EKG sequence convergence", "Python": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n    \n    c = count(start + 1)\n    last, so_far = start, list(range(2, start))\n    yield 1, []\n    yield last, []\n    while True:\n        for index, sf in enumerate(so_far):\n            if gcd(last, sf) > 1:\n                last = so_far.pop(index)\n                yield last, so_far[::]\n                break\n        else:\n            so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n    \"Returns the convergence point or zero if not found within the limit\"\n    ekg = [EKG_gen(n) for n in ekgs]\n    for e in ekg:\n        next(e)    \n    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),\n                                  zip(*ekg))))\n\nif __name__ == '__main__':\n    for start in 2, 5, 7, 9, 10:\n        print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n    print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n    int aa = *(int *)a;\n    int bb = *(int *)b;\n    return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n    int i;\n    for (i = 0; i < len; ++i) {\n        if (a[i] == b) return TRUE;\n    }\n    return FALSE;\n}\n\nint gcd(int a, int b) {\n    while (a != b) {\n        if (a > b)\n            a -= b;\n        else\n            b -= a;\n    }\n    return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n    int i;\n    qsort(s, len, sizeof(int), compareInts);    \n    qsort(t, len, sizeof(int), compareInts);\n    for (i = 0; i < len; ++i) {\n        if (s[i] != t[i]) return FALSE;\n    }\n    return TRUE;\n}\n\nint main() {\n    int s, n, i;\n    int starts[5] = {2, 5, 7, 9, 10};\n    int ekg[5][LIMIT];\n    for (s = 0; s < 5; ++s) {\n        ekg[s][0] = 1;\n        ekg[s][1] = starts[s];\n        for (n = 2; n < LIMIT; ++n) {\n            for (i = 2; ; ++i) {\n                \n                \n                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n                    ekg[s][n] = i;\n                    break;\n                }\n            }\n        }\n        printf(\"EKG(%2d): [\", starts[s]);\n        for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n        printf(\"\\b]\\n\");\n    }\n    \n    \n    for (i = 2; i < LIMIT; ++i) {\n        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n            printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n            return 0;\n        }\n    }\n    printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n    return 0;\n}\n"}
{"id": 55435, "name": "Rep-string", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55436, "name": "Terminal control_Preserve screen", "Python": "\n\nimport time\n\nprint \"\\033[?1049h\\033[H\"\nprint \"Alternate buffer!\"\n\nfor i in xrange(5, 0, -1):\n    print \"Going back in:\", i\n    time.sleep(1)\n\nprint \"\\033[?1049l\"\n", "C": "#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n\tint i;\n\tprintf(\"\\033[?1049h\\033[H\");\n\tprintf(\"Alternate screen buffer\\n\");\n\tfor (i = 5; i; i--) {\n\t\tprintf(\"\\rgoing back in %d...\", i);\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tprintf(\"\\033[?1049l\");\n\n\treturn 0;\n}\n"}
{"id": 55437, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "C": "char ch = 'z';\n"}
{"id": 55438, "name": "Changeable words", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55439, "name": "Changeable words", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55440, "name": "Window management", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n"}
{"id": 55441, "name": "Monads_List monad", "Python": "\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n    @classmethod\n    def unit(cls, value: Iterable[T]) -> MList[T]:\n        return cls(value)\n\n    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return MList(chain.from_iterable(map(func, self)))\n\n    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return self.bind(func)\n\n\nif __name__ == \"__main__\":\n    \n    print(\n        MList([1, 99, 4])\n        .bind(lambda val: MList([val + 1]))\n        .bind(lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList([1, 99, 4])\n        >> (lambda val: MList([val + 1]))\n        >> (lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList(range(1, 6)).bind(\n            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n        )\n    )\n\n    \n    print(\n        MList(range(1, 26)).bind(\n            lambda x: MList(range(x + 1, 26)).bind(\n                lambda y: MList(range(y + 1, 26)).bind(\n                    lambda z: MList([(x, y, z)])\n                    if x * x + y * y == z * z\n                    else MList([])\n                )\n            )\n        )\n    )\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n    return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n    char buf[100];\n    char*str= malloc(1+sprintf(buf, \"%d\", *x));\n    sprintf(str, \"%d\", *x);\n    return (MONAD)(str);\n}\n\nvoid task(int y) {\n    char *z= INTBIND(boundInt2str, boundInt, &y);\n    printf(\"%s\\n\", z);\n    free(z);\n}\n\nint main() {\n    task(13);\n}\n"}
{"id": 55442, "name": "Find squares n where n+1 is prime", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55443, "name": "Find squares n where n+1 is prime", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55444, "name": "Find squares n where n+1 is prime", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55445, "name": "Next special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n"}
{"id": 55446, "name": "Next special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n"}
{"id": 55447, "name": "Mayan numerals", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n"}
{"id": 55448, "name": "Mayan numerals", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n"}
{"id": 55449, "name": "Special factorials", "Python": "\n\nfrom math import prod\n\ndef superFactorial(n):\n    return prod([prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef hyperFactorial(n):\n    return prod([i**i for i in range(1,n+1)])\n\ndef alternatingFactorial(n):\n    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef exponentialFactorial(n):\n    if n in [0,1]:\n        return 1\n    else:\n        return n**exponentialFactorial(n-1)\n        \ndef inverseFactorial(n):\n    i = 1\n    while True:\n        if n == prod(range(1,i)):\n            return i-1\n        elif n < prod(range(1,i)):\n            return \"undefined\"\n        i+=1\n\nprint(\"Superfactorials for [0,9] :\")\nprint({\"sf(\" + str(i) + \") \" : superFactorial(i) for i in range(0,10)})\n\nprint(\"\\nHyperfactorials for [0,9] :\")\nprint({\"H(\" + str(i) + \") \"  : hyperFactorial(i) for i in range(0,10)})\n\nprint(\"\\nAlternating factorials for [0,9] :\")\nprint({\"af(\" + str(i) + \") \" : alternatingFactorial(i) for i in range(0,10)})\n\nprint(\"\\nExponential factorials for [0,4] :\")\nprint({str(i) + \"$ \" : exponentialFactorial(i) for i in range(0,5)})\n\nprint(\"\\nDigits in 5$ : \" , len(str(exponentialFactorial(5))))\n\nfactorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n\nprint(\"\\nInverse factorials for \" , factorialSet)\nprint({\"rf(\" + str(i) + \") \":inverseFactorial(i) for i in factorialSet})\n\nprint(\"\\nrf(119) : \" + inverseFactorial(119))\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 55450, "name": "Special neighbor primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n"}
{"id": 55451, "name": "Special neighbor primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n"}
{"id": 55452, "name": "Ramsey's theorem", "Python": "range17 = range(17)\na = [['0'] * 17 for i in range17]\nidx = [0] * 4\n\n\ndef find_group(mark, min_n, max_n, depth=1):\n    if (depth == 4):\n        prefix = \"\" if (mark == '1') else \"un\"\n        print(\"Fail, found totally {}connected group:\".format(prefix))\n        for i in range(4):\n            print(idx[i])\n        return True\n\n    for i in range(min_n, max_n):\n        n = 0\n        while (n < depth):\n            if (a[idx[n]][i] != mark):\n                break\n            n += 1\n\n        if (n == depth):\n            idx[n] = i\n            if (find_group(mark, 1, max_n, depth + 1)):\n                return True\n\n    return False\n\n\nif __name__ == '__main__':\n    for i in range17:\n        a[i][i] = '-'\n    for k in range(4):\n        for i in range17:\n            j = (i + pow(2, k)) % 17\n            a[i][j] = a[j][i] = '1'\n\n    \n    \n\n    for row in a:\n        print(' '.join(row))\n\n    for i in range17:\n        idx[0] = i\n        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):\n            print(\"no good\")\n            exit()\n\n    print(\"all good\")\n", "C": "#include <stdio.h>\n\nint a[17][17], idx[4];\n\nint find_group(int type, int min_n, int max_n, int depth)\n{\n\tint i, n;\n\tif (depth == 4) {\n\t\tprintf(\"totally %sconnected group:\", type ? \"\" : \"un\");\n\t\tfor (i = 0; i < 4; i++) printf(\" %d\", idx[i]);\n\t\tputchar('\\n');\n\t\treturn 1;\n\t}\n\n\tfor (i = min_n; i < max_n; i++) {\n\t\tfor (n = 0; n < depth; n++)\n\t\t\tif (a[idx[n]][i] != type) break;\n\n\t\tif (n == depth) {\n\t\t\tidx[n] = i;\n\t\t\tif (find_group(type, 1, max_n, depth + 1))\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tconst char *mark = \"01-\";\n\n\tfor (i = 0; i < 17; i++)\n\t\ta[i][i] = 2;\n\n\tfor (k = 1; k <= 8; k <<= 1) {\n\t\tfor (i = 0; i < 17; i++) {\n\t\t\tj = (i + k) % 17;\n\t\t\ta[i][j] = a[j][i] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < 17; i++) {\n\t\tfor (j = 0; j < 17; j++)\n\t\t\tprintf(\"%c \", mark[a[i][j]]);\n\t\tputchar('\\n');\n\t}\n\n\t\n\t\n\n\t\n\tfor (i = 0; i < 17; i++) {\n\t\tidx[0] = i;\n\t\tif (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {\n\t\t\tputs(\"no good\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"all good\");\n\treturn 0;\n}\n"}
{"id": 55453, "name": "GUI_Maximum window dimensions", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n"}
{"id": 55454, "name": "Terminal control_Inverse video", "Python": "\n\nprint \"\\033[7mReversed\\033[m Normal\"\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tprintf(\"\\033[7mReversed\\033[m Normal\\n\");\n\n\treturn 0;\n}\n"}
{"id": 55455, "name": "Four is magic", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 55456, "name": "Getting the number of decimals", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 55457, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 55458, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55459, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55460, "name": "Minimum number of cells after, before, above and below NxN squares", "Python": "def min_cells_matrix(siz):\n    return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]\n\ndef display_matrix(mat):\n    siz = len(mat)\n    spaces = 2 if siz < 20 else 3 if siz < 200 else 4\n    print(f\"\\nMinimum number of cells after, before, above and below {siz} x {siz} square:\")\n    for row in range(siz):\n        print(\"\".join([f\"{n:{spaces}}\" for n in mat[row]]))\n\ndef test_min_mat():\n    for siz in [23, 10, 9, 2, 1]:\n        display_matrix(min_cells_matrix(siz))\n\nif __name__ == \"__main__\":\n    test_min_mat()\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\n#define min(a, b) (a<=b?a:b)\n\nvoid minab( unsigned int n ) {\n    int i, j;\n    for(i=0;i<n;i++) {\n        for(j=0;j<n;j++) {\n            printf( \"%2d  \", min( min(i, n-1-i), min(j, n-1-j) ));\n        }\n        printf( \"\\n\" );\n    }\n    return;\n}\n\nint main(void) {\n    minab(10);\n    return 0;\n}\n"}
{"id": 55461, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55462, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55463, "name": "Parse an IP Address", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"}
{"id": 55464, "name": "Matrix digital rain", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n"}
{"id": 55465, "name": "Matrix digital rain", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n"}
{"id": 55466, "name": "Mind boggling card trick", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n"}
{"id": 55467, "name": "Mind boggling card trick", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n"}
{"id": 55468, "name": "Textonyms", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55469, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n"}
{"id": 55470, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n"}
{"id": 55471, "name": "Teacup rim text", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\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 <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55472, "name": "Increasing gaps between consecutive Niven numbers", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 55473, "name": "Print debugging statement", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n"}
{"id": 55474, "name": "Find prime n such that reversed n is also prime", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n"}
{"id": 55475, "name": "Find prime n such that reversed n is also prime", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n"}
{"id": 55476, "name": "Find prime n such that reversed n is also prime", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\n", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n"}
{"id": 55477, "name": "Superellipse", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55478, "name": "Superellipse", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55479, "name": "Permutations_Rank of a permutation", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n"}
{"id": 55480, "name": "Permutations_Rank of a permutation", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n"}
{"id": 55481, "name": "Banker's algorithm", "Python": "def main():\n    resources = int(input(\"Cantidad de recursos: \"))\n    processes = int(input(\"Cantidad de procesos: \"))\n    max_resources = [int(i) for i in input(\"Recursos máximos: \").split()]\n\n    print(\"\\n-- recursos asignados para cada proceso  --\")\n    currently_allocated = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    print(\"\\n--- recursos máximos para cada proceso  ---\")\n    max_need = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    allocated = [0] * resources\n    for i in range(processes):\n        for j in range(resources):\n            allocated[j] += currently_allocated[i][j]\n    print(f\"\\nRecursos totales asignados  : {allocated}\")\n\n    available = [max_resources[i] - allocated[i] for i in range(resources)]\n    print(f\"Recursos totales disponibles: {available}\\n\")\n\n    running = [True] * processes\n    count = processes\n    while count != 0:\n        safe = False\n        for i in range(processes):\n            if running[i]:\n                executing = True\n                for j in range(resources):\n                    if max_need[i][j] - currently_allocated[i][j] > available[j]:\n                        executing = False\n                        break\n                if executing:\n                    print(f\"proceso {i + 1} ejecutándose\")\n                    running[i] = False\n                    count -= 1\n                    safe = True\n                    for j in range(resources):\n                        available[j] += currently_allocated[i][j]\n                    break\n        if not safe:\n            print(\"El proceso está en un estado inseguro.\")\n            break\n\n        print(f\"El proceso está en un estado seguro.\\nRecursos disponibles: {available}\\n\")\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint main() {\n    int curr[5][5];\n    int max_claim[5][5];\n    int avl[5];\n    int alloc[5] = {0, 0, 0, 0, 0};\n    int max_res[5];\n    int running[5];\n\n    int i, j, exec, r, p;\n    int count = 0;\n    bool safe = false;\n\n    printf(\"\\nEnter the number of resources: \");\n    scanf(\"%d\", &r);\n\n    printf(\"\\nEnter the number of processes: \");\n    scanf(\"%d\", &p);\n    for (i = 0; i < p; i++) {\n        running[i] = 1;\n        count++;\n    }\n\n    printf(\"\\nEnter Claim Vector: \");\n    for (i = 0; i < r; i++)\n        scanf(\"%d\", &max_res[i]);\n\n    printf(\"\\nEnter Allocated Resource Table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &curr[i][j]);\n    }\n\n    printf(\"\\nEnter Maximum Claim table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &max_claim[i][j]);\n    }\n\n    printf(\"\\nThe Claim Vector is: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", max_res[i]);\n\n    printf(\"\\nThe Allocated Resource Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", curr[i][j]);\n        printf(\"\\n\");\n    }\n\n    printf(\"\\nThe Maximum Claim Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", max_claim[i][j]);\n        printf(\"\\n\");\n    }\n\n    for (i = 0; i < p; i++)\n        for (j = 0; j < r; j++)\n            alloc[j] += curr[i][j];\n\n    printf(\"\\nAllocated resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", alloc[i]);\n    for (i = 0; i < r; i++)\n        avl[i] = max_res[i] - alloc[i];\n\n    printf(\"\\nAvailable resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", avl[i]);\n    printf(\"\\n\");\n\n    while (count != 0) {\n        safe = false;\n        for (i = 0; i < p; i++) {\n            if (running[i]) {\n                exec = 1;\n                for (j = 0; j < r; j++) {\n                    if (max_claim[i][j] - curr[i][j] > avl[j]) {\n                        exec = 0;\n                        break;\n                    }\n                }\n\n                if (exec) {\n                    printf(\"\\nProcess%d is executing.\\n\", i + 1);\n                    running[i] = 0;\n                    count--;\n                    safe = true;\n                    for (j = 0; j < r; j++)\n                        avl[j] += curr[i][j];\n                    break;\n                }\n            }\n        }\n\n        if (!safe) {\n            printf(\"\\nThe processes are in unsafe state.\");\n            break;\n        }\n\n        if (safe)\n            printf(\"\\nThe process is in safe state.\");\n\n        printf(\"\\nAvailable vector: \");\n        for (i = 0; i < r; i++)\n            printf(\"%d \", avl[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55482, "name": "Range extraction", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 55483, "name": "Machine code", "Python": "import ctypes\nimport os\nfrom ctypes import c_ubyte, c_int\n\ncode = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])\n\ncode_size = len(code)\n\nif (os.name == 'posix'):\n    import mmap\n    executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)\n    \n    executable_map.write(code)\n    \n    \n    func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))\nelif (os.name == 'nt'):\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    PAGE_EXECUTE_READWRITE = 0x40  \n    MEM_COMMIT = 0x1000\n    executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)\n    if (executable_buffer_address == 0):\n        print('Warning: Failed to enable code execution, call will likely cause a protection fault.')\n        func_address = ctypes.addressof(code_buffer)\n    else:\n        ctypes.memmove(executable_buffer_address, code_buffer, code_size)\n        func_address = executable_buffer_address\nelse:\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    func_address = ctypes.addressof(code_buffer)\n\nprototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) \nfunc = prototype(func_address)                        \nres = func(7,12)\nprint(res)\n", "C": "#include <stdio.h>\n#include <sys/mman.h>\n#include <string.h>\n\nint test (int a, int b)\n{\n  \n  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};\n  void *buf;\n  int c;\n  \n  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,\n             MAP_PRIVATE|MAP_ANON,-1,0);\n\n  memcpy (buf, code, sizeof(code));\n  \n  c = ((int (*) (int, int))buf)(a, b);\n  \n  munmap (buf, sizeof(code));\n  return c;\n}\n\nint main ()\n{\n  printf(\"%d\\n\", test(7,12));\n  return 0;\n}\n"}
{"id": 55484, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 55485, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 55486, "name": "Zhang-Suen thinning algorithm", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n"}
{"id": 55487, "name": "Median filter", "Python": "import Image, ImageFilter\nim = Image.open('image.ppm')\n\nmedian = im.filter(ImageFilter.MedianFilter(3))\nmedian.save('image2.ppm')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef struct { unsigned char r, g, b; } rgb_t;\ntypedef struct {\n\tint w, h;\n\trgb_t **pix;\n} image_t, *image;\n\ntypedef struct {\n\tint r[256], g[256], b[256];\n\tint n;\n} color_histo_t;\n\nint write_ppm(image im, char *fn)\n{\n\tFILE *fp = fopen(fn, \"w\");\n\tif (!fp) return 0;\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", im->w, im->h);\n\tfwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);\n\tfclose(fp);\n\treturn 1;\n}\n\nimage img_new(int w, int h)\n{\n\tint i;\n\timage im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)\n\t\t\t+ sizeof(rgb_t) * w * h);\n\tim->w = w; im->h = h;\n\tim->pix = (rgb_t**)(im + 1);\n\tfor (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)\n\t\tim->pix[i] = im->pix[i - 1] + w;\n\treturn im;\n}\n\nint read_num(FILE *f)\n{\n\tint n;\n\twhile (!fscanf(f, \"%d \", &n)) {\n\t\tif ((n = fgetc(f)) == '#') {\n\t\t\twhile ((n = fgetc(f)) != '\\n')\n\t\t\t\tif (n == EOF) break;\n\t\t\tif (n == '\\n') continue;\n\t\t} else return 0;\n\t}\n\treturn n;\n}\n\nimage read_ppm(char *fn)\n{\n\tFILE *fp = fopen(fn, \"r\");\n\tint w, h, maxval;\n\timage im = 0;\n\tif (!fp) return 0;\n\n\tif (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))\n\t\tgoto bail;\n\n\tw = read_num(fp);\n\th = read_num(fp);\n\tmaxval = read_num(fp);\n\tif (!w || !h || !maxval) goto bail;\n\n\tim = img_new(w, h);\n\tfread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);\nbail:\n\tif (fp) fclose(fp);\n\treturn im;\n}\n\nvoid del_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]--;\n\t\th->g[pix->g]--;\n\t\th->b[pix->b]--;\n\t\th->n--;\n\t}\n}\n\nvoid add_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]++;\n\t\th->g[pix->g]++;\n\t\th->b[pix->b]++;\n\t\th->n++;\n\t}\n}\n\nvoid init_histo(image im, int row, int size, color_histo_t*h)\n{\n\tint j;\n\n\tmemset(h, 0, sizeof(color_histo_t));\n\n\tfor (j = 0; j < size && j < im->w; j++)\n\t\tadd_pixels(im, row, j, size, h);\n}\n\nint median(const int *x, int n)\n{\n\tint i;\n\tfor (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);\n\treturn i;\n}\n\nvoid median_color(rgb_t *pix, const color_histo_t *h)\n{\n\tpix->r = median(h->r, h->n);\n\tpix->g = median(h->g, h->n);\n\tpix->b = median(h->b, h->n);\n}\n\nimage median_filter(image in, int size)\n{\n\tint row, col;\n\timage out = img_new(in->w, in->h);\n\tcolor_histo_t h;\n\n\tfor (row = 0; row < in->h; row ++) {\n\t\tfor (col = 0; col < in->w; col++) {\n\t\t\tif (!col) init_histo(in, row, size, &h);\n\t\t\telse {\n\t\t\t\tdel_pixels(in, row, col - size, size, &h);\n\t\t\t\tadd_pixels(in, row, col + size, size, &h);\n\t\t\t}\n\t\t\tmedian_color(out->pix[row] + col, &h);\n\t\t}\n\t}\n\n\treturn out;\n}\n\nint main(int c, char **v)\n{\n\tint size;\n\timage in, out;\n\tif (c <= 3) {\n\t\tprintf(\"Usage: %s size ppm_in ppm_out\\n\", v[0]);\n\t\treturn 0;\n\t}\n\tsize = atoi(v[1]);\n\tprintf(\"filter size %d\\n\", size);\n\tif (size < 0) size = 1;\n\n\tin = read_ppm(v[2]);\n\tout = median_filter(in, size);\n\twrite_ppm(out, v[3]);\n\tfree(in);\n\tfree(out);\n\n\treturn 0;\n}\n"}
{"id": 55488, "name": "Run as a daemon or service", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n"}
{"id": 55489, "name": "Run as a daemon or service", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n"}
{"id": 55490, "name": "Coprime triplets", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n"}
{"id": 55491, "name": "Coprime triplets", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n"}
{"id": 55492, "name": "Coprime triplets", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n"}
{"id": 55493, "name": "Variable declaration reset", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n"}
{"id": 55494, "name": "SOAP", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n"}
{"id": 55495, "name": "SOAP", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n"}
{"id": 55496, "name": "Pragmatic directives", "Python": "Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> import __future__\n>>> __future__.all_feature_names\n['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']\n>>>\n", "C": "\n#include<stdio.h> \n\n\n#define Hi printf(\"Hi There.\");\n\n\n\n#define start int main(){\n#define end return 0;}\n\nstart\n\nHi\n\n\n#warning \"Don't you have anything better to do ?\"\n\n#ifdef __unix__\n#warning \"What are you doing still working on Unix ?\"\nprintf(\"\\nThis is an Unix system.\");\n#elif _WIN32\n#warning \"You couldn't afford a 64 bit ?\"\nprintf(\"\\nThis is a 32 bit Windows system.\");\n#elif _WIN64\n#warning \"You couldn't afford an Apple ?\"\nprintf(\"\\nThis is a 64 bit Windows system.\");\n#endif\n\nend\n\n\n"}
{"id": 55497, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55498, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55499, "name": "Numbers with equal rises and falls", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n"}
{"id": 55500, "name": "Terminal control_Cursor movement", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n", "C": "#include<conio.h>\n#include<dos.h>\n\nchar *strings[] = {\"The cursor will move one position to the left\", \n  \t\t   \"The cursor will move one position to the right\",\n \t\t   \"The cursor will move vetically up one line\", \n \t\t   \"The cursor will move vertically down one line\", \n \t\t   \"The cursor will move to the beginning of the line\", \n \t\t   \"The cursor will move to the end of the line\", \n \t\t   \"The cursor will move to the top left corner of the screen\", \n \t\t   \"The cursor will move to the bottom right corner of the screen\"};\n \t\t             \nint main()\n{\n\tint i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\t\n\tclrscr();\n\tcprintf(\"This is a demonstration of cursor control using gotoxy(). Press any key to continue.\");\n\tgetch();\n\t\n\tfor(i=0;i<8;i++)\n\t{\n\t\tclrscr();\n\t\tgotoxy(5,MAXROW/2);\n\t\t\n\t\tcprintf(\"%s\",strings[i]);\n\t\tgetch();\n\t\t\n\t\tswitch(i){\n\t\t\tcase 0:gotoxy(wherex()-1,wherey());\n\t\t\tbreak;\n\t\t\tcase 1:gotoxy(wherex()+1,wherey());\n\t\t\tbreak;\n\t\t\tcase 2:gotoxy(wherex(),wherey()-1);\n\t\t\tbreak;\n\t\t\tcase 3:gotoxy(wherex(),wherey()+1);\n\t\t\tbreak;\n\t\t\tcase 4:for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()-1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 5:gotoxy(wherex()-strlen(strings[i]),wherey());\n\t\t\t       for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()+1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 6:while(wherex()!=1)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()-1,wherey());\n\t\t\t\t     delay(100);\n\t\t               }\n\t\t\t       while(wherey()!=1)\n\t\t\t       {\n\t\t\t             gotoxy(wherex(),wherey()-1);\n\t\t\t             delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 7:while(wherex()!=MAXCOL)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()+1,wherey());\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\t       while(wherey()!=MAXROW)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex(),wherey()+1);\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\t};\n\t\t\tgetch();\n\t}\n\t\n\tclrscr();\n\tcprintf(\"End of demonstration.\");\n\tgetch();\n\treturn 0;\n}\n"}
{"id": 55501, "name": "Summation of primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    suma = 2\n    n = 1\n    for i in range(3, 2000000, 2):\n        if isPrime(i):\n            suma += i\n            n+=1 \n    print(suma)\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n    int p;\n    long int s = 2;\n    for(p=3;p<2000000;p+=2) {\n        if(isprime(p)) s+=p;\n    }\n    printf( \"%ld\\n\", s );\n    return 0;\n}\n"}
{"id": 55502, "name": "Koch curve", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55503, "name": "Draw pixel 2", "Python": "import Tkinter,random\ndef draw_pixel_2 ( sizex=640,sizey=480 ):\n    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )\n    root = Tkinter.Tk()\n    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )\n    can.create_rectangle( pos*2,outline='yellow' )\n    can.pack()\n    root.title('press ESCAPE to quit')\n    root.bind('<Escape>',lambda e : root.quit())\n    root.mainloop()\n\ndraw_pixel_2()\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<time.h>\n\nint main()\n{\n\tsrand(time(NULL));\n\t\n\tinitwindow(640,480,\"Yellow Random Pixel\");\n\t\n\tputpixel(rand()%640,rand()%480,YELLOW);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 55504, "name": "Count how many vowels and consonants occur in a string", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n"}
{"id": 55505, "name": "Count how many vowels and consonants occur in a string", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n"}
{"id": 55506, "name": "Compiler_syntax analyzer", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n"}
{"id": 55507, "name": "Compiler_syntax analyzer", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n"}
{"id": 55508, "name": "Compiler_syntax analyzer", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n"}
{"id": 55509, "name": "Draw a pixel", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 55510, "name": "Numbers whose binary and ternary digit sums are prime", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55511, "name": "Numbers whose binary and ternary digit sums are prime", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55512, "name": "Words from neighbour ones", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55513, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "Python": "\n\nfrom functools import reduce\nfrom operator import mul\n\n\n\ndef p(n):\n    \n    digits = [int(c) for c in str(n)]\n    return not 0 in digits and (\n        0 != (n % reduce(mul, digits, 1))\n    ) and all(0 == n % d for d in digits)\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1000)\n        if p(n)\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matching numbers:\\n')\n    print('\\n'.join(\n        ' '.join(cell.rjust(w, ' ') for cell in row)\n        for row in chunksOf(10)(xs)\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n\nint divisible(int n) {\n    int p = 1;\n    int c, d;\n    \n    for (c=n; c; c /= 10) {\n        d = c % 10;\n        if (!d || n % d) return 0;\n        p *= d;\n    }\n    \n    return n % p;\n}\n\nint main() {\n    int n, c=0;\n    \n    for (n=1; n<1000; n++) {\n        if (divisible(n)) {\n            printf(\"%5d\", n);\n            if (!(++c % 10)) printf(\"\\n\");\n        }\n    }\n    printf(\"\\n\");\n    \n    return 0;\n}\n"}
{"id": 55514, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "Python": "\n\nfrom functools import reduce\nfrom operator import mul\n\n\n\ndef p(n):\n    \n    digits = [int(c) for c in str(n)]\n    return not 0 in digits and (\n        0 != (n % reduce(mul, digits, 1))\n    ) and all(0 == n % d for d in digits)\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1000)\n        if p(n)\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matching numbers:\\n')\n    print('\\n'.join(\n        ' '.join(cell.rjust(w, ' ') for cell in row)\n        for row in chunksOf(10)(xs)\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n\nint divisible(int n) {\n    int p = 1;\n    int c, d;\n    \n    for (c=n; c; c /= 10) {\n        d = c % 10;\n        if (!d || n % d) return 0;\n        p *= d;\n    }\n    \n    return n % p;\n}\n\nint main() {\n    int n, c=0;\n    \n    for (n=1; n<1000; n++) {\n        if (divisible(n)) {\n            printf(\"%5d\", n);\n            if (!(++c % 10)) printf(\"\\n\");\n        }\n    }\n    printf(\"\\n\");\n    \n    return 0;\n}\n"}
{"id": 55515, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 55516, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 55517, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 55518, "name": "Magic squares of singly even order", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n"}
{"id": 55519, "name": "Generate Chess960 starting position", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55520, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "C": "int meaning_of_life();\n"}
{"id": 55521, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "C": "int meaning_of_life();\n"}
{"id": 55522, "name": "Perlin noise", "Python": "import math\n\ndef perlin_noise(x, y, z):\n    X = math.floor(x) & 255                  \n    Y = math.floor(y) & 255                  \n    Z = math.floor(z) & 255\n    x -= math.floor(x)                                \n    y -= math.floor(y)                                \n    z -= math.floor(z)\n    u = fade(x)                                \n    v = fade(y)                                \n    w = fade(z)\n    A = p[X  ]+Y; AA = p[A]+Z; AB = p[A+1]+Z      \n    B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z      \n \n    return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                   grad(p[BA  ], x-1, y  , z   )), \n                           lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                   grad(p[BB  ], x-1, y-1, z   ))),\n                   lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                   grad(p[BA+1], x-1, y  , z-1 )), \n                           lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                   grad(p[BB+1], x-1, y-1, z-1 ))))\n                                   \ndef fade(t): \n    return t ** 3 * (t * (t * 6 - 15) + 10)\n    \ndef lerp(t, a, b):\n    return a + t * (b - a)\n    \ndef grad(hash, x, y, z):\n    h = hash & 15                      \n    u = x if h<8 else y                \n    v = y if h<4 else (x if h in (12, 14) else z)\n    return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n    p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n    print(\"%1.17f\" % perlin_noise(3.14, 42, 7))\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55523, "name": "File size distribution", "Python": "import sys, os\nfrom collections import Counter\n\ndef dodir(path):\n    global h\n\n    for name in os.listdir(path):\n        p = os.path.join(path, name)\n\n        if os.path.islink(p):\n            pass\n        elif os.path.isfile(p):\n            h[os.stat(p).st_size] += 1\n        elif os.path.isdir(p):\n            dodir(p)\n        else:\n            pass\n\ndef main(arg):\n    global h\n    h = Counter()\n    for dir in arg:\n        dodir(dir)\n\n    s = n = 0\n    for k, v in sorted(h.items()):\n        print(\"Size %d -> %d file(s)\" % (k, v))\n        n += v\n        s += k * v\n    print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])\n", "C": "#include<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n"}
{"id": 55524, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n"}
{"id": 55525, "name": "Rendezvous", "Python": "\nfrom __future__ import annotations\n\nimport asyncio\nimport sys\n\nfrom typing import Optional\nfrom typing import TextIO\n\n\nclass OutOfInkError(Exception):\n    \n\n\nclass Printer:\n    def __init__(self, name: str, backup: Optional[Printer]):\n        self.name = name\n        self.backup = backup\n\n        self.ink_level: int = 5\n        self.output_stream: TextIO = sys.stdout\n\n    async def print(self, msg):\n        if self.ink_level <= 0:\n            if self.backup:\n                await self.backup.print(msg)\n            else:\n                raise OutOfInkError(self.name)\n        else:\n            self.ink_level -= 1\n            self.output_stream.write(f\"({self.name}): {msg}\\n\")\n\n\nasync def main():\n    reserve = Printer(\"reserve\", None)\n    main = Printer(\"main\", reserve)\n\n    humpty_lines = [\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men,\",\n        \"Couldn't put Humpty together again.\",\n    ]\n\n    goose_lines = [\n        \"Old Mother Goose,\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air,\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n    ]\n\n    async def print_humpty():\n        for line in humpty_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Humpty Dumpty out of ink!\")\n                break\n\n    async def print_goose():\n        for line in goose_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Mother Goose out of ink!\")\n                break\n\n    await asyncio.gather(print_goose(), print_humpty())\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main(), debug=True)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <pthread.h>\n\n\n\n\ntypedef struct rendezvous {\n    pthread_mutex_t lock;        \n    pthread_cond_t cv_entering;  \n    pthread_cond_t cv_accepting; \n    pthread_cond_t cv_done;      \n    int (*accept_func)(void*);   \n    int entering;                \n    int accepting;               \n    int done;                    \n} rendezvous_t;\n\n\n#define RENDEZVOUS_INITILIZER(accept_function) {   \\\n        .lock         = PTHREAD_MUTEX_INITIALIZER, \\\n        .cv_entering  = PTHREAD_COND_INITIALIZER,  \\\n        .cv_accepting = PTHREAD_COND_INITIALIZER,  \\\n        .cv_done      = PTHREAD_COND_INITIALIZER,  \\\n        .accept_func  = accept_function,           \\\n        .entering     = 0,                         \\\n        .accepting    = 0,                         \\\n        .done         = 0,                         \\\n    }\n\nint enter_rendezvous(rendezvous_t *rv, void* data)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n\n    rv->entering++;\n    pthread_cond_signal(&rv->cv_entering);\n\n    while (!rv->accepting) {\n        \n        pthread_cond_wait(&rv->cv_accepting, &rv->lock);\n    }\n\n    \n    int ret = rv->accept_func(data);\n\n    \n    rv->done = 1;\n    pthread_cond_signal(&rv->cv_done);\n\n    rv->entering--;\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n\n    return ret;\n}\n\nvoid accept_rendezvous(rendezvous_t *rv)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n    rv->accepting = 1;\n\n    while (!rv->entering) {\n        \n        pthread_cond_wait(&rv->cv_entering, &rv->lock);\n    }\n\n    pthread_cond_signal(&rv->cv_accepting);\n\n    while (!rv->done) {\n        \n        pthread_cond_wait(&rv->cv_done, &rv->lock);\n    }\n    rv->done = 0;\n\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n}\n\n\n\ntypedef struct printer {\n    rendezvous_t rv;\n    struct printer *backup;\n    int id;\n    int remaining_lines;\n} printer_t;\n\ntypedef struct print_args {\n    struct printer *printer;\n    const char* line;\n} print_args_t;\n\nint print_line(printer_t *printer, const char* line) {\n    print_args_t args;\n    args.printer = printer;\n    args.line = line;\n    return enter_rendezvous(&printer->rv, &args);\n}\n\nint accept_print(void* data) {\n    \n    print_args_t *args = (print_args_t*)data;\n    printer_t *printer = args->printer;\n    const char* line = args->line;\n\n    if (printer->remaining_lines) {\n        \n        printf(\"%d: \", printer->id);\n        while (*line != '\\0') {\n            putchar(*line++);\n        }\n        putchar('\\n');\n        printer->remaining_lines--;\n        return 1;\n    }\n    else if (printer->backup) {\n        \n        return print_line(printer->backup, line);\n    }\n    else {\n        \n        return -1;\n    }\n}\n\nprinter_t backup_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = NULL,\n    .id = 2,\n    .remaining_lines = 5,\n};\n\nprinter_t main_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = &backup_printer,\n    .id = 1,\n    .remaining_lines = 5,\n};\n\nvoid* printer_thread(void* thread_data) {\n    printer_t *printer = (printer_t*) thread_data;\n    while (1) {\n        accept_rendezvous(&printer->rv);\n    }\n}\n\ntypedef struct poem {\n    char* name;\n    char* lines[];\n} poem_t;\n\npoem_t humpty_dumpty = {\n    .name = \"Humpty Dumpty\",\n    .lines = {\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men\",\n        \"Couldn't put Humpty together again.\",\n        \"\"\n    },\n};\n\npoem_t mother_goose = {\n    .name = \"Mother Goose\",\n    .lines = {\n        \"Old Mother Goose\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n        \"\"\n    },\n};\n\nvoid* poem_thread(void* thread_data) {\n    poem_t *poem = (poem_t*)thread_data;\n\n    for (unsigned i = 0; poem->lines[i] != \"\"; i++) {\n        int ret = print_line(&main_printer, poem->lines[i]);\n        if (ret < 0) {\n            printf(\"      %s out of ink!\\n\", poem->name);\n            exit(1);\n        }\n    }\n    return NULL;\n}\n\nint main(void)\n{\n    pthread_t threads[4];\n\n    pthread_create(&threads[0], NULL, poem_thread,    &humpty_dumpty);\n    pthread_create(&threads[1], NULL, poem_thread,    &mother_goose);\n    pthread_create(&threads[2], NULL, printer_thread, &main_printer);\n    pthread_create(&threads[3], NULL, printer_thread, &backup_printer);\n\n    pthread_join(threads[0], NULL);\n    pthread_join(threads[1], NULL);\n    pthread_cancel(threads[2]);\n    pthread_cancel(threads[3]);\n\n    return 0;\n}\n"}
{"id": 55526, "name": "First class environments", "Python": "environments = [{'cnt':0, 'seq':i+1} for i in range(12)]\n\ncode = \n\nwhile any(env['seq'] > 1 for env in environments):\n    for env in environments:\n        exec(code, globals(), env)\n    print()\n\nprint('Counts')\nfor env in environments:\n    print('% 4d' % env['cnt'], end='')\nprint()\n", "C": "#include <stdio.h>\n\n#define JOBS 12\n#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf(\"\\n\"); switch_to(++a))\ntypedef struct { int seq, cnt; } env_t;\n\nenv_t env[JOBS] = {{0, 0}};\nint *seq, *cnt;\n\nvoid hail()\n{\n\tprintf(\"% 4d\", *seq);\n\tif (*seq == 1) return;\n\t++*cnt;\n\t*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;\n}\n\nvoid switch_to(int id)\n{\n\tseq = &env[id].seq;\n\tcnt = &env[id].cnt;\n}\n\nint main()\n{\n\tint i;\n\tjobs(i) { env[i].seq = i + 1; }\n\nagain:\tjobs(i) { hail(); }\n\tjobs(i) { if (1 != *seq) goto again; }\n\n\tprintf(\"COUNTS:\\n\");\n\tjobs(i) { printf(\"% 4d\", *cnt); }\n\n\treturn 0;\n}\n"}
{"id": 55527, "name": "UTF-8 encode and decode", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n"}
{"id": 55528, "name": "Xiaolin Wu's line algorithm", "Python": "\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n    return x - int(x)\n\ndef _rfpart(x):\n    return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n    \n    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n    c = compose_color(img.getpixel(xy), color)\n    img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n    \n    x1, y1 = p1\n    x2, y2 = p2\n    dx, dy = x2-x1, y2-y1\n    steep = abs(dx) < abs(dy)\n    p = lambda px, py: ((px,py), (py,px))[steep]\n\n    if steep:\n        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n    if x2 < x1:\n        x1, x2, y1, y2 = x2, x1, y2, y1\n\n    grad = dy/dx\n    intery = y1 + _rfpart(x1) * grad\n    def draw_endpoint(pt):\n        x, y = pt\n        xend = round(x)\n        yend = y + grad * (xend - x)\n        xgap = _rfpart(x + 0.5)\n        px, py = int(xend), int(yend)\n        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n        return px\n\n    xstart = draw_endpoint(p(*p1)) + 1\n    xend = draw_endpoint(p(*p2))\n\n    for x in range(xstart, xend):\n        y = int(intery)\n        putpixel(img, p(x, y), color, _rfpart(intery))\n        putpixel(img, p(x, y+1), color, _fpart(intery))\n        intery += grad\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print 'usage: python xiaolinwu.py [output-file]'\n        sys.exit(-1)\n\n    blue = (0, 0, 255)\n    yellow = (255, 255, 0)\n    img = Image.new(\"RGB\", (500,500), blue)\n    for a in range(10, 431, 60):\n        draw_line(img, (10, 10), (490, a), yellow)\n        draw_line(img, (10, 10), (a, 490), yellow)\n    draw_line(img, (10, 10), (490, 490), yellow)\n    filename = sys.argv[1]\n    img.save(filename)\n    print 'image saved to', filename\n", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 55529, "name": "Keyboard macros", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/keysym.h>\n\nint main()\n{\n  Display *d;\n  XEvent event;\n  \n  d = XOpenDisplay(NULL);\n  if ( d != NULL ) {\n                \n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), \n\t     Mod1Mask,  \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), \n\t     Mod1Mask, \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n\n    for(;;)\n    {\n      XNextEvent(d, &event);\n      if ( event.type == KeyPress ) {\n\tKeySym s = XLookupKeysym(&event.xkey, 0);\n\tif ( s == XK_F7 ) {\n\t  printf(\"something's happened\\n\");\n\t} else if ( s == XK_F6 ) {\n\t  break;\n\t}\n      }\n    }\n\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), Mod1Mask, DefaultRootWindow(d));\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), Mod1Mask, DefaultRootWindow(d));\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55530, "name": "McNuggets problem", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n"}
{"id": 55531, "name": "McNuggets problem", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n"}
{"id": 55532, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 55533, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n"}
{"id": 55534, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n"}
{"id": 55535, "name": "Pseudo-random numbers_Xorshift star", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55536, "name": "Four is the number of letters in the ...", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n", "C": "#include <ctype.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\ntypedef struct word_tag {\n    size_t offset;\n    size_t length;\n} word_t;\n\ntypedef struct word_list_tag {\n    GArray* words;\n    GString* str;\n} word_list;\n\nvoid word_list_create(word_list* words) {\n    words->words = g_array_new(FALSE, FALSE, sizeof(word_t));\n    words->str = g_string_new(NULL);\n}\n\nvoid word_list_destroy(word_list* words) {\n    g_string_free(words->str, TRUE);\n    g_array_free(words->words, TRUE);\n}\n\nvoid word_list_clear(word_list* words) {\n    g_string_truncate(words->str, 0);\n    g_array_set_size(words->words, 0);\n}\n\nvoid word_list_append(word_list* words, const char* str) {\n    size_t offset = words->str->len;\n    size_t len = strlen(str);\n    g_string_append_len(words->str, str, len);\n    word_t word;\n    word.offset = offset;\n    word.length = len;\n    g_array_append_val(words->words, word);\n}\n\nword_t* word_list_get(word_list* words, size_t index) {\n    return &g_array_index(words->words, word_t, index);\n}\n\nvoid word_list_extend(word_list* words, const char* str) {\n    word_t* word = word_list_get(words, words->words->len - 1);\n    size_t len = strlen(str);\n    word->length += len;\n    g_string_append_len(words->str, str, len);\n}\n\nsize_t append_number_name(word_list* words, integer n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        word_list_append(words, get_small_name(&small[n], ordinal));\n        count = 1;\n    } else if (n < 100) {\n        if (n % 10 == 0) {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], false));\n            word_list_extend(words, \"-\");\n            word_list_extend(words, get_small_name(&small[n % 10], ordinal));\n        }\n        count = 1;\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        count += append_number_name(words, n/p, false);\n        if (n % p == 0) {\n            word_list_append(words, get_big_name(num, ordinal));\n            ++count;\n        } else {\n            word_list_append(words, get_big_name(num, false));\n            ++count;\n            count += append_number_name(words, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(word_list* words, size_t index) {\n    const word_t* word = word_list_get(words, index);\n    size_t letters = 0;\n    const char* s = words->str->str + word->offset;\n    for (size_t i = 0, n = word->length; i < n; ++i) {\n        if (isalpha((unsigned char)s[i]))\n            ++letters;\n    }\n    return letters;\n}\n\nvoid sentence(word_list* result, size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    word_list_clear(result);\n    size_t n = sizeof(words)/sizeof(words[0]);\n    for (size_t i = 0; i < n; ++i)\n        word_list_append(result, words[i]);\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result, i), false);\n        word_list_append(result, \"in\");\n        word_list_append(result, \"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        \n        word_list_extend(result, \",\");\n    }\n}\n\nsize_t sentence_length(const word_list* words) {\n    size_t n = words->words->len;\n    if (n == 0)\n        return 0;\n    return words->str->len + n - 1;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    size_t n = 201;\n    word_list result = { 0 };\n    word_list_create(&result);\n    sentence(&result, n);\n    printf(\"Number of letters in first %'lu words in the sequence:\\n\", n);\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            printf(\"%c\", i % 25 == 0 ? '\\n' : ' ');\n        printf(\"%'2lu\", count_letters(&result, i));\n    }\n    printf(\"\\nSentence length: %'lu\\n\", sentence_length(&result));\n    for (n = 1000; n <= 10000000; n *= 10) {\n        sentence(&result, n);\n        const word_t* word = word_list_get(&result, n - 1);\n        const char* s = result.str->str + word->offset;\n        printf(\"The %'luth word is '%.*s' and has %lu letters. \", n,\n               (int)word->length, s, count_letters(&result, n - 1));\n        printf(\"Sentence length: %'lu\\n\" , sentence_length(&result));\n    }\n    word_list_destroy(&result);\n    return 0;\n}\n"}
{"id": 55537, "name": "ASCII art diagram converter", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n"}
{"id": 55538, "name": "Levenshtein distance_Alignment", "Python": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n    result = \"\"\n    pos, removed = 0, 0\n    for x in ndiff(str1, str2):\n        if pos<len(str1) and str1[pos] == x[2]:\n          pos += 1\n          result += x[2]\n          if x[0] == \"-\":\n              removed += 1\n          continue\n        else:\n          if removed > 0:\n            removed -=1\n          else:\n            result += \"-\"\n    print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}\n"}
{"id": 55539, "name": "Compare sorting algorithms' performance", "Python": "def builtinsort(x):\n    x.sort()\n\ndef partition(seq, pivot):\n   low, middle, up = [], [], []\n   for x in seq:\n       if x < pivot:\n           low.append(x)\n       elif x == pivot:\n           middle.append(x)\n       else:\n           up.append(x)\n   return low, middle, up\nimport random\ndef qsortranpart(seq):\n   size = len(seq)\n   if size < 2: return seq\n   low, middle, up = partition(seq, random.choice(seq))\n   return qsortranpart(low) + middle + qsortranpart(up)\n", "C": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n"}
{"id": 55540, "name": "Compare sorting algorithms' performance", "Python": "def builtinsort(x):\n    x.sort()\n\ndef partition(seq, pivot):\n   low, middle, up = [], [], []\n   for x in seq:\n       if x < pivot:\n           low.append(x)\n       elif x == pivot:\n           middle.append(x)\n       else:\n           up.append(x)\n   return low, middle, up\nimport random\ndef qsortranpart(seq):\n   size = len(seq)\n   if size < 2: return seq\n   low, middle, up = partition(seq, random.choice(seq))\n   return qsortranpart(low) + middle + qsortranpart(up)\n", "C": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n"}
{"id": 55541, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 55542, "name": "Parse command-line arguments", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n"}
{"id": 55543, "name": "Parse command-line arguments", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n"}
{"id": 55544, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n"}
{"id": 55545, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n"}
{"id": 55546, "name": "Simulate input_Keyboard", "Python": "import autopy\nautopy.key.type_string(\"Hello, world!\") \nautopy.key.type_string(\"Hello, world!\", wpm=60) \nautopy.key.tap(autopy.key.Code.RETURN)\nautopy.key.tap(autopy.key.Code.F1)\nautopy.key.tap(autopy.key.Code.LEFT_ARROW)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n\nint main(int argc, char *argv[])\n{\n  Display *dpy;\n  Window win;\n  GC gc;\n  int scr;\n  Atom WM_DELETE_WINDOW;\n  XEvent ev;\n  XEvent ev2;\n  KeySym keysym;\n  int loop;\n\n  \n  dpy = XOpenDisplay(NULL);\n  if (dpy == NULL) {\n    fputs(\"Cannot open display\", stderr);\n    exit(1);\n  }\n  scr = XDefaultScreen(dpy);\n\n  \n  win = XCreateSimpleWindow(dpy,\n          XRootWindow(dpy, scr),\n          \n          10, 10, 300, 200, 1,\n          \n          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));\n\n  \n  XStoreName(dpy, win, argv[0]);\n\n  \n  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);\n\n  \n  XMapWindow(dpy, win);\n  XFlush(dpy);\n\n  \n  gc = XDefaultGC(dpy, scr);\n\n  \n  WM_DELETE_WINDOW = XInternAtom(dpy, \"WM_DELETE_WINDOW\", True);\n  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);\n\n  \n  loop = 1;\n  while (loop) {\n    XNextEvent(dpy, &ev);\n    switch (ev.type)\n    {\n      case Expose:\n        \n        {\n          char msg1[] = \"Clic in the window to generate\";\n          char msg2[] = \"a key press event\";\n          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);\n          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);\n        }\n        break;\n\n      case ButtonPress:\n        puts(\"ButtonPress event received\");\n        \n        ev2.type = KeyPress;\n        ev2.xkey.state = ShiftMask;\n        ev2.xkey.keycode = 24 + (rand() % 33);\n        ev2.xkey.same_screen = True;\n        XSendEvent(dpy, win, True, KeyPressMask, &ev2);\n        break;\n   \n      case ClientMessage:\n        \n        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)\n          loop = 0;\n        break;\n   \n      case KeyPress:\n        \n        puts(\"KeyPress event received\");\n        printf(\"> keycode: %d\\n\", ev.xkey.keycode);\n        \n        keysym = XLookupKeysym(&(ev.xkey), 0);\n        if (keysym == XK_q ||\n            keysym == XK_Escape) {\n          loop = 0;\n        } else {\n          char buffer[] = \"  \";\n          int nchars = XLookupString(\n                &(ev.xkey),\n                buffer,\n                2,  \n                &keysym,\n                NULL );\n          if (nchars == 1)\n            printf(\"> Key '%c' pressed\\n\", buffer[0]);\n        }\n        break;\n    }\n  }\n  XDestroyWindow(dpy, win);\n  \n  XCloseDisplay(dpy);\n  return 1;\n}\n"}
{"id": 55547, "name": "Peaceful chess queen armies", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55548, "name": "Metaprogramming", "Python": "from macropy.core.macros import *\nfrom macropy.core.quotes import macros, q, ast, u\n\nmacros = Macros()\n\n@macros.expr\ndef expand(tree, **kw):\n    addition = 10\n    return q[lambda x: x * ast[tree] + u[addition]]\n", "C": "\n#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]\n\n#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)\n#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)\n#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)\n\nCOMPILE_TIME_ASSERT(sizeof(long)==8); \nint main()\n{\n    COMPILE_TIME_ASSERT(sizeof(int)==4); \n}\n"}
{"id": 55549, "name": "Numbers with same digit set in base 10 and base 16", "Python": "col = 0\nfor i in range(100000):\n    if set(str(i)) == set(hex(i)[2:]):\n        col += 1\n        print(\"{:7}\".format(i), end='\\n'[:col % 10 == 0])\nprint()\n", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55550, "name": "Largest prime factor", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    n = 600851475143\n    j = 3\n    while not isPrime(n):\n        if n % j == 0:\n            n /= j\n        j += 2\n    print(n);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( long int n ) {\n    int i=3;\n    if(!(n%2)) return 0;\n    while( i*i < n ) {\n        if(!(n%i)) return 0;\n        i+=2;\n    }\n    return 1;\n}\n\nint main(void) {\n    long int n=600851475143, j=3;\n\n    while(!isprime(n)) {\n        if(!(n%j)) n/=j;\n        j+=2;\n    }\n    printf( \"%ld\\n\", n );\n    return 0;\n}\n"}
{"id": 55551, "name": "Largest prime factor", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    n = 600851475143\n    j = 3\n    while not isPrime(n):\n        if n % j == 0:\n            n /= j\n        j += 2\n    print(n);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( long int n ) {\n    int i=3;\n    if(!(n%2)) return 0;\n    while( i*i < n ) {\n        if(!(n%i)) return 0;\n        i+=2;\n    }\n    return 1;\n}\n\nint main(void) {\n    long int n=600851475143, j=3;\n\n    while(!isprime(n)) {\n        if(!(n%j)) n/=j;\n        j+=2;\n    }\n    printf( \"%ld\\n\", n );\n    return 0;\n}\n"}
{"id": 55552, "name": "Largest proper divisor of n", "Python": "def lpd(n):\n    for i in range(n-1,0,-1):\n        if n%i==0: return i\n    return 1\n\nfor i in range(1,101):\n    print(\"{:3}\".format(lpd(i)), end=i%10==0 and '\\n' or '')\n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55553, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55554, "name": "Active Directory_Search for a user", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n"}
{"id": 55555, "name": "Singular value decomposition", "Python": "from numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n", "C": "#include <stdio.h>\n#include <gsl/gsl_linalg.h>\n\n\nvoid gsl_matrix_print(const gsl_matrix *M) {\n    int rows = M->size1;\n    int cols = M->size2;\n    for (int i = 0; i < rows; i++) {\n        printf(\"|\");\n        for (int j = 0; j < cols; j++) {\n            printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n        }\n        printf(\"\\b|\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main(){\n    double a[] = {3, 0, 4, 5};\n    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n    gsl_matrix *V = gsl_matrix_alloc(2, 2);\n    gsl_vector *S = gsl_vector_alloc(2);\n    gsl_vector *work = gsl_vector_alloc(2);\n\n    \n    gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n    gsl_matrix_transpose(V);\n    double s[] = {S->data[0], 0, 0, S->data[1]};\n    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n    printf(\"U:\\n\");\n    gsl_matrix_print(&A.matrix);\n\n    printf(\"S:\\n\");\n    gsl_matrix_print(&SM.matrix);\n\n    printf(\"VT:\\n\");\n    gsl_matrix_print(V);\n    \n    gsl_matrix_free(V);\n    gsl_vector_free(S);\n    gsl_vector_free(work);\n    return 0;\n}\n"}
{"id": 55556, "name": "Sum of first n cubes", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n"}
{"id": 55557, "name": "Test integerness", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n"}
{"id": 55558, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n"}
{"id": 55559, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n"}
{"id": 55560, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n"}
{"id": 55561, "name": "Death Star", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n"}
{"id": 55562, "name": "Lucky and even lucky numbers", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define LUCKY_SIZE 60000\nint luckyOdd[LUCKY_SIZE];\nint luckyEven[LUCKY_SIZE];\n\nvoid compactLucky(int luckyArray[]) {\n    int i, j, k;\n\n    for (i = 0; i < LUCKY_SIZE; i++) {\n        if (luckyArray[i] == 0) {\n            j = i;\n            break;\n        }\n    }\n\n    for (j = i + 1; j < LUCKY_SIZE; j++) {\n        if (luckyArray[j] > 0) {\n            luckyArray[i++] = luckyArray[j];\n        }\n    }\n\n    for (; i < LUCKY_SIZE; i++) {\n        luckyArray[i] = 0;\n    }\n}\n\nvoid initialize() {\n    int i, j;\n\n    \n    for (i = 0; i < LUCKY_SIZE; i++) {\n        luckyEven[i] = 2 * i + 2;\n        luckyOdd[i] = 2 * i + 1;\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyOdd[i] > 0) {\n            for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {\n                luckyOdd[j] = 0;\n            }\n            compactLucky(luckyOdd);\n        }\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyEven[i] > 0) {\n            for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {\n                luckyEven[j] = 0;\n            }\n            compactLucky(luckyEven);\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[j] == 0 || luckyEven[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyEven[i] != 0; i++) {\n            if (luckyEven[i] > k) {\n                break;\n            }\n            if (luckyEven[i] > j) {\n                printf(\" %d\", luckyEven[i]);\n            }\n        }\n    } else {\n        if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyOdd[i] != 0; i++) {\n            if (luckyOdd[i] > k) {\n                break;\n            }\n            if (luckyOdd[i] > j) {\n                printf(\" %d\", luckyOdd[i]);\n            }\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyEven[i]);\n        }\n    } else {\n        if (luckyOdd[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyOdd[i]);\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (luckyEven[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even number %d=%d\\n\", j, luckyEven[j - 1]);\n    } else {\n        if (luckyOdd[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky number %d=%d\\n\", j, luckyOdd[j - 1]);\n    }\n}\n\nvoid help() {\n    printf(\"./lucky j [k] [--lucky|--evenLucky]\\n\");\n    printf(\"\\n\");\n    printf(\"       argument(s)        |  what is displayed\\n\");\n    printf(\"==============================================\\n\");\n    printf(\"-j=m                      |  mth lucky number\\n\");\n    printf(\"-j=m  --lucky             |  mth lucky number\\n\");\n    printf(\"-j=m  --evenLucky         |  mth even lucky number\\n\");\n    printf(\"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\");\n    printf(\"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\");\n}\n\nvoid process(int argc, char *argv[]) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    bool good = false;\n    int i;\n\n    for (i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    fprintf(stderr, \"Unknown long argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    fprintf(stderr, \"Unknown short argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            fprintf(stderr, \"Unknown argument: [%s]\\n\", argv[i]);\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n}\n\nvoid test() {\n    printRange(1, 20, false);\n    printRange(1, 20, true);\n\n    printBetween(6000, 6100, false);\n    printBetween(6000, 6100, true);\n\n    printSingle(10000, false);\n    printSingle(10000, true);\n}\n\nint main(int argc, char *argv[]) {\n    initialize();\n\n    \n\n    if (argc < 2) {\n        help();\n        return 1;\n    }\n    process(argc, argv);\n\n    return 0;\n}\n"}
{"id": 55563, "name": "Scope modifiers", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n", "C": "int a;          \nstatic int p;   \n\nextern float v; \n\n\nint code(int arg)\n{\n  int myp;        \n                  \n                  \n  static int myc; \n                  \n                  \n                  \n                  \n}\n\n\nstatic void code2(void)\n{\n  v = v * 1.02;    \n  \n}\n"}
{"id": 55564, "name": "Simple database", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n", "C": "#include <stdio.h>\n#include <stdlib.h> \n#include <string.h> \n#define _XOPEN_SOURCE \n#define __USE_XOPEN\n#include <time.h>\n#define DB \"database.csv\" \n#define TRY(a)  if (!(a)) {perror(#a);exit(1);}\n#define TRY2(a) if((a)<0) {perror(#a);exit(1);}\n#define FREE(a) if(a) {free(a);a=NULL;}\n#define sort_by(foo) \\\nstatic int by_##foo (const void*p1, const void*p2) { \\\n    return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); }\ntypedef struct db {\n    char title[26];\n    char first_name[26];\n    char last_name[26];\n    time_t date;\n    char publ[100];\n    struct db *next;\n}\ndb_t,*pdb_t;\ntypedef int (sort)(const void*, const void*);\nenum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY};\nstatic pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby);\nstatic char *time2str (time_t *time);\nstatic time_t str2time (char *date);\n\nsort_by(last_name);\nsort_by(title);\nstatic int by_date(pdb_t *p1, pdb_t *p2);\n\nint main (int argc, char **argv) {\n    char buf[100];\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    db_t db;\n    db.next=NULL;\n    pdb_t dblist;\n    int i;\n    FILE *f;\n    TRY (f=fopen(DB,\"a+\"));\n    if (argc<2) {\nusage:  printf (\"Usage: %s [commands]\\n\"\n        \"-c  Create new entry.\\n\"\n        \"-p  Print the latest entry.\\n\"\n        \"-t  Print all entries sorted by title.\\n\"\n        \"-d  Print all entries sorted by date.\\n\"\n        \"-a  Print all entries sorted by author.\\n\",argv[0]);\n        fclose (f);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n        case CREATE:\n        printf(\"-c  Create a new entry.\\n\");\n        printf(\"Title           :\");if((scanf(\" %25[^\\n]\",db.title     ))<0)break;\n        printf(\"Author Firstname:\");if((scanf(\" %25[^\\n]\",db.first_name))<0)break;\n        printf(\"Author Lastname :\");if((scanf(\" %25[^\\n]\",db.last_name ))<0)break;\n        printf(\"Date 10-12-2000 :\");if((scanf(\" %10[^\\n]\",buf          ))<0)break;\n        printf(\"Publication     :\");if((scanf(\" %99[^\\n]\",db.publ      ))<0)break;\n        db.date=str2time (buf);\n        dao (CREATE,f,&db,NULL);\n        break;\n        case PRINT:\n        printf (\"-p  Print the latest entry.\\n\");\n        while (!feof(f)) dao (READLINE,f,&db,NULL);\n        dao (PRINT,f,&db,NULL);\n        break;\n        case TITLE:\n        printf (\"-t  Print all entries sorted by title.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_title);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case DATE:\n        printf (\"-d  Print all entries sorted by date.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,(int (*)(const void *,const  void *)) by_date);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case AUTH:\n        printf (\"-a  Print all entries sorted by author.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_last_name);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        default: {\n            printf (\"Unknown command: %s.\\n\",strlen(argv[1])<10?argv[1]:\"\");\n            goto usage;\n    }   }\n    fclose (f);\n    return 0;\n}\n\nstatic pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) {\n    pdb_t *pdb=NULL,rec=NULL,hd=NULL;\n    int i=0,ret;\n    char buf[100];\n    switch (cmd) {\n        case CREATE:\n        fprintf (f,\"\\\"%s\\\",\",in_db->title);\n        fprintf (f,\"\\\"%s\\\",\",in_db->first_name);\n        fprintf (f,\"\\\"%s\\\",\",in_db->last_name);\n        fprintf (f,\"\\\"%s\\\",\",time2str(&in_db->date));\n        fprintf (f,\"\\\"%s\\\" \\n\",in_db->publ);\n        break;\n        case PRINT:\n        for (;in_db;i++) {\n            printf (\"Title       : %s\\n\",     in_db->title);\n            printf (\"Author      : %s %s\\n\",  in_db->first_name, in_db->last_name);\n            printf (\"Date        : %s\\n\",     time2str(&in_db->date));\n            printf (\"Publication : %s\\n\\n\",   in_db->publ);\n            if (!((i+1)%3)) {\n                printf (\"Press Enter to continue.\\n\");\n                ret = scanf (\"%*[^\\n]\");\n                if (ret<0) return rec; \n                else getchar();\n            }\n            in_db=in_db->next;\n        }\n        break;\n        case READLINE:\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->title     ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->first_name))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->last_name ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",buf              ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\" \",in_db->publ      ))<0)break;\n        in_db->date=str2time (buf);\n        break;\n        case READ:\n        while (!feof(f)) {\n            dao (READLINE,f,in_db,NULL);\n            TRY (rec=malloc(sizeof(db_t)));\n            *rec=*in_db; \n            rec->next=hd;\n            hd=rec;i++;\n        }\n        if (i<2) {\n            puts (\"Empty database. Please create some entries.\");\n            fclose (f);\n            exit (0);\n        }\n        break;\n        case SORT:\n        rec=in_db;\n        for (;in_db;i++) in_db=in_db->next;\n        TRY (pdb=malloc(i*sizeof(pdb_t)));\n        in_db=rec;\n        for (i=0;in_db;i++) {\n            pdb[i]=in_db;\n            in_db=in_db->next;\n        }\n        qsort (pdb,i,sizeof in_db,sortby);\n        pdb[i-1]->next=NULL;\n        for (i=i-1;i;i--) {\n            pdb[i-1]->next=pdb[i];\n        }\n        rec=pdb[0];\n        FREE (pdb);\n        pdb=NULL;\n        break;\n        case DESTROY: {\n            while ((rec=in_db)) {\n                in_db=in_db->next;\n                FREE (rec);\n    }   }   }\n    return rec;\n}\n\nstatic char *time2str (time_t *time) {\n    static char buf[255];\n    struct tm *ptm;\n    ptm=localtime (time);\n    strftime(buf, 255, \"%m-%d-%Y\", ptm);\n    return buf;\n}\n\nstatic time_t str2time (char *date) {\n    struct tm tm;\n    memset (&tm, 0, sizeof(struct tm));\n    strptime(date, \"%m-%d-%Y\", &tm);\n    return mktime(&tm);\n}\n\nstatic int by_date (pdb_t *p1, pdb_t *p2) {\n    if ((*p1)->date < (*p2)->date) {\n        return -1;\n    }\n    else return ((*p1)->date > (*p2)->date);\n}\n"}
{"id": 55565, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55566, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55567, "name": "Hough transform", "Python": "from math import hypot, pi, cos, sin\nfrom PIL import Image\n\n\ndef hough(im, ntx=460, mry=360):\n    \"Calculate Hough transform.\"\n    pim = im.load()\n    nimx, mimy = im.size\n    mry = int(mry/2)*2          \n    him = Image.new(\"L\", (ntx, mry), 255)\n    phim = him.load()\n\n    rmax = hypot(nimx, mimy)\n    dr = rmax / (mry/2)\n    dth = pi / ntx\n\n    for jx in xrange(nimx):\n        for iy in xrange(mimy):\n            col = pim[jx, iy]\n            if col == 255: continue\n            for jtx in xrange(ntx):\n                th = dth * jtx\n                r = jx*cos(th) + iy*sin(th)\n                iry = mry/2 + int(r/dr+0.5)\n                phim[jtx, iry] -= 1\n    return him\n\n\ndef test():\n    \"Test Hough transform with pentagon.\"\n    im = Image.open(\"pentagon.png\").convert(\"L\")\n    him = hough(im)\n    him.save(\"ho5.bmp\")\n\n\nif __name__ == \"__main__\": test()\n", "C": "#include \"SL_Generated.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nint main( int argc, char** argv )\n{\n    string fileName = \"Pentagon.bmp\";\n    if(argc > 1) fileName = argv[1];\n    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);\n    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);\n    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);\n    int threads = 0; if(argc > 5) threads = atoi(argv[5]);\n    char titleBuffer[200];\n    SLTimer t;\n\n    CImg<int> image(fileName.c_str());\n    int imageDimensions[] = {image.height(), image.width(), 0};\n    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);\n    Sequence< Sequence<int> > result;\n\n    sl_init(threads);\n\n    t.start();\n    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);\n    t.stop();\n    \n    CImg<int> resultImage(result[1].size(), result.size());\n    for(int y = 0; y < result.size(); y++)\n        for(int x = 0; x < result[y+1].size(); x++)\n            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];\n    \n    sprintf(titleBuffer, \"SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\\0\", \n                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());\n    resultImage.display(titleBuffer);\n\n    sl_done();\n    return 0;\n}\n"}
{"id": 55568, "name": "Verify distribution uniformity_Chi-squared test", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n"}
{"id": 55569, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n"}
{"id": 55570, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n"}
{"id": 55571, "name": "Topological sort_Extracted top item", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n"}
{"id": 55572, "name": "Topological sort_Extracted top item", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n"}
{"id": 55573, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n"}
{"id": 55574, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 55575, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 55576, "name": "Superpermutation minimisation", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55577, "name": "GUI component interaction", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n"}
{"id": 55578, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 55579, "name": "Summarize and say sequence", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55580, "name": "Spelling of ordinal numbers", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 55581, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 55582, "name": "Addition chains", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 55583, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 55584, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 55585, "name": "Sparkline in unicode", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55586, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 55587, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 55588, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 55589, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 55590, "name": "Simulate input_Mouse", "Python": "import ctypes\n\ndef click():\n    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    \n    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    \n\nclick()\n", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n"}
{"id": 55591, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 55592, "name": "Sunflower fractal", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 55593, "name": "Vogel's approximation method", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 55594, "name": "Vogel's approximation method", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 55595, "name": "Air mass", "Python": "\n\nfrom math import sqrt, cos, exp\n\nDEG = 0.017453292519943295769236907684886127134  \nRE = 6371000                                     \ndd = 0.001      \nFIN = 10000000  \n \ndef rho(a):\n    \n    return exp(-a / 8500.0)\n \ndef height(a, z, d):\n     \n    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE\n \ndef column_density(a, z):\n    \n    dsum, d = 0.0, 0.0\n    while d < FIN:\n        delta = max(dd, (dd)*d)  \n        dsum += rho(height(a, z, d + 0.5 * delta)) * delta\n        d += delta\n    return dsum\n\ndef airmass(a, z):\n    return column_density(a, z) / column_density(a, 0)\n\nprint('Angle           0 m          13700 m\\n', '-' * 36)\nfor z in range(0, 91, 5):\n    print(f\"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}\")\n", "C": "#include <math.h>\n#include <stdio.h>\n\n#define DEG 0.017453292519943295769236907684886127134  \n#define RE 6371000.0 \n#define DD 0.001 \n#define FIN 10000000.0 \n\nstatic double rho(double a) {\n    \n    return exp(-a / 8500.0);\n}\n\nstatic double height(double a, double z, double d) {\n    \n    \n    \n    double aa = RE + a;\n    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));\n    return hh - RE;\n}\n\nstatic double column_density(double a, double z) {\n    \n    double sum = 0.0, d = 0.0;\n    while (d < FIN) {\n        \n        double delta = DD * d;\n        if (delta < DD)\n            delta = DD;\n        sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n        d += delta;\n    }\n    return sum;\n}\n\nstatic double airmass(double a, double z) {\n    return column_density(a, z) / column_density(a, 0.0);\n}\n\nint main() {\n    puts(\"Angle     0 m              13700 m\");\n    puts(\"------------------------------------\");\n    for (double z = 0; z <= 90; z+= 5) {\n        printf(\"%2.0f      %11.8f      %11.8f\\n\",\n               z, airmass(0.0, z), airmass(13700.0, z));\n    }\n}\n"}
{"id": 55596, "name": "Day of the week of Christmas and New Year", "Python": "import datetime\n\nweekDays = (\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\")\nthisXMas  = datetime.date(2021,12,25)\nthisXMasDay = thisXMas.weekday()\nthisXMasDayAsString = weekDays[thisXMasDay]\nprint(\"This year's Christmas is on a {}\".format(thisXMasDayAsString))\n\nnextNewYear = datetime.date(2022,1,1)\nnextNewYearDay = nextNewYear.weekday()\nnextNewYearDayAsString = weekDays[nextNewYearDay]\nprint(\"Next new year is on a {}\".format(nextNewYearDayAsString))\n", "C": "#define _XOPEN_SOURCE\n#include <stdio.h>\n#include <time.h>\n\nint main() {\n    struct tm t[2];\n    strptime(\"2021-12-25\", \"%F\", &t[0]);\n    strptime(\"2022-01-01\", \"%F\", &t[1]);\n    for (int i=0; i<2; i++) {\n        char buf[32];\n        strftime(buf, 32, \"%F is a %A\", &t[i]);\n        puts(buf);\n    }\n    return 0;\n}\n"}
{"id": 55597, "name": "Formal power series", "Python": "\n\nfrom itertools import islice\nfrom fractions import Fraction\nfrom functools import reduce\ntry:\n    from itertools import izip as zip \nexcept:\n    pass\n\ndef head(n):\n    \n    return lambda seq: islice(seq, n)\n\ndef pipe(gen, *cmds):\n    \n    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)\n\ndef sinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    zero = 0\n    yield zero\n    while True:\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\n        sign = -sign\n        n +=1\n        fac *= n\n        yield zero\ndef cosinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    yield Fraction(1,fac)\n    zero = 0\n    while True:\n        n +=1\n        fac *= n\n        yield zero\n        sign = -sign\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\ndef pluspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield sum(elements)\ndef minuspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield elements[0] - sum(elements[1:])\ndef mulpower(fgen,ggen):\n    'From: http://en.wikipedia.org/wiki/Power_series\n    a,b = [],[]\n    for f,g in zip(fgen, ggen):\n        a.append(f)\n        b.append(g)\n        yield sum(f*g for f,g in zip(a, reversed(b)))\ndef constpower(n):\n    yield n\n    while True:\n        yield 0\ndef diffpower(gen):\n    'differentiatiate power series'\n    next(gen)\n    for n, an in enumerate(gen, start=1):\n        yield an*n\ndef intgpower(k=0):\n    'integrate power series with constant k'\n    def _intgpower(gen):\n        yield k\n        for n, an in enumerate(gen, start=1):\n            yield an * Fraction(1,n)\n    return _intgpower\n\n\nprint(\"cosine\")\nc = list(pipe(cosinepower(), head(10)))\nprint(c)\nprint(\"sine\")\ns = list(pipe(sinepower(), head(10)))\nprint(s)\n\nintegc = list(pipe(cosinepower(),intgpower(0), head(10)))\n\nintegs1 = list(minuspower(pipe(constpower(1), head(10)),\n                          pipe(sinepower(),intgpower(0), head(10))))\n\nassert s == integc, \"The integral of cos should be sin\"\nassert c == integs1, \"1 minus the integral of sin should be cos\"\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h> \n\nenum fps_type {\n        FPS_CONST = 0,\n        FPS_ADD,\n        FPS_SUB,\n        FPS_MUL,\n        FPS_DIV,\n        FPS_DERIV,\n        FPS_INT,\n};\n\ntypedef struct fps_t *fps;\ntypedef struct fps_t {\n        int type;\n        fps s1, s2;\n        double a0;\n} fps_t;\n\nfps fps_new()\n{\n        fps x = malloc(sizeof(fps_t));\n        x->a0 = 0;\n        x->s1 = x->s2 = 0;\n        x->type = 0;\n        return x;\n}\n\n\nvoid fps_redefine(fps x, int op, fps y, fps z)\n{\n        x->type = op;\n        x->s1 = y;\n        x->s2 = z;\n}\n\nfps _binary(fps x, fps y, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->s2 = y;\n        s->type = op;\n        return s;\n}\n\nfps _unary(fps x, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->type = op;\n        return s;\n}\n\n\ndouble term(fps x, int n)\n{\n        double ret = 0;\n        int i;\n\n        switch (x->type) {\n        case FPS_CONST: return n > 0 ? 0 : x->a0;\n        case FPS_ADD:\n                ret = term(x->s1, n) + term(x->s2, n); break;\n\n        case FPS_SUB:\n                ret = term(x->s1, n) - term(x->s2, n); break;\n\n        case FPS_MUL:\n                for (i = 0; i <= n; i++)\n                        ret += term(x->s1, i) * term(x->s2, n - i);\n                break;\n\n        case FPS_DIV:\n                if (! term(x->s2, 0)) return NAN;\n\n                ret = term(x->s1, n);\n                for (i = 1; i <= n; i++)\n                        ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0);\n                break;\n\n        case FPS_DERIV:\n                ret = n * term(x->s1, n + 1);\n                break;\n\n        case FPS_INT:\n                if (!n) return x->a0;\n                ret = term(x->s1, n - 1) / n;\n                break;\n\n        default:\n                fprintf(stderr, \"Unknown operator %d\\n\", x->type);\n                exit(1);\n        }\n\n        return ret;\n}\n\n#define _add(x, y) _binary(x, y, FPS_ADD)\n#define _sub(x, y) _binary(x, y, FPS_SUB)\n#define _mul(x, y) _binary(x, y, FPS_MUL)\n#define _div(x, y) _binary(x, y, FPS_DIV)\n#define _integ(x)  _unary(x, FPS_INT)\n#define _deriv(x)  _unary(x, FPS_DERIV)\n\nfps fps_const(double a0)\n{\n        fps x = fps_new();\n        x->type = FPS_CONST;\n        x->a0 = a0;\n        return x;\n}\n\nint main()\n{\n        int i;\n        fps one = fps_const(1);\n        fps fcos = fps_new();           \n        fps fsin = _integ(fcos);        \n        fps ftan = _div(fsin, fcos);    \n\n        \n        fps_redefine(fcos, FPS_SUB, one, _integ(fsin));\n\n        fps fexp = fps_const(1);        \n        \n        fps_redefine(fexp, FPS_INT, fexp, 0);\n\n        printf(\"Sin:\");   for (i = 0; i < 10; i++) printf(\" %g\", term(fsin, i));\n        printf(\"\\nCos:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fcos, i));\n        printf(\"\\nTan:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(ftan, i));\n        printf(\"\\nExp:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fexp, i));\n\n        return 0;\n}\n"}
{"id": 55598, "name": "Own digits power sum", "Python": "\n\ndef isowndigitspowersum(integer):\n    \n    digits = [int(c) for c in str(integer)]\n    exponent = len(digits)\n    return sum(x ** exponent for x in digits) == integer\n\nprint(\"Own digits power sums for N = 3 to 9 inclusive:\")\nfor i in range(100, 1000000000):\n    if isowndigitspowersum(i):\n        print(i)\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define MAX_DIGITS 9\n\nint digits[MAX_DIGITS];\n\nvoid getDigits(int i) {\n    int ix = 0;\n    while (i > 0) {\n        digits[ix++] = i % 10;\n        i /= 10;\n    }\n}\n\nint main() {\n    int n, d, i, max, lastDigit, sum, dp;\n    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};\n    printf(\"Own digits power sums for N = 3 to 9 inclusive:\\n\");\n    for (n = 3; n < 10; ++n) {\n        for (d = 2; d < 10; ++d) powers[d] *= d;\n        i = (int)pow(10, n-1);\n        max = i * 10;\n        lastDigit = 0;\n        while (i < max) {\n            if (!lastDigit) {\n                getDigits(i);\n                sum = 0;\n                for (d = 0; d < n; ++d) {\n                    dp = digits[d];\n                    sum += powers[dp];\n                }\n            } else if (lastDigit == 1) {\n                sum++;\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1];\n            }\n            if (sum == i) {\n                printf(\"%d\\n\", i);\n                if (lastDigit == 0) printf(\"%d\\n\", i + 1);\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (sum > i) {\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (lastDigit < 9) {\n                i++;\n                lastDigit++;\n            } else {\n                i++;\n                lastDigit = 0;\n            }\n        }\n    }\n    return 0;\n}\n"}
{"id": 55599, "name": "Compiler_virtual machine interpreter", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <stdint.h>\n#include <ctype.h>\n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type)  type *name = NULL;          \\\n                            int _qy_ ## name ## _p = 0;  \\\n                            int _qy_ ## name ## _max = 0\n\n#define da_redim(name)      do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n                                name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name)     _qy_ ## name ## _p = 0\n\n#define da_append(name, x)  do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n    OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n    char    *text;\n    Code_t   op;\n} Code_map;\n\nCode_map code_map[] = {\n    {\"fetch\",  FETCH},\n    {\"store\",  STORE},\n    {\"push\",   PUSH },\n    {\"add\",    ADD  },\n    {\"sub\",    SUB  },\n    {\"mul\",    MUL  },\n    {\"div\",    DIV  },\n    {\"mod\",    MOD  },\n    {\"lt\",     LT   },\n    {\"gt\",     GT   },\n    {\"le\",     LE   },\n    {\"ge\",     GE   },\n    {\"eq\",     EQ   },\n    {\"ne\",     NE   },\n    {\"and\",    AND  },\n    {\"or\",     OR   },\n    {\"neg\",    NEG  },\n    {\"not\",    NOT  },\n    {\"jmp\",    JMP  },\n    {\"jz\",     JZ   },\n    {\"prtc\",   PRTC },\n    {\"prts\",   PRTS },\n    {\"prti\",   PRTI },\n    {\"halt\",   HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n    va_list ap;\n    char buf[1000];\n\n    va_start(ap, fmt);\n    vsprintf(buf, fmt, ap);\n    va_end(ap);\n    printf(\"error: %s\\n\", buf);\n    exit(1);\n}\n\n\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n    int32_t *sp = &data[g_size + 1];\n    const code *pc = obj;\n\n    again:\n    switch (*pc++) {\n        case FETCH: *sp++ = data[*(int32_t *)pc];  pc += sizeof(int32_t); goto again;\n        case STORE: data[*(int32_t *)pc] = *--sp;  pc += sizeof(int32_t); goto again;\n        case PUSH:  *sp++ = *(int32_t *)pc;        pc += sizeof(int32_t); goto again;\n        case ADD:   sp[-2] += sp[-1]; --sp;                             goto again;\n        case SUB:   sp[-2] -= sp[-1]; --sp;                             goto again;\n        case MUL:   sp[-2] *= sp[-1]; --sp;                             goto again;\n        case DIV:   sp[-2] /= sp[-1]; --sp;                             goto again;\n        case MOD:   sp[-2] %= sp[-1]; --sp;                             goto again;\n        case LT:    sp[-2] = sp[-2] <  sp[-1]; --sp;                    goto again;\n        case GT:    sp[-2] = sp[-2] >  sp[-1]; --sp;                    goto again;\n        case LE:    sp[-2] = sp[-2] <= sp[-1]; --sp;                    goto again;\n        case GE:    sp[-2] = sp[-2] >= sp[-1]; --sp;                    goto again;\n        case EQ:    sp[-2] = sp[-2] == sp[-1]; --sp;                    goto again;\n        case NE:    sp[-2] = sp[-2] != sp[-1]; --sp;                    goto again;\n        case AND:   sp[-2] = sp[-2] && sp[-1]; --sp;                    goto again;\n        case OR:    sp[-2] = sp[-2] || sp[-1]; --sp;                    goto again;\n        case NEG:   sp[-1] = -sp[-1];                                   goto again;\n        case NOT:   sp[-1] = !sp[-1];                                   goto again;\n        case JMP:   pc += *(int32_t *)pc;                               goto again;\n        case JZ:    pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n        case PRTC:  printf(\"%c\", sp[-1]); --sp;                         goto again;\n        case PRTS:  printf(\"%s\", string_pool[sp[-1]]); --sp;            goto again;\n        case PRTI:  printf(\"%d\", sp[-1]); --sp;                         goto again;\n        case HALT:                                                      break;\n        default:    error(\"Unknown opcode %d\\n\", *(pc - 1));\n    }\n}\n\nchar *read_line(int *len) {\n    static char *text = NULL;\n    static int textmax = 0;\n\n    for (*len = 0; ; (*len)++) {\n        int ch = fgetc(source_fp);\n        if (ch == EOF || ch == '\\n') {\n            if (*len == 0)\n                return NULL;\n            break;\n        }\n        if (*len + 1 >= textmax) {\n            textmax = (textmax == 0 ? 128 : textmax * 2);\n            text = realloc(text, textmax);\n        }\n        text[*len] = ch;\n    }\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *rtrim(char *text, int *len) {         \n    for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n        ;\n\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *translate(char *st) {\n    char *p, *q;\n    if (st[0] == '\"')                       \n        ++st;\n    p = q = st;\n\n    while ((*p++ = *q++) != '\\0') {\n        if (q[-1] == '\\\\') {\n            if (q[0] == 'n') {\n                p[-1] = '\\n';\n                ++q;\n            } else if (q[0] == '\\\\') {\n                ++q;\n            }\n        }\n        if (q[0] == '\"' && q[1] == '\\0')    \n            ++q;\n    }\n\n    return st;\n}\n\n\nint findit(const char text[], int offset) {\n    for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n        if (strcmp(code_map[i].text, text) == 0)\n            return code_map[i].op;\n    }\n    error(\"Unknown instruction %s at %d\\n\", text, offset);\n    return -1;\n}\n\nvoid emit_byte(int c) {\n    da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n    union {\n        int32_t n;\n        unsigned char c[sizeof(int32_t)];\n    } x;\n\n    x.n = n;\n\n    for (size_t i = 0; i < sizeof(x.n); ++i) {\n        emit_byte(x.c[i]);\n    }\n}\n\n\n\n\nchar **load_code(int *ds) {\n    int line_len, n_strings;\n    char **string_pool;\n    char *text = read_line(&line_len);\n    text = rtrim(text, &line_len);\n\n    strtok(text, \" \");                      \n    *ds = atoi(strtok(NULL, \" \"));          \n    strtok(NULL, \" \");                      \n    n_strings = atoi(strtok(NULL, \" \"));    \n\n    string_pool = malloc(n_strings * sizeof(char *));\n    for (int i = 0; i < n_strings; ++i) {\n        text = read_line(&line_len);\n        text = rtrim(text, &line_len);\n        text = translate(text);\n        string_pool[i] = strdup(text);\n    }\n\n    for (;;) {\n        int len;\n\n        text = read_line(&line_len);\n        if (text == NULL)\n            break;\n        text = rtrim(text, &line_len);\n\n        int offset = atoi(strtok(text, \" \"));   \n        char *instr = strtok(NULL, \" \");    \n        int opcode = findit(instr, offset);\n        emit_byte(opcode);\n        char *operand = strtok(NULL, \" \");\n\n        switch (opcode) {\n            case JMP: case JZ:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n            case PUSH:\n                emit_int(atoi(operand));\n                break;\n            case FETCH: case STORE:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n        }\n    }\n    return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n    if (fn[0] == '\\0')\n        *fp = std;\n    else if ((*fp = fopen(fn, mode)) == NULL)\n        error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n    init_io(&source_fp, stdin,  \"r\",  argc > 1 ? argv[1] : \"\");\n    int data_size;\n    char **string_pool = load_code(&data_size);\n    int data[1000 + data_size];\n    run_vm(object, data, data_size, string_pool);\n}\n"}
{"id": 55600, "name": "Compiler_virtual machine interpreter", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <stdint.h>\n#include <ctype.h>\n\n#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))\n\n#define da_dim(name, type)  type *name = NULL;          \\\n                            int _qy_ ## name ## _p = 0;  \\\n                            int _qy_ ## name ## _max = 0\n\n#define da_redim(name)      do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \\\n                                name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)\n\n#define da_rewind(name)     _qy_ ## name ## _p = 0\n\n#define da_append(name, x)  do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0)\n\ntypedef unsigned char uchar;\ntypedef uchar code;\n\ntypedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND,\n    OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT\n} Code_t;\n\ntypedef struct Code_map {\n    char    *text;\n    Code_t   op;\n} Code_map;\n\nCode_map code_map[] = {\n    {\"fetch\",  FETCH},\n    {\"store\",  STORE},\n    {\"push\",   PUSH },\n    {\"add\",    ADD  },\n    {\"sub\",    SUB  },\n    {\"mul\",    MUL  },\n    {\"div\",    DIV  },\n    {\"mod\",    MOD  },\n    {\"lt\",     LT   },\n    {\"gt\",     GT   },\n    {\"le\",     LE   },\n    {\"ge\",     GE   },\n    {\"eq\",     EQ   },\n    {\"ne\",     NE   },\n    {\"and\",    AND  },\n    {\"or\",     OR   },\n    {\"neg\",    NEG  },\n    {\"not\",    NOT  },\n    {\"jmp\",    JMP  },\n    {\"jz\",     JZ   },\n    {\"prtc\",   PRTC },\n    {\"prts\",   PRTS },\n    {\"prti\",   PRTI },\n    {\"halt\",   HALT },\n};\n\nFILE *source_fp;\nda_dim(object, code);\n\nvoid error(const char *fmt, ... ) {\n    va_list ap;\n    char buf[1000];\n\n    va_start(ap, fmt);\n    vsprintf(buf, fmt, ap);\n    va_end(ap);\n    printf(\"error: %s\\n\", buf);\n    exit(1);\n}\n\n\nvoid run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) {\n    int32_t *sp = &data[g_size + 1];\n    const code *pc = obj;\n\n    again:\n    switch (*pc++) {\n        case FETCH: *sp++ = data[*(int32_t *)pc];  pc += sizeof(int32_t); goto again;\n        case STORE: data[*(int32_t *)pc] = *--sp;  pc += sizeof(int32_t); goto again;\n        case PUSH:  *sp++ = *(int32_t *)pc;        pc += sizeof(int32_t); goto again;\n        case ADD:   sp[-2] += sp[-1]; --sp;                             goto again;\n        case SUB:   sp[-2] -= sp[-1]; --sp;                             goto again;\n        case MUL:   sp[-2] *= sp[-1]; --sp;                             goto again;\n        case DIV:   sp[-2] /= sp[-1]; --sp;                             goto again;\n        case MOD:   sp[-2] %= sp[-1]; --sp;                             goto again;\n        case LT:    sp[-2] = sp[-2] <  sp[-1]; --sp;                    goto again;\n        case GT:    sp[-2] = sp[-2] >  sp[-1]; --sp;                    goto again;\n        case LE:    sp[-2] = sp[-2] <= sp[-1]; --sp;                    goto again;\n        case GE:    sp[-2] = sp[-2] >= sp[-1]; --sp;                    goto again;\n        case EQ:    sp[-2] = sp[-2] == sp[-1]; --sp;                    goto again;\n        case NE:    sp[-2] = sp[-2] != sp[-1]; --sp;                    goto again;\n        case AND:   sp[-2] = sp[-2] && sp[-1]; --sp;                    goto again;\n        case OR:    sp[-2] = sp[-2] || sp[-1]; --sp;                    goto again;\n        case NEG:   sp[-1] = -sp[-1];                                   goto again;\n        case NOT:   sp[-1] = !sp[-1];                                   goto again;\n        case JMP:   pc += *(int32_t *)pc;                               goto again;\n        case JZ:    pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again;\n        case PRTC:  printf(\"%c\", sp[-1]); --sp;                         goto again;\n        case PRTS:  printf(\"%s\", string_pool[sp[-1]]); --sp;            goto again;\n        case PRTI:  printf(\"%d\", sp[-1]); --sp;                         goto again;\n        case HALT:                                                      break;\n        default:    error(\"Unknown opcode %d\\n\", *(pc - 1));\n    }\n}\n\nchar *read_line(int *len) {\n    static char *text = NULL;\n    static int textmax = 0;\n\n    for (*len = 0; ; (*len)++) {\n        int ch = fgetc(source_fp);\n        if (ch == EOF || ch == '\\n') {\n            if (*len == 0)\n                return NULL;\n            break;\n        }\n        if (*len + 1 >= textmax) {\n            textmax = (textmax == 0 ? 128 : textmax * 2);\n            text = realloc(text, textmax);\n        }\n        text[*len] = ch;\n    }\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *rtrim(char *text, int *len) {         \n    for (; *len > 0 && isspace(text[*len - 1]); --(*len))\n        ;\n\n    text[*len] = '\\0';\n    return text;\n}\n\nchar *translate(char *st) {\n    char *p, *q;\n    if (st[0] == '\"')                       \n        ++st;\n    p = q = st;\n\n    while ((*p++ = *q++) != '\\0') {\n        if (q[-1] == '\\\\') {\n            if (q[0] == 'n') {\n                p[-1] = '\\n';\n                ++q;\n            } else if (q[0] == '\\\\') {\n                ++q;\n            }\n        }\n        if (q[0] == '\"' && q[1] == '\\0')    \n            ++q;\n    }\n\n    return st;\n}\n\n\nint findit(const char text[], int offset) {\n    for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) {\n        if (strcmp(code_map[i].text, text) == 0)\n            return code_map[i].op;\n    }\n    error(\"Unknown instruction %s at %d\\n\", text, offset);\n    return -1;\n}\n\nvoid emit_byte(int c) {\n    da_append(object, (uchar)c);\n}\n\nvoid emit_int(int32_t n) {\n    union {\n        int32_t n;\n        unsigned char c[sizeof(int32_t)];\n    } x;\n\n    x.n = n;\n\n    for (size_t i = 0; i < sizeof(x.n); ++i) {\n        emit_byte(x.c[i]);\n    }\n}\n\n\n\n\nchar **load_code(int *ds) {\n    int line_len, n_strings;\n    char **string_pool;\n    char *text = read_line(&line_len);\n    text = rtrim(text, &line_len);\n\n    strtok(text, \" \");                      \n    *ds = atoi(strtok(NULL, \" \"));          \n    strtok(NULL, \" \");                      \n    n_strings = atoi(strtok(NULL, \" \"));    \n\n    string_pool = malloc(n_strings * sizeof(char *));\n    for (int i = 0; i < n_strings; ++i) {\n        text = read_line(&line_len);\n        text = rtrim(text, &line_len);\n        text = translate(text);\n        string_pool[i] = strdup(text);\n    }\n\n    for (;;) {\n        int len;\n\n        text = read_line(&line_len);\n        if (text == NULL)\n            break;\n        text = rtrim(text, &line_len);\n\n        int offset = atoi(strtok(text, \" \"));   \n        char *instr = strtok(NULL, \" \");    \n        int opcode = findit(instr, offset);\n        emit_byte(opcode);\n        char *operand = strtok(NULL, \" \");\n\n        switch (opcode) {\n            case JMP: case JZ:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n            case PUSH:\n                emit_int(atoi(operand));\n                break;\n            case FETCH: case STORE:\n                operand++;                  \n                len = strlen(operand);\n                operand[len - 1] = '\\0';    \n                emit_int(atoi(operand));\n                break;\n        }\n    }\n    return string_pool;\n}\n\nvoid init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) {\n    if (fn[0] == '\\0')\n        *fp = std;\n    else if ((*fp = fopen(fn, mode)) == NULL)\n        error(0, 0, \"Can't open %s\\n\", fn);\n}\n\nint main(int argc, char *argv[]) {\n    init_io(&source_fp, stdin,  \"r\",  argc > 1 ? argv[1] : \"\");\n    int data_size;\n    char **string_pool = load_code(&data_size);\n    int data[1000 + data_size];\n    run_vm(object, data, data_size, string_pool);\n}\n"}
{"id": 55601, "name": "Klarner-Rado sequence", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n"}
{"id": 55602, "name": "Klarner-Rado sequence", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n", "C": "#include <stdio.h>\n\n#define ELEMENTS 10000000U\n\nvoid make_klarner_rado(unsigned int *dst, unsigned int n) {\n    unsigned int i, i2 = 0, i3 = 0;\n    unsigned int m, m2 = 1, m3 = 1;\n\n    for (i = 0; i < n; ++i) {\n        dst[i] = m = m2 < m3 ? m2 : m3;\n        if (m2 == m) m2 = dst[i2++] << 1 | 1;\n        if (m3 == m) m3 = dst[i3++] * 3 + 1;\n    }\n}\n\nint main(void) {\n    static unsigned int klarner_rado[ELEMENTS];\n    unsigned int i;\n\n    make_klarner_rado(klarner_rado, ELEMENTS);\n\n    for (i = 0; i < 99; ++i)\n        printf(\"%u \", klarner_rado[i]);\n    for (i = 100; i <= ELEMENTS; i *= 10)\n        printf(\"%u\\n\", klarner_rado[i - 1]);\n\n    return 0;\n}\n"}
{"id": 55603, "name": "Bitmap_Bézier curves_Cubic", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n", "C": "void cubic_bezier(\n       \timage img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        unsigned int x4, unsigned int y4,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 55604, "name": "Sorting algorithms_Pancake sort", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n"}
{"id": 55605, "name": "Largest five adjacent number", "Python": "\n\nfrom random import seed,randint\nfrom datetime import datetime\n\nseed(str(datetime.now()))\n\nlargeNum = [randint(1,9)]\n\nfor i in range(1,1000):\n    largeNum.append(randint(0,9))\n\nmaxNum,minNum = 0,99999\n\nfor i in range(0,994):\n    num = int(\"\".join(map(str,largeNum[i:i+5])))\n    if num > maxNum:\n        maxNum = num\n    elif num < minNum:\n        minNum = num\n\nprint(\"Largest 5-adjacent number found \", maxNum)\nprint(\"Smallest 5-adjacent number found \", minNum)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\n#define DIGITS 1000\n#define NUMSIZE 5\n\nuint8_t randomDigit() {\n    uint8_t d;\n    do {d = rand() & 0xF;} while (d >= 10);\n    return d;\n}\n\nint numberAt(uint8_t *d, int size) {\n    int acc = 0;\n    while (size--) acc = 10*acc + *d++;\n    return acc;\n}\n\nint main() {\n    uint8_t digits[DIGITS];\n    int i, largest = 0;\n    \n    srand(time(NULL));\n    \n    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();\n    for (i=0; i<DIGITS-NUMSIZE; i++) {\n        int here = numberAt(&digits[i], NUMSIZE);\n        if (here > largest) largest = here;\n    }\n\n    printf(\"%d\\n\", largest);\n    return 0;\n}\n"}
{"id": 55606, "name": "Sum of square and cube digits of an integer are primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef digSum(n, b):\n    s = 0\n    while n:\n        s += (n % b)\n        n = n // b\n    return s\n\nif __name__ == '__main__':\n    for n in range(11, 99):\n        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):\n            print(n, end = \"  \")\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint digit_sum(int n) {\n    int sum;\n    for (sum = 0; n; n /= 10) sum += n % 10;\n    return sum;\n}\n\n\nbool prime(int n) {\n    if (n<4) return n>=2;\n    for (int d=2; d*d <= n; d++)\n        if (n%d == 0) return false;\n    return true;\n}\n\nint main() {\n    for (int i=1; i<100; i++)\n        if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i)))\n            printf(\"%d \", i);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55607, "name": "The sieve of Sundaram", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\nint main(void) {\n    int nprimes =  1000000;\n    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  \n      \n      \n    int i, j, m, k; int *a;\n    k = (nmax-2)/2; \n    a = (int *)calloc(k + 1, sizeof(int));\n    for(i = 0; i <= k; i++)a[i] = 2*i+1; \n    for (i = 1; (i+1)*i*2 <= k; i++)\n        for (j = i; j <= (k-i)/(2*i+1); j++) {\n            m = i + j + 2*i*j;\n            if(a[m]) a[m] = 0;\n            }            \n        \n    for (i = 1, j = 0; i <= k; i++) \n       if (a[i]) {\n           if(j%10 == 0 && j <= 100)printf(\"\\n\");\n           j++; \n           if(j <= 100)printf(\"%3d \", a[i]);\n           else if(j == nprimes){\n               printf(\"\\n%d th prime is %d\\n\",j,a[i]);\n               break;\n               }\n           }\n}\n"}
{"id": 55608, "name": "Chemical calculator", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef char *string;\n\ntypedef struct node_t {\n    string symbol;\n    double weight;\n    struct node_t *next;\n} node;\n\nnode *make_node(string symbol, double weight) {\n    node *nptr = malloc(sizeof(node));\n    if (nptr) {\n        nptr->symbol = symbol;\n        nptr->weight = weight;\n        nptr->next = NULL;\n        return nptr;\n    }\n    return NULL;\n}\n\nvoid free_node(node *ptr) {\n    if (ptr) {\n        free_node(ptr->next);\n        ptr->next = NULL;\n        free(ptr);\n    }\n}\n\nnode *insert(string symbol, double weight, node *head) {\n    node *nptr = make_node(symbol, weight);\n    nptr->next = head;\n    return nptr;\n}\n\nnode *dic;\nvoid init() {\n    dic = make_node(\"H\", 1.008);\n    dic = insert(\"He\", 4.002602, dic);\n    dic = insert(\"Li\", 6.94, dic);\n    dic = insert(\"Be\", 9.0121831, dic);\n    dic = insert(\"B\", 10.81, dic);\n    dic = insert(\"C\", 12.011, dic);\n    dic = insert(\"N\", 14.007, dic);\n    dic = insert(\"O\", 15.999, dic);\n    dic = insert(\"F\", 18.998403163, dic);\n    dic = insert(\"Ne\", 20.1797, dic);\n    dic = insert(\"Na\", 22.98976928, dic);\n    dic = insert(\"Mg\", 24.305, dic);\n    dic = insert(\"Al\", 26.9815385, dic);\n    dic = insert(\"Si\", 28.085, dic);\n    dic = insert(\"P\", 30.973761998, dic);\n    dic = insert(\"S\", 32.06, dic);\n    dic = insert(\"Cl\", 35.45, dic);\n    dic = insert(\"Ar\", 39.948, dic);\n    dic = insert(\"K\", 39.0983, dic);\n    dic = insert(\"Ca\", 40.078, dic);\n    dic = insert(\"Sc\", 44.955908, dic);\n    dic = insert(\"Ti\", 47.867, dic);\n    dic = insert(\"V\", 50.9415, dic);\n    dic = insert(\"Cr\", 51.9961, dic);\n    dic = insert(\"Mn\", 54.938044, dic);\n    dic = insert(\"Fe\", 55.845, dic);\n    dic = insert(\"Co\", 58.933194, dic);\n    dic = insert(\"Ni\", 58.6934, dic);\n    dic = insert(\"Cu\", 63.546, dic);\n    dic = insert(\"Zn\", 65.38, dic);\n    dic = insert(\"Ga\", 69.723, dic);\n    dic = insert(\"Ge\", 72.630, dic);\n    dic = insert(\"As\", 74.921595, dic);\n    dic = insert(\"Se\", 78.971, dic);\n    dic = insert(\"Br\", 79.904, dic);\n    dic = insert(\"Kr\", 83.798, dic);\n    dic = insert(\"Rb\", 85.4678, dic);\n    dic = insert(\"Sr\", 87.62, dic);\n    dic = insert(\"Y\", 88.90584, dic);\n    dic = insert(\"Zr\", 91.224, dic);\n    dic = insert(\"Nb\", 92.90637, dic);\n    dic = insert(\"Mo\", 95.95, dic);\n    dic = insert(\"Ru\", 101.07, dic);\n    dic = insert(\"Rh\", 102.90550, dic);\n    dic = insert(\"Pd\", 106.42, dic);\n    dic = insert(\"Ag\", 107.8682, dic);\n    dic = insert(\"Cd\", 112.414, dic);\n    dic = insert(\"In\", 114.818, dic);\n    dic = insert(\"Sn\", 118.710, dic);\n    dic = insert(\"Sb\", 121.760, dic);\n    dic = insert(\"Te\", 127.60, dic);\n    dic = insert(\"I\", 126.90447, dic);\n    dic = insert(\"Xe\", 131.293, dic);\n    dic = insert(\"Cs\", 132.90545196, dic);\n    dic = insert(\"Ba\", 137.327, dic);\n    dic = insert(\"La\", 138.90547, dic);\n    dic = insert(\"Ce\", 140.116, dic);\n    dic = insert(\"Pr\", 140.90766, dic);\n    dic = insert(\"Nd\", 144.242, dic);\n    dic = insert(\"Pm\", 145, dic);\n    dic = insert(\"Sm\", 150.36, dic);\n    dic = insert(\"Eu\", 151.964, dic);\n    dic = insert(\"Gd\", 157.25, dic);\n    dic = insert(\"Tb\", 158.92535, dic);\n    dic = insert(\"Dy\", 162.500, dic);\n    dic = insert(\"Ho\", 164.93033, dic);\n    dic = insert(\"Er\", 167.259, dic);\n    dic = insert(\"Tm\", 168.93422, dic);\n    dic = insert(\"Yb\", 173.054, dic);\n    dic = insert(\"Lu\", 174.9668, dic);\n    dic = insert(\"Hf\", 178.49, dic);\n    dic = insert(\"Ta\", 180.94788, dic);\n    dic = insert(\"W\", 183.84, dic);\n    dic = insert(\"Re\", 186.207, dic);\n    dic = insert(\"Os\", 190.23, dic);\n    dic = insert(\"Ir\", 192.217, dic);\n    dic = insert(\"Pt\", 195.084, dic);\n    dic = insert(\"Au\", 196.966569, dic);\n    dic = insert(\"Hg\", 200.592, dic);\n    dic = insert(\"Tl\", 204.38, dic);\n    dic = insert(\"Pb\", 207.2, dic);\n    dic = insert(\"Bi\", 208.98040, dic);\n    dic = insert(\"Po\", 209, dic);\n    dic = insert(\"At\", 210, dic);\n    dic = insert(\"Rn\", 222, dic);\n    dic = insert(\"Fr\", 223, dic);\n    dic = insert(\"Ra\", 226, dic);\n    dic = insert(\"Ac\", 227, dic);\n    dic = insert(\"Th\", 232.0377, dic);\n    dic = insert(\"Pa\", 231.03588, dic);\n    dic = insert(\"U\", 238.02891, dic);\n    dic = insert(\"Np\", 237, dic);\n    dic = insert(\"Pu\", 244, dic);\n    dic = insert(\"Am\", 243, dic);\n    dic = insert(\"Cm\", 247, dic);\n    dic = insert(\"Bk\", 247, dic);\n    dic = insert(\"Cf\", 251, dic);\n    dic = insert(\"Es\", 252, dic);\n    dic = insert(\"Fm\", 257, dic);\n    dic = insert(\"Uue\", 315, dic);\n    dic = insert(\"Ubn\", 299, dic);\n}\n\ndouble lookup(string symbol) {\n    for (node *ptr = dic; ptr; ptr = ptr->next) {\n        if (strcmp(symbol, ptr->symbol) == 0) {\n            return ptr->weight;\n        }\n    }\n\n    printf(\"symbol not found: %s\\n\", symbol);\n    return 0.0;\n}\n\ndouble total(double mass, int count) {\n    if (count > 0) {\n        return mass * count;\n    }\n    return mass;\n}\n\ndouble total_s(string sym, int count) {\n    double mass = lookup(sym);\n    return total(mass, count);\n}\n\ndouble evaluate_c(string expr, size_t *pos, double mass) {\n    int count = 0;\n    if (expr[*pos] < '0' || '9' < expr[*pos]) {\n        printf(\"expected to find a count, saw the character: %c\\n\", expr[*pos]);\n    }\n    for (; expr[*pos]; (*pos)++) {\n        char c = expr[*pos];\n        if ('0' <= c && c <= '9') {\n            count = count * 10 + c - '0';\n        } else {\n            break;\n        }\n    }\n    return total(mass, count);\n}\n\ndouble evaluate_p(string expr, size_t limit, size_t *pos) {\n    char sym[4];\n    int sym_pos = 0;\n    int count = 0;\n    double sum = 0.0;\n\n    for (; *pos < limit && expr[*pos]; (*pos)++) {\n        char c = expr[*pos];\n        if ('A' <= c && c <= 'Z') {\n            if (sym_pos > 0) {\n                sum += total_s(sym, count);\n                sym_pos = 0;\n                count = 0;\n            }\n            sym[sym_pos++] = c;\n            sym[sym_pos] = 0;\n        } else if ('a' <= c && c <= 'z') {\n            sym[sym_pos++] = c;\n            sym[sym_pos] = 0;\n        } else if ('0' <= c && c <= '9') {\n            count = count * 10 + c - '0';\n        } else if (c == '(') {\n            if (sym_pos > 0) {\n                sum += total_s(sym, count);\n                sym_pos = 0;\n                count = 0;\n            }\n\n            (*pos)++; \n            double mass = evaluate_p(expr, limit, pos);\n\n            sum += evaluate_c(expr, pos, mass);\n            (*pos)--; \n        } else if (c == ')') {\n            if (sym_pos > 0) {\n                sum += total_s(sym, count);\n                sym_pos = 0;\n                count = 0;\n            }\n\n            (*pos)++;\n            return sum;\n        } else {\n            printf(\"Unexpected character encountered: %c\\n\", c);\n        }\n    }\n\n    if (sym_pos > 0) {\n        sum += total_s(sym, count);\n    }\n    return sum;\n}\n\ndouble evaluate(string expr) {\n    size_t limit = strlen(expr);\n    size_t pos = 0;\n    return evaluate_p(expr, limit, &pos);\n}\n\nvoid test(string expr) {\n    double mass = evaluate(expr);\n    printf(\"%17s -> %7.3f\\n\", expr, mass);\n}\n\nint main() {\n    init();\n\n    test(\"H\");\n    test(\"H2\");\n    test(\"H2O\");\n    test(\"H2O2\");\n    test(\"(HO)2\");\n    test(\"Na2SO4\");\n    test(\"C6H12\");\n    test(\"COOH(C(CH3)2)3CH3\");\n    test(\"C6H4O2(OH)4\");\n    test(\"C27H46O\");\n    test(\"Uue\");\n\n    free_node(dic);\n    dic = NULL;\n    return 0;\n}\n"}
{"id": 55609, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n"}
{"id": 55610, "name": "Exactly three adjacent 3 in lists", "Python": "\n\nfrom itertools import dropwhile, takewhile\n\n\n\ndef nnPeers(n):\n    \n    def p(x):\n        return n == x\n\n    def go(xs):\n        fromFirstMatch = list(dropwhile(\n            lambda v: not p(v),\n            xs\n        ))\n        ns = list(takewhile(p, fromFirstMatch))\n        rest = fromFirstMatch[len(ns):]\n\n        return p(len(ns)) and (\n            not any(p(x) for x in rest)\n        )\n\n    return go\n\n\n\n\ndef main():\n    \n    print(\n        '\\n'.join([\n            f'{xs} -> {nnPeers(3)(xs)}' for xs in [\n                [9, 3, 3, 3, 2, 1, 7, 8, 5],\n                [5, 2, 9, 3, 3, 7, 8, 4, 1],\n                [1, 4, 3, 6, 7, 3, 8, 3, 2],\n                [1, 2, 3, 4, 5, 6, 7, 8, 9],\n                [4, 6, 8, 7, 2, 3, 3, 3, 1]\n            ]\n        ])\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool three_3s(const int *items, size_t len) {\n    int threes = 0;    \n    while (len--) \n        if (*items++ == 3)\n            if (threes<3) threes++;\n            else return false;\n        else if (threes != 0 && threes != 3) \n            return false;\n    return true;\n}\n\nvoid print_list(const int *items, size_t len) {\n    while (len--) printf(\"%d \", *items++);\n}\n\nint main() {\n    int lists[][9] = {\n        {9,3,3,3,2,1,7,8,5},\n        {5,2,9,3,3,6,8,4,1},\n        {1,4,3,6,7,3,8,3,2},\n        {1,2,3,4,5,6,7,8,9},\n        {4,6,8,7,2,3,3,3,1}\n    };\n    \n    size_t list_length = sizeof(lists[0]) / sizeof(int);\n    size_t n_lists = sizeof(lists) / sizeof(lists[0]);\n    \n    for (size_t i=0; i<n_lists; i++) {\n        print_list(lists[i], list_length);\n        printf(\"-> %s\\n\", three_3s(lists[i], list_length) ? \"true\" : \"false\");\n    }\n    \n    return 0;\n}\n"}
{"id": 55611, "name": "Permutations by swapping", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n"}
{"id": 55612, "name": "Minimum multiple of m where digital sum equals m", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n\nunsigned digit_sum(unsigned n) {\n    unsigned sum = 0;\n    do { sum += n % 10; }\n    while(n /= 10);\n    return sum;\n}\n\nunsigned a131382(unsigned n) {\n    unsigned m;\n    for (m = 1; n != digit_sum(m*n); m++);\n    return m;\n}\n\nint main() {\n    unsigned n;\n    for (n = 1; n <= 70; n++) {\n        printf(\"%9u\", a131382(n));\n        if (n % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55613, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 55614, "name": "Verhoeff algorithm", "Python": "MULTIPLICATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),\n    (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),\n    (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),\n    (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),\n    (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),\n    (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),\n    (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),\n    (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),\n    (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),\n]\n\nINV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)\n\nPERMUTATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),\n    (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),\n    (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),\n    (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),\n    (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),\n    (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),\n    (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),\n]\n\ndef verhoeffchecksum(n, validate=True, terse=True, verbose=False):\n    \n    if verbose:\n        print(f\"\\n{'Validation' if validate else 'Check digit'}\",\\\n            f\"calculations for {n}:\\n\\n i  nᵢ  p[i,nᵢ]   c\\n------------------\")\n    \n    c, dig = 0, list(str(n if validate else 10 * n))\n    for i, ni in enumerate(dig[::-1]):\n        p = PERMUTATION_TABLE[i % 8][int(ni)]\n        c = MULTIPLICATION_TABLE[c][p]\n        if verbose:\n            print(f\"{i:2}  {ni}      {p}    {c}\")\n\n    if verbose and not validate:\n        print(f\"\\ninv({c}) = {INV[c]}\")\n    if not terse:\n        print(f\"\\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}.\"\\\n              if validate else f\"\\nThe check digit for '{n}' is {INV[c]}.\")\n    return c == 0 if validate else INV[c]\n\nif __name__ == '__main__':\n\n    for n, va, t, ve in [\n        (236, False, False, True), (2363, True, False, True), (2369, True, False, True),\n        (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),\n        (123456789012, False, False, False), (1234567890120, True, False, False),\n        (1234567890129, True, False, False)]:\n        verhoeffchecksum(n, va, t, ve)\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic const int d[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n};\n\nstatic const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};\n\nstatic const int p[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n};\n\nint verhoeff(const char* s, bool validate, bool verbose) {\n    if (verbose) {\n        const char* t = validate ? \"Validation\" : \"Check digit\";\n        printf(\"%s calculations for '%s':\\n\\n\", t, s);\n        puts(u8\" i  n\\xE1\\xB5\\xA2  p[i,n\\xE1\\xB5\\xA2]  c\");\n        puts(\"------------------\");\n    }\n    int len = strlen(s);\n    if (validate)\n        --len;\n    int c = 0;\n    for (int i = len; i >= 0; --i) {\n        int ni = (i == len && !validate) ? 0 : s[i] - '0';\n        assert(ni >= 0 && ni < 10);\n        int pi = p[(len - i) % 8][ni];\n        c = d[c][pi];\n        if (verbose)\n            printf(\"%2d  %d      %d     %d\\n\", len - i, ni, pi, c);\n    }\n    if (verbose && !validate)\n        printf(\"\\ninv[%d] = %d\\n\", c, inv[c]);\n    return validate ? c == 0 : inv[c];\n}\n\nint main() {\n    const char* ss[3] = {\"236\", \"12345\", \"123456789012\"};\n    for (int i = 0; i < 3; ++i) {\n        const char* s = ss[i];\n        bool verbose = i < 2;\n        int c = verhoeff(s, false, verbose);\n        printf(\"\\nThe check digit for '%s' is '%d'.\\n\", s, c);\n        int len = strlen(s);\n        char sc[len + 2];\n        strncpy(sc, s, len + 2);\n        for (int j = 0; j < 2; ++j) {\n            sc[len] = (j == 0) ? c + '0' : '9';\n            int v = verhoeff(sc, true, verbose);\n            printf(\"\\nThe validation for '%s' is %s.\\n\", sc,\n                   v ? \"correct\" : \"incorrect\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 55615, "name": "Steady squares", "Python": "print(\"working...\")\nprint(\"Steady squares under 10.000 are:\")\nlimit = 10000\n\nfor n in range(1,limit):\n    nstr = str(n)\n    nlen = len(nstr)\n    square = str(pow(n,2))\n    rn = square[-nlen:]\n    if nstr == rn:\n       print(str(n) + \" \" + str(square))\n\nprint(\"done...\")\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n"}
{"id": 55616, "name": "Numbers in base 10 that are palindromic in bases 2, 4, and 16", "Python": "def reverse(n, base):\n    r = 0\n    while n > 0:\n        r = r*base + n%base\n        n = n//base\n    return r\n    \ndef palindrome(n, base):\n    return n == reverse(n, base)\n    \ncnt = 0\nfor i in range(25000):\n    if all(palindrome(i, base) for base in (2,4,16)):\n        cnt += 1\n        print(\"{:5}\".format(i), end=\" \\n\"[cnt % 12 == 0])\n\nprint()\n", "C": "#include <stdio.h>\n#define MAXIMUM 25000\n\nint reverse(int n, int base) {\n    int r;\n    for (r = 0; n; n /= base)\n        r = r*base + n%base;\n    return r;\n}\n\nint palindrome(int n, int base) {\n    return n == reverse(n, base);\n}\n\nint main() {\n    int i, c = 0;\n    \n    for (i = 0; i < MAXIMUM; i++) {\n        if (palindrome(i, 2) &&\n            palindrome(i, 4) &&\n            palindrome(i, 16)) {\n            printf(\"%5d%c\", i, ++c % 12 ? ' ' : '\\n');\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55617, "name": "Long stairs", "Python": "\n\nfrom numpy import mean\nfrom random import sample\n\ndef gen_long_stairs(start_step, start_length, climber_steps, add_steps):\n    secs, behind, total = 0, start_step, start_length\n    while True:\n        behind += climber_steps\n        behind += sum([behind > n for n in sample(range(total), add_steps)])\n        total += add_steps\n        secs += 1\n        yield (secs, behind, total)\n        \n\nls = gen_long_stairs(1, 100, 1, 5)\n\nprint(\"Seconds  Behind  Ahead\\n----------------------\")\nwhile True:\n    secs, pos, len = next(ls)\n    if 600 <= secs < 610:\n        print(secs, \"     \", pos, \"   \", len - pos)\n    elif secs == 610:\n        break\n\nprint(\"\\nTen thousand trials to top:\")\ntimes, heights = [], []\nfor trial in range(10_000):\n    trialstairs = gen_long_stairs(1, 100, 1, 5)\n    while True:\n        sec, step, height = next(trialstairs)\n        if step >= height:\n            times.append(sec)\n            heights.append(height)\n            break\n\nprint(\"Mean time:\", mean(times), \"secs. Mean height:\", mean(heights))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n    int trial, secs_tot=0, steps_tot=0;     \n    int sbeh, slen, wiz, secs;              \n    time_t t;\n    srand((unsigned) time(&t));             \n    printf( \"Seconds    steps behind    steps ahead\\n\" );\n    for( trial=1;trial<=10000;trial++ ) {   \n        sbeh = 0; slen = 100; secs = 0;     \n        while(sbeh<slen) {                  \n            sbeh+=1;                        \n            for(wiz=1;wiz<=5;wiz++) {       \n                if(rand()%slen < sbeh)\n                    sbeh+=1;                \n                slen+=1;                    \n            }\n            secs+=1;                        \n            if(trial==1&&599<secs&&secs<610)\n                printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh );\n            \n        }\n        secs_tot+=secs;\n        steps_tot+=slen;\n    }\n    printf( \"Average secs taken: %f\\n\", secs_tot/10000.0 );\n    printf( \"Average final length of staircase: %f\\n\", steps_tot/10000.0 ); \n    return 0;\n}\n"}
{"id": 55618, "name": "Terminal control_Positional read", "Python": "import curses\nfrom random import randint\n\n\n\nstdscr = curses.initscr()\nfor rows in range(10):\n    line = ''.join([chr(randint(41, 90)) for i in range(10)])\n    stdscr.addstr(line + '\\n')\n\n\nicol = 3 - 1\nirow = 6 - 1\nch = stdscr.instr(irow, icol, 1).decode(encoding=\"utf-8\")\n\n\nstdscr.move(irow, icol + 10)\nstdscr.addstr('Character at column 3, row 6 = ' + ch + '\\n')\nstdscr.getch()\n\ncurses.endwin()\n", "C": "#include <windows.h>\n#include <wchar.h>\n\nint\nmain()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n\tCOORD pos;\n\tHANDLE conout;\n\tlong len;\n\twchar_t c;\n\n\t\n\tconout = CreateFileW(L\"CONOUT$\", GENERIC_READ | GENERIC_WRITE,\n\t    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t    0, NULL);\n\tif (conout == INVALID_HANDLE_VALUE)\n\t\treturn 1;\n\n\t\n\tif (GetConsoleScreenBufferInfo(conout, &info) == 0)\n\t\treturn 1;\n\n\t\n\tpos.X = info.srWindow.Left + 3;  \n\tpos.Y = info.srWindow.Top  + 6;  \n\tif (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||\n\t    len <= 0)\n\t\treturn 1;\n\n\twprintf(L\"Character at (3, 6) had been '%lc'\\n\", c);\n\treturn 0;\n}\n"}
{"id": 55619, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 55620, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 55621, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 55622, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 55623, "name": "Image convolution", "Python": "\nfrom PIL import Image, ImageFilter\n\nif __name__==\"__main__\":\n\tim = Image.open(\"test.jpg\")\n\n\tkernelValues = [-2,-1,0,-1,1,1,0,1,2] \n\tkernel = ImageFilter.Kernel((3,3), kernelValues)\n\n\tim2 = im.filter(kernel)\n\n\tim2.show()\n", "C": "image filter(image img, double *K, int Ks, double, double);\n"}
{"id": 55624, "name": "Deconvolution_2D+", "Python": "\n\nimport numpy\nimport pprint\n\nh =  [\n      [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], \n      [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf =  [\n      [[-9, 5, -8], [3, 5, 1]], \n      [[-1, -7, 2], [-5, -6, 6]], \n      [[8, 5, 8],[-2, -6, -4]]]\ng =  [\n      [\n         [54, 42, 53, -42, 85, -72], \n         [45, -170, 94, -36, 48, 73], \n         [-39, 65, -112, -16, -78, -72], \n         [6, -11, -6, 62, 49, 8]], \n      [\n         [-57, 49, -23, 52, -135, 66], \n         [-23, 127, -58, -5, -118, 64], \n         [87, -16, 121, 23, -41, -12], \n         [-19, 29, 35, -148, -11, 45]], \n      [\n         [-55, -147, -146, -31, 55, 60], \n         [-88, -45, -28, 46, -26, -144], \n         [-12, -107, -34, 150, 249, 66], \n         [11, -15, -34, 27, -78, -50]], \n      [\n         [56, 67, 108, 4, 2, -48], \n         [58, 67, 89, 32, 32, -8], \n         [-42, -31, -103, -30, -23, -8],\n         [6, 4, -26, -10, 26, 12]]]\n      \ndef trim_zero_empty(x):\n    \n    \n    if len(x) > 0:\n        if type(x[0]) != numpy.ndarray:\n            \n            return list(numpy.trim_zeros(x))\n        else:\n            \n            new_x = []\n            for l in x:\n               tl = trim_zero_empty(l)\n               if len(tl) > 0:\n                   new_x.append(tl)\n            return new_x\n    else:\n        \n        return x\n       \ndef deconv(a, b):\n    \n    \n    \n\n    ffta = numpy.fft.fftn(a)\n    \n    \n    \n    \n    ashape = numpy.shape(a)\n    \n    \n    \n\n    fftb = numpy.fft.fftn(b,ashape)\n    \n    \n\n    fftquotient = ffta / fftb\n    \n    \n    \n\n    c = numpy.fft.ifftn(fftquotient)\n    \n    \n    \n\n    trimmedc = numpy.around(numpy.real(c),decimals=6)\n    \n    \n    \n    \n    cleanc = trim_zero_empty(trimmedc)\n                \n    return cleanc\n    \nprint(\"deconv(g,h)=\")\n\npprint.pprint(deconv(g,h))\n\nprint(\" \")\n\nprint(\"deconv(g,f)=\")\n\npprint.pprint(deconv(g,f))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n \n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n \n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n \nvoid deconv(double g[], int lg, double f[], int lf, double out[], int row_len) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n \n\tfft(g2, ns);\n\tfft(f2, ns);\n \n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i < ns; i++) {\n\t\tif (cabs(creal(h[i])) < 1e-10) \n\t\t\th[i] = 0;\n\t}\n\n\tfor (int i = 0; i > lf - lg - row_len; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\ndouble* unpack2(void *m, int rows, int len, int to_len)\n{\n\tdouble *buf = calloc(sizeof(double), rows * to_len);\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < len; j++)\n\t\t\tbuf[i * to_len + j] = ((double(*)[len])m)[i][j];\n\treturn buf;\n}\n\nvoid pack2(double * buf, int rows, int from_len, int to_len, void *out)\n{\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < to_len; j++)\n\t\t\t((double(*)[to_len])out)[i][j] = buf[i * from_len + j] / 4;\n}\n\nvoid deconv2(void *g, int row_g, int col_g, void *f, int row_f, int col_f, void *out) {\n\tdouble *g2 = unpack2(g, row_g, col_g, col_g);\n\tdouble *f2 = unpack2(f, row_f, col_f, col_g);\n\n\tdouble ff[(row_g - row_f + 1) * col_g];\n\tdeconv(g2, row_g * col_g, f2, row_f * col_g, ff, col_g);\n\tpack2(ff, row_g - row_f + 1, col_g, col_g - col_f + 1, out);\n\n\tfree(g2);\n\tfree(f2);\n}\n\ndouble* unpack3(void *m, int x, int y, int z, int to_y, int to_z)\n{\n\tdouble *buf = calloc(sizeof(double), x * to_y * to_z);\n\tfor (int i = 0; i < x; i++)\n\t\tfor (int j = 0; j < y; j++) {\n\t\t\tfor (int k = 0; k < z; k++)\n\t\t\t\tbuf[(i * to_y + j) * to_z + k] =\n\t\t\t\t\t((double(*)[y][z])m)[i][j][k];\n\t\t}\n\treturn buf;\n}\n\nvoid pack3(double * buf, int x, int y, int z, int to_y, int to_z, void *out)\n{\n\tfor (int i = 0; i < x; i++)\n\t\tfor (int j = 0; j < to_y; j++)\n\t\t\tfor (int k = 0; k < to_z; k++)\n\t\t\t\t((double(*)[to_y][to_z])out)[i][j][k] =\n\t\t\t\t\tbuf[(i * y + j) * z + k] / 4;\n}\n\nvoid deconv3(void *g, int gx, int gy, int gz, void *f, int fx, int fy, int fz, void *out) {\n\tdouble *g2 = unpack3(g, gx, gy, gz, gy, gz);\n\tdouble *f2 = unpack3(f, fx, fy, fz, gy, gz);\n\n\tdouble ff[(gx - fx + 1) * gy * gz];\n\tdeconv(g2, gx * gy * gz, f2, fx * gy * gz, ff, gy * gz);\n\tpack3(ff, gx - fx + 1, gy, gz, gy - fy + 1, gz - fz + 1, out);\n\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble h[2][3][4] = {\n\t\t{{-6, -8, -5,  9}, {-7, 9, -6, -8}, { 2, -7,  9,  8}},\n\t\t{{ 7,  4,  4, -6}, { 9, 9,  4, -4}, {-3,  7, -2, -3}}\n\t};\n\tint hx = 2, hy = 3, hz = 4;\n\tdouble f[3][2][3] = {\t{{-9,  5, -8}, { 3,  5,  1}},\n\t\t\t\t{{-1, -7,  2}, {-5, -6,  6}},\n\t\t\t\t{{ 8,  5,  8}, {-2, -6, -4}} };\n\tint fx = 3, fy = 2, fz = 3;\n\tdouble g[4][4][6] = {\n\t\t{\t{ 54,  42,  53, -42,  85, -72}, { 45,-170,  94, -36,  48,  73},\n\t\t\t{-39,  65,-112, -16, -78, -72}, {  6, -11,  -6,  62,  49,   8} },\n\t\t{ \t{-57,  49, -23,   52, -135,  66},{-23, 127, -58,   -5, -118,  64},\n\t\t\t{ 87, -16,  121,  23,  -41, -12},{-19,  29,   35,-148,  -11,  45} },\n\t\t{\t{-55, -147, -146, -31,  55,  60},{-88,  -45,  -28,  46, -26,-144},\n\t\t\t{-12, -107,  -34, 150, 249,  66},{ 11,  -15,  -34,  27, -78, -50} },\n\t\t{\t{ 56,  67, 108,   4,  2,-48},{ 58,  67,  89,  32, 32, -8},\n\t\t\t{-42, -31,-103, -30,-23, -8},{  6,   4, -26, -10, 26, 12}\n\t\t}\n\t};\n\tint gx = 4, gy = 4, gz = 6;\n\n\tdouble h2[gx - fx + 1][gy - fy + 1][gz - fz + 1];\n\tdeconv3(g, gx, gy, gz, f, fx, fy, fz, h2);\n\tprintf(\"deconv3(g, f):\\n\");\n\tfor (int i = 0; i < gx - fx + 1; i++) {\n\t\tfor (int j = 0; j < gy - fy + 1; j++) {\n\t\t\tfor (int k = 0; k < gz - fz + 1; k++)\n\t\t\t\tprintf(\"%g \", h2[i][j][k]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tif (i < gx - fx) printf(\"\\n\");\n\t}\n\n\tdouble f2[gx - hx + 1][gy - hy + 1][gz - hz + 1];\n\tdeconv3(g, gx, gy, gz, h, hx, hy, hz, f2);\n\tprintf(\"\\ndeconv3(g, h):\\n\");\n\tfor (int i = 0; i < gx - hx + 1; i++) {\n\t\tfor (int j = 0; j < gy - hy + 1; j++) {\n\t\t\tfor (int k = 0; k < gz - hz + 1; k++)\n\t\t\t\tprintf(\"%g \", f2[i][j][k]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tif (i < gx - hx) printf(\"\\n\");\n\t}\n}\n\n\n\n"}
{"id": 55625, "name": "Dice game probabilities", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n"}
{"id": 55626, "name": "Zebra puzzle", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n", "C": "#include <stdio.h>\n#include <string.h>\n\nenum HouseStatus { Invalid, Underfull, Valid };\n\nenum Attrib { C, M, D, A, S };\n\n\nenum Colors { Red, Green, White, Yellow, Blue };\nenum Mans { English, Swede, Dane, German, Norwegian };\nenum Drinks { Tea, Coffee, Milk, Beer, Water };\nenum Animals { Dog, Birds, Cats, Horse, Zebra };\nenum Smokes { PallMall, Dunhill, Blend, BlueMaster, Prince };\n\n\nvoid printHouses(int ha[5][5]) {\n    const char *color[] =  { \"Red\", \"Green\", \"White\", \"Yellow\", \"Blue\" };\n    const char *man[] =    { \"English\", \"Swede\", \"Dane\", \"German\", \"Norwegian\" };\n    const char *drink[] =  { \"Tea\", \"Coffee\", \"Milk\", \"Beer\", \"Water\" };\n    const char *animal[] = { \"Dog\", \"Birds\", \"Cats\", \"Horse\", \"Zebra\" };\n    const char *smoke[] =  { \"PallMall\", \"Dunhill\", \"Blend\", \"BlueMaster\", \"Prince\" };\n\n    printf(\"%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s\\n\",\n           \"House\", \"Color\", \"Man\", \"Drink\", \"Animal\", \"Smoke\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        if (ha[i][C] >= 0)\n            printf(\"%-10.10s\", color[ha[i][C]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][M] >= 0)\n            printf(\"%-10.10s\", man[ha[i][M]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][D] >= 0)\n            printf(\"%-10.10s\", drink[ha[i][D]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][A] >= 0)\n            printf(\"%-10.10s\", animal[ha[i][A]]);\n        else\n            printf(\"%-10.10s\", \"-\");\n        if (ha[i][S] >= 0)\n            printf(\"%-10.10s\\n\", smoke[ha[i][S]]);\n        else\n            printf(\"-\\n\");\n    }\n}\n\n\nint checkHouses(int ha[5][5]) {\n    int c_add = 0, c_or = 0;\n    int m_add = 0, m_or = 0;\n    int d_add = 0, d_or = 0;\n    int a_add = 0, a_or = 0;\n    int s_add = 0, s_or = 0;\n\n    \n    if (ha[2][D] >= 0 && ha[2][D] != Milk)\n        return Invalid;\n\n    \n    if (ha[0][M] >= 0 && ha[0][M] != Norwegian)\n        return Invalid;\n\n    for (int i = 0; i < 5; i++) {\n        \n        if (ha[i][C] >= 0) {\n            c_add += (1 << ha[i][C]);\n            c_or |= (1 << ha[i][C]);\n        }\n        if (ha[i][M] >= 0) {\n            m_add += (1 << ha[i][M]);\n            m_or |= (1 << ha[i][M]);\n        }\n        if (ha[i][D] >= 0) {\n            d_add += (1 << ha[i][D]);\n            d_or |= (1 << ha[i][D]);\n        }\n        if (ha[i][A] >= 0) {\n            a_add += (1 << ha[i][A]);\n            a_or |= (1 << ha[i][A]);\n        }\n        if (ha[i][S] >= 0) {\n            s_add += (1 << ha[i][S]);\n            s_or |= (1 << ha[i][S]);\n        }\n\n        \n        if ((ha[i][M] >= 0 && ha[i][C] >= 0) &&\n            ((ha[i][M] == English && ha[i][C] != Red) || \n             (ha[i][M] != English && ha[i][C] == Red)))  \n            return Invalid;\n\n        \n        if ((ha[i][M] >= 0 && ha[i][A] >= 0) &&\n            ((ha[i][M] == Swede && ha[i][A] != Dog) ||\n             (ha[i][M] != Swede && ha[i][A] == Dog)))\n            return Invalid;\n\n        \n        if ((ha[i][M] >= 0 && ha[i][D] >= 0) &&\n            ((ha[i][M] == Dane && ha[i][D] != Tea) ||\n             (ha[i][M] != Dane && ha[i][D] == Tea)))\n            return Invalid;\n\n        \n        if ((i > 0 && ha[i][C] >= 0  ) &&\n            ((ha[i - 1][C] == Green && ha[i][C] != White) ||\n             (ha[i - 1][C] != Green && ha[i][C] == White)))\n            return Invalid;\n\n        \n        if ((ha[i][C] >= 0 && ha[i][D] >= 0) &&\n            ((ha[i][C] == Green && ha[i][D] != Coffee) ||\n             (ha[i][C] != Green && ha[i][D] == Coffee)))\n            return Invalid;\n\n        \n        if ((ha[i][S] >= 0 && ha[i][A] >= 0) &&\n            ((ha[i][S] == PallMall && ha[i][A] != Birds) ||\n             (ha[i][S] != PallMall && ha[i][A] == Birds)))\n            return Invalid;\n\n        \n        if ((ha[i][S] >= 0 && ha[i][C] >= 0) &&\n            ((ha[i][S] == Dunhill && ha[i][C] != Yellow) ||\n             (ha[i][S] != Dunhill && ha[i][C] == Yellow)))\n            return Invalid;\n\n        \n        if (ha[i][S] == Blend) {\n            if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats)\n                return Invalid;\n            else if (i == 4 && ha[i - 1][A] != Cats)\n                return Invalid;\n            else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats && ha[i - 1][A] != Cats)\n                return Invalid;\n        }\n\n        \n        if (ha[i][S] == Dunhill) {\n            if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse)\n                return Invalid;\n            else if (i == 4 && ha[i - 1][A] != Horse)\n                return Invalid;\n            else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse && ha[i - 1][A] != Horse)\n                return Invalid;\n        }\n\n        \n        if ((ha[i][S] >= 0 && ha[i][D] >= 0) &&\n            ((ha[i][S] == BlueMaster && ha[i][D] != Beer) ||\n             (ha[i][S] != BlueMaster && ha[i][D] == Beer)))\n            return Invalid;\n\n        \n        if ((ha[i][M] >= 0 && ha[i][S] >= 0) &&\n            ((ha[i][M] == German && ha[i][S] != Prince) ||\n             (ha[i][M] != German && ha[i][S] == Prince)))\n            return Invalid;\n\n        \n        if (ha[i][M] == Norwegian &&\n            ((i < 4 && ha[i + 1][C] >= 0 && ha[i + 1][C] != Blue) ||\n             (i > 0 && ha[i - 1][C] != Blue)))\n            return Invalid;\n\n        \n        if (ha[i][S] == Blend) {\n            if (i == 0 && ha[i + 1][D] >= 0 && ha[i + 1][D] != Water)\n                return Invalid;\n            else if (i == 4 && ha[i - 1][D] != Water)\n                return Invalid;\n            else if (ha[i + 1][D] >= 0 && ha[i + 1][D] != Water && ha[i - 1][D] != Water)\n                return Invalid;\n        }\n\n    }\n\n    if ((c_add != c_or) || (m_add != m_or) || (d_add != d_or)\n        || (a_add != a_or) || (s_add != s_or)) {\n        return Invalid;\n    }\n\n    if ((c_add != 0b11111) || (m_add != 0b11111) || (d_add != 0b11111)\n        || (a_add != 0b11111) || (s_add != 0b11111)) {\n        return Underfull;\n    }\n\n    return Valid;\n}\n\n\nint bruteFill(int ha[5][5], int hno, int attr) {\n    int stat = checkHouses(ha);\n    if ((stat == Valid) || (stat == Invalid))\n        return stat;\n\n    int hb[5][5];\n    memcpy(hb, ha, sizeof(int) * 5 * 5);\n    for (int i = 0; i < 5; i++) {\n        hb[hno][attr] = i;\n        stat = checkHouses(hb);\n        if (stat != Invalid) {\n            int nexthno, nextattr;\n            if (attr < 4) {\n                nextattr = attr + 1;\n                nexthno = hno;\n            } else {\n                nextattr = 0;\n                nexthno = hno + 1;\n            }\n\n            stat = bruteFill(hb, nexthno, nextattr);\n            if (stat != Invalid) {\n                memcpy(ha, hb, sizeof(int) * 5 * 5);\n                return stat;\n            }\n        }\n    }\n\n    \n    return Invalid;\n}\n\n\nint main() {\n    int ha[5][5] = {{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},\n                    {-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1},\n                    {-1, -1, -1, -1, -1}};\n\n    bruteFill(ha, 0, 0);\n    printHouses(ha);\n\n    return 0;\n}\n"}
{"id": 55627, "name": "Rosetta Code_Find unimplemented tasks", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55628, "name": "Rosetta Code_Find unimplemented tasks", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55629, "name": "Plasma effect", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n"}
{"id": 55630, "name": "Plasma effect", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n"}
{"id": 55631, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "C": "int j;\n"}
{"id": 55632, "name": "Wordle comparison", "Python": "\n\nfrom functools import reduce\nfrom operator import add\n\n\n\ndef wordleScore(target, guess):\n    \n    return mapAccumL(amber)(\n        *first(charCounts)(\n            mapAccumL(green)(\n                [], zip(target, guess)\n            )\n        )\n    )[1]\n\n\n\ndef green(residue, tg):\n    \n    t, g = tg\n    return (residue, (g, 2)) if t == g else (\n        [t] + residue, (g, 0)\n    )\n\n\n\ndef amber(tally, cn):\n    \n    c, n = cn\n    return (tally, 2) if 2 == n else (\n        adjust(\n            lambda x: x - 1,\n            c, tally\n        ),\n        1\n    ) if 0 < tally.get(c, 0) else (tally, 0)\n\n\n\n\ndef main():\n    \n    print(' -> '.join(['Target', 'Guess', 'Scores']))\n    print()\n    print(\n        '\\n'.join([\n            wordleReport(*tg) for tg in [\n                (\"ALLOW\", \"LOLLY\"),\n                (\"CHANT\", \"LATTE\"),\n                (\"ROBIN\", \"ALERT\"),\n                (\"ROBIN\", \"SONIC\"),\n                (\"ROBIN\", \"ROBIN\"),\n                (\"BULLY\", \"LOLLY\"),\n                (\"ADAPT\", \"SÅLÅD\"),\n                (\"Ukraine\", \"Ukraíne\"),\n                (\"BBAAB\", \"BBBBBAA\"),\n                (\"BBAABBB\", \"AABBBAA\")\n            ]\n        ])\n    )\n\n\n\ndef wordleReport(target, guess):\n    \n    scoreName = {2: 'green', 1: 'amber', 0: 'gray'}\n\n    if 5 != len(target):\n        return f'{target}: Expected 5 character target.'\n    elif 5 != len(guess):\n        return f'{guess}: Expected 5 character guess.'\n    else:\n        scores = wordleScore(target, guess)\n        return ' -> '.join([\n            target, guess, repr(scores),\n            ' '.join([\n                scoreName[n] for n in scores\n            ])\n        ])\n\n\n\n\n\ndef adjust(f, k, dct):\n    \n    return dict(\n        dct,\n        **{k: f(dct[k]) if k in dct else None}\n    )\n\n\n\ndef charCounts(s):\n    \n    return reduce(\n        lambda a, c: insertWith(add)(c)(1)(a),\n        list(s),\n        {}\n    )\n\n\n\ndef first(f):\n    \n    return lambda xy: (f(xy[0]), xy[1])\n\n\n\n\ndef insertWith(f):\n    \n    return lambda k: lambda x: lambda dct: dict(\n        dct,\n        **{k: f(dct[k], x) if k in dct else x}\n    )\n\n\n\n\ndef mapAccumL(f):\n    \n    def nxt(a, x):\n        return second(lambda v: a[1] + [v])(\n            f(a[0], x)\n        )\n    return lambda acc, xs: reduce(\n        nxt, xs, (acc, [])\n    )\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid wordle(const char *answer, const char *guess, int *result) {\n    int i, ix, n = strlen(guess);\n    char *ptr;\n    if (n != strlen(answer)) {\n        printf(\"The words must be of the same length.\\n\");\n        exit(1);\n    }\n    char answer2[n+1];\n    strcpy(answer2, answer);\n    for (i = 0; i < n; ++i) {\n        if (guess[i] == answer2[i]) {\n            answer2[i] = '\\v';\n            result[i] = 2;\n        }\n    }\n    for (i = 0; i < n; ++i) {\n        if ((ptr = strchr(answer2, guess[i])) != NULL) {\n            ix = ptr - answer2;\n            answer2[ix] = '\\v';\n            result[i] = 1;\n        }\n    }\n}\n\nint main() {\n    int i, j;\n    const char *answer, *guess;\n    int res[5];\n    const char *res2[5];\n    const char *colors[3] = {\"grey\", \"yellow\", \"green\"};\n    const char *pairs[5][2] = {\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"}\n    };\n    for (i = 0; i < 5; ++i) {\n        answer = pairs[i][0];\n        guess  = pairs[i][1];\n        for (j = 0; j < 5; ++j) res[j] = 0;\n        wordle(answer, guess, res);\n        for (j = 0; j < 5; ++j) res2[j] = colors[res[j]];\n        printf(\"%s v %s => { \", answer, guess);\n        for (j = 0; j < 5; ++j) printf(\"%d \", res[j]);\n        printf(\"} => { \");\n        for (j = 0; j < 5; ++j) printf(\"%s \", res2[j]);\n        printf(\"}\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55633, "name": "Color quantization", "Python": "from PIL import Image\n\nif __name__==\"__main__\":\n\tim = Image.open(\"frog.png\")\n\tim2 = im.quantize(16)\n\tim2.show()\n", "C": "typedef struct oct_node_t oct_node_t, *oct_node;\nstruct oct_node_t{\n\t\n\tuint64_t r, g, b;\n\tint count, heap_idx;\n\toct_node kids[8], parent;\n\tunsigned char n_kids, kid_idx, flags, depth;\n};\n\n\ninline int cmp_node(oct_node a, oct_node b)\n{\n\tif (a->n_kids < b->n_kids) return -1;\n\tif (a->n_kids > b->n_kids) return 1;\n\n\tint ac = a->count * (1 + a->kid_idx) >> a->depth;\n\tint bc = b->count * (1 + b->kid_idx) >> b->depth;\n\treturn ac < bc ? -1 : ac > bc;\n}\n\n\noct_node node_insert(oct_node root, unsigned char *pix)\n{\n#\tdefine OCT_DEPTH 8\n\t\n\n\tunsigned char i, bit, depth = 0;\n\tfor (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i])\n\t\t\troot->kids[i] = node_new(i, depth, root);\n\n\t\troot = root->kids[i];\n\t}\n\n\troot->r += pix[0];\n\troot->g += pix[1];\n\troot->b += pix[2];\n\troot->count++;\n\treturn root;\n}\n\n\noct_node node_fold(oct_node p)\n{\n\tif (p->n_kids) abort();\n\toct_node q = p->parent;\n\tq->count += p->count;\n\n\tq->r += p->r;\n\tq->g += p->g;\n\tq->b += p->b;\n\tq->n_kids --;\n\tq->kids[p->kid_idx] = 0;\n\treturn q;\n}\n\n\nvoid color_replace(oct_node root, unsigned char *pix)\n{\n\tunsigned char i, bit;\n\n\tfor (bit = 1 << 7; bit; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i]) break;\n\t\troot = root->kids[i];\n\t}\n\n\tpix[0] = root->r;\n\tpix[1] = root->g;\n\tpix[2] = root->b;\n}\n\n\nvoid color_quant(image im, int n_colors)\n{\n\tint i;\n\tunsigned char *pix = im->pix;\n\tnode_heap heap = { 0, 0, 0 };\n\n\toct_node root = node_new(0, 0, 0), got;\n\tfor (i = 0; i < im->w * im->h; i++, pix += 3)\n\t\theap_add(&heap, node_insert(root, pix));\n\n\twhile (heap.n > n_colors + 1)\n\t\theap_add(&heap, node_fold(pop_heap(&heap)));\n\n\tdouble c;\n\tfor (i = 1; i < heap.n; i++) {\n\t\tgot = heap.buf[i];\n\t\tc = got->count;\n\t\tgot->r = got->r / c + .5;\n\t\tgot->g = got->g / c + .5;\n\t\tgot->b = got->b / c + .5;\n\t\tprintf(\"%2d | %3llu %3llu %3llu (%d pixels)\\n\",\n\t\t\ti, got->r, got->g, got->b, got->count);\n\t}\n\n\tfor (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)\n\t\tcolor_replace(root, pix);\n\n\tnode_free();\n\tfree(heap.buf);\n}\n"}
{"id": 55634, "name": "Function frequency", "Python": "import ast\n\nclass CallCountingVisitor(ast.NodeVisitor):\n\n    def __init__(self):\n        self.calls = {}\n\n    def visit_Call(self, node):\n        if isinstance(node.func, ast.Name):\n            fun_name = node.func.id\n            call_count = self.calls.get(fun_name, 0)\n            self.calls[fun_name] = call_count + 1\n        self.generic_visit(node)\n\nfilename = input('Enter a filename to parse: ')\nwith open(filename, encoding='utf-8') as f:\n    contents = f.read()\nroot = ast.parse(contents, filename=filename) \nvisitor = CallCountingVisitor()\nvisitor.visit(root)\ntop10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10]\nfor name, count in top10:\n    print(name,'called',count,'times')\n", "C": "#define _POSIX_SOURCE\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <stddef.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\nstruct functionInfo {\n    char* name;\n    int timesCalled;\n    char marked;\n};\nvoid addToList(struct functionInfo** list, struct functionInfo toAdd, \\\n               size_t* numElements, size_t* allocatedSize)\n{\n    static const char* keywords[32] = {\"auto\", \"break\", \"case\", \"char\", \"const\", \\\n                                       \"continue\", \"default\", \"do\", \"double\", \\\n                                       \"else\", \"enum\", \"extern\", \"float\", \"for\", \\\n                                       \"goto\", \"if\", \"int\", \"long\", \"register\", \\\n                                       \"return\", \"short\", \"signed\", \"sizeof\", \\\n                                       \"static\", \"struct\", \"switch\", \"typedef\", \\\n                                       \"union\", \"unsigned\", \"void\", \"volatile\", \\\n                                       \"while\"\n                                      };\n    int i;\n    \n    for (i = 0; i < 32; i++) {\n        if (!strcmp(toAdd.name, keywords[i])) {\n            return;\n        }\n    }\n    if (!*list) {\n        *allocatedSize = 10;\n        *list = calloc(*allocatedSize, sizeof(struct functionInfo));\n        if (!*list) {\n            printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                   *allocatedSize, sizeof(struct functionInfo));\n            abort();\n        }\n        (*list)[0].name = malloc(strlen(toAdd.name)+1);\n        if (!(*list)[0].name) {\n            printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n            abort();\n        }\n        strcpy((*list)[0].name, toAdd.name);\n        (*list)[0].timesCalled = 1;\n        (*list)[0].marked = 0;\n        *numElements = 1;\n    } else {\n        char found = 0;\n        unsigned int i;\n        for (i = 0; i < *numElements; i++) {\n            if (!strcmp((*list)[i].name, toAdd.name)) {\n                found = 1;\n                (*list)[i].timesCalled++;\n                break;\n            }\n        }\n        if (!found) {\n            struct functionInfo* newList = calloc((*allocatedSize)+10, \\\n                                                  sizeof(struct functionInfo));\n            if (!newList) {\n                printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                       (*allocatedSize)+10, sizeof(struct functionInfo));\n                abort();\n            }\n            memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo));\n            free(*list);\n            *allocatedSize += 10;\n            *list = newList;\n            (*list)[*numElements].name = malloc(strlen(toAdd.name)+1);\n            if (!(*list)[*numElements].name) {\n                printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n                abort();\n            }\n            strcpy((*list)[*numElements].name, toAdd.name);\n            (*list)[*numElements].timesCalled = 1;\n            (*list)[*numElements].marked = 0;\n            (*numElements)++;\n        }\n    }\n}\nvoid printList(struct functionInfo** list, size_t numElements)\n{\n    char maxSet = 0;\n    unsigned int i;\n    size_t maxIndex = 0;\n    for (i = 0; i<10; i++) {\n        maxSet = 0;\n        size_t j;\n        for (j = 0; j<numElements; j++) {\n            if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) {\n                if (!(*list)[j].marked) {\n                    maxSet = 1;\n                    maxIndex = j;\n                }\n            }\n        }\n        (*list)[maxIndex].marked = 1;\n        printf(\"%s() called %d times.\\n\", (*list)[maxIndex].name, \\\n               (*list)[maxIndex].timesCalled);\n    }\n}\nvoid freeList(struct functionInfo** list, size_t numElements)\n{\n    size_t i;\n    for (i = 0; i<numElements; i++) {\n        free((*list)[i].name);\n    }\n    free(*list);\n}\nchar* extractFunctionName(char* readHead)\n{\n    char* identifier = readHead;\n    if (isalpha(*identifier) || *identifier == '_') {\n        while (isalnum(*identifier) || *identifier == '_') {\n            identifier++;\n        }\n    }\n    \n    char* toParen = identifier;\n    if (toParen == readHead) return NULL;\n    while (isspace(*toParen)) {\n        toParen++;\n    }\n    if (*toParen != '(') return NULL;\n    \n    ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \\\n                     - ((ptrdiff_t)readHead)+1;\n    char* const name = malloc(size);\n    if (!name) {\n        printf(\"Failed to allocate %lu bytes.\\n\", size);\n        abort();\n    }\n    name[size-1] = '\\0';\n    memcpy(name, readHead, size-1);\n    \n    if (strcmp(name, \"\")) {\n        return name;\n    }\n    free(name);\n    return NULL;\n}\nint main(int argc, char** argv)\n{\n    int i;\n    for (i = 1; i<argc; i++) {\n        errno = 0;\n        FILE* file = fopen(argv[i], \"r\");\n        if (errno || !file) {\n            printf(\"fopen() failed with error code \\\"%s\\\"\\n\", \\\n                   strerror(errno));\n            abort();\n        }\n        char comment = 0;\n#define DOUBLEQUOTE 1\n#define SINGLEQUOTE 2\n        int string = 0;\n        struct functionInfo* functions = NULL;\n        struct functionInfo toAdd;\n        size_t numElements = 0;\n        size_t allocatedSize = 0;\n        struct stat metaData;\n        errno = 0;\n        if (fstat(fileno(file), &metaData) < 0) {\n            printf(\"fstat() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \\\n                                          MAP_PRIVATE, fileno(file), 0);\n        if (errno) {\n            printf(\"mmap() failed with error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        if (!mmappedSource) {\n            printf(\"mmap() returned NULL.\\n\");\n            abort();\n        }\n        char* readHead = mmappedSource;\n        while (readHead < mmappedSource + metaData.st_size) {\n            while (*readHead) {\n                \n                if (!string) {\n                    if (*readHead == '/' && !strncmp(readHead, \"\", 2)) {\n                        comment = 0;\n                    }\n                }\n                \n                if (!comment) {\n                    if (*readHead == '\"') {\n                        if (!string) {\n                            string = DOUBLEQUOTE;\n                        } else if (string == DOUBLEQUOTE) {\n                            \n                            if (strncmp((readHead-1), \"\\\\\\\"\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                    if (*readHead == '\\'') {\n                        if (!string) {\n                            string = SINGLEQUOTE;\n                        } else if (string == SINGLEQUOTE) {\n                            if (strncmp((readHead-1), \"\\\\\\'\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                }\n                \n                if (!comment && !string) {\n                    char* name = extractFunctionName(readHead);\n                    \n                    if (name) {\n                        toAdd.name = name;\n                        addToList(&functions, toAdd, &numElements, &allocatedSize);\n                        readHead += strlen(name);\n                    }\n                    free(name);\n                }\n                readHead++;\n            }\n        }\n        errno = 0;\n        munmap(mmappedSource, metaData.st_size);\n        if (errno) {\n            printf(\"munmap() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        errno = 0;\n        fclose(file);\n        if (errno) {\n            printf(\"fclose() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        printList(&functions, numElements);\n        freeList(&functions, numElements);\n    }\n    return 0;\n}\n"}
{"id": 55635, "name": "Unicode strings", "Python": "\n\n\nu = 'abcdé'\nprint(ord(u[-1]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n"}
{"id": 55636, "name": "Unicode strings", "Python": "\n\n\nu = 'abcdé'\nprint(ord(u[-1]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n"}
{"id": 55637, "name": "Bitmap_Read an image through a pipe", "Python": "\n\nfrom PIL import Image\n\n\n\nim = Image.open(\"boxes_1.jpg\")\nim.save(\"boxes_1v2.ppm\")\n", "C": "image read_image(const char *name);\n"}
{"id": 55638, "name": "Memory layout of a data structure", "Python": "from ctypes import Structure, c_int\n\nrs232_9pin  = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg\"\n                \"_11 SCD SCS STD TC  SRD RC\"\n                \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]\n", "C": "struct RS232_data\n{\n  unsigned carrier_detect        : 1;\n  unsigned received_data         : 1;\n  unsigned transmitted_data      : 1;\n  unsigned data_terminal_ready   : 1;\n  unsigned signal_ground         : 1;\n  unsigned data_set_ready        : 1;\n  unsigned request_to_send       : 1;\n  unsigned clear_to_send         : 1;\n  unsigned ring_indicator        : 1;\n};\n"}
{"id": 55639, "name": "Sum of two adjacent numbers are primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == \"__main__\":\n    n = 0\n    num = 0\n\n    print('The first 20 pairs of numbers whose sum is prime:') \n    while True:\n        n += 1\n        suma = 2*n+1\n        if isPrime(suma):\n            num += 1\n            if num < 21:\n                print('{:2}'.format(n), \"+\", '{:2}'.format(n+1), \"=\", '{:2}'.format(suma))\n            else:\n                break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nvoid primeSieve(int *c, int limit, bool processEven, bool primesOnly) {\n    int i, ix, p, p2;\n    limit++;\n    c[0] = TRUE;\n    c[1] = TRUE;\n    if (processEven) {\n        for (i = 4; i < limit; i +=2) c[i] = TRUE;\n    }\n    p = 3;\n    while (TRUE) {\n        p2 = p * p;\n        if (p2 >= limit) break;\n        for (i = p2; i < limit; i += 2*p) c[i] = TRUE;\n        while (TRUE) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    if (primesOnly) {\n        \n        c[0] = 2;\n        for (i = 3, ix = 1; i < limit; i += 2) {\n            if (!c[i]) c[ix++] = i;\n        }\n    }\n}\n\nint main() {\n    int i, p, hp, n = 10000000;\n    int limit = (int)(log(n) * (double)n * 1.2);  \n    int *primes = (int *)calloc(limit, sizeof(int));\n    primeSieve(primes, limit-1, FALSE, TRUE);\n    printf(\"The first 20 pairs of natural numbers whose sum is prime are:\\n\");\n    for (i = 1; i <= 20; ++i) {\n        p = primes[i];\n        hp = p / 2;\n        printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    }\n    printf(\"\\nThe 10 millionth such pair is:\\n\");\n    p = primes[n];\n    hp = p / 2;\n    printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    free(primes);\n    return 0;\n}\n"}
{"id": 55640, "name": "Sum of two adjacent numbers are primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == \"__main__\":\n    n = 0\n    num = 0\n\n    print('The first 20 pairs of numbers whose sum is prime:') \n    while True:\n        n += 1\n        suma = 2*n+1\n        if isPrime(suma):\n            num += 1\n            if num < 21:\n                print('{:2}'.format(n), \"+\", '{:2}'.format(n+1), \"=\", '{:2}'.format(suma))\n            else:\n                break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nvoid primeSieve(int *c, int limit, bool processEven, bool primesOnly) {\n    int i, ix, p, p2;\n    limit++;\n    c[0] = TRUE;\n    c[1] = TRUE;\n    if (processEven) {\n        for (i = 4; i < limit; i +=2) c[i] = TRUE;\n    }\n    p = 3;\n    while (TRUE) {\n        p2 = p * p;\n        if (p2 >= limit) break;\n        for (i = p2; i < limit; i += 2*p) c[i] = TRUE;\n        while (TRUE) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    if (primesOnly) {\n        \n        c[0] = 2;\n        for (i = 3, ix = 1; i < limit; i += 2) {\n            if (!c[i]) c[ix++] = i;\n        }\n    }\n}\n\nint main() {\n    int i, p, hp, n = 10000000;\n    int limit = (int)(log(n) * (double)n * 1.2);  \n    int *primes = (int *)calloc(limit, sizeof(int));\n    primeSieve(primes, limit-1, FALSE, TRUE);\n    printf(\"The first 20 pairs of natural numbers whose sum is prime are:\\n\");\n    for (i = 1; i <= 20; ++i) {\n        p = primes[i];\n        hp = p / 2;\n        printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    }\n    printf(\"\\nThe 10 millionth such pair is:\\n\");\n    p = primes[n];\n    hp = p / 2;\n    printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    free(primes);\n    return 0;\n}\n"}
{"id": 55641, "name": "Periodic table", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n", "C": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\n\nGD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );\nint select_box_chemical_elem( RDS(MT_CELL, Elements) );\nvoid put_information(RDS( MT_CELL, elem), int i);\n\nMain\n   \n   GD_VIDEO table;\n   \n   Resize_terminal(42,135);\n   Init_video( &table );\n   \n   Gpm_Connect conn;\n\n   if ( ! Init_mouse(&conn)){\n        Msg_red(\"No se puede conectar al servidor del ratón\\n\");\n        Stop(1);\n   }  \n   Enable_raw_mode();\n   Hide_cursor;\n\n   \n   New multitype Elements;\n   Elements = load_chem_elements( pSDS(Elements) );\n   Throw( load_fail );\n   \n  \n   New objects Btn_exit;\n   Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, \"  Terminar  \", 6,44, 15, 0);\n\n  \n   table = put_chemical_cell( table, SDS(Elements) );\n\n  \n   Refresh(table);\n   Put object Btn_exit;\n  \n  \n   int c;\n   Waiting_some_clic(c)\n   {\n       if( select_box_chemical_elem(SDS(Elements)) ){\n           Waiting_some_clic(c) break;\n       }\n       if (Object_mouse( Btn_exit)) break;\n       \n       Refresh(table);\n       Put object Btn_exit;\n   }\n\n   Free object Btn_exit;\n   Free multitype Elements;\n   \n   Exception( load_fail ){\n      Msg_red(\"No es un archivo matriciable\");\n   }\n\n   Free video table;\n   Disable_raw_mode();\n   Close_mouse();\n   Show_cursor;\n   \n   At SIZE_TERM_ROWS,0;\n   Prnl;\nEnd\n\nvoid put_information(RDS(MT_CELL, elem), int i)\n{\n    At 2,19;\n    Box_solid(11,64,67,17);\n    Color(15,17);\n    At 4,22; Print \"Elemento (%s) = %s\", (char*)$s-elem[i,5],(char*)$s-elem[i,6];\n    if (Cell_type(elem,i,7) == double_TYPE ){\n        At 5,22; Print \"Peso atómico  = %f\", $d-elem[i,7];\n    }else{\n        At 5,22; Print \"Peso atómico  = (%ld)\", $l-elem[i,7];\n    }\n    At 6,22; Print \"Posición      = (%ld, %ld)\",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;\n    At 8,22; Print \"1ª energía de\";\n    if (Cell_type(elem,i,12) == double_TYPE ){\n        At 9,22; Print \"ionización (kJ/mol) = %.*f\",2,$d-elem[i,12];\n    }else{\n        At 9,22; Print \"ionización (kJ/mol) = ---\";\n    }\n    if (Cell_type(elem,i,13) == double_TYPE ){\n        At 10,22; Print \"Electronegatividad  = %.*f\",2,$d-elem[i,13];\n    }else{\n        At 10,22; Print \"Electronegatividad  = ---\";\n    }\n    At 4,56; Print \"Conf. electrónica:\";\n    At 5,56; Print \"       %s\", (char*)$s-elem[i,14];\n    At 7,56; Print \"Estados de oxidación:\";\n    if ( Cell_type(elem,i,15) == string_TYPE ){\n        At 8,56; Print \"       %s\", (char*)$s-elem[i,15];\n    }else{\n       \n        At 8,56; Print \"       %ld\", $l-elem[i,15];\n    }\n    At 10,56; Print \"Número Atómico: %ld\",$l-elem[i,4];\n    Reset_color;\n}\n\nint select_box_chemical_elem( RDS(MT_CELL, elem) )\n{\n   int i;\n   Iterator up i [0:1:Rows(elem)]{\n       if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){\n           Gotoxy( $l-elem[i,8], $l-elem[i,9] );\n           Color_fore( 15 ); Color_back( 0 );\n           Box( 4,5, DOUB_ALL );\n\n           Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print \"%ld\",$l-elem[i,4];\n           Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print \"%s\",(char*)$s-elem[i,5];\n           Flush_out;\n           Reset_color;\n           put_information(SDS(elem),i);\n           return 1;\n       }\n   }\n   return 0;\n}\n\nGD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)\n{\n   int i;\n   \n   \n   Iterator up i [0:1:Rows(elem)]{\n       long rx = 2+($l-elem[i,0]*4);\n       long cx = 3+($l-elem[i,1]*7);\n       long offr = rx+3;\n       long offc = cx+6;\n\n       Gotoxy(table, rx, cx);\n\n       Color_fore(table, $l-elem[i,2]);\n       Color_back(table,$l-elem[i,3]);\n\n       Box(table, 4,5, SING_ALL );\n\n       char Atnum[50], Elem[50];\n       sprintf(Atnum,\"\\x1b[3m%ld\\x1b[23m\",$l-elem[i,4]);\n       sprintf(Elem, \"\\x1b[1m%s\\x1b[22m\",(char*)$s-elem[i,5]);\n\n       Outvid(table,rx+1, cx+2, Atnum);\n       Outvid(table,rx+2, cx+2, Elem);\n\n       Reset_text(table);\n       \n       $l-elem[i,8] = rx;\n       $l-elem[i,9] = cx;\n       $l-elem[i,10] = offr;\n       $l-elem[i,11] = offc;\n       \n   }\n   \n   Iterator up i [ 1: 1: 19 ]{\n       Gotoxy(table, 31, 5+(i-1)*7);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Iterator up i [ 1: 1: 8 ]{\n       Gotoxy(table, 3+(i-1)*4, 130);\n       char num[5]; sprintf( num, \"%d\",i );\n       Outvid(table, num );\n   }\n   Outvid( table, 35,116, \"8\");\n   Outvid( table, 39,116, \"9\");\n   \n   \n   Color_fore(table, 15);\n   Color_back(table, 0);\n   Outvid(table,35,2,\"Lantánidos ->\");\n   Outvid(table,39,2,\"Actínidos  ->\");\n   Reset_text(table);\n   return table;\n}\n\nMT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )\n{\n   F_STAT dataFile = Stat_file(\"chem_table.txt\");\n   if( dataFile.is_matrix ){\n       \n       Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];\n       E = Load_matrix_mt( SDS(E), \"chem_table.txt\", dataFile, DET_LONG);\n   }else{\n       Is_ok=0;\n   }\n   return E;\n}\n"}
{"id": 55642, "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 <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": 55643, "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 <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": 55644, "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 <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": 55645, "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 <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": 55646, "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 <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": 55647, "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 <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": 55648, "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 <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": 55649, "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", "C": "\nif (strcmp(a,b)) action_on_equality();\n"}
{"id": 55650, "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": "#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": 55651, "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", "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": 55652, "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", "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": 55653, "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", "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": 55654, "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": "#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": 55655, "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": "#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": 55656, "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": "#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": 55657, "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", "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": 55658, "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", "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": 55659, "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", "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": 55660, "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", "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": 55661, "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": "#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": 55662, "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": "#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": 55663, "name": "Memory allocation", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \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": 55664, "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": "#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": 55665, "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": "#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": 55666, "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", "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": 55667, "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", "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": 55668, "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": "#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": 55669, "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", "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": 55670, "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": "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": 55671, "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", "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": 55672, "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": "#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": 55673, "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": "#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": 55674, "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", "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": 55675, "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", "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": 55676, "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": "#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": 55677, "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": "#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": 55678, "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", "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": 55679, "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", "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": 55680, "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", "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": 55681, "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", "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": 55682, "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", "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": 55683, "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", "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": 55684, "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", "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": 55685, "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", "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": 55686, "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", "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": 55687, "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", "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": 55688, "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", "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": 55689, "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", "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": 55690, "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", "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": 55691, "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", "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": 55692, "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", "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": 55693, "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", "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": 55694, "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", "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": 55695, "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", "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": 55696, "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", "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": 55697, "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", "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"}
{"id": 55698, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 55699, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 55700, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 55701, "name": "Read a specific line from a file", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 55702, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 55703, "name": "File extension is in extensions list", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 55704, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 55705, "name": "24 game_Solve", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 55706, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n"}
{"id": 55707, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55708, "name": "SHA-256 Merkle tree", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\n", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55709, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 55710, "name": "User input_Graphical", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n"}
{"id": 55711, "name": "Sierpinski arrowhead curve", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\n", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55712, "name": "Text processing_1", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n"}
{"id": 55713, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55714, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 55715, "name": "Aliquot sequence classifications", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 55716, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55717, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 55718, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55719, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 55720, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 55721, "name": "Pythagorean triples", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 55722, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 55723, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 55724, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55725, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 55726, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 55727, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 55728, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 55729, "name": "Fractran", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n"}
{"id": 55730, "name": "Sorting algorithms_Stooge sort", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n"}
{"id": 55731, "name": "Galton box animation", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\n"}
{"id": 55732, "name": "Sorting Algorithms_Circle Sort", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\n", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\n"}
{"id": 55733, "name": "Kronecker product based fractals", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n"}
{"id": 55734, "name": "Read a configuration file", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 55735, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 55736, "name": "Circular primes", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 55737, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 55738, "name": "Sorting algorithms_Radix sort", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n"}
{"id": 55739, "name": "List comprehensions", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 55740, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 55741, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 55742, "name": "Jacobi symbol", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 55743, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 55744, "name": "K-d tree", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 55745, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 55746, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n"}
{"id": 55747, "name": "Safe addition", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n"}
{"id": 55748, "name": "Case-sensitivity of identifiers", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n"}
{"id": 55749, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 55750, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 55751, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 55752, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 55753, "name": "Palindromic gapful numbers", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 55754, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 55755, "name": "Sierpinski triangle_Graphical", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 55756, "name": "Non-continuous subsequences", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55757, "name": "Fibonacci word_fractal", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\n"}
{"id": 55758, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 55759, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55760, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 55761, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 55762, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 55763, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 55764, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55765, "name": "Product of divisors", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55766, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 55767, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 55768, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 55769, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 55770, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 55771, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 55772, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 55773, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 55774, "name": "Carmichael 3 strong pseudoprimes", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n"}
{"id": 55775, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 55776, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 55777, "name": "Sorting algorithms_Bead sort", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 55778, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 55779, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 55780, "name": "Cistercian numerals", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 55781, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 55782, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\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 *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 55783, "name": "Draw a sphere", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\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 *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 55784, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 55785, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 55786, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 55787, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 55788, "name": "Fermat numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class FermatNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 Fermat numbers:\");\n        for ( int i = 0 ; i < 10 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, fermat(i));\n        }\n        System.out.printf(\"%nFirst 12 Fermat numbers factored:%n\");\n        for ( int i = 0 ; i < 13 ; i++ ) {\n            System.out.printf(\"F[%d] = %s\\n\", i, getString(getFactors(i, fermat(i))));\n        }\n    }\n    \n    private static String getString(List<BigInteger> factors) {\n        if ( factors.size() == 1 ) {\n            return factors.get(0) + \" (PRIME)\";\n        }\n        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith(\"-\") ? \"(C\" + v.replace(\"-\", \"\") + \")\" : v).collect(Collectors.joining(\" * \"));\n    }\n\n    private static Map<Integer, String> COMPOSITE = new HashMap<>();\n    static {\n        COMPOSITE.put(9, \"5529\");\n        COMPOSITE.put(10, \"6078\");\n        COMPOSITE.put(11, \"1037\");\n        COMPOSITE.put(12, \"5488\");\n        COMPOSITE.put(13, \"2884\");\n    }\n\n    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {\n        List<BigInteger> factors = new ArrayList<>();\n        BigInteger factor = BigInteger.ONE;\n        while ( true ) {\n            if ( n.isProbablePrime(100) ) {\n                factors.add(n);\n                break;\n            }\n            else {\n                if ( COMPOSITE.containsKey(fermatIndex) ) {\n                    String stop = COMPOSITE.get(fermatIndex);\n                    if ( n.toString().startsWith(stop) ) {\n                        factors.add(new BigInteger(\"-\" + n.toString().length()));\n                        break;\n                    }\n                }\n                factor = pollardRhoFast(n);\n                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {\n                    factors.add(n);\n                    break;\n                }\n                else {\n                    factors.add(factor);\n                    n = n.divide(factor);\n                }\n            }\n        }\n        return factors;\n    }\n    \n    private static final BigInteger TWO = BigInteger.valueOf(2);\n    \n    private static BigInteger fermat(int n) {\n        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);\n    }\n        \n    \n    @SuppressWarnings(\"unused\")\n    private static BigInteger pollardRho(BigInteger n) {\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        while ( d.compareTo(BigInteger.ONE) == 0 ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs().gcd(n);\n        }\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n    \n    \n    \n    \n    \n    \n    private static BigInteger pollardRhoFast(BigInteger n) {\n        long start = System.currentTimeMillis();\n        BigInteger x = BigInteger.valueOf(2);\n        BigInteger y = BigInteger.valueOf(2);\n        BigInteger d = BigInteger.ONE;\n        int count = 0;\n        BigInteger z = BigInteger.ONE;\n        while ( true ) {\n            x = pollardRhoG(x, n);\n            y = pollardRhoG(pollardRhoG(y, n), n);\n            d = x.subtract(y).abs();\n            z = z.multiply(d).mod(n);\n            count++;\n            if ( count == 100 ) {\n                d = z.gcd(n);\n                if ( d.compareTo(BigInteger.ONE) != 0 ) {\n                    break;\n                }\n                z = BigInteger.ONE;\n                count = 0;\n            }\n        }\n        long end = System.currentTimeMillis();\n        System.out.printf(\"    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n\", n, (end-start), d);\n        if ( d.compareTo(n) == 0 ) {\n            return BigInteger.ZERO;\n        }\n        return d;\n    }\n\n    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {\n        return x.multiply(x).add(BigInteger.ONE).mod(n);\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <gmp.h>\n\nvoid mpz_factors(mpz_t n) {\n  int factors = 0;\n  mpz_t s, m, p;\n  mpz_init(s), mpz_init(m), mpz_init(p);\n\n  mpz_set_ui(m, 3);\n  mpz_set(p, n);\n  mpz_sqrt(s, p);\n\n  while (mpz_cmp(m, s) < 0) {\n    if (mpz_divisible_p(p, m)) {\n      gmp_printf(\"%Zd \", m);\n      mpz_fdiv_q(p, p, m);\n      mpz_sqrt(s, p);\n      factors ++;\n    }\n    mpz_add_ui(m, m, 2);\n  }\n\n  if (factors == 0) printf(\"PRIME\\n\");\n  else gmp_printf(\"%Zd\\n\", p);\n}\n\nint main(int argc, char const *argv[]) {\n  mpz_t fermat;\n  mpz_init_set_ui(fermat, 3);\n  printf(\"F(0) = 3 -> PRIME\\n\");\n  for (unsigned i = 1; i < 10; i ++) {\n    mpz_sub_ui(fermat, fermat, 1);\n    mpz_mul(fermat, fermat, fermat);\n    mpz_add_ui(fermat, fermat, 1);\n    gmp_printf(\"F(%d) = %Zd -> \", i, fermat);\n    mpz_factors(fermat);\n  }\n\n  return 0;\n}\n"}
{"id": 55789, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 55790, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 55791, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 55792, "name": "Hello world_Line printer", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 55793, "name": "Water collected between towers", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55794, "name": "Square-free integers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 55795, "name": "Jaro similarity", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n"}
{"id": 55796, "name": "Sum and product puzzle", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n"}
{"id": 55797, "name": "Fairshare between two and more", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 55798, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55799, "name": "Prime triangle", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n"}
{"id": 55800, "name": "Trabb Pardo–Knuth algorithm", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n"}
{"id": 55801, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 55802, "name": "Sequence_ nth number with exactly n divisors", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55803, "name": "Sequence_ smallest number with exactly n divisors", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55804, "name": "Pancake numbers", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55805, "name": "Generate random chess position", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n"}
{"id": 55806, "name": "Esthetic numbers", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n"}
{"id": 55807, "name": "Topswops", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55808, "name": "Old Russian measure of length", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55809, "name": "Old Russian measure of length", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55810, "name": "Rate counter", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n"}
{"id": 55811, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 55812, "name": "Pythagoras tree", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n"}
{"id": 55813, "name": "Pythagoras tree", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n"}
{"id": 55814, "name": "Odd word problem", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 55815, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55816, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 55817, "name": "Colorful numbers", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 55818, "name": "Rosetta Code_Tasks without examples", "Java": "import java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\n\npublic class TasksWithoutExamples {\n    private static String readPage(HttpClient client, URI uri) throws IOException, InterruptedException {\n        var request = HttpRequest.newBuilder()\n            .GET()\n            .uri(uri)\n            .timeout(Duration.ofSeconds(5))\n            .setHeader(\"accept\", \"text/html\")\n            .build();\n\n        var response = client.send(request, HttpResponse.BodyHandlers.ofString());\n        return response.body();\n    }\n\n    private static void process(HttpClient client, String base, String task) {\n        try {\n            var re = Pattern.compile(\".*using any language you may know.</div>(.*?)<div id=\\\"toc\\\".*\", Pattern.DOTALL + Pattern.MULTILINE);\n            var re2 = Pattern.compile(\"</?[^>]*>\");\n\n            var page = base + task;\n            String body = readPage(client, new URI(page));\n\n            var matcher = re.matcher(body);\n            if (matcher.matches()) {\n                var group = matcher.group(1);\n                var m2 = re2.matcher(group);\n                var text = m2.replaceAll(\"\");\n                System.out.println(text);\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {\n        var re = Pattern.compile(\"<li><a href=\\\"/wiki/(.*?)\\\"\", Pattern.DOTALL + Pattern.MULTILINE);\n\n        var client = HttpClient.newBuilder()\n            .version(HttpClient.Version.HTTP_1_1)\n            .followRedirects(HttpClient.Redirect.NORMAL)\n            .connectTimeout(Duration.ofSeconds(5))\n            .build();\n\n        var uri = new URI(\"http\", \"rosettacode.org\", \"/wiki/Category:Programming_Tasks\", \"\");\n        var body = readPage(client, uri);\n        var matcher = re.matcher(body);\n\n        var tasks = new ArrayList<String>();\n        while (matcher.find()) {\n            tasks.add(matcher.group(1));\n        }\n\n        var base = \"http:\n        var limit = 3L;\n\n        tasks.stream().limit(limit).forEach(task -> process(client, base, task));\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_tasks_without_examples.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 55819, "name": "Sine wave", "Java": "import processing.sound.*;\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\nsine.freq(500);\nsine.play();\n\ndelay(5000);\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n\nint header[] = {46, 115, 110, 100, 0, 0, 0, 24,\n                255, 255, 255, 255, 0, 0, 0, 3,\n                0, 0, 172, 68, 0, 0, 0, 1};\n\nint main(int argc, char *argv[]){\n        float freq, dur;\n        long i, v;\n\n        if (argc < 3) {\n                printf(\"Usage:\\n\");\n                printf(\"  csine <frequency> <duration>\\n\");\n                exit(1);\n        }\n        freq = atof(argv[1]);\n        dur = atof(argv[2]);\n        for (i = 0; i < 24; i++)\n                putchar(header[i]);\n        for (i = 0; i < dur * 44100; i++) {\n                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));\n                v = v % 65536;\n                putchar(v >> 8);\n                putchar(v % 256);\n        }\n}\n"}
{"id": 55820, "name": "Compiler_code generator", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 55821, "name": "Compiler_code generator", "Java": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n    final static int WORDSIZE = 4;\n    \n    static byte[] code = {};\n    \n    static Map<String, NodeType> str_to_nodes = new HashMap<>();\n    static List<String> string_pool = new ArrayList<>();\n    static List<String> variables = new ArrayList<>();\n    static int string_count = 0;\n    static int var_count = 0;\n    \n    static Scanner s;\n    static NodeType[] unary_ops = {\n        NodeType.nd_Negate, NodeType.nd_Not\n    };\n    static NodeType[] operators = {\n        NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n        NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n        NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n    };\n \n    static enum Mnemonic {\n        NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n        JMP, JZ, PRTC, PRTS, PRTI, HALT\n    }\n    static class Node {\n        public NodeType nt;\n        public Node left, right;\n        public String value;\n\n        Node() {\n            this.nt = null;\n            this.left = null;\n            this.right = null;\n            this.value = null;\n        }\n        Node(NodeType node_type, Node left, Node right, String value) {\n            this.nt = node_type;\n            this.left = left;\n            this.right = right;\n            this.value = value;\n        }\n        public static Node make_node(NodeType nodetype, Node left, Node right) {\n            return new Node(nodetype, left, right, \"\");\n        }\n        public static Node make_node(NodeType nodetype, Node left) {\n            return new Node(nodetype, left, null, \"\");\n        }\n        public static Node make_leaf(NodeType nodetype, String value) {\n            return new Node(nodetype, null, null, value);\n        }\n    }\n    static enum NodeType {\n        nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n        nd_If(\"If\", Mnemonic.NONE),\n        nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n        nd_Assign(\"Assign\", Mnemonic.NONE),\n        nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n        nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n        nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n        nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n        private final String name;\n        private final Mnemonic m;\n\n        NodeType(String name, Mnemonic m) {\n            this.name = name;\n            this.m = m;\n        }\n        Mnemonic getMnemonic() { return this.m; }\n\n        @Override\n        public String toString() { return this.name; }\n    }\n    static void appendToCode(int b) {\n        code = Arrays.copyOf(code, code.length + 1);\n        code[code.length - 1] = (byte) b;\n    }\n    static void emit_byte(Mnemonic m) {\n        appendToCode(m.ordinal());\n    }\n    static void emit_word(int n) {\n        appendToCode(n >> 24);\n        appendToCode(n >> 16);\n        appendToCode(n >> 8);\n        appendToCode(n);\n    }\n    static void emit_word_at(int pos, int n) {\n        code[pos] = (byte) (n >> 24);\n        code[pos + 1] = (byte) (n >> 16);\n        code[pos + 2] = (byte) (n >> 8);\n        code[pos + 3] = (byte) n;\n    }\n    static int get_word(int pos) {\n        int result;\n        result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff)  << 16) + ((code[pos + 2] & 0xff)  << 8) + (code[pos + 3] & 0xff) ;\n        \n        return result;\n    }\n    static int fetch_var_offset(String name) {\n        int n;\n        n = variables.indexOf(name);\n        if (n == -1) {\n            variables.add(name);\n            n = var_count++;\n        }\n        return n;\n    }\n    static int fetch_string_offset(String str) {\n        int n;\n        n = string_pool.indexOf(str);\n        if (n == -1) {\n            string_pool.add(str);\n            n = string_count++;\n        }\n        return n;\n    }\n    static int hole() {\n        int t = code.length;\n        emit_word(0);\n        return t;\n    }\n    static boolean arrayContains(NodeType[] a, NodeType n) {\n        boolean result = false;\n        for (NodeType test: a) {\n            if (test.equals(n)) {\n                result = true;\n                break;\n            }\n        }\n        return result;\n    }\n    static void code_gen(Node x) throws Exception {\n        int n, p1, p2;\n        if (x == null) return;\n        \n        switch (x.nt) {\n            case nd_None: return;\n            case nd_Ident:\n                emit_byte(Mnemonic.FETCH);\n                n = fetch_var_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Integer:\n                emit_byte(Mnemonic.PUSH);\n                emit_word(Integer.parseInt(x.value));\n                break;\n            case nd_String:\n                emit_byte(Mnemonic.PUSH);\n                n = fetch_string_offset(x.value);\n                emit_word(n);\n                break;\n            case nd_Assign:\n                n = fetch_var_offset(x.left.value);\n                code_gen(x.right);\n                emit_byte(Mnemonic.STORE);\n                emit_word(n);\n                break;\n            case nd_If:\n                p2 = 0; \n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p1 = hole();\n                code_gen(x.right.left);\n                if (x.right.right != null) {\n                    emit_byte(Mnemonic.JMP);\n                    p2 = hole();\n                }\n                emit_word_at(p1, code.length - p1);\n                if (x.right.right != null) {\n                    code_gen(x.right.right);\n                    emit_word_at(p2, code.length - p2);\n                }\n                break;\n            case nd_While:\n                p1 = code.length;\n                code_gen(x.left);\n                emit_byte(Mnemonic.JZ);\n                p2 = hole();\n                code_gen(x.right);\n                emit_byte(Mnemonic.JMP);\n                emit_word(p1 - code.length);\n                emit_word_at(p2, code.length - p2);\n                break;\n            case nd_Sequence:\n                code_gen(x.left);\n                code_gen(x.right);\n                break;\n            case nd_Prtc:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTC);\n                break;\n            case nd_Prti:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTI);\n                break;\n            case nd_Prts:\n                code_gen(x.left);\n                emit_byte(Mnemonic.PRTS);\n                break;\n            default:\n                if (arrayContains(operators, x.nt)) {\n                    code_gen(x.left);\n                    code_gen(x.right);\n                    emit_byte(x.nt.getMnemonic());\n                } else if (arrayContains(unary_ops, x.nt)) {\n                    code_gen(x.left);\n                    emit_byte(x.nt.getMnemonic());\n                } else {\n                    throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n                }\n        }\n    }\n    static void list_code() throws Exception {\n        int pc = 0, x;\n        Mnemonic op;\n        System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n        for (String s: string_pool) {\n            System.out.println(s);\n        }\n        while (pc < code.length) {\n            System.out.printf(\"%4d \", pc);\n            op = Mnemonic.values()[code[pc++]];\n            switch (op) {\n                case FETCH:\n                    x = get_word(pc);\n                    System.out.printf(\"fetch [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case STORE:\n                    x = get_word(pc);\n                    System.out.printf(\"store [%d]\", x);\n                    pc += WORDSIZE;\n                    break;\n                case PUSH:\n                    x = get_word(pc);\n                    System.out.printf(\"push  %d\", x);\n                    pc += WORDSIZE;\n                    break;\n                case ADD: case SUB: case MUL: case DIV: case MOD:\n                case LT: case GT: case LE: case GE: case EQ: case NE:\n                case AND: case OR: case NEG: case NOT:\n                case PRTC: case PRTI: case PRTS: case HALT:\n                    System.out.print(op.toString().toLowerCase());\n                    break;\n                case JMP:\n                    x = get_word(pc);\n                    System.out.printf(\"jmp     (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                case JZ:\n                    x = get_word(pc);\n                    System.out.printf(\"jz      (%d) %d\", x, pc + x);\n                    pc += WORDSIZE;\n                    break;\n                default:\n                    throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n            }\n            System.out.println();\n        }\n    }\n    static Node load_ast() throws Exception {\n        String command, value;\n        String line;\n        Node left, right;\n\n        while (s.hasNext()) {\n            line = s.nextLine();\n            value = null;\n            if (line.length() > 16) {\n                command = line.substring(0, 15).trim();\n                value = line.substring(15).trim();\n            } else {\n                command = line.trim();\n            }\n            if (command.equals(\";\")) {\n                return null;\n            }\n            if (!str_to_nodes.containsKey(command)) {\n                throw new Exception(\"Command not found: '\" + command + \"'\");\n            }\n            if (value != null) {\n                return Node.make_leaf(str_to_nodes.get(command), value);\n            }\n            left = load_ast(); right = load_ast();\n            return Node.make_node(str_to_nodes.get(command), left, right);\n        }\n        return null; \n    }\n    public static void main(String[] args) {\n        Node n;\n\n        str_to_nodes.put(\";\", NodeType.nd_None);\n        str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n        str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n        str_to_nodes.put(\"String\", NodeType.nd_String);\n        str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n        str_to_nodes.put(\"If\", NodeType.nd_If);\n        str_to_nodes.put(\"While\", NodeType.nd_While);\n        str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n        str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n        str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n        str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n        str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n        str_to_nodes.put(\"Not\", NodeType.nd_Not);\n        str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n        str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n        str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n        str_to_nodes.put(\"Add\", NodeType.nd_Add);\n        str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n        str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n        str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n        str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n        str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n        str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n        str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n        str_to_nodes.put(\"And\", NodeType.nd_And);\n        str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n        if (args.length > 0) {\n            try {\n                s = new Scanner(new File(args[0]));\n                n = load_ast();\n                code_gen(n);\n                emit_byte(Mnemonic.HALT);\n                list_code();\n            } catch (Exception e) {\n                System.out.println(\"Ex: \"+e);\n            }\n        }\n    }\n}\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 55822, "name": "Stern-Brocot sequence", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 55823, "name": "Numeric error propagation", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n"}
{"id": 55824, "name": "Soundex", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55825, "name": "List rooted trees", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n"}
{"id": 55826, "name": "List rooted trees", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n"}
{"id": 55827, "name": "Documentation", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n"}
{"id": 55828, "name": "Problem of Apollonius", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n"}
{"id": 55829, "name": "Longest common suffix", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n"}
{"id": 55830, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n"}
{"id": 55831, "name": "Idiomatically determine all the lowercase and uppercase letters", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n  putchar('\\n');\n  for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n  putchar('\\n');\n  return 0;\n}\n"}
{"id": 55832, "name": "Sum of elements below main diagonal of matrix", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n"}
{"id": 55833, "name": "Sorting algorithms_Tree sort on a linked list", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n"}
{"id": 55834, "name": "Sorting algorithms_Tree sort on a linked list", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n"}
{"id": 55835, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 55836, "name": "Truncate a file", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 55837, "name": "Numerical integration_Adaptive Simpson's method", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n"}
{"id": 55838, "name": "Numerical integration_Adaptive Simpson's method", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n"}
{"id": 55839, "name": "FASTA format", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n"}
{"id": 55840, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55841, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55842, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55843, "name": "Window creation_X11", "Java": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n  public static void main(String[] args) {\n    Runnable runnable = new Runnable() {\n      public void run() {\n\tcreateAndShow();\n      }\n    };\n    SwingUtilities.invokeLater(runnable);\n  }\n\t\n  static void createAndShow() {\n    JFrame frame = new JFrame(\"Hello World\");\n    frame.setSize(640,480);\n    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n}\n", "C": "'--- added a flush to exit cleanly   \nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n \n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n \n'---pointer to X Display structure\nDECLARE d TYPE  Display*\n \n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n \n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n \nDECLARE msg TYPE char*\n \n'--- number of screen to place the window on\nDECLARE s TYPE int\n \n \n \n  msg = \"Hello, World!\"\n \n \n   d = DISPLAY(NULL)\n   IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n   END IF\n \n   s = SCREEN(d)\n   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n \n   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n   MAP_EVENT(d, w)\n \n   WHILE  (1) \n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t    BREAK\n\t END IF   \n   WEND\n   FLUSH(d)\n   CLOSE_DISPLAY(d)\n"}
{"id": 55844, "name": "Finite state machine", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n"}
{"id": 55845, "name": "Vibrating rectangles", "Java": "\n\nint counter = 100;\n\nvoid setup(){\n  size(1000,1000);\n}\n\nvoid draw(){\n  \n  for(int i=0;i<20;i++){\n    fill(counter - 5*i);\n    rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);\n  }\n  counter++;\n  \n  if(counter > 255)\n    counter = 100;\n  \n  delay(100);\n}\n", "C": "\n\n#include<graphics.h>\n\nvoid vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)\n{\n\tint color = 1,i,x = winWidth/2, y = winHeight/2;\n\t\n\twhile(!kbhit()){\n\t\tsetcolor(color++);\n\t\tfor(i=num;i>0;i--){\n\t\t\trectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);\n\t\t\tdelay(msec);\n\t\t}\n\n\t\tif(color>MAXCOLORS){\n\t\t\tcolor = 1;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Vibrating Rectangles...\");\n\t\n\tvibratingRectangles(1000,1000,30,15,20,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 55846, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 55847, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 55848, "name": "Pseudo-random numbers_PCG32", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55849, "name": "Deconvolution_1D", "Java": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n    public static int[] deconv(int[] g, int[] f) {\n        int[] h = new int[g.length - f.length + 1];\n        for (int n = 0; n < h.length; n++) {\n            h[n] = g[n];\n            int lower = Math.max(n - f.length + 1, 0);\n            for (int i = lower; i < n; i++)\n                h[n] -= h[i] * f[n - i];\n            h[n] /= f[0];\n        }\n        return h;\n    }\n\n    public static void main(String[] args) {\n        int[] h = { -8, -9, -3, -1, -6, 7 };\n        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n                96, 31, 55, 36, 29, -43, -7 };\n\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n        sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n        sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n        sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n        System.out.println(sb.toString());\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n"}
{"id": 55850, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 55851, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 55852, "name": "NYSIIS", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 55853, "name": "Disarium numbers", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n"}
{"id": 55854, "name": "Disarium numbers", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n"}
{"id": 55855, "name": "Sierpinski pentagon", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 55856, "name": "Bitmap_Histogram", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n"}
{"id": 55857, "name": "Mutex", "Java": "import java.util.concurrent.Semaphore;\n\npublic class VolatileClass{\n   public Semaphore mutex = new Semaphore(1); \n                                              \n   public void needsToBeSynched(){\n      \n   }\n   \n}\n", "C": "HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);\n"}
{"id": 55858, "name": "Metronome", "Java": "class Metronome{\n\tdouble bpm;\n\tint measure, counter;\n\tpublic Metronome(double bpm, int measure){\n\t\tthis.bpm = bpm;\n\t\tthis.measure = measure;\t\n\t}\n\tpublic void start(){\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tThread.sleep((long)(1000*(60.0/bpm)));\n\t\t\t}catch(InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tcounter++;\n\t\t\tif (counter%measure==0){\n\t\t\t\t System.out.println(\"TICK\");\n\t\t\t}else{\n\t\t\t\t System.out.println(\"TOCK\");\n\t\t\t}\n\t\t}\n\t}\n}\npublic class test {\n\tpublic static void main(String[] args) {\n\t\tMetronome metronome1 = new Metronome(120,4);\n\t\tmetronome1.start();\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/time.h>\n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); \n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec)   \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}\n"}
{"id": 55859, "name": "EKG sequence convergence", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n    public static void main(String[] args) {\n        System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n        for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n            System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n        }\n        System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n        List<Integer> ekg5 = ekg(5, 100);\n        List<Integer> ekg7 = ekg(7, 100);\n        for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n            if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n                System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n                break;\n            }\n        }\n    }\n    \n    \n    private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {\n        List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));\n        Collections.sort(list1);\n        List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));\n        Collections.sort(list2);\n        for ( int i = 0 ; i < n ; i++ ) {\n            if ( list1.get(i) != list2.get(i) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    \n    \n    private static List<Integer> ekg(int two, int maxN) {\n        List<Integer> result = new ArrayList<>();\n        result.add(1);\n        result.add(two);\n        Map<Integer,Integer> seen = new HashMap<>();\n        seen.put(1, 1);\n        seen.put(two, 1);\n        int minUnseen = two == 2 ? 3 : 2;\n        int prev = two;\n        for ( int n = 3 ; n <= maxN ; n++ ) {\n            int test = minUnseen - 1;\n            while ( true ) {\n                test++;\n                if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n                    \n                    result.add(test);\n                    seen.put(test, n);\n                    prev = test;\n                    if ( minUnseen == test ) {\n                        do {\n                            minUnseen++;\n                        } while ( seen.containsKey(minUnseen) );\n                    }\n                    break;\n                }\n            }\n        }\n        return result;\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 <stdio.h>\n#include <stdlib.h>\n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n    int aa = *(int *)a;\n    int bb = *(int *)b;\n    return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n    int i;\n    for (i = 0; i < len; ++i) {\n        if (a[i] == b) return TRUE;\n    }\n    return FALSE;\n}\n\nint gcd(int a, int b) {\n    while (a != b) {\n        if (a > b)\n            a -= b;\n        else\n            b -= a;\n    }\n    return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n    int i;\n    qsort(s, len, sizeof(int), compareInts);    \n    qsort(t, len, sizeof(int), compareInts);\n    for (i = 0; i < len; ++i) {\n        if (s[i] != t[i]) return FALSE;\n    }\n    return TRUE;\n}\n\nint main() {\n    int s, n, i;\n    int starts[5] = {2, 5, 7, 9, 10};\n    int ekg[5][LIMIT];\n    for (s = 0; s < 5; ++s) {\n        ekg[s][0] = 1;\n        ekg[s][1] = starts[s];\n        for (n = 2; n < LIMIT; ++n) {\n            for (i = 2; ; ++i) {\n                \n                \n                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n                    ekg[s][n] = i;\n                    break;\n                }\n            }\n        }\n        printf(\"EKG(%2d): [\", starts[s]);\n        for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n        printf(\"\\b]\\n\");\n    }\n    \n    \n    for (i = 2; i < LIMIT; ++i) {\n        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n            printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n            return 0;\n        }\n    }\n    printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n    return 0;\n}\n"}
{"id": 55860, "name": "Rep-string", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55861, "name": "Terminal control_Preserve screen", "Java": "public class PreserveScreen\n{\n    public static void main(String[] args) throws InterruptedException {\n        System.out.print(\"\\033[?1049h\\033[H\");\n        System.out.println(\"Alternate screen buffer\\n\");\n        for (int i = 5; i > 0; i--) {\n            String s = (i > 1) ? \"s\" : \"\";\n            System.out.printf(\"\\rgoing back in %d second%s...\", i, s);\n            Thread.sleep(1000);\n        }\n        System.out.print(\"\\033[?1049l\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n\tint i;\n\tprintf(\"\\033[?1049h\\033[H\");\n\tprintf(\"Alternate screen buffer\\n\");\n\tfor (i = 5; i; i--) {\n\t\tprintf(\"\\rgoing back in %d...\", i);\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tprintf(\"\\033[?1049l\");\n\n\treturn 0;\n}\n"}
{"id": 55862, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "C": "char ch = 'z';\n"}
{"id": 55863, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "C": "char ch = 'z';\n"}
{"id": 55864, "name": "Changeable words", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55865, "name": "Window management", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n"}
{"id": 55866, "name": "Window management", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n"}
{"id": 55867, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n"}
{"id": 55868, "name": "Next special primes", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n"}
{"id": 55869, "name": "Mayan numerals", "Java": "import java.math.BigInteger;\n\npublic class MayanNumerals {\n\n    public static void main(String[] args) {\n        for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {\n            displayMyan(BigInteger.valueOf(base10));\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static char[] digits = \"0123456789ABCDEFGHJK\".toCharArray();\n    private static BigInteger TWENTY = BigInteger.valueOf(20);\n    \n    private static void displayMyan(BigInteger numBase10) {\n        System.out.printf(\"As base 10:  %s%n\", numBase10);\n        String numBase20 = \"\";\n        while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {\n            numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;\n            numBase10 = numBase10.divide(TWENTY);\n        }\n        System.out.printf(\"As base 20:  %s%nAs Mayan:%n\", numBase20);\n        displayMyanLine1(numBase20);\n        displayMyanLine2(numBase20);\n        displayMyanLine3(numBase20);\n        displayMyanLine4(numBase20);\n        displayMyanLine5(numBase20);\n        displayMyanLine6(numBase20);\n    }\n \n    private static char boxUL = Character.toChars(9556)[0];\n    private static char boxTeeUp = Character.toChars(9574)[0];\n    private static char boxUR = Character.toChars(9559)[0];\n    private static char boxHorz = Character.toChars(9552)[0];\n    private static char boxVert = Character.toChars(9553)[0];\n    private static char theta = Character.toChars(952)[0];\n    private static char boxLL = Character.toChars(9562)[0];\n    private static char boxLR = Character.toChars(9565)[0];\n    private static char boxTeeLow = Character.toChars(9577)[0];\n    private static char bullet = Character.toChars(8729)[0];\n    private static char dash = Character.toChars(9472)[0];\n    \n    private static void displayMyanLine1(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxUL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeUp : boxUR);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String getBullet(int count) {\n        StringBuilder sb = new StringBuilder();\n        switch ( count ) {\n        case 1:  sb.append(\" \" + bullet + \"  \"); break;\n        case 2:  sb.append(\" \" + bullet + bullet + \" \"); break;\n        case 3:  sb.append(\"\" + bullet + bullet + bullet + \" \"); break;\n        case 4:  sb.append(\"\" + bullet + bullet + bullet + bullet); break;\n        default:  throw new IllegalArgumentException(\"Must be 1-4:  \" + count);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine2(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'G':  sb.append(getBullet(1)); break;\n            case 'H':  sb.append(getBullet(2)); break;\n            case 'J':  sb.append(getBullet(3)); break;\n            case 'K':  sb.append(getBullet(4)); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String DASH = getDash();\n    \n    private static String getDash() {\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < 4 ; i++ ) {\n            sb.append(dash);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine3(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'B':  sb.append(getBullet(1)); break;\n            case 'C':  sb.append(getBullet(2)); break;\n            case 'D':  sb.append(getBullet(3)); break;\n            case 'E':  sb.append(getBullet(4)); break;\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine4(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '6':  sb.append(getBullet(1)); break;\n            case '7':  sb.append(getBullet(2)); break;\n            case '8':  sb.append(getBullet(3)); break;\n            case '9':  sb.append(getBullet(4)); break;\n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine5(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '0':  sb.append(\" \" + theta + \"  \"); break;\n            case '1':  sb.append(getBullet(1)); break;\n            case '2':  sb.append(getBullet(2)); break;\n            case '3':  sb.append(getBullet(3)); break;\n            case '4':  sb.append(getBullet(4)); break;\n            case '5': case '6': case '7': case '8': case '9': \n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine6(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxLL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeLow : boxLR);\n        }\n        System.out.println(sb.toString());\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n"}
{"id": 55870, "name": "Ramsey's theorem", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n", "C": "#include <stdio.h>\n\nint a[17][17], idx[4];\n\nint find_group(int type, int min_n, int max_n, int depth)\n{\n\tint i, n;\n\tif (depth == 4) {\n\t\tprintf(\"totally %sconnected group:\", type ? \"\" : \"un\");\n\t\tfor (i = 0; i < 4; i++) printf(\" %d\", idx[i]);\n\t\tputchar('\\n');\n\t\treturn 1;\n\t}\n\n\tfor (i = min_n; i < max_n; i++) {\n\t\tfor (n = 0; n < depth; n++)\n\t\t\tif (a[idx[n]][i] != type) break;\n\n\t\tif (n == depth) {\n\t\t\tidx[n] = i;\n\t\t\tif (find_group(type, 1, max_n, depth + 1))\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tconst char *mark = \"01-\";\n\n\tfor (i = 0; i < 17; i++)\n\t\ta[i][i] = 2;\n\n\tfor (k = 1; k <= 8; k <<= 1) {\n\t\tfor (i = 0; i < 17; i++) {\n\t\t\tj = (i + k) % 17;\n\t\t\ta[i][j] = a[j][i] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < 17; i++) {\n\t\tfor (j = 0; j < 17; j++)\n\t\t\tprintf(\"%c \", mark[a[i][j]]);\n\t\tputchar('\\n');\n\t}\n\n\t\n\t\n\n\t\n\tfor (i = 0; i < 17; i++) {\n\t\tidx[0] = i;\n\t\tif (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {\n\t\t\tputs(\"no good\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"all good\");\n\treturn 0;\n}\n"}
{"id": 55871, "name": "GUI_Maximum window dimensions", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n"}
{"id": 55872, "name": "Four is magic", "Java": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n", "C": "#include <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 55873, "name": "Getting the number of decimals", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 55874, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 55875, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 55876, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55877, "name": "Paraffins", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55878, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55879, "name": "Pentagram", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55880, "name": "Parse an IP Address", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"}
{"id": 55881, "name": "Knapsack problem_Unbounded", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n"}
{"id": 55882, "name": "Textonyms", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55883, "name": "Teacup rim text", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55884, "name": "Teacup rim text", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55885, "name": "Increasing gaps between consecutive Niven numbers", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 55886, "name": "Print debugging statement", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n"}
{"id": 55887, "name": "Superellipse", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 55888, "name": "Permutations_Rank of a permutation", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n"}
{"id": 55889, "name": "Permutations_Rank of a permutation", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n"}
{"id": 55890, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 55891, "name": "Type detection", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n"}
{"id": 55892, "name": "Maximum triangle path sum", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 55893, "name": "Zhang-Suen thinning algorithm", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n"}
{"id": 55894, "name": "Variable declaration reset", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n"}
{"id": 55895, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55896, "name": "Find first and last set bit of a long integer", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55897, "name": "Numbers with equal rises and falls", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n"}
{"id": 55898, "name": "Koch curve", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55899, "name": "Draw pixel 2", "Java": "\n\nsize(640,480);\n\nstroke(#ffff00);\n\nellipse(random(640),random(480),1,1);\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<time.h>\n\nint main()\n{\n\tsrand(time(NULL));\n\t\n\tinitwindow(640,480,\"Yellow Random Pixel\");\n\t\n\tputpixel(rand()%640,rand()%480,YELLOW);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 55900, "name": "Draw a pixel", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 55901, "name": "Words from neighbour ones", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55902, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 55903, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 55904, "name": "Magic squares of singly even order", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n"}
{"id": 55905, "name": "Generate Chess960 starting position", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55906, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 55907, "name": "Execute Brain____", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 55908, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "C": "int meaning_of_life();\n"}
{"id": 55909, "name": "Modulinos", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n", "C": "int meaning_of_life();\n"}
{"id": 55910, "name": "Perlin noise", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55911, "name": "Perlin noise", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 55912, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n"}
{"id": 55913, "name": "UTF-8 encode and decode", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n"}
{"id": 55914, "name": "Xiaolin Wu's line algorithm", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 55915, "name": "Xiaolin Wu's line algorithm", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 55916, "name": "Keyboard macros", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/keysym.h>\n\nint main()\n{\n  Display *d;\n  XEvent event;\n  \n  d = XOpenDisplay(NULL);\n  if ( d != NULL ) {\n                \n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), \n\t     Mod1Mask,  \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), \n\t     Mod1Mask, \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n\n    for(;;)\n    {\n      XNextEvent(d, &event);\n      if ( event.type == KeyPress ) {\n\tKeySym s = XLookupKeysym(&event.xkey, 0);\n\tif ( s == XK_F7 ) {\n\t  printf(\"something's happened\\n\");\n\t} else if ( s == XK_F6 ) {\n\t  break;\n\t}\n      }\n    }\n\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), Mod1Mask, DefaultRootWindow(d));\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), Mod1Mask, DefaultRootWindow(d));\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 55917, "name": "McNuggets problem", "Java": "public class McNuggets {\n\n    public static void main(String... args) {\n        int[] SIZES = new int[] { 6, 9, 20 };\n        int MAX_TOTAL = 100;\n        \n        int numSizes = SIZES.length;\n        int[] counts = new int[numSizes];\n        int maxFound = MAX_TOTAL + 1;\n        boolean[] found = new boolean[maxFound];\n        int numFound = 0;\n        int total = 0;\n        boolean advancedState = false;\n        do {\n            if (!found[total]) {\n                found[total] = true;\n                numFound++;\n            }\n            \n            \n            advancedState = false;\n            for (int i = 0; i < numSizes; i++) {\n                int curSize = SIZES[i];\n                if ((total + curSize) > MAX_TOTAL) {\n                    \n                    total -= counts[i] * curSize;\n                    counts[i] = 0;\n                }\n                else {\n                    \n                    counts[i]++;\n                    total += curSize;\n                    advancedState = true;\n                    break;\n                }\n            }\n            \n        } while ((numFound < maxFound) && advancedState);\n        \n        if (numFound < maxFound) {\n            \n            for (int i = MAX_TOTAL; i >= 0; i--) {\n                if (!found[i]) {\n                    System.out.println(\"Largest non-McNugget number in the search space is \" + i);\n                    break;\n                }\n            }\n        }\n        else {\n            System.out.println(\"All numbers in the search space are McNugget numbers\");\n        }\n        \n        return;\n    }\n}\n", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n"}
{"id": 55918, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 55919, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n"}
{"id": 55920, "name": "Extreme floating point values", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n"}
{"id": 55921, "name": "Pseudo-random numbers_Xorshift star", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 55922, "name": "ASCII art diagram converter", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n"}
{"id": 55923, "name": "ASCII art diagram converter", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n"}
{"id": 55924, "name": "Levenshtein distance_Alignment", "Java": "public class LevenshteinAlignment {\n\n    public static String[] alignment(String a, String b) {\n        a = a.toLowerCase();\n        b = b.toLowerCase();\n        \n        int[][] costs = new int[a.length()+1][b.length()+1];\n        for (int j = 0; j <= b.length(); j++)\n            costs[0][j] = j;\n        for (int i = 1; i <= a.length(); i++) {\n            costs[i][0] = i;\n            for (int j = 1; j <= b.length(); j++) {\n                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);\n            }\n        }\n\n\t\n\tStringBuilder aPathRev = new StringBuilder();\n\tStringBuilder bPathRev = new StringBuilder();\n\tfor (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {\n\t    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append(b.charAt(--j));\n\t    } else if (costs[i][j] == 1 + costs[i-1][j]) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append('-');\n\t    } else if (costs[i][j] == 1 + costs[i][j-1]) {\n\t\taPathRev.append('-');\n\t\tbPathRev.append(b.charAt(--j));\n\t    }\n\t}\n        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};\n    }\n\n    public static void main(String[] args) {\n\tString[] result = alignment(\"rosettacode\", \"raisethysword\");\n\tSystem.out.println(result[0]);\n\tSystem.out.println(result[1]);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}\n"}
{"id": 55925, "name": "Same fringe", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 55926, "name": "Simulate input_Keyboard", "Java": "import java.awt.Robot\npublic static void type(String str){\n   Robot robot = new Robot();\n   for(char ch:str.toCharArray()){\n      if(Character.isUpperCase(ch)){\n         robot.keyPress(KeyEvent.VK_SHIFT);\n         robot.keyPress((int)ch);\n         robot.keyRelease((int)ch);\n         robot.keyRelease(KeyEvent.VK_SHIFT);\n      }else{\n         char upCh = Character.toUpperCase(ch);\n         robot.keyPress((int)upCh);\n         robot.keyRelease((int)upCh);\n      }\n   }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n\nint main(int argc, char *argv[])\n{\n  Display *dpy;\n  Window win;\n  GC gc;\n  int scr;\n  Atom WM_DELETE_WINDOW;\n  XEvent ev;\n  XEvent ev2;\n  KeySym keysym;\n  int loop;\n\n  \n  dpy = XOpenDisplay(NULL);\n  if (dpy == NULL) {\n    fputs(\"Cannot open display\", stderr);\n    exit(1);\n  }\n  scr = XDefaultScreen(dpy);\n\n  \n  win = XCreateSimpleWindow(dpy,\n          XRootWindow(dpy, scr),\n          \n          10, 10, 300, 200, 1,\n          \n          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));\n\n  \n  XStoreName(dpy, win, argv[0]);\n\n  \n  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);\n\n  \n  XMapWindow(dpy, win);\n  XFlush(dpy);\n\n  \n  gc = XDefaultGC(dpy, scr);\n\n  \n  WM_DELETE_WINDOW = XInternAtom(dpy, \"WM_DELETE_WINDOW\", True);\n  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);\n\n  \n  loop = 1;\n  while (loop) {\n    XNextEvent(dpy, &ev);\n    switch (ev.type)\n    {\n      case Expose:\n        \n        {\n          char msg1[] = \"Clic in the window to generate\";\n          char msg2[] = \"a key press event\";\n          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);\n          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);\n        }\n        break;\n\n      case ButtonPress:\n        puts(\"ButtonPress event received\");\n        \n        ev2.type = KeyPress;\n        ev2.xkey.state = ShiftMask;\n        ev2.xkey.keycode = 24 + (rand() % 33);\n        ev2.xkey.same_screen = True;\n        XSendEvent(dpy, win, True, KeyPressMask, &ev2);\n        break;\n   \n      case ClientMessage:\n        \n        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)\n          loop = 0;\n        break;\n   \n      case KeyPress:\n        \n        puts(\"KeyPress event received\");\n        printf(\"> keycode: %d\\n\", ev.xkey.keycode);\n        \n        keysym = XLookupKeysym(&(ev.xkey), 0);\n        if (keysym == XK_q ||\n            keysym == XK_Escape) {\n          loop = 0;\n        } else {\n          char buffer[] = \"  \";\n          int nchars = XLookupString(\n                &(ev.xkey),\n                buffer,\n                2,  \n                &keysym,\n                NULL );\n          if (nchars == 1)\n            printf(\"> Key '%c' pressed\\n\", buffer[0]);\n        }\n        break;\n    }\n  }\n  XDestroyWindow(dpy, win);\n  \n  XCloseDisplay(dpy);\n  return 1;\n}\n"}
{"id": 55927, "name": "Peaceful chess queen armies", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 55928, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 55929, "name": "Active Directory_Search for a user", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n"}
{"id": 55930, "name": "Active Directory_Search for a user", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n"}
{"id": 55931, "name": "Singular value decomposition", "Java": "import Jama.Matrix;\npublic class SingularValueDecomposition {\n    public static void main(String[] args) {\n        double[][] matrixArray = {{3, 0}, {4, 5}};\n        var matrix = new Matrix(matrixArray);\n        var svd = matrix.svd();\n        svd.getU().print(0, 10); \n        svd.getS().print(0, 10);\n        svd.getV().print(0, 10);\n    }\n}\n", "C": "#include <stdio.h>\n#include <gsl/gsl_linalg.h>\n\n\nvoid gsl_matrix_print(const gsl_matrix *M) {\n    int rows = M->size1;\n    int cols = M->size2;\n    for (int i = 0; i < rows; i++) {\n        printf(\"|\");\n        for (int j = 0; j < cols; j++) {\n            printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n        }\n        printf(\"\\b|\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main(){\n    double a[] = {3, 0, 4, 5};\n    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n    gsl_matrix *V = gsl_matrix_alloc(2, 2);\n    gsl_vector *S = gsl_vector_alloc(2);\n    gsl_vector *work = gsl_vector_alloc(2);\n\n    \n    gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n    gsl_matrix_transpose(V);\n    double s[] = {S->data[0], 0, 0, S->data[1]};\n    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n    printf(\"U:\\n\");\n    gsl_matrix_print(&A.matrix);\n\n    printf(\"S:\\n\");\n    gsl_matrix_print(&SM.matrix);\n\n    printf(\"VT:\\n\");\n    gsl_matrix_print(V);\n    \n    gsl_matrix_free(V);\n    gsl_vector_free(S);\n    gsl_vector_free(work);\n    return 0;\n}\n"}
{"id": 55932, "name": "Test integerness", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n"}
{"id": 55933, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n"}
{"id": 55934, "name": "Rodrigues’ rotation formula", "Java": "\n\nclass Vector{\n  private double x, y, z;\n\n  public Vector(double x1,double y1,double z1){\n    x = x1;\n    y = y1;\n    z = z1;\n  }\n  \n  void printVector(int x,int y){\n    text(\"( \" + this.x + \" )  \\u00ee + ( \" + this.y + \" ) + \\u0135 ( \" + this.z + \") \\u006b\\u0302\",x,y);\n  }\n\n  public double norm() {\n    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);\n  }\n  \n  public Vector normalize(){\n    double length = this.norm();\n    return new Vector(this.x / length, this.y / length, this.z / length);\n  }\n  \n  public double dotProduct(Vector v2) {\n    return this.x*v2.x + this.y*v2.y + this.z*v2.z;\n  }\n  \n  public Vector crossProduct(Vector v2) {\n    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);\n  }\n  \n  public double getAngle(Vector v2) {\n    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));\n  }\n  \n  public Vector aRotate(Vector v, double a) {\n    double ca = Math.cos(a), sa = Math.sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    Vector[] r = {\n        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),\n        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),\n        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)\n    };\n    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));\n  }\n}\n\nvoid setup(){\n  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);\n  double a = v1.getAngle(v2);\n  Vector cp = v1.crossProduct(v2);\n  Vector normCP = cp.normalize();\n  Vector np = v1.aRotate(normCP,a);\n  \n  size(1200,600);\n  fill(#000000);\n  textSize(30);\n  \n  text(\"v1 = \",10,100);\n  v1.printVector(60,100);\n  text(\"v2 = \",10,150);\n  v2.printVector(60,150);\n  text(\"rV = \",10,200);\n  np.printVector(60,200);\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct {\n    double x, y, z;\n} vector;\n\ntypedef struct {\n    vector i, j, k;\n} matrix;\n\ndouble norm(vector v) {\n    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);\n}\n\nvector normalize(vector v){\n    double length = norm(v);\n    vector n = {v.x / length, v.y / length, v.z / length};\n    return n;\n}\n\ndouble dotProduct(vector v1, vector v2) {\n    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;\n}\n\nvector crossProduct(vector v1, vector v2) {\n    vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x};\n    return cp;\n}\n\ndouble getAngle(vector v1, vector v2) {\n    return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2)));\n}\n\nvector matrixMultiply(matrix m ,vector v) {\n    vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)};\n    return mm;\n}\n\nvector aRotate(vector p, vector v, double a) {\n    double ca = cos(a), sa = sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    matrix r = {\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}\n    };\n    return matrixMultiply(r, p);\n}\n\nint main() {\n    vector v1 = {5, -6, 4}, v2 = {8, 5, -30};\n    double a = getAngle(v1, v2);\n    vector cp = crossProduct(v1, v2);\n    vector ncp = normalize(cp);\n    vector np = aRotate(v1, ncp, a);\n    printf(\"[%.13f, %.13f, %.13f]\\n\", np.x, np.y, np.z);\n    return 0;\n}\n"}
{"id": 55935, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n"}
{"id": 55936, "name": "Death Star", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n"}
{"id": 55937, "name": "Lucky and even lucky numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define LUCKY_SIZE 60000\nint luckyOdd[LUCKY_SIZE];\nint luckyEven[LUCKY_SIZE];\n\nvoid compactLucky(int luckyArray[]) {\n    int i, j, k;\n\n    for (i = 0; i < LUCKY_SIZE; i++) {\n        if (luckyArray[i] == 0) {\n            j = i;\n            break;\n        }\n    }\n\n    for (j = i + 1; j < LUCKY_SIZE; j++) {\n        if (luckyArray[j] > 0) {\n            luckyArray[i++] = luckyArray[j];\n        }\n    }\n\n    for (; i < LUCKY_SIZE; i++) {\n        luckyArray[i] = 0;\n    }\n}\n\nvoid initialize() {\n    int i, j;\n\n    \n    for (i = 0; i < LUCKY_SIZE; i++) {\n        luckyEven[i] = 2 * i + 2;\n        luckyOdd[i] = 2 * i + 1;\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyOdd[i] > 0) {\n            for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {\n                luckyOdd[j] = 0;\n            }\n            compactLucky(luckyOdd);\n        }\n    }\n\n    \n    for (i = 1; i < LUCKY_SIZE; i++) {\n        if (luckyEven[i] > 0) {\n            for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {\n                luckyEven[j] = 0;\n            }\n            compactLucky(luckyEven);\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[j] == 0 || luckyEven[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyEven[i] != 0; i++) {\n            if (luckyEven[i] > k) {\n                break;\n            }\n            if (luckyEven[i] > j) {\n                printf(\" %d\", luckyEven[i]);\n            }\n        }\n    } else {\n        if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {\n            fprintf(stderr, \"At least one argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers between %d and %d are:\", j, k);\n        for (i = 0; luckyOdd[i] != 0; i++) {\n            if (luckyOdd[i] > k) {\n                break;\n            }\n            if (luckyOdd[i] > j) {\n                printf(\" %d\", luckyOdd[i]);\n            }\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    int i;\n\n    if (even) {\n        if (luckyEven[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyEven[i]);\n        }\n    } else {\n        if (luckyOdd[k] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky numbers %d to %d are:\", j, k);\n        for (i = j - 1; i < k; i++) {\n            printf(\" %d\", luckyOdd[i]);\n        }\n    }\n    printf(\"\\n\");\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (luckyEven[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky even number %d=%d\\n\", j, luckyEven[j - 1]);\n    } else {\n        if (luckyOdd[j] == 0) {\n            fprintf(stderr, \"The argument is too large\\n\");\n            exit(EXIT_FAILURE);\n        }\n        printf(\"Lucky number %d=%d\\n\", j, luckyOdd[j - 1]);\n    }\n}\n\nvoid help() {\n    printf(\"./lucky j [k] [--lucky|--evenLucky]\\n\");\n    printf(\"\\n\");\n    printf(\"       argument(s)        |  what is displayed\\n\");\n    printf(\"==============================================\\n\");\n    printf(\"-j=m                      |  mth lucky number\\n\");\n    printf(\"-j=m  --lucky             |  mth lucky number\\n\");\n    printf(\"-j=m  --evenLucky         |  mth even lucky number\\n\");\n    printf(\"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\");\n    printf(\"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\");\n    printf(\"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\");\n    printf(\"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\");\n}\n\nvoid process(int argc, char *argv[]) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    bool good = false;\n    int i;\n\n    for (i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    fprintf(stderr, \"Unknown long argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    fprintf(stderr, \"Unknown short argument: [%s]\\n\", argv[i]);\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            fprintf(stderr, \"Unknown argument: [%s]\\n\", argv[i]);\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n}\n\nvoid test() {\n    printRange(1, 20, false);\n    printRange(1, 20, true);\n\n    printBetween(6000, 6100, false);\n    printBetween(6000, 6100, true);\n\n    printSingle(10000, false);\n    printSingle(10000, true);\n}\n\nint main(int argc, char *argv[]) {\n    initialize();\n\n    \n\n    if (argc < 2) {\n        help();\n        return 1;\n    }\n    process(argc, argv);\n\n    return 0;\n}\n"}
{"id": 55938, "name": "Scope modifiers", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n", "C": "int a;          \nstatic int p;   \n\nextern float v; \n\n\nint code(int arg)\n{\n  int myp;        \n                  \n                  \n  static int myc; \n                  \n                  \n                  \n                  \n}\n\n\nstatic void code2(void)\n{\n  v = v * 1.02;    \n  \n}\n"}
{"id": 55939, "name": "Simple database", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h> \n#include <string.h> \n#define _XOPEN_SOURCE \n#define __USE_XOPEN\n#include <time.h>\n#define DB \"database.csv\" \n#define TRY(a)  if (!(a)) {perror(#a);exit(1);}\n#define TRY2(a) if((a)<0) {perror(#a);exit(1);}\n#define FREE(a) if(a) {free(a);a=NULL;}\n#define sort_by(foo) \\\nstatic int by_##foo (const void*p1, const void*p2) { \\\n    return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); }\ntypedef struct db {\n    char title[26];\n    char first_name[26];\n    char last_name[26];\n    time_t date;\n    char publ[100];\n    struct db *next;\n}\ndb_t,*pdb_t;\ntypedef int (sort)(const void*, const void*);\nenum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY};\nstatic pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby);\nstatic char *time2str (time_t *time);\nstatic time_t str2time (char *date);\n\nsort_by(last_name);\nsort_by(title);\nstatic int by_date(pdb_t *p1, pdb_t *p2);\n\nint main (int argc, char **argv) {\n    char buf[100];\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    db_t db;\n    db.next=NULL;\n    pdb_t dblist;\n    int i;\n    FILE *f;\n    TRY (f=fopen(DB,\"a+\"));\n    if (argc<2) {\nusage:  printf (\"Usage: %s [commands]\\n\"\n        \"-c  Create new entry.\\n\"\n        \"-p  Print the latest entry.\\n\"\n        \"-t  Print all entries sorted by title.\\n\"\n        \"-d  Print all entries sorted by date.\\n\"\n        \"-a  Print all entries sorted by author.\\n\",argv[0]);\n        fclose (f);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n        case CREATE:\n        printf(\"-c  Create a new entry.\\n\");\n        printf(\"Title           :\");if((scanf(\" %25[^\\n]\",db.title     ))<0)break;\n        printf(\"Author Firstname:\");if((scanf(\" %25[^\\n]\",db.first_name))<0)break;\n        printf(\"Author Lastname :\");if((scanf(\" %25[^\\n]\",db.last_name ))<0)break;\n        printf(\"Date 10-12-2000 :\");if((scanf(\" %10[^\\n]\",buf          ))<0)break;\n        printf(\"Publication     :\");if((scanf(\" %99[^\\n]\",db.publ      ))<0)break;\n        db.date=str2time (buf);\n        dao (CREATE,f,&db,NULL);\n        break;\n        case PRINT:\n        printf (\"-p  Print the latest entry.\\n\");\n        while (!feof(f)) dao (READLINE,f,&db,NULL);\n        dao (PRINT,f,&db,NULL);\n        break;\n        case TITLE:\n        printf (\"-t  Print all entries sorted by title.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_title);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case DATE:\n        printf (\"-d  Print all entries sorted by date.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,(int (*)(const void *,const  void *)) by_date);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        case AUTH:\n        printf (\"-a  Print all entries sorted by author.\\n\");\n        dblist = dao (READ,f,&db,NULL);\n        dblist = dao (SORT,f,dblist,by_last_name);\n        dao (PRINT,f,dblist,NULL);\n        dao (DESTROY,f,dblist,NULL);\n        break;\n        default: {\n            printf (\"Unknown command: %s.\\n\",strlen(argv[1])<10?argv[1]:\"\");\n            goto usage;\n    }   }\n    fclose (f);\n    return 0;\n}\n\nstatic pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) {\n    pdb_t *pdb=NULL,rec=NULL,hd=NULL;\n    int i=0,ret;\n    char buf[100];\n    switch (cmd) {\n        case CREATE:\n        fprintf (f,\"\\\"%s\\\",\",in_db->title);\n        fprintf (f,\"\\\"%s\\\",\",in_db->first_name);\n        fprintf (f,\"\\\"%s\\\",\",in_db->last_name);\n        fprintf (f,\"\\\"%s\\\",\",time2str(&in_db->date));\n        fprintf (f,\"\\\"%s\\\" \\n\",in_db->publ);\n        break;\n        case PRINT:\n        for (;in_db;i++) {\n            printf (\"Title       : %s\\n\",     in_db->title);\n            printf (\"Author      : %s %s\\n\",  in_db->first_name, in_db->last_name);\n            printf (\"Date        : %s\\n\",     time2str(&in_db->date));\n            printf (\"Publication : %s\\n\\n\",   in_db->publ);\n            if (!((i+1)%3)) {\n                printf (\"Press Enter to continue.\\n\");\n                ret = scanf (\"%*[^\\n]\");\n                if (ret<0) return rec; \n                else getchar();\n            }\n            in_db=in_db->next;\n        }\n        break;\n        case READLINE:\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->title     ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->first_name))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",in_db->last_name ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\",\",buf              ))<0)break;\n        if((fscanf(f,\" \\\"%[^\\\"]\\\" \",in_db->publ      ))<0)break;\n        in_db->date=str2time (buf);\n        break;\n        case READ:\n        while (!feof(f)) {\n            dao (READLINE,f,in_db,NULL);\n            TRY (rec=malloc(sizeof(db_t)));\n            *rec=*in_db; \n            rec->next=hd;\n            hd=rec;i++;\n        }\n        if (i<2) {\n            puts (\"Empty database. Please create some entries.\");\n            fclose (f);\n            exit (0);\n        }\n        break;\n        case SORT:\n        rec=in_db;\n        for (;in_db;i++) in_db=in_db->next;\n        TRY (pdb=malloc(i*sizeof(pdb_t)));\n        in_db=rec;\n        for (i=0;in_db;i++) {\n            pdb[i]=in_db;\n            in_db=in_db->next;\n        }\n        qsort (pdb,i,sizeof in_db,sortby);\n        pdb[i-1]->next=NULL;\n        for (i=i-1;i;i--) {\n            pdb[i-1]->next=pdb[i];\n        }\n        rec=pdb[0];\n        FREE (pdb);\n        pdb=NULL;\n        break;\n        case DESTROY: {\n            while ((rec=in_db)) {\n                in_db=in_db->next;\n                FREE (rec);\n    }   }   }\n    return rec;\n}\n\nstatic char *time2str (time_t *time) {\n    static char buf[255];\n    struct tm *ptm;\n    ptm=localtime (time);\n    strftime(buf, 255, \"%m-%d-%Y\", ptm);\n    return buf;\n}\n\nstatic time_t str2time (char *date) {\n    struct tm tm;\n    memset (&tm, 0, sizeof(struct tm));\n    strptime(date, \"%m-%d-%Y\", &tm);\n    return mktime(&tm);\n}\n\nstatic int by_date (pdb_t *p1, pdb_t *p2) {\n    if ((*p1)->date < (*p2)->date) {\n        return -1;\n    }\n    else return ((*p1)->date > (*p2)->date);\n}\n"}
{"id": 55940, "name": "Total circles area", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55941, "name": "Total circles area", "Java": "public class CirclesTotalArea {\n\n    \n    \n    private static double distSq(double x1, double y1, double x2, double y2) {\n        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    }\n    \n    private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {\n        double r2 = circ[2] * circ[2];\n        \n        return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;\n    }\n    \n    private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {\n        \n        if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&\n          rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }\n        \n        double r2 = circ[2] + Math.max(rect[2], rect[3]);\n        r2 = r2 * r2;\n        return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&\n          distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;\n    }\n    \n    private static boolean[] surelyOutside;\n    \n    private static double totalArea(double[] rect, double[][] circs, int d) {    \n        \n        int surelyOutsideCount = 0;\n        for(int i = 0; i < circs.length; i++) {\n            if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }\n            if(rectangleSurelyOutsideCircle(rect, circs[i])) {\n                surelyOutside[i] = true;\n                surelyOutsideCount++;\n            }\n            else { surelyOutside[i] = false; }\n        }\n        \n        if(surelyOutsideCount == circs.length) { return 0; }\n        \n        if(d < 1) { \n            return rect[2] * rect[3] / 3;  \n        }\n        \n        if(surelyOutsideCount > 0) {\n            double[][] newCircs = new double[circs.length - surelyOutsideCount][3];\n            int loc = 0;\n            for(int i = 0; i < circs.length; i++) {\n                if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }\n            }\n            circs = newCircs;\n        }\n        \n        double w = rect[2] / 2; \n        double h = rect[3] / 2; \n        double[][] pieces = {\n            { rect[0], rect[1], w, h }, \n            { rect[0] + w, rect[1], w, h }, \n            { rect[0], rect[1] - h, w, h }, \n            { rect[0] + w, rect[1] - h, w, h } \n        };\n        double total = 0;\n        for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }\n        return total;\n    }\n    \n    public static double totalArea(double[][] circs, int d) {\n        double maxx = Double.NEGATIVE_INFINITY;\n        double minx = Double.POSITIVE_INFINITY;\n        double maxy = Double.NEGATIVE_INFINITY;\n        double miny = Double.POSITIVE_INFINITY;\n        \n        for(double[] circ: circs) {\n            if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }\n            if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }\n            if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }\n            if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }\n        }\n        double[] rect = { minx, maxy, maxx - minx, maxy - miny };\n        surelyOutside = new boolean[circs.length];\n        return totalArea(rect, circs, d);\n    }\n    \n    public static void main(String[] args) {\n        double[][] circs = {\n            { 1.6417233788, 1.6121789534, 0.0848270516 },\n            {-1.4944608174, 1.2077959613, 1.1039549836 },\n            { 0.6110294452, -0.6907087527, 0.9089162485 },\n            { 0.3844862411, 0.2923344616, 0.2375743054 },\n            {-0.2495892950, -0.3832854473, 1.0845181219 },\n            {1.7813504266, 1.6178237031, 0.8162655711 },\n            {-0.1985249206, -0.8343333301, 0.0538864941 },\n            {-1.7011985145, -0.1263820964, 0.4776976918 },\n            {-0.4319462812, 1.4104420482, 0.7886291537 },\n            {0.2178372997, -0.9499557344, 0.0357871187 },\n            {-0.6294854565, -1.3078893852, 0.7653357688 },\n            {1.7952608455, 0.6281269104, 0.2727652452 },\n            {1.4168575317, 1.0683357171, 1.1016025378 },\n            {1.4637371396, 0.9463877418, 1.1846214562 },\n            {-0.5263668798, 1.7315156631, 1.4428514068 },\n            {-1.2197352481, 0.9144146579, 1.0727263474 },\n            {-0.1389358881, 0.1092805780, 0.7350208828 },\n            {1.5293954595, 0.0030278255, 1.2472867347 },\n            {-0.5258728625, 1.3782633069, 1.3495508831 },\n            {-0.1403562064, 0.2437382535, 1.3804956588 },\n            {0.8055826339, -0.0482092025, 0.3327165165 },\n            {-0.6311979224, 0.7184578971, 0.2491045282 },\n            {1.4685857879, -0.8347049536, 1.3670667538 },\n            {-0.6855727502, 1.6465021616, 1.0593087096 },\n            {0.0152957411, 0.0638919221, 0.9771215985 }\n        };\n        double ans = totalArea(circs, 24);\n        System.out.println(\"Approx. area is \" + ans);\n        System.out.println(\"Error is \" + Math.abs(21.56503660 - ans));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <stdbool.h>\n\ntypedef double Fp;\ntypedef struct { Fp x, y, r; } Circle;\n\nCircle circles[] = {\n    { 1.6417233788,  1.6121789534, 0.0848270516},\n    {-1.4944608174,  1.2077959613, 1.1039549836},\n    { 0.6110294452, -0.6907087527, 0.9089162485},\n    { 0.3844862411,  0.2923344616, 0.2375743054},\n    {-0.2495892950, -0.3832854473, 1.0845181219},\n    { 1.7813504266,  1.6178237031, 0.8162655711},\n    {-0.1985249206, -0.8343333301, 0.0538864941},\n    {-1.7011985145, -0.1263820964, 0.4776976918},\n    {-0.4319462812,  1.4104420482, 0.7886291537},\n    { 0.2178372997, -0.9499557344, 0.0357871187},\n    {-0.6294854565, -1.3078893852, 0.7653357688},\n    { 1.7952608455,  0.6281269104, 0.2727652452},\n    { 1.4168575317,  1.0683357171, 1.1016025378},\n    { 1.4637371396,  0.9463877418, 1.1846214562},\n    {-0.5263668798,  1.7315156631, 1.4428514068},\n    {-1.2197352481,  0.9144146579, 1.0727263474},\n    {-0.1389358881,  0.1092805780, 0.7350208828},\n    { 1.5293954595,  0.0030278255, 1.2472867347},\n    {-0.5258728625,  1.3782633069, 1.3495508831},\n    {-0.1403562064,  0.2437382535, 1.3804956588},\n    { 0.8055826339, -0.0482092025, 0.3327165165},\n    {-0.6311979224,  0.7184578971, 0.2491045282},\n    { 1.4685857879, -0.8347049536, 1.3670667538},\n    {-0.6855727502,  1.6465021616, 1.0593087096},\n    { 0.0152957411,  0.0638919221, 0.9771215985}};\n\nconst size_t n_circles = sizeof(circles) / sizeof(Circle);\n\nstatic inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }\n\nstatic inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }\n\nstatic inline Fp sq(const Fp a) { return a * a; }\n\n\nstatic inline double uniform(const double a, const double b) {\n    const double r01 = rand() / (double)RAND_MAX;\n    return a + (b - a) * r01;\n}\n\nstatic inline bool is_inside_circles(const Fp x, const Fp y) {\n    for (size_t i = 0; i < n_circles; i++)\n        if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)\n            return true;\n    return false;\n}\n\nint main() {\n    \n    Fp x_min = INFINITY, x_max = -INFINITY;\n    Fp y_min = x_min, y_max = x_max;\n\n    \n    for (size_t i = 0; i < n_circles; i++) {\n        Circle *c = &circles[i];\n        x_min = min(x_min, c->x - c->r);\n        x_max = max(x_max, c->x + c->r);\n        y_min = min(y_min, c->y - c->r);\n        y_max = max(y_max, c->y + c->r);\n\n        c->r *= c->r; \n    }\n\n    const Fp bbox_area = (x_max - x_min) * (y_max - y_min);\n\n    \n    srand(time(0));\n    size_t to_try = 1U << 16;\n    size_t n_tries = 0;\n    size_t n_hits = 0;\n\n    while (true) {\n        n_hits += is_inside_circles(uniform(x_min, x_max),\n                                    uniform(y_min, y_max));\n        n_tries++;\n\n        if (n_tries == to_try) {\n            const Fp area = bbox_area * n_hits / n_tries;\n            const Fp r = (Fp)n_hits / n_tries;\n            const Fp s = area * sqrt(r * (1 - r) / n_tries);\n            printf(\"%.4f +/- %.4f (%zd samples)\\n\", area, s, n_tries);\n            if (s * 3 <= 1e-3) \n                break;\n            to_try *= 2;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 55942, "name": "Hough transform", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\n  }\n}\n", "C": "#include \"SL_Generated.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nint main( int argc, char** argv )\n{\n    string fileName = \"Pentagon.bmp\";\n    if(argc > 1) fileName = argv[1];\n    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);\n    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);\n    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);\n    int threads = 0; if(argc > 5) threads = atoi(argv[5]);\n    char titleBuffer[200];\n    SLTimer t;\n\n    CImg<int> image(fileName.c_str());\n    int imageDimensions[] = {image.height(), image.width(), 0};\n    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);\n    Sequence< Sequence<int> > result;\n\n    sl_init(threads);\n\n    t.start();\n    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);\n    t.stop();\n    \n    CImg<int> resultImage(result[1].size(), result.size());\n    for(int y = 0; y < result.size(); y++)\n        for(int x = 0; x < result[y+1].size(); x++)\n            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];\n    \n    sprintf(titleBuffer, \"SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\\0\", \n                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());\n    resultImage.display(titleBuffer);\n\n    sl_done();\n    return 0;\n}\n"}
{"id": 55943, "name": "Verify distribution uniformity_Chi-squared test", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n"}
{"id": 55944, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n"}
{"id": 55945, "name": "Welch's t-test", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\ndouble Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {\n\tif (ARRAY1_SIZE <= 1) {\n\t\treturn 1.0;\n\t} else if (ARRAY2_SIZE <= 1) {\n\t\treturn 1.0;\n\t}\n\tdouble fmean1 = 0.0, fmean2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tif (isfinite(ARRAY1[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 1st array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean1 += ARRAY1[x];\n\t}\n\tfmean1 /= ARRAY1_SIZE;\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tif (isfinite(ARRAY2[x]) == 0) {\n\t\t\tputs(\"Got a non-finite number in 2nd array, can't calculate P-value.\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfmean2 += ARRAY2[x];\n\t}\n\tfmean2 /= ARRAY2_SIZE;\n\n\tif (fmean1 == fmean2) {\n\t\treturn 1.0;\n\t}\n\tdouble unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0;\n\tfor (size_t x = 0; x < ARRAY1_SIZE; x++) {\n\t\tunbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1);\n\t}\n\tfor (size_t x = 0; x < ARRAY2_SIZE; x++) {\n\t\tunbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2);\n\t}\n\n\tunbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1);\n\tunbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1);\n\tconst double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE);\n\tconst double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0)\n\t /\n\t(\n\t\t(unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+\n\t\t(unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1))\n\t);\n\n\t\tconst double a = DEGREES_OF_FREEDOM/2;\n\tdouble value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM);\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\tif ((isinf(value) != 0) || (isnan(value) != 0)) {\n\t\treturn 1.0;\n\t}\n\n\n\tconst double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5);\n\tconst double acu = 0.1E-14;\n  double ai;\n  double cx;\n  int indx;\n  int ns;\n  double pp;\n  double psq;\n  double qq;\n  double rx;\n  double temp;\n  double term;\n  double xx;\n\n\n\n  if ( (a <= 0.0)) {\n\n\n  }\n  if ( value < 0.0 || 1.0 < value )\n  {\n\n    return value;\n  }\n\n  if ( value == 0.0 || value == 1.0 )   {\n    return value;\n  }\n  psq = a + 0.5;\n  cx = 1.0 - value;\n\n  if ( a < psq * value )\n  {\n    xx = cx;\n    cx = value;\n    pp = 0.5;\n    qq = a;\n    indx = 1;\n  }\n  else\n  {\n    xx = value;\n    pp = a;\n    qq = 0.5;\n    indx = 0;\n  }\n\n  term = 1.0;\n  ai = 1.0;\n  value = 1.0;\n  ns = ( int ) ( qq + cx * psq );\n\n  rx = xx / cx;\n  temp = qq - ai;\n  if ( ns == 0 )\n  {\n    rx = xx;\n  }\n\n  for ( ; ; )\n  {\n    term = term * temp * rx / ( pp + ai );\n    value = value + term;;\n    temp = fabs ( term );\n\n    if ( temp <= acu && temp <= acu * value )\n    {\n      value = value * exp ( pp * log ( xx ) \n      + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n      if ( indx )\n      {\n        value = 1.0 - value;\n      }\n      break;\n    }\n\n    ai = ai + 1.0;\n    ns = ns - 1;\n\n    if ( 0 <= ns )\n    {\n      temp = qq - ai;\n      if ( ns == 0 )\n      {\n        rx = xx;\n      }\n    }\n    else\n    {\n      temp = psq;\n      psq = psq + 1.0;\n    }\n  }\n  return value;\n}\n\nint main(void) {\n\n\tconst double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4};\n\tconst double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4};\n\tconst double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8};\n\tconst double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8};\n\tconst double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0};\n\tconst double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2};\n\tconst double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99};\n\tconst double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98};\n\tconst double x[] = {3.0,4.0,1.0,2.1};\n\tconst double y[] = {490.2,340.0,433.9};\n\tconst double v1[] = {0.010268,0.000167,0.000167};\n\tconst double v2[] = {0.159258,0.136278,0.122389};\n\tconst double s1[] = {1.0/15,10.0/62.0};\n\tconst double s2[] = {1.0/10,2/50.0};\n\tconst double z1[] = {9/23.0,21/45.0,0/38.0};\n\tconst double z2[] = {0/44.0,42/94.0,0/22.0};\n\t\n\tconst double CORRECT_ANSWERS[] = {0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794};\n\n\n\n\tdouble pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2));\n\tdouble error = fabs(pvalue - CORRECT_ANSWERS[0]);\n\tprintf(\"Test sets 1 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4));\n\terror += fabs(pvalue - CORRECT_ANSWERS[1]);\n\tprintf(\"Test sets 2 p-value = %g\\n\",pvalue);\n\n\tpvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6));\n\terror += fabs(pvalue - CORRECT_ANSWERS[2]);\n\tprintf(\"Test sets 3 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8));\n\tprintf(\"Test sets 4 p-value = %g\\n\", pvalue);\n\terror += fabs(pvalue - CORRECT_ANSWERS[3]);\n\n\tpvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y));\n\terror += fabs(pvalue - CORRECT_ANSWERS[4]);\n\tprintf(\"Test sets 5 p-value = %g\\n\", pvalue);\n\n\tpvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[5]);\n\tprintf(\"Test sets 6 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2));\n\terror += fabs(pvalue - CORRECT_ANSWERS[6]);\n\tprintf(\"Test sets 7 p-value = %g\\n\", pvalue);\n\t\n\tpvalue = Pvalue(z1, 3, z2, 3);\n\terror += fabs(pvalue - CORRECT_ANSWERS[7]);\n\tprintf(\"Test sets z p-value = %g\\n\", pvalue);\n\n\tprintf(\"the cumulative error is %g\\n\", error);\n\treturn 0;\n}\n"}
{"id": 55946, "name": "Topological sort_Extracted top item", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n"}
{"id": 55947, "name": "Topological sort_Extracted top item", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n"}
{"id": 55948, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n"}
{"id": 55949, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 55950, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 55951, "name": "Call a function", "Java": "foo();             \nInt x = bar();     \n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 55952, "name": "Superpermutation minimisation", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55953, "name": "GUI component interaction", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n"}
{"id": 55954, "name": "One of n lines in a file", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 55955, "name": "Summarize and say sequence", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 55956, "name": "Spelling of ordinal numbers", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 55957, "name": "Self-describing numbers", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 55958, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 55959, "name": "Numeric separator syntax", "Java": "public class NumericSeparatorSyntax {\n\n    public static void main(String[] args) {\n        runTask(\"Underscore allowed as seperator\", 1_000);\n        runTask(\"Multiple consecutive underscores allowed:\", 1__0_0_0);\n        runTask(\"Many multiple consecutive underscores allowed:\", 1________________________00);\n        runTask(\"Underscores allowed in multiple positions\", 1__4__4);\n        runTask(\"Underscores allowed in negative number\", -1__4__4);\n        runTask(\"Underscores allowed in floating point number\", 1__4__4e-5);\n        runTask(\"Underscores allowed in floating point exponent\", 1__4__440000e-1_2);\n        \n        \n        \n        \n    }\n    \n    private static void runTask(String description, long n) {\n        runTask(description, n, \"%d\");\n    }\n\n    private static void runTask(String description, double n) {\n        runTask(description, n, \"%3.7f\");\n    }\n\n    private static void runTask(String description, Number n, String format) {\n        System.out.printf(\"%s:  \" + format + \"%n\", description, n);\n    }\n\n}\n", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n"}
{"id": 55960, "name": "Repeat", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 55961, "name": "Sparkline in unicode", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 55962, "name": "Compiler_AST interpreter", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 55963, "name": "Compiler_AST interpreter", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 55964, "name": "Compiler_AST interpreter", "Java": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map<String, Integer> globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List<Node> list = new ArrayList<>();\n\tstatic Map<String, NodeType> str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; \n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 55965, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 55966, "name": "Simulate input_Mouse", "Java": "Point p = component.getLocation();\nRobot robot = new Robot();\nrobot.mouseMove(p.getX(), p.getY()); \nrobot.mousePress(InputEvent.BUTTON1_MASK); \n                                       \nrobot.mouseRelease(InputEvent.BUTTON1_MASK);\n", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n"}
{"id": 55967, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 55968, "name": "Terminal control_Clear the screen", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n", "C": "void cls(void) {\n    printf(\"\\33[2J\");\n}\n"}
{"id": 55969, "name": "Sunflower fractal", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 55970, "name": "Vogel's approximation method", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 55971, "name": "Air mass", "Java": "public class AirMass {\n    public static void main(String[] args) {\n        System.out.println(\"Angle     0 m              13700 m\");\n        System.out.println(\"------------------------------------\");\n        for (double z = 0; z <= 90; z+= 5) {\n            System.out.printf(\"%2.0f      %11.8f      %11.8f\\n\",\n                            z, airmass(0.0, z), airmass(13700.0, z));\n        }\n    }\n\n    private static double rho(double a) {\n        \n        return Math.exp(-a / 8500.0);\n    }\n\n    private static double height(double a, double z, double d) {\n        \n        \n        \n        double aa = RE + a;\n        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));\n        return hh - RE;\n    }\n\n    private static double columnDensity(double a, double z) {\n        \n        double sum = 0.0, d = 0.0;\n        while (d < FIN) {\n            \n            double delta = Math.max(DD * d, DD);\n            sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n            d += delta;\n        }\n        return sum;\n    }\n     \n    private static double airmass(double a, double z) {\n        return columnDensity(a, z) / columnDensity(a, 0.0);\n    }\n\n    private static final double RE = 6371000.0; \n    private static final double DD = 0.001; \n    private static final double FIN = 10000000.0; \n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\n#define DEG 0.017453292519943295769236907684886127134  \n#define RE 6371000.0 \n#define DD 0.001 \n#define FIN 10000000.0 \n\nstatic double rho(double a) {\n    \n    return exp(-a / 8500.0);\n}\n\nstatic double height(double a, double z, double d) {\n    \n    \n    \n    double aa = RE + a;\n    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));\n    return hh - RE;\n}\n\nstatic double column_density(double a, double z) {\n    \n    double sum = 0.0, d = 0.0;\n    while (d < FIN) {\n        \n        double delta = DD * d;\n        if (delta < DD)\n            delta = DD;\n        sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n        d += delta;\n    }\n    return sum;\n}\n\nstatic double airmass(double a, double z) {\n    return column_density(a, z) / column_density(a, 0.0);\n}\n\nint main() {\n    puts(\"Angle     0 m              13700 m\");\n    puts(\"------------------------------------\");\n    for (double z = 0; z <= 90; z+= 5) {\n        printf(\"%2.0f      %11.8f      %11.8f\\n\",\n               z, airmass(0.0, z), airmass(13700.0, z));\n    }\n}\n"}
{"id": 55972, "name": "Sorting algorithms_Pancake sort", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n"}
{"id": 55973, "name": "Sorting algorithms_Pancake sort", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n"}
{"id": 55974, "name": "Active Directory_Connect", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n"}
{"id": 55975, "name": "Permutations by swapping", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n"}
{"id": 55976, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 55977, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 55978, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 55979, "name": "Update a configuration file", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 55980, "name": "Image convolution", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class ImageConvolution\n{\n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n  }\n  \n  private static int bound(int value, int endIndex)\n  {\n    if (value < 0)\n      return 0;\n    if (value < endIndex)\n      return value;\n    return endIndex - 1;\n  }\n  \n  public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)\n  {\n    int inputWidth = inputData.width;\n    int inputHeight = inputData.height;\n    int kernelWidth = kernel.width;\n    int kernelHeight = kernel.height;\n    if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd width\");\n    if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd height\");\n    int kernelWidthRadius = kernelWidth >>> 1;\n    int kernelHeightRadius = kernelHeight >>> 1;\n    \n    ArrayData outputData = new ArrayData(inputWidth, inputHeight);\n    for (int i = inputWidth - 1; i >= 0; i--)\n    {\n      for (int j = inputHeight - 1; j >= 0; j--)\n      {\n        double newValue = 0.0;\n        for (int kw = kernelWidth - 1; kw >= 0; kw--)\n          for (int kh = kernelHeight - 1; kh >= 0; kh--)\n            newValue += kernel.get(kw, kh) * inputData.get(\n                          bound(i + kw - kernelWidthRadius, inputWidth),\n                          bound(j + kh - kernelHeightRadius, inputHeight));\n        outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));\n      }\n    }\n    return outputData;\n  }\n  \n  public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData reds = new ArrayData(width, height);\n    ArrayData greens = new ArrayData(width, height);\n    ArrayData blues = new ArrayData(width, height);\n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        reds.set(x, y, (rgbValue >>> 16) & 0xFF);\n        greens.set(x, y, (rgbValue >>> 8) & 0xFF);\n        blues.set(x, y, rgbValue & 0xFF);\n      }\n    }\n    return new ArrayData[] { reds, greens, blues };\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException\n  {\n    ArrayData reds = redGreenBlue[0];\n    ArrayData greens = redGreenBlue[1];\n    ArrayData blues = redGreenBlue[2];\n    BufferedImage outputImage = new BufferedImage(reds.width, reds.height,\n                                                  BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < reds.height; y++)\n    {\n      for (int x = 0; x < reds.width; x++)\n      {\n        int red = bound(reds.get(x, y), 256);\n        int green = bound(greens.get(x, y), 256);\n        int blue = bound(blues.get(x, y), 256);\n        outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    int kernelWidth = Integer.parseInt(args[2]);\n    int kernelHeight = Integer.parseInt(args[3]);\n    int kernelDivisor = Integer.parseInt(args[4]);\n    System.out.println(\"Kernel size: \" + kernelWidth + \"x\" + kernelHeight +\n                       \", divisor=\" + kernelDivisor);\n    int y = 5;\n    ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);\n    for (int i = 0; i < kernelHeight; i++)\n    {\n      System.out.print(\"[\");\n      for (int j = 0; j < kernelWidth; j++)\n      {\n        kernel.set(j, i, Integer.parseInt(args[y++]));\n        System.out.print(\" \" + kernel.get(j, i) + \" \");\n      }\n      System.out.println(\"]\");\n    }\n    \n    ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);\n    for (int i = 0; i < dataArrays.length; i++)\n      dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);\n    writeOutputImage(args[1], dataArrays);\n    return;\n  }\n}\n", "C": "image filter(image img, double *K, int Ks, double, double);\n"}
{"id": 55981, "name": "Dice game probabilities", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n"}
{"id": 55982, "name": "Plasma effect", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n"}
{"id": 55983, "name": "WiktionaryDumps to words", "Java": "import org.xml.sax.*;\nimport org.xml.sax.helpers.DefaultHandler;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nclass MyHandler extends DefaultHandler {\n    private static final String TITLE = \"title\";\n    private static final String TEXT = \"text\";\n\n    private String lastTag = \"\";\n    private String title = \"\";\n\n    @Override\n    public void characters(char[] ch, int start, int length) throws SAXException {\n        String regex = \".*==French==.*\";\n        Pattern pat = Pattern.compile(regex, Pattern.DOTALL);\n\n        switch (lastTag) {\n            case TITLE:\n                title = new String(ch, start, length);\n                break;\n            case TEXT:\n                String text = new String(ch, start, length);\n                Matcher mat = pat.matcher(text);\n                if (mat.matches()) {\n                    System.out.println(title);\n                }\n                break;\n        }\n    }\n\n    @Override\n    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n        lastTag = qName;\n    }\n\n    @Override\n    public void endElement(String uri, String localName, String qName) throws SAXException {\n        lastTag = \"\";\n    }\n}\n\npublic class WiktoWords {\n    public static void main(java.lang.String[] args) {\n        try {\n            SAXParserFactory spFactory = SAXParserFactory.newInstance();\n            SAXParser saxParser = spFactory.newSAXParser();\n            MyHandler handler = new MyHandler();\n            saxParser.parse(new InputSource(System.in), handler);\n        } catch(Exception e) {\n            System.exit(1);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <expat.h>\n#include <pcre.h>\n\n#ifdef XML_LARGE_SIZE\n#  define XML_FMT_INT_MOD \"ll\"\n#else\n#  define XML_FMT_INT_MOD \"l\"\n#endif\n\n#ifdef XML_UNICODE_WCHAR_T\n#  define XML_FMT_STR \"ls\"\n#else\n#  define XML_FMT_STR \"s\"\n#endif\n\nvoid reset_char_data_buffer();\nvoid process_char_data_buffer();\n\nstatic bool last_tag_is_title;\nstatic bool last_tag_is_text;\n\nstatic pcre *reCompiled;\nstatic pcre_extra *pcreExtra;\n\n\nvoid start_element(void *data, const char *element, const char **attribute) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n\n    if (strcmp(\"title\", element) == 0) {\n        last_tag_is_title = true;\n    }\n    if (strcmp(\"text\", element) == 0) {\n        last_tag_is_text = true;\n    }\n}\n\nvoid end_element(void *data, const char *el) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n}\n\n\n#define TITLE_BUF_SIZE (1024 * 8)\n\nstatic char char_data_buffer[1024 * 64 * 8];\nstatic char title_buffer[TITLE_BUF_SIZE];\nstatic size_t offs;\nstatic bool overflow;\n\n\nvoid reset_char_data_buffer(void) {\n    offs = 0;\n    overflow = false;\n}\n\n\nvoid char_data(void *userData, const XML_Char *s, int len) {\n    if (!overflow) {\n        if (len + offs >= sizeof(char_data_buffer)) {\n            overflow = true;\n            fprintf(stderr, \"Warning: buffer overflow\\n\");\n            fflush(stderr);\n        } else {\n            memcpy(char_data_buffer + offs, s, len);\n            offs += len;\n        }\n    }\n}\n\nvoid try_match();\n\n\nvoid process_char_data_buffer(void) {\n    if (offs > 0) {\n        char_data_buffer[offs] = '\\0';\n\n        if (last_tag_is_title) {\n            unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1);\n            memcpy(title_buffer, char_data_buffer, n);\n            last_tag_is_title = false;\n        }\n        if (last_tag_is_text) {\n            try_match();\n            last_tag_is_text = false;\n        }\n    }\n}\n\nvoid try_match()\n{\n    int subStrVec[80];\n    int subStrVecLen;\n    int pcreExecRet;\n    subStrVecLen = sizeof(subStrVec) / sizeof(int);\n\n    pcreExecRet = pcre_exec(\n            reCompiled, pcreExtra,\n            char_data_buffer, strlen(char_data_buffer),\n            0, 0,\n            subStrVec, subStrVecLen);\n\n    if (pcreExecRet < 0) {\n        switch (pcreExecRet) {\n            case PCRE_ERROR_NOMATCH      : break;\n            case PCRE_ERROR_NULL         : fprintf(stderr, \"Something was null\\n\");                      break;\n            case PCRE_ERROR_BADOPTION    : fprintf(stderr, \"A bad option was passed\\n\");                 break;\n            case PCRE_ERROR_BADMAGIC     : fprintf(stderr, \"Magic number bad (compiled re corrupt?)\\n\"); break;\n            case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, \"Something kooky in the compiled re\\n\");      break;\n            case PCRE_ERROR_NOMEMORY     : fprintf(stderr, \"Ran out of memory\\n\");                       break;\n            default                      : fprintf(stderr, \"Unknown error\\n\");                           break;\n        }\n    } else {\n        puts(title_buffer);  \n    }\n}\n\n\n#define BUF_SIZE 1024\n\nint main(int argc, char *argv[])\n{\n    char buffer[BUF_SIZE];\n    int n;\n\n    const char *pcreErrorStr;\n    int pcreErrorOffset;\n    char *aStrRegex;\n    char **aLineToMatch;\n\n    \n\n    aStrRegex = \"(.*)(==French==)(.*)\";  \n\n    reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL);\n    if (reCompiled == NULL) {\n        fprintf(stderr, \"ERROR: Could not compile regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr);\n    if (pcreErrorStr != NULL) {\n        fprintf(stderr, \"ERROR: Could not study regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    \n\n    XML_Parser parser = XML_ParserCreate(NULL);\n\n    XML_SetElementHandler(parser, start_element, end_element);\n    XML_SetCharacterDataHandler(parser, char_data);\n\n    reset_char_data_buffer();\n\n    while (1) {\n        int done;\n        int len;\n\n        len = (int)fread(buffer, 1, BUF_SIZE, stdin);\n        if (ferror(stdin)) {\n            fprintf(stderr, \"Read error\\n\");\n            exit(1);\n        }\n        done = feof(stdin);\n\n        if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) {\n            fprintf(stderr,\n                \"Parse error at line %\" XML_FMT_INT_MOD \"u:\\n%\" XML_FMT_STR \"\\n\",\n                XML_GetCurrentLineNumber(parser),\n                XML_ErrorString(XML_GetErrorCode(parser)));\n            exit(1);\n        }\n\n        if (done) break;\n    }\n\n    XML_ParserFree(parser);\n\n    pcre_free(reCompiled);\n\n    if (pcreExtra != NULL) {\n#ifdef PCRE_CONFIG_JIT\n        pcre_free_study(pcreExtra);\n#else\n        pcre_free(pcreExtra);\n#endif\n    }\n\n    return 0;\n}\n"}
{"id": 55984, "name": "WiktionaryDumps to words", "Java": "import org.xml.sax.*;\nimport org.xml.sax.helpers.DefaultHandler;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nclass MyHandler extends DefaultHandler {\n    private static final String TITLE = \"title\";\n    private static final String TEXT = \"text\";\n\n    private String lastTag = \"\";\n    private String title = \"\";\n\n    @Override\n    public void characters(char[] ch, int start, int length) throws SAXException {\n        String regex = \".*==French==.*\";\n        Pattern pat = Pattern.compile(regex, Pattern.DOTALL);\n\n        switch (lastTag) {\n            case TITLE:\n                title = new String(ch, start, length);\n                break;\n            case TEXT:\n                String text = new String(ch, start, length);\n                Matcher mat = pat.matcher(text);\n                if (mat.matches()) {\n                    System.out.println(title);\n                }\n                break;\n        }\n    }\n\n    @Override\n    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n        lastTag = qName;\n    }\n\n    @Override\n    public void endElement(String uri, String localName, String qName) throws SAXException {\n        lastTag = \"\";\n    }\n}\n\npublic class WiktoWords {\n    public static void main(java.lang.String[] args) {\n        try {\n            SAXParserFactory spFactory = SAXParserFactory.newInstance();\n            SAXParser saxParser = spFactory.newSAXParser();\n            MyHandler handler = new MyHandler();\n            saxParser.parse(new InputSource(System.in), handler);\n        } catch(Exception e) {\n            System.exit(1);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <expat.h>\n#include <pcre.h>\n\n#ifdef XML_LARGE_SIZE\n#  define XML_FMT_INT_MOD \"ll\"\n#else\n#  define XML_FMT_INT_MOD \"l\"\n#endif\n\n#ifdef XML_UNICODE_WCHAR_T\n#  define XML_FMT_STR \"ls\"\n#else\n#  define XML_FMT_STR \"s\"\n#endif\n\nvoid reset_char_data_buffer();\nvoid process_char_data_buffer();\n\nstatic bool last_tag_is_title;\nstatic bool last_tag_is_text;\n\nstatic pcre *reCompiled;\nstatic pcre_extra *pcreExtra;\n\n\nvoid start_element(void *data, const char *element, const char **attribute) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n\n    if (strcmp(\"title\", element) == 0) {\n        last_tag_is_title = true;\n    }\n    if (strcmp(\"text\", element) == 0) {\n        last_tag_is_text = true;\n    }\n}\n\nvoid end_element(void *data, const char *el) {\n    process_char_data_buffer();\n    reset_char_data_buffer();\n}\n\n\n#define TITLE_BUF_SIZE (1024 * 8)\n\nstatic char char_data_buffer[1024 * 64 * 8];\nstatic char title_buffer[TITLE_BUF_SIZE];\nstatic size_t offs;\nstatic bool overflow;\n\n\nvoid reset_char_data_buffer(void) {\n    offs = 0;\n    overflow = false;\n}\n\n\nvoid char_data(void *userData, const XML_Char *s, int len) {\n    if (!overflow) {\n        if (len + offs >= sizeof(char_data_buffer)) {\n            overflow = true;\n            fprintf(stderr, \"Warning: buffer overflow\\n\");\n            fflush(stderr);\n        } else {\n            memcpy(char_data_buffer + offs, s, len);\n            offs += len;\n        }\n    }\n}\n\nvoid try_match();\n\n\nvoid process_char_data_buffer(void) {\n    if (offs > 0) {\n        char_data_buffer[offs] = '\\0';\n\n        if (last_tag_is_title) {\n            unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1);\n            memcpy(title_buffer, char_data_buffer, n);\n            last_tag_is_title = false;\n        }\n        if (last_tag_is_text) {\n            try_match();\n            last_tag_is_text = false;\n        }\n    }\n}\n\nvoid try_match()\n{\n    int subStrVec[80];\n    int subStrVecLen;\n    int pcreExecRet;\n    subStrVecLen = sizeof(subStrVec) / sizeof(int);\n\n    pcreExecRet = pcre_exec(\n            reCompiled, pcreExtra,\n            char_data_buffer, strlen(char_data_buffer),\n            0, 0,\n            subStrVec, subStrVecLen);\n\n    if (pcreExecRet < 0) {\n        switch (pcreExecRet) {\n            case PCRE_ERROR_NOMATCH      : break;\n            case PCRE_ERROR_NULL         : fprintf(stderr, \"Something was null\\n\");                      break;\n            case PCRE_ERROR_BADOPTION    : fprintf(stderr, \"A bad option was passed\\n\");                 break;\n            case PCRE_ERROR_BADMAGIC     : fprintf(stderr, \"Magic number bad (compiled re corrupt?)\\n\"); break;\n            case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, \"Something kooky in the compiled re\\n\");      break;\n            case PCRE_ERROR_NOMEMORY     : fprintf(stderr, \"Ran out of memory\\n\");                       break;\n            default                      : fprintf(stderr, \"Unknown error\\n\");                           break;\n        }\n    } else {\n        puts(title_buffer);  \n    }\n}\n\n\n#define BUF_SIZE 1024\n\nint main(int argc, char *argv[])\n{\n    char buffer[BUF_SIZE];\n    int n;\n\n    const char *pcreErrorStr;\n    int pcreErrorOffset;\n    char *aStrRegex;\n    char **aLineToMatch;\n\n    \n\n    aStrRegex = \"(.*)(==French==)(.*)\";  \n\n    reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL);\n    if (reCompiled == NULL) {\n        fprintf(stderr, \"ERROR: Could not compile regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr);\n    if (pcreErrorStr != NULL) {\n        fprintf(stderr, \"ERROR: Could not study regex '%s': %s\\n\", aStrRegex, pcreErrorStr);\n        exit(1);\n    }\n\n    \n\n    XML_Parser parser = XML_ParserCreate(NULL);\n\n    XML_SetElementHandler(parser, start_element, end_element);\n    XML_SetCharacterDataHandler(parser, char_data);\n\n    reset_char_data_buffer();\n\n    while (1) {\n        int done;\n        int len;\n\n        len = (int)fread(buffer, 1, BUF_SIZE, stdin);\n        if (ferror(stdin)) {\n            fprintf(stderr, \"Read error\\n\");\n            exit(1);\n        }\n        done = feof(stdin);\n\n        if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) {\n            fprintf(stderr,\n                \"Parse error at line %\" XML_FMT_INT_MOD \"u:\\n%\" XML_FMT_STR \"\\n\",\n                XML_GetCurrentLineNumber(parser),\n                XML_ErrorString(XML_GetErrorCode(parser)));\n            exit(1);\n        }\n\n        if (done) break;\n    }\n\n    XML_ParserFree(parser);\n\n    pcre_free(reCompiled);\n\n    if (pcreExtra != NULL) {\n#ifdef PCRE_CONFIG_JIT\n        pcre_free_study(pcreExtra);\n#else\n        pcre_free(pcreExtra);\n#endif\n    }\n\n    return 0;\n}\n"}
{"id": 55985, "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": 55986, "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", "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": 55987, "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", "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": 55988, "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", "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": 55989, "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", "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": 55990, "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", "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": 55991, "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", "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": 55992, "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", "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": 55993, "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", "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": 55994, "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", "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": 55995, "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", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 55996, "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", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n"}
{"id": 55997, "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", "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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 55998, "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", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n"}
{"id": 55999, "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", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 56000, "name": "Chinese remainder theorem", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\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": 56001, "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", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 56002, "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", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 56003, "name": "Van Eck sequence", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\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": 56004, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56005, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 56006, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 56007, "name": "Checkpoint synchronization", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n"}
{"id": 56008, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n"}
{"id": 56009, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 56010, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 56011, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 56012, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 56013, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 56014, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 56015, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 56016, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "C++": "#include <stack>\n"}
{"id": 56017, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56018, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 56019, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 56020, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n"}
{"id": 56021, "name": "Sorting algorithms_Radix sort", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n"}
{"id": 56022, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n"}
{"id": 56023, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 56024, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 56025, "name": "Singleton", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 56026, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n"}
{"id": 56027, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 56028, "name": "Write entire file", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 56029, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 56030, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 56031, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n"}
{"id": 56032, "name": "Roots of unity", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 56033, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 56034, "name": "Pell's equation", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 56035, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 56036, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 56037, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 56038, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 56039, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 56040, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 56041, "name": "Man or boy test", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n"}
{"id": 56042, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n"}
{"id": 56043, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 56044, "name": "Find limit of recursion", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 56045, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 56046, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 56047, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 56048, "name": "Inverted index", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n"}
{"id": 56049, "name": "Least common multiple", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 56050, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 56051, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 56052, "name": "Water collected between towers", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 56053, "name": "Descending primes", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n"}
{"id": 56054, "name": "Descending primes", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n"}
{"id": 56055, "name": "Sum and product puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n"}
{"id": 56056, "name": "Parsing_Shunting-yard algorithm", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 56057, "name": "Middle three digits", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 56058, "name": "Stern-Brocot sequence", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 56059, "name": "FASTA format", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n"}
{"id": 56060, "name": "Literals_String", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n"}
{"id": 56061, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 56062, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56063, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56064, "name": "A_ search algorithm", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56065, "name": "Range extraction", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 56066, "name": "Type detection", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 56067, "name": "Type detection", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 56068, "name": "Maximum triangle path sum", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n"}
{"id": 56069, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 56070, "name": "Unix_ls", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 56071, "name": "Magic squares of doubly even order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n"}
{"id": 56072, "name": "Same fringe", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n"}
{"id": 56073, "name": "Peaceful chess queen armies", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 56074, "name": "Move-to-front algorithm", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 56075, "name": "Sum of first n cubes", "C#": "using System; using static System.Console;\nclass Program { static void Main(string[] args) {\n    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)\n      Write(\"{0,-7}{1}\",s, (i+=i==3?-4:1)==0?\"\\n\":\" \"); } }\n", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 56076, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "C++": "system(\"pause\");\n"}
{"id": 56077, "name": "Longest increasing subsequence", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 56078, "name": "Brace expansion", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 56079, "name": "GUI component interaction", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n"}
{"id": 56080, "name": "One of n lines in a file", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 56081, "name": "Addition chains", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 56082, "name": "Repeat", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 56083, "name": "Modular inverse", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 56084, "name": "Chemical calculator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56085, "name": "Pythagorean quadruples", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 56086, "name": "Zebra puzzle", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n", "C++": "#include <stdio.h>\n#include <string.h>\n\n#define defenum(name, val0, val1, val2, val3, val4) \\\n    enum name { val0, val1, val2, val3, val4 }; \\\n    const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }\n\ndefenum( Attrib,    Color, Man, Drink, Animal, Smoke );\ndefenum( Colors,    Red, Green, White, Yellow, Blue );\ndefenum( Mans,      English, Swede, Dane, German, Norwegian );\ndefenum( Drinks,    Tea, Coffee, Milk, Beer, Water );\ndefenum( Animals,   Dog, Birds, Cats, Horse, Zebra );\ndefenum( Smokes,    PallMall, Dunhill, Blend, BlueMaster, Prince );\n\nvoid printHouses(int ha[5][5]) {\n    const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};\n\n    printf(\"%-10s\", \"House\");\n    for (const char *name : Attrib_str) printf(\"%-10s\", name);\n    printf(\"\\n\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        for (int j = 0; j < 5; j++) printf(\"%-10s\", attr_names[j][ha[i][j]]);\n        printf(\"\\n\");\n    }\n}\n\nstruct HouseNoRule {\n    int houseno;\n    Attrib a; int v;\n} housenos[] = {\n    {2, Drink, Milk},     \n    {0, Man, Norwegian}   \n};\n\nstruct AttrPairRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&\n               ((ha[i][a1] == v1 && ha[i][a2] != v2) ||\n                (ha[i][a1] != v1 && ha[i][a2] == v2));\n    }\n} pairs[] = {\n    {Man, English,      Color, Red},     \n    {Man, Swede,        Animal, Dog},    \n    {Man, Dane,         Drink, Tea},     \n    {Color, Green,      Drink, Coffee},  \n    {Smoke, PallMall,   Animal, Birds},  \n    {Smoke, Dunhill,    Color, Yellow},  \n    {Smoke, BlueMaster, Drink, Beer},    \n    {Man, German,       Smoke, Prince}    \n};\n\nstruct NextToRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] == v1) &&\n               ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||\n                (i == 4 && ha[i - 1][a2] != v2) ||\n                (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));\n    }\n} nexttos[] = {\n    {Smoke, Blend,      Animal, Cats},    \n    {Smoke, Dunhill,    Animal, Horse},   \n    {Man, Norwegian,    Color, Blue},     \n    {Smoke, Blend,      Drink, Water}     \n};\n\nstruct LeftOfRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5]) {\n        return (ha[0][a2] == v2) || (ha[4][a1] == v1);\n    }\n\n    bool invalid(int ha[5][5], int i) {\n        return ((i > 0 && ha[i][a1] >= 0) &&\n                ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||\n                 (ha[i - 1][a1] != v1 && ha[i][a2] == v2)));\n    }\n} leftofs[] = {\n    {Color, Green,  Color, White}     \n};\n\nbool invalid(int ha[5][5]) {\n    for (auto &rule : leftofs) if (rule.invalid(ha)) return true;\n\n    for (int i = 0; i < 5; i++) {\n#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;\n        eval_rules(pairs);\n        eval_rules(nexttos);\n        eval_rules(leftofs);\n    }\n    return false;\n}\n\nvoid search(bool used[5][5], int ha[5][5], const int hno, const int attr) {\n    int nexthno, nextattr;\n    if (attr < 4) {\n        nextattr = attr + 1;\n        nexthno = hno;\n    } else {\n        nextattr = 0;\n        nexthno = hno + 1;\n    }\n\n    if (ha[hno][attr] != -1) {\n        search(used, ha, nexthno, nextattr);\n    } else {\n        for (int i = 0; i < 5; i++) {\n            if (used[attr][i]) continue;\n            used[attr][i] = true;\n            ha[hno][attr] = i;\n\n            if (!invalid(ha)) {\n                if ((hno == 4) && (attr == 4)) {\n                    printHouses(ha);\n                } else {\n                    search(used, ha, nexthno, nextattr);\n                }\n            }\n\n            used[attr][i] = false;\n        }\n        ha[hno][attr] = -1;\n    }\n}\n\nint main() {\n    bool used[5][5] = {};\n    int ha[5][5]; memset(ha, -1, sizeof(ha));\n\n    for (auto &rule : housenos) {\n        ha[rule.houseno][rule.a] = rule.v;\n        used[rule.a][rule.v] = true;\n    }\n\n    search(used, ha, 0, 0);\n\n    return 0;\n}\n"}
{"id": 56087, "name": "First-class functions_Use numbers analogously", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n"}
{"id": 56088, "name": "First-class functions_Use numbers analogously", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 56089, "name": "Sokoban", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n"}
{"id": 56090, "name": "Almkvist-Giullera formula for pi", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 56091, "name": "Almkvist-Giullera formula for pi", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 56092, "name": "Practical numbers", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n"}
{"id": 56093, "name": "Consecutive primes with ascending or descending differences", "C#": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        const int mil = (int)1e6;\n        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n        {\n            int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n            var desc = new string[] { \"A\", \"\", \"De\" };\n            int[] mx = new int[] { 0, 0, 0 },\n                  bi = new int[] { 0, 0, 0 },\n                   c = new int[] { 2, 2, 2 };\n            WriteLine(\"For primes up to {0:n0}:\", lmt);\n            var pr = PG.Primes(lmt).ToArray();\n            for (int i = 0; i < pr.Length; i++)\n            {\n                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n                if (ld == d)\n                    c[2 - d]++;\n                else\n                {\n                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n                    c[d] = 2;\n                }\n                ld = d; lg = ng;\n            }\n            for (int r = 0; r <= 2; r += 2)\n            {\n                Write(\"{0}scending, found run of {1} consecutive primes:\\n  {2} \",\n                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n                    Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n            }\n        }\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<TG> Primes(int lim)\n    {\n        bool[] flags = new bool[lim + 1];\n        int j = 3, lj = 2;\n        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n            }\n        for (; j <= lim; j += 2)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n            }\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n"}
{"id": 56094, "name": "Literals_Floating point", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n"}
{"id": 56095, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 56096, "name": "Erdős-primes", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 56097, "name": "Solve a Numbrix puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 56098, "name": "Solve a Numbrix puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 56099, "name": "Church numerals", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 56100, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 56101, "name": "Solve a Hopido puzzle", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 56102, "name": "Solve a Hopido puzzle", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56103, "name": "Nonogram solver", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 56104, "name": "Nonogram solver", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 56105, "name": "Word search", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n"}
{"id": 56106, "name": "Break OO privacy", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 56107, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 56108, "name": "Object serialization", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n"}
{"id": 56109, "name": "Eertree", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 56110, "name": "Eertree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 56111, "name": "Long year", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 56112, "name": "Zumkeller numbers", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n"}
{"id": 56113, "name": "Associative array_Merging", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 56114, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 56115, "name": "Metallic ratios", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 56116, "name": "Metallic ratios", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 56117, "name": "Halt and catch fire", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n", "C#": "int a=0,b=1/a;\n"}
{"id": 56118, "name": "Constrained genericity", "C#": "interface IEatable\n{\n    void Eat();\n}\n", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n"}
{"id": 56119, "name": "Markov chain text generator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n"}
{"id": 56120, "name": "Dijkstra's algorithm", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n"}
{"id": 56121, "name": "Geometric algebra", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n"}
{"id": 56122, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 56123, "name": "Suffix tree", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 56124, "name": "Associative array_Iteration", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n"}
{"id": 56125, "name": "Define a primitive data type", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n"}
{"id": 56126, "name": "Solve a Holy Knight's tour", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56127, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 56128, "name": "Solve a Holy Knight's tour", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 56129, "name": "Hash join", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n"}
{"id": 56130, "name": "Odd squarefree semiprimes", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n"}
{"id": 56131, "name": "Odd squarefree semiprimes", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n"}
{"id": 56132, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 56133, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 56134, "name": "Polynomial synthetic division", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 56135, "name": "Respond to an unknown method call", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n"}
{"id": 56136, "name": "Latin Squares in reduced form", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n"}
{"id": 56137, "name": "Closest-pair problem", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n"}
{"id": 56138, "name": "Inheritance_Single", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 56139, "name": "Color wheel", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 56140, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56141, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56142, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 56143, "name": "Kosaraju", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 56144, "name": "Sieve of Pritchard", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program {\n\n    \n    static List<int> PrimesUpTo(int limit, bool verbose = false) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var members = new SortedSet<int>{ 1 };\n        int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1;\n        List<int> primes = new List<int>(), tl = new List<int>();\n        while (prime < rtlim) {\n            nl = Math.Min(prime * stp, limit);\n            if (stp < limit) {\n                tl.Clear(); \n                foreach (var w in members)\n                    for (n = w + stp; n <= nl; n += stp) tl.Add(n);\n                members.UnionWith(tl); ac += tl.Count;\n            }\n            stp = nl; \n            nxtpr = 5; \n            tl.Clear();\n            foreach (var w in members) {\n                if (nxtpr == 5 && w > prime) nxtpr = w;\n                if ((n = prime * w) > nl) break; else tl.Add(n);\n            }\n            foreach (var itm in tl) members.Remove(itm); rc += tl.Count;\n            primes.Add(prime);\n            prime = prime == 2 ? 3 : nxtpr;\n        }\n        members.Remove(1); primes.AddRange(members); sw.Stop();\n        if (verbose) Console.WriteLine(\"Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms\", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds);\n        return primes;\n    }\n\n    static void Main(string[] args) {\n        Console.WriteLine(\"[{0}]\", string.Join(\", \", PrimesUpTo(150, true)));\n        PrimesUpTo(1000000, true);\n    }\n}\n", "C++": "\n\n\n\n#include <cstring>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <ctime>\n\nvoid Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) {\n    \n    uint32_t i, j, x;\n    i = 0; j = w_end;\n    x = length + 1; \n    while (x <= n) {\n        w[++j] = x; \n        d[x] = false;\n        x = length + w[++i];\n    }\n    length = n; w_end = j;\n    if (w_end > w_end_max) w_end_max = w_end;\n}\n\nvoid Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) {\n    \n    uint32_t i, x;\n    i = 0;\n    x = p; \n    while (x <= length) {\n        d[x] = true; \n        x = p*w[++i];\n    }\n    imaxf = i-1;\n}\n\nvoid Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) {\n    \n    uint32_t i, j;\n    j = 0;\n    for (i=1; i <= to; i++) {\n        if (!d[w[i]]) {\n            w[++j] = w[i];\n        }\n    }\n    if (to == w_end) {\n        w_end = j;\n    } else {\n        for (uint32_t k=j+1; k <= to; k++) w[k] = 0;\n    }\n}\n\nvoid Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) {\n    \n    uint32_t *w = new uint32_t[N/4+5];\n    bool *d = new bool[N+1];\n    uint32_t w_end, length;\n    \n    \n    \n    \n    uint32_t w_end_max, p, imaxf;\n    \n    w_end = 0; w[0] = 1;\n    w_end_max = 0;\n    length = 2;\n    \n    nrPrimes = 1;\n    if (printPrimes) printf(\"%d\", 2);\n    p = 3;\n    \n    \n    while (p*p <= N) {\n        \n        nrPrimes++;\n        if (printPrimes) printf(\" %d\", p);\n        if (length < N) {\n            \n            Extend (w, w_end, length, std::min(p*length,N), d, w_end_max);\n        }\n        Delete(w, length, p, d, imaxf);\n        Compress(w, d, (length < N ? w_end : imaxf), w_end);\n        \n        p = w[1];\n        if (p == 0) break; \n        \n    }\n    if (length < N) {\n        \n        Extend (w, w_end, length, N, d, w_end_max);\n    }\n    \n    for (uint32_t i=1; i <= w_end; i++) {\n        if (w[i] == 0 || d[w[i]]) continue;\n        if (printPrimes) printf(\" %d\", w[i]);\n        nrPrimes++;\n    }\n    vBound = w_end_max+1;\n}\n\nint main (int argc, char *argw[]) {\n    bool error = false;\n    bool printPrimes = false;\n    uint32_t N, nrPrimes, vBound;\n    if (argc == 3) {\n        if (strcmp(argw[2], \"-p\") == 0) {\n            printPrimes = true;\n            argc--;\n        } else {\n            error = true;\n        }\n    }\n    if (argc == 2) {\n        N = atoi(argw[1]);\n        if (N < 2 || N > 1000000000) error = true;\n    } else {\n        error = true;\n    }\n    if (error) {\n        printf(\"call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \\n\", argw[0]);\n        exit(1);\n    }\n    int start_s = clock();\n    Sift(N, printPrimes, nrPrimes, vBound);\n    int stop_s=clock();\n    printf(\"\\n%d primes up to %lu found in %.3f ms using array w[%d]\\n\", nrPrimes,\n      (unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound);\n}\n"}
{"id": 56145, "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": 56146, "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 <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 56147, "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++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\n}\n"}
{"id": 56148, "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++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n"}
{"id": 56149, "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 <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 1);\n    return 0;\n}\n"}
{"id": 56150, "name": "Extensible prime generator", "Python": "islice(count(7), 0, None, 2)\n", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56151, "name": "Extensible prime generator", "Python": "islice(count(7), 0, None, 2)\n", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56152, "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 <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\n\n"}
{"id": 56153, "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 <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n"}
{"id": 56154, "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++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 56155, "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++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 56156, "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 <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\n}\n"}
{"id": 56157, "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 <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 56158, "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 <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 56159, "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 <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 56160, "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", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 56161, "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", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 56162, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n"}
{"id": 56163, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56164, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56165, "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", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56166, "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", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 56167, "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", "C++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 56168, "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", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 56169, "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", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 56170, "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", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 56171, "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", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 56172, "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", "C++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 56173, "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", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\n}\n"}
{"id": 56174, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 56175, "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", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 56176, "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", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 56177, "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", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 56178, "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", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 56179, "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", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 56180, "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", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 56181, "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", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n"}
{"id": 56182, "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", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n"}
{"id": 56183, "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", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\nusing namespace std;\n\nclass recorder\n{\npublic:\n    void start()\n    {\n\tpaused = rec = false; action = \"IDLE\";\n\twhile( true )\n\t{\n\t    cout << endl << \"==\" << action << \"==\" << endl << endl;\n\t    cout << \"1) Record\" << endl << \"2) Play\" << endl << \"3) Pause\" << endl << \"4) Stop\" << endl << \"5) Quit\" << endl;\n\t    char c; cin >> c;\n\t    if( c > '0' && c < '6' )\n\t    {\n\t\tswitch( c )\n\t\t{\n\t\t    case '1': record(); break;\n\t\t    case '2': play();   break;\n\t\t    case '3': pause();  break;\n\t\t    case '4': stop();   break;\n\t\t    case '5': stop();   return;\n\t\t}\n\t    }\n\t}\n    }\nprivate:\n    void record()\n    {\n\tif( mciExecute( \"open new type waveaudio alias my_sound\") )\n\t{ \n\t    mciExecute( \"record my_sound\" ); \n\t    action = \"RECORDING\"; rec = true; \n\t}\n    }\n    void play()\n    {\n\tif( paused )\n\t    mciExecute( \"play my_sound\" );\n\telse\n\t    if( mciExecute( \"open tmp.wav alias my_sound\" ) )\n\t\tmciExecute( \"play my_sound\" );\n\n\taction = \"PLAYING\";\n\tpaused = false;\n    }\n    void pause()\n    {\n\tif( rec ) return;\n\tmciExecute( \"pause my_sound\" );\n\tpaused = true; action = \"PAUSED\";\n    }\n    void stop()\n    {\n\tif( rec )\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"save my_sound tmp.wav\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\"; rec = false;\n\t}\n\telse\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\";\n\t}\n    }\n    bool mciExecute( string cmd )\n    {\n\tif( mciSendString( cmd.c_str(), NULL, 0, NULL ) )\n\t{\n\t    cout << \"Can't do this: \" << cmd << endl;\n\t    return false;\n\t}\n\treturn true;\n    }\n\n    bool paused, rec;\n    string action;\n};\n\nint main( int argc, char* argv[] )\n{\n    recorder r; r.start();\n    return 0;\n}\n"}
{"id": 56184, "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", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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": 56185, "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", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 56186, "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", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n"}
{"id": 56187, "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", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56188, "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", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n"}
{"id": 56189, "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", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 56190, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 56191, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 56192, "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", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 56193, "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", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 56194, "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", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 56195, "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", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 56196, "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", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 56197, "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", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 56198, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 56199, "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", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 56200, "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", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56201, "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", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 56202, "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", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n"}
{"id": 56203, "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", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n"}
{"id": 56204, "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", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n"}
{"id": 56205, "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", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n"}
{"id": 56206, "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", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\n"}
{"id": 56207, "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", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\n"}
{"id": 56208, "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", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 56209, "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", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 56210, "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", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 56211, "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", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 56212, "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", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n"}
{"id": 56213, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n"}
{"id": 56214, "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", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n"}
{"id": 56215, "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", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 56216, "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", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 56217, "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", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 56218, "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", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 56219, "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", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56220, "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", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56221, "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", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 56222, "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", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 56223, "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", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n"}
{"id": 56224, "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", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n"}
{"id": 56225, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 56226, "name": "Write entire file", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 56227, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 56228, "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", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 56229, "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", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 56230, "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", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 56231, "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", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 56232, "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", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 56233, "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", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 56234, "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", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 56235, "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", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 56236, "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", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 56237, "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", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 56238, "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", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 56239, "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", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 56240, "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", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\n"}
{"id": 56241, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n"}
{"id": 56242, "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", "C++": "\nclass fifteenSolver{\n  const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};\n  int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};\n  unsigned long N2[100]{};\n  const bool fY(){\n    if (N4[n]<_n) return fN();\n    if (N2[n]==0x123456789abcdef0) {std::cout<<\"Solution found in \"<<n<<\" moves :\"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};\n    if (N4[n]==_n) return fN(); else return false;\n  }\n  const bool                     fN(){\n    if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}\n    return false;\n  }\n  void fI(){\n    const int           g = (11-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);\n  } \n  void fG(){\n    const int           g = (19-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);\n  } \n  void fE(){\n    const int           g = (14-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);\n  } \n  void fL(){\n    const int           g = (16-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);\n  }\npublic:\n  fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}\n  void Solve(){for(;not fY();++_n);}\n};\n"}
{"id": 56243, "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", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 56244, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 56245, "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", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 56246, "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", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 56247, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 56248, "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", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 56249, "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", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 56250, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 56251, "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", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 56252, "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", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 56253, "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", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n"}
{"id": 56254, "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", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n"}
{"id": 56255, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 56256, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 56257, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 56258, "name": "Carmichael 3 strong pseudoprimes", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n"}
{"id": 56259, "name": "Image noise", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 56260, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 56261, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 56262, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 56263, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 56264, "name": "Conjugate transpose", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n"}
{"id": 56265, "name": "Conjugate transpose", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n"}
{"id": 56266, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 56267, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 56268, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n"}
{"id": 56269, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56270, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56271, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 56272, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 56273, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 56274, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n"}
{"id": 56275, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 56276, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 56277, "name": "Fermat numbers", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntypedef boost::multiprecision::cpp_int integer;\n\ninteger fermat(unsigned int n) {\n    unsigned int p = 1;\n    for (unsigned int i = 0; i < n; ++i)\n        p *= 2;\n    return 1 + pow(integer(2), p);\n}\n\ninline void g(integer& x, const integer& n) {\n    x *= x;\n    x += 1;\n    x %= n;\n}\n\ninteger pollard_rho(const integer& n) {\n    integer x = 2, y = 2, d = 1, z = 1;\n    int count = 0;\n    for (;;) {\n        g(x, n);\n        g(y, n);\n        g(y, n);\n        d = abs(x - y);\n        z = (z * d) % n;\n        ++count;\n        if (count == 100) {\n            d = gcd(z, n);\n            if (d != 1)\n                break;\n            z = 1;\n            count = 0;\n        }\n    }\n    if (d == n)\n        return 0;\n    return d;\n}\n\nstd::vector<integer> get_prime_factors(integer n) {\n    std::vector<integer> factors;\n    for (;;) {\n        if (miller_rabin_test(n, 25)) {\n            factors.push_back(n);\n            break;\n        }\n        integer f = pollard_rho(n);\n        if (f == 0) {\n            factors.push_back(n);\n            break;\n        }\n        factors.push_back(f);\n        n /= f;\n    }\n    return factors;\n}\n\nvoid print_vector(const std::vector<integer>& factors) {\n    if (factors.empty())\n        return;\n    auto i = factors.begin();\n    std::cout << *i++;\n    for (; i != factors.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout << \"First 10 Fermat numbers:\\n\";\n    for (unsigned int i = 0; i < 10; ++i)\n        std::cout << \"F(\" << i << \") = \" << fermat(i) << '\\n';\n    std::cout << \"\\nPrime factors:\\n\";\n    for (unsigned int i = 0; i < 9; ++i) {\n        std::cout << \"F(\" << i << \"): \";\n        print_vector(get_prime_factors(fermat(i)));\n    }\n    return 0;\n}\n"}
{"id": 56278, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 56279, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 56280, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 56281, "name": "Water collected between towers", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 56282, "name": "Descending primes", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 56283, "name": "Square-free integers", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n"}
{"id": 56284, "name": "Jaro similarity", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n"}
{"id": 56285, "name": "Sum and product puzzle", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n"}
{"id": 56286, "name": "Fairshare between two and more", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 56287, "name": "Two bullet roulette", "Python": "\nimport numpy as np\n\nclass Revolver:\n    \n\n    def __init__(self):\n        \n        self.cylinder = np.array([False] * 6)\n\n    def unload(self):\n        \n        self.cylinder[:] = False\n\n    def load(self):\n        \n        while self.cylinder[1]:\n            self.cylinder[:] = np.roll(self.cylinder, 1)\n        self.cylinder[1] = True\n\n    def spin(self):\n        \n        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n    def fire(self):\n        \n        shot = self.cylinder[0]\n        self.cylinder[:] = np.roll(self.cylinder, 1)\n        return shot\n\n    def LSLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LSLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n    def LLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n\nif __name__ == '__main__':\n\n    REV = Revolver()\n    TESTCOUNT = 100000\n    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n                           ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n        print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <sstream>\n\nclass Roulette {\nprivate:\n    std::array<bool, 6> cylinder;\n\n    std::mt19937 gen;\n    std::uniform_int_distribution<> distrib;\n\n    int next_int() {\n        return distrib(gen);\n    }\n\n    void rshift() {\n        std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n    }\n\n    void unload() {\n        std::fill(cylinder.begin(), cylinder.end(), false);\n    }\n\n    void load() {\n        while (cylinder[0]) {\n            rshift();\n        }\n        cylinder[0] = true;\n        rshift();\n    }\n\n    void spin() {\n        int lim = next_int();\n        for (int i = 1; i < lim; i++) {\n            rshift();\n        }\n    }\n\n    bool fire() {\n        auto shot = cylinder[0];\n        rshift();\n        return shot;\n    }\n\npublic:\n    Roulette() {\n        std::random_device rd;\n        gen = std::mt19937(rd());\n        distrib = std::uniform_int_distribution<>(1, 6);\n\n        unload();\n    }\n\n    int method(const std::string &s) {\n        unload();\n        for (auto c : s) {\n            switch (c) {\n            case 'L':\n                load();\n                break;\n            case 'S':\n                spin();\n                break;\n            case 'F':\n                if (fire()) {\n                    return 1;\n                }\n                break;\n            }\n        }\n        return 0;\n    }\n};\n\nstd::string mstring(const std::string &s) {\n    std::stringstream ss;\n    bool first = true;\n\n    auto append = [&ss, &first](const std::string s) {\n        if (first) {\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << s;\n    };\n\n    for (auto c : s) {\n        switch (c) {\n        case 'L':\n            append(\"load\");\n            break;\n        case 'S':\n            append(\"spin\");\n            break;\n        case 'F':\n            append(\"fire\");\n            break;\n        }\n    }\n\n    return ss.str();\n}\n\nvoid test(const std::string &src) {\n    const int tests = 100000;\n    int sum = 0;\n\n    Roulette r;\n    for (int t = 0; t < tests; t++) {\n        sum += r.method(src);\n    }\n\n    double pc = 100.0 * sum / tests;\n\n    std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n"}
{"id": 56288, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n"}
{"id": 56289, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 56290, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 56291, "name": "Sequence_ nth number with exactly n divisors", "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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 56292, "name": "Sequence_ smallest number with exactly n divisors", "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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n"}
{"id": 56293, "name": "Pancake numbers", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56294, "name": "Generate random chess position", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n"}
{"id": 56295, "name": "Esthetic numbers", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n"}
{"id": 56296, "name": "Topswops", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n"}
{"id": 56297, "name": "Old Russian measure of length", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n"}
{"id": 56298, "name": "Rate counter", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n"}
{"id": 56299, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n"}
{"id": 56300, "name": "Padovan sequence", "Python": "from math import floor\nfrom collections import deque\nfrom typing import Dict, Generator\n\n\ndef padovan_r() -> Generator[int, None, None]:\n    last = deque([1, 1, 1], 4)\n    while True:\n        last.append(last[-2] + last[-3])\n        yield last.popleft()\n\n_p, _s = 1.324717957244746025960908854, 1.0453567932525329623\n\ndef padovan_f(n: int) -> int:\n    return floor(_p**(n-1) / _s + .5)\n\ndef padovan_l(start: str='A',\n             rules: Dict[str, str]=dict(A='B', B='C', C='AB')\n             ) -> Generator[str, None, None]:\n    axiom = start\n    while True:\n        yield axiom\n        axiom = ''.join(rules[ch] for ch in axiom)\n\n\nif __name__ == \"__main__\":\n    from itertools import islice\n\n    print(\"The first twenty terms of the sequence.\")\n    print(str([padovan_f(n) for n in range(20)])[1:-1])\n\n    r_generator = padovan_r()\n    if all(next(r_generator) == padovan_f(n) for n in range(64)):\n        print(\"\\nThe recurrence and floor based algorithms match to n=63 .\")\n    else:\n        print(\"\\nThe recurrence and floor based algorithms DIFFER!\")\n\n    print(\"\\nThe first 10 L-system string-lengths and strings\")\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    print('\\n'.join(f\"  {len(string):3} {repr(string)}\"\n                    for string in islice(l_generator, 10)))\n\n    r_generator = padovan_r()\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)\n           for n in range(32)):\n        print(\"\\nThe L-system, recurrence and floor based algorithms match to n=31 .\")\n    else:\n        print(\"\\nThe L-system, recurrence and floor based algorithms DIFFER!\")\n", "C++": "#include <iostream>\n#include <map>\n#include <cmath>\n\n\n\nint pRec(int n) {\n    static std::map<int,int> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n\n    if (n <= 2) memo[n] = 1;\n    else memo[n] = pRec(n-2) + pRec(n-3);\n    return memo[n];\n}\n\n\n\nint pFloor(int n) {\n    long const double p = 1.324717957244746025960908854;\n    long const double s = 1.0453567932525329623;\n    return std::pow(p, n-1)/s + 0.5;\n}\n\n\nstd::string& lSystem(int n) {\n    static std::map<int,std::string> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n    \n    if (n == 0) memo[n] = \"A\";\n    else {\n        memo[n] = \"\";\n        for (char ch : memo[n-1]) {\n            switch(ch) {\n                case 'A': memo[n].push_back('B'); break;\n                case 'B': memo[n].push_back('C'); break;\n                case 'C': memo[n].append(\"AB\"); break;\n            }\n        }\n    }\n    return memo[n];\n}\n\n\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n    std::cout << \"The \" << descr << \" functions \";\n    int i;\n    for (i=0; i<stop; i++) {\n        int n1 = f1(i);\n        int n2 = f2(i);\n        if (n1 != n2) {\n            std::cout << \"do not match at \" << i\n                      << \": \" << n1 << \" != \" << n2 << \".\\n\";\n            break;\n        }\n    }\n    if (i == stop) {\n        std::cout << \"match from P_0 to P_\" << stop << \".\\n\";\n    }\n}\n\nint main() {\n    \n    std::cout << \"P_0 .. P_19: \";\n    for (int i=0; i<20; i++) std::cout << pRec(i) << \" \";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, pRec, \"floor- and recurrence-based\", 64);\n    \n    \n    std::cout << \"\\nThe first 10 L-system strings are:\\n\";\n    for (int i=0; i<10; i++) std::cout << lSystem(i) << \"\\n\";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, [](int n){return (int)lSystem(n).length();}, \n                            \"floor- and L-system-based\", 32);\n    return 0;\n}\n"}
{"id": 56301, "name": "Pythagoras tree", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n"}
{"id": 56302, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 56303, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56304, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56305, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56306, "name": "Numeric error propagation", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n"}
{"id": 56307, "name": "List rooted trees", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n"}
{"id": 56308, "name": "List rooted trees", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n"}
{"id": 56309, "name": "Longest common suffix", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n"}
{"id": 56310, "name": "Sum of elements below main diagonal of matrix", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n"}
{"id": 56311, "name": "FASTA format", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 56312, "name": "Elementary cellular automaton_Random number generator", "Python": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n    cells = '1' + '0' * (lencells - 1)\n    gen = eca(cells, 30)\n    while True:\n        yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n    print([b for i,b in zip(range(10), rule30bytes())])\n", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n"}
{"id": 56313, "name": "Pseudo-random numbers_PCG32", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56314, "name": "Sierpinski pentagon", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 56315, "name": "Sierpinski pentagon", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 56316, "name": "Rep-string", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 56317, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n"}
{"id": 56318, "name": "Changeable words", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56319, "name": "Monads_List monad", "Python": "\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n    @classmethod\n    def unit(cls, value: Iterable[T]) -> MList[T]:\n        return cls(value)\n\n    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return MList(chain.from_iterable(map(func, self)))\n\n    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return self.bind(func)\n\n\nif __name__ == \"__main__\":\n    \n    print(\n        MList([1, 99, 4])\n        .bind(lambda val: MList([val + 1]))\n        .bind(lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList([1, 99, 4])\n        >> (lambda val: MList([val + 1]))\n        >> (lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList(range(1, 6)).bind(\n            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n        )\n    )\n\n    \n    print(\n        MList(range(1, 26)).bind(\n            lambda x: MList(range(x + 1, 26)).bind(\n                lambda y: MList(range(y + 1, 26)).bind(\n                    lambda z: MList([(x, y, z)])\n                    if x * x + y * y == z * z\n                    else MList([])\n                )\n            )\n        )\n    )\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate <typename T>\nauto operator>>(const vector<T>& monad, auto f)\n{\n    \n    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;\n    for(auto& item : monad)\n    {\n        \n        \n        const auto r = f(item);\n        \n        result.insert(result.end(), begin(r), end(r));\n    }\n    \n    return result;\n}\n\n\nauto Pure(auto t)\n{\n    return vector{t};\n}\n\n\nauto Double(int i)\n{\n    return Pure(2 * i);\n}\n\n\nauto Increment(int i)\n{\n    return Pure(i + 1);\n}\n\n\nauto NiceNumber(int i)\n{\n    return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n\n\nauto UpperSequence = [](auto startingVal)\n{\n    const int MaxValue = 500;\n    vector<decltype(startingVal)> sequence;\n    while(startingVal <= MaxValue) \n        sequence.push_back(startingVal++);\n    return sequence;\n};\n\n\nvoid PrintVector(const auto& vec)\n{\n    cout << \" \";\n    for(auto value : vec)\n    {\n        cout << value << \" \";\n    }\n    cout << \"\\n\";\n}\n\n\nvoid PrintTriples(const auto& vec)\n{\n    cout << \"Pythagorean triples:\\n\";\n    for(auto it = vec.begin(); it != vec.end();)\n    {\n        auto x = *it++;\n        auto y = *it++;\n        auto z = *it++;\n        \n        cout << x << \", \" << y << \", \" << z << \"\\n\";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    \n    auto listMonad = \n        vector<int> {2, 3, 4} >> \n        Increment >> \n        Double >>\n        NiceNumber;\n        \n    PrintVector(listMonad);\n    \n    \n    \n    \n    \n    auto pythagoreanTriples = UpperSequence(1) >> \n        [](int x){return UpperSequence(x) >>\n        [x](int y){return UpperSequence(y) >>\n        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};\n    \n    PrintTriples(pythagoreanTriples);\n}\n"}
{"id": 56320, "name": "Special factorials", "Python": "\n\nfrom math import prod\n\ndef superFactorial(n):\n    return prod([prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef hyperFactorial(n):\n    return prod([i**i for i in range(1,n+1)])\n\ndef alternatingFactorial(n):\n    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef exponentialFactorial(n):\n    if n in [0,1]:\n        return 1\n    else:\n        return n**exponentialFactorial(n-1)\n        \ndef inverseFactorial(n):\n    i = 1\n    while True:\n        if n == prod(range(1,i)):\n            return i-1\n        elif n < prod(range(1,i)):\n            return \"undefined\"\n        i+=1\n\nprint(\"Superfactorials for [0,9] :\")\nprint({\"sf(\" + str(i) + \") \" : superFactorial(i) for i in range(0,10)})\n\nprint(\"\\nHyperfactorials for [0,9] :\")\nprint({\"H(\" + str(i) + \") \"  : hyperFactorial(i) for i in range(0,10)})\n\nprint(\"\\nAlternating factorials for [0,9] :\")\nprint({\"af(\" + str(i) + \") \" : alternatingFactorial(i) for i in range(0,10)})\n\nprint(\"\\nExponential factorials for [0,4] :\")\nprint({str(i) + \"$ \" : exponentialFactorial(i) for i in range(0,5)})\n\nprint(\"\\nDigits in 5$ : \" , len(str(exponentialFactorial(5))))\n\nfactorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n\nprint(\"\\nInverse factorials for \" , factorialSet)\nprint({\"rf(\" + str(i) + \") \":inverseFactorial(i) for i in factorialSet})\n\nprint(\"\\nrf(119) : \" + inverseFactorial(119))\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 56321, "name": "Four is magic", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n", "C++": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 56322, "name": "Getting the number of decimals", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 56323, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 56324, "name": "Parse an IP Address", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n"}
{"id": 56325, "name": "Textonyms", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n"}
{"id": 56326, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56327, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 56328, "name": "Teacup rim text", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56329, "name": "Increasing gaps between consecutive Niven numbers", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 56330, "name": "Print debugging statement", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n"}
{"id": 56331, "name": "Print debugging statement", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n"}
{"id": 56332, "name": "Range extraction", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 56333, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 56334, "name": "Zhang-Suen thinning algorithm", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n", "C++": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <valarray>\nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n    friend class ZhangSuen;\n    using pixel_t = char;\n    static const pixel_t BLACK_PIX;\n    static const pixel_t WHITE_PIX;\n\n    Image(unsigned width = 1, unsigned height = 1) \n    : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n    {}\n    Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n    {}\n    Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n    {}\n    ~Image() = default;\n    Image& operator=(const Image& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = i.data_;\n        }\n        return *this;\n    }\n    Image& operator=(Image&& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = std::move(i.data_);\n        }\n        return *this;\n    }\n    size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n    bool operator()(unsigned x, unsigned y) {\n        return data_[idx(x, y)];\n    }\n    friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n        o << i.width_ << \" x \" << i.height_ << std::endl;\n        size_t px = 0;\n        for(const auto& e : i.data_) {\n            o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n            if (++px % i.width_ == 0)\n                o << std::endl;\n        }\n        return o << std::endl;\n    }\n    friend std::istream& operator>>(std::istream& in, Image& img) {\n        auto it = std::begin(img.data_);\n        const auto end = std::end(img.data_);\n        Image::pixel_t tmp;\n        while(in && it != end) {\n            in >> tmp;\n            if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n                throw \"Bad character found in image\";\n            *it = (tmp == Image::BLACK_PIX)?1:0;\n            ++it;\n        }\n        return in;\n    }\n    unsigned width() const noexcept { return width_; }\n    unsigned height() const noexcept { return height_; }\n    struct Neighbours {\n        \n        \n        \n        Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n        : img_{img}\n        , p1_{img.idx(p1_x, p1_y)}\n        , p2_{p1_ - img.width()}\n        , p3_{p2_ + 1}\n        , p4_{p1_ + 1}\n        , p5_{p4_ + img.width()}\n        , p6_{p5_ - 1}\n        , p7_{p6_ - 1}\n        , p8_{p1_ - 1}\n        , p9_{p2_ - 1} \n        {}\n        const Image& img_;\n        const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n        const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n        const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n        const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n        const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n        const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n        const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n        const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n        const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n        const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n    };\n    Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n    unsigned height_ { 0 };\n    unsigned width_ { 0 };\n    std::valarray<pixel_t> data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n    \n    unsigned transitions_white_black(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += (a.p9() == 0) && a.p2();\n        sum += (a.p2() == 0) && a.p3();\n        sum += (a.p3() == 0) && a.p4();\n        sum += (a.p8() == 0) && a.p9();\n        sum += (a.p4() == 0) && a.p5();\n        sum += (a.p7() == 0) && a.p8();\n        sum += (a.p6() == 0) && a.p7();\n        sum += (a.p5() == 0) && a.p6();\n        return sum;\n    }\n\n    \n    unsigned black_pixels(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += a.p9();\n        sum += a.p2();\n        sum += a.p3();\n        sum += a.p8();\n        sum += a.p4();\n        sum += a.p7();\n        sum += a.p6();\n        sum += a.p5();\n        return sum;\n    }\n    const Image& operator()(const Image& img) {\n        tmp_a_ = img;\n        size_t changed_pixels = 0;\n        do {\n            changed_pixels = 0;\n            \n            tmp_b_ = tmp_a_;\n            for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n                    if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n                        auto n = tmp_a_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p6() == 0)\n                                && (n.p4() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_b_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n            \n            tmp_a_ = tmp_b_;\n            for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n                    if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n                        auto n = tmp_b_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p8() == 0)\n                                && (n.p2() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_a_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n        } while(changed_pixels > 0);\n        return tmp_a_;\n    }\nprivate:\n    Image tmp_a_;\n    Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n    using namespace std;\n    Image img(32, 10);\n    istringstream iss{input};\n    iss >> img;\n    cout << img;\n    cout << \"ZhangSuen\" << endl;\n    ZhangSuen zs;\n    Image res = std::move(zs(img));\n    cout << res << endl;\n\n    Image img2(58,18);\n    istringstream iss2{input2};\n    iss2 >> img2;\n    cout << img2;\n    cout << \"ZhangSuen with big image\" << endl;\n    Image res2 = std::move(zs(img2));\n    cout << res2 << endl;\n    return 0;\n}\n"}
{"id": 56335, "name": "Variable declaration reset", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n"}
{"id": 56336, "name": "Numbers with equal rises and falls", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n"}
{"id": 56337, "name": "Koch curve", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56338, "name": "Koch curve", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56339, "name": "Words from neighbour ones", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56340, "name": "Magic squares of singly even order", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n"}
{"id": 56341, "name": "Generate Chess960 starting position", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n"}
{"id": 56342, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "C++": "int meaning_of_life();\n"}
{"id": 56343, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "C++": "int meaning_of_life();\n"}
{"id": 56344, "name": "File size distribution", "Python": "import sys, os\nfrom collections import Counter\n\ndef dodir(path):\n    global h\n\n    for name in os.listdir(path):\n        p = os.path.join(path, name)\n\n        if os.path.islink(p):\n            pass\n        elif os.path.isfile(p):\n            h[os.stat(p).st_size] += 1\n        elif os.path.isdir(p):\n            dodir(p)\n        else:\n            pass\n\ndef main(arg):\n    global h\n    h = Counter()\n    for dir in arg:\n        dodir(dir)\n\n    s = n = 0\n    for k, v in sorted(h.items()):\n        print(\"Size %d -> %d file(s)\" % (k, v))\n        n += v\n        s += k * v\n    print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])\n", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56345, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 56346, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 56347, "name": "Pseudo-random numbers_Xorshift star", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56348, "name": "Four is the number of letters in the ...", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n", "C++": "#include <cctype>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        result.push_back(get_name(small[n], ordinal));\n        count = 1;\n    }\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result.push_back(get_name(tens[n/10 - 2], ordinal));\n        } else {\n            std::string name(get_name(tens[n/10 - 2], false));\n            name += \"-\";\n            name += get_name(small[n % 10], ordinal);\n            result.push_back(name);\n        }\n        count = 1;\n    } else {\n        const named_number& num = get_named_number(n);\n        uint64_t p = num.number;\n        count += append_number_name(result, n/p, false);\n        if (n % p == 0) {\n            result.push_back(get_name(num, ordinal));\n            ++count;\n        } else {\n            result.push_back(get_name(num, false));\n            ++count;\n            count += append_number_name(result, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(const std::string& str) {\n    size_t letters = 0;\n    for (size_t i = 0, n = str.size(); i < n; ++i) {\n        if (isalpha(static_cast<unsigned char>(str[i])))\n            ++letters;\n    }\n    return letters;\n}\n\nstd::vector<std::string> sentence(size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    std::vector<std::string> result;\n    result.reserve(count + 10);\n    size_t n = std::size(words);\n    for (size_t i = 0; i < n && i < count; ++i) {\n        result.push_back(words[i]);\n    }\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result[i]), false);\n        result.push_back(\"in\");\n        result.push_back(\"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        result.back() += ',';\n    }\n    return result;\n}\n\nsize_t sentence_length(const std::vector<std::string>& words) {\n    size_t n = words.size();\n    if (n == 0)\n        return 0;\n    size_t length = n - 1;\n    for (size_t i = 0; i < n; ++i)\n        length += words[i].size();\n    return length;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    size_t n = 201;\n    auto result = sentence(n);\n    std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            std::cout << (i % 25 == 0 ? '\\n' : ' ');\n        std::cout << std::setw(2) << count_letters(result[i]);\n    }\n    std::cout << '\\n';\n    std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    for (n = 1000; n <= 10000000; n *= 10) {\n        result = sentence(n);\n        const std::string& word = result[n - 1];\n        std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n            << count_letters(word) << \" letters. \";\n        std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56349, "name": "ASCII art diagram converter", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n"}
{"id": 56350, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n"}
{"id": 56351, "name": "Peaceful chess queen armies", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 56352, "name": "Numbers with same digit set in base 10 and base 16", "Python": "col = 0\nfor i in range(100000):\n    if set(str(i)) == set(hex(i)[2:]):\n        col += 1\n        print(\"{:7}\".format(i), end='\\n'[:col % 10 == 0])\nprint()\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n"}
{"id": 56353, "name": "Largest proper divisor of n", "Python": "def lpd(n):\n    for i in range(n-1,0,-1):\n        if n%i==0: return i\n    return 1\n\nfor i in range(1,101):\n    print(\"{:3}\".format(lpd(i)), end=i%10==0 and '\\n' or '')\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n"}
{"id": 56354, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 56355, "name": "Sum of first n cubes", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 56356, "name": "Sum of first n cubes", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 56357, "name": "Test integerness", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n"}
{"id": 56358, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 56359, "name": "Lucky and even lucky numbers", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nconst int luckySize = 60000;\nstd::vector<int> luckyEven(luckySize);\nstd::vector<int> luckyOdd(luckySize);\n\nvoid init() {\n    for (int i = 0; i < luckySize; ++i) {\n        luckyEven[i] = i * 2 + 2;\n        luckyOdd[i] = i * 2 + 1;\n    }\n}\n\nvoid filterLuckyEven() {\n    for (size_t n = 2; n < luckyEven.size(); ++n) {\n        int m = luckyEven[n - 1];\n        int end = (luckyEven.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n            luckyEven.pop_back();\n        }\n    }\n}\n\nvoid filterLuckyOdd() {\n    for (size_t n = 2; n < luckyOdd.size(); ++n) {\n        int m = luckyOdd[n - 1];\n        int end = (luckyOdd.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n            luckyOdd.pop_back();\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n\n    if (even) {\n        size_t max = luckyEven.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    } else {\n        size_t max = luckyOdd.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    }\n    std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n    if (even) {\n        if (k >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n    } else {\n        if (k >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n    }\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (j >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n    } else {\n        if (j >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n    }\n}\n\nvoid help() {\n    std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"       argument(s)        |  what is displayed\\n\";\n    std::cout << \"==============================================\\n\";\n    std::cout << \"-j=m                      |  mth lucky number\\n\";\n    std::cout << \"-j=m  --lucky             |  mth lucky number\\n\";\n    std::cout << \"-j=m  --evenLucky         |  mth even lucky number\\n\";\n    std::cout << \"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\";\n    std::cout << \"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    \n    if (argc < 2) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    bool good = false;\n    for (int i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n            exit(EXIT_FAILURE);\n        }\n    }\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    init();\n    filterLuckyEven();\n    filterLuckyOdd();\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n\n    return 0;\n}\n"}
{"id": 56360, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 56361, "name": "Superpermutation minimisation", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56362, "name": "GUI component interaction", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n"}
{"id": 56363, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 56364, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 56365, "name": "Summarize and say sequence", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 56366, "name": "Spelling of ordinal numbers", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 56367, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 56368, "name": "Addition chains", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 56369, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n"}
{"id": 56370, "name": "Sparkline in unicode", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n"}
{"id": 56371, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 56372, "name": "Sunflower fractal", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56373, "name": "Vogel's approximation method", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n"}
{"id": 56374, "name": "Chemical calculator", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56375, "name": "Permutations by swapping", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n"}
{"id": 56376, "name": "Minimum multiple of m where digital sum equals m", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n"}
{"id": 56377, "name": "Minimum multiple of m where digital sum equals m", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n"}
{"id": 56378, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n"}
{"id": 56379, "name": "Steady squares", "Python": "print(\"working...\")\nprint(\"Steady squares under 10.000 are:\")\nlimit = 10000\n\nfor n in range(1,limit):\n    nstr = str(n)\n    nlen = len(nstr)\n    square = str(pow(n,2))\n    rn = square[-nlen:]\n    if nstr == rn:\n       print(str(n) + \" \" + str(square))\n\nprint(\"done...\")\n", "C++": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n"}
{"id": 56380, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 56381, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 56382, "name": "Dice game probabilities", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n"}
{"id": 56383, "name": "Dice game probabilities", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n"}
{"id": 56384, "name": "Zebra puzzle", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n", "C++": "#include <stdio.h>\n#include <string.h>\n\n#define defenum(name, val0, val1, val2, val3, val4) \\\n    enum name { val0, val1, val2, val3, val4 }; \\\n    const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }\n\ndefenum( Attrib,    Color, Man, Drink, Animal, Smoke );\ndefenum( Colors,    Red, Green, White, Yellow, Blue );\ndefenum( Mans,      English, Swede, Dane, German, Norwegian );\ndefenum( Drinks,    Tea, Coffee, Milk, Beer, Water );\ndefenum( Animals,   Dog, Birds, Cats, Horse, Zebra );\ndefenum( Smokes,    PallMall, Dunhill, Blend, BlueMaster, Prince );\n\nvoid printHouses(int ha[5][5]) {\n    const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};\n\n    printf(\"%-10s\", \"House\");\n    for (const char *name : Attrib_str) printf(\"%-10s\", name);\n    printf(\"\\n\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        for (int j = 0; j < 5; j++) printf(\"%-10s\", attr_names[j][ha[i][j]]);\n        printf(\"\\n\");\n    }\n}\n\nstruct HouseNoRule {\n    int houseno;\n    Attrib a; int v;\n} housenos[] = {\n    {2, Drink, Milk},     \n    {0, Man, Norwegian}   \n};\n\nstruct AttrPairRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&\n               ((ha[i][a1] == v1 && ha[i][a2] != v2) ||\n                (ha[i][a1] != v1 && ha[i][a2] == v2));\n    }\n} pairs[] = {\n    {Man, English,      Color, Red},     \n    {Man, Swede,        Animal, Dog},    \n    {Man, Dane,         Drink, Tea},     \n    {Color, Green,      Drink, Coffee},  \n    {Smoke, PallMall,   Animal, Birds},  \n    {Smoke, Dunhill,    Color, Yellow},  \n    {Smoke, BlueMaster, Drink, Beer},    \n    {Man, German,       Smoke, Prince}    \n};\n\nstruct NextToRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] == v1) &&\n               ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||\n                (i == 4 && ha[i - 1][a2] != v2) ||\n                (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));\n    }\n} nexttos[] = {\n    {Smoke, Blend,      Animal, Cats},    \n    {Smoke, Dunhill,    Animal, Horse},   \n    {Man, Norwegian,    Color, Blue},     \n    {Smoke, Blend,      Drink, Water}     \n};\n\nstruct LeftOfRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5]) {\n        return (ha[0][a2] == v2) || (ha[4][a1] == v1);\n    }\n\n    bool invalid(int ha[5][5], int i) {\n        return ((i > 0 && ha[i][a1] >= 0) &&\n                ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||\n                 (ha[i - 1][a1] != v1 && ha[i][a2] == v2)));\n    }\n} leftofs[] = {\n    {Color, Green,  Color, White}     \n};\n\nbool invalid(int ha[5][5]) {\n    for (auto &rule : leftofs) if (rule.invalid(ha)) return true;\n\n    for (int i = 0; i < 5; i++) {\n#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;\n        eval_rules(pairs);\n        eval_rules(nexttos);\n        eval_rules(leftofs);\n    }\n    return false;\n}\n\nvoid search(bool used[5][5], int ha[5][5], const int hno, const int attr) {\n    int nexthno, nextattr;\n    if (attr < 4) {\n        nextattr = attr + 1;\n        nexthno = hno;\n    } else {\n        nextattr = 0;\n        nexthno = hno + 1;\n    }\n\n    if (ha[hno][attr] != -1) {\n        search(used, ha, nexthno, nextattr);\n    } else {\n        for (int i = 0; i < 5; i++) {\n            if (used[attr][i]) continue;\n            used[attr][i] = true;\n            ha[hno][attr] = i;\n\n            if (!invalid(ha)) {\n                if ((hno == 4) && (attr == 4)) {\n                    printHouses(ha);\n                } else {\n                    search(used, ha, nexthno, nextattr);\n                }\n            }\n\n            used[attr][i] = false;\n        }\n        ha[hno][attr] = -1;\n    }\n}\n\nint main() {\n    bool used[5][5] = {};\n    int ha[5][5]; memset(ha, -1, sizeof(ha));\n\n    for (auto &rule : housenos) {\n        ha[rule.houseno][rule.a] = rule.v;\n        used[rule.a][rule.v] = true;\n    }\n\n    search(used, ha, 0, 0);\n\n    return 0;\n}\n"}
{"id": 56385, "name": "First-class functions_Use numbers analogously", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n"}
{"id": 56386, "name": "First-class functions_Use numbers analogously", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n"}
{"id": 56387, "name": "Sokoban", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n"}
{"id": 56388, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 56389, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 56390, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 56391, "name": "Practical numbers", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n"}
{"id": 56392, "name": "Consecutive primes with ascending or descending differences", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n"}
{"id": 56393, "name": "Consecutive primes with ascending or descending differences", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n"}
{"id": 56394, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n"}
{"id": 56395, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 56396, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 56397, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 56398, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 56399, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56400, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56401, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 56402, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 56403, "name": "Word search", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n"}
{"id": 56404, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 56405, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 56406, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n"}
{"id": 56407, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 56408, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 56409, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 56410, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n"}
{"id": 56411, "name": "Zumkeller numbers", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n"}
{"id": 56412, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 56413, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 56414, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 56415, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 56416, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n"}
{"id": 56417, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n"}
{"id": 56418, "name": "Geometric algebra", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n"}
{"id": 56419, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 56420, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 56421, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n"}
{"id": 56422, "name": "Define a primitive data type", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n"}
{"id": 56423, "name": "Arithmetic derivative", "Python": "from sympy.ntheory import factorint\n\ndef D(n):\n    if n < 0:\n        return -D(-n)\n    elif n < 2:\n        return 0\n    else:\n        fdict = factorint(n)\n        if len(fdict) == 1 and 1 in fdict: \n            return 1\n        return sum([n * e // p for p, e in fdict.items()])\n\nfor n in range(-99, 101):\n    print('{:5}'.format(D(n)), end='\\n' if n % 10 == 0 else '')\n\nprint()\nfor m in range(1, 21):\n    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\ntemplate <typename IntegerType>\nIntegerType arithmetic_derivative(IntegerType n) {\n    bool negative = n < 0;\n    if (negative)\n        n = -n;\n    if (n < 2)\n        return 0;\n    IntegerType sum = 0, count = 0, m = n;\n    while ((m & 1) == 0) {\n        m >>= 1;\n        count += n;\n    }\n    if (count > 0)\n        sum += count / 2;\n    for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {\n        count = 0;\n        while (m % p == 0) {\n            m /= p;\n            count += n;\n        }\n        if (count > 0)\n            sum += count / p;\n        sq += (p + 1) << 2;\n    }\n    if (m > 1)\n        sum += n / m;\n    if (negative)\n        sum = -sum;\n    return sum;\n}\n\nint main() {\n    using boost::multiprecision::int128_t;\n\n    for (int n = -99, i = 0; n <= 100; ++n, ++i) {\n        std::cout << std::setw(4) << arithmetic_derivative(n)\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    int128_t p = 10;\n    std::cout << '\\n';\n    for (int i = 0; i < 20; ++i, p *= 10) {\n        std::cout << \"D(10^\" << std::setw(2) << i + 1\n                  << \") / 7 = \" << arithmetic_derivative(p) / 7 << '\\n';\n    }\n}\n"}
{"id": 56424, "name": "Permutations with some identical elements", "Python": "\n\nfrom itertools import permutations\n\nnumList = [2,3,1]\n\nbaseList = []\n\nfor i in numList:\n    for j in range(0,i):\n        baseList.append(i)\n\nstringDict = {'A':2,'B':3,'C':1}\n\nbaseString=\"\"\n\nfor i in stringDict:\n    for j in range(0,stringDict[i]):\n        baseString+=i\n\nprint(\"Permutations for \" + str(baseList) + \" : \")\n[print(i) for i in set(permutations(baseList))]\n\nprint(\"Permutations for \" + baseString + \" : \")\n[print(i) for i in set(permutations(baseString))]\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n    std::string str(\"AABBBC\");\n    int count = 0;\n    do {\n        std::cout << str << (++count % 10 == 0 ? '\\n' : ' ');\n    } while (std::next_permutation(str.begin(), str.end()));\n}\n"}
{"id": 56425, "name": "Penrose tiling", "Python": "def penrose(depth):\n    print(\t<g id=\"A{d+1}\" transform=\"translate(100, 0) scale(0.6180339887498949)\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n\t<g id=\"B{d+1}\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\t<g id=\"G\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n  </defs>\n  <g transform=\"scale(2, 2)\">\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n  </g>\n</svg>''')\n\npenrose(6)\n", "C++": "#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n\nint main() {\n    std::ofstream out(\"penrose_tiling.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string penrose(\"[N]++[N]++[N]++[N]++[N]\");\n    for (int i = 1; i <= 4; ++i) {\n        std::string next;\n        for (char ch : penrose) {\n            switch (ch) {\n            case 'A':\n                break;\n            case 'M':\n                next += \"OA++PA----NA[-OA----MA]++\";\n                break;\n            case 'N':\n                next += \"+OA--PA[---MA--NA]+\";\n                break;\n            case 'O':\n                next += \"-MA++NA[+++OA++PA]-\";\n                break;\n            case 'P':\n                next += \"--OA++++MA[+PA++++NA]--NA\";\n                break;\n            default:\n                next += ch;\n                break;\n            }\n        }\n        penrose = std::move(next);\n    }\n    const double r = 30;\n    const double pi5 = 0.628318530717959;\n    double x = r * 8, y = r * 8, theta = pi5;\n    std::set<std::string> svg;\n    std::stack<std::tuple<double, double, double>> stack;\n    for (char ch : penrose) {\n        switch (ch) {\n        case 'A': {\n            double nx = x + r * std::cos(theta);\n            double ny = y + r * std::sin(theta);\n            std::ostringstream line;\n            line << std::fixed << std::setprecision(3) << \"<line x1='\" << x\n                 << \"' y1='\" << y << \"' x2='\" << nx << \"' y2='\" << ny << \"'/>\";\n            svg.insert(line.str());\n            x = nx;\n            y = ny;\n        } break;\n        case '+':\n            theta += pi5;\n            break;\n        case '-':\n            theta -= pi5;\n            break;\n        case '[':\n            stack.push({x, y, theta});\n            break;\n        case ']':\n            std::tie(x, y, theta) = stack.top();\n            stack.pop();\n            break;\n        }\n    }\n    out << \"<svg xmlns='http:\n        << \"' width='\" << r * 16 << \"'>\\n\"\n        << \"<rect height='100%' width='100%' fill='black'/>\\n\"\n        << \"<g stroke='rgb(255,165,0)'>\\n\";\n    for (const auto& line : svg)\n        out << line << '\\n';\n    out << \"</g>\\n</svg>\\n\";\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56426, "name": "Sphenic numbers", "Python": "\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n    d = factorint(i)\n    if len(d) == 3 and sum(d.values()) == 3:\n        sphenics1m.append(i)\n        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n            sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n    if n < 1000:\n        print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n    else:\n        break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n    if n < 10_000:\n        print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else '  ')\n    else:\n        break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n      'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nstd::vector<int> prime_factors(int n) {\n    std::vector<int> factors;\n    if (n > 1 && (n & 1) == 0) {\n        factors.push_back(2);\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            factors.push_back(p);\n            while (n % p == 0)\n                n /= p;\n        }\n    }\n    if (n > 1)\n        factors.push_back(n);\n    return factors;\n}\n\nint main() {\n    const int limit = 1000000;\n    const int imax = limit / 6;\n    std::vector<bool> sieve = prime_sieve(imax + 1);\n    std::vector<bool> sphenic(limit + 1, false);\n    for (int i = 0; i <= imax; ++i) {\n        if (!sieve[i])\n            continue;\n        int jmax = std::min(imax, limit / (i * i));\n        if (jmax <= i)\n            break;\n        for (int j = i + 1; j <= jmax; ++j) {\n            if (!sieve[j])\n                continue;\n            int p = i * j;\n            int kmax = std::min(imax, limit / p);\n            if (kmax <= j)\n                break;\n            for (int k = j + 1; k <= kmax; ++k) {\n                if (!sieve[k])\n                    continue;\n                assert(p * k <= limit);\n                sphenic[p * k] = true;\n            }\n        }\n    }\n\n    std::cout << \"Sphenic numbers < 1000:\\n\";\n    for (int i = 0, n = 0; i < 1000; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++n;\n        std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n    for (int i = 0, n = 0; i < 10000; ++i) {\n        if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n            ++n;\n            std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n                      << (n % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n\n    int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n    for (int i = 0; i < limit; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++count;\n        if (count == 200000)\n            s200000 = i;\n        if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n            ++triplets;\n            if (triplets == 5000)\n                t5000 = i;\n        }\n    }\n\n    std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n    std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n    auto factors = prime_factors(s200000);\n    assert(factors.size() == 3);\n    std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n              << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n              << '\\n';\n\n    std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n              << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}\n"}
{"id": 56427, "name": "Tree from nesting levels", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 56428, "name": "Tree from nesting levels", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 56429, "name": "Tree from nesting levels", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 56430, "name": "Find duplicate files", "Python": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n    knownFiles = {}\n\n    \n    for root, dirs, files in os.walk(pth):\n        for fina in files:\n            fullFina = os.path.join(root, fina)\n            isSymLink = os.path.islink(fullFina)\n            if isSymLink:\n                continue \n            si = os.path.getsize(fullFina)\n            if si < minSize:\n                continue\n            if si not in knownFiles:\n                knownFiles[si] = {}\n            h = hashlib.new(hashName)\n            h.update(open(fullFina, \"rb\").read())\n            hashed = h.digest()\n            if hashed in knownFiles[si]:\n                fileRec = knownFiles[si][hashed]\n                fileRec.append(fullFina)\n            else:\n                knownFiles[si][hashed] = [fullFina]\n\n    \n    sizeList = list(knownFiles.keys())\n    sizeList.sort(reverse=True)\n    for si in sizeList:\n        filesAtThisSize = knownFiles[si]\n        for hashVal in filesAtThisSize:\n            if len(filesAtThisSize[hashVal]) < 2:\n                continue\n            fullFinaLi = filesAtThisSize[hashVal]\n            print (\"=======Duplicate=======\")\n            for fullFina in fullFinaLi:\n                st = os.stat(fullFina)\n                isHardLink = st.st_nlink > 1 \n                infoStr = []\n                if isHardLink:\n                    infoStr.append(\"(Hard linked)\")\n                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n                print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n", "C++": "#include<iostream>\n#include<string>\n#include<boost/filesystem.hpp>\n#include<boost/format.hpp>\n#include<boost/iostreams/device/mapped_file.hpp>\n#include<optional>\n#include<algorithm>\n#include<iterator>\n#include<execution>\n#include\"dependencies/xxhash.hpp\" \n\n\ntemplate<typename  T, typename V, typename F>\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n    size_t partitions = 0;\n    while (begin != end) {\n        auto const& value = getvalue(*begin);\n        auto current = begin;\n        while (++current != end && getvalue(*current) == value);\n        callback(begin, current, value);\n        ++partitions;\n        begin = current;\n    }\n    return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n    explicit file_entry(fs::directory_entry const & entry) \n        : path_{entry.path()}, size_{fs::file_size(entry)}\n    {}\n    auto size() const { return size_; }\n    auto const& path() const { return path_; }\n    auto get_hash() {\n        if (!hash_)\n            hash_ = compute_hash();\n        return *hash_;\n    }\nprivate:\n    xxh::hash64_t compute_hash() {\n        bi::mapped_file_source source;\n        source.open<fs::wpath>(this->path());\n        if (!source.is_open()) {\n            std::cerr << \"Cannot open \" << path() << std::endl;\n            throw std::runtime_error(\"Cannot open file\");\n        }\n        xxh::hash_state64_t hash_stream;\n        hash_stream.update(source.data(), size_);\n        return hash_stream.digest();\n    }\nprivate:\n    fs::wpath path_;\n    uintmax_t size_;\n    std::optional<xxh::hash64_t> hash_;\n};\n\nusing vector_type = std::vector<file_entry>;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n    size_t found = 0, ignored = 0;\n    if (!fs::is_directory(path)) {\n        std::cerr << path << \" is not a directory!\" << std::endl;\n    }\n    else {\n        std::cerr << \"Searching \" << path << std::endl;\n\n        for (auto& e : fs::recursive_directory_iterator(path)) {\n            ++found;\n            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n                file_vector.emplace_back(e);\n            else ++ignored;\n        }\n    }\n    return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n    vector_type files;\n    for (auto i = 1; i < argn; ++i) {\n        fs::wpath path(argv[i]);\n        auto [found, ignored] = find_files_in_dir(path, files);\n        std::cerr << boost::format{\n            \"  %1$6d files found\\n\"\n            \"  %2$6d files ignored\\n\"\n            \"  %3$6d files added\\n\" } % found % ignored % (found - ignored) \n            << std::endl;\n    }\n\n    std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n    \n    std::sort(std::execution::par_unseq, files.begin(), files.end()\n        , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n    );\n    for_each_adjacent_range(\n        std::begin(files)\n        , std::end(files)\n        , [](vector_type::value_type const& f) { return f.size(); }\n        , [](auto start, auto end, auto file_size) {\n            \n            size_t nr_of_files = std::distance(start, end);\n            if (nr_of_files > 1) {\n                \n                std::sort(start, end, [](auto& a, auto& b) { \n                    auto const& ha = a.get_hash();\n                    auto const& hb = b.get_hash();\n                    auto const& pa = a.path();\n                    auto const& pb = b.path();\n                    return std::tie(ha, pa) < std::tie(hb, pb); \n                    });\n                for_each_adjacent_range(\n                    start\n                    , end\n                    , [](vector_type::value_type& f) { return f.get_hash(); }\n                    , [file_size](auto hstart, auto hend, auto hash) {\n                        \n                        \n                        size_t hnr_of_files = std::distance(hstart, hend);\n                        if (hnr_of_files > 1) {\n                            std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n                                % hnr_of_files % file_size % hash;\n                            std::for_each(hstart, hend, [hash, file_size](auto& e) {\n                                std::cout << '\\t' << e.path() << '\\n';\n                                }\n                            );\n                        }\n                    }\n                );\n            }\n        }\n    );\n    \n    return 0;\n}\n"}
{"id": 56431, "name": "Sylvester's sequence", "Python": "\n\nfrom functools import reduce\nfrom itertools import count, islice\n\n\n\ndef sylvester():\n    \n    def go(n):\n        return 1 + reduce(\n            lambda a, x: a * go(x),\n            range(0, n),\n            1\n        ) if 0 != n else 2\n\n    return map(go, count(0))\n\n\n\n\ndef main():\n    \n\n    print(\"First 10 terms of OEIS A000058:\")\n    xs = list(islice(sylvester(), 10))\n    print('\\n'.join([\n        str(x) for x in xs\n    ]))\n\n    print(\"\\nSum of the reciprocals of the first 10 terms:\")\n    print(\n        reduce(lambda a, x: a + 1 / x, xs, 0)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing integer = boost::multiprecision::cpp_int;\nusing rational = boost::rational<integer>;\n\ninteger sylvester_next(const integer& n) {\n    return n * n - n + 1;\n}\n\nint main() {\n    std::cout << \"First 10 elements in Sylvester's sequence:\\n\";\n    integer term = 2;\n    rational sum = 0;\n    for (int i = 1; i <= 10; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        sum += rational(1, term);\n        term = sylvester_next(term);\n    }\n    std::cout << \"Sum of reciprocals: \" << sum << '\\n';\n}\n"}
{"id": 56432, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56433, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56434, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 56435, "name": "Order disjoint list items", "Python": "from __future__ import print_function\n\ndef order_disjoint_list_items(data, items):\n    \n    itemindices = []\n    for item in set(items):\n        itemcount = items.count(item)\n        \n        lastindex = [-1]\n        for i in range(itemcount):\n            lastindex.append(data.index(item, lastindex[-1] + 1))\n        itemindices += lastindex[1:]\n    itemindices.sort()\n    for index, item in zip(itemindices, items):\n        data[index] = item\n\nif __name__ == '__main__':\n    tostring = ' '.join\n    for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),\n                         (str.split('the cat sat on the mat'), str.split('cat mat')),\n                         (list('ABCABCABC'), list('CACA')),\n                         (list('ABCABDABE'), list('EADA')),\n                         (list('AB'), list('B')),\n                         (list('AB'), list('BA')),\n                         (list('ABBA'), list('BA')),\n                         (list(''), list('')),\n                         (list('A'), list('A')),\n                         (list('AB'), list('')),\n                         (list('ABBA'), list('AB')),\n                         (list('ABAB'), list('AB')),\n                         (list('ABAB'), list('BABA')),\n                         (list('ABCCBA'), list('ACAC')),\n                         (list('ABCCBA'), list('CACA')),\n                       ]:\n        print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')\n        order_disjoint_list_items(data, items)\n        print(\"-> M' %r\" % tostring(data))\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\ntemplate <typename T>\nvoid print(const std::vector<T> v) {\n  std::cout << \"{ \";\n  for (const auto& e : v) {\n    std::cout << e << \" \";\n  }\n  std::cout << \"}\";\n}\n\ntemplate <typename T>\nauto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {\n  std::vector<T*> M_p(std::size(M));\n  for (auto i = 0; i < std::size(M_p); ++i) {\n    M_p[i] = &M[i];\n  }\n  for (auto e : N) {\n    auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {\n      if (c != nullptr) {\n        if (*c == e) return true;\n      }\n      return false;\n    });\n    if (i != std::end(M_p)) {\n      *i = nullptr;\n    }\n  }\n  for (auto i = 0; i < std::size(N); ++i) {\n    auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {\n      return c == nullptr;\n    });\n    if (j != std::end(M_p)) {\n      *j = &M[std::distance(std::begin(M_p), j)];\n      **j = N[i];\n    }\n  }\n  return M;\n}\n\nint main() {\n  std::vector<std::vector<std::vector<std::string>>> l = {\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" }, { \"mat\", \"cat\" } },\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" },{ \"cat\", \"mat\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"C\", \"A\", \"B\", \"C\" },{ \"C\", \"A\", \"C\", \"A\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"D\", \"A\", \"B\", \"E\" },{ \"E\", \"A\", \"D\", \"A\" } },\n    { { \"A\", \"B\" },{ \"B\" } },\n    { { \"A\", \"B\" },{ \"B\", \"A\" } },\n    { { \"A\", \"B\", \"B\", \"A\" },{ \"B\", \"A\" } }\n  };\n  for (const auto& e : l) {\n    std::cout << \"M: \";\n    print(e[0]);\n    std::cout << \", N: \";\n    print(e[1]);\n    std::cout << \", M': \";\n    auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);\n    print(res);\n    std::cout << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 56436, "name": "Here document", "Python": "print()\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 56437, "name": "Here document", "Python": "print()\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 56438, "name": "Here document", "Python": "print()\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 56439, "name": "Here document", "Python": "print()\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 56440, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 56441, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 56442, "name": "Achilles numbers", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 56443, "name": "Achilles numbers", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 56444, "name": "Odd squarefree semiprimes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n"}
{"id": 56445, "name": "Odd squarefree semiprimes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n"}
{"id": 56446, "name": "Sierpinski curve", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n"}
{"id": 56447, "name": "Sierpinski curve", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n"}
{"id": 56448, "name": "Most frequent k chars distance", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n", "C++": "#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <sstream>\n\nstd::string mostFreqKHashing ( const std::string & input , int k ) {\n   std::ostringstream oss ;\n   std::map<char, int> frequencies ;\n   for ( char c : input ) {\n      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;\n   }\n   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;\n   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,\n\t         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; \n\t         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }\n\t         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;\n   for ( int i = 0 ; i < letters.size( ) ; i++ ) {\n      oss << std::get<0>( letters[ i ] ) ;\n      oss << std::get<1>( letters[ i ] ) ;\n   }\n   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;\n   if ( letters.size( ) >= k ) {\n      return output ;\n   }\n   else {\n      return output.append( \"NULL0\" ) ;\n   }\n}\n\nint mostFreqKSimilarity ( const std::string & first , const std::string & second ) {\n   int i = 0 ;\n   while ( i < first.length( ) - 1  ) {\n      auto found = second.find_first_of( first.substr( i , 2 ) ) ;\n      if ( found != std::string::npos ) \n\t return std::stoi ( first.substr( i , 2 )) ;\n      else \n\t i += 2 ;\n   }\n   return 0 ;\n}\n\nint mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {\n   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;\n}\n\nint main( ) {\n   std::string s1(\"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\" ) ;\n   std::string s2( \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\" ) ;\n   std::cout << \"MostFreqKHashing( s1 , 2 ) = \" << mostFreqKHashing( s1 , 2 ) << '\\n' ;\n   std::cout << \"MostFreqKHashing( s2 , 2 ) = \" << mostFreqKHashing( s2 , 2 ) << '\\n' ;\n   return 0 ;\n}\n"}
{"id": 56449, "name": "Palindromic primes", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n"}
{"id": 56450, "name": "Palindromic primes", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n"}
{"id": 56451, "name": "Find words which contains all the vowels", "Python": "import urllib.request\nfrom collections import Counter\n\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>10:\n        frequency = Counter(word.lower())\n        if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:\n            print(word)\n", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\nbool contains_all_vowels_once(const std::string& word) {\n    std::bitset<5> vowels;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        size_t bit = 0;\n        switch (ch) {\n        case 'a': bit = 0; break;\n        case 'e': bit = 1; break;\n        case 'i': bit = 2; break;\n        case 'o': bit = 3; break;\n        case 'u': bit = 4; break;\n        default: continue;\n        }\n        if (vowels.test(bit))\n            return false;\n        vowels.set(bit);\n    }\n    return vowels.all();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        if (word.size() > 10 && contains_all_vowels_once(word))\n            std::cout << std::setw(2) << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56452, "name": "Tropical algebra overloading", "Python": "from numpy import Inf\n\nclass MaxTropical:\n    \n    def __init__(self, x=0):\n        self.x = x\n\n    def __str__(self):\n        return str(self.x)\n\n    def __add__(self, other):\n        return MaxTropical(max(self.x, other.x))\n\n    def __mul__(self, other):\n        return MaxTropical(self.x + other.x)\n\n    def __pow__(self, other):\n        assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n        return MaxTropical(self.x * other.x)\n\n    def __eq__(self, other):\n        return self.x == other.x\n\n\nif __name__ == \"__main__\":\n    a = MaxTropical(-2)\n    b = MaxTropical(-1)\n    c = MaxTropical(-0.5)\n    d = MaxTropical(-0.001)\n    e = MaxTropical(0)\n    f = MaxTropical(0.5)\n    g = MaxTropical(1)\n    h = MaxTropical(1.5)\n    i = MaxTropical(2)\n    j = MaxTropical(5)\n    k = MaxTropical(7)\n    l = MaxTropical(8)\n    m = MaxTropical(-Inf)\n\n    print(\"2 * -2 == \", i * a)\n    print(\"-0.001 + -Inf == \", d + m)\n    print(\"0 * -Inf == \", e * m)\n    print(\"1.5 + -1 == \", h + b)\n    print(\"-0.5 * 0 == \", c * e)\n    print(\"5**7 == \", j**k)\n    print(\"5 * (8 + 7)) == \", j * (l + k))\n    print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n    print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n", "C++": "#include <iostream>\n#include <optional>\n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n    \n    optional<double> m_value;\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n    \n    \n    TropicalAlgebra() = default;\n\n    \n    explicit TropicalAlgebra(double value) noexcept\n        : m_value{value} {}\n\n    \n    \n    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            *this = rhs;\n        }\n        else if (!rhs.m_value)\n        {\n            \n        }\n        else\n        {\n            \n            *m_value = max(*rhs.m_value, *m_value);\n        }\n\n        return *this;\n    }\n    \n    \n    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            \n        }\n        else if (!rhs.m_value)\n        {\n            \n            *this = rhs;\n        }\n        else\n        {\n            *m_value += *rhs.m_value;\n        }\n\n        return *this;\n    }\n};\n\n\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n    \n    lhs += rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n    auto result = base;\n    for(unsigned int i = 1; i < exponent; i++)\n    {\n        \n        result *= base;\n    }\n    return result;\n}\n\n\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n    if(!pt.m_value) cout << \"-Inf\\n\";\n    else cout << *pt.m_value << \"\\n\";\n    return os;\n}\n\nint main(void) {\n    const TropicalAlgebra a(-2);\n    const TropicalAlgebra b(-1);\n    const TropicalAlgebra c(-0.5);\n    const TropicalAlgebra d(-0.001);\n    const TropicalAlgebra e(0);\n    const TropicalAlgebra h(1.5);\n    const TropicalAlgebra i(2);\n    const TropicalAlgebra j(5);\n    const TropicalAlgebra k(7);\n    const TropicalAlgebra l(8);\n    const TropicalAlgebra m; \n    \n    cout << \"2 * -2 == \" << i * a;\n    cout << \"-0.001 + -Inf == \" << d + m;\n    cout << \"0 * -Inf == \" << e * m;\n    cout << \"1.5 + -1 == \" << h + b;\n    cout << \"-0.5 * 0 == \" << c * e;\n    cout << \"pow(5, 7) == \" << pow(j, 7);\n    cout << \"5 * (8 + 7)) == \" << j * (l + k);\n    cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n"}
{"id": 56453, "name": "Tropical algebra overloading", "Python": "from numpy import Inf\n\nclass MaxTropical:\n    \n    def __init__(self, x=0):\n        self.x = x\n\n    def __str__(self):\n        return str(self.x)\n\n    def __add__(self, other):\n        return MaxTropical(max(self.x, other.x))\n\n    def __mul__(self, other):\n        return MaxTropical(self.x + other.x)\n\n    def __pow__(self, other):\n        assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n        return MaxTropical(self.x * other.x)\n\n    def __eq__(self, other):\n        return self.x == other.x\n\n\nif __name__ == \"__main__\":\n    a = MaxTropical(-2)\n    b = MaxTropical(-1)\n    c = MaxTropical(-0.5)\n    d = MaxTropical(-0.001)\n    e = MaxTropical(0)\n    f = MaxTropical(0.5)\n    g = MaxTropical(1)\n    h = MaxTropical(1.5)\n    i = MaxTropical(2)\n    j = MaxTropical(5)\n    k = MaxTropical(7)\n    l = MaxTropical(8)\n    m = MaxTropical(-Inf)\n\n    print(\"2 * -2 == \", i * a)\n    print(\"-0.001 + -Inf == \", d + m)\n    print(\"0 * -Inf == \", e * m)\n    print(\"1.5 + -1 == \", h + b)\n    print(\"-0.5 * 0 == \", c * e)\n    print(\"5**7 == \", j**k)\n    print(\"5 * (8 + 7)) == \", j * (l + k))\n    print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n    print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n", "C++": "#include <iostream>\n#include <optional>\n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n    \n    optional<double> m_value;\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n    \n    \n    TropicalAlgebra() = default;\n\n    \n    explicit TropicalAlgebra(double value) noexcept\n        : m_value{value} {}\n\n    \n    \n    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            *this = rhs;\n        }\n        else if (!rhs.m_value)\n        {\n            \n        }\n        else\n        {\n            \n            *m_value = max(*rhs.m_value, *m_value);\n        }\n\n        return *this;\n    }\n    \n    \n    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            \n        }\n        else if (!rhs.m_value)\n        {\n            \n            *this = rhs;\n        }\n        else\n        {\n            *m_value += *rhs.m_value;\n        }\n\n        return *this;\n    }\n};\n\n\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n    \n    lhs += rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n    auto result = base;\n    for(unsigned int i = 1; i < exponent; i++)\n    {\n        \n        result *= base;\n    }\n    return result;\n}\n\n\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n    if(!pt.m_value) cout << \"-Inf\\n\";\n    else cout << *pt.m_value << \"\\n\";\n    return os;\n}\n\nint main(void) {\n    const TropicalAlgebra a(-2);\n    const TropicalAlgebra b(-1);\n    const TropicalAlgebra c(-0.5);\n    const TropicalAlgebra d(-0.001);\n    const TropicalAlgebra e(0);\n    const TropicalAlgebra h(1.5);\n    const TropicalAlgebra i(2);\n    const TropicalAlgebra j(5);\n    const TropicalAlgebra k(7);\n    const TropicalAlgebra l(8);\n    const TropicalAlgebra m; \n    \n    cout << \"2 * -2 == \" << i * a;\n    cout << \"-0.001 + -Inf == \" << d + m;\n    cout << \"0 * -Inf == \" << e * m;\n    cout << \"1.5 + -1 == \" << h + b;\n    cout << \"-0.5 * 0 == \" << c * e;\n    cout << \"pow(5, 7) == \" << pow(j, 7);\n    cout << \"5 * (8 + 7)) == \" << j * (l + k);\n    cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n"}
{"id": 56454, "name": "Pig the dice game_Player", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 56455, "name": "Pig the dice game_Player", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 56456, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n"}
{"id": 56457, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n"}
{"id": 56458, "name": "Base 16 numbers needing a to f", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n"}
{"id": 56459, "name": "Base 16 numbers needing a to f", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n"}
{"id": 56460, "name": "Base 16 numbers needing a to f", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n"}
{"id": 56461, "name": "Range modifications", "Python": "class Sequence():\n    \n    def __init__(self, sequence_string):\n        self.ranges = self.to_ranges(sequence_string)\n        assert self.ranges == sorted(self.ranges), \"Sequence order error\"\n        \n    def to_ranges(self, txt):\n        return [[int(x) for x in r.strip().split('-')]\n                for r in txt.strip().split(',') if r]\n    \n    def remove(self, rem):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= rem <= r[1]:\n                if r[0] == rem:     \n                    if r[1] > rem:\n                        r[0] += 1\n                    else:\n                        del ranges[i]\n                elif r[1] == rem:   \n                    if r[0] < rem:\n                        r[1] -= 1\n                    else:\n                        del ranges[i]\n                else:               \n                    r[1], splitrange = rem - 1, [rem + 1, r[1]]\n                    ranges.insert(i + 1, splitrange)\n                break\n            if r[0] > rem:  \n                break\n        return self\n            \n    def add(self, add):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= add <= r[1]:     \n                break\n            elif r[0] - 1 == add:      \n                r[0] = add\n                break\n            elif r[1] + 1 == add:      \n                r[1] = add\n                break\n            elif r[0] > add:      \n                ranges.insert(i, [add, add])\n                break\n        else:\n            ranges.append([add, add])\n            return self\n        return self.consolidate()\n    \n    def consolidate(self):\n        \"Combine overlapping ranges\"\n        ranges = self.ranges\n        for this, that in zip(ranges, ranges[1:]):\n            if this[1] + 1 >= that[0]:  \n                if this[1] >= that[1]:  \n                    this[:], that[:] = [], this\n                else:   \n                    this[:], that[:] = [], [this[0], that[1]]\n        ranges[:] = [r for r in ranges if r]\n        return self\n    def __repr__(self):\n        rr = self.ranges\n        return \",\".join(f\"{r[0]}-{r[1]}\" for r in rr)\n\ndef demo(opp_txt):\n    by_line = opp_txt.strip().split('\\n')\n    start = by_line.pop(0)\n    ex = Sequence(start.strip().split()[-1][1:-1])    \n    lines = [line.strip().split() for line in by_line]\n    opps = [((ex.add if word[0] == \"add\" else ex.remove), int(word[1]))\n            for word in lines]\n    print(f\"Start: \\\"{ex}\\\"\")\n    for op, val in opps:\n        print(f\"    {op.__name__:>6} {val:2} => {op(val)}\")\n    print()\n                    \nif __name__ == '__main__':\n    demo()\n    demo()\n    demo()\n", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <list>\n\nstruct range {\n    range(int lo, int hi) : low(lo), high(hi) {}\n    int low;\n    int high;\n};\n\nstd::ostream& operator<<(std::ostream& out, const range& r) {\n    return out << r.low << '-' << r.high;\n}\n\nclass ranges {\npublic:\n    ranges() {}\n    explicit ranges(std::initializer_list<range> init) : ranges_(init) {}\n    void add(int n);\n    void remove(int n);\n    bool empty() const { return ranges_.empty(); }\nprivate:\n    friend std::ostream& operator<<(std::ostream& out, const ranges& r);\n    std::list<range> ranges_;\n};\n\nvoid ranges::add(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n + 1 < i->low) {\n            ranges_.emplace(i, n, n);\n            return;\n        }\n        if (n > i->high + 1)\n            continue;\n        if (n + 1 == i->low)\n            i->low = n;\n        else if (n == i->high + 1)\n            i->high = n;\n        else\n            return;\n        if (i != ranges_.begin()) {\n            auto prev = std::prev(i);\n            if (prev->high + 1 == i->low) {\n                i->low = prev->low;\n                ranges_.erase(prev);\n            }\n        }\n        auto next = std::next(i);\n        if (next != ranges_.end() && next->low - 1 == i->high) {\n            i->high = next->high;\n            ranges_.erase(next);\n        }\n        return;\n    }\n    ranges_.emplace_back(n, n);\n}\n\nvoid ranges::remove(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n < i->low)\n            return;\n        if (n == i->low) {\n            if (++i->low > i->high)\n                ranges_.erase(i);\n            return;\n        }\n        if (n == i->high) {\n            if (--i->high < i->low)\n                ranges_.erase(i);\n            return;\n        }\n        if (n > i->low & n < i->high) {\n            int low = i->low;\n            i->low = n + 1;\n            ranges_.emplace(i, low, n - 1);\n            return;\n        }\n    }\n}\n\nstd::ostream& operator<<(std::ostream& out, const ranges& r) {\n    if (!r.empty()) {\n        auto i = r.ranges_.begin();\n        out << *i++;\n        for (; i != r.ranges_.end(); ++i)\n            out << ',' << *i;\n    }\n    return out;\n}\n\nvoid test_add(ranges& r, int n) {\n    r.add(n);\n    std::cout << \"       add \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test_remove(ranges& r, int n) {\n    r.remove(n);\n    std::cout << \"    remove \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test1() {\n    ranges r;\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 77);\n    test_add(r, 79);\n    test_add(r, 78);\n    test_remove(r, 77);\n    test_remove(r, 78);\n    test_remove(r, 79);\n}\n\nvoid test2() {\n    ranges r{{1,3}, {5,5}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 1);\n    test_remove(r, 4);\n    test_add(r, 7);\n    test_add(r, 8);\n    test_add(r, 6);\n    test_remove(r, 7);\n}\n\nvoid test3() {\n    ranges r{{1,5}, {10,25}, {27,30}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 26);\n    test_add(r, 9);\n    test_add(r, 7);\n    test_remove(r, 26);\n    test_remove(r, 9);\n    test_remove(r, 7);\n}\n\nint main() {\n    test1();\n    std::cout << '\\n';\n    test2();\n    std::cout << '\\n';\n    test3();\n    return 0;\n}\n"}
{"id": 56462, "name": "Juggler sequence", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n"}
{"id": 56463, "name": "Juggler sequence", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n"}
{"id": 56464, "name": "Sierpinski square curve", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n"}
{"id": 56465, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 56466, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 56467, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 56468, "name": "Fixed length records", "Python": "infile = open('infile.dat', 'rb')\noutfile = open('outfile.dat', 'wb')\n\nwhile True:\n    onerecord = infile.read(80)\n    if len(onerecord) < 80:\n        break\n    onerecordreversed = bytes(reversed(onerecord))\n    outfile.write(onerecordreversed)\n\ninfile.close()\noutfile.close()\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nvoid reverse(std::istream& in, std::ostream& out) {\n    constexpr size_t record_length = 80;\n    char record[record_length];\n    while (in.read(record, record_length)) {\n        std::reverse(std::begin(record), std::end(record));\n        out.write(record, record_length);\n    }\n    out.flush();\n}\n\nint main(int argc, char** argv) {\n    std::ifstream in(\"infile.dat\", std::ios_base::binary);\n    if (!in) {\n        std::cerr << \"Cannot open input file\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ofstream out(\"outfile.dat\", std::ios_base::binary);\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        in.exceptions(std::ios_base::badbit);\n        out.exceptions(std::ios_base::badbit);\n        reverse(in, out);\n    } catch (const std::exception& ex) {\n        std::cerr << \"I/O error: \" << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56469, "name": "Find words whose first and last three letters are equal", "Python": "import urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>5 and word[:3].lower()==word[-3:].lower():\n        print(word)\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        const size_t len = word.size();\n        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)\n            std::cout << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56470, "name": "Giuga numbers", "Python": "\n\nfrom math import sqrt\n\ndef isGiuga(m):\n    n = m\n    f = 2\n    l = sqrt(n)\n    while True:\n        if n % f == 0:\n            if ((m / f) - 1) % f != 0:\n                return False\n            n /= f\n            if f > n:\n                return True\n        else:\n            f += 1\n            if f > l:\n                return False\n\n\nif __name__ == '__main__':\n    n = 3\n    c = 0\n    print(\"The first 4 Giuga numbers are: \")\n    while c < 4:\n        if isGiuga(n):\n            c += 1\n            print(n)\n        n += 1\n", "C++": "#include <iostream>\n\n\nbool is_giuga(unsigned int n) {\n    unsigned int m = n / 2;\n    auto test_factor = [&m, n](unsigned int p) -> bool {\n        if (m % p != 0)\n            return true;\n        m /= p;\n        return m % p != 0 && (n / p - 1) % p == 0;\n    };\n    if (!test_factor(3) || !test_factor(5))\n        return false;\n    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n    for (unsigned int p = 7, i = 0; p * p <= m; ++i) {\n        if (!test_factor(p))\n            return false;\n        p += wheel[i & 7];\n    }\n    return m == 1 || (n / m - 1) % m == 0;\n}\n\nint main() {\n    std::cout << \"First 5 Giuga numbers:\\n\";\n    \n    for (unsigned int i = 0, n = 6; i < 5; n += 4) {\n        if (is_giuga(n)) {\n            std::cout << n << '\\n';\n            ++i;\n        }\n    }\n}\n"}
{"id": 56471, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 56472, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 56473, "name": "Odd words", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing word_list = std::vector<std::pair<std::string, std::string>>;\n\nvoid print_words(std::ostream& out, const word_list& words) {\n    int n = 1;\n    for (const auto& pair : words) {\n        out << std::right << std::setw(2) << n++ << \": \"\n            << std::left << std::setw(14) << pair.first\n            << pair.second << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    const int min_length = 5;\n    std::string line;\n    std::set<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            dictionary.insert(line);\n    }\n\n    word_list odd_words, even_words;\n\n    for (const std::string& word : dictionary) {\n        if (word.size() < min_length + 2*(min_length/2))\n            continue;\n        std::string odd_word, even_word;\n        for (auto w = word.begin(); w != word.end(); ++w) {\n            odd_word += *w;\n            if (++w == word.end())\n                break;\n            even_word += *w;\n        }\n\n        if (dictionary.find(odd_word) != dictionary.end())\n            odd_words.emplace_back(word, odd_word);\n\n        if (dictionary.find(even_word) != dictionary.end())\n            even_words.emplace_back(word, even_word);\n    }\n\n    std::cout << \"Odd words:\\n\";\n    print_words(std::cout, odd_words);\n\n    std::cout << \"\\nEven words:\\n\";\n    print_words(std::cout, even_words);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56474, "name": "Tree datastructures", "Python": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n    if flat is None:\n        flat = []\n    if node:\n        flat.append((depth, node[0]))\n    for child in node[1]:\n        to_indent(child, depth + 1, flat)\n    return flat\n\ndef to_nest(lst, depth=0, level=None):\n    if level is None:\n        level = []\n    while lst:\n        d, name = lst[0]\n        if d == depth:\n            children = []\n            level.append((name, children))\n            lst.pop(0)\n        elif d > depth:  \n            to_nest(lst, d, children)\n        elif d < depth:  \n            return\n    return level[0] if level else None\n                    \nif __name__ == '__main__':\n    print('Start Nest format:')\n    nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n                            ('mocks', [('trolling', [])])])\n    pp(nest, width=25)\n\n    print('\\n... To Indent format:')\n    as_ind = to_indent(nest)\n    pp(as_ind, width=25)\n\n    print('\\n... To Nest format:')\n    as_nest = to_nest(as_ind)\n    pp(as_nest, width=25)\n\n    if nest != as_nest:\n        print(\"Whoops round-trip issues\")\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n#include <utility>\n#include <vector>\n\nclass nest_tree;\n\nbool operator==(const nest_tree&, const nest_tree&);\n\nclass nest_tree {\npublic:\n    explicit nest_tree(const std::string& name) : name_(name) {}\n    nest_tree& add_child(const std::string& name) {\n        children_.emplace_back(name);\n        return children_.back();\n    }\n    void print(std::ostream& out) const {\n        print(out, 0);\n    }\n    const std::string& name() const {\n        return name_;\n    }\n    const std::list<nest_tree>& children() const {\n        return children_;\n    }\n    bool equals(const nest_tree& n) const {\n        return name_ == n.name_ && children_ == n.children_;\n    }\nprivate:\n    void print(std::ostream& out, int level) const {\n        std::string indent(level * 4, ' ');\n        out << indent << name_ << '\\n';\n        for (const nest_tree& child : children_)\n            child.print(out, level + 1);\n    }\n    std::string name_;\n    std::list<nest_tree> children_;\n};\n\nbool operator==(const nest_tree& a, const nest_tree& b) {\n    return a.equals(b);\n}\n\nclass indent_tree {\npublic:\n    explicit indent_tree(const nest_tree& n) {\n        items_.emplace_back(0, n.name());\n        from_nest(n, 0);\n    }\n    void print(std::ostream& out) const {\n        for (const auto& item : items_)\n            std::cout << item.first << ' ' << item.second << '\\n';\n    }\n    nest_tree to_nest() const {\n        nest_tree n(items_[0].second);\n        to_nest_(n, 1, 0);\n        return n;\n    }\nprivate:\n    void from_nest(const nest_tree& n, int level) {\n        for (const nest_tree& child : n.children()) {\n            items_.emplace_back(level + 1, child.name());\n            from_nest(child, level + 1);\n        }\n    }\n    size_t to_nest_(nest_tree& n, size_t pos, int level) const {\n        while (pos < items_.size() && items_[pos].first == level + 1) {\n            nest_tree& child = n.add_child(items_[pos].second);\n            pos = to_nest_(child, pos + 1, level + 1);\n        }\n        return pos;\n    }\n    std::vector<std::pair<int, std::string>> items_;\n};\n\nint main() {\n    nest_tree n(\"RosettaCode\");\n    auto& child1 = n.add_child(\"rocks\");\n    auto& child2 = n.add_child(\"mocks\");\n    child1.add_child(\"code\");\n    child1.add_child(\"comparison\");\n    child1.add_child(\"wiki\");\n    child2.add_child(\"trolling\");\n    \n    std::cout << \"Initial nest format:\\n\";\n    n.print(std::cout);\n    \n    indent_tree i(n);\n    std::cout << \"\\nIndent format:\\n\";\n    i.print(std::cout);\n    \n    nest_tree n2(i.to_nest());\n    std::cout << \"\\nFinal nest format:\\n\";\n    n2.print(std::cout);\n\n    std::cout << \"\\nAre initial and final nest formats equal? \"\n        << std::boolalpha << n.equals(n2) << '\\n';\n    \n    return 0;\n}\n"}
{"id": 56475, "name": "Selectively replace multiple instances of a character within a string", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n"}
{"id": 56476, "name": "Selectively replace multiple instances of a character within a string", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n"}
{"id": 56477, "name": "Repunit primes", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 56478, "name": "Repunit primes", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 56479, "name": "Curzon numbers", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 56480, "name": "Curzon numbers", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 56481, "name": "Curzon numbers", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 56482, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56483, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56484, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56485, "name": "Respond to an unknown method call", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n"}
{"id": 56486, "name": "Word break problem", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n"}
{"id": 56487, "name": "Brilliant numbers", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 56488, "name": "Brilliant numbers", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 56489, "name": "Word ladder", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n\nbool one_away(const std::string& s1, const std::string& s2) {\n    if (s1.size() != s2.size())\n        return false;\n    bool result = false;\n    for (size_t i = 0, n = s1.size(); i != n; ++i) {\n        if (s1[i] != s2[i]) {\n            if (result)\n                return false;\n            result = true;\n        }\n    }\n    return result;\n}\n\n\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n                 separator_type separator) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += separator;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\n\n\n\nbool word_ladder(const word_map& words, const std::string& from,\n                 const std::string& to) {\n    auto w = words.find(from.size());\n    if (w != words.end()) {\n        auto poss = w->second;\n        std::vector<std::vector<std::string>> queue{{from}};\n        while (!queue.empty()) {\n            auto curr = queue.front();\n            queue.erase(queue.begin());\n            for (auto i = poss.begin(); i != poss.end();) {\n                if (!one_away(*i, curr.back())) {\n                    ++i;\n                    continue;\n                }\n                if (to == *i) {\n                    curr.push_back(to);\n                    std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n                    return true;\n                }\n                std::vector<std::string> temp(curr);\n                temp.push_back(*i);\n                queue.push_back(std::move(temp));\n                i = poss.erase(i);\n            }\n        }\n    }\n    std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n    return false;\n}\n\nint main() {\n    word_map words;\n    std::ifstream in(\"unixdict.txt\");\n    if (!in) {\n        std::cerr << \"Cannot open file unixdict.txt.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    while (getline(in, word))\n        words[word.size()].push_back(word);\n    word_ladder(words, \"boy\", \"man\");\n    word_ladder(words, \"girl\", \"lady\");\n    word_ladder(words, \"john\", \"jane\");\n    word_ladder(words, \"child\", \"adult\");\n    word_ladder(words, \"cat\", \"dog\");\n    word_ladder(words, \"lead\", \"gold\");\n    word_ladder(words, \"white\", \"black\");\n    word_ladder(words, \"bubble\", \"tickle\");\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56490, "name": "Joystick position", "Python": "import sys\nimport pygame\n\npygame.init()\n\n\nclk = pygame.time.Clock()\n\n\nif pygame.joystick.get_count() == 0:\n    raise IOError(\"No joystick detected\")\njoy = pygame.joystick.Joystick(0)\njoy.init()\n\n\nsize = width, height = 600, 600\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Joystick Tester\")\n\n\nframeRect = pygame.Rect((45, 45), (510, 510))\n\n\ncrosshair = pygame.surface.Surface((10, 10))\ncrosshair.fill(pygame.Color(\"magenta\"))\npygame.draw.circle(crosshair, pygame.Color(\"blue\"), (5,5), 5, 0)\ncrosshair.set_colorkey(pygame.Color(\"magenta\"), pygame.RLEACCEL)\ncrosshair = crosshair.convert()\n\n\nwriter = pygame.font.Font(pygame.font.get_default_font(), 15)\nbuttons = {}\nfor b in range(joy.get_numbuttons()):\n    buttons[b] = [\n        writer.render(\n            hex(b)[2:].upper(),\n            1,\n            pygame.Color(\"red\"),\n            pygame.Color(\"black\")\n        ).convert(),\n        \n        \n        ((15*b)+45, 560)\n    ]\n\nwhile True:\n    \n    pygame.event.pump()\n    for events in pygame.event.get():\n        if events.type == pygame.QUIT:\n            pygame.quit()\n            sys.exit()\n\n    \n    screen.fill(pygame.Color(\"black\"))\n\n    \n    x = joy.get_axis(0)\n    y = joy.get_axis(1)\n\n    \n    \n    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))\n    pygame.draw.rect(screen, pygame.Color(\"red\"), frameRect, 1)\n\n    \n    for b in range(joy.get_numbuttons()):\n        if joy.get_button(b):\n            screen.blit(buttons[b][0], buttons[b][1])\n\n    \n    pygame.display.flip()\n    clk.tick(40) \n", "C++": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid clear() {\n\tfor(int n = 0;n < 10; n++) {\n\t\tprintf(\"\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\r\\n\\r\\n\\r\\n\");\n\t}\n}\n\n#define UP    \"00^00\\r\\n00|00\\r\\n00000\\r\\n\"\n#define DOWN  \"00000\\r\\n00|00\\r\\n00v00\\r\\n\"\n#define LEFT  \"00000\\r\\n<--00\\r\\n00000\\r\\n\"\n#define RIGHT \"00000\\r\\n00-->\\r\\n00000\\r\\n\"\n#define HOME  \"00000\\r\\n00+00\\r\\n00000\\r\\n\"\n\nint main() {\n\tclear();\n\tsystem(\"stty raw\");\n\n\tprintf(HOME);\n\tprintf(\"space to exit; wasd to move\\r\\n\");\n\tchar c = 1;\n\n\twhile(c) {\n\t\tc = getc(stdin);\n\t\tclear();\n\n\t\tswitch (c)\n\t\t{\n\t\t\tcase 'a':\n\t\t\t\tprintf(LEFT);\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tprintf(RIGHT);\n\t\t\t\tbreak;\n\t\t\tcase 'w':\n\t\t\t\tprintf(UP);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tprintf(DOWN);\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tc = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprintf(HOME);\n\t\t};\n\n\t\tprintf(\"space to exit; wasd key to move\\r\\n\");\n\t}\n\n\tsystem(\"stty cooked\");\n\tsystem(\"clear\"); \n\treturn 1;\n}\n"}
{"id": 56491, "name": "Earliest difference between prime gaps", "Python": "\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n    if pri[i] - pri[i - 1] not in gapstarts:\n        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n    while GAP1 not in gapstarts:\n        GAP1 += 2\n    start1 = gapstarts[GAP1]\n    GAP2 = GAP1 + 2\n    if GAP2 not in gapstarts:\n        GAP1 = GAP2 + 2\n        continue\n    start2 = gapstarts[GAP2]\n    diff = abs(start2 - start1)\n    if diff > PM:\n        print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n        print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n        if PM == LIMIT:\n            break\n        PM *= 10\n    else:\n        GAP1 = GAP2\n", "C++": "#include <iostream>\n#include <locale>\n#include <unordered_map>\n\n#include <primesieve.hpp>\n\nclass prime_gaps {\npublic:\n    prime_gaps() { last_prime_ = iterator_.next_prime(); }\n    uint64_t find_gap_start(uint64_t gap);\nprivate:\n    primesieve::iterator iterator_;\n    uint64_t last_prime_;\n    std::unordered_map<uint64_t, uint64_t> gap_starts_;\n};\n\nuint64_t prime_gaps::find_gap_start(uint64_t gap) {\n    auto i = gap_starts_.find(gap);\n    if (i != gap_starts_.end())\n        return i->second;\n    for (;;) {\n        uint64_t prev = last_prime_;\n        last_prime_ = iterator_.next_prime();\n        uint64_t diff = last_prime_ - prev;\n        gap_starts_.emplace(diff, prev);\n        if (gap == diff)\n            return prev;\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const uint64_t limit = 100000000000;\n    prime_gaps pg;\n    for (uint64_t pm = 10, gap1 = 2;;) {\n        uint64_t start1 = pg.find_gap_start(gap1);\n        uint64_t gap2 = gap1 + 2;\n        uint64_t start2 = pg.find_gap_start(gap2);\n        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;\n        if (diff > pm) {\n            std::cout << \"Earliest difference > \" << pm\n                      << \" between adjacent prime gap starting primes:\\n\"\n                      << \"Gap \" << gap1 << \" starts at \" << start1 << \", gap \"\n                      << gap2 << \" starts at \" << start2 << \", difference is \"\n                      << diff << \".\\n\\n\";\n            if (pm == limit)\n                break;\n            pm *= 10;\n        } else {\n            gap1 = gap2;\n        }\n    }\n}\n"}
{"id": 56492, "name": "Latin Squares in reduced form", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 56493, "name": "Ormiston pairs", "Python": "\n\nfrom sympy import primerange\n\n\nPRIMES1M = list(primerange(1, 1_000_000))\nASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M]\nORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M))\n             if ASBASE10SORT[i - 1] == ASBASE10SORT[i]]\n\nprint('First 30 Ormiston pairs:')\nfor (i, o) in enumerate(ORMISTONS):\n    if i < 30:\n        print(f'({o[0] : 6} {o[1] : 6} )',\n              end='\\n' if (i + 1) % 5 == 0 else '  ')\n    else:\n        break\n\nprint(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <utility>\n\n#include <primesieve.hpp>\n\nclass ormiston_pair_generator {\npublic:\n    ormiston_pair_generator() { prime_ = pi_.next_prime(); }\n    std::pair<uint64_t, uint64_t> next_pair() {\n        for (;;) {\n            uint64_t prime = prime_;\n            auto digits = digits_;\n            prime_ = pi_.next_prime();\n            digits_ = get_digits(prime_);\n            if (digits_ == digits)\n                return std::make_pair(prime, prime_);\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    uint64_t prime_;\n    std::array<int, 10> digits_;\n};\n\nint main() {\n    ormiston_pair_generator generator;\n    int count = 0;\n    std::cout << \"First 30 Ormiston pairs:\\n\";\n    for (; count < 30; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        std::cout << '(' << std::setw(5) << p1 << \", \" << std::setw(5) << p2\n                  << ')' << ((count + 1) % 3 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        if (p1 > limit) {\n            std::cout << \"Number of Ormiston pairs < \" << limit << \": \" << count\n                      << '\\n';\n            limit *= 10;\n        }\n    }\n}\n"}
{"id": 56494, "name": "UPC", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n"}
{"id": 56495, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 56496, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 56497, "name": "Harmonic series", "Python": "from  fractions import Fraction\n\ndef harmonic_series():\n    n, h = Fraction(1), Fraction(1)\n    while True:\n        yield h\n        h += 1 / (n + 1)\n        n += 1\n\nif __name__ == '__main__':\n    from itertools import islice\n    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):\n        print(n, '/', d)\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\nusing integer = boost::multiprecision::mpz_int;\nusing rational = boost::rational<integer>;\n\nclass harmonic_generator {\npublic:\n    rational next() {\n        rational result = term_;\n        term_ += rational(1, ++n_);\n        return result;\n    }\n    void reset() {\n        n_ = 1;\n        term_ = 1;\n    }\nprivate:\n    integer n_ = 1;\n    rational term_ = 1;\n};\n\nint main() {\n    std::cout << \"First 20 harmonic numbers:\\n\";\n    harmonic_generator hgen;\n    for (int i = 1; i <= 20; ++i)\n        std::cout << std::setw(2) << i << \". \" << hgen.next() << '\\n';\n    \n    rational h;\n    for (int i = 1; i <= 80; ++i)\n        h = hgen.next();\n    std::cout << \"\\n100th harmonic number: \" << h << \"\\n\\n\";\n\n    int n = 1;\n    hgen.reset();\n    for (int i = 1; n <= 10; ++i) {\n        if (hgen.next() > n)\n            std::cout << \"Position of first term > \" << std::setw(2) << n++ << \": \" << i << '\\n';\n    }\n}\n"}
{"id": 56498, "name": "External sort", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n"}
{"id": 56499, "name": "External sort", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n"}
{"id": 56500, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n)", "Python": "class NG:\n  def __init__(self, a1, a, b1, b):\n    self.a1, self.a, self.b1, self.b = a1, a, b1, b\n\n  def ingress(self, n):\n    self.a, self.a1 = self.a1, self.a + self.a1 * n\n    self.b, self.b1 = self.b1, self.b + self.b1 * n\n\n  @property\n  def needterm(self):\n    return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1\n\n  @property\n  def egress(self):\n    n = self.a // self.b\n    self.a,  self.b  = self.b,  self.a  - self.b  * n\n    self.a1, self.b1 = self.b1, self.a1 - self.b1 * n\n    return n\n\n  @property\n  def egress_done(self):\n    if self.needterm: self.a, self.b = self.a1, self.b1\n    return self.egress\n\n  @property\n  def done(self):\n    return self.b == 0 and self.b1 == 0\n", "C++": "\nclass matrixNG {\n  private:\n  virtual void consumeTerm(){}\n  virtual void consumeTerm(int n){}\n  virtual const bool needTerm(){}\n  protected: int cfn = 0, thisTerm;\n             bool haveTerm = false;\n  friend class NG;\n};\n\nclass NG_4 : public matrixNG {\n  private: int a1, a, b1, b, t;\n  const bool needTerm() {\n    if (b1==0 and b==0) return false;\n    if (b1==0 or b==0) return true; else thisTerm = a/b;\n    if (thisTerm==(int)(a1/b1)){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;\n      haveTerm=true; return false;\n    }\n    return true;\n  }\n  void consumeTerm(){a=a1; b=b1;}\n  void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}\n  public:\n  NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}\n};\n\nclass NG : public ContinuedFraction {\n  private:\n   matrixNG* ng;\n   ContinuedFraction* n[2];\n  public:\n  NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}\n  NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}\n  const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}\n  const bool moreTerms(){\n    while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();\n    return ng->haveTerm;\n  }\n};\n"}
{"id": 56501, "name": "Calkin-Wilf sequence", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n"}
{"id": 56502, "name": "Calkin-Wilf sequence", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n"}
{"id": 56503, "name": "Distribution of 0 digits in factorial series", "Python": "def facpropzeros(N, verbose = True):\n    proportions = [0.0] * N\n    fac, psum = 1, 0.0\n    for i in range(N):\n        fac *= i + 1\n        d = list(str(fac))\n        psum += sum(map(lambda x: x == '0', d)) / len(d)\n        proportions[i] = psum / (i + 1)\n\n    if verbose:\n        print(\"The mean proportion of 0 in factorials from 1 to {} is {}.\".format(N, psum / N))\n\n    return proportions\n\n\nfor n in [100, 1000, 10000]:\n    facpropzeros(n)\n\nprops = facpropzeros(47500, False)\nn = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))\n\nprint(\"The mean proportion dips permanently below 0.16 at {}.\".format(n + 2))\n", "C++": "#include <array>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nauto init_zc() {\n    std::array<int, 1000> zc;\n    zc.fill(0);\n    zc[0] = 3;\n    for (int x = 1; x <= 9; ++x) {\n        zc[x] = 2;\n        zc[10 * x] = 2;\n        zc[100 * x] = 2;\n        for (int y = 10; y <= 90; y += 10) {\n            zc[y + x] = 1;\n            zc[10 * y + x] = 1;\n            zc[10 * (y + x)] = 1;\n        }\n    }\n    return zc;\n}\n\ntemplate <typename clock_type>\nauto elapsed(const std::chrono::time_point<clock_type>& t0) {\n    auto t1 = clock_type::now();\n    auto duration =\n        std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);\n    return duration.count();\n}\n\nint main() {\n    auto zc = init_zc();\n    auto t0 = std::chrono::high_resolution_clock::now();\n    int trail = 1, first = 0;\n    double total = 0;\n    std::vector<int> rfs{1};\n    std::cout << std::fixed << std::setprecision(10);\n    for (int f = 2; f <= 50000; ++f) {\n        int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();\n        for (int j = trail - 1; j < len || carry != 0; ++j) {\n            if (j < len)\n                carry += rfs[j] * f;\n            d999 = carry % 1000;\n            if (j < len)\n                rfs[j] = d999;\n            else\n                rfs.push_back(d999);\n            zeroes += zc[d999];\n            carry /= 1000;\n        }\n        while (rfs[trail - 1] == 0)\n            ++trail;\n        d999 = rfs.back();\n        d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;\n        zeroes -= d999;\n        int digits = rfs.size() * 3 - d999;\n        total += double(zeroes) / digits;\n        double ratio = total / f;\n        if (ratio >= 0.16)\n            first = 0;\n        else if (first == 0)\n            first = f;\n        if (f == 100 || f == 1000 || f == 10000) {\n            std::cout << \"Mean proportion of zero digits in factorials to \" << f\n                      << \" is \" << ratio << \". (\" << elapsed(t0) << \"ms)\\n\";\n        }\n    }\n    std::cout << \"The mean proportion dips permanently below 0.16 at \" << first\n              << \". (\" << elapsed(t0) << \"ms)\\n\";\n}\n"}
{"id": 56504, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n"}
{"id": 56505, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n"}
{"id": 56506, "name": "Address of a variable", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n", "C++": "int i;\nvoid* address_of_i = &i;\n"}
{"id": 56507, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 56508, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "C++": "#include <map>\n"}
{"id": 56509, "name": "Color wheel", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 56510, "name": "Plasma effect", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n"}
{"id": 56511, "name": "Abelian sandpile model_Identity", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n"}
{"id": 56512, "name": "Abelian sandpile model_Identity", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n"}
{"id": 56513, "name": "Hello world_Newbie", "Python": "print \"Goodbye, World!\"\n", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n"}
{"id": 56514, "name": "Hello world_Newbie", "Python": "print \"Goodbye, World!\"\n", "C++": "#include <iostream>\nint main() {\n    using namespace std;\n    cout << \"Hello, World!\" << endl;\n    return 0;\n}\n"}
{"id": 56515, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56516, "name": "Wagstaff primes", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n"}
{"id": 56517, "name": "Wagstaff primes", "Python": "\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n    \n    pri, wcount = 1, 0\n    while wcount < N:\n        pri += 2\n        if isprime(pri):\n            wag = (2**pri + 1) // 3\n            if isprime(wag):\n                wcount += 1\n                print(f'{wcount: 3}: {pri: 5} => ', \n                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n", "C++": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n) {\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n        str += \" (\";\n        str += std::to_string(len);\n        str += \" digits)\";\n    }\n    return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n    const big_int one(1);\n    primesieve::iterator pi;\n    pi.next_prime();\n    for (int i = 0; i < 24;) {\n        uint64_t p = pi.next_prime();\n        big_int n = ((one << p) + 1) / 3;\n        if (is_probably_prime(n))\n            std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n    }\n}\n"}
{"id": 56518, "name": "Create an object_Native demonstration", "Python": "from collections import UserDict\nimport copy\n\nclass Dict(UserDict):\n    \n    def __init__(self, dict=None, **kwargs):\n        self.__init = True\n        super().__init__(dict, **kwargs)\n        self.default = copy.deepcopy(self.data)\n        self.__init = False\n    \n    def __delitem__(self, key):\n        if key in self.default:\n            self.data[key] = self.default[key]\n        else:\n            raise NotImplementedError\n\n    def __setitem__(self, key, item):\n        if self.__init:\n            super().__setitem__(key, item)\n        elif key in self.data:\n            self.data[key] = item\n        else:\n            raise KeyError\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, super().__repr__())\n    \n    def fromkeys(cls, iterable, value=None):\n        if self.__init:\n            super().fromkeys(cls, iterable, value)\n        else:\n            for key in iterable:\n                if key in self.data:\n                    self.data[key] = value\n                else:\n                    raise KeyError\n\n    def clear(self):\n        self.data.update(copy.deepcopy(self.default))\n\n    def pop(self, key, default=None):\n        raise NotImplementedError\n\n    def popitem(self):\n        raise NotImplementedError\n\n    def update(self, E, **F):\n        if self.__init:\n            super().update(E, **F)\n        else:\n            haskeys = False\n            try:\n                keys = E.keys()\n                haskeys = Ture\n            except AttributeError:\n                pass\n            if haskeys:\n                for key in keys:\n                    self[key] = E[key]\n            else:\n                for key, val in E:\n                    self[key] = val\n            for key in F:\n                self[key] = F[key]\n\n    def setdefault(self, key, default=None):\n        if key not in self.data:\n            raise KeyError\n        else:\n            return super().setdefault(key, default)\n", "C++": "#include <iostream>\n#include <map>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nclass FixedMap : private T\n{\n    \n    \n    \n    \n    \n    T m_defaultValues;\n    \npublic:\n    FixedMap(T map)\n    : T(map), m_defaultValues(move(map)){}\n    \n    \n    using T::cbegin;\n    using T::cend;\n    using T::empty;\n    using T::find;\n    using T::size;\n\n    \n    using T::at;\n    using T::begin;\n    using T::end;\n    \n    \n    \n    auto& operator[](typename T::key_type&& key)\n    {\n        \n        return this->at(forward<typename T::key_type>(key));\n    }\n    \n    \n    \n    void erase(typename T::key_type&& key)\n    {\n        T::operator[](key) = m_defaultValues.at(key);\n    }\n\n    \n    void clear()\n    {\n        \n        T::operator=(m_defaultValues);\n    }\n    \n};\n\n\nauto PrintMap = [](const auto &map)\n{\n    for(auto &[key, value] : map)\n    {\n        cout << \"{\" << key << \" : \" << value << \"} \";\n    }\n    cout << \"\\n\\n\";\n};\n\nint main(void) \n{\n    \n    cout << \"Map intialized with values\\n\";\n    FixedMap<map<string, int>> fixedMap ({\n        {\"a\", 1},\n        {\"b\", 2}});\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values of the keys\\n\";\n    fixedMap[\"a\"] = 55;\n    fixedMap[\"b\"] = 56;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset the 'a' key\\n\";\n    fixedMap.erase(\"a\");\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values the again\\n\";\n    fixedMap[\"a\"] = 88;\n    fixedMap[\"b\"] = 99;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset all keys\\n\";\n    fixedMap.clear();\n    PrintMap(fixedMap);\n  \n    try\n    {\n        \n        cout << \"Try to add a new key\\n\";\n        fixedMap[\"newKey\"] = 99;\n    }\n    catch (exception &ex)\n    {\n        cout << \"error: \" << ex.what();\n    }\n}\n"}
{"id": 56519, "name": "Magic numbers", "Python": "from itertools import groupby\n\ndef magic_numbers(base):\n    hist = []\n    n = l = i = 0\n    while True:\n        l += 1\n        hist.extend((n + digit, l) for digit in range(-n % l, base, l))\n        i += 1\n        if i == len(hist):\n            return hist\n        n, l = hist[i]\n        n *= base\n\nmn = magic_numbers(10)\nprint(\"found\", len(mn), \"magic numbers\")\nprint(\"the largest one is\", mn[-1][0])\n\nprint(\"count by number of digits:\")\nprint(*(f\"{l}:{sum(1 for _ in g)}\" for l, g in groupby(l for _, l in mn)))\n\nprint(end=\"minimally pandigital in 1..9: \")\nprint(*(m for m, l in mn if l == 9 == len(set(str(m)) - {\"0\"})))\nprint(end=\"minimally pandigital in 0..9: \")\nprint(*(m for m, l in mn if l == 10 == len(set(str(m)))))\n", "C++": "#include <array>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\nclass magic_number_generator {\npublic:\n    magic_number_generator() : magic_(10) {\n        std::iota(magic_.begin(), magic_.end(), 0);\n    }\n    bool next(uint128_t& n);\n\npublic:\n    std::vector<uint128_t> magic_;\n    size_t index_ = 0;\n    int digits_ = 2;\n};\n\nbool magic_number_generator::next(uint128_t& n) {\n    if (index_ == magic_.size()) {\n        std::vector<uint128_t> magic;\n        for (uint128_t m : magic_) {\n            if (m == 0)\n                continue;\n            uint128_t n = 10 * m;\n            for (int d = 0; d < 10; ++d, ++n) {\n                if (n % digits_ == 0)\n                    magic.push_back(n);\n            }\n        }\n        index_ = 0;\n        ++digits_;\n        magic_ = std::move(magic);\n    }\n    if (magic_.empty())\n        return false;\n    n = magic_[index_++];\n    return true;\n}\n\nstd::array<int, 10> get_digits(uint128_t n) {\n    std::array<int, 10> result = {};\n    for (; n > 0; n /= 10)\n        ++result[static_cast<int>(n % 10)];\n    return result;\n}\n\nint main() {\n    int count = 0, dcount = 0;\n    uint128_t magic = 0, p = 10;\n    std::vector<int> digit_count;\n\n    std::array<int, 10> digits0 = {1,1,1,1,1,1,1,1,1,1};\n    std::array<int, 10> digits1 = {0,1,1,1,1,1,1,1,1,1};\n    std::vector<uint128_t> pandigital0, pandigital1;\n\n    for (magic_number_generator gen; gen.next(magic);) {\n        if (magic >= p) {\n            p *= 10;\n            digit_count.push_back(dcount);\n            dcount = 0;\n        }\n        auto digits = get_digits(magic);\n        if (digits == digits0)\n            pandigital0.push_back(magic);\n        else if (digits == digits1)\n            pandigital1.push_back(magic);\n        ++count;\n        ++dcount;\n    }\n    digit_count.push_back(dcount);\n\n    std::cout << \"There are \" << count << \" magic numbers.\\n\\n\";\n    std::cout << \"The largest magic number is \" << magic << \".\\n\\n\";\n\n    std::cout << \"Magic number count by digits:\\n\";\n    for (int i = 0; i < digit_count.size(); ++i)\n        std::cout << i + 1 << '\\t' << digit_count[i] << '\\n';\n\n    std::cout << \"\\nMagic numbers that are minimally pandigital in 1-9:\\n\";\n    for (auto m : pandigital1)\n        std::cout << m << '\\n';\n\n    std::cout << \"\\nMagic numbers that are minimally pandigital in 0-9:\\n\";\n    for (auto m : pandigital0)\n        std::cout << m << '\\n';\n}\n"}
{"id": 56520, "name": "Iterators", "Python": "\nfrom collections import deque\nfrom typing import Iterable\nfrom typing import Iterator\nfrom typing import Reversible\n\n\ndays = [\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n    \"Sunday\",\n]\n\n\ncolors = deque(\n    [\n        \"red\",\n        \"yellow\",\n        \"pink\",\n        \"green\",\n        \"purple\",\n        \"orange\",\n        \"blue\",\n    ]\n)\n\n\nclass MyIterable:\n    class MyIterator:\n        def __init__(self) -> None:\n            self._day = -1\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day >= 6:\n                raise StopIteration\n\n            self._day += 1\n            return days[self._day]\n\n    class MyReversedIterator:\n        def __init__(self) -> None:\n            self._day = 7\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day <= 0:\n                raise StopIteration\n\n            self._day -= 1\n            return days[self._day]\n\n    def __iter__(self):\n        return self.MyIterator()\n\n    def __reversed__(self):\n        return self.MyReversedIterator()\n\n\ndef print_elements(container: Iterable[object]) -> None:\n    for element in container:\n        print(element, end=\" \")\n    print(\"\")  \n\n\ndef _drop(it: Iterator[object], n: int) -> None:\n    \n    try:\n        for _ in range(n):\n            next(it)\n    except StopIteration:\n        pass\n\n\ndef print_first_fourth_fifth(container: Iterable[object]) -> None:\n    \n    it = iter(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:\n    \n    it = reversed(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef main() -> None:\n    my_iterable = MyIterable()\n\n    print(\"All elements:\")\n    print_elements(days)\n    print_elements(colors)\n    print_elements(my_iterable)\n\n    print(\"\\nFirst, fourth, fifth:\")\n    print_first_fourth_fifth(days)\n    print_first_fourth_fifth(colors)\n    print_first_fourth_fifth(my_iterable)\n\n    print(\"\\nLast, fourth to last, fifth to last:\")\n    print_reversed_first_fourth_fifth(days)\n    print_reversed_first_fourth_fifth(colors)\n    print_reversed_first_fourth_fifth(my_iterable)\n\n\nif __name__ == \"__main__\":\n    main()\n", "C++": "#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\n\n\nvoid PrintContainer(forward_iterator auto start, forward_iterator auto sentinel)\n{\n  for(auto it = start; it != sentinel; ++it)\n  {\n    cout << *it << \" \"; \n  }\n  cout << \"\\n\";\n}\n\n\nvoid FirstFourthFifth(input_iterator auto it)\n{\n  cout << *it;\n  advance(it, 3);\n  cout << \", \" << *it;\n  advance(it, 1);\n  cout << \", \" << *it;\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  vector<string> days{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n   \"Thursday\", \"Friday\", \"Saturday\"};\n  list<string> colors{\"Red\", \"Orange\", \"Yellow\", \"Green\", \"Blue\", \"Purple\"};\n\n  cout << \"All elements:\\n\";\n  PrintContainer(days.begin(), days.end());\n  PrintContainer(colors.begin(), colors.end());\n  \n  cout << \"\\nFirst, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.begin());\n  FirstFourthFifth(colors.begin());\n\n  cout << \"\\nReverse first, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.rbegin());\n  FirstFourthFifth(colors.rbegin());\n}\n"}
{"id": 56521, "name": "Iterators", "Python": "\nfrom collections import deque\nfrom typing import Iterable\nfrom typing import Iterator\nfrom typing import Reversible\n\n\ndays = [\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n    \"Sunday\",\n]\n\n\ncolors = deque(\n    [\n        \"red\",\n        \"yellow\",\n        \"pink\",\n        \"green\",\n        \"purple\",\n        \"orange\",\n        \"blue\",\n    ]\n)\n\n\nclass MyIterable:\n    class MyIterator:\n        def __init__(self) -> None:\n            self._day = -1\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day >= 6:\n                raise StopIteration\n\n            self._day += 1\n            return days[self._day]\n\n    class MyReversedIterator:\n        def __init__(self) -> None:\n            self._day = 7\n\n        def __iter__(self):\n            return self\n\n        def __next__(self):\n            if self._day <= 0:\n                raise StopIteration\n\n            self._day -= 1\n            return days[self._day]\n\n    def __iter__(self):\n        return self.MyIterator()\n\n    def __reversed__(self):\n        return self.MyReversedIterator()\n\n\ndef print_elements(container: Iterable[object]) -> None:\n    for element in container:\n        print(element, end=\" \")\n    print(\"\")  \n\n\ndef _drop(it: Iterator[object], n: int) -> None:\n    \n    try:\n        for _ in range(n):\n            next(it)\n    except StopIteration:\n        pass\n\n\ndef print_first_fourth_fifth(container: Iterable[object]) -> None:\n    \n    it = iter(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:\n    \n    it = reversed(container)\n    print(next(it), end=\" \")\n    _drop(it, 2)\n    print(next(it), end=\" \")\n    print(next(it))\n\n\ndef main() -> None:\n    my_iterable = MyIterable()\n\n    print(\"All elements:\")\n    print_elements(days)\n    print_elements(colors)\n    print_elements(my_iterable)\n\n    print(\"\\nFirst, fourth, fifth:\")\n    print_first_fourth_fifth(days)\n    print_first_fourth_fifth(colors)\n    print_first_fourth_fifth(my_iterable)\n\n    print(\"\\nLast, fourth to last, fifth to last:\")\n    print_reversed_first_fourth_fifth(days)\n    print_reversed_first_fourth_fifth(colors)\n    print_reversed_first_fourth_fifth(my_iterable)\n\n\nif __name__ == \"__main__\":\n    main()\n", "C++": "#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\n\n\nvoid PrintContainer(forward_iterator auto start, forward_iterator auto sentinel)\n{\n  for(auto it = start; it != sentinel; ++it)\n  {\n    cout << *it << \" \"; \n  }\n  cout << \"\\n\";\n}\n\n\nvoid FirstFourthFifth(input_iterator auto it)\n{\n  cout << *it;\n  advance(it, 3);\n  cout << \", \" << *it;\n  advance(it, 1);\n  cout << \", \" << *it;\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  vector<string> days{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n   \"Thursday\", \"Friday\", \"Saturday\"};\n  list<string> colors{\"Red\", \"Orange\", \"Yellow\", \"Green\", \"Blue\", \"Purple\"};\n\n  cout << \"All elements:\\n\";\n  PrintContainer(days.begin(), days.end());\n  PrintContainer(colors.begin(), colors.end());\n  \n  cout << \"\\nFirst, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.begin());\n  FirstFourthFifth(colors.begin());\n\n  cout << \"\\nReverse first, fourth, and fifth elements:\\n\";\n  FirstFourthFifth(days.rbegin());\n  FirstFourthFifth(colors.rbegin());\n}\n"}
{"id": 56522, "name": "Rare numbers", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n", "C++": "\n\n#include <functional>\n#include <bitset>\n#include <cmath>\nusing namespace std;\nusing Z2 = optional<long long>; using Z1 = function<Z2()>;\n\nconstexpr auto pow10 = [] { array <long long, 19> n {1}; for (int j{0}, i{1}; i < 19; j = i++) n[i] = n[j] * 10; return n; } ();\nlong long acc, l;\nbool izRev(int n, unsigned long long i, unsigned long long g) {\n  return (i / pow10[n - 1] != g % 10) ? false : n < 2 ? true : izRev(n - 1, i % pow10[n - 1], g / 10);\n}\nconst Z1 fG(Z1 n, int start, int end, int reset, const long long step, long long &l) {\n  return [n, i{step * start}, g{step * end}, e{step * reset}, &l, step] () mutable {\n    while (i<g){i+=step; return Z2(l+=step);}\n    l-=g-(i=e); return n();};\n}\nstruct nLH {\n  vector<unsigned long long>even{}, odd{};\n  nLH(const Z1 a, const vector<long long> b, long long llim){while (auto i = a()) for (auto ng : b)\n    if(ng>0 | *i>llim){unsigned long long sq{ng+ *i}, r{sqrt(sq)}; if (r*r == sq) ng&1 ? odd.push_back(sq) : even.push_back(sq);}}\n};\nconst double fac = 3.94;\nconst int mbs = (int)sqrt(fac * pow10[9]), mbt = (int)sqrt(fac * fac * pow10[9]) >> 3;\nconst bitset<100000>bs {[]{bitset<100000>n{false}; for(int g{3};g<mbs;++g) n[(g*g)%100000]=true; return n;}()};\nconstexpr array<const int,  7>li{1,3,0,0,1,1,1},lin{0,-7,0,0,-8,-3,-9},lig{0,9,0,0,8,7,9},lil{0,2,0,0,2,10,2};\nconst nLH makeL(const int n){\n  constexpr int r{9}; acc=0; Z1 g{[]{return Z2{};}}; int s{-r}, q{(n>11)*5}; vector<long long> w{};\n  for (int i{1};i<n/2-q+1;++i){l=pow10[n-i-q]-pow10[i+q-1]; s-=i==n/2-q; g=fG(g,s,r,-r,l,acc+=l*s);}\n  if(q){long long g0{0}, g1{0}, g2{0}, g3{0}, g4{0}, l3{pow10[n-5]}; while (g0<7){const long long g{-10000*g4-1000*g3-100*g2-10*g1-g0};\n    if (bs[(g+1000000000000LL)%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);\n    if(g4<r) ++g4; else{g4= -r; if(g3<r) ++g3; else{g3= -r; if(g2<r) ++g2; else{g2= -r; if(g1<lig[g0]) g1+=lil[g0]; else {g0+=li[g0];g1=lin[g0];}}}}}}\n  return q ? nLH(g,w,0) : nLH(g,{0},0);\n}\nconst bitset<100000>bt {[]{bitset<100000>n{false}; for(int g{11};g<mbt;++g) n[(g*g)%100000]=true; return n;}()};\nconstexpr array<const int, 17>lu{0,0,0,0,2,0,4,0,0,0,1,4,0,0,0,1,1},lun{0,0,0,0,0,0,1,0,0,0,9,1,0,0,0,1,0},lug{0,0,0,0,18,0,17,0,0,0,9,17,0,0,0,11,18},lul{0,0,0,0,2,0,2,0,0,0,0,2,0,0,0,10,2};\nconst nLH makeH(const int n){\n  acc= -pow10[n>>1]-pow10[(n-1)>>1]; Z1 g{[]{ return Z2{};}}; int q{(n>11)*5}; vector<long long> w {};\n  for (int i{1}; i<(n>>1)-q+1; ++i) g = fG(g,0,18,0,pow10[n-i-q]+pow10[i+q-1], acc); \n  if (n & 1){l=pow10[n>>1]<<1; g=fG(g,0,9,0,l,acc+=l);}\n  if(q){long long g0{4}, g1{0}, g2{0}, g3{0}, g4{0},l3{pow10[n-5]}; while (g0<17){const long long g{g4*10000+g3*1000+g2*100+g1*10+g0};\n    if (bt[g%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);\n    if (g4<18) ++g4; else{g4=0; if(g3<18) ++g3; else{g3=0; if(g2<18) ++g2; else{g2=0; if(g1<lug[g0]) g1+=lul[g0]; else{g0+=lu[g0];g1=lun[g0];}}}}}}\n  return q ? nLH(g,w,0) : nLH(g,{0},pow10[n-1]<<2);\n}\n#include <chrono>\nusing namespace chrono; using VU = vector<unsigned long long>; using VS = vector<string>;\ntemplate <typename T> \nvector<T>& operator +=(vector<T>& v, const vector<T>& w) { v.insert(v.end(), w.begin(), w.end()); return v; }\nint c{0}; \nauto st{steady_clock::now()}, st0{st}, tmp{st}; \n\nstring dFmt(duration<double> et, int digs) {\n  string res{\"\"}; double dt{et.count()};\n  if (dt > 60.0) { int m = (int)(dt / 60.0); dt -= m * 60.0; res = to_string(m) + \"m\"; }\n  res += to_string(dt); return res.substr(0, digs - 1) + 's';\n}\n\nVS dump(int nd, VU lo, VU hi) {\n  VS res {};\n  for (auto l : lo) for (auto h : hi) {\n    auto r { (h - l) >> 1 }, z { h - r };\n    if (izRev(nd, r, z)) {\n      char buf[99]; sprintf(buf, \"%20llu %11lu %10lu\", z, (long long)sqrt(h), (long long)sqrt(l));\n      res.push_back(buf); } } return res;\n}\n\nvoid doOne(int n, nLH L, nLH H) {\n  VS lines = dump(n, L.even, H.even); lines += dump(n, L.odd , H.odd); sort(lines.begin(), lines.end());\n  duration<double> tet = (tmp = steady_clock::now()) - st; int ls = lines.size();\n  if (ls-- > 0)\n    for (int i{0}; i <= ls; ++i)\n      printf(\"%3d %s%s\", ++c, lines[i].c_str(), i == ls ? \"\" : \"\\n\");\n  else printf(\"%s\", string(47, ' ').c_str());\n  printf(\"  %2d:     %s  %s\\n\", n, dFmt(tmp - st0, 8).c_str(), dFmt(tet, 8).c_str()); st0 = tmp;\n}\nvoid Rare(int n) { doOne(n, makeL(n), makeH(n)); }\nint main(int argc, char *argv[]) {\n  int max{argc > 1 ? stoi(argv[1]) : 19}; if (max < 2) max = 2; if (max > 19 ) max = 19;\n  printf(\"%4s %19s %11s %10s %5s %11s %9s\\n\", \"nth\", \"forward\", \"rt.sum\", \"rt.diff\", \"digs\", \"block.et\", \"total.et\");\n  for (int nd{2}; nd <= max; ++nd) Rare(nd);\n}\n"}
{"id": 56523, "name": "Find words which contain the most consonants", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56524, "name": "Prime words", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56525, "name": "Prime words", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56526, "name": "Prime words", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56527, "name": "Riordan numbers", "Python": "def Riordan(N):\n    a = [1, 0, 1]\n    for n in range(3, N):\n        a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))\n    return a\n\nrios = Riordan(10_000)\n\nfor i in range(32):\n    print(f'{rios[i] : 18,}', end='\\n' if (i + 1) % 4 == 0 else '')\n\nprint(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')\nprint(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nclass riordan_number_generator {\npublic:\n    big_int next();\n\nprivate:\n    big_int a0_ = 1;\n    big_int a1_ = 0;\n    int n_ = 0;\n};\n\nbig_int riordan_number_generator::next() {\n    int n = n_++;\n    if (n == 0)\n        return a0_;\n    if (n == 1)\n        return a1_;\n    big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1);\n    a0_ = a1_;\n    a1_ = a;\n    return a;\n}\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n)\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n    return str;\n}\n\nint main() {\n    riordan_number_generator rng;\n    std::cout << \"First 32 Riordan numbers:\\n\";\n    int i = 1;\n    for (; i <= 32; ++i) {\n        std::cout << std::setw(14) << rng.next()\n                  << (i % 4 == 0 ? '\\n' : ' ');\n    }\n    for (; i < 1000; ++i)\n        rng.next();\n    auto num = rng.next();\n    ++i;\n    std::cout << \"\\nThe 1000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n    for (; i < 10000; ++i)\n        rng.next();\n    num = rng.next();\n    std::cout << \"The 10000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n}\n"}
{"id": 56528, "name": "Riordan numbers", "Python": "def Riordan(N):\n    a = [1, 0, 1]\n    for n in range(3, N):\n        a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))\n    return a\n\nrios = Riordan(10_000)\n\nfor i in range(32):\n    print(f'{rios[i] : 18,}', end='\\n' if (i + 1) % 4 == 0 else '')\n\nprint(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')\nprint(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nclass riordan_number_generator {\npublic:\n    big_int next();\n\nprivate:\n    big_int a0_ = 1;\n    big_int a1_ = 0;\n    int n_ = 0;\n};\n\nbig_int riordan_number_generator::next() {\n    int n = n_++;\n    if (n == 0)\n        return a0_;\n    if (n == 1)\n        return a1_;\n    big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1);\n    a0_ = a1_;\n    a1_ = a;\n    return a;\n}\n\nstd::string to_string(const big_int& num, size_t n) {\n    std::string str = num.get_str();\n    size_t len = str.size();\n    if (len > n)\n        str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n    return str;\n}\n\nint main() {\n    riordan_number_generator rng;\n    std::cout << \"First 32 Riordan numbers:\\n\";\n    int i = 1;\n    for (; i <= 32; ++i) {\n        std::cout << std::setw(14) << rng.next()\n                  << (i % 4 == 0 ? '\\n' : ' ');\n    }\n    for (; i < 1000; ++i)\n        rng.next();\n    auto num = rng.next();\n    ++i;\n    std::cout << \"\\nThe 1000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n    for (; i < 10000; ++i)\n        rng.next();\n    num = rng.next();\n    std::cout << \"The 10000th is \" << to_string(num, 40) << \" (\"\n              << num.get_str().size() << \" digits).\\n\";\n}\n"}
{"id": 56529, "name": "Numbers which are the cube roots of the product of their proper divisors", "Python": "\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n    if num * num * num == divprod:\n        FOUND += 1\n        if FOUND <= 50:\n            print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n        if FOUND == 500:\n            print(f'\\nFive hundreth: {num:,}')\n        if FOUND == 5000:\n            print(f'\\nFive thousandth: {num:,}')\n        if FOUND == 50000:\n            print(f'\\nFifty thousandth: {num:,}')\n            break\n", "C++": "#include <iomanip>\n#include <iostream>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\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    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"First 50 numbers which are the cube roots of the products of \"\n                 \"their proper divisors:\\n\";\n    for (unsigned int n = 1, count = 0; count < 50000; ++n) {\n        if (n == 1 || divisor_count(n) == 8) {\n            ++count;\n            if (count <= 50)\n                std::cout << std::setw(3) << n\n                          << (count % 10 == 0 ? '\\n' : ' ');\n            else if (count == 500 || count == 5000 || count == 50000)\n                std::cout << std::setw(6) << count << \"th: \" << n << '\\n';\n        }\n    }\n}\n"}
{"id": 56530, "name": "Arithmetic evaluation", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n"}
{"id": 56531, "name": "Arithmetic evaluation", "Python": "import operator\n\nclass AstNode(object):\n   def __init__( self, opr, left, right ):\n      self.opr = opr\n      self.l = left\n      self.r = right\n\n   def eval(self):\n      return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n   def __init__( self, valStrg ):\n      self.v = int(valStrg)\n\n   def eval(self):\n      return self.v\n\nclass Yaccer(object):\n   def __init__(self):\n      self.operstak = []\n      self.nodestak =[]\n      self.__dict__.update(self.state1)\n\n   def v1( self, valStrg ):\n      \n      self.nodestak.append( LeafNode(valStrg))\n      self.__dict__.update(self.state2)\n      \n\n   def o2( self, operchar ):\n      \n      def openParen(a,b):\n         return 0\t\t\n\n      opDict= { '+': ( operator.add, 2, 2 ),\n         '-': (operator.sub, 2, 2 ),\n         '*': (operator.mul, 3, 3 ),\n         '/': (operator.div, 3, 3 ),\n         '^': ( pow,         4, 5 ),  \n         '(': ( openParen,   0, 8 )\n         }\n      operPrecidence = opDict[operchar][2]\n      self.redeuce(operPrecidence)\n\n      self.operstak.append(opDict[operchar])\n      self.__dict__.update(self.state1)\n      \n\n   def syntaxErr(self, char ):\n      \n      print 'parse error - near operator \"%s\"' %char\n\n   def pc2( self,operchar ):\n      \n      \n      self.redeuce( 1 )\n      if len(self.operstak)>0:\n         self.operstak.pop()\t\t\n      else:\n         print 'Error - no open parenthesis matches close parens.'\n      self.__dict__.update(self.state2)\n\n   def end(self):\n      self.redeuce(0)\n      return self.nodestak.pop()\n\n   def redeuce(self, precidence):\n      while len(self.operstak)>0:\n         tailOper = self.operstak[-1]\n         if tailOper[1] < precidence: break\n\n         tailOper = self.operstak.pop()\n         vrgt = self.nodestak.pop()\n         vlft= self.nodestak.pop()\n         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n         \n\n   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n   bgn = None\n   cp = -1\n   for c in exprssn:\n      cp += 1\n      if c in '+-/*^()':         \n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         if c=='(': p.po(p, c)\n         elif c==')':p.pc(p, c)\n         else: p.o(p, c)\n      elif c in ' \\t':\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n      elif c in '0123456789':\n         if bgn is None:\n            bgn = cp\n      else:\n         print 'Invalid character in expression'\n         if bgn is not None:\n            p.v(p, exprssn[bgn:cp])\n            bgn = None\n         \n   if bgn is not None:\n      p.v(p, exprssn[bgn:cp+1])\n      bgn = None\n   return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()\n", "C++": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n \n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n \n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n \n \n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n \n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n \n   mutable double tmp;\n \n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n \n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n \n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n \n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n \n \n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n"}
{"id": 56532, "name": "Ormiston triples", "Python": "import textwrap\n\nfrom itertools import pairwise\nfrom typing import Iterator\nfrom typing import List\n\nimport primesieve\n\n\ndef primes() -> Iterator[int]:\n    it = primesieve.Iterator()\n    while True:\n        yield it.next_prime()\n\n\ndef triplewise(iterable):\n    for (a, _), (b, c) in pairwise(pairwise(iterable)):\n        yield a, b, c\n\n\ndef is_anagram(a: int, b: int, c: int) -> bool:\n    return sorted(str(a)) == sorted(str(b)) == sorted(str(c))\n\n\ndef up_to_one_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 1_000_000_000:\n            break\n    return count\n\n\ndef up_to_ten_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 10_000_000_000:\n            break\n    return count\n\n\ndef first_25() -> List[int]:\n    rv: List[int] = []\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            rv.append(triple[0])\n            if len(rv) >= 25:\n                break\n    return rv\n\n\nif __name__ == \"__main__\":\n    print(\"Smallest members of first 25 Ormiston triples:\")\n    print(textwrap.fill(\" \".join(str(i) for i in first_25())), \"\\n\")\n    print(up_to_one_billion(), \"Ormiston triples before 1,000,000,000\")\n    print(up_to_ten_billion(), \"Ormiston triples before 10,000,000,000\")\n", "C++": "#include <array>\n#include <iostream>\n\n#include <primesieve.hpp>\n\nclass ormiston_triple_generator {\npublic:\n    ormiston_triple_generator() {\n        for (int i = 0; i < 2; ++i) {\n            primes_[i] = pi_.next_prime();\n            digits_[i] = get_digits(primes_[i]);\n        }\n    }\n    std::array<uint64_t, 3> next_triple() {\n        for (;;) {\n            uint64_t prime = pi_.next_prime();\n            auto digits = get_digits(prime);\n            bool is_triple = digits == digits_[0] && digits == digits_[1];\n            uint64_t prime0 = primes_[0];\n            primes_[0] = primes_[1];\n            primes_[1] = prime;\n            digits_[0] = digits_[1];\n            digits_[1] = digits;\n            if (is_triple)\n                return {prime0, primes_[0], primes_[1]};\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    std::array<uint64_t, 2> primes_;\n    std::array<std::array<int, 10>, 2> digits_;\n};\n\nint main() {\n    ormiston_triple_generator generator;\n    int count = 0;\n    std::cout << \"Smallest members of first 25 Ormiston triples:\\n\";\n    for (; count < 25; ++count) {\n        auto primes = generator.next_triple();\n        std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {\n        auto primes = generator.next_triple();\n        if (primes[2] > limit) {\n            std::cout << \"Number of Ormiston triples < \" << limit << \": \"\n                      << count << '\\n';\n            limit *= 10;\n        }\n    }\n}\n"}
{"id": 56533, "name": "Super-Poulet numbers", "Python": "from sympy import isprime, divisors\n \ndef is_super_Poulet(n):\n    return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n))\n\nspoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)]\n\nprint('The first 20 super-Poulet numbers are:', spoulets[:20])\n\nidx1m, val1m = next((i, v) for i, v in enumerate(spoulets) if v > 1_000_000)\nprint(f'The first super-Poulet number over 1 million is the {idx1m}th one, which is {val1m}')\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nstd::vector<unsigned int> divisors(unsigned int n) {\n    std::vector<unsigned int> result{1};\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        result.push_back(power);\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        size_t size = result.size();\n        for (power = p; n % p == 0; power *= p, n /= p)\n            for (size_t i = 0; i != size; ++i)\n                result.push_back(power * result[i]);\n    }\n    if (n > 1) {\n        size_t size = result.size();\n        for (size_t i = 0; i != size; ++i)\n            result.push_back(n * result[i]);\n    }\n    return result;\n}\n\nunsigned long long modpow(unsigned long long base, unsigned int exp,\n                          unsigned int mod) {\n    if (mod == 1)\n        return 0;\n    unsigned long long result = 1;\n    base %= mod;\n    for (; exp != 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\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    if (n % 5 == 0)\n        return n == 5;\n    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n    for (unsigned int p = 7;;) {\n        for (unsigned int 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\nbool is_poulet_number(unsigned int n) {\n    return modpow(2, n - 1, n) == 1 && !is_prime(n);\n}\n\nbool is_sp_num(unsigned int n) {\n    if (!is_poulet_number(n))\n        return false;\n    auto div = divisors(n);\n    return all_of(div.begin() + 1, div.end(),\n                  [](unsigned int d) { return modpow(2, d, d) == 2; });\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    unsigned int n = 1, count = 0;\n    std::cout << \"First 20 super-Poulet numbers:\\n\";\n    for (; count < 20; n += 2) {\n        if (is_sp_num(n)) {\n            ++count;\n            std::cout << n << ' ';\n        }\n    }\n    std::cout << '\\n';\n    for (unsigned int limit = 1000000; limit <= 10000000; limit *= 10) {\n        for (;;) {\n            n += 2;\n            if (is_sp_num(n)) {\n                ++count;\n                if (n > limit)\n                    break;\n            }\n        }\n        std::cout << \"\\nIndex and value of first super-Poulet greater than \"\n                  << limit << \":\\n#\" << count << \" is \" << n << '\\n';\n    }\n}\n"}
{"id": 56534, "name": "Special variables", "Python": "names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))\nprint( '\\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )\n", "C++": "#include <iostream>\n\nstruct SpecialVariables\n{\n    int i = 0;\n\n    SpecialVariables& operator++()\n    {\n        \n        \n        \n        this->i++;  \n\n        \n        return *this;\n    }\n\n};\n\nint main()\n{\n    SpecialVariables sv;\n    auto sv2 = ++sv;     \n    std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}\n"}
{"id": 56535, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\nusing namespace std;\ntypedef unsigned char byte;\n\nenum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };\n\nclass fieldData\n{\npublic:\n    fieldData() : value( CLOSED ), open( false ) {}\n    byte value;\n    bool open, mine;\n};\n\nclass game\n{\npublic:\n    ~game()\n    { if( field ) delete [] field; }\n\n    game( int x, int y )\n    {\n        go = false; wid = x; hei = y;\n\tfield = new fieldData[x * y];\n\tmemset( field, 0, x * y * sizeof( fieldData ) );\n\toMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;\n\tmMines = 0;\n\tint mx, my, m = 0;\n\tfor( ; m < oMines; m++ )\n\t{\n\t    do\n\t    { mx = rand() % wid; my = rand() % hei; }\n\t    while( field[mx + wid * my].mine );\n\t    field[mx + wid * my].mine = true;\n\t}\n\tgraphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; \n\tgraphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; \n    }\n\t\n    void gameLoop()\n    {\n\tstring c, r, a;\n\tint col, row;\n\twhile( !go )\n\t{\n\t    drawBoard();\n\t    cout << \"Enter column, row and an action( c r a ):\\nActions: o => open, f => flag, ? => unknown\\n\";\n\t    cin >> c >> r >> a;\n\t    if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;\n\t    col = c[0] - 65; row = r[0] - 49;\n\t    makeMove( col, row, a );\n\t}\n    }\n\nprivate:\n    void makeMove( int x, int y, string a )\n    {\n\tfieldData* fd = &field[wid * y + x];\n\tif( fd->open && fd->value < CLOSED )\n\t{\n\t    cout << \"This cell is already open!\";\n\t    Sleep( 3000 ); return;\n\t}\n\tif( a[0] == 'O' ) openCell( x, y );\n\telse if( a[0] == 'F' ) \n\t{\n\t    fd->open = true;\n\t    fd->value = FLAG;\n\t    mMines++;\n\t    checkWin();\n\t}\n\telse\n\t{\n\t    fd->open = true;\n\t    fd->value = UNKNOWN;\n\t}\n    }\n\n    bool openCell( int x, int y )\n    {\n\tif( !isInside( x, y ) ) return false;\n\tif( field[x + y * wid].mine ) boom();\n\telse \n\t{\n\t    if( field[x + y * wid].value == FLAG )\n\t    {\n\t\tfield[x + y * wid].value = CLOSED;\n\t\tfield[x + y * wid].open = false;\n\t\tmMines--;\n\t    }\n\t    recOpen( x, y );\n\t    checkWin();\n\t}\n\treturn true;\n    }\n\n    void drawBoard()\n    {\n\tsystem( \"cls\" );\n\tcout << \"Marked mines: \" << mMines << \" from \" << oMines << \"\\n\\n\";\t\t\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"  \" << ( char )( 65 + x ) << \" \"; \n\tcout << \"\\n\"; int yy;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = y * wid;\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << \"+---\";\n\n\t    cout << \"+\\n\"; fieldData* fd;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy]; cout<< \"| \";\n\t\tif( !fd->open ) cout << ( char )graphs[1] << \" \";\n\t\telse \n\t\t{\n\t\t    if( fd->value > 9 )\n\t\t\tcout << ( char )graphs[fd->value - 9] << \" \";\n\t\t    else\n\t\t    {\n\t\t\tif( fd->value < 1 ) cout << \"  \";\n\t\t\t    else cout << ( char )(fd->value + 48 ) << \" \";\n\t\t    }\n\t\t}\n\t    }\n\t    cout << \"| \" << y + 1 << \"\\n\";\n\t}\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"+---\";\n\n\tcout << \"+\\n\\n\";\n    }\n\n    void checkWin()\n    {\n\tint z = wid * hei - oMines, yy;\n\tfieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->open && fd->value != FLAG ) z--;\n\t    }\n\t}\n\tif( !z ) lastMsg( \"Congratulations, you won the game!\");\n    }\n\n    void boom()\n    {\n\tint yy; fieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->value == FLAG )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = fd->mine ? MINE : ERR;\n\t\t}\n\t\telse if( fd->mine )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = MINE;\n\t\t}\n\t    }\n\t}\n\tlastMsg( \"B O O O M M M M M !\" );\n    }\n\n    void lastMsg( string s )\n    {\n\tgo = true; drawBoard();\n\tcout << s << \"\\n\\n\";\n    }\n\n    bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }\n\n    void recOpen( int x, int y )\n    {\n\tif( !isInside( x, y ) || field[x + y * wid].open ) return;\n\tint bc = getMineCount( x, y );\n\tfield[x + y * wid].open = true;\n\tfield[x + y * wid].value = bc;\n\tif( bc ) return;\n\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\trecOpen( x + xx, y + yy );\n\t    }\n    }\n\n    int getMineCount( int x, int y )\n    {\n\tint m = 0;\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\tif( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;\n\t    }\n\t\t\n\treturn m;\n    }\n\t\n    int wid, hei, mMines, oMines;\n    fieldData* field; bool go;\n    int graphs[6];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    game g( 4, 6 ); g.gameLoop();\n    return system( \"pause\" );\n}\n"}
{"id": 56536, "name": "Elementary cellular automaton_Infinite length", "Python": "def _notcell(c):\n    return '0' if c == '1' else '1'\n\ndef eca_infinite(cells, rule):\n    lencells = len(cells)\n    rulebits = '{0:08b}'.format(rule)\n    neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n    c = cells\n    while True:\n        yield c\n        c = _notcell(c[0])*2 + c + _notcell(c[-1])*2    \n\n        c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))\n        \n\nif __name__ == '__main__':\n    lines = 25\n    for rule in (90, 30):\n        print('\\nRule: %i' % rule)\n        for i, c in zip(range(lines), eca_infinite('1', rule)):\n            print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <string>\n\nclass oo {\npublic:\n    void evolve( int l, int rule ) {\n        std::string    cells = \"O\";\n        std::cout << \" Rule #\" << rule << \":\\n\";\n        for( int x = 0; x < l; x++ ) {\n            addNoCells( cells );\n            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n            step( cells, rule );\n        }\n    }\nprivate:\n    void step( std::string& cells, int rule ) {\n        int bin;\n        std::string newCells;\n        for( size_t i = 0; i < cells.length() - 2; i++ ) {\n            bin = 0;\n            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n            }\n            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n        }\n        cells = newCells;\n    }\n    void addNoCells( std::string& s ) {\n        char l = s.at( 0 ) == 'O' ? '.' : 'O',\n             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n        s = l + s + r;\n        s = l + s + r;\n    }\n};\nint main( int argc, char* argv[] ) {\n    oo o;\n    o.evolve( 35, 90 );\n    std::cout << \"\\n\";\n    return 0;\n}\n"}
{"id": 56537, "name": "Execute CopyPasta Language", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n", "C++": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n\n#include <stdlib.h>\n\nusing namespace std;\n\n\nvoid fatal_error(string errtext, char *argv[])\n{\n\tcout << \"%\" << errtext << endl;\n\tcout << \"usage: \" << argv[0] << \" [filename.cp]\" << endl;\n\texit(1);\n}\n\n\n\nstring& ltrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(0, str.find_first_not_of(chars));\n\treturn str;\n}\nstring& rtrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(str.find_last_not_of(chars) + 1);\n\treturn str;\n}\nstring& trim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\treturn ltrim(rtrim(str, chars), chars);\n}\n\nint main(int argc, char *argv[])\n{\n\t\n\tstring fname = \"\";\n\tstring source = \"\";\n\ttry\n\t{\n\t\tfname = argv[1];\n\t\tifstream t(fname);\n\n\t\tt.seekg(0, ios::end);\n\t\tsource.reserve(t.tellg());\n\t\tt.seekg(0, ios::beg);\n\n\t\tsource.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t}\n\tcatch(const exception& e)\n\t{\n\t\tfatal_error(\"error while trying to read from specified file\", argv);\n\t}\n\n\t\n\tstring clipboard = \"\";\n\n\t\n\tint loc = 0;\n\tstring remaining = source;\n\tstring line = \"\";\n\tstring command = \"\";\n\tstringstream ss;\n\twhile(remaining.find(\"\\n\") != string::npos)\n\t{\n\t\t\n\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\tcommand = trim(line);\n\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\n\t\ttry\n\t\t{\n\t\t\tif(line == \"Copy\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tclipboard += line;\n\t\t\t}\n\t\t\telse if(line == \"CopyFile\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tif(line == \"TheF*ckingCode\")\n\t\t\t\t\tclipboard += source;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring filetext = \"\";\n\t\t\t\t\tifstream t(line);\n\n\t\t\t\t\tt.seekg(0, ios::end);\n\t\t\t\t\tfiletext.reserve(t.tellg());\n\t\t\t\t\tt.seekg(0, ios::beg);\n\n\t\t\t\t\tfiletext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t\t\t\t\tclipboard += filetext;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Duplicate\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tint amount = stoi(line);\n\t\t\t\tstring origClipboard = clipboard;\n\t\t\t\tfor(int i = 0; i < amount - 1; i++) {\n\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Pasta!\")\n\t\t\t{\n\t\t\t\tcout << clipboard << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss << (loc + 1);\n\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encounter on line \" + ss.str(), argv);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception& e)\n\t\t{\n\t\t\tss << (loc + 1);\n\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + ss.str(), argv);\n\t\t}\n\n\t\t\n\t\tloc += 2;\n\t}\n\n\t\n\treturn 0;\n}\n"}
{"id": 56538, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "Python": "\n\nfrom sympy import sieve\n\n\ndef nonpairsums(include1=False, limit=20_000):\n    \n    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)\n            for i in range(limit+2)]\n    if include1:\n        tpri[1] = True\n    twinsums = [False] * (limit * 2)\n    for i in range(limit):\n        for j in range(limit-i+1):\n            if tpri[i] and tpri[j]:\n                twinsums[i + j] = True\n\n    return [i for i in range(2, limit+1, 2) if not twinsums[i]]\n\n\nprint('Non twin prime sums:')\nfor k, p in enumerate(nonpairsums()):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n\nprint('\\n\\nNon twin prime sums (including 1):')\nfor k, p in enumerate(nonpairsums(include1=True)):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nvoid print_non_twin_prime_sums(const std::vector<bool>& sums) {\n    int count = 0;\n    for (size_t i = 2; i < sums.size(); i += 2) {\n        if (!sums[i]) {\n            ++count;\n            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nFound \" << count << '\\n';\n}\n\nint main() {\n    const int limit = 100001;\n\n    std::vector<bool> sieve = prime_sieve(limit + 2);\n    \n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))\n            sieve[i] = false;\n    }\n\n    std::vector<bool> twin_prime_sums(limit, false);\n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i]) {\n            for (size_t j = i; i + j < limit; ++j) {\n                if (sieve[j])\n                    twin_prime_sums[i + j] = true;\n            }\n        }\n    }\n\n    std::cout << \"Non twin prime sums:\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n\n    sieve[1] = true;\n    for (size_t i = 1; i + 1 < limit; ++i) {\n        if (sieve[i])\n            twin_prime_sums[i + 1] = true;\n    }\n\n    std::cout << \"\\nNon twin prime sums (including 1):\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n}\n"}
{"id": 56539, "name": "Kosaraju", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 56540, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "C++": "int a;\n"}
{"id": 56541, "name": "Sieve of Pritchard", "Python": "\n\nfrom numpy import ndarray\nfrom math import isqrt\n\n\ndef pritchard(limit):\n    \n    members = ndarray(limit + 1, dtype=bool)\n    members.fill(False)\n    members[1] = True\n    steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2\n    primes = []\n    while prime <= rtlim:\n        if steplength < limit:\n            for w in range(1, len(members)):\n                if members[w]:\n                    n = w + steplength\n                    while n <= nlimit:\n                        members[n] = True\n                        n += steplength\n            steplength = nlimit\n\n        np = 5\n        mcpy = members.copy()\n        for w in range(1, len(members)):\n            if mcpy[w]:\n                if np == 5 and w > prime:\n                    np = w\n                n = prime * w\n                if n > nlimit:\n                    break  \n                members[n] = False  \n\n        if np < prime:\n            break\n        primes.append(prime)\n        prime = 3 if prime == 2 else np\n        nlimit = min(steplength * prime, limit)  \n\n    newprimes = [i for i in range(2, len(members)) if members[i]]\n    return sorted(primes + newprimes)\n\n\nprint(pritchard(150))\nprint('Number of primes up to 1,000,000:', len(pritchard(1000000)))\n", "C++": "\n\n\n\n#include <cstring>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <ctime>\n\nvoid Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) {\n    \n    uint32_t i, j, x;\n    i = 0; j = w_end;\n    x = length + 1; \n    while (x <= n) {\n        w[++j] = x; \n        d[x] = false;\n        x = length + w[++i];\n    }\n    length = n; w_end = j;\n    if (w_end > w_end_max) w_end_max = w_end;\n}\n\nvoid Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) {\n    \n    uint32_t i, x;\n    i = 0;\n    x = p; \n    while (x <= length) {\n        d[x] = true; \n        x = p*w[++i];\n    }\n    imaxf = i-1;\n}\n\nvoid Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) {\n    \n    uint32_t i, j;\n    j = 0;\n    for (i=1; i <= to; i++) {\n        if (!d[w[i]]) {\n            w[++j] = w[i];\n        }\n    }\n    if (to == w_end) {\n        w_end = j;\n    } else {\n        for (uint32_t k=j+1; k <= to; k++) w[k] = 0;\n    }\n}\n\nvoid Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) {\n    \n    uint32_t *w = new uint32_t[N/4+5];\n    bool *d = new bool[N+1];\n    uint32_t w_end, length;\n    \n    \n    \n    \n    uint32_t w_end_max, p, imaxf;\n    \n    w_end = 0; w[0] = 1;\n    w_end_max = 0;\n    length = 2;\n    \n    nrPrimes = 1;\n    if (printPrimes) printf(\"%d\", 2);\n    p = 3;\n    \n    \n    while (p*p <= N) {\n        \n        nrPrimes++;\n        if (printPrimes) printf(\" %d\", p);\n        if (length < N) {\n            \n            Extend (w, w_end, length, std::min(p*length,N), d, w_end_max);\n        }\n        Delete(w, length, p, d, imaxf);\n        Compress(w, d, (length < N ? w_end : imaxf), w_end);\n        \n        p = w[1];\n        if (p == 0) break; \n        \n    }\n    if (length < N) {\n        \n        Extend (w, w_end, length, N, d, w_end_max);\n    }\n    \n    for (uint32_t i=1; i <= w_end; i++) {\n        if (w[i] == 0 || d[w[i]]) continue;\n        if (printPrimes) printf(\" %d\", w[i]);\n        nrPrimes++;\n    }\n    vBound = w_end_max+1;\n}\n\nint main (int argc, char *argw[]) {\n    bool error = false;\n    bool printPrimes = false;\n    uint32_t N, nrPrimes, vBound;\n    if (argc == 3) {\n        if (strcmp(argw[2], \"-p\") == 0) {\n            printPrimes = true;\n            argc--;\n        } else {\n            error = true;\n        }\n    }\n    if (argc == 2) {\n        N = atoi(argw[1]);\n        if (N < 2 || N > 1000000000) error = true;\n    } else {\n        error = true;\n    }\n    if (error) {\n        printf(\"call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \\n\", argw[0]);\n        exit(1);\n    }\n    int start_s = clock();\n    Sift(N, printPrimes, nrPrimes, vBound);\n    int stop_s=clock();\n    printf(\"\\n%d primes up to %lu found in %.3f ms using array w[%d]\\n\", nrPrimes,\n      (unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound);\n}\n"}
{"id": 56542, "name": "Monads_Writer monad", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n", "C++": "#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct LoggingMonad\n{\n    double Value;\n    string Log;\n};\n\n\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n    auto result = f(monad.Value);\n    return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n\nauto MakeWriter = [](auto f, string message)\n{\n    return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n    \n    auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n    cout << result.Log << \"\\nResult: \" << result.Value;\n}\n"}
{"id": 56543, "name": "Nested templated data", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n"}
{"id": 56544, "name": "Nested templated data", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n"}
{"id": 56545, "name": "Honaker primes", "Python": "\n\n\nfrom pyprimesieve import primes\n\n\ndef digitsum(num):\n    \n    return sum(int(c) for c in str(num))\n\n\ndef generate_honaker(limit=5_000_000):\n    \n    honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]\n    for hcount, (ppi, pri) in enumerate(honaker):\n        yield hcount + 1, ppi, pri\n\n\nprint('First 50 Honaker primes:')\nfor p in generate_honaker():\n    if p[0] < 51:\n        print(f'{str(p):16}', end='\\n' if p[0] % 5 == 0 else '')\n    elif p[0] == 10_000:\n        print(f'\\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.')\n        break\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <utility>\n\n#include <primesieve.hpp>\n\nuint64_t digit_sum(uint64_t n) {\n    uint64_t sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nclass honaker_prime_generator {\npublic:\n    std::pair<uint64_t, uint64_t> next();\n\nprivate:\n    primesieve::iterator pi_;\n    uint64_t index_ = 0;\n};\n\nstd::pair<uint64_t, uint64_t> honaker_prime_generator::next() {\n    for (;;) {\n        uint64_t prime = pi_.next_prime();\n        ++index_;\n        if (digit_sum(index_) == digit_sum(prime))\n            return std::make_pair(index_, prime);\n    }\n}\n\nstd::ostream& operator<<(std::ostream& os,\n                         const std::pair<uint64_t, uint64_t>& p) {\n    std::ostringstream str;\n    str << '(' << p.first << \", \" << p.second << ')';\n    return os << str.str();\n}\n\nint main() {\n    honaker_prime_generator hpg;\n    std::cout << \"First 50 Honaker primes (index, prime):\\n\";\n    int i = 1;\n    for (; i <= 50; ++i)\n        std::cout << std::setw(11) << hpg.next() << (i % 5 == 0 ? '\\n' : ' ');\n    for (; i < 10000; ++i)\n        hpg.next();\n    std::cout << \"\\nTen thousandth: \" << hpg.next() << '\\n';\n}\n"}
{"id": 56546, "name": "De Polignac numbers", "Python": "\n\nfrom sympy import isprime\nfrom math import log\nfrom numpy import ndarray\n\nmax_value = 1_000_000\n\nall_primes = [i for i in range(max_value + 1) if isprime(i)]\npowers_of_2 = [2**i for i in range(int(log(max_value, 2)))]\n\nallvalues = ndarray(max_value, dtype=bool)\nallvalues[:] = True\n\nfor i in all_primes:\n    for j in powers_of_2:\n        if i + j < max_value:\n            allvalues[i + j] = False\n        \ndePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]]\n\nprint('First fifty de Polignac numbers:')\nfor i, n in enumerate(dePolignac[:50]):\n    print(f'{n:5}', end='\\n' if (i + 1) % 10 == 0 else '')\n    \nprint(f'\\nOne thousandth: {dePolignac[999]:,}')\nprint(f'\\nTen thousandth: {dePolignac[9999]:,}')\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(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 (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\nbool is_depolignac_number(int n) {\n    for (int p = 1; p < n; p <<= 1) {\n        if (is_prime(n - p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"First 50 de Polignac numbers:\\n\";\n    for (int n = 1, count = 0; count < 10000; n += 2) {\n        if (is_depolignac_number(n)) {\n            ++count;\n            if (count <= 50)\n                std::cout << std::setw(5) << n\n                          << (count % 10 == 0 ? '\\n' : ' ');\n            else if (count == 1000)\n                std::cout << \"\\nOne thousandth: \" << n << '\\n';\n            else if (count == 10000)\n                std::cout << \"\\nTen thousandth: \" << n << '\\n';\n        }\n    }\n}\n"}
{"id": 56547, "name": "Mastermind", "Python": "import random\n\n\ndef encode(correct, guess):\n    output_arr = [''] * len(correct)\n\n    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):\n        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'\n\n    return ''.join(output_arr)\n\n\ndef safe_int_input(prompt, min_val, max_val):\n    while True:\n        user_input = input(prompt)\n\n        try:\n            user_input = int(user_input)\n        except ValueError:\n            continue\n\n        if min_val <= user_input <= max_val:\n            return user_input\n\n\ndef play_game():\n    print(\"Welcome to Mastermind.\")\n    print(\"You will need to guess a random code.\")\n    print(\"For each guess, you will receive a hint.\")\n    print(\"In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.\")\n    print()\n\n    number_of_letters = safe_int_input(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n    code_length = safe_int_input(\"Select a length for the code (4-10): \", 4, 10)\n\n    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]\n    code = ''.join(random.choices(letters, k=code_length))\n    guesses = []\n\n    while True:\n        print()\n        guess = input(f\"Enter a guess of length {code_length} ({letters}): \").upper().strip()\n\n        if len(guess) != code_length or any([char not in letters for char in guess]):\n            continue\n        elif guess == code:\n            print(f\"\\nYour guess {guess} was correct!\")\n            break\n        else:\n            guesses.append(f\"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}\")\n\n        for i_guess in guesses:\n            print(\"------------------------------------\")\n            print(i_guess)\n        print(\"------------------------------------\")\n\n\nif __name__ == '__main__':\n    play_game()\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <ctime>\n#include <string>\n#include <vector>\n\ntypedef std::vector<char> vecChar;\n\nclass master {\npublic:\n    master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {\n        std::string color = \"ABCDEFGHIJKLMNOPQRST\";\n\n        if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;\n        if( !rpt && clr_count < code_len ) clr_count = code_len; \n        if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;\n        if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;\n        \n        codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;\n\n        for( size_t s = 0; s < colorsCnt; s++ ) {\n            colors.append( 1, color.at( s ) );\n        }\n    }\n    void play() {\n        bool win = false;\n        combo = getCombo();\n\n        while( guessCnt ) {\n            showBoard();\n            if( checkInput( getInput() ) ) {\n                win = true;\n                break;\n            }\n            guessCnt--;\n        }\n        if( win ) {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"Very well done!\\nYou found the code: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        } else {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"I am sorry, you couldn't make it!\\nThe code was: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        }\n    }\nprivate:\n    void showBoard() {\n        vecChar::iterator y;\n        for( int x = 0; x < guesses.size(); x++ ) {\n            std::cout << \"\\n--------------------------------\\n\";\n            std::cout << x + 1 << \": \";\n            for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            std::cout << \" :  \";\n            for( y = results[x].begin(); y != results[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            int z = codeLen - results[x].size();\n            if( z > 0 ) {\n                for( int x = 0; x < z; x++ ) std::cout << \"- \";\n            }\n        }\n        std::cout << \"\\n\\n\";\n    }\n    std::string getInput() {\n        std::string a;\n        while( true ) {\n            std::cout << \"Enter your guess (\" << colors << \"): \";\n            a = \"\"; std::cin >> a;\n            std::transform( a.begin(), a.end(), a.begin(), ::toupper );\n            if( a.length() > codeLen ) a.erase( codeLen );\n            bool r = true;\n            for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n                if( colors.find( *x ) == std::string::npos ) {\n                    r = false;\n                    break;\n                }\n            }\n            if( r ) break;\n        }\n        return a;\n    }\n    bool checkInput( std::string a ) {\n        vecChar g;\n        for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n            g.push_back( *x );\n        }\n        guesses.push_back( g );\n        \n        int black = 0, white = 0;\n        std::vector<bool> gmatch( codeLen, false );\n        std::vector<bool> cmatch( codeLen, false );\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if( a.at( i ) == combo.at( i ) ) {\n                gmatch[i] = true;\n                cmatch[i] = true;\n                black++;\n            }\n        }\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if (gmatch[i]) continue;\n            for( int j = 0; j < codeLen; j++ ) {\n                if (i == j || cmatch[j]) continue;\n                if( a.at( i ) == combo.at( j ) ) {\n                    cmatch[j] = true;\n                    white++;\n                    break;\n                }\n            }\n        }\n       \n        vecChar r;\n        for( int b = 0; b < black; b++ ) r.push_back( 'X' );\n        for( int w = 0; w < white; w++ ) r.push_back( 'O' );\n        results.push_back( r );\n\n        return ( black == codeLen );\n    }\n    std::string getCombo() {\n        std::string c, clr = colors;\n        int l, z;\n\n        for( size_t s = 0; s < codeLen; s++ ) {\n            z = rand() % ( int )clr.length();\n            c.append( 1, clr[z] );\n            if( !repeatClr ) clr.erase( z, 1 );\n        }\n        return c;\n    }\n\n    size_t codeLen, colorsCnt, guessCnt;\n    bool repeatClr;\n    std::vector<vecChar> guesses, results;\n    std::string colors, combo;\n};\n\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    master m( 4, 8, 12, false );\n    m.play();\n    return 0;\n}\n"}
{"id": 56548, "name": "Zsigmondy numbers", "Python": "\n\nfrom math import gcd\nfrom sympy import divisors\n\n\ndef zsig(num, aint, bint):\n    \n    assert aint > bint\n    dexpms = [aint**i - bint**i for i in range(1, num)]\n    dexpn = aint**num - bint**num\n    return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)])\n\n\ntests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1),\n         (7, 1), (3, 2), (5, 3), (7, 3), (7, 5)]\nfor (a, b) in tests:\n    print(f'\\nZsigmondy(n, {a}, {b}):', ', '.join(\n        [str(zsig(n, a, b)) for n in range(1, 21)]))\n", "C++": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nstd::vector<uint64_t> divisors(uint64_t n) {\n    std::vector<uint64_t> result{1};\n    uint64_t power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        result.push_back(power);\n    for (uint64_t p = 3; p * p <= n; p += 2) {\n        size_t size = result.size();\n        for (power = p; n % p == 0; power *= p, n /= p)\n            for (size_t i = 0; i != size; ++i)\n                result.push_back(power * result[i]);\n    }\n    if (n > 1) {\n        size_t size = result.size();\n        for (size_t i = 0; i != size; ++i)\n            result.push_back(n * result[i]);\n    }\n    sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t ipow(uint64_t base, uint64_t exp) {\n    if (exp == 0)\n        return 1;\n    if ((exp & 1) == 0)\n        return ipow(base * base, exp >> 1);\n    return base * ipow(base * base, (exp - 1) >> 1);\n}\n\nuint64_t zsigmondy(uint64_t n, uint64_t a, uint64_t b) {\n    auto p = ipow(a, n) - ipow(b, n);\n    auto d = divisors(p);\n    if (d.size() == 2)\n        return p;\n    std::vector<uint64_t> dms(n - 1);\n    for (uint64_t m = 1; m < n; ++m)\n        dms[m - 1] = ipow(a, m) - ipow(b, m);\n    for (auto i = d.rbegin(); i != d.rend(); ++i) {\n        uint64_t z = *i;\n        if (all_of(dms.begin(), dms.end(),\n                   [z](uint64_t x) { return std::gcd(x, z) == 1; }))\n            return z;\n    }\n    return 1;\n}\n\nvoid test(uint64_t a, uint64_t b) {\n    std::cout << \"Zsigmondy(n, \" << a << \", \" << b << \"):\\n\";\n    for (uint64_t n = 1; n <= 20; ++n) {\n        std::cout << zsigmondy(n, a, b) << ' ';\n    }\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    test(2, 1);\n    test(3, 1);\n    test(4, 1);\n    test(5, 1);\n    test(6, 1);\n    test(7, 1);\n    test(3, 2);\n    test(5, 3);\n    test(7, 3);\n    test(7, 5);\n}\n"}
{"id": 56549, "name": "Sorensen–Dice coefficient", "Python": "\n\nfrom multiset import Multiset\n\n\ndef tokenizetext(txt):\n    \n    arr = []\n    for wrd in txt.lower().split(' '):\n        arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2]\n                for i in range(len(wrd)-1)])\n    return Multiset(arr)\n\n\ndef sorenson_dice(text1, text2):\n    \n    bc1, bc2 = tokenizetext(text1), tokenizetext(text2)\n    return 2 * len(bc1 & bc2) / (len(bc1) + len(bc2))\n\n\nwith open('tasklist_sorenson.txt', 'r') as fd:\n    alltasks = fd.read().split('\\n')\n\nfor testtext in ['Primordial primes', 'Sunkist-Giuliani formula',\n                 'Sieve of Euripides', 'Chowder numbers']:\n    taskvalues = sorted([(sorenson_dice(testtext, t), t)\n                        for t in alltasks], reverse=True)\n    print(f'\\n{testtext}:')\n    for (val, task) in taskvalues[:5]:\n        print(f'  {val:.6f}  {task}')\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <set>\n#include <sstream>\n#include <string>\n#include <vector>\n\nusing bigram = std::pair<char, char>;\n\nstd::multiset<bigram> bigrams(const std::string& phrase) {\n    std::multiset<bigram> result;\n    std::istringstream is(phrase);\n    std::string word;\n    while (is >> word) {\n        for (char& ch : word) {\n            ch = std::tolower(static_cast<unsigned char>(ch));\n        }\n        size_t length = word.size();\n        if (length == 1) {\n            result.emplace(word[0], '\\0');\n        } else {\n            for (size_t i = 0; i + 1 < length; ++i) {\n                result.emplace(word[i], word[i + 1]);\n            }\n        }\n    }\n    return result;\n}\n\ndouble sorensen(const std::string& s1, const std::string& s2) {\n    auto a = bigrams(s1);\n    auto b = bigrams(s2);\n    std::multiset<bigram> c;\n    std::set_intersection(a.begin(), a.end(), b.begin(), b.end(),\n                          std::inserter(c, c.begin()));\n    return (2.0 * c.size()) / (a.size() + b.size());\n}\n\nint main() {\n    std::vector<std::string> tasks;\n    std::ifstream is(\"tasks.txt\");\n    if (!is) {\n        std::cerr << \"Cannot open tasks file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string task;\n    while (getline(is, task)) {\n        tasks.push_back(task);\n    }\n    const size_t tc = tasks.size();\n    const std::string tests[] = {\"Primordial primes\",\n                                 \"Sunkist-Giuliani formula\",\n                                 \"Sieve of Euripides\", \"Chowder numbers\"};\n    std::vector<std::pair<double, size_t>> sdi(tc);\n    std::cout << std::fixed;\n    for (const std::string& test : tests) {\n        for (size_t i = 0; i != tc; ++i) {\n            sdi[i] = std::make_pair(sorensen(tasks[i], test), i);\n        }\n        std::partial_sort(sdi.begin(), sdi.begin() + 5, sdi.end(),\n                          [](const std::pair<double, size_t>& a,\n                             const std::pair<double, size_t>& b) {\n                              return a.first > b.first;\n                          });\n        std::cout << test << \" >\\n\";\n        for (size_t i = 0; i < 5 && i < tc; ++i) {\n            std::cout << \"  \" << sdi[i].first << ' ' << tasks[sdi[i].second]\n                      << '\\n';\n        }\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56550, "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": 56551, "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 <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": 56552, "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 <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": 56553, "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": "#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": 56554, "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 <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": 56555, "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 <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": 56556, "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", "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": 56557, "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", "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": 56558, "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", "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": 56559, "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", "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": 56560, "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", "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": 56561, "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", "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": 56562, "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", "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": 56563, "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", "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": 56564, "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", "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": 56565, "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", "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": 56566, "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", "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": 56567, "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", "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": 56568, "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", "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": 56569, "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", "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": 56570, "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", "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": 56571, "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", "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": 56572, "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", "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": 56573, "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", "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": 56574, "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", "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": 56575, "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", "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": 56576, "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", "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": 56577, "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", "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": 56578, "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", "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": 56579, "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", "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": 56580, "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", "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": 56581, "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", "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": 56582, "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", "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": 56583, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\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": 56584, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\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": 56585, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 56586, "name": "Checkpoint synchronization", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n"}
{"id": 56587, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56588, "name": "Variable-length quantity", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56589, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 56590, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 56591, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 56592, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 56593, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 56594, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 56595, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 56596, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56597, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56598, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 56599, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 56600, "name": "Totient function", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 56601, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 56602, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 56603, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 56604, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 56605, "name": "Animation", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 56606, "name": "Sorting algorithms_Radix sort", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n"}
{"id": 56607, "name": "Sorting algorithms_Radix sort", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n"}
{"id": 56608, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 56609, "name": "List comprehensions", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 56610, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 56611, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 56612, "name": "Singleton", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n"}
{"id": 56613, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n"}
{"id": 56614, "name": "Safe addition", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n"}
{"id": 56615, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 56616, "name": "Write entire file", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 56617, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 56618, "name": "Common sorted list", "C#": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 56619, "name": "Non-continuous subsequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56620, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 56621, "name": "Twin primes", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 56622, "name": "Roots of unity", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56623, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 56624, "name": "Pell's equation", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 56625, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 56626, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 56627, "name": "Product of divisors", "C#": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 56628, "name": "Product of divisors", "C#": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 56629, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 56630, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 56631, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 56632, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 56633, "name": "Man or boy test", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 56634, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 56635, "name": "Short-circuit evaluation", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 56636, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 56637, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 56638, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 56639, "name": "Image noise", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 56640, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 56641, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 56642, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 56643, "name": "Inverted index", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 56644, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 56645, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 56646, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 56647, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 56648, "name": "Water collected between towers", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 56649, "name": "Descending primes", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 56650, "name": "Sum and product puzzle", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n"}
{"id": 56651, "name": "Sum and product puzzle", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n"}
{"id": 56652, "name": "Parsing_Shunting-yard algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 56653, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 56654, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 56655, "name": "Stern-Brocot sequence", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 56656, "name": "Documentation", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n"}
{"id": 56657, "name": "Problem of Apollonius", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n"}
{"id": 56658, "name": "Longest common suffix", "C#": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n"}
{"id": 56659, "name": "Chat server", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n"}
{"id": 56660, "name": "Chat server", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n"}
{"id": 56661, "name": "FASTA format", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n"}
{"id": 56662, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 56663, "name": "Find palindromic numbers in both binary and ternary bases", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 56664, "name": "Terminal control_Dimensions", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n"}
{"id": 56665, "name": "Terminal control_Dimensions", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n"}
{"id": 56666, "name": "Cipolla's algorithm", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 56667, "name": "Changeable words", "C#": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56668, "name": "Changeable words", "C#": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56669, "name": "Special factorials", "C#": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 56670, "name": "GUI_Maximum window dimensions", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n"}
{"id": 56671, "name": "GUI_Maximum window dimensions", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n"}
{"id": 56672, "name": "Getting the number of decimals", "C#": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 56673, "name": "Getting the number of decimals", "C#": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 56674, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 56675, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 56676, "name": "Knapsack problem_Unbounded", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n"}
{"id": 56677, "name": "Print debugging statement", "C#": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n"}
{"id": 56678, "name": "Range extraction", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 56679, "name": "Type detection", "C#": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n"}
{"id": 56680, "name": "Maximum triangle path sum", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 56681, "name": "Terminal control_Cursor movement", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n", "C": "#include<conio.h>\n#include<dos.h>\n\nchar *strings[] = {\"The cursor will move one position to the left\", \n  \t\t   \"The cursor will move one position to the right\",\n \t\t   \"The cursor will move vetically up one line\", \n \t\t   \"The cursor will move vertically down one line\", \n \t\t   \"The cursor will move to the beginning of the line\", \n \t\t   \"The cursor will move to the end of the line\", \n \t\t   \"The cursor will move to the top left corner of the screen\", \n \t\t   \"The cursor will move to the bottom right corner of the screen\"};\n \t\t             \nint main()\n{\n\tint i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\t\n\tclrscr();\n\tcprintf(\"This is a demonstration of cursor control using gotoxy(). Press any key to continue.\");\n\tgetch();\n\t\n\tfor(i=0;i<8;i++)\n\t{\n\t\tclrscr();\n\t\tgotoxy(5,MAXROW/2);\n\t\t\n\t\tcprintf(\"%s\",strings[i]);\n\t\tgetch();\n\t\t\n\t\tswitch(i){\n\t\t\tcase 0:gotoxy(wherex()-1,wherey());\n\t\t\tbreak;\n\t\t\tcase 1:gotoxy(wherex()+1,wherey());\n\t\t\tbreak;\n\t\t\tcase 2:gotoxy(wherex(),wherey()-1);\n\t\t\tbreak;\n\t\t\tcase 3:gotoxy(wherex(),wherey()+1);\n\t\t\tbreak;\n\t\t\tcase 4:for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()-1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 5:gotoxy(wherex()-strlen(strings[i]),wherey());\n\t\t\t       for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()+1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 6:while(wherex()!=1)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()-1,wherey());\n\t\t\t\t     delay(100);\n\t\t               }\n\t\t\t       while(wherey()!=1)\n\t\t\t       {\n\t\t\t             gotoxy(wherex(),wherey()-1);\n\t\t\t             delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 7:while(wherex()!=MAXCOL)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()+1,wherey());\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\t       while(wherey()!=MAXROW)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex(),wherey()+1);\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\t};\n\t\t\tgetch();\n\t}\n\t\n\tclrscr();\n\tcprintf(\"End of demonstration.\");\n\tgetch();\n\treturn 0;\n}\n"}
{"id": 56682, "name": "Words from neighbour ones", "C#": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56683, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 56684, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 56685, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 56686, "name": "Four bit adder", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 56687, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n"}
{"id": 56688, "name": "UTF-8 encode and decode", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n"}
{"id": 56689, "name": "Magic squares of doubly even order", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 56690, "name": "Same fringe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 56691, "name": "Same fringe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 56692, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n"}
{"id": 56693, "name": "Peaceful chess queen armies", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56694, "name": "Numbers with same digit set in base 10 and base 16", "C#": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 56695, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 56696, "name": "Sum of first n cubes", "C#": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n"}
{"id": 56697, "name": "Sum of first n cubes", "C#": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n"}
{"id": 56698, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n"}
{"id": 56699, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n"}
{"id": 56700, "name": "Scope modifiers", "C#": "public \nprotected \ninternal \nprotected internal \nprivate \n\nprivate protected \n\n\n\n\n\n\n\n\n\n\n\n", "C": "int a;          \nstatic int p;   \n\nextern float v; \n\n\nint code(int arg)\n{\n  int myp;        \n                  \n                  \n  static int myc; \n                  \n                  \n                  \n                  \n}\n\n\nstatic void code2(void)\n{\n  v = v * 1.02;    \n  \n}\n"}
{"id": 56701, "name": "GUI component interaction", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n"}
{"id": 56702, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 56703, "name": "One of n lines in a file", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 56704, "name": "Addition chains", "C#": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 56705, "name": "Addition chains", "C#": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 56706, "name": "Numeric separator syntax", "C#": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n"}
{"id": 56707, "name": "Numeric separator syntax", "C#": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n"}
{"id": 56708, "name": "Repeat", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 56709, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 56710, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 56711, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 56712, "name": "Sunflower fractal", "C#": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 56713, "name": "The sieve of Sundaram", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\nint main(void) {\n    int nprimes =  1000000;\n    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  \n      \n      \n    int i, j, m, k; int *a;\n    k = (nmax-2)/2; \n    a = (int *)calloc(k + 1, sizeof(int));\n    for(i = 0; i <= k; i++)a[i] = 2*i+1; \n    for (i = 1; (i+1)*i*2 <= k; i++)\n        for (j = i; j <= (k-i)/(2*i+1); j++) {\n            m = i + j + 2*i*j;\n            if(a[m]) a[m] = 0;\n            }            \n        \n    for (i = 1, j = 0; i <= k; i++) \n       if (a[i]) {\n           if(j%10 == 0 && j <= 100)printf(\"\\n\");\n           j++; \n           if(j <= 100)printf(\"%3d \", a[i]);\n           else if(j == nprimes){\n               printf(\"\\n%d th prime is %d\\n\",j,a[i]);\n               break;\n               }\n           }\n}\n"}
{"id": 56714, "name": "Active Directory_Connect", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n"}
{"id": 56715, "name": "Active Directory_Connect", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n"}
{"id": 56716, "name": "Pythagorean quadruples", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 56717, "name": "Steady squares", "C#": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n"}
{"id": 56718, "name": "Rosetta Code_Find unimplemented tasks", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 56719, "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": 56720, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 56721, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 56722, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\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": 56723, "name": "Peano curve", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\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": 56724, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\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": 56725, "name": "Magnanimous numbers", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\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": 56726, "name": "Extensible prime generator", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\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": 56727, "name": "Create a two-dimensional array at runtime", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\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": 56728, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 56729, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 56730, "name": "Pi", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\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": 56731, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 56732, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 56733, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 56734, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 56735, "name": "Return multiple values", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 56736, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 56737, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 56738, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 56739, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 56740, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 56741, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\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": 56742, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\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": 56743, "name": "LU decomposition", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\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": 56744, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\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": 56745, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\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": 56746, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\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": 56747, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\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": 56748, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\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": 56749, "name": "Text processing_1", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\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": 56750, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\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": 56751, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\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": 56752, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\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": 56753, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\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": 56754, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\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": 56755, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\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": 56756, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\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": 56757, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\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": 56758, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\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": 56759, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\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": 56760, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "Go": "var intStack []int\n"}
{"id": 56761, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\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": 56762, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 56763, "name": "Fractran", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\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": 56764, "name": "Read a configuration file", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\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": 56765, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\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": 56766, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\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": 56767, "name": "List comprehensions", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\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": 56768, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\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": 56769, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\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": 56770, "name": "Case-sensitivity of identifiers", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\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": 56771, "name": "Loops_Downward for", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 56772, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 56773, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\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": 56774, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \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": 56775, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \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": 56776, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\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": 56777, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\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": 56778, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\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": 56779, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\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": 56780, "name": "Pell's equation", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\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": 56781, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\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": 56782, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\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": 56783, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\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": 56784, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\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": 56785, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\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": 56786, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\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": 56787, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\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": 56788, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\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": 56789, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\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": 56790, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\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": 56791, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n"}
{"id": 56792, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n"}
{"id": 56793, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 56794, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 56795, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 56796, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 56797, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 56798, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 56799, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 56800, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 56801, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 56802, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 56803, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 56804, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 56805, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 56806, "name": "Jaro similarity", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n"}
{"id": 56807, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n"}
{"id": 56808, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 56809, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 56810, "name": "Prime triangle", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n"}
{"id": 56811, "name": "Trabb Pardo–Knuth algorithm", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 56812, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 56813, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 56814, "name": "Biorhythms", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n"}
{"id": 56815, "name": "Biorhythms", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n"}
{"id": 56816, "name": "Table creation_Postal addresses", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n"}
{"id": 56817, "name": "Include a file", "VB": "\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 56818, "name": "Include a file", "VB": "\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 56819, "name": "Stern-Brocot sequence", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n"}
{"id": 56820, "name": "Soundex", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n"}
{"id": 56821, "name": "Chat server", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n"}
{"id": 56822, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 56823, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 56824, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 56825, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 56826, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 56827, "name": "Terminal control_Dimensions", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n"}
{"id": 56828, "name": "Terminal control_Dimensions", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n"}
{"id": 56829, "name": "Finite state machine", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n"}
{"id": 56830, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 56831, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 56832, "name": "Sierpinski pentagon", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n"}
{"id": 56833, "name": "Rep-string", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n"}
{"id": 56834, "name": "Literals_String", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 56835, "name": "GUI_Maximum window dimensions", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n"}
{"id": 56836, "name": "GUI_Maximum window dimensions", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n"}
{"id": 56837, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 56838, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 56839, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 56840, "name": "Parse an IP Address", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n"}
{"id": 56841, "name": "Knapsack problem_Unbounded", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n"}
{"id": 56842, "name": "Textonyms", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n"}
{"id": 56843, "name": "Range extraction", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n"}
{"id": 56844, "name": "Type detection", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n"}
{"id": 56845, "name": "Maximum triangle path sum", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 56846, "name": "Zhang-Suen thinning algorithm", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n"}
{"id": 56847, "name": "Variable declaration reset", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n"}
{"id": 56848, "name": "Start from a main routine", "VB": "SUB Main()\n  \nEND\n", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n"}
{"id": 56849, "name": "Start from a main routine", "VB": "SUB Main()\n  \nEND\n", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n"}
{"id": 56850, "name": "Start from a main routine", "VB": "SUB Main()\n  \nEND\n", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n"}
{"id": 56851, "name": "Koch 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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n"}
{"id": 56852, "name": "Draw a pixel", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n"}
{"id": 56853, "name": "Words from neighbour ones", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n"}
{"id": 56854, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 56855, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 56856, "name": "UTF-8 encode and decode", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n"}
{"id": 56857, "name": "Magic squares of doubly even order", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 56858, "name": "Calendar - for _REAL_ programmers", "VB": "OPTION COMPARE BINARY\nOPTION EXPLICIT ON\nOPTION INFER ON\nOPTION STRICT ON\n\nIMPORTS SYSTEM.GLOBALIZATION\nIMPORTS SYSTEM.TEXT\nIMPORTS SYSTEM.RUNTIME.INTEROPSERVICES\nIMPORTS SYSTEM.RUNTIME.COMPILERSERVICES\n\nMODULE ARGHELPER\n    READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()\n\n    DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN\n\n    SUB INITIALIZEARGUMENTS(ARGS AS STRING())\n        FOR EACH ITEM IN ARGS\n            ITEM = ITEM.TOUPPERINVARIANT()\n\n            IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> \"\"\"\"C THEN\n                DIM COLONPOS = ITEM.INDEXOF(\":\"C, STRINGCOMPARISON.ORDINAL)\n\n                IF COLONPOS <> -1 THEN\n                    \n                    _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))\n                END IF\n            END IF\n        NEXT\n    END SUB\n\n    SUB FROMARGUMENT(OF T)(\n            KEY AS STRING,\n            <OUT> BYREF VAR AS T,\n            GETDEFAULT AS FUNC(OF T),\n            TRYPARSE AS TRYPARSE(OF STRING, T),\n            OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)\n\n        DIM VALUE AS STRING = NOTHING\n        IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN\n            IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN\n                CONSOLE.WRITELINE($\"INVALID VALUE FOR {KEY}: {VALUE}\")\n                ENVIRONMENT.EXIT(-1)\n            END IF\n        ELSE\n            VAR = GETDEFAULT()\n        END IF\n    END SUB\nEND MODULE\n\nMODULE PROGRAM\n    SUB MAIN(ARGS AS STRING())\n        DIM DT AS DATE\n        DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER\n        DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN\n\n        INITIALIZEARGUMENTS(ARGS)\n        FROMARGUMENT(\"DATE\", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)\n        FROMARGUMENT(\"COLS\", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)\n        FROMARGUMENT(\"ROWS\", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)\n        FROMARGUMENT(\"MS/ROW\", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \\ 20)\n        FROMARGUMENT(\"VSTRETCH\", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"HSTRETCH\", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"WSIZE\", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n\n        \n        IF RESIZEWINDOW THEN\n            CONSOLE.WINDOWWIDTH = COLUMNS + 1\n            CONSOLE.WINDOWHEIGHT = ROWS\n        END IF\n\n        IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \\ 22, 1)\n\n        FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)\n            CONSOLE.WRITE(ROW)\n        NEXT\n    END SUB\n\n    ITERATOR FUNCTION GETCALENDARROWS(\n            DT AS DATE,\n            WIDTH AS INTEGER,\n            HEIGHT AS INTEGER,\n            MONTHSPERROW AS INTEGER,\n            VERTSTRETCH AS BOOLEAN,\n            HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n\n        DIM YEAR = DT.YEAR\n        DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))\n        \n        DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3\n\n        YIELD \"[SNOOPY]\".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD ENVIRONMENT.NEWLINE\n\n        DIM MONTH = 0\n        DO WHILE MONTH < 12\n            DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)\n\n            DIM CELLWIDTH = WIDTH \\ MONTHSPERROW\n            DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \\ 20)\n\n            DIM CELLHEIGHT = MONTHGRIDHEIGHT \\ CALENDARROWCOUNT\n            DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \\ 20\n\n            \n            DIM GETMONTHFROM =\n                FUNCTION(M AS INTEGER) BUILDMONTH(\n                    DT:=NEW DATE(DT.YEAR, M, 1),\n                    WIDTH:=CELLCONTENTWIDTH,\n                    HEIGHT:=CELLCONTENTHEIGHT,\n                    VERTSTRETCH:=VERTSTRETCH,\n                    HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))\n\n            \n            DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =\n                ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)\n\n            DIM CALENDARROW AS IENUMERABLE(OF STRING) =\n                INTERLEAVED(\n                    MONTHSTHISROW,\n                    USEINNERSEPARATOR:=FALSE,\n                    USEOUTERSEPARATOR:=TRUE,\n                    OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)\n\n            DIM EN = CALENDARROW.GETENUMERATOR()\n            DIM HASNEXT = EN.MOVENEXT()\n            DO WHILE HASNEXT\n\n                DIM CURRENT AS STRING = EN.CURRENT\n\n                \n                \n                HASNEXT = EN.MOVENEXT()\n                YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)\n            LOOP\n\n            MONTH += MONTHSPERROW\n        LOOP\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION INTERLEAVED(OF T)(\n            SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),\n            OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL INNERSEPARATOR AS T = NOTHING,\n            OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL OUTERSEPARATOR AS T = NOTHING,\n            OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)\n        DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING\n\n        TRY\n            SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()\n            DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH\n            DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN\n\n            DIM ANYPREVITERS AS BOOLEAN = FALSE\n            DO\n                \n                DIM FIRSTACTIVE = -1, LASTACTIVE = -1\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()\n                    IF ENUMERATORSTATES(I) THEN\n                        IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I\n                        LASTACTIVE = I\n                    END IF\n                NEXT\n\n                \n                \n                DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)\n                IF NOT THISITERHASRESULTS THEN EXIT DO\n\n                \n                IF ANYPREVITERS THEN\n                    IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR\n                ELSE\n                    ANYPREVITERS = TRUE\n                END IF\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    IF ENUMERATORSTATES(I) THEN\n                        \n                        IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR\n                        YIELD SOURCEENUMERATORS(I).CURRENT\n                    END IF\n                NEXT\n            LOOP\n\n        FINALLY\n            IF SOURCEENUMERATORS ISNOT NOTHING THEN\n                FOR EACH EN IN SOURCEENUMERATORS\n                    EN.DISPOSE()\n                NEXT\n            END IF\n        END TRY\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n        CONST DAY_WDT = 2 \n        CONST ALLDAYS_WDT = DAY_WDT * 7 \n\n        \n        DT = NEW DATE(DT.YEAR, DT.MONTH, 1)\n\n        \n        DIM DAYSEP AS NEW STRING(\" \"C, MATH.MIN((WIDTH - ALLDAYS_WDT) \\ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))\n        \n        DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \\ 7)\n\n        \n        DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6\n\n        \n        DIM LEFTPAD AS NEW STRING(\" \"C, (WIDTH - BLOCKWIDTH) \\ 2)\n        \n        DIM FULLPAD AS NEW STRING(\" \"C, WIDTH)\n\n        \n        DIM SB AS NEW STRINGBUILDER(LEFTPAD)\n        DIM NUMLINES = 0\n\n        \n        \n        \n        DIM ENDLINE =\n         FUNCTION() AS IENUMERABLE(OF STRING)\n             DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)\n             SB.CLEAR()\n             SB.APPEND(LEFTPAD)\n\n             \n             RETURN IF(NUMLINES >= HEIGHT,\n                 ENUMERABLE.EMPTY(OF STRING)(),\n                 ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)\n                     YIELD FINISHEDLINE\n                     NUMLINES += 1\n\n                     FOR I = 1 TO VERTBLANKCOUNT\n                         IF NUMLINES >= HEIGHT THEN RETURN\n                         YIELD FULLPAD\n                         NUMLINES += 1\n                     NEXT\n                 END FUNCTION())\n         END FUNCTION\n\n        \n        SB.APPEND(PADCENTER(DT.TOSTRING(\"MMMM\", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())\n        SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM STARTWKDY = CINT(DT.DAYOFWEEK)\n\n        \n        DIM FIRSTPAD AS NEW STRING(\" \"C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)\n        SB.APPEND(FIRSTPAD)\n\n        DIM D = DT\n        DO WHILE D.MONTH = DT.MONTH\n            SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $\"{{0,{DAY_WDT}}}\", D.DAY)\n\n            \n            IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN\n                FOR EACH L IN ENDLINE()\n                    YIELD L\n                NEXT\n            ELSE\n                SB.APPEND(DAYSEP)\n            END IF\n\n            D = D.ADDDAYS(1)\n        LOOP\n\n        \n        DIM NEXTLINES AS IENUMERABLE(OF STRING)\n        DO\n            NEXTLINES = ENDLINE()\n            FOR EACH L IN NEXTLINES\n                YIELD L\n            NEXT\n        LOOP WHILE NEXTLINES.ANY()\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    <EXTENSION()>\n    PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = \" \"C) AS STRING\n        RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \\ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)\n    END FUNCTION\nEND MODULE\n", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n"}
{"id": 56859, "name": "Loops_Infinite", "VB": "Do\n   Debug.Print \"SPAM\"\nLoop\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 56860, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 56861, "name": "Execute a system command", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 56862, "name": "XML validation", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 56863, "name": "Longest increasing subsequence", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 56864, "name": "Death Star", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": 56865, "name": "Verify distribution uniformity_Chi-squared test", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n"}
{"id": 56866, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 56867, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 56868, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 56869, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 56870, "name": "One of n lines in a file", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 56871, "name": "Spelling of ordinal numbers", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": 56872, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 56873, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 56874, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n"}
{"id": 56875, "name": "Repeat", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 56876, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n"}
{"id": 56877, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 56878, "name": "Hello world_Web server", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 56879, "name": "Own digits power sum", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\n\n\n\nModule OwnDigitsPowerSum\n\n    Public Sub Main\n\n        \n        Dim used(9) As Integer\n        Dim check(9) As Integer\n        Dim power(9, 9) As Long\n        For i As Integer = 0 To 9\n            check(i) = 0\n        Next i\n        For i As Integer = 1 To 9\n            power(1,  i) = i\n        Next i\n        For j As Integer =  2 To 9\n            For i As Integer = 1 To 9\n                power(j, i) = power(j - 1, i) * i\n            Next i\n        Next j\n        \n        \n        Dim lowestDigit(9) As Integer\n        lowestDigit(1) = -1\n        lowestDigit(2) = -1\n        Dim p10 As Long = 100\n        For i As Integer = 3 To 9\n            For p As Integer = 2 To 9\n                Dim np As Long = power(i, p) * i\n                If Not ( np < p10) Then Exit For\n                lowestDigit(i) = p\n            Next p\n            p10 *= 10\n        Next i\n        \n        Dim maxZeros(9, 9) As Integer\n        For i As Integer = 1 To 9\n            For j As Integer = 1 To 9\n                maxZeros(i, j) = 0\n            Next j\n        Next i\n        p10 = 1000\n        For w As Integer = 3 To 9\n            For d As Integer = lowestDigit(w) To 9\n                Dim nz As Integer = 9\n                Do\n                    If nz < 0 Then\n                        Exit Do\n                    Else\n                        Dim np As Long = power(w, d) * nz\n                        IF Not ( np > p10) Then Exit Do\n                    End If\n                    nz -= 1\n                Loop\n                maxZeros(w, d) = If(nz > w, 0, w - nz)\n            Next d\n            p10 *= 10\n        Next w\n        \n        \n        Dim numbers(100) As Long     \n        Dim nCount As Integer = 0    \n        Dim tryCount As Integer = 0  \n        Dim digits(9) As Integer     \n        For d As Integer = 1 To 9\n             digits(d) = 9\n        Next d\n        For d As Integer = 0 To 8\n            used(d) = 0\n        Next d\n        used(9) = 9\n        Dim width As Integer = 9     \n        Dim last As Integer = width  \n        p10 = 100000000              \n        Do While width > 2\n            tryCount += 1\n            Dim dps As Long = 0      \n            check(0) = used(0)\n            For i As Integer = 1 To 9\n                check(i) = used(i)\n                If used(i) <> 0 Then\n                    dps += used(i) * power(width, i)\n                End If\n            Next i\n            \n            Dim n As Long = dps\n            Do\n                check(CInt(n Mod 10)) -= 1 \n                n \\= 10\n            Loop Until n <= 0\n            Dim reduceWidth As Boolean = dps <= p10\n            If Not reduceWidth Then\n                \n                \n                \n                Dim zCount As Integer = 0\n                For i As Integer = 0 To 9\n                    If check(i) <> 0 Then Exit For\n                    zCount+= 1\n                Next i\n                If zCount = 10 Then\n                    nCount += 1\n                    numbers(nCount) = dps\n                End If\n                \n                used(digits(last)) -= 1\n                digits(last) -= 1\n                If digits(last) = 0 Then\n                    \n                    If used(0) >= maxZeros(width, digits(1)) Then\n                        \n                        digits(last) = -1\n                    End If\n                End If\n                If digits(last) >= 0 Then\n                    \n                    used(digits(last)) += 1\n                Else\n                    \n                    Dim prev As Integer = last\n                    Do\n                        prev -= 1\n                        If prev < 1 Then\n                            Exit Do\n                        Else\n                            used(digits(prev)) -= 1\n                            digits(prev) -= 1\n                            IF digits(prev) >= 0 Then Exit Do\n                        End If\n                    Loop\n                    If prev > 0 Then\n                        \n                        If prev = 1 Then\n                            If digits(1) <= lowestDigit(width) Then\n                               \n                               prev = 0\n                            End If\n                        End If\n                        If prev <> 0 Then\n                           \n                            used(digits(prev)) += 1\n                            For i As Integer = prev + 1 To width\n                                digits(i) = digits(prev)\n                                used(digits(prev)) += 1\n                            Next i\n                        End If\n                    End If\n                    If prev <= 0 Then\n                        \n                        reduceWidth = True\n                    End If\n                End If\n            End If\n            If reduceWidth Then\n                \n                last -= 1\n                width = last\n                If last > 0 Then\n                    \n                    For d As Integer = 1 To last\n                        digits(d) = 9\n                    Next d\n                    For d As Integer = last + 1 To 9\n                        digits(d) = -1\n                    Next d\n                    For d As Integer = 0 To 8\n                        used(d) = 0\n                    Next d\n                    used(9) = last\n                    p10 \\= 10\n                End If\n            End If\n        Loop\n        \n        Console.Out.WriteLine(\"Own digits power sums for N = 3 to 9 inclusive:\")\n        For i As Integer = nCount To 1 Step -1\n            Console.Out.WriteLine(numbers(i))\n        Next i\n        Console.Out.WriteLine(\"Considered \" & tryCount & \" digit combinations\")\n\n    End Sub\n\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n    fmt.Println(\"Own digits power sums for N = 3 to 9 inclusive:\")\n    for n := 3; n < 10; n++ {\n        for d := 2; d < 10; d++ {\n            powers[d] *= d\n        }\n        i := int(math.Pow(10, float64(n-1)))\n        max := i * 10\n        lastDigit := 0\n        sum := 0\n        var digits []int\n        for i < max {\n            if lastDigit == 0 {\n                digits = rcu.Digits(i, 10)\n                sum = 0\n                for _, d := range digits {\n                    sum += powers[d]\n                }\n            } else if lastDigit == 1 {\n                sum++\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1]\n            }\n            if sum == i {\n                fmt.Println(i)\n                if lastDigit == 0 {\n                    fmt.Println(i + 1)\n                }\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if sum > i {\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if lastDigit < 9 {\n                i++\n                lastDigit++\n            } else {\n                i++\n                lastDigit = 0\n            }\n        }\n    }\n}\n"}
{"id": 56880, "name": "Sorting algorithms_Pancake sort", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n"}
{"id": 56881, "name": "Sorting algorithms_Pancake sort", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n"}
{"id": 56882, "name": "Chemical calculator", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n"}
{"id": 56883, "name": "Chemical calculator", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n"}
{"id": 56884, "name": "Pythagorean quadruples", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n"}
{"id": 56885, "name": "Long stairs", "VB": "Option Explicit\nRandomize Timer\n\nFunction pad(s,n) \n  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If \nEnd Function\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\nFunction Rounds(maxsecs,wiz,a)\n  Dim mystep,maxstep,toend,j,i,x,d \n  If IsArray(a) Then d=True: print \"seconds behind pending\"   \n  maxstep=100\n  For j=1 To maxsecs\n    For i=1 To wiz\n      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1\n      maxstep=maxstep+1  \n    Next \n    mystep=mystep+1 \n    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function\n    If d Then\n      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)\n    End If     \n  Next \n  Rounds=Array(maxsecs,maxstep)\nEnd Function\n\n\nDim n,r,a,sumt,sums,ntests,t,maxsecs\nntests=10000\nmaxsecs=7000\nt=timer\na=Array(600,609)\nFor n=1 To ntests\n  r=Rounds(maxsecs,5,a)\n  If r(0)<>maxsecs Then \n    sumt=sumt+r(0)\n    sums=sums+r(1)\n  End if  \n  a=\"\"\nNext  \n\nprint vbcrlf & \"Done \" & ntests & \" tests in \" & Timer-t & \" seconds\" \nprint \"escaped in \" & sumt/ntests  & \" seconds with \" & sums/ntests & \" stairs\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    totalSecs := 0\n    totalSteps := 0\n    fmt.Println(\"Seconds    steps behind    steps ahead\")\n    fmt.Println(\"-------    ------------    -----------\")\n    for trial := 1; trial < 10000; trial++ {\n        sbeh := 0\n        slen := 100\n        secs := 0\n        for sbeh < slen {\n            sbeh++\n            for wiz := 1; wiz < 6; wiz++ {\n                if rand.Intn(slen) < sbeh {\n                    sbeh++\n                }\n                slen++\n            }\n            secs++\n            if trial == 1 && secs > 599 && secs < 610 {\n                fmt.Printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh)\n            }\n        }\n        totalSecs += secs\n        totalSteps += slen\n    }\n    fmt.Println(\"\\nAverage secs taken:\", float64(totalSecs)/10000)\n    fmt.Println(\"Average final length of staircase:\", float64(totalSteps)/10000)\n}\n"}
{"id": 56886, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 56887, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 56888, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 56889, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 56890, "name": "Zebra puzzle", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"log\"\n        \"strings\"\n)\n\n\n\ntype HouseSet [5]*House\ntype House struct {\n        n Nationality\n        c Colour\n        a Animal\n        d Drink\n        s Smoke\n}\ntype Nationality int8\ntype Colour int8\ntype Animal int8\ntype Drink int8\ntype Smoke int8\n\n\n\nconst (\n        English Nationality = iota\n        Swede\n        Dane\n        Norwegian\n        German\n)\nconst (\n        Red Colour = iota\n        Green\n        White\n        Yellow\n        Blue\n)\nconst (\n        Dog Animal = iota\n        Birds\n        Cats\n        Horse\n        Zebra\n)\nconst (\n        Tea Drink = iota\n        Coffee\n        Milk\n        Beer\n        Water\n)\nconst (\n        PallMall Smoke = iota\n        Dunhill\n        Blend\n        BlueMaster\n        Prince\n)\n\n\n\nvar nationalities = [...]string{\"English\", \"Swede\", \"Dane\", \"Norwegian\", \"German\"}\nvar colours = [...]string{\"red\", \"green\", \"white\", \"yellow\", \"blue\"}\nvar animals = [...]string{\"dog\", \"birds\", \"cats\", \"horse\", \"zebra\"}\nvar drinks = [...]string{\"tea\", \"coffee\", \"milk\", \"beer\", \"water\"}\nvar smokes = [...]string{\"Pall Mall\", \"Dunhill\", \"Blend\", \"Blue Master\", \"Prince\"}\n\nfunc (n Nationality) String() string { return nationalities[n] }\nfunc (c Colour) String() string      { return colours[c] }\nfunc (a Animal) String() string      { return animals[a] }\nfunc (d Drink) String() string       { return drinks[d] }\nfunc (s Smoke) String() string       { return smokes[s] }\nfunc (h House) String() string {\n        return fmt.Sprintf(\"%-9s  %-6s  %-5s  %-6s  %s\", h.n, h.c, h.a, h.d, h.s)\n}\nfunc (hs HouseSet) String() string {\n        lines := make([]string, 0, len(hs))\n        for i, h := range hs {\n                s := fmt.Sprintf(\"%d  %s\", i, h)\n                lines = append(lines, s)\n        }\n        return strings.Join(lines, \"\\n\")\n}\n\n\n\nfunc simpleBruteForce() (int, HouseSet) {\n        var v []House\n        for n := range nationalities {\n                for c := range colours {\n                        for a := range animals {\n                                for d := range drinks {\n                                        for s := range smokes {\n                                                h := House{\n                                                        n: Nationality(n),\n                                                        c: Colour(c),\n                                                        a: Animal(a),\n                                                        d: Drink(d),\n                                                        s: Smoke(s),\n                                                }\n                                                if !h.Valid() {\n                                                        continue\n                                                }\n                                                v = append(v, h)\n                                        }\n                                }\n                        }\n                }\n        }\n        n := len(v)\n        log.Println(\"Generated\", n, \"valid houses\")\n\n        combos := 0\n        first := 0\n        valid := 0\n        var validSet HouseSet\n        for a := 0; a < n; a++ {\n                if v[a].n != Norwegian { \n                        continue\n                }\n                for b := 0; b < n; b++ {\n                        if b == a {\n                                continue\n                        }\n                        if v[b].anyDups(&v[a]) {\n                                continue\n                        }\n                        for c := 0; c < n; c++ {\n                                if c == b || c == a {\n                                        continue\n                                }\n                                if v[c].d != Milk { \n                                        continue\n                                }\n                                if v[c].anyDups(&v[b], &v[a]) {\n                                        continue\n                                }\n                                for d := 0; d < n; d++ {\n                                        if d == c || d == b || d == a {\n                                                continue\n                                        }\n                                        if v[d].anyDups(&v[c], &v[b], &v[a]) {\n                                                continue\n                                        }\n                                        for e := 0; e < n; e++ {\n                                                if e == d || e == c || e == b || e == a {\n                                                        continue\n                                                }\n                                                if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {\n                                                        continue\n                                                }\n                                                combos++\n                                                set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}\n                                                if set.Valid() {\n                                                        valid++\n                                                        if valid == 1 {\n                                                                first = combos\n                                                        }\n                                                        validSet = set\n                                                        \n                                                }\n                                        }\n                                }\n                        }\n                }\n        }\n        log.Println(\"Tested\", first, \"different combinations of valid houses before finding solution\")\n        log.Println(\"Tested\", combos, \"different combinations of valid houses in total\")\n        return valid, validSet\n}\n\n\nfunc (h *House) anyDups(list ...*House) bool {\n        for _, b := range list {\n                if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {\n                        return true\n                }\n        }\n        return false\n}\n\nfunc (h *House) Valid() bool {\n        \n        if h.n == English && h.c != Red || h.n != English && h.c == Red {\n                return false\n        }\n        \n        if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {\n                return false\n        }\n        \n        if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {\n                return false\n        }\n        \n        if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {\n                return false\n        }\n        \n        if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {\n                return false\n        }\n        \n        if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {\n                return false\n        }\n        \n        if h.a == Cats && h.s == Blend {\n                return false\n        }\n        \n        if h.a == Horse && h.s == Dunhill {\n                return false\n        }\n        \n        if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {\n                return false\n        }\n        \n        if h.n == German && h.s != Prince || h.n != German && h.s == Prince {\n                return false\n        }\n        \n        if h.n == Norwegian && h.c == Blue {\n                return false\n        }\n        \n        if h.d == Water && h.s == Blend {\n                return false\n        }\n        return true\n}\n\nfunc (hs *HouseSet) Valid() bool {\n        ni := make(map[Nationality]int, 5)\n        ci := make(map[Colour]int, 5)\n        ai := make(map[Animal]int, 5)\n        di := make(map[Drink]int, 5)\n        si := make(map[Smoke]int, 5)\n        for i, h := range hs {\n                ni[h.n] = i\n                ci[h.c] = i\n                ai[h.a] = i\n                di[h.d] = i\n                si[h.s] = i\n        }\n        \n        if ci[Green]+1 != ci[White] {\n                return false\n        }\n        \n        if dist(ai[Cats], si[Blend]) != 1 {\n                return false\n        }\n        \n        if dist(ai[Horse], si[Dunhill]) != 1 {\n                return false\n        }\n        \n        if dist(ni[Norwegian], ci[Blue]) != 1 {\n                return false\n        }\n        \n        if dist(di[Water], si[Blend]) != 1 {\n                return false\n        }\n\n        \n        if hs[2].d != Milk {\n                return false\n        }\n        \n        if hs[0].n != Norwegian {\n                return false\n        }\n        return true\n}\n\nfunc dist(a, b int) int {\n        if a > b {\n                return a - b\n        }\n        return b - a\n}\n\nfunc main() {\n        log.SetFlags(0)\n        n, sol := simpleBruteForce()\n        fmt.Println(n, \"solution found\")\n        fmt.Println(sol)\n}\n"}
{"id": 56891, "name": "Rosetta Code_Find unimplemented tasks", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n"}
{"id": 56892, "name": "Rosetta Code_Find unimplemented tasks", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n"}
{"id": 56893, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 56894, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 56895, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 56896, "name": "Practical numbers", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n"}
{"id": 56897, "name": "Word search", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n"}
{"id": 56898, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 56899, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 56900, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 56901, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 56902, "name": "Long year", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 56903, "name": "Zumkeller numbers", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 56904, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 56905, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 56906, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 56907, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 56908, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 56909, "name": "Dijkstra's algorithm", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 56910, "name": "Geometric algebra", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n"}
{"id": 56911, "name": "Associative array_Iteration", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 56912, "name": "Define a primitive data type", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n"}
{"id": 56913, "name": "Hash join", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 56914, "name": "Sierpinski square 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n"}
{"id": 56915, "name": "Find words whose first and last three letters are equal", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\nset d= createobject(\"Scripting.Dictionary\")\nfor each aa in a\n  x=trim(aa)\n  l=len(x)\n  if l>5 then\n   d.removeall\n   for i=1 to 3\n     m=mid(x,i,1)\n     if not d.exists(m) then d.add m,null\n   next\n   res=true\n   for i=l-2 to l\n     m=mid(x,i,1)\n     if not d.exists(m) then \n       res=false:exit for \n      else\n        d.remove(m)\n      end if        \n   next \n   if res then \n     wscript.stdout.write left(x & space(15),15)\n     if left(x,3)=right(x,3) then  wscript.stdout.write \"*\"\n     wscript.stdout.writeline\n    end if \n  end if\nnext\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    count := 0\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {\n            count++\n            fmt.Printf(\"%d: %s\\n\", count, s)\n        }\n    }\n}\n"}
{"id": 56916, "name": "Word break problem", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n"}
{"id": 56917, "name": "Latin Squares in reduced form", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n"}
{"id": 56918, "name": "UPC", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 56919, "name": "Closest-pair problem", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n"}
{"id": 56920, "name": "Address of a variable", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n"}
{"id": 56921, "name": "Address of a variable", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n"}
{"id": 56922, "name": "Inheritance_Single", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 56923, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 56924, "name": "Color wheel", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n"}
{"id": 56925, "name": "Find words which contain the most consonants", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n"}
{"id": 56926, "name": "Minesweeper game", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\ntype cell struct {\n    isMine  bool\n    display byte \n}\n\nconst lMargin = 4\n\nvar (\n    grid        [][]cell\n    mineCount   int\n    minesMarked int\n    isGameOver  bool\n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc makeGrid(n, m int) {\n    if n <= 0 || m <= 0 {\n        panic(\"Grid dimensions must be positive.\")\n    }\n    grid = make([][]cell, n)\n    for i := 0; i < n; i++ {\n        grid[i] = make([]cell, m)\n        for j := 0; j < m; j++ {\n            grid[i][j].display = '.'\n        }\n    }\n    min := int(math.Round(float64(n*m) * 0.1)) \n    max := int(math.Round(float64(n*m) * 0.2)) \n    mineCount = min + rand.Intn(max-min+1)\n    rm := mineCount\n    for rm > 0 {\n        x, y := rand.Intn(n), rand.Intn(m)\n        if !grid[x][y].isMine {\n            rm--\n            grid[x][y].isMine = true\n        }\n    }\n    minesMarked = 0\n    isGameOver = false\n}\n\nfunc displayGrid(isEndOfGame bool) {\n    if !isEndOfGame {\n        fmt.Println(\"Grid has\", mineCount, \"mine(s),\", minesMarked, \"mine(s) marked.\")\n    }\n    margin := strings.Repeat(\" \", lMargin)\n    fmt.Print(margin, \" \")\n    for i := 1; i <= len(grid); i++ {\n        fmt.Print(i)\n    }\n    fmt.Println()\n    fmt.Println(margin, strings.Repeat(\"-\", len(grid)))\n    for y := 0; y < len(grid[0]); y++ {\n        fmt.Printf(\"%*d:\", lMargin, y+1)\n        for x := 0; x < len(grid); x++ {\n            fmt.Printf(\"%c\", grid[x][y].display)\n        }\n        fmt.Println()\n    }\n}\n\nfunc endGame(msg string) {\n    isGameOver = true\n    fmt.Println(msg)\n    ans := \"\"\n    for ans != \"y\" && ans != \"n\" {\n        fmt.Print(\"Another game (y/n)? : \")\n        scanner.Scan()\n        ans = strings.ToLower(scanner.Text())\n    }\n    if scanner.Err() != nil || ans == \"n\" {\n        return\n    }\n    makeGrid(6, 4)\n    displayGrid(false)\n}\n\nfunc resign() {\n    found := 0\n    for y := 0; y < len(grid[0]); y++ {\n        for x := 0; x < len(grid); x++ {\n            if grid[x][y].isMine {\n                if grid[x][y].display == '?' {\n                    grid[x][y].display = 'Y'\n                    found++\n                } else if grid[x][y].display != 'x' {\n                    grid[x][y].display = 'N'\n                }\n            }\n        }\n    }\n    displayGrid(true)\n    msg := fmt.Sprint(\"You found \", found, \" out of \", mineCount, \" mine(s).\")\n    endGame(msg)\n}\n\nfunc usage() {\n    fmt.Println(\"h or ? - this help,\")\n    fmt.Println(\"c x y  - clear cell (x,y),\")\n    fmt.Println(\"m x y  - marks (toggles) cell (x,y),\")\n    fmt.Println(\"n      - start a new game,\")\n    fmt.Println(\"q      - quit/resign the game,\")\n    fmt.Println(\"where x is the (horizontal) column number and y is the (vertical) row number.\\n\")\n}\n\nfunc markCell(x, y int) {\n    if grid[x][y].display == '?' {\n        minesMarked--\n        grid[x][y].display = '.'\n    } else if grid[x][y].display == '.' {\n        minesMarked++\n        grid[x][y].display = '?'\n    }\n}\n\nfunc countAdjMines(x, y int) int {\n    count := 0\n    for j := y - 1; j <= y+1; j++ {\n        if j >= 0 && j < len(grid[0]) {\n            for i := x - 1; i <= x+1; i++ {\n                if i >= 0 && i < len(grid) {\n                    if grid[i][j].isMine {\n                        count++\n                    }\n                }\n            }\n        }\n    }\n    return count\n}\n\nfunc clearCell(x, y int) bool {\n    if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {\n        if grid[x][y].display == '.' {\n            if !grid[x][y].isMine {\n                count := countAdjMines(x, y)\n                if count > 0 {\n                    grid[x][y].display = string(48 + count)[0]\n                } else {\n                    grid[x][y].display = ' '\n                    clearCell(x+1, y)\n                    clearCell(x+1, y+1)\n                    clearCell(x, y+1)\n                    clearCell(x-1, y+1)\n                    clearCell(x-1, y)\n                    clearCell(x-1, y-1)\n                    clearCell(x, y-1)\n                    clearCell(x+1, y-1)\n                }\n            } else {\n                grid[x][y].display = 'x'\n                fmt.Println(\"Kaboom! You lost!\")\n                return false\n            }\n        }\n    }\n    return true\n}\n\nfunc testForWin() bool {\n    isCleared := false\n    if minesMarked == mineCount {\n        isCleared = true\n        for x := 0; x < len(grid); x++ {\n            for y := 0; y < len(grid[0]); y++ {\n                if grid[x][y].display == '.' {\n                    isCleared = false\n                }\n            }\n        }\n    }\n    if isCleared {\n        fmt.Println(\"You won!\")\n    }\n    return isCleared\n}\n\nfunc splitAction(action string) (int, int, bool) {\n    fields := strings.Fields(action)\n    if len(fields) != 3 {\n        return 0, 0, false\n    }\n    x, err := strconv.Atoi(fields[1])\n    if err != nil || x < 1 || x > len(grid) {\n        return 0, 0, false\n    }\n    y, err := strconv.Atoi(fields[2])\n    if err != nil || y < 1 || y > len(grid[0]) {\n        return 0, 0, false\n    }\n    return x, y, true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    usage()\n    makeGrid(6, 4)\n    displayGrid(false)\n    for !isGameOver {\n        fmt.Print(\"\\n>\")\n        scanner.Scan()\n        action := strings.ToLower(scanner.Text())\n        if scanner.Err() != nil || len(action) == 0 {\n            continue\n        }\n        switch action[0] {\n        case 'h', '?':\n            usage()\n        case 'n':\n            makeGrid(6, 4)\n            displayGrid(false)\n        case 'c':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            if clearCell(x-1, y-1) {\n                displayGrid(false)\n                if testForWin() {\n                    resign()\n                }\n            } else {\n                resign()\n            }\n        case 'm':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            markCell(x-1, y-1)\n            displayGrid(false)\n            if testForWin() {\n                resign()\n            }\n        case 'q':\n            resign()\n        }\n    }\n}\n"}
{"id": 56927, "name": "Square root by hand", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 56928, "name": "Square root by hand", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n"}
{"id": 56929, "name": "Primes with digits in nondecreasing order", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n"}
{"id": 56930, "name": "Primes with digits in nondecreasing order", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n"}
{"id": 56931, "name": "Reflection_List properties", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 56932, "name": "Align columns", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n"}
{"id": 56933, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 56934, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 56935, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 56936, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 56937, "name": "Data Encryption Standard", "VB": "Imports System.IO\nImports System.Security.Cryptography\n\nModule Module1\n\n    \n    Function ByteArrayToString(ba As Byte()) As String\n        Return BitConverter.ToString(ba).Replace(\"-\", \"\")\n    End Function\n\n    \n    \n    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateEncryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(messageBytes, 0, messageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim encryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n\n        Return encryptedMessageBytes\n    End Function\n\n    \n    \n    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateDecryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim decryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)\n\n        Return decryptedMessageBytes\n    End Function\n\n    Sub Main()\n        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}\n        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}\n\n        Dim encStr = Encrypt(plainBytes, keyBytes)\n        Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr))\n\n        Dim decStr = Decrypt(encStr, keyBytes)\n        Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decStr))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n"}
{"id": 56938, "name": "Commatizing numbers", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n"}
{"id": 56939, "name": "Arithmetic coding_As a generalized change of radix", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\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 cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n"}
{"id": 56940, "name": "Kosaraju", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n"}
{"id": 56941, "name": "Pentomino tiling", "VB": "Module Module1\n\n    Dim symbols As Char() = \"XYPFTVNLUZWI█\".ToCharArray(),\n        nRows As Integer = 8, nCols As Integer = 8,\n        target As Integer = 12, blank As Integer = 12,\n        grid As Integer()() = New Integer(nRows - 1)() {},\n        placed As Boolean() = New Boolean(target - 1) {},\n        pens As List(Of List(Of Integer())), rand As Random,\n        seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}\n\n    Sub Main()\n        Unpack(seeds) : rand = New Random() : ShuffleShapes(2)\n        For r As Integer = 0 To nRows - 1\n            grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next\n        For i As Integer = 0 To 3\n            Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)\n            Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank\n        Next\n        If Solve(0, 0) Then\n            PrintResult()\n        Else\n            Console.WriteLine(\"no solution for this configuration:\") : PrintResult()\n        End If\n        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\n    Sub ShuffleShapes(count As Integer) \n        For i As Integer = 0 To count : For j = 0 To pens.Count - 1\n                Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j\n                Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp\n                Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch\n            Next : Next\n    End Sub\n\n    Sub PrintResult() \n        For Each r As Integer() In grid : For Each i As Integer In r\n                Console.Write(\"{0} \", If(i < 0, \".\", symbols(i)))\n            Next : Console.WriteLine() : Next\n    End Sub\n\n    \n    Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean\n        If numPlaced = target Then Return True\n        Dim row As Integer = pos \\ nCols, col As Integer = pos Mod nCols\n        If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)\n        For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then\n                For Each orientation As Integer() In pens(i)\n                    If Not TPO(orientation, row, col, i) Then Continue For\n                    placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True\n                    RmvO(orientation, row, col) : placed(i) = False\n                Next : End If : Next : Return False\n    End Function\n\n    \n    Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)\n        grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = -1 : Next\n    End Sub\n\n    \n    Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,\n                 ByVal sIdx As Integer) As Boolean\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)\n            If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse\n                grid(y)(x) <> -1 Then Return False\n        Next : grid(row)(col) = sIdx\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = sIdx\n        Next : Return True\n    End Function\n\n    \n    \n    \n    \n\n    Sub Unpack(sv As Integer()) \n        pens = New List(Of List(Of Integer())) : For Each item In sv\n            Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),\n                fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7\n                If i = 4 Then Mir(exi) Else Rot(exi)\n                fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))\n            Next : pens.Add(Gen) : Next\n    End Sub\n\n    \n    Function Expand(i As Integer) As List(Of Integer)\n        Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next\n    End Function\n\n    \n    Function ToP(p As List(Of Integer)) As Integer()\n        Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)\n            tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next\n        tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next\n        Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)\n            Dim adj = If((item And 7) > 4, 8, 0)\n            res.Add((adj + item) \\ 8) : res.Add((item And 7) - adj)\n        Next : Return res.ToArray()\n    End Function\n\n    \n    Function TheSame(a As Integer(), b As Integer()) As Boolean\n        For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False\n        Next : Return True\n    End Function\n\n    Sub Rot(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next\n    End Sub\n\n    Sub Mir(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar F = [][]int{\n    {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},\n    {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},\n    {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},\n}\n\nvar I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}\n\nvar L = [][]int{\n    {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},\n}\n\nvar N = [][]int{\n    {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},\n}\n\nvar P = [][]int{\n    {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},\n}\n\nvar T = [][]int{\n    {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},\n}\n\nvar U = [][]int{\n    {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},\n}\n\nvar V = [][]int{\n    {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},\n}\n\nvar W = [][]int{\n    {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},\n}\n\nvar X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}\n\nvar Y = [][]int{\n    {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},\n}\n\nvar Z = [][]int{\n    {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},\n}\n\nvar shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}\n\nvar symbols = []byte(\"FILNPTUVWXYZ-\")\n\nconst (\n    nRows = 8\n    nCols = 8\n    blank = 12\n)\n\nvar grid [nRows][nCols]int\nvar placed [12]bool\n\nfunc tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {\n    for i := 0; i < len(o); i += 2 {\n        x := c + o[i+1]\n        y := r + o[i]\n        if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {\n            return false\n        }\n    }\n    grid[r][c] = shapeIndex\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = shapeIndex\n    }\n    return true\n}\n\nfunc removeOrientation(o []int, r, c int) {\n    grid[r][c] = -1\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = -1\n    }\n}\n\nfunc solve(pos, numPlaced int) bool {\n    if numPlaced == len(shapes) {\n        return true\n    }\n    row := pos / nCols\n    col := pos % nCols\n    if grid[row][col] != -1 {\n        return solve(pos+1, numPlaced)\n    }\n\n    for i := range shapes {\n        if !placed[i] {\n            for _, orientation := range shapes[i] {\n                if !tryPlaceOrientation(orientation, row, col, i) {\n                    continue\n                }\n                placed[i] = true\n                if solve(pos+1, numPlaced+1) {\n                    return true\n                }\n                removeOrientation(orientation, row, col)\n                placed[i] = false\n            }\n        }\n    }\n    return false\n}\n\nfunc shuffleShapes() {\n    rand.Shuffle(len(shapes), func(i, j int) {\n        shapes[i], shapes[j] = shapes[j], shapes[i]\n        symbols[i], symbols[j] = symbols[j], symbols[i]\n    })\n}\n\nfunc printResult() {\n    for _, r := range grid {\n        for _, i := range r {\n            fmt.Printf(\"%c \", symbols[i])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    shuffleShapes()\n    for r := 0; r < nRows; r++ {\n        for i := range grid[r] {\n            grid[r][i] = -1\n        }\n    }\n    for i := 0; i < 4; i++ {\n        var randRow, randCol int\n        for {\n            randRow = rand.Intn(nRows)\n            randCol = rand.Intn(nCols)\n            if grid[randRow][randCol] != blank {\n                break\n            }\n        }\n        grid[randRow][randCol] = blank\n    }\n    if solve(0, 0) {\n        printResult()\n    } else {\n        fmt.Println(\"No solution\")\n    }\n}\n"}
{"id": 56942, "name": "Make a backup file", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 56943, "name": "Make a backup file", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 56944, "name": "Check Machin-like formulas", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n"}
{"id": 56945, "name": "Check Machin-like formulas", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n"}
{"id": 56946, "name": "Solve triangle solitare puzzle", "VB": "Imports System, Microsoft.VisualBasic.DateAndTime\n\nPublic Module Module1\n    Const n As Integer = 5 \n    Dim Board As String \n    Dim Starting As Integer = 1 \n    Dim Target As Integer = 13 \n    Dim Moves As Integer() \n    Dim bi() As Integer \n    Dim ib() As Integer \n    Dim nl As Char = Convert.ToChar(10) \n\n    \n    Public Function Dou(s As String) As String\n        Dou = \"\" : Dim b As Boolean = True\n        For Each ch As Char In s\n            If b Then b = ch <> \" \"\n            If b Then Dou &= ch & \" \" Else Dou = \" \" & Dou\n        Next : Dou = Dou.TrimEnd()\n    End Function\n\n    \n    Public Function Fmt(s As String) As String\n        If s.Length < Board.Length Then Return s\n        Fmt = \"\" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &\n                If(i = n, s.Substring(Board.Length), \"\") & nl\n        Next\n    End Function\n\n    \n    Public Function Triangle(n As Integer) As Integer\n        Return (n * (n + 1)) / 2\n    End Function\n\n    \n    Public Function Init(s As String, pos As Integer) As String\n        Init = s : Mid(Init, pos, 1) = \"0\"\n    End Function\n\n    \n    Public Sub InitIndex()\n        ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0\n        For i As Integer = 0 To ib.Length - 1\n            If i = 0 Then\n                ib(i) = 0 : bi(j) = 0 : j += 1\n            Else\n                If Board(i - 1) = \"1\" Then ib(i) = j : bi(j) = i : j += 1\n            End If\n        Next\n    End Sub\n\n    \n    Public Function solve(brd As String, pegsLeft As Integer) As String\n        If pegsLeft = 1 Then \n            If Target = 0 Then Return \"Completed\" \n            If brd(bi(Target) - 1) = \"1\" Then Return \"Completed\" Else Return \"fail\"\n        End If\n        For i = 1 To Board.Length \n            If brd(i - 1) = \"1\" Then \n                For Each mj In Moves \n                    Dim over As Integer = i + mj \n                    Dim land As Integer = i + 2 * mj \n                    \n                    If land >= 1 AndAlso land <= brd.Length _\n                                AndAlso brd(land - 1) = \"0\" _\n                                AndAlso brd(over - 1) = \"1\" Then\n                        setPegs(brd, \"001\", i, over, land) \n                        \n                        Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)\n                        \n                        If Res.Length <> 4 Then _\n                            Return brd & info(i, over, land) & nl & Res\n                        setPegs(brd, \"110\", i, over, land) \n                    End If\n                Next\n            End If\n        Next\n        Return \"fail\"\n    End Function\n\n    \n    Function info(frm As Integer, over As Integer, dest As Integer) As String\n        Return \"  Peg from \" & ib(frm).ToString() & \" goes to \" & ib(dest).ToString() &\n            \", removing peg at \" & ib(over).ToString()\n    End Function\n\n    \n    Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)\n        Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)\n    End Sub\n\n    \n    Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)\n        x = Math.Max(Math.Min(x, hi), lo)\n    End Sub\n\n    Public Sub Main()\n        Dim t As Integer = Triangle(n) \n        LimitIt(Starting, 1, t) \n        LimitIt(Target, 0, t)\n        Dim stime As Date = Now() \n        Moves = {-n - 1, -n, -1, 1, n, n + 1} \n        Board = New String(\"1\", n * n) \n        For i As Integer = 0 To n - 2 \n            Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(\" \", n - 1 - i)\n        Next\n        InitIndex() \n        Dim B As String = Init(Board, bi(Starting)) \n        Console.WriteLine(Fmt(B & \"  Starting with peg removed from \" & Starting.ToString()))\n        Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)\n        Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & \" ms.\"\n        If res(0).Length = 4 Then\n            If Target = 0 Then\n                Console.WriteLine(\"Unable to find a solution with last peg left anywhere.\")\n            Else\n                Console.WriteLine(\"Unable to find a solution with last peg left at \" &\n                                  Target.ToString() & \".\")\n            End If\n            Console.WriteLine(\"Computation time: \" & ts)\n        Else\n            For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next\n            Console.WriteLine(\"Computation time to first found solution: \" & ts)\n        End If\n        If Diagnostics.Debugger.IsAttached Then Console.ReadLine()\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\ntype solution struct{ peg, over, land int }\n\ntype move struct{ from, to int }\n\nvar emptyStart = 1\n\nvar board [16]bool\n\nvar jumpMoves = [16][]move{\n    {},\n    {{2, 4}, {3, 6}},\n    {{4, 7}, {5, 9}},\n    {{5, 8}, {6, 10}},\n    {{2, 1}, {5, 6}, {7, 11}, {8, 13}},\n    {{8, 12}, {9, 14}},\n    {{3, 1}, {5, 4}, {9, 13}, {10, 15}},\n    {{4, 2}, {8, 9}},\n    {{5, 3}, {9, 10}},\n    {{5, 2}, {8, 7}},\n    {{9, 8}},\n    {{12, 13}},\n    {{8, 5}, {13, 14}},\n    {{8, 4}, {9, 6}, {12, 11}, {14, 15}},\n    {{9, 5}, {13, 12}},\n    {{10, 6}, {14, 13}},\n}\n\nvar solutions []solution\n\nfunc initBoard() {\n    for i := 1; i < 16; i++ {\n        board[i] = true\n    }\n    board[emptyStart] = false\n}\n\nfunc (sol solution) split() (int, int, int) {\n    return sol.peg, sol.over, sol.land\n}\n\nfunc (mv move) split() (int, int) {\n    return mv.from, mv.to\n}\n\nfunc drawBoard() {\n    var pegs [16]byte\n    for i := 1; i < 16; i++ {\n        if board[i] {\n            pegs[i] = fmt.Sprintf(\"%X\", i)[0]\n        } else {\n            pegs[i] = '-'\n        }\n    }\n    fmt.Printf(\"       %c\\n\", pegs[1])\n    fmt.Printf(\"      %c %c\\n\", pegs[2], pegs[3])\n    fmt.Printf(\"     %c %c %c\\n\", pegs[4], pegs[5], pegs[6])\n    fmt.Printf(\"    %c %c %c %c\\n\", pegs[7], pegs[8], pegs[9], pegs[10])\n    fmt.Printf(\"   %c %c %c %c %c\\n\", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n}\n\nfunc solved() bool {\n    count := 0\n    for _, b := range board {\n        if b {\n            count++\n        }\n    }\n    return count == 1 \n}\n\nfunc solve() {\n    if solved() {\n        return\n    }\n    for peg := 1; peg < 16; peg++ {\n        if board[peg] {\n            for _, mv := range jumpMoves[peg] {\n                over, land := mv.split()\n                if board[over] && !board[land] {\n                    saveBoard := board\n                    board[peg] = false\n                    board[over] = false\n                    board[land] = true\n                    solutions = append(solutions, solution{peg, over, land})\n                    solve()\n                    if solved() {\n                        return \n                    }\n                    board = saveBoard\n                    solutions = solutions[:len(solutions)-1]\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    initBoard()\n    solve()\n    initBoard()\n    drawBoard()\n    fmt.Printf(\"Starting with peg %X removed\\n\\n\", emptyStart)\n    for _, solution := range solutions {\n        peg, over, land := solution.split()\n        board[peg] = false\n        board[over] = false\n        board[land] = true\n        drawBoard()\n        fmt.Printf(\"Peg %X jumped over %X to land on %X\\n\\n\", peg, over, land)\n    }\n}\n"}
{"id": 56947, "name": "Twelve statements", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 56948, "name": "Suffixation of decimal numbers", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n"}
{"id": 56949, "name": "Suffixation of decimal numbers", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n"}
{"id": 56950, "name": "Nested templated data", "VB": "Public Sub test()\n    Dim t(2) As Variant\n    t(0) = [{1,2}]\n    t(1) = [{3,4,1}]\n    t(2) = 5\n    p = [{\"Payload#0\",\"Payload#1\",\"Payload#2\",\"Payload#3\",\"Payload#4\",\"Payload#5\",\"Payload#6\"}]\n    Dim q(6) As Boolean\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            For j = LBound(t(i)) To UBound(t(i))\n                q(t(i)(j)) = True\n                t(i)(j) = p(t(i)(j) + 1)\n            Next j\n        Else\n            q(t(i)) = True\n            t(i) = p(t(i) + 1)\n        End If\n    Next i\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            Debug.Print Join(t(i), \", \")\n        Else\n            Debug.Print t(i)\n        End If\n    Next i\n    For i = LBound(q) To UBound(q)\n        If Not q(i) Then Debug.Print p(i + 1); \" is not used\"\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"text/template\"\n)\n\nfunc main() {\n    const t = `[[[{{index .P 1}}, {{index .P 2}}],\n  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n  {{index .P 5}}]]\n`\n    type S struct {\n        P map[int]string\n    }\n\n    var s S\n    s.P = map[int]string{\n        0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n        4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n    }\n    tmpl := template.Must(template.New(\"\").Parse(t))\n    tmpl.Execute(os.Stdout, s)\n\n    var unused []int\n    for k, _ := range s.P {\n        if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n            unused = append(unused, k)\n        }\n    }\n    sort.Ints(unused)\n    fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}\n"}
{"id": 56951, "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": 56952, "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 <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 56953, "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++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\n}\n"}
{"id": 56954, "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++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n"}
{"id": 56955, "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 <array>\n#include <iostream>\n#include <vector>\n\nstd::vector<std::pair<int, int>> connections = {\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};\nstd::array<int, 8> pegs;\nint num = 0;\n\nvoid printSolution() {\n    std::cout << \"----- \" << num++ << \" -----\\n\";\n    std::cout << \"  \"  << pegs[0] << ' ' << pegs[1] << '\\n';\n    std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\\n';\n    std::cout << \"  \"  << pegs[6] << ' ' << pegs[7] << '\\n';\n    std::cout << '\\n';\n}\n\nbool valid() {\n    for (size_t i = 0; i < connections.size(); i++) {\n        if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        for (size_t i = le; i <= ri; i++) {\n            std::swap(pegs[le], pegs[i]);\n            solution(le + 1, ri);\n            std::swap(pegs[le], pegs[i]);\n        }\n    }\n}\n\nint main() {\n    pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    solution(0, pegs.size() - 1);\n    return 0;\n}\n"}
{"id": 56956, "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 <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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56957, "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 <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 56958, "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 <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };\nenum indexes { PLAYER, COMPUTER, DRAW };\n\n\nclass stats\n{\npublic:\n    stats() : _draw( 0 )\n    {\n        ZeroMemory( _moves, sizeof( _moves ) );\n\tZeroMemory( _win, sizeof( _win ) );\n    }\n    void draw()\t\t        { _draw++; }\n    void win( int p )\t        { _win[p]++; }\n    void move( int p, int m )   { _moves[p][m]++; }\n    int getMove( int p, int m ) { return _moves[p][m]; }\n    string format( int a )\n    {\n\tchar t[32];\n\twsprintf( t, \"%.3d\", a );\n\tstring d( t );\n\treturn d;\n    }\n\n    void print()\n    {\n        string  d = format( _draw ),\n\t       pw = format( _win[PLAYER] ),\t\tcw = format( _win[COMPUTER] ),\n\t       pr = format( _moves[PLAYER][ROCK] ),\tcr = format( _moves[COMPUTER][ROCK] ),\n               pp = format( _moves[PLAYER][PAPER] ),\tcp = format( _moves[COMPUTER][PAPER] ),\n\t       ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),\n\t       pl = format( _moves[PLAYER][LIZARD] ),\tcl = format( _moves[COMPUTER][LIZARD] ),\n\t       pk = format( _moves[PLAYER][SPOCK] ),\tck = format( _moves[COMPUTER][SPOCK] );\n\n\tsystem( \"cls\" );\n\tcout << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|          |  WON  |  DRAW  |  ROCK  |  PAPER  | SCISSORS | LIZARD |  SPOCK  |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"|  PLAYER  |  \"  << pw << \"  |        |   \" << pr << \"  |   \" << pp << \"   |   \" << ps << \"    |  \" << pl << \"   |   \" << pk << \"   |\" << endl;\n\tcout << \"+----------+-------+   \" << d << \"  +--------+---------+----------+--------+---------+\" << endl;\n\tcout << \"| COMPUTER |  \"  << cw << \"  |        |   \" << cr << \"  |   \" << cp << \"   |   \" << cs << \"    |  \" << cl << \"   |   \" << ck << \"   |\" << endl;\n\tcout << \"+----------+-------+--------+--------+---------+----------+--------+---------+\" << endl;\n\tcout << endl << endl;\n\n\tsystem( \"pause\" );\n\n    }\n\nprivate:\n    int _moves[2][MX_C], _win[2], _draw;\n};\n\nclass rps\n{\nprivate:\n    int makeMove()\n    {\n\tint total = 0, r, s;\n\tfor( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );\n\tr = rand() % total;\n\n\tfor( int i = ROCK; i < SCISSORS; i++ )\n\t{\n\t    s = statistics.getMove( PLAYER, i );\n\t    if( r < s ) return ( i + 1 );\n\t    r -= s;\n\t}\n\n\treturn ROCK;\n    }\n\n    void printMove( int p, int m )\n    {\n\tif( p == COMPUTER ) cout << \"My move: \";\n\telse cout << \"Your move: \";\n\n\tswitch( m )\n\t{\n\t    case ROCK: cout << \"ROCK\\n\"; break;\n\t    case PAPER: cout << \"PAPER\\n\"; break;\n\t    case SCISSORS: cout << \"SCISSORS\\n\"; break;\n\t    case LIZARD: cout << \"LIZARD\\n\"; break;\n\t    case SPOCK: cout << \"SPOCK\\n\";\n\t}\n    }\n\npublic:\n    rps()\n    {\n\tchecker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;\n\tchecker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;\n\tchecker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;\n\tchecker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;\n\tchecker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;\n    }\n    void play()\n    {\n\tint p, r, m;\n\twhile( true )\n\t{\n\t    cout << \"What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? \";\n\t    cin >> p;\n\t    if( !p || p < 0 ) break;\n\t    if( p > 0 && p < 6 )\n\t    {\n\t\tp--;\n\t\tcout << endl;\n\t\tprintMove( PLAYER, p );\n\t\tstatistics.move( PLAYER, p );\n\n\t\tm = makeMove();\n\t\tstatistics.move( COMPUTER, m );\n\t\tprintMove( COMPUTER, m );\n\n\t\tr = checker[p][m];\n\t\tswitch( r )\n\t\t{\n\t\t    case DRAW: \n\t\t        cout << endl << \"DRAW!\" << endl << endl; \n\t\t        statistics.draw();\n\t\t    break;\n\t\t    case COMPUTER: \n\t\t\tcout << endl << \"I WIN!\" << endl << endl;  \n\t\t\tstatistics.win( COMPUTER );\n\t\t    break;\n\t\t    case PLAYER: \n\t\t\tcout << endl << \"YOU WIN!\" << endl << endl; \n\t\t\tstatistics.win( PLAYER );\n\n\t\t}\n\t\tsystem( \"pause\" );\n\t    }\n\t    system( \"cls\" );\n\t}\n\tstatistics.print();\n    }\n\nprivate:\n    stats statistics;\n    int checker[MX_C][MX_C];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    rps game;\n    game.play();\n    return 0;\n}\n\n"}
{"id": 56959, "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 <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n"}
{"id": 56960, "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++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 56961, "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++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 56962, "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 <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser \n{\nprivate:\n  array<double, 26> targets;\n  array<double, 26> sortedTargets;\n  FreqArray freq;\n\n  \n  FreqArray& frequency(const string& input) \n  {\n    for (char c = 'A'; c <= 'Z'; ++c)\n      freq[c - 'A'] = make_pair(c, 0);\n\n    for (size_t i = 0; i < input.size(); ++i)\n      freq[input[i] - 'A'].second++;\n\n    return freq;\n  }\n\n  double correlation(const string& input) \n  {\n    double result = 0.0;\n    frequency(input);\n\n    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n      { return u.second < v.second; });\n\n    for (size_t i = 0; i < 26; ++i)\n      result += freq[i].second * sortedTargets[i];\n\n    return result;\n  }\n\npublic:\n  VigenereAnalyser(const array<double, 26>& targetFreqs) \n  {\n    targets = targetFreqs;\n    sortedTargets = targets;\n    sort(sortedTargets.begin(), sortedTargets.end());\n  }\n\n  pair<string, string> analyze(string input) \n  {\n    string cleaned;\n    for (size_t i = 0; i < input.size(); ++i) \n    {\n      if (input[i] >= 'A' && input[i] <= 'Z')\n        cleaned += input[i];\n      else if (input[i] >= 'a' && input[i] <= 'z')\n        cleaned += input[i] + 'A' - 'a';\n    }\n\n    size_t bestLength = 0;\n    double bestCorr = -100.0;\n\n    \n    \n    for (size_t i = 2; i < cleaned.size() / 20; ++i) \n    {\n      vector<string> pieces(i);\n      for (size_t j = 0; j < cleaned.size(); ++j)\n        pieces[j % i] += cleaned[j];\n\n      \n      \n      double corr = -0.5*i;\n      for (size_t j = 0; j < i; ++j)\n        corr += correlation(pieces[j]);\n\n      if (corr > bestCorr) \n      {\n        bestLength = i;\n        bestCorr = corr;\n      }\n    }\n\n    if (bestLength == 0)\n      return make_pair(\"Text is too short to analyze\", \"\");\n\n    vector<string> pieces(bestLength);\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      pieces[i % bestLength] += cleaned[i];\n\n    vector<FreqArray> freqs;\n    for (size_t i = 0; i < bestLength; ++i)\n      freqs.push_back(frequency(pieces[i]));\n\n    string key = \"\";\n    for (size_t i = 0; i < bestLength; ++i) \n    {\n      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n        { return u.second > v.second; });\n\n      size_t m = 0;\n      double mCorr = 0.0;\n      for (size_t j = 0; j < 26; ++j) \n      {\n        double corr = 0.0;\n        char c = 'A' + j;\n        for (size_t k = 0; k < 26; ++k) \n        {\n          int d = (freqs[i][k].first - c + 26) % 26;\n          corr += freqs[i][k].second * targets[d];\n        }\n\n        if (corr > mCorr) \n        {\n          m = j;\n          mCorr = corr;\n        }\n      }\n\n      key += m + 'A';\n    }\n\n    string result = \"\";\n    for (size_t i = 0; i < cleaned.size(); ++i)\n      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n    return make_pair(result, key);\n  }\n};\n\nint main() \n{\n  string input =\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\n  array<double, 26> english = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n    0.01974, 0.00074};\n\n  VigenereAnalyser va(english);\n  pair<string, string> output = va.analyze(input);\n\n  cout << \"Key: \" << output.second << endl << endl;\n  cout << \"Text: \" << output.first << endl;\n}\n"}
{"id": 56963, "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 <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 56964, "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 <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 56965, "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 <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 56966, "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 <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 56967, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n"}
{"id": 56968, "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 <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56969, "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 <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 56970, "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++": " \n\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <sys/stat.h>   \n#include <ftplib.h>     \n#include <ftp++.hpp>    \n\n\n\n\n\n\n\n\nint stat(const char *pathname, struct stat *buf); \nchar *strerror(int errnum);  \nchar *basename(char *path);  \n\n\n\nnamespace stl\n{\n  using std::cout;           \n  using std::cerr;           \n  using std::string;         \n  using std::ifstream;       \n  using std::remove;         \n};\n\nusing namespace stl;\n\n\n\nusing Mode = ftp::Connection::Mode;\nMode PASV  = Mode::PASSIVE;\nMode PORT  = Mode::PORT;\n\n\nusing TransferMode  = ftp::Connection::TransferMode;\nTransferMode BINARY = TransferMode::BINARY;\nTransferMode TEXT   = TransferMode::TEXT;\n\n\n \n\nstruct session\n{\n  const string server;  \n  const string port;    \n  const string user;    \n  const string pass;    \n  Mode  mode;           \n  TransferMode txmode;  \n  string dir;           \n};\n\n \n\n\nftp::Connection connect_ftp( const session& sess);\nsize_t get_ftp( ftp::Connection& conn, string const& path);\nstring readFile( const string& filename);\nstring login_ftp(ftp::Connection& conn, const session& sess);\nstring dir_listing( ftp::Connection& conn, const string& path);\n\n\n \n\n\nstring readFile( const string& filename)\n{\n  struct stat stat_buf;  \n  string contents;\n  \n  errno = 0;\n  if (stat(filename.c_str() , &stat_buf) != -1) \n    {  \n      size_t len = stat_buf.st_size;            \n  \n      string bytes(len+1, '\\0');                \n      \n      ifstream ifs(filename); \n\n      ifs.read(&bytes[0], len);  \n\n      if (! ifs.fail() ) contents.swap(bytes);  \n\n      ifs.close();\n   }\n  else\n    {\n      cerr << \"stat error: \" << strerror(errno);\n    }\n\n  return contents;     \n}\n\n \n\n\nftp::Connection connect_ftp( const session& sess)\n  try\n    {\n      string constr = sess.server + \":\" + sess.port;\n      \n      cerr << \"connecting to \" << constr << \" ...\\n\";\n\n      ftp::Connection conn{ constr.c_str() };\n      \n      cerr << \"connected to \" << constr << \"\\n\";\n      conn.setConnectionMode(sess.mode);\n\n      return conn; \n   }\n  catch (ftp::ConnectException e) \n    {\n      cerr << \"FTP error: could not connect to server\" << \"\\n\";\n    }\n\n  \n\n\nstring login_ftp(ftp::Connection& conn, const session& sess)\n{\n  conn.login(sess.user.c_str() , sess.pass.c_str() );\n\n  return conn.getLastResponse();\n}\n\n \n\n\n    \n    \n\nstring dir_listing( ftp::Connection& conn, const string& path)\ntry\n  {\n      \n      const char* dirdata = \"/dev/shm/dirdata\";\n      \n      conn.getList(dirdata, path.c_str() ); \n      \n      \n      \n      string dir_string = readFile(dirdata);\n\n      cerr << conn.getLastResponse() << \"\\n\";\n      \n      errno = 0;\n      if ( remove(dirdata) != 0 ) \n      \t{\n\t  cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      \t}\n      \n      return dir_string;\n  }\n catch (...) {\n    cerr << \"error: getting dir contents: \\n\" \n\t << strerror(errno) << \"\\n\";\n  }\n\n \n\n\nsize_t get_ftp( ftp::Connection& conn, const string& r_path)\n{\n  size_t received = 0;\n\n  const char* path = r_path.c_str();\n\n  unsigned remotefile_size = conn.size(path , BINARY);\n \n  const char* localfile = basename(path);\n  \n  conn.get(localfile, path, BINARY);  \n\n  cerr << conn.getLastResponse() << \"\\n\";\n\n  \n  struct stat stat_buf;\n\n  errno = 0;\n  if (stat(localfile, &stat_buf) != -1)\n     received = stat_buf.st_size;   \n  else\n    cerr << strerror(errno);\n\n  return received;\n}\n\n \n\nconst session sonic\n{ \n    \"mirrors.sonic.net\", \n    \"21\" ,\n    \"anonymous\", \n    \"xxxx@nohost.org\",\n    PASV, \n    BINARY,\n    \"/pub/OpenBSD\" \n    };\n\n\n\n\nint main(int argc, char* argv[], char * env[] )\n{\n  const session remote = sonic;  \n\n  try\n    {\n           \n      \n      ftp::Connection conn = connect_ftp(remote);\n\n      \n      cerr << login_ftp(conn, remote);\n\n      \n      cout << \"System type: \" << conn.getSystemType() << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      conn.cd(remote.dir.c_str());  \n      cerr << conn.getLastResponse() << \"\\n\";\n\n      \n      string pwdstr = conn.getDirectory();\n      cout << \"PWD: \" << pwdstr << \"\\n\";\n      cerr << conn.getLastResponse() << \"\\n\";\n\n\n      \n      string dirlist = dir_listing(conn, pwdstr.c_str() );\n      cout << dirlist << \"\\n\";\n      \n      string filename = \"ftplist\";       \n\n      auto pos = dirlist.find(filename); \n\n      auto notfound = string::npos;   \n\n      if (pos != notfound)  \n\t{\n\t  \n\t  size_t received = get_ftp(conn, filename.c_str() );\n\n\t  if (received == 0) \n\t    cerr << \"got 0 bytes\\n\";\n\t  else\n\t    cerr << \"got \" << filename  \n\t\t << \" (\"   << received << \" bytes)\\n\";\n\t}\n      else\n\t{\n\t  cerr << \"file \" << filename \n\t       << \"not found on server. \\n\"; \n\t}\n      \n    }\n    catch (ftp::ConnectException e) \n      {\n        cerr << \"FTP error: could not connect to server\" << \"\\n\";\n      }\n    catch (ftp::Exception e) \n      {\n        cerr << \"FTP error: \" << e << \"\\n\";\n      }\n    catch (...) \n      {\n        cerr << \"error: \" <<  strerror(errno) << \"\\n\";\n      }\n\n  \n\n  return 0;\n}\n\n"}
{"id": 56971, "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 <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 56972, "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 <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 56973, "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   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 56974, "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++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 56975, "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++": "#ifndef MYWIDGET_H\n#define MYWIDGET_H\n#include <QWidget>\n\nclass QPaintEvent ;\n\nclass MyWidget : public QWidget {\npublic :\n   MyWidget( ) ;\n\nprotected :\n   void paintEvent( QPaintEvent * ) ;\nprivate :\n   int width ;\n   int height ;\n   const int colornumber ;\n} ;\n#endif\n"}
{"id": 56976, "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 <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\n}\n"}
{"id": 56977, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 56978, "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", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 56979, "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", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 56980, "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", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 56981, "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", "C++": "#include <algorithm>\n#include <cctype>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n    const size_t n1 = str.length();\n    const size_t n2 = suffix.length();\n    if (n1 < n2)\n        return false;\n    return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n        [](char c1, char c2) {\n            return std::tolower(static_cast<unsigned char>(c1))\n                == std::tolower(static_cast<unsigned char>(c2));\n    });\n}\n\nbool filenameHasExtension(const std::string& filename,\n                          const std::vector<std::string>& extensions) {\n    return std::any_of(extensions.begin(), extensions.end(),\n        [&filename](const std::string& extension) {\n            return endsWithIgnoreCase(filename, \".\" + extension);\n    });\n}\n\nvoid test(const std::string& filename,\n          const std::vector<std::string>& extensions) {\n    std::cout << std::setw(20) << std::left << filename\n        << \": \" << std::boolalpha\n        << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n    const std::vector<std::string> extensions{\"zip\", \"rar\", \"7z\",\n        \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n    test(\"MyData.a##\", extensions);\n    test(\"MyData.tar.Gz\", extensions);\n    test(\"MyData.gzip\", extensions);\n    test(\"MyData.7z.backup\", extensions);\n    test(\"MyData...\", extensions);\n    test(\"MyData\", extensions);\n    test(\"MyData_v1.0.tar.bz2\", extensions);\n    test(\"MyData_v1.0.bz2\", extensions);\n    return 0;\n}\n"}
{"id": 56982, "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", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 56983, "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", "C++": "#include <iostream>\n#include <ratio>\n#include <array>\n#include <algorithm>\n#include <random>\n\ntypedef short int Digit;  \n\nconstexpr Digit nDigits{4};      \nconstexpr Digit maximumDigit{9}; \nconstexpr short int gameGoal{24};    \n\ntypedef std::array<Digit, nDigits> digitSet; \ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};\n\t\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\n\t\tdo {\n\t\t\t\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) / \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" + \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" / \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) / \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) / \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) / ( \", \" - \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" / \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" / ( \", \" * \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" / ( \", \" - \", \" / \", \" )\");\n\t\t\t\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" / \", \" ) / \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \n\t}\n\treturn 0;\n}\n"}
{"id": 56984, "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", "C++": "#include <iostream>\n#include <chrono>\n#include <atomic>\n#include <mutex>\n#include <random>\n#include <thread>\n\nstd::mutex cout_lock;\n\nclass Latch\n{\n    std::atomic<int> semafor;\n  public:\n    Latch(int limit) : semafor(limit) {}\n\n    void wait()\n    {\n        semafor.fetch_sub(1);\n        while(semafor.load() > 0)\n            std::this_thread::yield();\n    }\n};\n\nstruct Worker\n{\n    static void do_work(int how_long, Latch& barrier, std::string name)\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(how_long));\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished work\\n\";   }\n        barrier.wait();\n        {   std::lock_guard<std::mutex> lock(cout_lock);\n            std::cout << \"Worker \" << name << \" finished assembly\\n\";   }\n    }\n};\n\nint main()\n{\n    Latch latch(5);\n    std::mt19937 rng(std::random_device{}());\n    std::uniform_int_distribution<> dist(300, 3000);\n    std::thread threads[] {\n        std::thread(&Worker::do_work, dist(rng), std::ref(latch), \"John\"),\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Henry\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Smith\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Jane\"},\n        std::thread{&Worker::do_work, dist(rng), std::ref(latch), \"Mary\"},\n    };\n    for(auto& t: threads) t.join();\n    std::cout << \"Assembly is finished\";\n}\n"}
{"id": 56985, "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", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n"}
{"id": 56986, "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", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\nusing namespace std;\n\nclass recorder\n{\npublic:\n    void start()\n    {\n\tpaused = rec = false; action = \"IDLE\";\n\twhile( true )\n\t{\n\t    cout << endl << \"==\" << action << \"==\" << endl << endl;\n\t    cout << \"1) Record\" << endl << \"2) Play\" << endl << \"3) Pause\" << endl << \"4) Stop\" << endl << \"5) Quit\" << endl;\n\t    char c; cin >> c;\n\t    if( c > '0' && c < '6' )\n\t    {\n\t\tswitch( c )\n\t\t{\n\t\t    case '1': record(); break;\n\t\t    case '2': play();   break;\n\t\t    case '3': pause();  break;\n\t\t    case '4': stop();   break;\n\t\t    case '5': stop();   return;\n\t\t}\n\t    }\n\t}\n    }\nprivate:\n    void record()\n    {\n\tif( mciExecute( \"open new type waveaudio alias my_sound\") )\n\t{ \n\t    mciExecute( \"record my_sound\" ); \n\t    action = \"RECORDING\"; rec = true; \n\t}\n    }\n    void play()\n    {\n\tif( paused )\n\t    mciExecute( \"play my_sound\" );\n\telse\n\t    if( mciExecute( \"open tmp.wav alias my_sound\" ) )\n\t\tmciExecute( \"play my_sound\" );\n\n\taction = \"PLAYING\";\n\tpaused = false;\n    }\n    void pause()\n    {\n\tif( rec ) return;\n\tmciExecute( \"pause my_sound\" );\n\tpaused = true; action = \"PAUSED\";\n    }\n    void stop()\n    {\n\tif( rec )\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"save my_sound tmp.wav\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\"; rec = false;\n\t}\n\telse\n\t{\n\t    mciExecute( \"stop my_sound\" );\n\t    mciExecute( \"close my_sound\" );\n\t    action = \"IDLE\";\n\t}\n    }\n    bool mciExecute( string cmd )\n    {\n\tif( mciSendString( cmd.c_str(), NULL, 0, NULL ) )\n\t{\n\t    cout << \"Can't do this: \" << cmd << endl;\n\t    return false;\n\t}\n\treturn true;\n    }\n\n    bool paused, rec;\n    string action;\n};\n\nint main( int argc, char* argv[] )\n{\n    recorder r; r.start();\n    return 0;\n}\n"}
{"id": 56987, "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", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <openssl/sha.h>\n\nclass sha256_exception : public std::exception {\npublic:\n    const char* what() const noexcept override {\n        return \"SHA-256 error\";\n    }\n};\n\nclass sha256 {\npublic:\n    sha256() { reset(); }\n    sha256(const sha256&) = delete;\n    sha256& operator=(const sha256&) = delete;\n    void reset() {\n        if (SHA256_Init(&context_) == 0)\n            throw sha256_exception();\n    }\n    void update(const void* data, size_t length) {\n        if (SHA256_Update(&context_, data, length) == 0)\n            throw sha256_exception();\n    }\n    std::vector<unsigned char> digest() {\n        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);\n        if (SHA256_Final(digest.data(), &context_) == 0)\n            throw sha256_exception();\n        return digest;\n    }\nprivate:\n    SHA256_CTX context_;\n};\n\nstd::string digest_to_string(const std::vector<unsigned char>& digest) {\n    std::ostringstream out;\n    out << std::hex << std::setfill('0');\n    for (size_t i = 0; i < digest.size(); ++i)\n        out << std::setw(2) << static_cast<int>(digest[i]);\n    return out.str();\n}\n\nstd::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {\n    std::vector<std::vector<unsigned char>> hashes;\n    std::vector<char> buffer(block_size);\n    sha256 md;\n    while (in) {\n        in.read(buffer.data(), block_size);\n        size_t bytes = in.gcount();\n        if (bytes == 0)\n            break;\n        md.reset();\n        md.update(buffer.data(), bytes);\n        hashes.push_back(md.digest());\n    }\n    if (hashes.empty())\n        return {};\n    size_t length = hashes.size();\n    while (length > 1) {\n        size_t j = 0;\n        for (size_t i = 0; i < length; i += 2, ++j) {\n            auto& digest1 = hashes[i];\n            auto& digest_out = hashes[j];\n            if (i + 1 < length) {\n                auto& digest2 = hashes[i + 1];\n                md.reset();\n                md.update(digest1.data(), digest1.size());\n                md.update(digest2.data(), digest2.size());\n                digest_out = md.digest();\n            } else {\n                digest_out = digest1;\n            }\n        }\n        length = j;\n    }\n    return hashes[0];\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1], std::ios::binary);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << \".\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\\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": 56988, "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", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 56989, "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", "C++": "#ifndef TASK_H\n#define TASK_H\n\n#include <QWidget>\n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n   Q_OBJECT \npublic :\n   EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n   QHBoxLayout *upperpart , *lowerpart ;\n   QVBoxLayout *entryLayout ;\n   QLineEdit *stringinput ;\n   QLineEdit *numberinput ;\n   QLabel *stringlabel ;\n   QLabel *numberlabel ;\n} ;\n\n#endif\n"}
{"id": 56990, "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", "C++": "#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(3*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i, j += 3) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dx = x1 - x0;\n        output[j] = {x0, y0};\n        if (y0 == y1) {\n            double d = dx * sqrt3_2/2;\n            if (d < 0) d = -d;\n            output[j + 1] = {x0 + dx/4, y0 - d};\n            output[j + 2] = {x1 - dx/4, y0 - d};\n        } else if (y1 < y0) {\n            output[j + 1] = {x1, y0};\n            output[j + 2] = {x1 + dx/2, (y0 + y1)/2};\n        } else {\n            output[j + 1] = {x0 - dx/2, (y0 + y1)/2};\n            output[j + 2] = {x0, y1};\n        }\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nvoid write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    const double x = margin;\n    const double y = 0.5 * size + 0.5 * sqrt3_2 * side;\n    std::vector<point> points{{x, y}, {x + side, y}};\n    for (int i = 0; i < iterations; ++i)\n        points = sierpinski_arrowhead_next(points);\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_arrowhead.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 56991, "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", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n"}
{"id": 56992, "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", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 56993, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 56994, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 56995, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 56996, "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", "C++": "#include <string>\n#include <iostream>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <cstdlib>\n#include <locale>\n\n\nint main( ) {\n   std::string datestring (\"March 7 2009 7:30pm EST\" ) ;\n   \n   \n   \n   std::vector<std::string> elements ;\n   \n   boost::split( elements , datestring , boost::is_any_of( \" \" ) ) ;\n   std::string datepart = elements[ 0 ] + \" \" + \"0\" + elements[ 1 ] + \" \" +\n      elements[ 2 ] ; \n   std::string timepart = elements[ 3 ] ;\n   std::string timezone = elements[ 4 ] ;\n   const char meridians[ ] = { 'a' , 'p' } ;\n   \n   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;\n   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;\n   timepart = timepart.substr( 0 , found ) ; \n   elements.clear( ) ;\n   boost::split( elements , timepart , boost::is_any_of ( \":\" ) ) ;\n   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;\n   if ( twelve_hour == \"p\" ) \n      hour += 12 ;\n   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; \n   boost::local_time::tz_database tz_db ;\n   tz_db.load_from_file( \"/home/ulrich/internetpages/date_time_zonespec.csv\" ) ;\n   \n   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( \"America/New_York\" ) ;\n   \n   boost::gregorian::date_input_facet *f =\n      new boost::gregorian::date_input_facet( \"%B %d %Y\"  ) ;\n   std::stringstream ss ;\n   ss << datepart ;\n   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;\n   boost::gregorian::date d ;\n   ss >> d ;\n   boost::posix_time::time_duration td (  hour , minute , 0  ) ;\n   \n   \n   boost::local_time::local_date_time lt ( d , td ,  dyc ,\n\t boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;\n   std::cout << \"local time: \" << lt << '\\n' ;\n   ss.str( \"\" ) ;\n   ss << lt ;\n   \n   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;\n   boost::local_time::local_date_time ltlater = lt + td2 ; \n   boost::gregorian::date_facet *f2 =\n      new boost::gregorian::date_facet( \"%B %d %Y , %R %Z\" ) ;\n   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;\n   std::cout << \"12 hours after \" << ss.str( )  << \" it is \" << ltlater << \" !\\n\" ;\n   \n   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( \"Europe/Berlin\" ) ;\n   std::cout.imbue( std::locale( \"de_DE.UTF-8\" ) ) ; \n   std::cout << \"This corresponds to \" << ltlater.local_time_in( bt ) << \" in Berlin!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 56997, "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", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 56998, "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", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 56999, "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", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 57000, "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", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 57001, "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", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 57002, "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", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 57003, "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", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57004, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 57005, "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", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n"}
{"id": 57006, "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", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n"}
{"id": 57007, "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", "C++": "#include <iostream>\n#include <time.h>\n\n\nusing namespace std;\n\n\nclass stooge\n{\npublic:\n    void sort( int* arr, int start, int end )\n    {\n        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );\n\tint n = end - start; if( n > 2 )\n\t{\n\t    n /= 3; sort( arr, start, end - n );\n\t    sort( arr, start + n, end ); sort( arr, start, end - n );\n        }\n    }\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; \n    cout << \"before:\\n\";\n    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << \" \"; }\n    s.sort( a, 0, m ); cout << \"\\n\\nafter:\\n\"; \n    for( int x = 0; x < m; x++ ) cout << a[x] << \" \"; cout << \"\\n\\n\"; \n    return system( \"pause\" );\n}\n"}
{"id": 57008, "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", "C++": "#include \"stdafx.h\"\n#include <windows.h>\n#include <stdlib.h>\n\nconst int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\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};\nclass point {\npublic:\n    int x; float y;\n    void set( int a, float b ) { x = a; y = b; }\n};\ntypedef struct {\n    point position, offset;\n    bool alive, start;\n}ball;\nclass galton {\npublic :\n    galton() {\n        bmp.create( BMP_WID, BMP_HEI );\n        initialize();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n    void simulate() {\n        draw(); update(); Sleep( 1 );\n    }\nprivate:\n    void draw() {\n        bmp.clear();\n        bmp.setPenColor( RGB( 0, 255, 0 ) );\n        bmp.setBrushColor( RGB( 0, 255, 0 ) );\n        int xx, yy;\n        for( int y = 3; y < 14; y++ ) {\n            yy = 10 * y;\n            for( int x = 0; x < 41; x++ ) {\n                xx = 10 * x;\n                if( pins[y][x] )\n                    Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );\n            }\n        }\n        bmp.setPenColor( RGB( 255, 0, 0 ) );\n        bmp.setBrushColor( RGB( 255, 0, 0 ) );\n        ball* b; \n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive )\n                Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), \n                                        static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );\n        }\n        for( int x = 0; x < 70; x++ ) {\n            if( cols[x] > 0 ) {\n                xx = 10 * x;\n                Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );\n            }\n        }\n        HDC dc = GetDC( _hwnd );\n        BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, dc );\n    }\n    void update() {\n        ball* b;\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            b = &balls[x];\n            if( b->alive ) {\n                b->position.x += b->offset.x; b->position.y += b->offset.y;\n                if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {\n                    b->start = true;\n                    balls[x + 1].alive = true;\n                }\n                int c = ( int )b->position.x, d = ( int )b->position.y + 6;\n                if( d > 10 || d < 41 ) {\n                    if( pins[d / 10][c / 10] ) {\n                        if( rand() % 30 < 15 ) b->position.x -= 10;\n                        else b->position.x += 10;\n                    }\n                }\n                if( b->position.y > 160 ) {\n                    b->alive = false;\n                    cols[c / 10] += 1;\n                }\n            }\n        }\n    }\n    void initialize() {\n        for( int x = 0; x < MAX_BALLS; x++ ) {\n            balls[x].position.set( 200, -10 );\n            balls[x].offset.set( 0, 0.5f );\n            balls[x].alive = balls[x].start = false;\n        }\n        balls[0].alive = true;\n        for( int x = 0; x < 70; x++ )\n            cols[x] = 0;\n        for( int y = 0; y < 70; y++ )\n            for( int x = 0; x < 41; x++ )\n                pins[x][y] = false;\n        int p;\n        for( int y = 0; y < 11; y++ ) {\n            p = ( 41 / 2 ) - y;\n            for( int z = 0; z < y + 1; z++ ) {\n                pins[3 + y][p] = true;\n                p += 2;\n            }\n        }\n    }\n    myBitmap bmp;\n    HWND _hwnd;\n    bool pins[70][40];\n    ball balls[MAX_BALLS];\n    int cols[70];\n};\nclass wnd {\npublic:\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst;\n        _hwnd = InitAll();\n        _gtn.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            } else _gtn.simulate();\n        }\n        return UnregisterClass( \"_GALTON_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            default:\n                return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize           = sizeof( WNDCLASSEX );\n        wcex.style           = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_GALTON_\";\n        RegisterClassEx( &wcex );\n        RECT rc;\n        SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );\n        AdjustWindowRect( &rc, WS_CAPTION, FALSE );\n        return CreateWindow( \"_GALTON_\", \".: Galton Box -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );\n    }\n    HINSTANCE _hInst;\n    HWND      _hwnd;\n    galton    _gtn;\n};\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    srand( GetTickCount() );\n    wnd myWnd; \n    return myWnd.Run( hInstance );\n}\n"}
{"id": 57009, "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", "C++": "#include <iostream>\n\nint circlesort(int* arr, int lo, int hi, int swaps) {\n    if(lo == hi) {\n        return swaps;\n    }\n    int high = hi;\n    int low = lo;\n    int mid = (high - low) / 2;\n    while(lo < hi) {\n        if(arr[lo] > arr[hi]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi];\n            arr[hi] = temp;\n            swaps++;\n        }\n        lo++;\n        hi--;\n    }\n\n    if(lo == hi) {\n        if(arr[lo] > arr[hi+1]) {\n            int temp = arr[lo];\n            arr[lo] = arr[hi+1];\n            arr[hi+1] = temp;\n            swaps++;\n        }\n    }\n    swaps = circlesort(arr, low, low+mid, swaps);\n    swaps = circlesort(arr, low+mid+1, high, swaps);\n    return swaps;\n}\n\nvoid circlesortDriver(int* arr, int n) {\n    do {\n        for(int i = 0; i < n; i++) {\n            std::cout << arr[i] << ' ';\n        }\n        std::cout << std::endl;\n    } while(circlesort(arr, 0, n-1, 0));\n}\n\nint main() {\n    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };\n    circlesortDriver(arr, sizeof(arr)/sizeof(int));\n    return 0;\n}\n"}
{"id": 57010, "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", "C++": "#include <cassert>\n#include <vector>\n\n#include <QImage>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\n\ntemplate <typename scalar_type>\nmatrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,\n                                      const matrix<scalar_type>& b) {\n    size_t arows = a.rows();\n    size_t acolumns = a.columns();\n    size_t brows = b.rows();\n    size_t bcolumns = b.columns();\n    matrix<scalar_type> c(arows * brows, acolumns * bcolumns);\n    for (size_t i = 0; i < arows; ++i)\n        for (size_t j = 0; j < acolumns; ++j)\n            for (size_t k = 0; k < brows; ++k)\n                for (size_t l = 0; l < bcolumns; ++l)\n                    c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);\n    return c;\n}\n\nbool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {\n    matrix<unsigned char> result = m;\n    for (int i = 0; i < order; ++i)\n        result = kronecker_product(result, m);\n\n    size_t height = result.rows();\n    size_t width = result.columns();\n    size_t bytesPerLine = 4 * ((width + 3)/4);\n    std::vector<uchar> imageData(bytesPerLine * height);\n\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j)\n            imageData[i * bytesPerLine + j] = result(i, j);\n\n    QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);\n    QVector<QRgb> colours(2);\n    colours[0] = qRgb(0, 0, 0);\n    colours[1] = qRgb(255, 255, 255);\n    image.setColorTable(colours);\n    return image.save(fileName);\n}\n\nint main() {\n    matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});\n    matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});\n    matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});\n    kronecker_fractal(\"vicsek.png\", matrix1, 5);\n    kronecker_fractal(\"sierpinski_carpet.png\", matrix2, 5);\n    kronecker_fractal(\"sierpinski_triangle.png\", matrix3, 8);\n    return 0;\n}\n"}
{"id": 57011, "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", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 57012, "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", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 57013, "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", "C++": "#include <cstdint>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_prime(const integer& n, int reps = 50) {\n    return mpz_probab_prime_p(n.get_mpz_t(), reps);\n}\n\nstd::string to_string(const integer& n) {\n    std::ostringstream out;\n    out << n;\n    return out.str();\n}\n\nbool is_circular_prime(const integer& p) {\n    if (!is_prime(p))\n        return false;\n    std::string str(to_string(p));\n    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {\n        std::rotate(str.begin(), str.begin() + 1, str.end());\n        integer p2(str, 10);\n        if (p2 < p || !is_prime(p2))\n            return false;\n    }\n    return true;\n}\n\ninteger next_repunit(const integer& n) {\n    integer p = 1;\n    while (p < n)\n        p = 10 * p + 1;\n    return p;\n}\n\ninteger repunit(int digits) {\n    std::string str(digits, '1');\n    integer p(str);\n    return p;\n}\n\nvoid test_repunit(int digits) {\n    if (is_prime(repunit(digits), 10))\n        std::cout << \"R(\" << digits << \") is probably prime\\n\";\n    else\n        std::cout << \"R(\" << digits << \") is not prime\\n\";\n}\n\nint main() {\n    integer p = 2;\n    std::cout << \"First 19 circular primes:\\n\";\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    std::cout << \"Next 4 circular primes:\\n\";\n    p = next_repunit(p);\n    std::string str(to_string(p));\n    int digits = str.size();\n    for (int count = 0; count < 4; ) {\n        if (is_prime(p, 15)) {\n            if (count > 0)\n                std::cout << \", \";\n            std::cout << \"R(\" << digits << \")\";\n            ++count;\n        }\n        p = repunit(++digits);\n    }\n    std::cout << '\\n';\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 57014, "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", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n"}
{"id": 57015, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n\nclass radix_test\n{\n    const int bit; \npublic:\n    radix_test(int offset) : bit(offset) {} \n\n    bool operator()(int value) const \n    {\n        if (bit == 31) \n            return value < 0; \n        else\n            return !(value & (1 << bit)); \n    }\n};\n\n\nvoid lsd_radix_sort(int *first, int *last)\n{\n    for (int lsb = 0; lsb < 32; ++lsb) \n    {\n        std::stable_partition(first, last, radix_test(lsb));\n    }\n}\n\n\nvoid msd_radix_sort(int *first, int *last, int msb = 31)\n{\n    if (first != last && msb >= 0)\n    {\n        int *mid = std::partition(first, last, radix_test(msb));\n        msb--; \n        msd_radix_sort(first, mid, msb); \n        msd_radix_sort(mid, last, msb); \n    }\n}\n\n\nint main()\n{\n    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n    lsd_radix_sort(data, data + 8);\n    \n\n    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, \" \"));\n\n    return 0;\n}\n"}
{"id": 57016, "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", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n"}
{"id": 57017, "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", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 57018, "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", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 57019, "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", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint jacobi(int n, int k) {\n    assert(k > 0 && k % 2 == 1);\n    n %= k;\n    int t = 1;\n    while (n != 0) {\n        while (n % 2 == 0) {\n            n /= 2;\n            int r = k % 8;\n            if (r == 3 || r == 5)\n                t = -t;\n        }\n        std::swap(n, k);\n        if (n % 4 == 3 && k % 4 == 3)\n            t = -t;\n        n %= k;\n    }\n    return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n    out << \"n\\\\k|\";\n    for (int k = 0; k <= kmax; ++k)\n        out << ' ' << std::setw(2) << k;\n    out << \"\\n----\";\n    for (int k = 0; k <= kmax; ++k)\n        out << \"---\";\n    out << '\\n';\n    for (int n = 1; n <= nmax; n += 2) {\n        out << std::setw(2) << n << \" |\";\n        for (int k = 0; k <= kmax; ++k)\n            out << ' ' << std::setw(2) << jacobi(k, n);\n        out << '\\n';\n    }\n}\n\nint main() {\n    print_table(std::cout, 20, 21);\n    return 0;\n}\n"}
{"id": 57020, "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", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57021, "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", "C++": "#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass point {\npublic:\n    point(std::array<coordinate_type, dimensions> c) : coords_(c) {}\n    point(std::initializer_list<coordinate_type> list) {\n        size_t n = std::min(dimensions, list.size());\n        std::copy_n(list.begin(), n, coords_.begin());\n    }\n    \n    coordinate_type get(size_t index) const {\n        return coords_[index];\n    }\n    \n    double distance(const point& pt) const {\n        double dist = 0;\n        for (size_t i = 0; i < dimensions; ++i) {\n            double d = get(i) - pt.get(i);\n            dist += d * d;\n        }\n        return dist;\n    }\nprivate:\n    std::array<coordinate_type, dimensions> coords_;\n};\n\ntemplate<typename coordinate_type, size_t dimensions>\nstd::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {\n    out << '(';\n    for (size_t i = 0; i < dimensions; ++i) {\n        if (i > 0)\n            out << \", \";\n        out << pt.get(i);\n    }\n    out << ')';\n    return out;\n}\n\n\ntemplate<typename coordinate_type, size_t dimensions>\nclass kdtree {\npublic:\n    typedef point<coordinate_type, dimensions> point_type;\nprivate:\n    struct node {\n        node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n        coordinate_type get(size_t index) const {\n            return point_.get(index);\n        }\n        double distance(const point_type& pt) const {\n            return point_.distance(pt);\n        }\n        point_type point_;\n        node* left_;\n        node* right_;\n    };\n    node* root_ = nullptr;\n    node* best_ = nullptr;\n    double best_dist_ = 0;\n    size_t visited_ = 0;\n    std::vector<node> nodes_;\n\n    struct node_cmp {\n        node_cmp(size_t index) : index_(index) {}\n        bool operator()(const node& n1, const node& n2) const {\n            return n1.point_.get(index_) < n2.point_.get(index_);\n        }\n        size_t index_;\n    };\n\n    node* make_tree(size_t begin, size_t end, size_t index) {\n        if (end <= begin)\n            return nullptr;\n        size_t n = begin + (end - begin)/2;\n        auto i = nodes_.begin();\n        std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n        index = (index + 1) % dimensions;\n        nodes_[n].left_ = make_tree(begin, n, index);\n        nodes_[n].right_ = make_tree(n + 1, end, index);\n        return &nodes_[n];\n    }\n\n    void nearest(node* root, const point_type& point, size_t index) {\n        if (root == nullptr)\n            return;\n        ++visited_;\n        double d = root->distance(point);\n        if (best_ == nullptr || d < best_dist_) {\n            best_dist_ = d;\n            best_ = root;\n        }\n        if (best_dist_ == 0)\n            return;\n        double dx = root->get(index) - point.get(index);\n        index = (index + 1) % dimensions;\n        nearest(dx > 0 ? root->left_ : root->right_, point, index);\n        if (dx * dx >= best_dist_)\n            return;\n        nearest(dx > 0 ? root->right_ : root->left_, point, index);\n    }\npublic:\n    kdtree(const kdtree&) = delete;\n    kdtree& operator=(const kdtree&) = delete;\n    \n    template<typename iterator>\n    kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n    \n    \n    template<typename func>\n    kdtree(func&& f, size_t n) {\n        nodes_.reserve(n);\n        for (size_t i = 0; i < n; ++i)\n            nodes_.push_back(f());\n        root_ = make_tree(0, nodes_.size(), 0);\n    }\n\n    \n    bool empty() const { return nodes_.empty(); }\n\n    \n    size_t visited() const { return visited_; }\n\n    \n    double distance() const { return std::sqrt(best_dist_); }\n\n    \n    const point_type& nearest(const point_type& pt) {\n        if (root_ == nullptr)\n            throw std::logic_error(\"tree is empty\");\n        best_ = nullptr;\n        visited_ = 0;\n        best_dist_ = 0;\n        nearest(root_, pt, 0);\n        return best_->point_;\n    }\n};\n\nvoid test_wikipedia() {\n    typedef point<int, 2> point2d;\n    typedef kdtree<int, 2> tree2d;\n\n    point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n    tree2d tree(std::begin(points), std::end(points));\n    point2d n = tree.nearest({ 9, 2 });\n\n    std::cout << \"Wikipedia example data:\\n\";\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point<double, 3> point3d;\ntypedef kdtree<double, 3> tree3d;\n\nstruct random_point_generator {\n    random_point_generator(double min, double max)\n        : engine_(std::random_device()()), distribution_(min, max) {}\n\n    point3d operator()() {\n        double x = distribution_(engine_);\n        double y = distribution_(engine_);\n        double z = distribution_(engine_);\n        return point3d({x, y, z});\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<double> distribution_;\n};\n\nvoid test_random(size_t count) {\n    random_point_generator rpg(0, 1);\n    tree3d tree(rpg, count);\n    point3d pt(rpg());\n    point3d n = tree.nearest(pt);\n\n    std::cout << \"Random data (\" << count << \" points):\\n\";\n    std::cout << \"point: \" << pt << '\\n';\n    std::cout << \"nearest point: \" << n << '\\n';\n    std::cout << \"distance: \" << tree.distance() << '\\n';\n    std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n    try {\n        test_wikipedia();\n        std::cout << '\\n';\n        test_random(1000);\n        std::cout << '\\n';\n        test_random(1000000);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57022, "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", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 57023, "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", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 57024, "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", "C++": "#include <stdexcept>\n\ntemplate <typename Self>\nclass singleton\n{\nprotected:\n\tstatic Self*\n\t\tsentry;\npublic:\t\n\tstatic Self& \n\t\tinstance()\n\t{\n\t\treturn *sentry;\n\t}\n\tsingleton()\n\t{\n\t\tif(sentry)\n\t\t\tthrow std::logic_error(\"Error: attempt to instantiate a singleton over a pre-existing one!\");\n\t\tsentry = (Self*)this;\n\t}\n\tvirtual ~singleton()\n\t{\n\t\tif(sentry == this)\n\t\t\tsentry = 0;\n\t}\n};\ntemplate <typename Self>\nSelf* \n\tsingleton<Self>::sentry = 0;\n\n\n\n#include <iostream>\n#include <string>\n\nusing namespace \n\tstd;\n\nclass controller : public singleton<controller>\n{\npublic:\n\tcontroller(string const& name)\n\t: name(name)\n\t{\n\t\ttrace(\"begin\");\n\t}\n\t~controller()\n\t{\n\t\ttrace(\"end\");\n\t}\n\tvoid\n\t\twork()\n\t{\n\t\ttrace(\"doing stuff\");\n\t}\n\tvoid\n\t\ttrace(string const& message)\n\t{\n\t\tcout << name << \": \" << message << endl;\n\t}\n\tstring\n\t\tname;\n};\nint\n\tmain()\n{\n\tcontroller*\n\t\tfirst = new controller(\"first\");\n\tcontroller::instance().work();\n\tdelete first;\n\t\n\tcontroller\n\t\tsecond(\"second\");\n\tcontroller::instance().work();\n\ttry\n\t{\n\t\n\t\tcontroller\n\t\t\tgoner(\"goner\");\n\t\tcontroller::instance().work();\n\t}\n\tcatch(exception const& error)\n\t{\n\t\tcout << error.what() << endl; \n\t}\n\tcontroller::instance().work();\n\n\tcontroller\n\t\tgoner(\"goner\");\n\tcontroller::instance().work();\n}\n"}
{"id": 57025, "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", "C++": "#include <iostream>\n#include <tuple>\n\nunion conv {\n    int i;\n    float f;\n};\n\nfloat nextUp(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i++;\n\n    return c.f;\n}\n\nfloat nextDown(float d) {\n    if (isnan(d) || d == -INFINITY || d == INFINITY) return d;\n    if (d == 0.0) return -FLT_EPSILON;\n\n    conv c;\n    c.f = d;\n    c.i--;\n\n    return c.f;\n}\n\nauto safeAdd(float a, float b) {\n    return std::make_tuple(nextDown(a + b), nextUp(a + b));\n}\n\nint main() {\n    float a = 1.20f;\n    float b = 0.03f;\n\n    auto result = safeAdd(a, b);\n    printf(\"(%f + %f) is in the range (%0.16f, %0.16f)\\n\", a, b, std::get<0>(result), std::get<1>(result));\n\n    return 0;\n}\n"}
{"id": 57026, "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", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n"}
{"id": 57027, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 57028, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 57029, "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", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 57030, "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", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 57031, "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", "C++": "#include <iostream>\n#include <cstdint>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\n\n\nclass palindrome_generator {\npublic:\n    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n        digit_(digit), even_(false) {}\n    integer next_palindrome() {\n        ++next_;\n        if (next_ == power_ * (digit_ + 1)) {\n            if (even_)\n                power_ *= 10;\n            next_ = digit_ * power_;\n            even_ = !even_;\n        }\n        return next_ * (even_ ? 10 * power_ : power_)\n            + reverse(even_ ? next_ : next_/10);\n    }\nprivate:\n    integer power_;\n    integer next_;\n    int digit_;\n    bool even_;\n};\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate<size_t len>\nvoid print(integer (&array)[9][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        std::cout << digit << \":\";\n        for (int i = 0; i < len; ++i)\n            std::cout << ' ' << array[digit - 1][i];\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palindrome_generator pgen(digit);\n        for (int i = 0; i < m2; ) {\n            integer n = pgen.next_palindrome();\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg1);\n\n    std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg2);\n\n    std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n    print(pg3);\n\n    return 0;\n}\n"}
{"id": 57032, "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", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 57033, "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", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 57034, "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", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 57035, "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", "C++": "#include <iostream>\n\nbool is_prime(int n) {\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    int i = 5;\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n\n    for (int p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 57036, "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", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 57037, "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", "C++": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\ntemplate<typename T>\nstd::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {\n    std::set<T> resultset;\n    std::vector<T> result;\n    for (auto& list : ll)\n        for (auto& item : list)\n            resultset.insert(item);\n    for (auto& item : resultset)\n        result.push_back(item);\n    \n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nint main() {\n    std::vector<int> a = {5,1,3,8,9,4,8,7};\n    std::vector<int> b = {3,5,9,8,4};\n    std::vector<int> c = {1,3,7,9};\n    std::vector<std::vector<int>> nums = {a, b, c};\n    \n    auto csl = common_sorted_list(nums);\n    for (auto n : csl) std::cout << n << \" \";\n    std::cout << std::endl;\n    \n    return 0;\n}\n"}
{"id": 57038, "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", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 57039, "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", "C++": "#include <windows.h>\n#include <string>\nusing namespace std;\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n        DeleteObject( pen );\n        DeleteDC( hdc );\n        DeleteObject( bmp );\n    }\n \n    bool create( int w, int h )\n    {\n        BITMAPINFO\tbi;\n        ZeroMemory( &bi, sizeof( bi ) );\n        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n        bi.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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\tclear();\n\treturn true;\n    }\n \n    void clear()\n    {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\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 fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD*\t\t dwpBits;\n\tDWORD\t\t wb;\n\tHANDLE\t\t file;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\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    void    *pBits;\n    int\t    width, height;\n};\nclass fiboFractal\n{\npublic:\n    fiboFractal( int l )\n    {\n\tbmp.create( 600, 440 );\n\tbmp.setPenColor( 0x00ff00 );\n\tcreateWord( l ); createFractal();\n\tbmp.saveBitmap( \"path_to_save_bitmap\" );\n    }\nprivate:\n    void createWord( int l )\n    {\n\tstring a = \"1\", b = \"0\", c;\n\tl -= 2;\n\twhile( l-- )\n\t{ c = b + a; a = b; b = c; }\n\tfWord = c;\n    }\n\n    void createFractal()\n    {\n\tint n = 1, px = 10, dir, \n\t    py = 420, len = 1, \n\t    x = 0, y = -len, goingTo = 0;\n\n\tHDC dc = bmp.getDC();\n\tMoveToEx( dc, px, py, NULL );\n\tfor( string::iterator si = fWord.begin(); si != fWord.end(); si++ )\n\t{\n\t    px += x; py += y;\n\t    LineTo( dc, px, py );\n\t    if( !( *si - 48 ) )\n\t    {\t\n\t\tif( n & 1 ) dir = 1;\t\n\t\telse dir = 0;\t\t\t\n\t\tswitch( goingTo )\n\t\t{\n\t\t    case 0: \n\t\t        y = 0;\n\t\t\tif( dir ){ x = len; goingTo = 1; }\n\t\t\telse { x = -len; goingTo = 3; }\n\t\t    break;\n\t\t    case 1: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = len; goingTo = 2; }\n\t\t\telse { y = -len; goingTo = 0; }\n\t\t    break;\n\t\t    case 2: \n\t\t\ty = 0;\n\t\t\tif( dir ) { x = -len; goingTo = 3; }\n\t\t\telse { x = len; goingTo = 1; }\n\t\t    break;\n\t\t    case 3: \n\t\t\tx = 0;\n\t\t\tif( dir ) { y = -len; goingTo = 0; }\n\t\t\telse { y = len; goingTo = 2; }\n\t\t}\n            }\n\t    n++;\n        }\n    }\n\n    string fWord;\n    myBitmap bmp;\n};\nint main( int argc, char* argv[] )\n{\n    fiboFractal ff( 23 );\n    return system( \"pause\" );\n}\n"}
{"id": 57040, "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", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n"}
{"id": 57041, "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", "C++": "\nclass fifteenSolver{\n  const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};\n  int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};\n  unsigned long N2[100]{};\n  const bool fY(){\n    if (N4[n]<_n) return fN();\n    if (N2[n]==0x123456789abcdef0) {std::cout<<\"Solution found in \"<<n<<\" moves :\"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};\n    if (N4[n]==_n) return fN(); else return false;\n  }\n  const bool                     fN(){\n    if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}\n    if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}\n    return false;\n  }\n  void fI(){\n    const int           g = (11-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);\n  } \n  void fG(){\n    const int           g = (19-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);\n  } \n  void fE(){\n    const int           g = (14-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);\n  } \n  void fL(){\n    const int           g = (16-N0[n])*4;\n    const unsigned long a = N2[n]&((unsigned long)15<<g);\n    N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);\n  }\npublic:\n  fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}\n  void Solve(){for(;not fY();++_n);}\n};\n"}
{"id": 57042, "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", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 57043, "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", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 57044, "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", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 57045, "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", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 57046, "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", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 57047, "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", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 57048, "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", "C++": "#include <cmath>\n#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\n\nunsigned int divisor_product(unsigned int n) {\n    return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));\n}\n\nint main() {\n    const unsigned int limit = 50;\n    std::cout << \"Product of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(11) << divisor_product(n);\n        if (n % 5 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 57049, "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", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 57050, "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", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 57051, "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", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 57052, "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", "C++": "#include <iostream>\n#include <tr1/memory>\nusing std::tr1::shared_ptr;\nusing std::tr1::enable_shared_from_this;\n\nstruct Arg {\n  virtual int run() = 0;\n  virtual ~Arg() { };\n};\n\nint A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,\n      shared_ptr<Arg>, shared_ptr<Arg>);\n\nclass B : public Arg, public enable_shared_from_this<B> {\nprivate:\n  int k;\n  const shared_ptr<Arg> x1, x2, x3, x4;\n\npublic:\n  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,\n    shared_ptr<Arg> _x4)\n    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }\n  int run() {\n    return A(--k, shared_from_this(), x1, x2, x3, x4);\n  }\n};\n\nclass Const : public Arg {\nprivate:\n  const int x;\npublic:\n  Const(int _x) : x(_x) { }\n  int run () { return x; }\n};\n\nint A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,\n      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {\n  if (k <= 0)\n    return x4->run() + x5->run();\n  else {\n    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));\n    return b->run();\n  }\n}\n\nint main() {\n  std::cout << A(10, shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(-1)),\n                 shared_ptr<Arg>(new Const(1)),\n                 shared_ptr<Arg>(new Const(0))) << std::endl;\n  return 0;\n}\n"}
{"id": 57053, "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", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n"}
{"id": 57054, "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", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 57055, "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", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 57056, "name": "Carmichael 3 strong pseudoprimes", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint mod(int n, int d) {\n    return (d + n % d) % d;\n}\n\nbool is_prime(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 (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\nvoid print_carmichael_numbers(int prime1) {\n    for (int h3 = 1; h3 < prime1; ++h3) {\n        for (int d = 1; d < h3 + prime1; ++d) {\n            if (mod((h3 + prime1) * (prime1 - 1), d) != 0\n                || mod(-prime1 * prime1, h3) != mod(d, h3))\n                continue;\n            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;\n            if (!is_prime(prime2))\n                continue;\n            int prime3 = 1 + prime1 * prime2/h3;\n            if (!is_prime(prime3))\n                continue;\n            if (mod(prime2 * prime3, prime1 - 1) != 1)\n                continue;\n            unsigned int c = prime1 * prime2 * prime3;\n            std::cout << std::setw(2) << prime1 << \" x \"\n                << std::setw(4) << prime2 << \" x \"\n                << std::setw(5) << prime3 << \" = \"\n                << std::setw(10) << c << '\\n';\n        }\n    }\n}\n\nint main() {\n    for (int p = 2; p <= 61; ++p) {\n        if (is_prime(p))\n            print_carmichael_numbers(p);\n    }\n    return 0;\n}\n"}
{"id": 57057, "name": "Arithmetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n"}
{"id": 57058, "name": "Arithmetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n"}
{"id": 57059, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 57060, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 57061, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 57062, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 57063, "name": "Conjugate transpose", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n"}
{"id": 57064, "name": "Conjugate transpose", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n", "C++": "#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class complex_matrix {\npublic:\n    using element_type = std::complex<scalar_type>;\n\n    complex_matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    complex_matrix(size_t rows, size_t columns, element_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    complex_matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<element_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const element_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    element_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n\n    friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n        return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n               a.elements_ == b.elements_;\n    }\n\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<element_type> elements_;\n};\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,\n                                    const complex_matrix<scalar_type>& b) {\n    assert(a.columns() == b.rows());\n    size_t arows = a.rows();\n    size_t bcolumns = b.columns();\n    size_t n = a.columns();\n    complex_matrix<scalar_type> c(arows, bcolumns);\n    for (size_t i = 0; i < arows; ++i) {\n        for (size_t j = 0; j < n; ++j) {\n            for (size_t k = 0; k < bcolumns; ++k)\n                c(i, k) += a(i, j) * b(j, k);\n        }\n    }\n    return c;\n}\n\ntemplate <typename scalar_type>\ncomplex_matrix<scalar_type>\nconjugate_transpose(const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    complex_matrix<scalar_type> b(columns, rows);\n    for (size_t i = 0; i < columns; i++) {\n        for (size_t j = 0; j < rows; j++) {\n            b(i, j) = std::conj(a(j, i));\n        }\n    }\n    return b;\n}\n\ntemplate <typename scalar_type>\nstd::string to_string(const std::complex<scalar_type>& c) {\n    std::ostringstream out;\n    const int precision = 6;\n    out << std::fixed << std::setprecision(precision);\n    out << std::setw(precision + 3) << c.real();\n    if (c.imag() > 0)\n        out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n    else if (c.imag() == 0)\n        out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n    else\n        out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n    return out.str();\n}\n\ntemplate <typename scalar_type>\nvoid print(std::ostream& out, const complex_matrix<scalar_type>& a) {\n    size_t rows = a.rows(), columns = a.columns();\n    for (size_t row = 0; row < rows; ++row) {\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << ' ';\n            out << to_string(a(row, column));\n        }\n        out << '\\n';\n    }\n}\n\ntemplate <typename scalar_type>\nbool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    return matrix == conjugate_transpose(matrix);\n}\n\ntemplate <typename scalar_type>\nbool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex<double>& a, double b) {\n    constexpr double e = 1e-15;\n    return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate <typename scalar_type>\nbool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    size_t rows = matrix.rows();\n    for (size_t i = 0; i < rows; ++i) {\n        for (size_t j = 0; j < rows; ++j) {\n            if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n                return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename scalar_type>\nbool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {\n    if (matrix.rows() != matrix.columns())\n        return false;\n    auto c = conjugate_transpose(matrix);\n    auto p = product(c, matrix);\n    return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate <typename scalar_type>\nvoid test(const complex_matrix<scalar_type>& matrix) {\n    std::cout << \"Matrix:\\n\";\n    print(std::cout, matrix);\n    std::cout << \"Conjugate transpose:\\n\";\n    print(std::cout, conjugate_transpose(matrix));\n    std::cout << std::boolalpha;\n    std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n    std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n    std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n    using matrix = complex_matrix<double>;\n\n    matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n                          {{2, -1}, {3, 0}, {0, 1}},\n                          {{4, 0}, {0, -1}, {1, 0}}});\n\n    double n = std::sqrt(0.5);\n    matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n                          {{0, -n}, {0, n}, {0, 0}},\n                          {{0, 0}, {0, 0}, {0, 1}}});\n\n    matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n                          {{2, -1}, {4, 1}, {0, 0}},\n                          {{7, -5}, {1, -4}, {1, 0}}});\n\n    test(matrix1);\n    std::cout << '\\n';\n    test(matrix2);\n    std::cout << '\\n';\n    test(matrix3);\n    return 0;\n}\n"}
{"id": 57065, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 57066, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 57067, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "C++": "#include <gmpxx.h>\n\n#include <iomanip>\n#include <iostream>\n\nusing big_int = mpz_class;\n\nbool is_probably_prime(const big_int& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;\n}\n\nbig_int jacobsthal_number(unsigned int n) {\n    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;\n}\n\nbig_int jacobsthal_lucas_number(unsigned int n) {\n    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);\n}\n\nbig_int jacobsthal_oblong_number(unsigned int n) {\n    return jacobsthal_number(n) * jacobsthal_number(n + 1);\n}\n\nint main() {\n    std::cout << \"First 30 Jacobsthal Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 30 Jacobsthal-Lucas Numbers:\\n\";\n    for (unsigned int n = 0; n < 30; ++n) {\n        std::cout << std::setw(9) << jacobsthal_lucas_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal oblong Numbers:\\n\";\n    for (unsigned int n = 0; n < 20; ++n) {\n        std::cout << std::setw(11) << jacobsthal_oblong_number(n)\n                  << ((n + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 20 Jacobsthal primes:\\n\";\n    for (unsigned int n = 0, count = 0; count < 20; ++n) {\n        auto jn = jacobsthal_number(n);\n        if (is_probably_prime(jn)) {\n            ++count;\n            std::cout << jn << '\\n';\n        }\n    }\n}\n"}
{"id": 57068, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n"}
{"id": 57069, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57070, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57071, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\ntemplate<typename T, size_t S>\nusing FixedSquareGrid = std::array<std::array<T, S>, S>;\n\nstruct Cistercian {\npublic:\n    Cistercian() {\n        initN();\n    }\n\n    Cistercian(int v) {\n        initN();\n        draw(v);\n    }\n\n    Cistercian &operator=(int v) {\n        initN();\n        draw(v);\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n    FixedSquareGrid<char, 15> canvas;\n\n    void initN() {\n        for (auto &row : canvas) {\n            row.fill(' ');\n            row[5] = 'x';\n        }\n    }\n\n    void horizontal(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void vertical(size_t r1, size_t r2, size_t c) {\n        for (size_t r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    void diagd(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    void diagu(size_t c1, size_t c2, size_t r) {\n        for (size_t c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    void drawOnes(int v) {\n        switch (v) {\n        case 1:\n            horizontal(6, 10, 0);\n            break;\n        case 2:\n            horizontal(6, 10, 4);\n            break;\n        case 3:\n            diagd(6, 10, 0);\n            break;\n        case 4:\n            diagu(6, 10, 4);\n            break;\n        case 5:\n            drawOnes(1);\n            drawOnes(4);\n            break;\n        case 6:\n            vertical(0, 4, 10);\n            break;\n        case 7:\n            drawOnes(1);\n            drawOnes(6);\n            break;\n        case 8:\n            drawOnes(2);\n            drawOnes(6);\n            break;\n        case 9:\n            drawOnes(1);\n            drawOnes(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawTens(int v) {\n        switch (v) {\n        case 1:\n            horizontal(0, 4, 0);\n            break;\n        case 2:\n            horizontal(0, 4, 4);\n            break;\n        case 3:\n            diagu(0, 4, 4);\n            break;\n        case 4:\n            diagd(0, 4, 0);\n            break;\n        case 5:\n            drawTens(1);\n            drawTens(4);\n            break;\n        case 6:\n            vertical(0, 4, 0);\n            break;\n        case 7:\n            drawTens(1);\n            drawTens(6);\n            break;\n        case 8:\n            drawTens(2);\n            drawTens(6);\n            break;\n        case 9:\n            drawTens(1);\n            drawTens(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawHundreds(int hundreds) {\n        switch (hundreds) {\n        case 1:\n            horizontal(6, 10, 14);\n            break;\n        case 2:\n            horizontal(6, 10, 10);\n            break;\n        case 3:\n            diagu(6, 10, 14);\n            break;\n        case 4:\n            diagd(6, 10, 10);\n            break;\n        case 5:\n            drawHundreds(1);\n            drawHundreds(4);\n            break;\n        case 6:\n            vertical(10, 14, 10);\n            break;\n        case 7:\n            drawHundreds(1);\n            drawHundreds(6);\n            break;\n        case 8:\n            drawHundreds(2);\n            drawHundreds(6);\n            break;\n        case 9:\n            drawHundreds(1);\n            drawHundreds(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void drawThousands(int thousands) {\n        switch (thousands) {\n        case 1:\n            horizontal(0, 4, 14);\n            break;\n        case 2:\n            horizontal(0, 4, 10);\n            break;\n        case 3:\n            diagd(0, 4, 10);\n            break;\n        case 4:\n            diagu(0, 4, 14);\n            break;\n        case 5:\n            drawThousands(1);\n            drawThousands(4);\n            break;\n        case 6:\n            vertical(10, 14, 0);\n            break;\n        case 7:\n            drawThousands(1);\n            drawThousands(6);\n            break;\n        case 8:\n            drawThousands(2);\n            drawThousands(6);\n            break;\n        case 9:\n            drawThousands(1);\n            drawThousands(8);\n            break;\n        default:\n            break;\n        }\n    }\n\n    void draw(int v) {\n        int thousands = v / 1000;\n        v %= 1000;\n\n        int hundreds = v / 100;\n        v %= 100;\n\n        int tens = v / 10;\n        int ones = v % 10;\n\n        if (thousands > 0) {\n            drawThousands(thousands);\n        }\n        if (hundreds > 0) {\n            drawHundreds(hundreds);\n        }\n        if (tens > 0) {\n            drawTens(tens);\n        }\n        if (ones > 0) {\n            drawOnes(ones);\n        }\n    }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n    for (auto &row : c.canvas) {\n        for (auto cell : row) {\n            os << cell;\n        }\n        os << '\\n';\n    }\n    return os;\n}\n\nint main() {\n    for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n        std::cout << number << \":\\n\";\n\n        Cistercian c(number);\n        std::cout << c << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57072, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 57073, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 57074, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 57075, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 57076, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n\nconst std::string _CHARS = \"abcdefghijklmnopqrstuvwxyz0123456789.:-_/\";\nconst size_t MAX_NODES = 41;\n\nclass node\n{\npublic:\n    node() { clear(); }\n    node( char z ) { clear(); }\n    ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }\n    void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }\n    bool isWord;\n    std::vector<std::string> files;\n    node* next[MAX_NODES];\n};\n\nclass index {\npublic:\n    void add( std::string s, std::string fileName ) {\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        std::string h;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            if( *i == 32 ) {\n                pushFileName( addWord( h ), fileName );\n                h.clear();\n                continue;\n            }\n            h.append( 1, *i );\n        }\n        if( h.length() )\n            pushFileName( addWord( h ), fileName );\n    }\n    void findWord( std::string s ) {\n        std::vector<std::string> v = find( s );\n        if( !v.size() ) {\n            std::cout << s + \" was not found!\\n\";\n            return;\n        }\n        std::cout << s << \" found in:\\n\";\n        for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {\n            std::cout << *i << \"\\n\";\n        }\n        std::cout << \"\\n\";\n    }\nprivate:\n    void pushFileName( node* n, std::string fn ) {\n        std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );\n        if( i == n->files.end() ) n->files.push_back( fn );\n    }\n    const std::vector<std::string>& find( std::string s ) {\n        size_t idx;\n        std::transform( s.begin(), s.end(), s.begin(), tolower );\n        node* rt = &root;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                if( !rt->next[idx] ) return std::vector<std::string>();\n                rt = rt->next[idx];\n            }\n        }\n        if( rt->isWord ) return rt->files;\n        return std::vector<std::string>();\n    }\n    node* addWord( std::string s ) {\n        size_t idx;\n        node* rt = &root, *n;\n        for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n            idx = _CHARS.find( *i );\n            if( idx < MAX_NODES ) {\n                n = rt->next[idx];\n                if( n ){\n                    rt = n;\n                    continue;\n                }\n                n = new node( *i );\n                rt->next[idx] = n;\n                rt = n;\n            }\n        }\n        rt->isWord = true;\n        return rt;\n    }\n    node root;\n};\nint main( int argc, char* argv[] ) {\n    index t;\n    std::string s;\n    std::string files[] = { \"file1.txt\", \"f_text.txt\", \"text_1b.txt\" };\n\n    for( int x = 0; x < 3; x++ ) {\n        std::ifstream f;\n        f.open( files[x].c_str(), std::ios::in );\n        if( f.good() ) {\n            while( !f.eof() ) {\n                f >> s;\n                t.add( s, files[x] );\n                s.clear();\n            }\n            f.close();\n        }\n    }\n\n    while( true ) {\n        std::cout << \"Enter one word to search for, return to exit: \";\n        std::getline( std::cin, s );\n        if( !s.length() ) break;\n        t.findWord( s );\n\n    }\n    return 0;\n}\n"}
{"id": 57077, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 57078, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 57079, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 57080, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 57081, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main(){\n  std::ofstream lprFile;\n  lprFile.open( \"/dev/lp0\" );\n  lprFile << \"Hello World!\\n\";\n  lprFile.close();\n  return 0;\n}\n"}
{"id": 57082, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 57083, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 57084, "name": "Descending primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 57085, "name": "Descending primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n", "C++": "#include <iostream>\n\nbool ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n  while (true) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 57086, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n"}
{"id": 57087, "name": "Jaro similarity", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n"}
{"id": 57088, "name": "Sum and product puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n"}
{"id": 57089, "name": "Sum and product puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {\n    for (auto &p : v) {\n        auto sum = p.first + p.second;\n        auto prod = p.first * p.second;\n        os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n    }\n    return os << '\\n';\n}\n\nvoid print_count(const std::vector<std::pair<int, int>> &candidates) {\n    auto c = candidates.size();\n    if (c == 0) {\n        std::cout << \"no candidates\\n\";\n    } else if (c == 1) {\n        std::cout << \"one candidate\\n\";\n    } else {\n        std::cout << c << \" candidates\\n\";\n    }\n}\n\nauto setup() {\n    std::vector<std::pair<int, int>> candidates;\n\n    \n    for (int x = 2; x <= 98; x++) {\n        \n        for (int y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                candidates.push_back(std::make_pair(x, y));\n            }\n        }\n    }\n\n    return candidates;\n}\n\nvoid remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [sum](const std::pair<int, int> &pair) {\n            auto s = pair.first + pair.second;\n            return s == sum;\n        }\n    ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {\n    candidates.erase(std::remove_if(\n        candidates.begin(), candidates.end(),\n        [prod](const std::pair<int, int> &pair) {\n            auto p = pair.first * pair.second;\n            return p == prod;\n        }\n    ), candidates.end());\n}\n\nvoid statement1(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] == 1) {\n                auto sum = pair.first + pair.second;\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement2(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto prod = pair.first * pair.second;\n            uniqueMap[prod]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto prod = pair.first * pair.second;\n            if (uniqueMap[prod] > 1) {\n                remove_by_prod(candidates, prod);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nvoid statement3(std::vector<std::pair<int, int>> &candidates) {\n    std::map<int, int> uniqueMap;\n\n    std::for_each(\n        candidates.cbegin(), candidates.cend(),\n        [&uniqueMap](const std::pair<int, int> &pair) {\n            auto sum = pair.first + pair.second;\n            uniqueMap[sum]++;\n        }\n    );\n\n    bool loop;\n    do {\n        loop = false;\n        for (auto &pair : candidates) {\n            auto sum = pair.first + pair.second;\n            if (uniqueMap[sum] > 1) {\n                remove_by_sum(candidates, sum);\n\n                loop = true;\n                break;\n            }\n        }\n    } while (loop);\n}\n\nint main() {\n    auto candidates = setup();\n    print_count(candidates);\n\n    statement1(candidates);\n    print_count(candidates);\n\n    statement2(candidates);\n    print_count(candidates);\n\n    statement3(candidates);\n    print_count(candidates);\n\n    std::cout << candidates;\n\n    return 0;\n}\n"}
{"id": 57090, "name": "Fairshare between two and more", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 57091, "name": "Two bullet roulette", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n    t := cylinder[5]\n    for i := 4; i >= 0; i-- {\n        cylinder[i+1] = cylinder[i]\n    }\n    cylinder[0] = t\n}\n\nfunc unload() {\n    for i := 0; i < 6; i++ {\n        cylinder[i] = false\n    }\n}\n\nfunc load() {\n    for cylinder[0] {\n        rshift()\n    }\n    cylinder[0] = true\n    rshift()\n}\n\nfunc spin() {\n    var lim = 1 + rand.Intn(6)\n    for i := 1; i < lim; i++ {\n        rshift()\n    }\n}\n\nfunc fire() bool {\n    shot := cylinder[0]\n    rshift()\n    return shot\n}\n\nfunc method(s string) int {\n    unload()\n    for _, c := range s {\n        switch c {\n        case 'L':\n            load()\n        case 'S':\n            spin()\n        case 'F':\n            if fire() {\n                return 1\n            }\n        }\n    }\n    return 0\n}\n\nfunc mstring(s string) string {\n    var l []string\n    for _, c := range s {\n        switch c {\n        case 'L':\n            l = append(l, \"load\")\n        case 'S':\n            l = append(l, \"spin\")\n        case 'F':\n            l = append(l, \"fire\")\n        }\n    }\n    return strings.Join(l, \", \")\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := 100000\n    for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n        sum := 0\n        for t := 1; t <= tests; t++ {\n            sum += method(m)\n        }\n        pc := float64(sum) * 100 / float64(tests)\n        fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n    }\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <sstream>\n\nclass Roulette {\nprivate:\n    std::array<bool, 6> cylinder;\n\n    std::mt19937 gen;\n    std::uniform_int_distribution<> distrib;\n\n    int next_int() {\n        return distrib(gen);\n    }\n\n    void rshift() {\n        std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n    }\n\n    void unload() {\n        std::fill(cylinder.begin(), cylinder.end(), false);\n    }\n\n    void load() {\n        while (cylinder[0]) {\n            rshift();\n        }\n        cylinder[0] = true;\n        rshift();\n    }\n\n    void spin() {\n        int lim = next_int();\n        for (int i = 1; i < lim; i++) {\n            rshift();\n        }\n    }\n\n    bool fire() {\n        auto shot = cylinder[0];\n        rshift();\n        return shot;\n    }\n\npublic:\n    Roulette() {\n        std::random_device rd;\n        gen = std::mt19937(rd());\n        distrib = std::uniform_int_distribution<>(1, 6);\n\n        unload();\n    }\n\n    int method(const std::string &s) {\n        unload();\n        for (auto c : s) {\n            switch (c) {\n            case 'L':\n                load();\n                break;\n            case 'S':\n                spin();\n                break;\n            case 'F':\n                if (fire()) {\n                    return 1;\n                }\n                break;\n            }\n        }\n        return 0;\n    }\n};\n\nstd::string mstring(const std::string &s) {\n    std::stringstream ss;\n    bool first = true;\n\n    auto append = [&ss, &first](const std::string s) {\n        if (first) {\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << s;\n    };\n\n    for (auto c : s) {\n        switch (c) {\n        case 'L':\n            append(\"load\");\n            break;\n        case 'S':\n            append(\"spin\");\n            break;\n        case 'F':\n            append(\"fire\");\n            break;\n        }\n    }\n\n    return ss.str();\n}\n\nvoid test(const std::string &src) {\n    const int tests = 100000;\n    int sum = 0;\n\n    Roulette r;\n    for (int t = 0; t < tests; t++) {\n        sum += r.method(src);\n    }\n\n    double pc = 100.0 * sum / tests;\n\n    std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n"}
{"id": 57092, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n"}
{"id": 57093, "name": "Prime triangle", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 57094, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 57095, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 57096, "name": "Sequence_ nth number with exactly n divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<int> smallPrimes;\n\nbool is_prime(size_t test) {\n    if (test < 2) {\n        return false;\n    }\n    if (test % 2 == 0) {\n        return test == 2;\n    }\n    for (size_t d = 3; d * d <= test; d += 2) {\n        if (test % d == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n    smallPrimes.push_back(2);\n\n    int count = 0;\n    for (size_t n = 3; count < numPrimes; n += 2) {\n        if (is_prime(n)) {\n            smallPrimes.push_back(n);\n            count++;\n        }\n    }\n}\n\nsize_t divisor_count(size_t n) {\n    size_t count = 1;\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n    for (size_t d = 3; d * d <= n; d += 2) {\n        size_t q = n / d;\n        size_t r = n % d;\n        size_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n    if (n != 1) {\n        count *= 2;\n    }\n    return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n    if (is_prime(n)) {\n        return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n    }\n\n    size_t count = 0;\n    uint64_t result = 0;\n    for (size_t i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            size_t root = (size_t) sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n    return result;\n}\n\nint main() {\n    const int MAX = 15;\n    init_small_primes(MAX);\n    for (size_t n = 1; n <= MAX; n++) {\n        if (n == 13) {\n            std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n        } else {\n            std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 57097, "name": "Sequence_ smallest number with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n    cout << endl;\n    return 0;\n}\n"}
{"id": 57098, "name": "Pancake numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    for (int i = 0; i < 4; i++) {\n        for (int j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            std::cout << \"p(\" << std::setw(2) << n << \") = \" << std::setw(2) << pancake(n) << \"  \";\n        }\n        std::cout << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57099, "name": "Generate random chess position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n", "C++": "#include <ctime>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass chessBoard {\npublic:\n    void generateRNDBoard( int brds ) {\n        int a, b, i; char c;\n        for( int cc = 0; cc < brds; cc++ ) {\n            memset( brd, 0, 64 );\n            std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n            random_shuffle( pieces.begin(), pieces.end() );\n\n            while( pieces.length() ) {\n                i = rand() % pieces.length(); c = pieces.at( i );\n                while( true ) {\n                    a = rand() % 8; b = rand() % 8;\n                    if( brd[a][b] == 0 ) {\n                        if( c == 'P' && !b || c == 'p' && b == 7 || \n                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n                        break;\n                    }\n                }\n                brd[a][b] = c;\n                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n            }\n            print();\n        }\n    }\nprivate:\n    bool search( char c, int a, int b ) {\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n                    if( brd[a + x][b + y] == c ) return true;\n                }\n            }\n        }\n        return false;\n    }\n    void print() {\n        int e = 0;\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) e++;\n                else {\n                    if( e > 0 ) { std::cout << e; e = 0; }\n                    std::cout << brd[x][y];\n                }\n            }\n            if( e > 0 ) { std::cout << e; e = 0; } \n            if( y < 7 ) std::cout << \"/\";\n        }\n        std::cout << \" w - - 0 1\\n\\n\";\n\n        for( int y = 0; y < 8; y++ ) {\n            for( int x = 0; x < 8; x++ ) {\n                if( brd[x][y] == 0 ) std::cout << \".\";\n                else std::cout << brd[x][y];\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n    char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    chessBoard c;\n    c.generateRNDBoard( 2 );\n    return 0;\n}\n"}
{"id": 57100, "name": "Esthetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nstd::string to(int n, int b) {\n    static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n    std::stringstream ss;\n    while (n > 0) {\n        auto rem = n % b;\n        n = n / b;\n        ss << BASE[rem];\n    }\n\n    auto fwd = ss.str();\n    return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n    if (a < b) {\n        return b - a;\n    }\n    return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n    if (n == 0) {\n        return false;\n    }\n    auto i = n % b;\n    n /= b;\n    while (n > 0) {\n        auto j = n % b;\n        if (uabs(i, j) != 1) {\n            return false;\n        }\n        n /= b;\n        i = j;\n    }\n    return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n    std::vector<uint64_t> esths;\n    const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n        auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n            if (i >= n && i <= m) {\n                esths.push_back(i);\n            }\n            if (i == 0 || i > m) {\n                return;\n            }\n            auto d = i % 10;\n            auto i1 = i * 10 + d - 1;\n            auto i2 = i1 + 2;\n            if (d == 0) {\n                dfs_ref(n, m, i2, dfs_ref);\n            } else if (d == 9) {\n                dfs_ref(n, m, i1, dfs_ref);\n            } else {\n                dfs_ref(n, m, i1, dfs_ref);\n                dfs_ref(n, m, i2, dfs_ref);\n            }\n        };\n        dfs_impl(n, m, i, dfs_impl);\n    };\n\n    for (int i = 0; i < 10; i++) {\n        dfs(n2, m2, i);\n    }\n    auto le = esths.size();\n    printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n    if (all) {\n        for (size_t c = 0; c < esths.size(); c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n            if ((c + 1) % perLine == 0) {\n                printf(\"\\n\");\n            }\n        }\n        printf(\"\\n\");\n    } else {\n        for (int c = 0; c < perLine; c++) {\n            auto esth = esths[c];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n............\\n\");\n        for (size_t i = le - perLine; i < le; i++) {\n            auto esth = esths[i];\n            printf(\"%llu \", esth);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main() {\n    for (int b = 2; b <= 16; b++) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n        for (int n = 1, c = 0; c < 6 * b; n++) {\n            if (isEsthetic(n, b)) {\n                c++;\n                if (c >= 4 * b) {\n                    std::cout << to(n, b) << ' ';\n                }\n            }\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true);\n    listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n    listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n    listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n    listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n    return 0;\n}\n"}
{"id": 57101, "name": "Topswops", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\nint topswops(int n) {\n  std::vector<int> list(n);\n  std::iota(std::begin(list), std::end(list), 1);\n  int max_steps = 0;\n  do {\n    auto temp_list = list;\n    for (int steps = 1; temp_list[0] != 1; ++steps) {\n      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n      if (steps > max_steps) max_steps = steps;\n    }\n  } while (std::next_permutation(std::begin(list), std::end(list)));\n  return max_steps;\n}\n\nint main() {\n  for (int i = 1; i <= 10; ++i) {\n    std::cout << i << \": \" << topswops(i) << std::endl;\n  }\n  return 0;\n}\n"}
{"id": 57102, "name": "Old Russian measure of length", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\n\nclass ormConverter\n{\npublic:\n    ormConverter() :  AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t      MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n    void convert( char c, float l )\n    {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t    case 'A': cout << \" Arshin to:\";     l *= AR; break;\n\t    case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t    case 'D': cout << \" Diuym to:\";      l *= DI; break;\n\t    case 'F': cout << \" Fut to:\";        l *= FU; break;\n\t    case 'K': cout << \" Kilometer to:\";  l *= KI; break;\n\t    case 'L': cout << \" Liniya to:\";     l *= LI; break;\n\t    case 'M': cout << \" Meter to:\";      l *= ME; break;\n\t    case 'I': cout << \" Milia to:\";      l *= MI; break;\n\t    case 'P': cout << \" Piad to:\";       l *= PI; break;\n\t    case 'S': cout << \" Sazhen to:\";     l *= SA; break;\n\t    case 'T': cout << \" Tochka to:\";     l *= TO; break;\n\t    case 'V': cout << \" Vershok to:\";    l *= VE; break;\n\t    case 'E': cout << \" Versta to:\";     l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t      mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t     << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t     << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t     << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t     << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t     << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t     << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t     << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n    }\nprivate:\n    const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    ormConverter c;\n    char s; float l;\n    while( true )\n    {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n    }\n    return 0;\n}\n\n"}
{"id": 57103, "name": "Rate counter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n", "C++": "#include <iostream>\n#include <ctime>\n\n\n\nclass CRateState\n{\nprotected:\n    time_t m_lastFlush;\n    time_t m_period;\n    size_t m_tickCount;\npublic:\n    CRateState(time_t period);\n    void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n                                        m_period(period),\n                                        m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n    m_tickCount++;\n\n    time_t now = std::time(NULL);\n\n    if((now - m_lastFlush) >= m_period)\n    {\n        \n        size_t tps = 0.0;\n        if(m_tickCount > 0)\n            tps = m_tickCount / (now - m_lastFlush);\n\n        std::cout << tps << \" tics per second\" << std::endl;\n\n        \n        m_tickCount = 0;\n        m_lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    for(size_t x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = std::time(NULL);\n\n    CRateState rateWatch(5);\n\n    \n    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        rateWatch.Tick();\n    }\n\n    return 0;\n}\n"}
{"id": 57104, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n", "C++": "#include <iostream>\n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n    int count = 0;\n    for (int i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n    for (int i = 1, next = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            cout << i << \" \";\n            next++;\n        }\n    }\n    cout << endl;\n    return 0;\n}\n"}
{"id": 57105, "name": "Padovan sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n", "C++": "#include <iostream>\n#include <map>\n#include <cmath>\n\n\n\nint pRec(int n) {\n    static std::map<int,int> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n\n    if (n <= 2) memo[n] = 1;\n    else memo[n] = pRec(n-2) + pRec(n-3);\n    return memo[n];\n}\n\n\n\nint pFloor(int n) {\n    long const double p = 1.324717957244746025960908854;\n    long const double s = 1.0453567932525329623;\n    return std::pow(p, n-1)/s + 0.5;\n}\n\n\nstd::string& lSystem(int n) {\n    static std::map<int,std::string> memo;\n    auto it = memo.find(n);\n    if (it != memo.end()) return it->second;\n    \n    if (n == 0) memo[n] = \"A\";\n    else {\n        memo[n] = \"\";\n        for (char ch : memo[n-1]) {\n            switch(ch) {\n                case 'A': memo[n].push_back('B'); break;\n                case 'B': memo[n].push_back('C'); break;\n                case 'C': memo[n].append(\"AB\"); break;\n            }\n        }\n    }\n    return memo[n];\n}\n\n\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n    std::cout << \"The \" << descr << \" functions \";\n    int i;\n    for (i=0; i<stop; i++) {\n        int n1 = f1(i);\n        int n2 = f2(i);\n        if (n1 != n2) {\n            std::cout << \"do not match at \" << i\n                      << \": \" << n1 << \" != \" << n2 << \".\\n\";\n            break;\n        }\n    }\n    if (i == stop) {\n        std::cout << \"match from P_0 to P_\" << stop << \".\\n\";\n    }\n}\n\nint main() {\n    \n    std::cout << \"P_0 .. P_19: \";\n    for (int i=0; i<20; i++) std::cout << pRec(i) << \" \";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, pRec, \"floor- and recurrence-based\", 64);\n    \n    \n    std::cout << \"\\nThe first 10 L-system strings are:\\n\";\n    for (int i=0; i<10; i++) std::cout << lSystem(i) << \"\\n\";\n    std::cout << \"\\n\";\n    \n    \n    compare(pFloor, [](int n){return (int)lSystem(n).length();}, \n                            \"floor- and L-system-based\", 32);\n    return 0;\n}\n"}
{"id": 57106, "name": "Pythagoras tree", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass tree {\npublic:\n    tree() {\n        bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n        clr[0] = RGB( 90, 30, 0 );   clr[1] = RGB( 255, 255, 0 );\n        clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n        clr[4] = RGB( 255, 0, 0 );   clr[5] = RGB( 0, 100, 190 );\n    }\n    void draw( int it, POINT a, POINT b ) {\n        if( !it ) return;\n        bmp.setPenColor( clr[it % 6] );\n        POINT df = { b.x - a.x, a.y -  b.y }; POINT c = { b.x - df.y, b.y - df.x };\n        POINT d = { a.x - df.y, a.y - df.x };\n        POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n        drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n    }\n    void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n    void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n        HDC dc = bmp.getDC();\n        MoveToEx( dc, a.x, a.y, NULL );\n        LineTo( dc, b.x, b.y );\n        LineTo( dc, c.x, c.y );\n        LineTo( dc, d.x, d.y );\n        LineTo( dc, a.x, a.y );\n    }\n    myBitmap bmp;\n    DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n    POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n          ptB = { ptA.x + LINE_LEN, ptA.y };\n    tree t; t.draw( 12, ptA, ptB );\n    \n    t.save( \"?:/pt.bmp\" );\n    return 0;\n}\n"}
{"id": 57107, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 57108, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 57109, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\nclass RNG {\nprivate:\n    \n    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };\n    const int64_t m1 = (1LL << 32) - 209;\n    std::array<int64_t, 3> x1;\n    \n    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };\n    const int64_t m2 = (1LL << 32) - 22853;\n    std::array<int64_t, 3> x2;\n    \n    const int64_t d = (1LL << 32) - 209 + 1; \n\npublic:\n    void seed(int64_t state) {\n        x1 = { state, 0, 0 };\n        x2 = { state, 0, 0 };\n    }\n\n    int64_t next_int() {\n        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n        int64_t z = mod(x1i - x2i, m1);\n\n        \n        x1 = { x1i, x1[0], x1[1] };\n        \n        x2 = { x2i, x2[0], x2[1] };\n\n        return z + 1;\n    }\n\n    double next_float() {\n        return static_cast<double>(next_int()) / d;\n    }\n};\n\nint main() {\n    RNG rng;\n\n    rng.seed(1234567);\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << rng.next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    rng.seed(987654321);\n    for (size_t i = 0; i < 100000; i++) \t\t{\n        auto value = floor(rng.next_float() * 5.0);\n        counts[value]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) \t\t{\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57110, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "C++": "\nimport <iostream>;\n"}
{"id": 57111, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "C++": "\nimport <iostream>;\n"}
{"id": 57112, "name": "Stern-Brocot sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 57113, "name": "Numeric error propagation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n", "C++": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nclass Approx {\npublic:\n    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n    operator std::string() const {\n        std::ostringstream os(\"\");\n        os << std::setprecision(15) << v << \" ±\" << std::setprecision(15) << s << std::ends;\n        return os.str();\n    }\n\n    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator +(double d) const { return Approx(v + d, s); }\n    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n    Approx operator -(double d) const { return Approx(v - d, s); }\n\n    Approx operator *(const Approx& a) const {\n        const double t = v * a.v;\n        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n    Approx operator /(const Approx& a) const {\n        const double t = v / a.v;\n        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n    }\n\n    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n    Approx pow(double d) const {\n        const double t = ::pow(v, d);\n        return Approx(t, fabs(t * d * s / v));\n    }\n\nprivate:\n    double v, s;\n};\n"}
{"id": 57114, "name": "List rooted trees", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<long> TREE_LIST;\nstd::vector<int> OFFSET;\n\nvoid init() {\n    for (size_t i = 0; i < 32; i++) {\n        if (i == 1) {\n            OFFSET.push_back(1);\n        } else {\n            OFFSET.push_back(0);\n        }\n    }\n}\n\nvoid append(long t) {\n    TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n    while (l-- > 0) {\n        if (t % 2 == 1) {\n            std::cout << '(';\n        } else {\n            std::cout << ')';\n        }\n        t = t >> 1;\n    }\n}\n\nvoid listTrees(int n) {\n    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n        show(TREE_LIST[i], 2 * n);\n        std::cout << '\\n';\n    }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n    if (rem == 0) {\n        append(t);\n        return;\n    }\n\n    auto pp = pos;\n    auto ss = sl;\n\n    if (sl > rem) {\n        ss = rem;\n        pp = OFFSET[ss];\n    } else if (pp >= OFFSET[ss + 1]) {\n        ss--;\n        if (ss == 0) {\n            return;\n        }\n        pp = OFFSET[ss];\n    }\n\n    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n    assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n    if (OFFSET[n + 1] != 0) {\n        return;\n    }\n    if (n > 0) {\n        makeTrees(n - 1);\n    }\n    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n    OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n    if (n < 1 || n > 12) {\n        throw std::runtime_error(\"Argument must be between 1 and 12\");\n    }\n\n    append(0);\n\n    makeTrees(n);\n    std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n    listTrees(n);\n}\n\nint main() {\n    init();\n    test(5);\n\n    return 0;\n}\n"}
{"id": 57115, "name": "Longest common suffix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nstd::string lcs(const std::vector<std::string>& strs) {\n    std::vector<std::string::const_reverse_iterator> backs;\n    std::string s;\n    \n    if (strs.size() == 0) return \"\";\n    if (strs.size() == 1) return strs[0];\n    \n    for (auto& str : strs) backs.push_back(str.crbegin());\n    \n    while (backs[0] != strs[0].crend()) {\n        char ch = *backs[0]++;\n        for (std::size_t i = 1; i<strs.size(); i++) {\n            if (backs[i] == strs[i].crend()) goto done;\n            if (*backs[i] != ch) goto done;\n            backs[i]++;\n        }\n        s.push_back(ch);\n    }\n    \ndone:\n    reverse(s.begin(), s.end());\n    return s;\n}\n\nvoid test(const std::vector<std::string>& strs) {\n    std::cout << \"[\";\n    for (std::size_t i = 0; i<strs.size(); i++) {\n        std::cout << '\"' << strs[i] << '\"';\n        if (i != strs.size()-1) std::cout << \", \";\n    }\n    std::cout << \"] -> `\" << lcs(strs) << \"`\\n\";\n}\n\nint main() {\n    std::vector<std::string> t1 = {\"baabababc\", \"baabc\", \"bbabc\"};\n    std::vector<std::string> t2 = {\"baabababc\", \"baabc\", \"bbazc\"};\n    std::vector<std::string> t3 = \n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Friday\", \"Saturday\"};\n    std::vector<std::string> t4 = {\"longest\", \"common\", \"suffix\"};\n    std::vector<std::string> t5 = {\"\"};\n    std::vector<std::string> t6 = {};\n    std::vector<std::string> t7 = {\"foo\", \"foo\", \"foo\", \"foo\"};\n\n    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};\n    \n    for (auto t : tests) test(t);\n    return 0;\n}\n"}
{"id": 57116, "name": "Arena storage pool", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n", "C++": "T* foo = new(arena) T;\n"}
{"id": 57117, "name": "Arena storage pool", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n", "C++": "T* foo = new(arena) T;\n"}
{"id": 57118, "name": "Arena storage pool", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n", "C++": "T* foo = new(arena) T;\n"}
{"id": 57119, "name": "Sum of elements below main diagonal of matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate<typename T>\nT sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {\n    T sum = 0;\n    for (std::size_t y = 0; y < matrix.size(); y++)\n        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n            sum += matrix[y][x];\n    return sum;\n}\n\nint main() {\n    std::vector<std::vector<int>> matrix = {\n        {1,3,7,8,10},\n        {2,4,16,14,4},\n        {3,1,9,18,11},\n        {12,14,17,18,20},\n        {7,1,3,9,5}\n    };\n    \n    std::cout << sum_below_diagonal(matrix) << std::endl;\n    return 0;\n}\n"}
{"id": 57120, "name": "FASTA format", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\nint main( int argc, char **argv ){\n    if( argc <= 1 ){\n        std::cerr << \"Usage: \"<<argv[0]<<\" [infile]\" << std::endl;\n        return -1;\n    }\n\n    std::ifstream input(argv[1]);\n    if(!input.good()){\n        std::cerr << \"Error opening '\"<<argv[1]<<\"'. Bailing out.\" << std::endl;\n        return -1;\n    }\n\n    std::string line, name, content;\n    while( std::getline( input, line ).good() ){\n        if( line.empty() || line[0] == '>' ){ \n            if( !name.empty() ){ \n                std::cout << name << \" : \" << content << std::endl;\n                name.clear();\n            }\n            if( !line.empty() ){\n                name = line.substr(1);\n            }\n            content.clear();\n        } else if( !name.empty() ){\n            if( line.find(' ') != std::string::npos ){ \n                name.clear();\n                content.clear();\n            } else {\n                content += line;\n            }\n        }\n    }\n    if( !name.empty() ){ \n        std::cout << name << \" : \" << content << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 57121, "name": "Elementary cellular automaton_Random number generator", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n"}
{"id": 57122, "name": "Elementary cellular automaton_Random number generator", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n", "C++": "#include <bitset>\n#include <stdio.h>\n\n#define SIZE\t           80\n#define RULE               30\n#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset<SIZE> &s) {\n    int i;\n    std::bitset<SIZE> t(0);\n    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );\n    for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n    for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset<SIZE> s) {\n    int i;\n    for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n    printf(\"|\\n\");\n}\nunsigned char byte(std::bitset<SIZE> &s) {\n    unsigned char b = 0;\n    int i;\n    for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n    }\n    return b;\n}\n\nint main() {\n    int i;\n    std::bitset<SIZE> state(1);\n    for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n    return 0;\n}\n"}
{"id": 57123, "name": "Pseudo-random numbers_PCG32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nclass PCG32 {\nprivate:\n    const uint64_t N = 6364136223846793005;\n    uint64_t state = 0x853c49e6748fea9b;\n    uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n    uint32_t nextInt() {\n        uint64_t old = state;\n        state = old * N + inc;\n        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n        uint32_t rot = old >> 59;\n        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    double nextFloat() {\n        return ((double)nextInt()) / (1LL << 32);\n    }\n\n    void seed(uint64_t seed_state, uint64_t seed_sequence) {\n        state = 0;\n        inc = (seed_sequence << 1) | 1;\n        nextInt();\n        state = state + seed_state;\n        nextInt();\n    }\n};\n\nint main() {\n    auto r = new PCG32();\n\n    r->seed(42, 54);\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << r->nextInt() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };\n    r->seed(987654321, 1);\n    for (size_t i = 0; i < 100000; i++) {\n        int j = (int)floor(r->nextFloat() * 5.0);\n        counts[j]++;\n    }\n\n    std::cout << \"The counts for 100,000 repetitions are:\\n\";\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << \"  \" << i << \" : \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57124, "name": "Sierpinski pentagon", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 57125, "name": "Rep-string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 57126, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n"}
{"id": 57127, "name": "Changeable words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint hamming_distance(const std::string& str1, const std::string& str2) {\n    size_t len1 = str1.size();\n    size_t len2 = str2.size();\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    for (size_t i = 0; i < len1; ++i) {\n        if (str1[i] != str2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() > 11)\n            dictionary.push_back(line);\n    }\n    std::cout << \"Changeable words in \" << filename << \":\\n\";\n    int n = 1;\n    for (const std::string& word1 : dictionary) {\n        for (const std::string& word2 : dictionary) {\n            if (hamming_distance(word1, word2) == 1)\n                std::cout << std::setw(2) << std::right << n++\n                    << \": \" << std::setw(14) << std::left << word1\n                    << \" -> \" << word2 << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57128, "name": "Monads_List monad", "Go": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n    return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n    return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = v + 1\n    }\n    return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = 2 * v\n    }\n    return unit(lst2)\n}\n\nfunc main() {\n    ml1 := unit([]int{3, 4, 5})\n    ml2 := ml1.bind(increment).bind(double)\n    fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate <typename T>\nauto operator>>(const vector<T>& monad, auto f)\n{\n    \n    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;\n    for(auto& item : monad)\n    {\n        \n        \n        const auto r = f(item);\n        \n        result.insert(result.end(), begin(r), end(r));\n    }\n    \n    return result;\n}\n\n\nauto Pure(auto t)\n{\n    return vector{t};\n}\n\n\nauto Double(int i)\n{\n    return Pure(2 * i);\n}\n\n\nauto Increment(int i)\n{\n    return Pure(i + 1);\n}\n\n\nauto NiceNumber(int i)\n{\n    return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n\n\nauto UpperSequence = [](auto startingVal)\n{\n    const int MaxValue = 500;\n    vector<decltype(startingVal)> sequence;\n    while(startingVal <= MaxValue) \n        sequence.push_back(startingVal++);\n    return sequence;\n};\n\n\nvoid PrintVector(const auto& vec)\n{\n    cout << \" \";\n    for(auto value : vec)\n    {\n        cout << value << \" \";\n    }\n    cout << \"\\n\";\n}\n\n\nvoid PrintTriples(const auto& vec)\n{\n    cout << \"Pythagorean triples:\\n\";\n    for(auto it = vec.begin(); it != vec.end();)\n    {\n        auto x = *it++;\n        auto y = *it++;\n        auto z = *it++;\n        \n        cout << x << \", \" << y << \", \" << z << \"\\n\";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    \n    auto listMonad = \n        vector<int> {2, 3, 4} >> \n        Increment >> \n        Double >>\n        NiceNumber;\n        \n    PrintVector(listMonad);\n    \n    \n    \n    \n    \n    auto pythagoreanTriples = UpperSequence(1) >> \n        [](int x){return UpperSequence(x) >>\n        [x](int y){return UpperSequence(y) >>\n        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};\n    \n    PrintTriples(pythagoreanTriples);\n}\n"}
{"id": 57129, "name": "Special factorials", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc sf(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    sfact := big.NewInt(1)\n    fact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        sfact.Mul(sfact, fact)\n    }\n    return sfact\n}\n\nfunc H(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    hfact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        bi := big.NewInt(int64(i))\n        hfact.Mul(hfact, bi.Exp(bi, bi, nil))\n    }\n    return hfact\n}\n\nfunc af(n int) *big.Int {\n    if n < 1 {\n        return new(big.Int)\n    }\n    afact := new(big.Int)\n    fact := big.NewInt(1)\n    sign := new(big.Int)\n    if n%2 == 0 {\n        sign.SetInt64(-1)\n    } else {\n        sign.SetInt64(1)\n    }\n    t := new(big.Int)\n    for i := 1; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        afact.Add(afact, t.Mul(fact, sign))\n        sign.Neg(sign)\n    }\n    return afact\n}\n\nfunc ef(n int) *big.Int {\n    if n < 1 {\n        return big.NewInt(1)\n    }\n    t := big.NewInt(int64(n))\n    return t.Exp(t, ef(n-1), nil)\n}\n\nfunc rf(n *big.Int) int {\n    i := 0\n    fact := big.NewInt(1)\n    for {\n        if fact.Cmp(n) == 0 {\n            return i\n        }\n        if fact.Cmp(n) > 0 {\n            return -1\n        }\n        i++\n        fact.Mul(fact, big.NewInt(int64(i)))\n    }\n}\n\nfunc main() {\n    fmt.Println(\"First 10 superfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sf(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 hyperfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(H(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 alternating factorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Print(af(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 exponential factorials:\")\n    for i := 0; i <= 4; i++ {\n        fmt.Print(ef(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nThe number of digits in 5$ is\", len(ef(5).String()))\n\n    fmt.Println(\"\\nReverse factorials:\")\n    facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}\n    for _, fact := range facts {\n        bfact := big.NewInt(fact)\n        rfact := rf(bfact)\n        srfact := fmt.Sprintf(\"%d\", rfact)\n        if rfact == -1 {\n            srfact = \"none\"\n        }\n        fmt.Printf(\"%4s <- rf(%d)\\n\", srfact, fact)\n    }\n}\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <functional>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= i;\n    }\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    for (int i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    for (int i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n    return result;\n}\n\nvoid test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {\n    std::cout << \"First \" << count << ' ' << name << '\\n';\n    for (int i = 0; i < count; i++) {\n        std::cout << func(i) << ' ';\n    }\n    std::cout << '\\n';\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        std::cout << \"rf(\" << f << \") = No Solution\\n\";\n    } else {\n        std::cout << \"rf(\" << f << \") = \" << n << '\\n';\n    }\n}\n\nint main() {\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    std::cout << '\\n';\n\n    \n    test_factorial(8, hyper_factorial, \"hyper factorials\");\n    std::cout << '\\n';\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    std::cout << '\\n';\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    std::cout << '\\n';\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 57130, "name": "Four is magic", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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 <iostream>\n#include <string>\n#include <cctype>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n    \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n    \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n    \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n    \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n    const char* name_;\n    integer number_;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number_)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n    std::string result;\n    if (n < 20)\n        result = small[n];\n    else if (n < 100) {\n        result = tens[n/10 - 2];\n        if (n % 10 != 0) {\n            result += \"-\";\n            result += small[n % 10];\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number_;\n        result = cardinal(n/p);\n        result += \" \";\n        result += num.name_;\n        if (n % p != 0) {\n            result += \" \";\n            result += cardinal(n % p);\n        }\n    }\n    return result;\n}\n\ninline char uppercase(char ch) {\n    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));\n}\n\nstd::string magic(integer n) {\n    std::string result;\n    for (unsigned int i = 0; ; ++i) {\n        std::string text(cardinal(n));\n        if (i == 0)\n            text[0] = uppercase(text[0]);\n        result += text;\n        if (n == 4) {\n            result += \" is magic.\";\n            break;\n        }\n        integer len = text.length();\n        result += \" is \";\n        result += cardinal(len);\n        result += \", \";\n        n = len;\n    }\n    return result;\n}\n\nvoid test_magic(integer n) {\n    std::cout << magic(n) << '\\n';\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 57131, "name": "Getting the number of decimals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nint findNumOfDec(double x) {\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(14) << x;\n\n    auto s = ss.str();\n    auto pos = s.find('.');\n    if (pos == std::string::npos) {\n        return 0;\n    }\n\n    auto tail = s.find_last_not_of('0');\n\n    return tail - pos;\n}\n\nvoid test(double x) {\n    std::cout << x << \" has \" << findNumOfDec(x) << \" decimals\\n\";\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 57132, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 57133, "name": "Parse an IP Address", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n"}
{"id": 57134, "name": "Textonyms", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n"}
{"id": 57135, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 57136, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C++": "#include <list>\n#include <algorithm>\n#include <iostream>\n\nclass point {\npublic:\n    point( int a = 0, int b = 0 ) { x = a; y = b; }\n    bool operator ==( const point& o ) { return o.x == x && o.y == y; }\n    point operator +( const point& o ) { return point( o.x + x, o.y + y ); }\n    int x, y;\n};\n\nclass map {\npublic:\n    map() {\n        char t[8][8] = {\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},\n            {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},\n            {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},\n            {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}\n        };\n        w = h = 8;\n        for( int r = 0; r < h; r++ )\n            for( int s = 0; s < w; s++ )\n                m[s][r] = t[r][s];\n    }\n    int operator() ( int x, int y ) { return m[x][y]; }\n    char m[8][8];\n    int w, h;\n};\n\nclass node {\npublic:\n    bool operator == (const node& o ) { return pos == o.pos; }\n    bool operator == (const point& o ) { return pos == o; }\n    bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }\n    point pos, parent;\n    int dist, cost;\n};\n\nclass aStar {\npublic:\n    aStar() {\n        neighbours[0] = point( -1, -1 ); neighbours[1] = point(  1, -1 );\n        neighbours[2] = point( -1,  1 ); neighbours[3] = point(  1,  1 );\n        neighbours[4] = point(  0, -1 ); neighbours[5] = point( -1,  0 );\n        neighbours[6] = point(  0,  1 ); neighbours[7] = point(  1,  0 );\n    }\n\n    int calcDist( point& p ){\n        \n        int x = end.x - p.x, y = end.y - p.y;\n        return( x * x + y * y );\n    }\n\n    bool isValid( point& p ) {\n        return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );\n    }\n\n    bool existPoint( point& p, int cost ) {\n        std::list<node>::iterator i;\n        i = std::find( closed.begin(), closed.end(), p );\n        if( i != closed.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { closed.erase( i ); return false; }\n        }\n        i = std::find( open.begin(), open.end(), p );\n        if( i != open.end() ) {\n            if( ( *i ).cost + ( *i ).dist < cost ) return true;\n            else { open.erase( i ); return false; }\n        }\n        return false;\n    }\n\n    bool fillOpen( node& n ) {\n        int stepCost, nc, dist;\n        point neighbour;\n\n        for( int x = 0; x < 8; x++ ) {\n            \n            stepCost = x < 4 ? 1 : 1;\n            neighbour = n.pos + neighbours[x];\n            if( neighbour == end ) return true;\n\n            if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {\n                nc = stepCost + n.cost;\n                dist = calcDist( neighbour );\n                if( !existPoint( neighbour, nc + dist ) ) {\n                    node m;\n                    m.cost = nc; m.dist = dist;\n                    m.pos = neighbour;\n                    m.parent = n.pos;\n                    open.push_back( m );\n                }\n            }\n        }\n        return false;\n    }\n\n    bool search( point& s, point& e, map& mp ) {\n        node n; end = e; start = s; m = mp;\n        n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );\n        open.push_back( n );\n        while( !open.empty() ) {\n            \n            node n = open.front();\n            open.pop_front();\n            closed.push_back( n );\n            if( fillOpen( n ) ) return true;\n        }\n        return false;\n    }\n\n    int path( std::list<point>& path ) {\n        path.push_front( end );\n        int cost = 1 + closed.back().cost;\n        path.push_front( closed.back().pos );\n        point parent = closed.back().parent;\n\n        for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {\n            if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {\n                path.push_front( ( *i ).pos );\n                parent = ( *i ).parent;\n            }\n        }\n        path.push_front( start );\n        return cost;\n    }\n\n    map m; point end, start;\n    point neighbours[8];\n    std::list<node> open;\n    std::list<node> closed;\n};\n\nint main( int argc, char* argv[] ) {\n    map m;\n    point s, e( 7, 7 );\n    aStar as;\n\n    if( as.search( s, e, m ) ) {\n        std::list<point> path;\n        int c = as.path( path );\n        for( int y = -1; y < 9; y++ ) {\n            for( int x = -1; x < 9; x++ ) {\n                if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )\n                    std::cout << char(0xdb);\n                else {\n                    if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )\n                        std::cout << \"x\";\n                    else std::cout << \".\";\n                }\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\nPath cost \" << c << \": \";\n        for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {\n            std::cout<< \"(\" << ( *i ).x << \", \" << ( *i ).y << \") \";\n        }\n    }\n    std::cout << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 57137, "name": "Teacup rim text", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n\n\nstd::set<std::string> load_dictionary(const std::string& filename) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::set<std::string> words;\n    std::string word;\n    while (getline(in, word))\n        words.insert(word);\n    return words;\n}\n\nvoid find_teacup_words(const std::set<std::string>& words) {\n    std::vector<std::string> teacup_words;\n    std::set<std::string> found;\n    for (auto w = words.begin(); w != words.end(); ++w) {\n        std::string word = *w;\n        size_t len = word.size();\n        if (len < 3 || found.find(word) != found.end())\n            continue;\n        teacup_words.clear();\n        teacup_words.push_back(word);\n        for (size_t i = 0; i + 1 < len; ++i) {\n            std::rotate(word.begin(), word.begin() + 1, word.end());\n            if (word == *w || words.find(word) == words.end())\n                break;\n            teacup_words.push_back(word);\n        }\n        if (teacup_words.size() == len) {\n            found.insert(teacup_words.begin(), teacup_words.end());\n            std::cout << teacup_words[0];\n            for (size_t i = 1; i < len; ++i)\n                std::cout << ' ' << teacup_words[i];\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        find_teacup_words(load_dictionary(argv[1]));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57138, "name": "Increasing gaps between consecutive Niven numbers", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    std::cout << \"Gap index  Gap    Niven index    Niven number\\n\";\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                std::cout << std::setw(9) << gap_index++\n                    << std::setw(5) << gap\n                    << std::setw(15) << niven_index\n                    << std::setw(16) << previous << '\\n';\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 57139, "name": "Print debugging statement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n", "C++": "#include <iostream>\n\n\n#define DEBUG(msg,...) fprintf(stderr, \"[DEBUG %s@%d] \" msg \"\\n\", __FILE__, __LINE__, __VA_ARGS__)\n\n\n\nint main() {\n    DEBUG(\"Hello world\");\n    DEBUG(\"Some %d Things\", 42);\n\n    return 0;\n}\n"}
{"id": 57140, "name": "Range extraction", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 57141, "name": "Type detection", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 57142, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 57143, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 57144, "name": "Variable declaration reset", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n"}
{"id": 57145, "name": "Numbers with equal rises and falls", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool equal_rises_and_falls(int n) {\n    int total = 0;\n    for (int previous_digit = -1; n > 0; n /= 10) {\n        int digit = n % 10;\n        if (previous_digit > digit)\n            ++total;\n        else if (previous_digit >= 0 && previous_digit < digit)\n            --total;\n        previous_digit = digit;\n    }\n    return total == 0;\n}\n\nint main() {\n    const int limit1 = 200;\n    const int limit2 = 10000000;\n    int n = 0;\n    std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n    for (int count = 0; count < limit2; ) {\n        if (equal_rises_and_falls(++n)) {\n            ++count;\n            if (count <= limit1)\n                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}\n"}
{"id": 57146, "name": "Koch curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57147, "name": "Koch curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57148, "name": "Words from neighbour ones", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57149, "name": "Magic squares of singly even order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n"}
{"id": 57150, "name": "Magic squares of singly even order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n \nclass magicSqr\n{\npublic: \n    magicSqr() { sqr = 0; }\n    ~magicSqr() { if( sqr ) delete [] sqr; }\n \n    void create( int d ) {\n        if( sqr ) delete [] sqr;\n        if( d & 1 ) d++;\n        while( d % 4 == 0 ) { d += 2; }\n        sz = d;\n        sqr = new int[sz * sz];\n        memset( sqr, 0, sz * sz * sizeof( int ) );\n        fillSqr();\n    }\n    void display() {\n        cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void siamese( int from, int to ) {\n        int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n        while( count > 0 ) {\n            bool done = false;\n            while ( false == done ) {\n                if( curCol >= oneSide ) curCol = 0;\n                if( curRow < 0 ) curRow = oneSide - 1;\n                done = true;\n                if( sqr[curCol + sz * curRow] != 0 ) {\n                    curCol -= 1; curRow += 2;\n                    if( curCol < 0 ) curCol = oneSide - 1;\n                    if( curRow >= oneSide ) curRow -= oneSide;\n\n                    done = false;\n                }\n            }\n            sqr[curCol + sz * curRow] = s;\n            s++; count--; curCol++; curRow--;\n        }\n    }\n    void fillSqr() {\n        int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n        siamese( 0, n );\n\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;\n            for( int c = n; c < sz; c++ ) {\n                int m = sqr[c - n + row];\n                \n                sqr[c + row] = m + add1;\n                sqr[c + row + ns] = m + add3;\n                sqr[c - n + row + ns] = m + add2;\n            }\n        }\n\n        int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = co; c < sz; c++ ) {    \n                sqr[c + row] -= add3;\n                sqr[c + row + ns] += add3;\n            }\n        }\n        for( int r = 0; r < n; r++ ) {\n            int row = r * sz;    \n            for( int c = 0; c < lc; c++ ) {\n                int cc = c;\n                if( r == lc ) cc++;\n                sqr[cc + row] += add2;\n                sqr[cc + row + ns] -= add2;\n            }\n        }\n    }\n    int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n    void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n    int* sqr;\n    int sz;\n};\nint main( int argc, char* argv[] ) {\n    magicSqr s; s.create( 6 );\n    s.display();\n    return 0;\n}\n"}
{"id": 57151, "name": "Generate Chess960 starting position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <time.h>\nusing namespace std;\n\nnamespace\n{\n    void placeRandomly(char* p, char c)\n    {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t    p[loc] = c;\n\telse\n\t    placeRandomly(p, c);    \n    }\n    int placeFirst(char* p, char c, int loc = 0)\n    {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n        return loc;\n    }\n\n    string startPos()\n    {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t\n\tfor (char c : \"QNN\")\n\t    placeRandomly(p, c);\n\n\t\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n    }\n}   \n\nnamespace chess960\n{\n    void generate( int c )\n    {\n\tfor( int x = 0; x < c; x++ )\n\t    cout << startPos() << \"\\n\";\n    }\n}\n\nint main( int argc, char* argv[] )\n{\n    srand( time( NULL ) );\n    chess960::generate( 10 );\n    cout << \"\\n\\n\";\n    return system( \"pause\" );\n}\n"}
{"id": 57152, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "C++": "int meaning_of_life();\n"}
{"id": 57153, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "C++": "int meaning_of_life();\n"}
{"id": 57154, "name": "File size distribution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc commatize(n int64) 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 fileSizeDistribution(root string) {\n    var sizes [12]int\n    files := 0\n    directories := 0\n    totalSize := int64(0)\n    walkFunc := func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        files++\n        if info.IsDir() {\n            directories++\n        }\n        size := info.Size()\n        if size == 0 {\n            sizes[0]++\n            return nil\n        }\n        totalSize += size\n        logSize := math.Log10(float64(size))\n        index := int(math.Floor(logSize))\n        sizes[index+1]++\n        return nil\n    }\n    err := filepath.Walk(root, walkFunc)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n    for i := 0; i < len(sizes); i++ {\n        if i == 0 {\n            fmt.Print(\"  \")\n        } else {\n            fmt.Print(\"+ \")\n        }\n        fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n    }\n    fmt.Println(\"                                  -----\")\n    fmt.Printf(\"= Total number of files         : %5d\\n\", files)\n    fmt.Printf(\"  including directories         : %5d\\n\", directories)\n    c := commatize(totalSize)\n    fmt.Println(\"\\n  Total size of files           :\", c, \"bytes\")\n}\n\nfunc main() {\n    fileSizeDistribution(\"./\")\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n    constexpr size_t n = 9;\n    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,\n        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n    std::array<size_t, n + 1> count = { 0 };\n    size_t files = 0;\n    std::uintmax_t total_size = 0;\n    std::filesystem::recursive_directory_iterator iter(directory);\n    for (const auto& dir_entry : iter) {\n        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n            std::uintmax_t file_size = dir_entry.file_size();\n            total_size += file_size;\n            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n            size_t index = std::distance(sizes.begin(), i);\n            ++count[index];\n            ++files;\n        }\n    }\n    std::cout << \"File size distribution for \" << directory << \":\\n\";\n    for (size_t i = 0; i <= n; ++i) {\n        if (i == n)\n            std::cout << \"> \" << sizes[i - 1];\n        else\n            std::cout << std::setw(16) << sizes[i];\n        std::cout << \" bytes: \" << count[i] << '\\n';\n    }\n    std::cout << \"Number of files: \" << files << '\\n';\n    std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    try {\n        const char* directory(argc > 1 ? argv[1] : \".\");\n        std::filesystem::path path(directory);\n        if (!is_directory(path)) {\n            std::cerr << directory << \" is not a directory.\\n\";\n            return EXIT_FAILURE;\n        }\n        file_size_distribution(path);\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57155, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main(void)\n{\n    fs::path p(fs::current_path());\n    std::set<std::string> tree;\n\n    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)\n        tree.insert(it->path().filename().native());\n\n    for (auto entry : tree)\n        std::cout << entry << '\\n';\n}\n"}
{"id": 57156, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 57157, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 57158, "name": "Pseudo-random numbers_Xorshift star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "C++": "#include <array>\n#include <cstdint>\n#include <iostream>\n\nclass XorShiftStar {\nprivate:\n    const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n    uint64_t state;\npublic:\n    void seed(uint64_t num) {\n        state = num;\n    }\n\n    uint32_t next_int() {\n        uint64_t x;\n        uint32_t answer;\n\n        x = state;\n        x = x ^ (x >> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >> 27);\n        state = x;\n        answer = ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    float next_float() {\n        return (float)next_int() / (1LL << 32);\n    }\n};\n\nint main() {\n    auto rng = new XorShiftStar();\n    rng->seed(1234567);\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << rng->next_int() << '\\n';\n    std::cout << '\\n';\n\n    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };\n    rng->seed(987654321);\n    for (int i = 0; i < 100000; i++) {\n        int j = (int)floor(rng->next_float() * 5.0);\n        counts[j]++;\n    }\n    for (size_t i = 0; i < counts.size(); i++) {\n        std::cout << i << \": \" << counts[i] << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57159, "name": "Four is the number of letters in the ...", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n", "C++": "#include <cctype>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        result.push_back(get_name(small[n], ordinal));\n        count = 1;\n    }\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result.push_back(get_name(tens[n/10 - 2], ordinal));\n        } else {\n            std::string name(get_name(tens[n/10 - 2], false));\n            name += \"-\";\n            name += get_name(small[n % 10], ordinal);\n            result.push_back(name);\n        }\n        count = 1;\n    } else {\n        const named_number& num = get_named_number(n);\n        uint64_t p = num.number;\n        count += append_number_name(result, n/p, false);\n        if (n % p == 0) {\n            result.push_back(get_name(num, ordinal));\n            ++count;\n        } else {\n            result.push_back(get_name(num, false));\n            ++count;\n            count += append_number_name(result, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(const std::string& str) {\n    size_t letters = 0;\n    for (size_t i = 0, n = str.size(); i < n; ++i) {\n        if (isalpha(static_cast<unsigned char>(str[i])))\n            ++letters;\n    }\n    return letters;\n}\n\nstd::vector<std::string> sentence(size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    std::vector<std::string> result;\n    result.reserve(count + 10);\n    size_t n = std::size(words);\n    for (size_t i = 0; i < n && i < count; ++i) {\n        result.push_back(words[i]);\n    }\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result[i]), false);\n        result.push_back(\"in\");\n        result.push_back(\"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        result.back() += ',';\n    }\n    return result;\n}\n\nsize_t sentence_length(const std::vector<std::string>& words) {\n    size_t n = words.size();\n    if (n == 0)\n        return 0;\n    size_t length = n - 1;\n    for (size_t i = 0; i < n; ++i)\n        length += words[i].size();\n    return length;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    size_t n = 201;\n    auto result = sentence(n);\n    std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            std::cout << (i % 25 == 0 ? '\\n' : ' ');\n        std::cout << std::setw(2) << count_letters(result[i]);\n    }\n    std::cout << '\\n';\n    std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    for (n = 1000; n <= 10000000; n *= 10) {\n        result = sentence(n);\n        const std::string& word = result[n - 1];\n        std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n            << count_letters(word) << \" letters. \";\n        std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57160, "name": "ASCII art diagram converter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n", "C++": "#include <array>\n#include <bitset>\n#include <iostream>\n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n\n\ntemplate <const char *T> consteval auto ParseDiagram()\n{  \n    \n    constexpr string_view rawArt(T);\n    constexpr auto firstBar = rawArt.find(\"|\");\n    constexpr auto lastBar = rawArt.find_last_of(\"|\");\n    constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n    static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n    \n    \n    constexpr auto numFields = \n        count(rawArt.begin(), rawArt.end(), '|') -\n        count(rawArt.begin(), rawArt.end(), '\\n') / 2;    \n    array<FieldDetails, numFields> fields;\n    \n    \n    bool isValidDiagram = true;\n    int startDiagramIndex = 0;\n    int totalBits = 0;\n    for(int i = 0; i < numFields; )\n    {\n        auto beginningBar = art.find(\"|\", startDiagramIndex);\n        auto endingBar = art.find(\"|\", beginningBar + 1);\n        auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n        if(field.find(\"-\") == field.npos) \n        {\n            int numBits = (field.size() + 1) / 3;\n            auto nameStart = field.find_first_not_of(\" \");\n            auto nameEnd = field.find_last_not_of(\" \");\n            if (nameStart > nameEnd || nameStart == string_view::npos) \n            {\n                \n                isValidDiagram = false;\n                field = \"\"sv;\n            }\n            else\n            {\n                field = field.substr(nameStart, 1 + nameEnd - nameStart);\n            }\n            fields[i++] = FieldDetails {field, numBits};\n            totalBits += numBits;\n        }\n        startDiagramIndex = endingBar;\n    }\n    \n    int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n    return make_pair(fields, numRawBytes);\n}\n\n\ntemplate <const char *T> auto Encode(auto inputValues)\n{\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n    array<unsigned char, parsedDiagram.second> data;\n\n    int startBit = 0;\n    int i = 0;\n    for(auto value : inputValues)\n    {\n        const auto &field = parsedDiagram.first[i++];\n        int remainingValueBits = field.NumBits;\n        while(remainingValueBits > 0)\n        {\n            \n            auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n            int unusedBits = 8 - fieldStartBit;\n            int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n            int divisor = 1 << (remainingValueBits - numBitsToEncode);\n            unsigned char bitsToEncode = value / divisor;\n            data[fieldStartByte] <<= numBitsToEncode;\n            data[fieldStartByte] |= bitsToEncode;\n            value %= divisor;\n            startBit += numBitsToEncode;\n            remainingValueBits -= numBitsToEncode;\n        }\n    }\n    \n    return data;\n}\n\n\ntemplate <const char *T> void Decode(auto data)\n{\n    cout << \"Name      Bit Pattern\\n\";\n    cout << \"=======   ================\\n\";\n    constexpr auto parsedDiagram = ParseDiagram<T>();\n    static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n    int startBit = 0;\n    for(const auto& field : parsedDiagram.first)\n    {\n        \n        auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n        unsigned char firstByte = data[fieldStartByte];\n        firstByte <<= fieldStartBit;\n        firstByte >>= fieldStartBit;\n        int64_t value = firstByte;\n        auto endBit = startBit + field.NumBits;\n        auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n        fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n        for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n        {\n            value <<= 8;\n            value += data[index];\n        }\n        value >>= fieldEndBit;\n        startBit = endBit;\n        \n        cout << field.Name << \n            string_view(\"        \", (7 - field.Name.size())) << \"   \" << \n            string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) <<  \"\\n\";\n    }\n            \n}\n\nint main(void) \n{\n    static constexpr char art[] = R\"(\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                      ID                       |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    QDCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ANCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    NSCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    |                    ARCOUNT                    |\n    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n    \n    \n    auto rawData = Encode<art> (initializer_list<int64_t> {\n        30791,\n        0, 15, 0, 1, 1, 1, 3, 15,\n        21654,\n        57646,\n        7153,\n        27044\n    });\n    \n    cout << \"Raw encoded data in hex:\\n\";\n    for (auto v : rawData) printf(\"%.2X\", v);\n    cout << \"\\n\\n\";\n    \n    cout << \"Decoded raw data:\\n\";\n    Decode<art>(rawData);\n}\n"}
{"id": 57161, "name": "Same fringe", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n", "C++": "#include <algorithm>\n#include <coroutine>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <variant>\n\nusing namespace std;\n\nclass BinaryTree\n{\n  \n  \n  \n  \n  using Node = tuple<BinaryTree, int, BinaryTree>;\n  unique_ptr<Node> m_tree;\n\npublic:\n  \n  BinaryTree() = default; \n  BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n  : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}\n  BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n  BinaryTree(BinaryTree&& leftChild, int value)\n  : BinaryTree(move(leftChild), value, BinaryTree{}){}\n  BinaryTree(int value, BinaryTree&& rightChild)\n  : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n  \n  explicit operator bool() const\n  {\n    return (bool)m_tree;\n  }\n\n  \n  int Value() const\n  {\n    return get<1>(*m_tree);\n  }\n\n  \n  const BinaryTree& LeftChild() const\n  {\n    return get<0>(*m_tree);\n  }\n\n  \n  const BinaryTree& RightChild() const\n  {\n    return get<2>(*m_tree);\n  }\n};\n\n\nstruct TreeWalker {\n  struct promise_type {\n    int val;\n\n    suspend_never initial_suspend() noexcept {return {};}\n    suspend_never return_void() noexcept {return {};}\n    suspend_always final_suspend() noexcept {return {};}\n    void unhandled_exception() noexcept { }\n\n    TreeWalker get_return_object() \n    {\n      return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};\n    }\n\n    suspend_always yield_value(int x) noexcept \n    {\n      val=x;\n      return {};\n    }\n  };\n\n  coroutine_handle<promise_type> coro;\n\n  TreeWalker(coroutine_handle<promise_type> h): coro(h) {}\n\n  ~TreeWalker()\n  {\n    if(coro) coro.destroy();\n  }\n\n  \n  class Iterator\n  {\n    const coroutine_handle<promise_type>* m_h = nullptr;\n\n  public:\n    Iterator() = default;\n    constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}\n\n    Iterator& operator++()\n    {\n      m_h->resume();\n      return *this;\n    }\n\n    Iterator operator++(int)\n    {\n      auto old(*this);\n      m_h->resume();\n      return old;\n    }\n\n    int operator*() const\n    {\n      return m_h->promise().val;\n    }\n\n    bool operator!=(monostate) const noexcept\n    {\n      return !m_h->done();\n      return m_h && !m_h->done();\n    }\n\n    bool operator==(monostate) const noexcept\n    {\n      return !operator!=(monostate{});\n    }\n  };\n\n  constexpr Iterator begin() const noexcept\n  {\n    return Iterator(&coro);\n  }\n\n  constexpr monostate end() const noexcept\n  {\n    return monostate{};\n  }\n};\n\n\nnamespace std {\n    template<>\n    class iterator_traits<TreeWalker::Iterator>\n    {\n    public:\n        using difference_type = std::ptrdiff_t;\n        using size_type = std::size_t;\n        using value_type = int;\n        using pointer = int*;\n        using reference = int&;\n        using iterator_category = std::input_iterator_tag;\n    };\n}\n\n\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    auto& left = tree.LeftChild();\n    auto& right = tree.RightChild();\n    if(!left && !right)\n    {\n      \n      co_yield tree.Value();\n    }\n\n    for(auto v : WalkFringe(left))\n    {\n      co_yield v;\n    }\n\n    for(auto v : WalkFringe(right))\n    {\n      co_yield v;\n    }\n  }\n  co_return;\n}\n\n\nvoid PrintTree(const BinaryTree& tree)\n{\n  if(tree)\n  {\n    cout << \"(\";\n    PrintTree(tree.LeftChild());\n    cout << tree.Value();\n    PrintTree(tree.RightChild());\n    cout <<\")\";\n  }\n}\n\n\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n  \n  auto walker1 = WalkFringe(tree1);\n  auto walker2 = WalkFringe(tree2);\n  \n  \n  bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n               walker2.begin(), walker2.end());\n  \n  \n  PrintTree(tree1);\n  cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n  PrintTree(tree2);\n  cout << \"\\n\";\n}\n\nint main()\n{\n  \n  BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n    BinaryTree{77, BinaryTree{9}}});\n  BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n    BinaryTree{3}, 77, BinaryTree{9}}});\n  \n  BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n  \n  Compare(tree1, tree2);\n  Compare(tree1, tree3);\n}\n"}
{"id": 57162, "name": "Peaceful chess queen armies", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nenum class Piece {\n    empty,\n    black,\n    white\n};\n\ntypedef std::pair<int, int> position;\n\nbool isAttacking(const position &queen, const position &pos) {\n    return queen.first == pos.first\n        || queen.second == pos.second\n        || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {\n    if (m == 0) {\n        return true;\n    }\n    bool placingBlack = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            auto pos = std::make_pair(i, j);\n            for (auto queen : pBlackQueens) {\n                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            for (auto queen : pWhiteQueens) {\n                if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n                    goto inner;\n                }\n            }\n            if (placingBlack) {\n                pBlackQueens.push_back(pos);\n                placingBlack = false;\n            } else {\n                pWhiteQueens.push_back(pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                pBlackQueens.pop_back();\n                pWhiteQueens.pop_back();\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        pBlackQueens.pop_back();\n    }\n    return false;\n}\n\nvoid printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {\n    std::vector<Piece> board(n * n);\n    std::fill(board.begin(), board.end(), Piece::empty);\n\n    for (auto &queen : blackQueens) {\n        board[queen.first * n + queen.second] = Piece::black;\n    }\n    for (auto &queen : whiteQueens) {\n        board[queen.first * n + queen.second] = Piece::white;\n    }\n\n    for (size_t i = 0; i < board.size(); ++i) {\n        if (i != 0 && i % n == 0) {\n            std::cout << '\\n';\n        }\n        switch (board[i]) {\n        case Piece::black:\n            std::cout << \"B \";\n            break;\n        case Piece::white:\n            std::cout << \"W \";\n            break;\n        case Piece::empty:\n        default:\n            int j = i / n;\n            int k = i - j * n;\n            if (j % 2 == k % 2) {\n                std::cout << \"x \";\n            } else {\n                std::cout << \"* \";\n            }\n            break;\n        }\n    }\n\n    std::cout << \"\\n\\n\";\n}\n\nint main() {\n    std::vector<position> nms = {\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    };\n\n    for (auto nm : nms) {\n        std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n        std::vector<position> blackQueens, whiteQueens;\n        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n            printBoard(nm.first, blackQueens, whiteQueens);\n        } else {\n            std::cout << \"No solution exists.\\n\\n\";\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 57163, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "C++": "while (true)\n  std::cout << \"SPAM\\n\";\n"}
{"id": 57164, "name": "Numbers with same digit set in base 10 and base 16", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n"}
{"id": 57165, "name": "Numbers with same digit set in base 10 and base 16", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <bitset>\n\nconst int LIMIT = 100000;\n\nstd::bitset<16> digitset(int num, int base) {\n    std::bitset<16> set;\n    for (; num; num /= base) set.set(num % base);\n    return set;\n}\n\nint main() {\n    int c = 0;\n    for (int i=0; i<LIMIT; i++) {\n        if (digitset(i,10) == digitset(i,16)) {\n            std::cout << std::setw(7) << i;\n            if (++c % 10 == 0) std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl;\n    return 0;\n}\n"}
{"id": 57166, "name": "Largest proper divisor of n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            return n / i\n        }\n    }\n    return 1\n}\n\nfunc main() {\n    fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n    fmt.Print(\" 1  \")\n    for n := 2; n <= 100; n++ {\n        if n%2 == 0 {\n            fmt.Printf(\"%2d  \", n/2)\n        } else {\n            fmt.Printf(\"%2d  \", largestProperDivisor(n))\n        }\n        if n%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint largest_proper_divisor(int n) {\n    assert(n > 0);\n    if ((n & 1) == 0)\n        return n >> 1;\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return n / p;\n    }\n    return 1;\n}\n\nint main() {\n    for (int n = 1; n < 101; ++n) {\n        std::cout << std::setw(2) << largest_proper_divisor(n)\n            << (n % 10 == 0 ? '\\n' : ' ');\n    }\n}\n"}
{"id": 57167, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 57168, "name": "Sum of first n cubes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n", "C++": "#include <array>\n#include <cstdio>\n#include <numeric>\n\nvoid PrintContainer(const auto& vec)\n{\n    int count = 0;\n    for(auto value : vec)\n    {\n        printf(\"%7d%c\", value, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n}\n\nint main()\n{\n    \n    auto cube = [](auto x){return x * x * x;};\n\n    \n    std::array<int, 50> a;\n    std::iota(a.begin(), a.end(), 0);\n\n    \n    \n    \n    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);\n    PrintContainer(a);    \n}\n"}
{"id": 57169, "name": "Test integerness", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n", "C++": "#include <complex>\n#include <math.h>\n#include <iostream>\n\ntemplate<class Type>\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);\n\ntemplate<class DigType>\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision<DigType>::GetEps());\n}\n\ntemplate<class DigType>\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate<class DigType>\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart<DigType>(value) - value);\n}\n\ntemplate<class Type>\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)         \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<type>(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(FractionPart<type>(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger<std::complex<type> >(const std::complex<type>& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual<type>(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate<class Type>\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex<unsigned int> ci1(2, 0);\n\tstd::complex<int> ci2(2, 4);\n\tstd::complex<int> ci3(-2, 4);\n\tstd::complex<unsigned short> cs1(2, 0);\n\tstd::complex<short> cs2(2, 4);\n\tstd::complex<short> cs3(-2, 4);\n\n\tstd::complex<double> cd1(2, 0);\n\tstd::complex<float> cf1(2, 4);\n\tstd::complex<double> cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision<float>::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n"}
{"id": 57170, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "C++": "system(\"pause\");\n"}
{"id": 57171, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 57172, "name": "Lucky and even lucky numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n    for i := 0; i < luckySize; i++ {\n        luckyOdd[i] = i*2 + 1\n        luckyEven[i] = i*2 + 2\n    }\n}\n\nfunc filterLuckyOdd() {\n    for n := 2; n < len(luckyOdd); n++ {\n        m := luckyOdd[n-1]\n        end := (len(luckyOdd)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyOdd[j:], luckyOdd[j+1:])\n            luckyOdd = luckyOdd[:len(luckyOdd)-1]\n        }\n    }\n}\n\nfunc filterLuckyEven() {\n    for n := 2; n < len(luckyEven); n++ {\n        m := luckyEven[n-1]\n        end := (len(luckyEven)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyEven[j:], luckyEven[j+1:])\n            luckyEven = luckyEven[:len(luckyEven)-1]\n        }\n    }\n}\n\nfunc printSingle(j int, odd bool) error {\n    if odd {\n        if j >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n    } else {\n        if j >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n    }\n    return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n    if odd {\n        if k >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyOdd[j-1 : k])\n    } else {\n        if k >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyEven[j-1 : k])\n    }\n    return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n    var r []int\n    if odd {\n        max := luckyOdd[len(luckyOdd)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyOdd {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    } else {\n        max := luckyEven[len(luckyEven)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyEven {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    }\n    return nil\n}\n\nfunc main() {\n    nargs := len(os.Args)\n    if nargs < 2 || nargs > 4 {\n        log.Fatal(\"there must be between 1 and 3 command line arguments\")\n    }\n    filterLuckyOdd()\n    filterLuckyEven()\n    j, err := strconv.Atoi(os.Args[1])\n    if err != nil || j < 1 {\n        log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n    }\n    if nargs == 2 {\n        if err := printSingle(j, true); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    if nargs == 3 {\n        k, err := strconv.Atoi(os.Args[2])\n        if err != nil {\n            log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n        }\n        if k >= 0 {\n            if j > k {\n                log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n            }\n            if err := printRange(j, k, true); err != nil {\n                log.Fatal(err)\n            }\n        } else {\n            l := -k\n            if j > l {\n                log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n            }\n            if err := printBetween(j, l, true); err != nil {\n                log.Fatal(err)\n            }\n        }\n        return\n    }\n\n    var odd bool\n    switch lucky := strings.ToLower(os.Args[3]); lucky {\n    case \"lucky\":\n        odd = true\n    case \"evenlucky\":\n        odd = false\n    default:\n        log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n    }\n    if os.Args[2] == \",\" {\n        if err := printSingle(j, odd); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    k, err := strconv.Atoi(os.Args[2])\n    if err != nil {\n        log.Fatal(\"second argument must be an integer or a comma\")\n    }\n    if k >= 0 {\n        if j > k {\n            log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n        }\n        if err := printRange(j, k, odd); err != nil {\n            log.Fatal(err)\n        }\n    } else {\n        l := -k\n        if j > l {\n            log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n        }\n        if err := printBetween(j, l, odd); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nconst int luckySize = 60000;\nstd::vector<int> luckyEven(luckySize);\nstd::vector<int> luckyOdd(luckySize);\n\nvoid init() {\n    for (int i = 0; i < luckySize; ++i) {\n        luckyEven[i] = i * 2 + 2;\n        luckyOdd[i] = i * 2 + 1;\n    }\n}\n\nvoid filterLuckyEven() {\n    for (size_t n = 2; n < luckyEven.size(); ++n) {\n        int m = luckyEven[n - 1];\n        int end = (luckyEven.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n            luckyEven.pop_back();\n        }\n    }\n}\n\nvoid filterLuckyOdd() {\n    for (size_t n = 2; n < luckyOdd.size(); ++n) {\n        int m = luckyOdd[n - 1];\n        int end = (luckyOdd.size() / m) * m - 1;\n        for (int j = end; j >= m - 1; j -= m) {\n            std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n            luckyOdd.pop_back();\n        }\n    }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n\n    if (even) {\n        size_t max = luckyEven.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    } else {\n        size_t max = luckyOdd.back();\n        if (j > max || k > max) {\n            std::cerr << \"At least one are is too big\\n\";\n            exit(EXIT_FAILURE);\n        }\n\n        std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n        std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n            return j <= n && n <= k;\n        });\n    }\n    std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n    std::ostream_iterator<int> out_it{ std::cout, \", \" };\n    if (even) {\n        if (k >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n    } else {\n        if (k >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n        std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n    }\n}\n\nvoid printSingle(size_t j, bool even) {\n    if (even) {\n        if (j >= luckyEven.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n    } else {\n        if (j >= luckyOdd.size()) {\n            std::cerr << \"The argument is too large\\n\";\n            exit(EXIT_FAILURE);\n        }\n        std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n    }\n}\n\nvoid help() {\n    std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"       argument(s)        |  what is displayed\\n\";\n    std::cout << \"==============================================\\n\";\n    std::cout << \"-j=m                      |  mth lucky number\\n\";\n    std::cout << \"-j=m  --lucky             |  mth lucky number\\n\";\n    std::cout << \"-j=m  --evenLucky         |  mth even lucky number\\n\";\n    std::cout << \"-j=m  -k=n                |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --lucky       |  mth through nth (inclusive) lucky numbers\\n\";\n    std::cout << \"-j=m  -k=n  --evenLucky   |  mth through nth (inclusive) even lucky numbers\\n\";\n    std::cout << \"-j=m  -k=-n               |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --lucky      |  all lucky numbers in the range [m, n]\\n\";\n    std::cout << \"-j=m  -k=-n  --evenLucky  |  all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n    bool evenLucky = false;\n    int j = 0;\n    int k = 0;\n\n    \n    if (argc < 2) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    bool good = false;\n    for (int i = 1; i < argc; ++i) {\n        if ('-' == argv[i][0]) {\n            if ('-' == argv[i][1]) {\n                \n                if (0 == strcmp(\"--lucky\", argv[i])) {\n                    evenLucky = false;\n                } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n                    evenLucky = true;\n                } else {\n                    std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n                    exit(EXIT_FAILURE);\n                }\n            } else {\n                \n                if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n                    good = true;\n                    j = atoi(&argv[i][3]);\n                } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n                    k = atoi(&argv[i][3]);\n                } else {\n                    std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n                    exit(EXIT_FAILURE);\n                }\n            }\n        } else {\n            std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n            exit(EXIT_FAILURE);\n        }\n    }\n    if (!good) {\n        help();\n        exit(EXIT_FAILURE);\n    }\n\n    init();\n    filterLuckyEven();\n    filterLuckyOdd();\n    if (k > 0) {\n        printRange(j, k, evenLucky);\n    } else if (k < 0) {\n        printBetween(j, -k, evenLucky);\n    } else {\n        printSingle(j, evenLucky);\n    }\n\n    return 0;\n}\n"}
{"id": 57173, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 57174, "name": "Superpermutation minimisation", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n\nconstexpr int MAX = 12;\n\nstatic std::vector<char> sp;\nstatic std::array<int, MAX> count;\nstatic int pos = 0;\n\nint factSum(int n) {\n    int s = 0;\n    int x = 0;\n    int f = 1;\n    while (x < n) {\n        f *= ++x;\n        s += f;\n    }\n    return s;\n}\n\nbool r(int n) {\n    if (n == 0) {\n        return false;\n    }\n    char c = sp[pos - n];\n    if (--count[n] == 0) {\n        count[n] = n;\n        if (!r(n - 1)) {\n            return false;\n        }\n    }\n    sp[pos++] = c;\n    return true;\n}\n\nvoid superPerm(int n) {\n    pos = n;\n    int len = factSum(n);\n    if (len > 0) {\n        sp.resize(len);\n    }\n    for (size_t i = 0; i <= n; i++) {\n        count[i] = i;\n    }\n    for (size_t i = 1; i <= n; i++) {\n        sp[i - 1] = '0' + i;\n    }\n    while (r(n)) {}\n}\n\nint main() {\n    for (size_t n = 0; n < MAX; n++) {\n        superPerm(n);\n        std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57175, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n"}
{"id": 57176, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 57177, "name": "Summarize and say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nstd::map<char, int> _map;\nstd::vector<std::string> _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n    _map.clear();\n    for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n        _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n    std::string z;\n    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n        char c = ( *i ).second + 48;\n        z.append( 1, c );\n        z.append( 1, i->first );\n    }\n\n    if( longest <= z.length() ) {\n        longest = z.length();\n        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n            _result.push_back( z );\n            make_sequence( z );\n        }\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> tests;\n    tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {\n        make_sequence( *i );\n        std::cout  << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {\n            std::cout << *j << \"\\n\";\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 57178, "name": "Spelling of ordinal numbers", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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 <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 57179, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 57180, "name": "Addition chains", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 57181, "name": "Numeric separator syntax", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n", "C++": "\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n    long long int a = 30'00'000;\n\n    std::cout <<\"And with the ' in C++ 14 : \"<< a << endl;\n\n    return 0;\n}\n"}
{"id": 57182, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n"}
{"id": 57183, "name": "Sparkline in unicode", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n"}
{"id": 57184, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 57185, "name": "Sunflower fractal", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n\nbool sunflower(const char* filename) {\n    std::ofstream out(filename);\n    if (!out)\n        return false;\n\n    constexpr int size = 600;\n    constexpr int seeds = 5 * size;\n    constexpr double pi = 3.14159265359;\n    constexpr double phi = 1.61803398875;\n    \n    out << \"<svg xmlns='http:\n    out << \"' height='\" << size << \"' style='stroke:gold'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << std::setprecision(2) << std::fixed;\n    for (int i = 1; i <= seeds; ++i) {\n        double r = 2 * std::pow(i, phi)/seeds;\n        double theta = 2 * pi * phi * i;\n        double x = r * std::sin(theta) + size/2;\n        double y = r * std::cos(theta) + size/2;\n        double radius = std::sqrt(i)/13;\n        out << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='\" << radius << \"'/>\\n\";\n    }\n    out << \"</svg>\\n\";\n    return true;\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" filename\\n\";\n        return EXIT_FAILURE;\n    }\n    if (!sunflower(argv[1])) {\n        std::cerr << \"image generation failed\\n\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57186, "name": "Vogel's approximation method", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <numeric>\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\n    return os << ']';\n}\n\nstd::vector<int> demand = { 30, 20, 70, 30, 60 };\nstd::vector<int> supply = { 50, 60, 50, 50 };\nstd::vector<std::vector<int>> costs = {\n    {16, 16, 13, 22, 17},\n    {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50},\n    {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector<bool> rowDone(nRows, false);\nstd::vector<bool> colDone(nCols, false);\nstd::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));\n\nstd::vector<int> diff(int j, int len, bool isRow) {\n    int min1 = INT_MAX;\n    int min2 = INT_MAX;\n    int minP = -1;\n    for (int i = 0; i < len; i++) {\n        if (isRow ? colDone[i] : rowDone[i]) {\n            continue;\n        }\n        int c = isRow\n            ? costs[j][i]\n            : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            minP = i;\n        } else if (c < min2) {\n            min2 = c;\n        }\n    }\n    return { min2 - min1, min1, minP };\n}\n\nstd::vector<int> maxPenalty(int len1, int len2, bool isRow) {\n    int md = INT_MIN;\n    int pc = -1;\n    int pm = -1;\n    int mc = -1;\n    for (int i = 0; i < len1; i++) {\n        if (isRow ? rowDone[i] : colDone[i]) {\n            continue;\n        }\n        std::vector<int> res = diff(i, len2, isRow);\n        if (res[0] > md) {\n            md = res[0];    \n            pm = i;         \n            mc = res[1];    \n            pc = res[2];    \n        }\n    }\n    return isRow\n        ? std::vector<int> { pm, pc, mc, md }\n    : std::vector<int>{ pc, pm, mc, md };\n}\n\nstd::vector<int> nextCell() {\n    auto res1 = maxPenalty(nRows, nCols, true);\n    auto res2 = maxPenalty(nCols, nRows, false);\n\n    if (res1[3] == res2[3]) {\n        return res1[2] < res2[2]\n            ? res1\n            : res2;\n    }\n    return res1[3] > res2[3]\n        ? res2\n        : res1;\n}\n\nint main() {\n    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n    int totalCost = 0;\n\n    while (supplyLeft > 0) {\n        auto cell = nextCell();\n        int r = cell[0];\n        int c = cell[1];\n\n        int quantity = std::min(demand[c], supply[r]);\n\n        demand[c] -= quantity;\n        if (demand[c] == 0) {\n            colDone[c] = true;\n        }\n\n        supply[r] -= quantity;\n        if (supply[r] == 0) {\n            rowDone[r] = true;\n        }\n\n        result[r][c] = quantity;\n        supplyLeft -= quantity;\n\n        totalCost += quantity * costs[r][c];\n    }\n\n    for (auto &a : result) {\n        std::cout << a << '\\n';\n    }\n\n    std::cout << \"Total cost: \" << totalCost;\n\n    return 0;\n}\n"}
{"id": 57187, "name": "Chemical calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57188, "name": "Permutations by swapping", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> UpTo(int n, int offset = 0)\n{\n\tvector<int> retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector<int> values_;\n\tvector<int> positions_;\t\n\tvector<bool> directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n"}
{"id": 57189, "name": "Minimum multiple of m where digital sum equals m", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n"}
{"id": 57190, "name": "Minimum multiple of m where digital sum equals m", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint digit_sum(int n) {\n    int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    for (int n = 1; n <= 70; ++n) {\n        for (int m = 1;; ++m) {\n            if (digit_sum(m * n) == n) {\n                std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n                break;\n            }\n        }\n    }\n}\n"}
{"id": 57191, "name": "Pythagorean quadruples", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n"}
{"id": 57192, "name": "Steady squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc contains(list []int, s int) bool {\n    for _, e := range list {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"Steady squares under 10,000:\")\n    finalDigits := []int{1, 5, 6}\n    for i := 1; i < 10000; i++ {\n        if !contains(finalDigits, i%10) {\n            continue\n        }\n        sq := i * i\n        sqs := strconv.Itoa(sq)\n        is := strconv.Itoa(i)\n        if strings.HasSuffix(sqs, is) {\n            fmt.Printf(\"%5s -> %10s\\n\", rcu.Commatize(i), rcu.Commatize(sq))\n        }\n    }\n}\n", "C++": "#include <iostream>\nusing namespace std;\n\nbool steady(int n) {\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main() {\n    for (int i = 1; i < 10000; i++)\n        if (steady(i)) printf(\"%4d^2 = %8d\\n\", i, i * i);\n}\n"}
{"id": 57193, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 57194, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 57195, "name": "Dice game probabilities", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n", "C++": "#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <map>\n\n\nstd::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {\n    std::map<uint32_t, uint32_t> result;\n    for (uint32_t i = 1; i <= faces; ++i)\n        result.emplace(i, 1);\n    for (uint32_t d = 2; d <= dice; ++d) {\n        std::map<uint32_t, uint32_t> tmp;\n        for (const auto& p : result) {\n            for (uint32_t i = 1; i <= faces; ++i)\n                tmp[p.first + i] += p.second;\n        }\n        tmp.swap(result);\n    }\n    return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n    auto totals1 = get_totals(dice1, faces1);\n    auto totals2 = get_totals(dice2, faces2);\n    double wins = 0;\n    for (const auto& p1 : totals1) {\n        for (const auto& p2 : totals2) {\n            if (p2.first >= p1.first)\n                break;\n            wins += p1.second * p2.second;\n        }\n    }\n    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n    return wins/total;\n}\n\nint main() {\n    std::cout << std::setprecision(10);\n    std::cout << probability(9, 4, 6, 6) << '\\n';\n    std::cout << probability(5, 10, 6, 7) << '\\n';\n    return 0;\n}\n"}
{"id": 57196, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n"}
{"id": 57197, "name": "First-class functions_Use numbers analogously", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  double x  = 2.0;\n  double xi = 0.5;\n  double y  = 4.0;\n  double yi = 0.25;\n  double z  = x + y;\n  double zi = 1.0 / ( x + y );\n\n  const std::array values{x, y, z};\n  const std::array inverses{xi, yi, zi};\n\n  auto multiplier = [](double a, double b)\n  {\n    return [=](double m){return a * b * m;};\n  };\n\n  for(size_t i = 0; i < values.size(); ++i)\n  {\n    auto new_function = multiplier(values[i], inverses[i]);\n    double value = new_function(i + 1.0);\n    std::cout << value << \"\\n\"; \n  }\n}\n"}
{"id": 57198, "name": "Sokoban", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <regex>\n#include <tuple>\n#include <set>\n#include <array>\nusing namespace std;\n\nclass Board\n{\npublic:\n  vector<vector<char>> sData, dData;\n  int px, py;\n\n  Board(string b)\n  {\n    regex pattern(\"([^\\\\n]+)\\\\n?\");\n    sregex_iterator end, iter(b.begin(), b.end(), pattern);\n    \n    int w = 0;\n    vector<string> data;\n    for(; iter != end; ++iter){\n      data.push_back((*iter)[1]);\n      w = max(w, (*iter)[1].length());\n    }\n\n    for(int v = 0; v < data.size(); ++v){\n      vector<char> sTemp, dTemp;\n      for(int u = 0; u < w; ++u){\n        if(u > data[v].size()){\n          sTemp.push_back(' ');\n          dTemp.push_back(' ');\n        }else{\n          char s = ' ', d = ' ', c = data[v][u];\n\n          if(c == '#')\n            s = '#';\n          else if(c == '.' || c == '*' || c == '+')\n            s = '.';\n\n          if(c == '@' || c == '+'){\n            d = '@';\n            px = u;\n            py = v;\n          }else if(c == '$' || c == '*')\n            d = '*';\n\n          sTemp.push_back(s);\n          dTemp.push_back(d);\n        }\n      }\n\n      sData.push_back(sTemp);\n      dData.push_back(dTemp);\n    }\n  }\n\n  bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') \n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n\n    return true;\n  }\n\n  bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)\n  {\n    if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')\n      return false;\n\n    data[y][x] = ' ';\n    data[y+dy][x+dx] = '@';\n    data[y+2*dy][x+2*dx] = '*';\n\n    return true;\n  }\n\n  bool isSolved(const vector<vector<char>> &data)\n  {\n    for(int v = 0; v < data.size(); ++v)\n      for(int u = 0; u < data[v].size(); ++u)\n        if((sData[v][u] == '.') ^ (data[v][u] == '*'))\n          return false;\n    return true;\n  }\n\n  string solve()\n  {\n    set<vector<vector<char>>> visited;\n    queue<tuple<vector<vector<char>>, string, int, int>> open;\n\n    open.push(make_tuple(dData, \"\", px, py));\n    visited.insert(dData);\n\n    array<tuple<int, int, char, char>, 4> dirs;\n    dirs[0] = make_tuple(0, -1, 'u', 'U');\n    dirs[1] = make_tuple(1, 0, 'r', 'R');\n    dirs[2] = make_tuple(0, 1, 'd', 'D');\n    dirs[3] = make_tuple(-1, 0, 'l', 'L');\n\n    while(open.size() > 0){\n      vector<vector<char>> temp, cur = get<0>(open.front());\n      string cSol = get<1>(open.front());\n      int x = get<2>(open.front());\n      int y = get<3>(open.front());\n      open.pop();\n\n      for(int i = 0; i < 4; ++i){\n        temp = cur;\n        int dx = get<0>(dirs[i]);\n        int dy = get<1>(dirs[i]);\n\n        if(temp[y+dy][x+dx] == '*'){\n          if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n            if(isSolved(temp))\n              return cSol + get<3>(dirs[i]);\n            open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));\n            visited.insert(temp);\n          }\n        }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){\n          if(isSolved(temp))\n            return cSol + get<2>(dirs[i]);\n          open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));\n          visited.insert(temp);\n        }\n      }\n    }\n\n    return \"No solution\";\n  }\n};\n\nint main()\n{\n  string level =\n    \"#######\\n\"\n    \"#     #\\n\"\n    \"#     #\\n\"\n    \"#. #  #\\n\"\n    \"#. $$ #\\n\"\n    \"#.$$  #\\n\"\n    \"#.#  @#\\n\"\n    \"#######\";\n\n  Board b(level);\n\n  cout << level << endl << endl << b.solve() << endl;\n  return 0;\n}\n"}
{"id": 57199, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 57200, "name": "Almkvist-Giullera formula for pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 57201, "name": "Practical numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n"}
{"id": 57202, "name": "Practical numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n"}
{"id": 57203, "name": "Consecutive primes with ascending or descending differences", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n    pd := 0\n    longSeqs := [][]int{{2}}\n    currSeq := []int{2}\n    for i := 1; i < len(primes); i++ {\n        d := primes[i] - primes[i-1]\n        if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n            if len(currSeq) > len(longSeqs[0]) {\n                longSeqs = [][]int{currSeq}\n            } else if len(currSeq) == len(longSeqs[0]) {\n                longSeqs = append(longSeqs, currSeq)\n            }\n            currSeq = []int{primes[i-1], primes[i]}\n        } else {\n            currSeq = append(currSeq, primes[i])\n        }\n        pd = d\n    }\n    if len(currSeq) > len(longSeqs[0]) {\n        longSeqs = [][]int{currSeq}\n    } else if len(currSeq) == len(longSeqs[0]) {\n        longSeqs = append(longSeqs, currSeq)\n    }\n    fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n    for _, ls := range longSeqs {\n        var diffs []int\n        for i := 1; i < len(ls); i++ {\n            diffs = append(diffs, ls[i]-ls[i-1])\n        }\n        for i := 0; i < len(ls)-1; i++ {\n            fmt.Print(ls[i], \" (\", diffs[i], \") \")\n        }\n        fmt.Println(ls[len(ls)-1])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    fmt.Println(\"For primes < 1 million:\\n\")\n    for _, dir := range []string{\"ascending\", \"descending\"} {\n        longestSeq(dir)\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <vector>\n#include <primesieve.hpp>\n\nvoid print_diffs(const std::vector<uint64_t>& vec) {\n    for (size_t i = 0, n = vec.size(); i != n; ++i) {\n        if (i != 0)\n            std::cout << \" (\" << vec[i] - vec[i - 1] << \") \";\n        std::cout << vec[i];\n    }\n    std::cout << '\\n';\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::vector<uint64_t> asc, desc;\n    std::vector<std::vector<uint64_t>> max_asc, max_desc;\n    size_t max_asc_len = 0, max_desc_len = 0;\n    uint64_t prime;\n    const uint64_t limit = 1000000;\n    for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {\n        size_t alen = asc.size();\n        if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])\n            asc.erase(asc.begin(), asc.end() - 1);\n        asc.push_back(prime);\n        if (asc.size() >= max_asc_len) {\n            if (asc.size() > max_asc_len) {\n                max_asc_len = asc.size();\n                max_asc.clear();\n            }\n            max_asc.push_back(asc);\n        }\n        size_t dlen = desc.size();\n        if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])\n            desc.erase(desc.begin(), desc.end() - 1);\n        desc.push_back(prime);\n        if (desc.size() >= max_desc_len) {\n            if (desc.size() > max_desc_len) {\n                max_desc_len = desc.size();\n                max_desc.clear();\n            }\n            max_desc.push_back(desc);\n        }\n    }\n    std::cout << \"Longest run(s) of ascending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_asc)\n        print_diffs(v);\n    std::cout << \"\\nLongest run(s) of descending prime gaps up to \" << limit << \":\\n\";\n    for (const auto& v : max_desc)\n        print_diffs(v);\n    return 0;\n}\n"}
{"id": 57204, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 57205, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 57206, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <primesieve.hpp>\n\nclass erdos_prime_generator {\npublic:\n    erdos_prime_generator() {}\n    uint64_t next();\nprivate:\n    bool erdos(uint64_t p) const;\n    primesieve::iterator iter_;\n    std::set<uint64_t> primes_;\n};\n\nuint64_t erdos_prime_generator::next() {\n    uint64_t prime;\n    for (;;) {\n        prime = iter_.next_prime();\n        primes_.insert(prime);\n        if (erdos(prime))\n            break;\n    }\n    return prime;\n}\n\nbool erdos_prime_generator::erdos(uint64_t p) const {\n    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {\n        if (primes_.find(p - f) != primes_.end())\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    erdos_prime_generator epgen;\n    const int max_print = 2500;\n    const int max_count = 7875;\n    uint64_t p;\n    std::wcout << L\"Erd\\x151s primes less than \" << max_print << L\":\\n\";\n    for (int count = 1; count <= max_count; ++count) {\n        p = epgen.next();\n        if (p < max_print)\n            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::wcout << L\"\\n\\nThe \" << max_count << L\"th Erd\\x151s prime is \" << p << L\".\\n\";\n    return 0;\n}\n"}
{"id": 57207, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 57208, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <bitset>\n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector<string>& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast<int>(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector<node>(len, node({ 0, 0 }));\n\t\tweHave = vector<bool>(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector<int> dx = vector<int>({ -1, 1, 0, 0 });\n\tvector<int> dy = vector<int>({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector<node> arr;\n\tvector<bool> weHave;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t\n\t\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector<string> puzz;\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \"   \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"}
{"id": 57209, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 57210, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "C++": "#include <iostream>\n\n\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n\nauto Successor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(f(x));\n        };\n    };\n}\n\n\nauto Add(auto a, auto b) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(f)(b(f)(x));\n        };\n    };\n}\n\n\nauto Multiply(auto a, auto b) {\n    return [=](auto f) {\n        return a(b(f));\n    };\n}\n\n\nauto Exp(auto a, auto b) {\n    return b(a);\n}\n\n\nauto IsZero(auto a){\n    return a([](auto){ return False; })(True);\n}\n\n\nauto Predecessor(auto a) {\n    return [=](auto f) {\n        return [=](auto x) {\n            return a(\n                [=](auto g) {\n                    return [=](auto h){\n                        return h(g(f));\n                    };\n                }\n             )([=](auto){ return x; })([](auto y){ return y; });\n        };\n    };\n}\n\n\nauto Subtract(auto a, auto b) {\n    {\n        return b([](auto c){ return Predecessor(c); })(a);\n    };\n}\n\nnamespace\n{\n    \n\n    \n    auto Divr(decltype(Zero), auto) {\n        return Zero;\n    }\n\n    \n    auto Divr(auto a, auto b) {\n        auto a_minus_b = Subtract(a, b);\n        auto isZero = IsZero(a_minus_b);\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        return isZero\n                    (Zero)\n                    (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n    }\n}\n\n\nauto Divide(auto a, auto b) {\n    return Divr(Successor(a), b);\n}\n\n\ntemplate <int N> constexpr auto ToChurch() {\n    if constexpr(N<=0) return Zero;\n    else return Successor(ToChurch<N-1>());\n}\n\n\nint ToInt(auto church) {\n    return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n    \n    auto three = Successor(Successor(Successor(Zero)));\n    auto four = Successor(three);\n    auto six = ToChurch<6>();\n    auto ten = ToChurch<10>();\n    auto thousand = Exp(ten, three);\n\n    std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n    std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n    std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n    std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n    std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n    std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n    std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n    std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n    std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n    auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n    auto looloolool = Successor(looloolooo);\n    std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n    \n    \n    std::cout << \"\\n golden ratio = \" <<\n        thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"}
{"id": 57211, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 57212, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 57213, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] =  2;\n\tdx[2] =  2; dy[2] = -2; dx[3] =  2; dy[3] =  2;\n\tdx[4] = -3; dy[4] =  0; dx[5] =  3; dy[5] =  0; \n\tdx[6] =  0; dy[6] = -3; dx[7] =  0; dy[7] =  3;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t    x = a; y = b; z = 1;\n\t\t    arr[a + wid * b].val = z;\n\t\t    return;\n\t\t}\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n\t}\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 57214, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 57215, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "C++": "\n\ntemplate<uint _N, uint _G> class Nonogram {\n  enum class ng_val : char {X='#',B='.',V='?'};\n  template<uint _NG> struct N {\n    N() {}\n    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n    std::bitset<_NG> X, B, T, Tx, Tb;\n    std::vector<int> ng;\n    int En, gNG;\n    void        fn (const int n,const int i,const int g,const int e,const int l){ \n      if (fe(g,l,false) and fe(g+l,e,true)){\n      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n      else {\n        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n      }}\n      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n    }\n    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n    inline bool fe (const int n,const int i, const bool g){\n      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;\n      return true;\n    }\n    int         fl (){\n      if (En == 1) return 1;\n      Tx.set(); Tb.set(); En=0;\n      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);\n      return En;\n    }}; \n  std::vector<N<_G>> ng;\n  std::vector<N<_N>> gn;\n  int En, zN, zG;\n  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));\n    for (int i=0; i<zN; i++) {\n      ng.push_back(N<_G>(n[i],zG));\n      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);\n    }}\n  bool solve(){\n    int i{}, g{};  \n    for (int l = 0; l<zN; l++) {\n      if ((g = ng[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);\n    }\n    for (int l = 0; l<zG; l++) {\n      if ((g = gn[l].fl()) == 0) return false; else i+=g;\n      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);\n    }\n    if (i == En)    return false; else En = i;\n    if (i == zN+zG) return true;  else return solve();\n  }\n  const std::string toStr() const {\n    std::ostringstream n;\n    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}\n    return n.str();\n  }};\n"}
{"id": 57216, "name": "Word search", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n"}
{"id": 57217, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 57218, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 57219, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 57220, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n"}
{"id": 57221, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "C++": "#include <string>\n#include <fstream>\n#include <boost/serialization/string.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <iostream>\n\nclass Employee {\npublic :   \n   Employee( ) { }\n\n   Employee ( const std::string &dep , const std::string &namen ) \n      : department( dep ) , name( namen ) {\n\t my_id = count++ ;\n      }\n\n   std::string getName( ) const {\n      return name ;\n   }\n\n   std::string getDepartment( ) const {\n      return department ;\n   }\n\n   int getId( ) const {\n      return my_id ;\n   }\n\n   void setDepartment( const std::string &dep ) {\n      department.assign( dep ) ;\n   }\n\n   virtual void print( ) {\n      std::cout << \"Name: \" << name << '\\n' ;\n      std::cout << \"Id: \" << my_id << '\\n' ;\n      std::cout << \"Department: \" << department << '\\n' ;\n   }\n\n   virtual ~Employee( ) { } \n   static int count ;\nprivate :\n   std::string name ;\n   std::string department ;\n   int my_id ;\n   friend class boost::serialization::access ;\n\n   template <class Archive>\n      void serialize( Archive &ar, const unsigned int version ) {\n\t ar & my_id ;\n\t ar & name ;\n\t ar & department ;\n      }\n\n} ;\n\nclass Worker : public Employee {\npublic :\n   Worker( const std::string & dep, const std::string &namen ,\n\t double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }\n\n   Worker( ) { }\n\n   double getSalary( ) {\n      return salary ;\n   }\n\n   void setSalary( double pay ) {\n      if ( pay > 0 ) \n\t salary = pay ;\n   }\n   \n   virtual void print( ) {\n      Employee::print( ) ;\n      std::cout << \"wage per hour: \" << salary << '\\n' ;\n   }\nprivate :\n   double salary ;\n   friend class boost::serialization::access ;\n   template <class Archive>\n      void serialize ( Archive & ar, const unsigned int version ) {\n\t ar & boost::serialization::base_object<Employee>( *this ) ;\n\t ar & salary ;\n      }\n} ;\n  \nint Employee::count = 0 ;\n\nint main( ) {\n   std::ofstream storefile( \"/home/ulrich/objects.dat\"  ) ; \n   const Employee emp1( \"maintenance\" , \"Fritz Schmalstieg\"  ) ;\n   const Employee emp2( \"maintenance\" , \"John Berry\" ) ;\n   const Employee emp3( \"repair\" , \"Pawel Lichatschow\" ) ;\n   const Employee emp4( \"IT\" , \"Marian Niculescu\" ) ;\n   const Worker worker1( \"maintenance\" , \"Laurent Le Chef\" , 20 ) ;\n   const Worker worker2 ( \"IT\" , \"Srinivan Taraman\" , 55.35 ) ;\n   boost::archive::text_oarchive oar ( storefile ) ;\n   oar << emp1 ; \n   oar << emp2 ;\n   oar << emp3 ;\n   oar << emp4 ;\n   oar << worker1 ;\n   oar << worker2 ;\n   storefile.close( ) ;\n   std::cout << \"Reading out the data again\\n\" ;\n   Employee e1 , e2 , e3 , e4 ; \n   Worker w1, w2 ; \n   std::ifstream sourcefile( \"/home/ulrich/objects.dat\"  ) ;\n   boost::archive::text_iarchive iar( sourcefile ) ;\n   iar >> e1 >> e2 >> e3 >> e4 ; \n   iar >> w1 >> w2 ;\n   sourcefile.close( ) ;\n   std::cout << \"And here are the data after deserialization!( abridged):\\n\" ;\n   e1.print( ) ;\n   e3.print( ) ;\n   w2.print( ) ;\n   return 0 ;\n}\n"}
{"id": 57222, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 57223, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 57224, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n"}
{"id": 57225, "name": "Zumkeller numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n"}
{"id": 57226, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 57227, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 57228, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 57229, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 57230, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 57231, "name": "Halt and catch fire", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n"}
{"id": 57232, "name": "Halt and catch fire", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n", "C++": "#include <stdexcept>\nint main()\n{\n    throw std::runtime_error(\"boom\");\n}\n"}
{"id": 57233, "name": "Constrained genericity", "Go": "type eatable interface {\n    eat()\n}\n", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n"}
{"id": 57234, "name": "Constrained genericity", "Go": "type eatable interface {\n    eat()\n}\n", "C++": "template<typename T> \nstruct can_eat       \n{\n  private:\n    template<typename U, void (U::*)()> struct SFINAE {};\n    template<typename U> static char Test(SFINAE<U, &U::eat>*);\n    template<typename U> static int Test(...);\n  public:\n    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nstruct potato\n{ void eat(); };\n\nstruct brick\n{};\n\ntemplate<typename T>\nclass FoodBox\n{\n    \n    static_assert(can_eat<T>::value, \"Only edible items are allowed in foodbox\");\n\n    \n};\n\nint main()\n{\n    FoodBox<potato> lunch;\n\n    \n    \n}\n"}
{"id": 57235, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n", "C++": "#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\nclass markov {\npublic:\n    void create( std::string& file, unsigned int keyLen, unsigned int words ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );\n        f.close();\n        if( fileBuffer.length() < 1 ) return;\n        createDictionary( keyLen );\n        createText( words - keyLen );\n    }\nprivate:\n    void createText( int w ) {\n        std::string key, first, second;\n        size_t next;\n        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();\n        std::advance( it, rand() % dictionary.size() );\n        key = ( *it ).first;\n        std::cout << key;\n        while( true ) {\n            std::vector<std::string> d = dictionary[key];\n            if( d.size() < 1 ) break;\n            second = d[rand() % d.size()];\n            if( second.length() < 1 ) break;\n            std::cout << \" \" << second;\n            if( --w < 0 ) break;\n            next = key.find_first_of( 32, 0 );\n            first = key.substr( next + 1 );\n            key = first + \" \" + second;\n        }\n        std::cout << \"\\n\";\n    }\n    void createDictionary( unsigned int kl ) {\n        std::string w1, key;\n        size_t wc = 0, pos, next;\n        next = fileBuffer.find_first_not_of( 32, 0 );\n        if( next == std::string::npos ) return;\n        while( wc < kl ) {\n            pos = fileBuffer.find_first_of( ' ', next );\n            w1 = fileBuffer.substr( next, pos - next );\n            key += w1 + \" \";\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            wc++;\n        }\n        key = key.substr( 0, key.size() - 1 );\n        while( true ) {\n            next = fileBuffer.find_first_not_of( 32, pos + 1 );\n            if( next == std::string::npos ) return;\n            pos = fileBuffer.find_first_of( 32, next );\n            w1 = fileBuffer.substr( next, pos - next );\n            if( w1.size() < 1 ) break;\n            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) \n                dictionary[key].push_back( w1 );\n            key = key.substr( key.find_first_of( 32 ) + 1 ) + \" \" + w1;\n        }\n    }\n    std::string fileBuffer;\n    std::map<std::string, std::vector<std::string> > dictionary;\n};\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    markov m;\n    m.create( std::string( \"alice_oz.txt\" ), 3, 200 );\n    return 0;\n}\n"}
{"id": 57236, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n"}
{"id": 57237, "name": "Geometric algebra", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n"}
{"id": 57238, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 57239, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <vector>\n\nstruct Node {\n    std::string sub = \"\";   \n    std::vector<int> ch;    \n\n    Node() {\n        \n    }\n\n    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {\n        ch.insert(ch.end(), children);\n    }\n};\n\nstruct SuffixTree {\n    std::vector<Node> nodes;\n\n    SuffixTree(const std::string& str) {\n        nodes.push_back(Node{});\n        for (size_t i = 0; i < str.length(); i++) {\n            addSuffix(str.substr(i));\n        }\n    }\n\n    void visualize() {\n        if (nodes.size() == 0) {\n            std::cout << \"<empty>\\n\";\n            return;\n        }\n\n        std::function<void(int, const std::string&)> f;\n        f = [&](int n, const std::string & pre) {\n            auto children = nodes[n].ch;\n            if (children.size() == 0) {\n                std::cout << \"- \" << nodes[n].sub << '\\n';\n                return;\n            }\n            std::cout << \"+ \" << nodes[n].sub << '\\n';\n\n            auto it = std::begin(children);\n            if (it != std::end(children)) do {\n                if (std::next(it) == std::end(children)) break;\n                std::cout << pre << \"+-\";\n                f(*it, pre + \"| \");\n                it = std::next(it);\n            } while (true);\n\n            std::cout << pre << \"+-\";\n            f(children[children.size() - 1], pre + \"  \");\n        };\n\n        f(0, \"\");\n    }\n\nprivate:\n    void addSuffix(const std::string & suf) {\n        int n = 0;\n        size_t i = 0;\n        while (i < suf.length()) {\n            char b = suf[i];\n            int x2 = 0;\n            int n2;\n            while (true) {\n                auto children = nodes[n].ch;\n                if (x2 == children.size()) {\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(suf.substr(i), {}));\n                    nodes[n].ch.push_back(n2);\n                    return;\n                }\n                n2 = children[x2];\n                if (nodes[n2].sub[0] == b) {\n                    break;\n                }\n                x2++;\n            }\n            \n            auto sub2 = nodes[n2].sub;\n            size_t j = 0;\n            while (j < sub2.size()) {\n                if (suf[i + j] != sub2[j]) {\n                    \n                    auto n3 = n2;\n                    \n                    n2 = nodes.size();\n                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));\n                    nodes[n3].sub = sub2.substr(j); \n                    nodes[n].ch[x2] = n2;\n                    break; \n                }\n                j++;\n            }\n            i += j; \n            n = n2; \n        }\n    }\n};\n\nint main() {\n    SuffixTree(\"banana$\").visualize();\n}\n"}
{"id": 57240, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n"}
{"id": 57241, "name": "Define a primitive data type", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n"}
{"id": 57242, "name": "AVL tree", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n"}
{"id": 57243, "name": "AVL tree", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\n\ntemplate <class T>\nclass AVLnode {\npublic:\n    T key;\n    int balance;\n    AVLnode *left, *right, *parent;\n\n    AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n                        left(NULL), right(NULL) {}\n\n    ~AVLnode() {\n        delete left;\n        delete right;\n    }\n};\n\n\ntemplate <class T>\nclass AVLtree {\npublic:\n    AVLtree(void);\n    ~AVLtree(void);\n    bool insert(T key);\n    void deleteKey(const T key);\n    void printBalance();\n\nprivate:\n    AVLnode<T> *root;\n\n    AVLnode<T>* rotateLeft          ( AVLnode<T> *a );\n    AVLnode<T>* rotateRight         ( AVLnode<T> *a );\n    AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );\n    AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );\n    void rebalance                  ( AVLnode<T> *n );\n    int height                      ( AVLnode<T> *n );\n    void setBalance                 ( AVLnode<T> *n );\n    void printBalance               ( AVLnode<T> *n );\n};\n\n\ntemplate <class T>\nvoid AVLtree<T>::rebalance(AVLnode<T> *n) {\n    setBalance(n);\n\n    if (n->balance == -2) {\n        if (height(n->left->left) >= height(n->left->right))\n            n = rotateRight(n);\n        else\n            n = rotateLeftThenRight(n);\n    }\n    else if (n->balance == 2) {\n        if (height(n->right->right) >= height(n->right->left))\n            n = rotateLeft(n);\n        else\n            n = rotateRightThenLeft(n);\n    }\n\n    if (n->parent != NULL) {\n        rebalance(n->parent);\n    }\n    else {\n        root = n;\n    }\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {\n    AVLnode<T> *b = a->right;\n    b->parent = a->parent;\n    a->right = b->left;\n\n    if (a->right != NULL)\n        a->right->parent = a;\n\n    b->left = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {\n    AVLnode<T> *b = a->left;\n    b->parent = a->parent;\n    a->left = b->right;\n\n    if (a->left != NULL)\n        a->left->parent = a;\n\n    b->right = a;\n    a->parent = b;\n\n    if (b->parent != NULL) {\n        if (b->parent->right == a) {\n            b->parent->right = b;\n        }\n        else {\n            b->parent->left = b;\n        }\n    }\n\n    setBalance(a);\n    setBalance(b);\n    return b;\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {\n    n->left = rotateLeft(n->left);\n    return rotateRight(n);\n}\n\ntemplate <class T>\nAVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {\n    n->right = rotateRight(n->right);\n    return rotateLeft(n);\n}\n\ntemplate <class T>\nint AVLtree<T>::height(AVLnode<T> *n) {\n    if (n == NULL)\n        return -1;\n    return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate <class T>\nvoid AVLtree<T>::setBalance(AVLnode<T> *n) {\n    n->balance = height(n->right) - height(n->left);\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance(AVLnode<T> *n) {\n    if (n != NULL) {\n        printBalance(n->left);\n        std::cout << n->balance << \" \";\n        printBalance(n->right);\n    }\n}\n\ntemplate <class T>\nAVLtree<T>::AVLtree(void) : root(NULL) {}\n\ntemplate <class T>\nAVLtree<T>::~AVLtree(void) {\n    delete root;\n}\n\ntemplate <class T>\nbool AVLtree<T>::insert(T key) {\n    if (root == NULL) {\n        root = new AVLnode<T>(key, NULL);\n    }\n    else {\n        AVLnode<T>\n            *n = root,\n            *parent;\n\n        while (true) {\n            if (n->key == key)\n                return false;\n\n            parent = n;\n\n            bool goLeft = n->key > key;\n            n = goLeft ? n->left : n->right;\n\n            if (n == NULL) {\n                if (goLeft) {\n                    parent->left = new AVLnode<T>(key, parent);\n                }\n                else {\n                    parent->right = new AVLnode<T>(key, parent);\n                }\n\n                rebalance(parent);\n                break;\n            }\n        }\n    }\n\n    return true;\n}\n\ntemplate <class T>\nvoid AVLtree<T>::deleteKey(const T delKey) {\n    if (root == NULL)\n        return;\n\n    AVLnode<T>\n        *n       = root,\n        *parent  = root,\n        *delNode = NULL,\n        *child   = root;\n\n    while (child != NULL) {\n        parent = n;\n        n = child;\n        child = delKey >= n->key ? n->right : n->left;\n        if (delKey == n->key)\n            delNode = n;\n    }\n\n    if (delNode != NULL) {\n        delNode->key = n->key;\n\n        child = n->left != NULL ? n->left : n->right;\n\n        if (root->key == delKey) {\n            root = child;\n        }\n        else {\n            if (parent->left == n) {\n                parent->left = child;\n            }\n            else {\n                parent->right = child;\n            }\n\n            rebalance(parent);\n        }\n    }\n}\n\ntemplate <class T>\nvoid AVLtree<T>::printBalance() {\n    printBalance(root);\n    std::cout << std::endl;\n}\n\nint main(void)\n{\n    AVLtree<int> t;\n\n    std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n    for (int i = 1; i <= 10; ++i)\n        t.insert(i);\n\n    std::cout << \"Printing balance: \";\n    t.printBalance();\n}\n"}
{"id": 57244, "name": "Arithmetic derivative", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc D(n float64) float64 {\n    if n < 0 {\n        return -D(-n)\n    }\n    if n < 2 {\n        return 0\n    }\n    var f []int\n    if n < 1e19 {\n        f = rcu.PrimeFactors(int(n))\n    } else {\n        g := int(n / 100)\n        f = rcu.PrimeFactors(g)\n        f = append(f, []int{2, 2, 5, 5}...)\n    }\n    c := len(f)\n    if c == 1 {\n        return 1\n    }\n    if c == 2 {\n        return float64(f[0] + f[1])\n    }\n    d := n / float64(f[0])\n    return D(d)*float64(f[0]) + d\n}\n\nfunc main() {\n    ad := make([]int, 200)\n    for n := -99; n < 101; n++ {\n        ad[n+99] = int(D(float64(n)))\n    }\n    rcu.PrintTable(ad, 10, 4, false)\n    fmt.Println()\n    pow := 1.0\n    for m := 1; m < 21; m++ {\n        pow *= 10\n        fmt.Printf(\"D(10^%-2d) / 7 = %.0f\\n\", m, D(pow)/7)\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\ntemplate <typename IntegerType>\nIntegerType arithmetic_derivative(IntegerType n) {\n    bool negative = n < 0;\n    if (negative)\n        n = -n;\n    if (n < 2)\n        return 0;\n    IntegerType sum = 0, count = 0, m = n;\n    while ((m & 1) == 0) {\n        m >>= 1;\n        count += n;\n    }\n    if (count > 0)\n        sum += count / 2;\n    for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {\n        count = 0;\n        while (m % p == 0) {\n            m /= p;\n            count += n;\n        }\n        if (count > 0)\n            sum += count / p;\n        sq += (p + 1) << 2;\n    }\n    if (m > 1)\n        sum += n / m;\n    if (negative)\n        sum = -sum;\n    return sum;\n}\n\nint main() {\n    using boost::multiprecision::int128_t;\n\n    for (int n = -99, i = 0; n <= 100; ++n, ++i) {\n        std::cout << std::setw(4) << arithmetic_derivative(n)\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    int128_t p = 10;\n    std::cout << '\\n';\n    for (int i = 0; i < 20; ++i, p *= 10) {\n        std::cout << \"D(10^\" << std::setw(2) << i + 1\n                  << \") / 7 = \" << arithmetic_derivative(p) / 7 << '\\n';\n    }\n}\n"}
{"id": 57245, "name": "Permutations with some identical elements", "Go": "package main\n\nimport \"fmt\"\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 createSlice(nums []int, charSet string) []byte {\n    var chars []byte\n    for i := 0; i < len(nums); i++ {\n        for j := 0; j < nums[i]; j++ {\n            chars = append(chars, charSet[i])\n        }\n    }\n    return chars\n}\n\nfunc main() {\n    var res, res2, res3 []string\n    nums := []int{2, 1}\n    s := createSlice(nums, \"12\")\n    findPerms(s, 0, len(s), &res)\n    fmt.Println(res)\n    fmt.Println()\n\n    nums = []int{2, 3, 1}\n    s = createSlice(nums, \"123\")\n    findPerms(s, 0, len(s), &res2)\n    fmt.Println(res2)\n    fmt.Println()\n\n    s = createSlice(nums, \"ABC\")\n    findPerms(s, 0, len(s), &res3)\n    fmt.Println(res3)\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n    std::string str(\"AABBBC\");\n    int count = 0;\n    do {\n        std::cout << str << (++count % 10 == 0 ? '\\n' : ' ');\n    } while (std::next_permutation(str.begin(), str.end()));\n}\n"}
{"id": 57246, "name": "Penrose tiling", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\ntype tiletype int\n\nconst (\n    kite tiletype = iota\n    dart\n)\n\ntype tile struct {\n    tt          tiletype\n    x, y        float64\n    angle, size float64\n}\n\nvar gr = (1 + math.Sqrt(5)) / 2 \n\nconst theta = math.Pi / 5 \n\nfunc setupPrototiles(w, h int) []tile {\n    var proto []tile\n    \n    for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {\n        ww := float64(w / 2)\n        hh := float64(h / 2)\n        proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})\n    }\n    return proto\n}\n\nfunc distinctTiles(tls []tile) []tile {\n    tileset := make(map[tile]bool)\n    for _, tl := range tls {\n        tileset[tl] = true\n    }\n    distinct := make([]tile, len(tileset))\n    for tl, _ := range tileset {\n        distinct = append(distinct, tl)\n    }\n    return distinct\n}\n\nfunc deflateTiles(tls []tile, gen int) []tile {\n    if gen <= 0 {\n        return tls\n    }\n    var next []tile\n    for _, tl := range tls {\n        x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr\n        var nx, ny float64\n        if tl.tt == dart {\n            next = append(next, tile{kite, x, y, a + 5*theta, size})\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                nx = x + math.Cos(a-4*theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-4*theta*sign)*gr*tl.size\n                next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})\n            }\n        } else {\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                next = append(next, tile{dart, x, y, a - 4*theta*sign, size})\n                nx = x + math.Cos(a-theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-theta*sign)*gr*tl.size\n                next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})\n            }\n        }\n    }\n    \n    tls = distinctTiles(next)\n    return deflateTiles(tls, gen-1)\n}\n\nfunc drawTiles(dc *gg.Context, tls []tile) {\n    dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}\n    for _, tl := range tls {\n        angle := tl.angle - theta\n        dc.MoveTo(tl.x, tl.y)\n        ord := tl.tt\n        for i := 0; i < 3; i++ {\n            x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)\n            y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)\n            dc.LineTo(x, y)\n            angle += theta\n        }\n        dc.ClosePath()\n        if ord == kite {\n            dc.SetHexColor(\"FFA500\") \n        } else {\n            dc.SetHexColor(\"FFFF00\") \n        }\n        dc.FillPreserve()\n        dc.SetHexColor(\"A9A9A9\") \n        dc.SetLineWidth(1)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    w, h := 700, 450\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    tiles := deflateTiles(setupPrototiles(w, h), 5)\n    drawTiles(dc, tiles)\n    dc.SavePNG(\"penrose_tiling.png\")\n}\n", "C++": "#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <tuple>\n\nint main() {\n    std::ofstream out(\"penrose_tiling.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string penrose(\"[N]++[N]++[N]++[N]++[N]\");\n    for (int i = 1; i <= 4; ++i) {\n        std::string next;\n        for (char ch : penrose) {\n            switch (ch) {\n            case 'A':\n                break;\n            case 'M':\n                next += \"OA++PA----NA[-OA----MA]++\";\n                break;\n            case 'N':\n                next += \"+OA--PA[---MA--NA]+\";\n                break;\n            case 'O':\n                next += \"-MA++NA[+++OA++PA]-\";\n                break;\n            case 'P':\n                next += \"--OA++++MA[+PA++++NA]--NA\";\n                break;\n            default:\n                next += ch;\n                break;\n            }\n        }\n        penrose = std::move(next);\n    }\n    const double r = 30;\n    const double pi5 = 0.628318530717959;\n    double x = r * 8, y = r * 8, theta = pi5;\n    std::set<std::string> svg;\n    std::stack<std::tuple<double, double, double>> stack;\n    for (char ch : penrose) {\n        switch (ch) {\n        case 'A': {\n            double nx = x + r * std::cos(theta);\n            double ny = y + r * std::sin(theta);\n            std::ostringstream line;\n            line << std::fixed << std::setprecision(3) << \"<line x1='\" << x\n                 << \"' y1='\" << y << \"' x2='\" << nx << \"' y2='\" << ny << \"'/>\";\n            svg.insert(line.str());\n            x = nx;\n            y = ny;\n        } break;\n        case '+':\n            theta += pi5;\n            break;\n        case '-':\n            theta -= pi5;\n            break;\n        case '[':\n            stack.push({x, y, theta});\n            break;\n        case ']':\n            std::tie(x, y, theta) = stack.top();\n            stack.pop();\n            break;\n        }\n    }\n    out << \"<svg xmlns='http:\n        << \"' width='\" << r * 16 << \"'>\\n\"\n        << \"<rect height='100%' width='100%' fill='black'/>\\n\"\n        << \"<g stroke='rgb(255,165,0)'>\\n\";\n    for (const auto& line : svg)\n        out << line << '\\n';\n    out << \"</g>\\n</svg>\\n\";\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57247, "name": "Greed", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"log\"\n    \"math/rand\"\n    \"strconv\"\n    \"time\"\n)\n\ntype coord struct{ x, y int }\n\nconst (\n    width  = 79\n    height = 22\n    nCount = float64(width * height)\n)\n\nvar (\n    board  [width * height]int\n    score  = 0\n    bold   = termbox.AttrBold\n    cursor coord\n)\n\nvar colors = [10]termbox.Attribute{\n    termbox.ColorDefault,\n    termbox.ColorWhite,\n    termbox.ColorBlack | bold,\n    termbox.ColorBlue | bold,\n    termbox.ColorGreen | bold,\n    termbox.ColorCyan | bold,\n    termbox.ColorRed | bold,\n    termbox.ColorMagenta | bold,\n    termbox.ColorYellow | bold,\n    termbox.ColorWhite | bold,\n}\n\nfunc printAt(x, y int, s string, fg, bg termbox.Attribute) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, fg, bg)\n        x++\n    }\n}\n\nfunc createBoard() {\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            board[x+width*y] = rand.Intn(9) + 1\n        }\n    }\n    cursor = coord{rand.Intn(width), rand.Intn(height)}\n    board[cursor.x+width*cursor.y] = 0\n    score = 0\n    printScore()\n}\n\nfunc displayBoard() {\n    termbox.SetCursor(0, 0)\n    bg := colors[0]\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            i := board[x+width*y]\n            fg := colors[i]\n            s := \" \"\n            if i > 0 {\n                s = strconv.Itoa(i)\n            }\n            printAt(x, y, s, fg, bg)\n        }\n    }\n    fg := colors[9]\n    termbox.SetCursor(cursor.x, cursor.y)\n    printAt(cursor.x, cursor.y, \"@\", fg, bg)\n    termbox.Flush()\n}\n\nfunc printScore() {\n    termbox.SetCursor(0, 24)\n    fg := colors[4]\n    bg := termbox.ColorGreen\n    s := fmt.Sprintf(\"      SCORE: %d : %.3f%%      \", score, float64(score)*100.0/nCount)\n    printAt(0, 24, s, fg, bg)\n    termbox.Flush()\n}\n\nfunc execute(x, y int) {\n    i := board[cursor.x+x+width*(cursor.y+y)]\n    if countSteps(i, x, y) {\n        score += i\n        for i != 0 {\n            i--\n            cursor.x += x\n            cursor.y += y\n            board[cursor.x+width*cursor.y] = 0\n        }\n    }\n}\n\nfunc countSteps(i, x, y int) bool {\n    t := cursor\n    for i != 0 {\n        i--\n        t.x += x\n        t.y += y\n        if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc existsMoves() bool {\n    for y := -1; y < 2; y++ {\n        for x := -1; x < 2; x++ {\n            if x == 0 && y == 0 {\n                continue\n            }\n            ix := cursor.x + x + width*(cursor.y+y)\n            i := 0\n            if ix >= 0 && ix < len(board) {\n                i = board[ix]\n            }\n            if i > 0 && countSteps(i, x, y) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    for {\n        termbox.HideCursor()\n        createBoard()\n        for {\n            displayBoard()\n            select {\n            case ev := <-eventQueue:\n                if ev.Type == termbox.EventKey {\n                    switch ev.Ch {\n                    case 'q', 'Q':\n                        if cursor.x > 0 && cursor.y > 0 {\n                            execute(-1, -1)\n                        }\n                    case 'w', 'W':\n                        if cursor.y > 0 {\n                            execute(0, -1)\n                        }\n                    case 'e', 'E':\n                        if cursor.x < width-1 && cursor.y > 0 {\n                            execute(1, -1)\n                        }\n                    case 'a', 'A':\n                        if cursor.x > 0 {\n                            execute(-1, 0)\n                        }\n                    case 'd', 'D':\n                        if cursor.x < width-1 {\n                            execute(1, 0)\n                        }\n                    case 'z', 'Z':\n                        if cursor.x > 0 && cursor.y < height-1 {\n                            execute(-1, 1)\n                        }\n                    case 'x', 'X':\n                        if cursor.y < height-1 {\n                            execute(0, 1)\n                        }\n                    case 'c', 'C':\n                        if cursor.x < width-1 && cursor.y < height-1 {\n                            execute(1, 1)\n                        }\n                    case 'l', 'L': \n                        return\n                    }\n                } else if ev.Type == termbox.EventResize {\n                    termbox.Flush()\n                }\n            }\n            printScore()\n            if !existsMoves() {\n                break\n            }\n        }\n        displayBoard()\n        fg := colors[7]\n        bg := colors[0]\n        printAt(19, 8, \"+----------------------------------------+\", fg, bg)\n        printAt(19, 9, \"|               GAME OVER                |\", fg, bg)\n        printAt(19, 10, \"|            PLAY AGAIN(Y/N)?            |\", fg, bg)\n        printAt(19, 11, \"+----------------------------------------+\", fg, bg)\n        termbox.SetCursor(48, 10)\n        termbox.Flush()\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'y' || ev.Ch == 'Y' {\n                    break\n                } else {\n                    return\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <ctime>\n\nconst int WID = 79, HEI = 22;\nconst float NCOUNT = ( float )( WID * HEI );\n\nclass coord : public COORD {\npublic:\n    coord( short x = 0, short y = 0 ) { set( x, y ); }\n    void set( short x, short y ) { X = x; Y = y; }\n};\nclass winConsole {\npublic:\n    static winConsole* getInstamnce() { if( 0 == inst ) { inst = new winConsole(); } return inst; }\n    void showCursor( bool s ) { CONSOLE_CURSOR_INFO ci = { 1, s }; SetConsoleCursorInfo( conOut, &ci ); }\n    void setColor( WORD clr ) { SetConsoleTextAttribute( conOut, clr ); }\n    void setCursor( coord p ) { SetConsoleCursorPosition( conOut, p ); }\n    void flush() { FlushConsoleInputBuffer( conIn ); }\n    void kill() { delete inst; }\nprivate:\n    winConsole() { conOut = GetStdHandle( STD_OUTPUT_HANDLE ); \n                   conIn  = GetStdHandle( STD_INPUT_HANDLE ); showCursor( false ); }\n    static winConsole* inst;\n    HANDLE conOut, conIn;\n};\nclass greed {\npublic:\n    greed() { console = winConsole::getInstamnce(); }\n    ~greed() { console->kill(); }\n    void play() {\n        char g; do {\n            console->showCursor( false ); createBoard();\n            do { displayBoard(); getInput(); } while( existsMoves() );\n            displayBoard(); console->setCursor( coord( 0, 24 ) ); console->setColor( 0x07 );\n            console->setCursor( coord( 19,  8 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 19,  9 ) ); std::cout << \"|               GAME OVER                |\";\n            console->setCursor( coord( 19, 10 ) ); std::cout << \"|            PLAY AGAIN(Y/N)?            |\";\n            console->setCursor( coord( 19, 11 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 48, 10 ) ); console->showCursor( true ); console->flush(); std::cin >> g;\n        } while( g == 'Y' || g == 'y' );\n    }\nprivate:\n    void createBoard() {\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                brd[x + WID * y] = rand() % 9 + 1;\n            }\n        }\n        cursor.set( rand() % WID, rand() % HEI );\n        brd[cursor.X + WID * cursor.Y] = 0; score = 0;\n        printScore();\n    }\n    void displayBoard() {\n        console->setCursor( coord() ); int i;\n\t\tfor( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                i = brd[x + WID * y]; console->setColor( 6 + i );\n                if( !i ) std::cout << \" \"; else std::cout << i;\n            }\n            std::cout << \"\\n\";\n        }\n        console->setColor( 15 ); console->setCursor( cursor ); std::cout << \"@\";\n    }\n    void getInput() { \n        while( 1 ) {\n            if( ( GetAsyncKeyState( 'Q' ) & 0x8000 ) && cursor.X > 0 && cursor.Y > 0 ) { execute( -1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'W' ) & 0x8000 ) &&  cursor.Y > 0 ) { execute( 0, -1 ); break; }\n            if( ( GetAsyncKeyState( 'E' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y > 0 ) { execute( 1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'A' ) & 0x8000 ) && cursor.X > 0 ) { execute( -1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'D' ) & 0x8000 ) && cursor.X < WID - 1 ) { execute( 1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'Y' ) & 0x8000 ) && cursor.X > 0 && cursor.Y < HEI - 1 ) { execute( -1, 1 ); break; }\n            if( ( GetAsyncKeyState( 'X' ) & 0x8000 ) && cursor.Y < HEI - 1 ) { execute( 0, 1 ); break; }\n            if( ( GetAsyncKeyState( 'C' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y < HEI - 1 ) { execute( 1, 1 ); break; }\n        }\n        console->flush(); printScore();\n    }\n    void printScore() {\n        console->setCursor( coord( 0, 24 ) ); console->setColor( 0x2a );\n        std::cout << \"      SCORE: \" << score << \" : \" << score * 100.f / NCOUNT << \"%      \";\n    }\n    void execute( int x, int y ) {\n        int i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n        if( countSteps( i, x, y ) ) {\n            score += i;\n            while( i ) {\n                --i; cursor.X += x; cursor.Y += y;\n                brd[cursor.X + WID * cursor.Y] = 0;\n            }\n        }\n    }\n    bool countSteps( int i, int x, int y ) {\n        coord t( cursor.X, cursor.Y );\n        while( i ) {\n            --i; t.X += x; t.Y += y;\n            if( t.X < 0 || t.Y < 0 || t.X >= WID || t.Y >= HEI || !brd[t.X + WID * t.Y] ) return false;\n        }\n        return true;\n    }\n    bool existsMoves() {\n        int i;\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n                if( i > 0 && countSteps( i, x, y ) ) return true;\n            }\n        }\n        return false;\n    }\n    winConsole* console;\n    int brd[WID * HEI];\n    float score; coord cursor;\n};\nwinConsole* winConsole::inst = 0;\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    SetConsoleTitle( \"Greed\" );\n    greed g; g.play(); return 0;\n}\n"}
{"id": 57248, "name": "Greed", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"log\"\n    \"math/rand\"\n    \"strconv\"\n    \"time\"\n)\n\ntype coord struct{ x, y int }\n\nconst (\n    width  = 79\n    height = 22\n    nCount = float64(width * height)\n)\n\nvar (\n    board  [width * height]int\n    score  = 0\n    bold   = termbox.AttrBold\n    cursor coord\n)\n\nvar colors = [10]termbox.Attribute{\n    termbox.ColorDefault,\n    termbox.ColorWhite,\n    termbox.ColorBlack | bold,\n    termbox.ColorBlue | bold,\n    termbox.ColorGreen | bold,\n    termbox.ColorCyan | bold,\n    termbox.ColorRed | bold,\n    termbox.ColorMagenta | bold,\n    termbox.ColorYellow | bold,\n    termbox.ColorWhite | bold,\n}\n\nfunc printAt(x, y int, s string, fg, bg termbox.Attribute) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, fg, bg)\n        x++\n    }\n}\n\nfunc createBoard() {\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            board[x+width*y] = rand.Intn(9) + 1\n        }\n    }\n    cursor = coord{rand.Intn(width), rand.Intn(height)}\n    board[cursor.x+width*cursor.y] = 0\n    score = 0\n    printScore()\n}\n\nfunc displayBoard() {\n    termbox.SetCursor(0, 0)\n    bg := colors[0]\n    for y := 0; y < height; y++ {\n        for x := 0; x < width; x++ {\n            i := board[x+width*y]\n            fg := colors[i]\n            s := \" \"\n            if i > 0 {\n                s = strconv.Itoa(i)\n            }\n            printAt(x, y, s, fg, bg)\n        }\n    }\n    fg := colors[9]\n    termbox.SetCursor(cursor.x, cursor.y)\n    printAt(cursor.x, cursor.y, \"@\", fg, bg)\n    termbox.Flush()\n}\n\nfunc printScore() {\n    termbox.SetCursor(0, 24)\n    fg := colors[4]\n    bg := termbox.ColorGreen\n    s := fmt.Sprintf(\"      SCORE: %d : %.3f%%      \", score, float64(score)*100.0/nCount)\n    printAt(0, 24, s, fg, bg)\n    termbox.Flush()\n}\n\nfunc execute(x, y int) {\n    i := board[cursor.x+x+width*(cursor.y+y)]\n    if countSteps(i, x, y) {\n        score += i\n        for i != 0 {\n            i--\n            cursor.x += x\n            cursor.y += y\n            board[cursor.x+width*cursor.y] = 0\n        }\n    }\n}\n\nfunc countSteps(i, x, y int) bool {\n    t := cursor\n    for i != 0 {\n        i--\n        t.x += x\n        t.y += y\n        if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc existsMoves() bool {\n    for y := -1; y < 2; y++ {\n        for x := -1; x < 2; x++ {\n            if x == 0 && y == 0 {\n                continue\n            }\n            ix := cursor.x + x + width*(cursor.y+y)\n            i := 0\n            if ix >= 0 && ix < len(board) {\n                i = board[ix]\n            }\n            if i > 0 && countSteps(i, x, y) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    for {\n        termbox.HideCursor()\n        createBoard()\n        for {\n            displayBoard()\n            select {\n            case ev := <-eventQueue:\n                if ev.Type == termbox.EventKey {\n                    switch ev.Ch {\n                    case 'q', 'Q':\n                        if cursor.x > 0 && cursor.y > 0 {\n                            execute(-1, -1)\n                        }\n                    case 'w', 'W':\n                        if cursor.y > 0 {\n                            execute(0, -1)\n                        }\n                    case 'e', 'E':\n                        if cursor.x < width-1 && cursor.y > 0 {\n                            execute(1, -1)\n                        }\n                    case 'a', 'A':\n                        if cursor.x > 0 {\n                            execute(-1, 0)\n                        }\n                    case 'd', 'D':\n                        if cursor.x < width-1 {\n                            execute(1, 0)\n                        }\n                    case 'z', 'Z':\n                        if cursor.x > 0 && cursor.y < height-1 {\n                            execute(-1, 1)\n                        }\n                    case 'x', 'X':\n                        if cursor.y < height-1 {\n                            execute(0, 1)\n                        }\n                    case 'c', 'C':\n                        if cursor.x < width-1 && cursor.y < height-1 {\n                            execute(1, 1)\n                        }\n                    case 'l', 'L': \n                        return\n                    }\n                } else if ev.Type == termbox.EventResize {\n                    termbox.Flush()\n                }\n            }\n            printScore()\n            if !existsMoves() {\n                break\n            }\n        }\n        displayBoard()\n        fg := colors[7]\n        bg := colors[0]\n        printAt(19, 8, \"+----------------------------------------+\", fg, bg)\n        printAt(19, 9, \"|               GAME OVER                |\", fg, bg)\n        printAt(19, 10, \"|            PLAY AGAIN(Y/N)?            |\", fg, bg)\n        printAt(19, 11, \"+----------------------------------------+\", fg, bg)\n        termbox.SetCursor(48, 10)\n        termbox.Flush()\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'y' || ev.Ch == 'Y' {\n                    break\n                } else {\n                    return\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <ctime>\n\nconst int WID = 79, HEI = 22;\nconst float NCOUNT = ( float )( WID * HEI );\n\nclass coord : public COORD {\npublic:\n    coord( short x = 0, short y = 0 ) { set( x, y ); }\n    void set( short x, short y ) { X = x; Y = y; }\n};\nclass winConsole {\npublic:\n    static winConsole* getInstamnce() { if( 0 == inst ) { inst = new winConsole(); } return inst; }\n    void showCursor( bool s ) { CONSOLE_CURSOR_INFO ci = { 1, s }; SetConsoleCursorInfo( conOut, &ci ); }\n    void setColor( WORD clr ) { SetConsoleTextAttribute( conOut, clr ); }\n    void setCursor( coord p ) { SetConsoleCursorPosition( conOut, p ); }\n    void flush() { FlushConsoleInputBuffer( conIn ); }\n    void kill() { delete inst; }\nprivate:\n    winConsole() { conOut = GetStdHandle( STD_OUTPUT_HANDLE ); \n                   conIn  = GetStdHandle( STD_INPUT_HANDLE ); showCursor( false ); }\n    static winConsole* inst;\n    HANDLE conOut, conIn;\n};\nclass greed {\npublic:\n    greed() { console = winConsole::getInstamnce(); }\n    ~greed() { console->kill(); }\n    void play() {\n        char g; do {\n            console->showCursor( false ); createBoard();\n            do { displayBoard(); getInput(); } while( existsMoves() );\n            displayBoard(); console->setCursor( coord( 0, 24 ) ); console->setColor( 0x07 );\n            console->setCursor( coord( 19,  8 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 19,  9 ) ); std::cout << \"|               GAME OVER                |\";\n            console->setCursor( coord( 19, 10 ) ); std::cout << \"|            PLAY AGAIN(Y/N)?            |\";\n            console->setCursor( coord( 19, 11 ) ); std::cout << \"+----------------------------------------+\";\n            console->setCursor( coord( 48, 10 ) ); console->showCursor( true ); console->flush(); std::cin >> g;\n        } while( g == 'Y' || g == 'y' );\n    }\nprivate:\n    void createBoard() {\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                brd[x + WID * y] = rand() % 9 + 1;\n            }\n        }\n        cursor.set( rand() % WID, rand() % HEI );\n        brd[cursor.X + WID * cursor.Y] = 0; score = 0;\n        printScore();\n    }\n    void displayBoard() {\n        console->setCursor( coord() ); int i;\n\t\tfor( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                i = brd[x + WID * y]; console->setColor( 6 + i );\n                if( !i ) std::cout << \" \"; else std::cout << i;\n            }\n            std::cout << \"\\n\";\n        }\n        console->setColor( 15 ); console->setCursor( cursor ); std::cout << \"@\";\n    }\n    void getInput() { \n        while( 1 ) {\n            if( ( GetAsyncKeyState( 'Q' ) & 0x8000 ) && cursor.X > 0 && cursor.Y > 0 ) { execute( -1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'W' ) & 0x8000 ) &&  cursor.Y > 0 ) { execute( 0, -1 ); break; }\n            if( ( GetAsyncKeyState( 'E' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y > 0 ) { execute( 1, -1 ); break; }\n            if( ( GetAsyncKeyState( 'A' ) & 0x8000 ) && cursor.X > 0 ) { execute( -1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'D' ) & 0x8000 ) && cursor.X < WID - 1 ) { execute( 1, 0 ); break; }\n            if( ( GetAsyncKeyState( 'Y' ) & 0x8000 ) && cursor.X > 0 && cursor.Y < HEI - 1 ) { execute( -1, 1 ); break; }\n            if( ( GetAsyncKeyState( 'X' ) & 0x8000 ) && cursor.Y < HEI - 1 ) { execute( 0, 1 ); break; }\n            if( ( GetAsyncKeyState( 'C' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y < HEI - 1 ) { execute( 1, 1 ); break; }\n        }\n        console->flush(); printScore();\n    }\n    void printScore() {\n        console->setCursor( coord( 0, 24 ) ); console->setColor( 0x2a );\n        std::cout << \"      SCORE: \" << score << \" : \" << score * 100.f / NCOUNT << \"%      \";\n    }\n    void execute( int x, int y ) {\n        int i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n        if( countSteps( i, x, y ) ) {\n            score += i;\n            while( i ) {\n                --i; cursor.X += x; cursor.Y += y;\n                brd[cursor.X + WID * cursor.Y] = 0;\n            }\n        }\n    }\n    bool countSteps( int i, int x, int y ) {\n        coord t( cursor.X, cursor.Y );\n        while( i ) {\n            --i; t.X += x; t.Y += y;\n            if( t.X < 0 || t.Y < 0 || t.X >= WID || t.Y >= HEI || !brd[t.X + WID * t.Y] ) return false;\n        }\n        return true;\n    }\n    bool existsMoves() {\n        int i;\n        for( int y = -1; y < 2; y++ ) {\n            for( int x = -1; x < 2; x++ ) {\n                if( !x && !y ) continue;\n                i = brd[cursor.X + x + WID * ( cursor.Y + y )];\n                if( i > 0 && countSteps( i, x, y ) ) return true;\n            }\n        }\n        return false;\n    }\n    winConsole* console;\n    int brd[WID * HEI];\n    float score; coord cursor;\n};\nwinConsole* winConsole::inst = 0;\nint main( int argc, char* argv[] ) {\n    srand( ( unsigned )time( 0 ) );\n    SetConsoleTitle( \"Greed\" );\n    greed g; g.play(); return 0;\n}\n"}
{"id": 57249, "name": "Ruth-Aaron numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc prune(a []int) []int {\n    prev := a[0]\n    b := []int{prev}\n    for i := 1; i < len(a); i++ {\n        if a[i] != prev {\n            b = append(b, a[i])\n            prev = a[i]\n        }\n    }\n    return b\n}\n\nfunc main() {\n    var resF, resD, resT, factors1 []int\n    factors2 := []int{2}\n    factors3 := []int{3}\n    var sum1, sum2, sum3 int = 0, 2, 3\n    var countF, countD, countT int\n    for n := 2; countT < 1 || countD < 30 || countF < 30; n++ {\n        factors1 = factors2\n        factors2 = factors3\n        factors3 = rcu.PrimeFactors(n + 2)\n        sum1 = sum2\n        sum2 = sum3\n        sum3 = rcu.SumInts(factors3)\n        if countF < 30 && sum1 == sum2 {\n            resF = append(resF, n)\n            countF++\n        }\n        if sum1 == sum2 && sum2 == sum3 {\n            resT = append(resT, n)\n            countT++\n        }\n        if countD < 30 {\n            factors4 := make([]int, len(factors1))\n            copy(factors4, factors1)\n            factors5 := make([]int, len(factors2))\n            copy(factors5, factors2)\n            factors4 = prune(factors4)\n            factors5 = prune(factors5)\n            if rcu.SumInts(factors4) == rcu.SumInts(factors5) {\n                resD = append(resD, n)\n                countD++\n            }\n        }\n    }\n    fmt.Println(\"First 30 Ruth-Aaron numbers (factors):\")\n    fmt.Println(resF)\n    fmt.Println(\"\\nFirst 30 Ruth-Aaron numbers (divisors):\")\n    fmt.Println(resD)\n    fmt.Println(\"\\nFirst Ruth-Aaron triple (factors):\")\n    fmt.Println(resT[0])\n\n    resT = resT[:0]\n    factors1 = factors1[:0]\n    factors2 = factors2[:1]\n    factors2[0] = 2\n    factors3 = factors3[:1]\n    factors3[0] = 3\n    countT = 0\n    for n := 2; countT < 1; n++ {\n        factors1 = factors2\n        factors2 = factors3\n        factors3 = prune(rcu.PrimeFactors(n + 2))\n        sum1 = sum2\n        sum2 = sum3\n        sum3 = rcu.SumInts(factors3)\n        if sum1 == sum2 && sum2 == sum3 {\n            resT = append(resT, n)\n            countT++\n        }\n    }\n    fmt.Println(\"\\nFirst Ruth-Aaron triple (divisors):\")\n    fmt.Println(resT[0])\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nint prime_factor_sum(int n) {\n    int sum = 0;\n    for (; (n & 1) == 0; n >>= 1)\n        sum += 2;\n    for (int p = 3, sq = 9; sq <= n; p += 2) {\n        for (; n % p == 0; n /= p)\n            sum += p;\n        sq += (p + 1) << 2;\n    }\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nint prime_divisor_sum(int n) {\n    int sum = 0;\n    if ((n & 1) == 0) {\n        sum += 2;\n        n >>= 1;\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3, sq = 9; sq <= n; p += 2) {\n        if (n % p == 0) {\n            sum += p;\n            n /= p;\n            while (n % p == 0)\n                n /= p;\n        }\n        sq += (p + 1) << 2;\n    }\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nint main() {\n    const int limit = 30;\n    int dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;\n\n    std::cout << \"First \" << limit << \" Ruth-Aaron numbers (factors):\\n\";\n    for (int n = 2, count = 0; count < limit; ++n) {\n        fsum2 = prime_factor_sum(n);\n        if (fsum1 == fsum2) {\n            ++count;\n            std::cout << std::setw(5) << n - 1\n                      << (count % 10 == 0 ? '\\n' : ' ');\n        }\n        fsum1 = fsum2;\n    }\n\n    std::cout << \"\\nFirst \" << limit << \" Ruth-Aaron numbers (divisors):\\n\";\n    for (int n = 2, count = 0; count < limit; ++n) {\n        dsum2 = prime_divisor_sum(n);\n        if (dsum1 == dsum2) {\n            ++count;\n            std::cout << std::setw(5) << n - 1\n                      << (count % 10 == 0 ? '\\n' : ' ');\n        }\n        dsum1 = dsum2;\n    }\n\n    dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;\n    for (int n = 2;; ++n) {\n        int fsum3 = prime_factor_sum(n);\n        if (fsum1 == fsum2 && fsum2 == fsum3) {\n            std::cout << \"\\nFirst Ruth-Aaron triple (factors): \" << n - 2\n                      << '\\n';\n            break;\n        }\n        fsum1 = fsum2;\n        fsum2 = fsum3;\n    }\n    for (int n = 2;; ++n) {\n        int dsum3 = prime_divisor_sum(n);\n        if (dsum1 == dsum2 && dsum2 == dsum3) {\n            std::cout << \"\\nFirst Ruth-Aaron triple (divisors): \" << n - 2\n                      << '\\n';\n            break;\n        }\n        dsum1 = dsum2;\n        dsum2 = dsum3;\n    }\n}\n"}
{"id": 57250, "name": "Duffinian numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc main() {\n    limit := 200000 \n    d := rcu.PrimeSieve(limit-1, true)\n    d[1] = false\n    for i := 2; i < limit; i++ {\n        if !d[i] {\n            continue\n        }\n        if i%2 == 0 && !isSquare(i) && !isSquare(i/2) {\n            d[i] = false\n            continue\n        }\n        sigmaSum := rcu.SumInts(rcu.Divisors(i))\n        if rcu.Gcd(sigmaSum, i) != 1 {\n            d[i] = false\n        }\n    }\n\n    var duff []int\n    for i := 1; i < len(d); i++ {\n        if d[i] {\n            duff = append(duff, i)\n        }\n    }\n    fmt.Println(\"First 50 Duffinian numbers:\")\n    rcu.PrintTable(duff[0:50], 10, 3, false)\n\n    var triplets [][3]int\n    for i := 2; i < limit; i++ {\n        if d[i] && d[i-1] && d[i-2] {\n            triplets = append(triplets, [3]int{i - 2, i - 1, i})\n        }\n    }\n    fmt.Println(\"\\nFirst 56 Duffinian triplets:\")\n    for i := 0; i < 14; i++ {\n        s := fmt.Sprintf(\"%6v\", triplets[i*4:i*4+4])\n        fmt.Println(s[1 : len(s)-1])\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n\nbool duffinian(int n) {\n    if (n == 2)\n        return false;\n    int total = 1, power = 2, m = n;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    for (int p = 3; p * p <= n; p += 2) {\n        int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    if (m == n)\n        return false;\n    if (n > 1)\n        total *= n + 1;\n    return std::gcd(total, m) == 1;\n}\n\nint main() {\n    std::cout << \"First 50 Duffinian numbers:\\n\";\n    for (int n = 1, count = 0; count < 50; ++n) {\n        if (duffinian(n))\n            std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nFirst 50 Duffinian triplets:\\n\";\n    for (int n = 1, m = 0, count = 0; count < 50; ++n) {\n        if (duffinian(n))\n            ++m;\n        else\n            m = 0;\n        if (m == 3) {\n            std::ostringstream os;\n            os << '(' << n - 2 << \", \" << n - 1 << \", \" << n << ')';\n            std::cout << std::left << std::setw(24) << os.str()\n                      << (++count % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << '\\n';\n}\n"}
{"id": 57251, "name": "Sphenic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = 1000000\n    limit2 := int(math.Cbrt(limit)) \n    primes := rcu.Primes(limit / 6)\n    pc := len(primes)\n    var sphenic []int\n    fmt.Println(\"Sphenic numbers less than 1,000:\")\n    for i := 0; i < pc-2; i++ {\n        if primes[i] > limit2 {\n            break\n        }\n        for j := i + 1; j < pc-1; j++ {\n            prod := primes[i] * primes[j]\n            if prod+primes[j+1] >= limit {\n                break\n            }\n            for k := j + 1; k < pc; k++ {\n                res := prod * primes[k]\n                if res >= limit {\n                    break\n                }\n                sphenic = append(sphenic, res)\n            }\n        }\n    }\n    sort.Ints(sphenic)\n    ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })\n    rcu.PrintTable(sphenic[:ix], 15, 3, false)\n    fmt.Println(\"\\nSphenic triplets less than 10,000:\")\n    var triplets [][3]int\n    for i := 0; i < len(sphenic)-2; i++ {\n        s := sphenic[i]\n        if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {\n            triplets = append(triplets, [3]int{s, s + 1, s + 2})\n        }\n    }\n    ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })\n    for i := 0; i < ix; i++ {\n        fmt.Printf(\"%4d \", triplets[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThere are %s sphenic numbers less than 1,000,000.\\n\", rcu.Commatize(len(sphenic)))\n    fmt.Printf(\"There are %s sphenic triplets less than 1,000,000.\\n\", rcu.Commatize(len(triplets)))\n    s := sphenic[199999]\n    pf := rcu.PrimeFactors(s)\n    fmt.Printf(\"The 200,000th sphenic number is %s (%d*%d*%d).\\n\", rcu.Commatize(s), pf[0], pf[1], pf[2])\n    fmt.Printf(\"The 5,000th sphenic triplet is %v.\\n.\", triplets[4999])\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nstd::vector<int> prime_factors(int n) {\n    std::vector<int> factors;\n    if (n > 1 && (n & 1) == 0) {\n        factors.push_back(2);\n        while ((n & 1) == 0)\n            n >>= 1;\n    }\n    for (int p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            factors.push_back(p);\n            while (n % p == 0)\n                n /= p;\n        }\n    }\n    if (n > 1)\n        factors.push_back(n);\n    return factors;\n}\n\nint main() {\n    const int limit = 1000000;\n    const int imax = limit / 6;\n    std::vector<bool> sieve = prime_sieve(imax + 1);\n    std::vector<bool> sphenic(limit + 1, false);\n    for (int i = 0; i <= imax; ++i) {\n        if (!sieve[i])\n            continue;\n        int jmax = std::min(imax, limit / (i * i));\n        if (jmax <= i)\n            break;\n        for (int j = i + 1; j <= jmax; ++j) {\n            if (!sieve[j])\n                continue;\n            int p = i * j;\n            int kmax = std::min(imax, limit / p);\n            if (kmax <= j)\n                break;\n            for (int k = j + 1; k <= kmax; ++k) {\n                if (!sieve[k])\n                    continue;\n                assert(p * k <= limit);\n                sphenic[p * k] = true;\n            }\n        }\n    }\n\n    std::cout << \"Sphenic numbers < 1000:\\n\";\n    for (int i = 0, n = 0; i < 1000; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++n;\n        std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n    for (int i = 0, n = 0; i < 10000; ++i) {\n        if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n            ++n;\n            std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n                      << (n % 3 == 0 ? '\\n' : ' ');\n        }\n    }\n\n    int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n    for (int i = 0; i < limit; ++i) {\n        if (!sphenic[i])\n            continue;\n        ++count;\n        if (count == 200000)\n            s200000 = i;\n        if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n            ++triplets;\n            if (triplets == 5000)\n                t5000 = i;\n        }\n    }\n\n    std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n    std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n    auto factors = prime_factors(s200000);\n    assert(factors.size() == 3);\n    std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n              << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n              << '\\n';\n\n    std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n              << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}\n"}
{"id": 57252, "name": "Tree from nesting levels", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 57253, "name": "Tree from nesting levels", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n", "C++": "#include <any>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace std;\n\n\nvector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n    vector<any> tree;\n    while (first < last && depth <= *first)\n    {\n        if(*first == depth)\n        {\n            \n            tree.push_back(*first);\n            ++first;\n        }\n        else \n        {\n            \n            tree.push_back(MakeTree(first, last, depth + 1));\n            first = find(first + 1, last, depth); \n        }\n    }\n        \n    return tree;\n}\n\n\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n    cout << \"[\";\n    for(auto it = first; it != last; ++it)\n    {\n        if(it != first) cout << \", \";\n        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)\n        {\n            \n            cout << *it;\n        }\n        else\n        {\n            \n            if(it->type() == typeid(unsigned int))\n            {\n                \n                cout << any_cast<unsigned int>(*it);\n            }\n            else\n            {\n                \n                const auto& subTree = any_cast<vector<any>>(*it);\n                PrintTree(subTree.begin(), subTree.end());\n            }\n        }\n    }\n    cout << \"]\";\n}\n\nint main(void) \n{\n    auto execises = vector<vector<unsigned int>> {\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3}\n        };\n    \n    for(const auto& e : execises)\n    {\n        auto tree = MakeTree(e.begin(), e.end());\n        PrintTree(e.begin(), e.end());\n        cout << \" Nests to:\\n\"; \n        PrintTree(tree.begin(), tree.end());\n        cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 57254, "name": "Recursive descent parser generator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"log\"\n)\n\nfunc labelStr(label int) string {\n    return fmt.Sprintf(\"_%04d\", label)\n}\n\ntype binexp struct {\n    op, left, right string\n    kind, index     int\n}\n\nfunc main() {\n    x := \"(one + two) * three - four * five\"\n    fmt.Println(\"Expression to parse: \", x)\n    f, err := parser.ParseExpr(x)\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Println(\"\\nThe abstract syntax tree for this expression:\")\n    ast.Print(nil, f)\n\n    fmt.Println(\"\\nThe corresponding three-address code:\")\n    var binexps []binexp\n    \n    ast.Inspect(f, func(n ast.Node) bool {\n        switch x := n.(type) {\n        case *ast.BinaryExpr:\n            sx, ok1 := x.X.(*ast.Ident)\n            sy, ok2 := x.Y.(*ast.Ident)\n            op := x.Op.String()\n            if ok1 && ok2 {\n                binexps = append(binexps, binexp{op, sx.Name, sy.Name, 3, 0})\n            } else if !ok1 && ok2 {\n                binexps = append(binexps, binexp{op, \"<addr>\", sy.Name, 2, 0})\n            } else if ok1 && !ok2 {\n                binexps = append(binexps, binexp{op, sx.Name, \"<addr>\", 1, 0})\n            } else {\n                binexps = append(binexps, binexp{op, \"<addr>\", \"<addr>\", 0, 0})\n            }\n        }\n        return true\n    })\n\n    for i := 0; i < len(binexps); i++ {\n        binexps[i].index = i\n    }\n\n    label, last := 0, -1\n    var ops, args []binexp\n    var labels []string\n    for i, be := range binexps {\n        if be.kind == 0 {\n            ops = append(ops, be)\n        }\n        if be.kind != 3 {\n            continue\n        }\n        label++\n        ls := labelStr(label)\n        fmt.Printf(\"    %s = %s %s %s\\n\", ls, be.left, be.op, be.right)\n        for j := i - 1; j > last; j-- {\n            be2 := binexps[j]\n            if be2.kind == 2 {\n                label++\n                ls2 := labelStr(label)\n                fmt.Printf(\"    %s = %s %s %s\\n\", ls2, ls, be2.op, be2.right)\n                ls = ls2\n                be = be2\n            } else if be2.kind == 1 {\n                label++\n                ls2 := labelStr(label)\n                fmt.Printf(\"    %s = %s %s %s\\n\", ls2, be2.left, be2.op, ls)\n                ls = ls2\n                be = be2\n            }\n        }\n        args = append(args, be)\n        labels = append(labels, ls)\n        lea, leo := len(args), len(ops)\n        for lea >= 2 {\n            if i < len(binexps)-1 && args[lea-2].index <= ops[leo-1].index {\n                break\n            }\n            label++\n            ls2 := labelStr(label)\n            fmt.Printf(\"    %s = %s %s %s\\n\", ls2, labels[lea-2], ops[leo-1].op, labels[lea-1])\n            ops = ops[0 : leo-1]\n            args = args[0 : lea-1]\n            labels = labels[0 : lea-1]\n            lea--\n            leo--\n            args[lea-1] = be\n            labels[lea-1] = ls2\n        }\n        last = i\n    }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <map>\n#include <set>\n#include <regex>\nusing namespace std;\n\nmap<string, string> terminals;\nmap<string, vector<vector<string>>> nonterminalRules;\nmap<string, set<string>> nonterminalFirst;\nmap<string, vector<string>> nonterminalCode;\n\nint main(int argc, char **argv) {\n\tif (argc < 3) {\n\t\tcout << \"Usage: <input file> <output file>\" << endl;\n\t\treturn 1;\n\t}\n\n\tifstream inFile(argv[1]);\n\tofstream outFile(argv[2]);\n\n\tregex blankLine(R\"(^\\s*$)\");\n\tregex terminalPattern(R\"((\\w+)\\s+(.+))\");\n\tregex rulePattern(R\"(^!!\\s*(\\w+)\\s*->\\s*((?:\\w+\\s*)*)$)\");\n\tregex argPattern(R\"(\\$(\\d+))\");\n\tsmatch results;\n\n\t\n\tstring line;\n\twhile (true) {\n\t\tgetline(inFile, line);\n\n\t\t\n\t\tif (regex_match(line, blankLine))\n\t\t\tbreak;\n\n\t\tregex_match(line, results, terminalPattern);\n\t\tterminals[results[1]] = results[2];\n\t}\n\n\toutFile << \"#include <iostream>\" << endl;\n\toutFile << \"#include <fstream>\" << endl;\n\toutFile << \"#include <string>\" << endl;\n\toutFile << \"#include <regex>\" << endl;\n\toutFile << \"using namespace std;\" << endl << endl;\n\n\t\n\toutFile << \"string input, nextToken, nextTokenValue;\" << endl;\n\toutFile << \"string prevToken, prevTokenValue;\" << endl << endl;\n\n\toutFile << \"void advanceToken() {\" << endl;\n\toutFile << \"\tstatic smatch results;\" << endl << endl;\n\n\toutFile << \"\tprevToken = nextToken;\" << endl;\n\toutFile << \"\tprevTokenValue = nextTokenValue;\" << endl << endl;\n\n\tfor (auto i = terminals.begin(); i != terminals.end(); ++i) {\n\t\tstring name = i->first + \"_pattern\";\n\t\tstring pattern = i->second;\n\n\t\toutFile << \"\tstatic regex \" << name << \"(R\\\"(^\\\\s*(\" << pattern << \"))\\\");\" << endl;\n\t\toutFile << \"\tif (regex_search(input, results, \" << name << \", regex_constants::match_continuous)) {\" << endl;\n\t\toutFile << \"\t\tnextToken = \\\"\" << i->first << \"\\\";\" << endl;\n\t\toutFile << \"\t\tnextTokenValue = results[1];\" << endl;\n\t\toutFile << \"\t\tinput = regex_replace(input, \" << name << \", \\\"\\\");\" << endl;\n\t\toutFile << \"\t\treturn;\" << endl;\n\t\toutFile << \"\t}\" << endl << endl;\n\t}\n\n\toutFile << \"\tstatic regex eof(R\\\"(\\\\s*)\\\");\" << endl;\n\toutFile << \"\tif (regex_match(input, results, eof, regex_constants::match_continuous)) {\" << endl;\n\toutFile << \"\t\tnextToken = \\\"\\\";\" << endl;\n\toutFile << \"\t\tnextTokenValue = \\\"\\\";\" << endl;\n\toutFile << \"\t\treturn;\" << endl;\n\toutFile << \"\t}\" << endl << endl;\n\n\toutFile << \"\tthrow \\\"Unknown token\\\";\" << endl;\n\toutFile << \"}\" << endl << endl;\n\n\toutFile << \"bool same(string symbol) {\" << endl;\n\toutFile << \"\tif (symbol == nextToken) {\" << endl;\n\toutFile << \"\t\tadvanceToken();\" << endl;\n\toutFile << \"\t\treturn true;\" << endl;\n\toutFile << \"\t}\" << endl;\n\toutFile << \"\treturn false;\" << endl;\n\toutFile << \"}\" << endl << endl;\n\n\t\n\twhile (true) {\n\t\tgetline(inFile, line);\n\t\t\n\t\t\n\t\tif (regex_match(line, results, rulePattern))\n\t\t\tbreak;\n\n\t\toutFile << line << endl;\n\t}\n\n\t\n\twhile (true) {\n\t\t\n\t\tstring name = results[1];\n\t\tstringstream ss(results[2]);\n\n\t\tstring tempString;\n\t\tvector<string> tempVector;\n\t\twhile (ss >> tempString)\n\t\t\ttempVector.push_back(tempString);\n\t\tnonterminalRules[name].push_back(tempVector);\n\n\t\t\n\t\tstring code = \"\";\n\t\twhile (true) {\n\t\t\tgetline(inFile, line);\n\n\t\t\tif (!inFile || regex_match(line, results, rulePattern))\n\t\t\t\tbreak;\n\n\t\t\t\n\t\t\tline = regex_replace(line, argPattern, \"results[$1]\");\n\n\t\t\tcode += line + \"\\n\";\n\t\t}\n\t\tnonterminalCode[name].push_back(code);\n\n\t\t\n\t\tif (!inFile)\n\t\t\tbreak;\n\t}\n\n\t\n\tbool done = false;\n\twhile (!done)\n\t\tfor (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {\n\t\t\tstring name = i->first;\n\t\t\tdone = true; \n\n\t\t\tif (nonterminalFirst.find(i->first) == nonterminalFirst.end())\n\t\t\t\tnonterminalFirst[i->first] = set<string>();\n\n\t\t\tfor (int j = 0; j < i->second.size(); ++j) {\n\t\t\t\tif (i->second[j].size() == 0)\n\t\t\t\t\tnonterminalFirst[i->first].insert(\"\");\n\t\t\t\telse {\n\t\t\t\t\tstring first = i->second[j][0];\n\t\t\t\t\tif (nonterminalFirst.find(first) != nonterminalFirst.end()) {\n\t\t\t\t\t\tfor (auto k = nonterminalFirst[first].begin(); k != nonterminalFirst[first].end(); ++k) {\n\t\t\t\t\t\t\tif (nonterminalFirst[name].find(*k) == nonterminalFirst[name].end()) {\n\t\t\t\t\t\t\t\tnonterminalFirst[name].insert(*k);\n\t\t\t\t\t\t\t\tdone = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (nonterminalFirst[name].find(first) == nonterminalFirst[name].end()) {\n\t\t\t\t\t\tnonterminalFirst[name].insert(first);\n\t\t\t\t\t\tdone = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\n\tfor (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {\n\t\tstring name = i->first + \"_rule\";\n\t\toutFile << \"string \" << name << \"();\" << endl;\n\t}\n\toutFile << endl;\n\n\t\n\tfor (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {\n\t\tstring name = i->first + \"_rule\";\n\t\toutFile << \"string \" << name << \"() {\" << endl;\n\t\toutFile << \"\tvector<string> results;\" << endl;\n\t\toutFile << \"\tresults.push_back(\\\"\\\");\" << endl << endl;\n\t\t\n\t\t\n\t\tint epsilon = -1;\n\t\tfor (int j = 0; epsilon == -1 && j < i->second.size(); ++j)\n\t\t\tif (i->second[j].size() == 0)\n\t\t\t\tepsilon = j;\n\n\t\t\n\t\tfor (int j = 0; j < i->second.size(); ++j) {\n\t\t\t\n\t\t\tif (j == epsilon)\n\t\t\t\tcontinue;\n\n\t\t\tstring token = i->second[j][0];\n\t\t\tif (terminals.find(token) != terminals.end())\n\t\t\t\toutFile << \"\tif (nextToken == \\\"\" << i->second[j][0] << \"\\\") {\" << endl;\n\t\t\telse {\n\t\t\t\toutFile << \"\tif (\";\n\t\t\t\tbool first = true;\n\t\t\t\tfor (auto k = nonterminalFirst[token].begin(); k != nonterminalFirst[token].end(); ++k, first = false) {\n\t\t\t\t\tif (!first)\n\t\t\t\t\t\toutFile << \" || \";\n\t\t\t\t\toutFile << \"nextToken == \\\"\" << (*k) << \"\\\"\";\n\t\t\t\t}\n\t\t\t\toutFile << \") {\" << endl;\n\t\t\t}\n\t\t\t\n\t\t\tfor (int k = 0; k < i->second[j].size(); ++k) {\n\t\t\t\tif (terminals.find(i->second[j][k]) != terminals.end()) {\n\t\t\t\t\toutFile << \"\t\tif(same(\\\"\" << i->second[j][k] << \"\\\"))\" << endl;\n\t\t\t\t\toutFile << \"\t\t\tresults.push_back(prevTokenValue);\" << endl;\n\t\t\t\t\toutFile << \"\t\telse\" << endl;\n\t\t\t\t\toutFile << \"\t\t\tthrow \\\"Syntax error - mismatched token\\\";\" << endl;\n\t\t\t\t} else\n\t\t\t\t\toutFile << \"\t\tresults.push_back(\" << i->second[j][k] << \"_rule());\" << endl;\n\t\t\t}\n\n\t\t\t\n\t\t\toutFile << nonterminalCode[i->first][j];\n\n\t\t\toutFile << \"\t}\" << endl << endl;\n\t\t}\n\n\t\tif (epsilon == -1)\n\t\t\toutFile << \"\tthrow \\\"Syntax error - unmatched token\\\";\" << endl;\n\t\telse\n\t\t\toutFile << nonterminalCode[i->first][epsilon];\n\n\t\toutFile << \"}\" << endl << endl;\n\t}\n\n\t\n\toutFile << \"int main(int argc, char **argv) {\" << endl;\n\toutFile << \"\tif(argc < 2) {\" << endl;\n\toutFile << \"\t\tcout << \\\"Usage: <input file>\\\" << endl;\" << endl;\n\toutFile << \"\t\treturn 1;\" << endl;\n\toutFile << \"\t}\" << endl << endl;\n\n\toutFile << \"\tifstream file(argv[1]);\" << endl;\n\toutFile << \"\tstring line;\" << endl;\n\toutFile << \"\tinput = \\\"\\\";\" << endl << endl;\n\n\toutFile << \"\twhile(true) {\" << endl;\n\toutFile << \"\t\tgetline(file, line);\" << endl;\n\toutFile << \"\t\tif(!file) break;\" << endl;\n\toutFile << \"\t\tinput += line + \\\"\\\\n\\\";\" << endl;\n\toutFile << \"\t}\" << endl << endl;\n\n\toutFile << \"\tadvanceToken();\" << endl << endl;\n\n\toutFile << \"\tstart_rule();\" << endl;\n\toutFile << \"}\" << endl;\n}\n"}
{"id": 57255, "name": "Find duplicate files", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"crypto/md5\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"path/filepath\"\n    \"sort\"\n    \"time\"\n)\n\ntype fileData struct {\n    filePath string\n    info     os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc checksum(filePath string) hash {\n    bytes, err := ioutil.ReadFile(filePath)\n    check(err)\n    return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n    var dups [][2]fileData\n    m := make(map[hash]fileData)\n    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        if !info.IsDir() && info.Size() >= minSize {\n            h := checksum(path)\n            fd, ok := m[h]\n            fd2 := fileData{path, info}\n            if !ok {\n                m[h] = fd2\n            } else {\n                dups = append(dups, [2]fileData{fd, fd2})\n            }\n        }\n        return nil\n    })\n    check(werr)\n    return dups\n}\n\nfunc main() {\n    dups := findDuplicates(\".\", 1)\n    fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n    fmt.Println(\"File name                 Size      Date last modified\")\n    fmt.Println(\"==========================================================\")\n    sort.Slice(dups, func(i, j int) bool {\n        return dups[i][0].info.Size() > dups[j][0].info.Size() \n    })\n    for _, dup := range dups {\n        for i := 0; i < 2; i++ {\n            d := dup[i]\n            fmt.Printf(\"%-20s  %8d    %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include<iostream>\n#include<string>\n#include<boost/filesystem.hpp>\n#include<boost/format.hpp>\n#include<boost/iostreams/device/mapped_file.hpp>\n#include<optional>\n#include<algorithm>\n#include<iterator>\n#include<execution>\n#include\"dependencies/xxhash.hpp\" \n\n\ntemplate<typename  T, typename V, typename F>\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n    size_t partitions = 0;\n    while (begin != end) {\n        auto const& value = getvalue(*begin);\n        auto current = begin;\n        while (++current != end && getvalue(*current) == value);\n        callback(begin, current, value);\n        ++partitions;\n        begin = current;\n    }\n    return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n    explicit file_entry(fs::directory_entry const & entry) \n        : path_{entry.path()}, size_{fs::file_size(entry)}\n    {}\n    auto size() const { return size_; }\n    auto const& path() const { return path_; }\n    auto get_hash() {\n        if (!hash_)\n            hash_ = compute_hash();\n        return *hash_;\n    }\nprivate:\n    xxh::hash64_t compute_hash() {\n        bi::mapped_file_source source;\n        source.open<fs::wpath>(this->path());\n        if (!source.is_open()) {\n            std::cerr << \"Cannot open \" << path() << std::endl;\n            throw std::runtime_error(\"Cannot open file\");\n        }\n        xxh::hash_state64_t hash_stream;\n        hash_stream.update(source.data(), size_);\n        return hash_stream.digest();\n    }\nprivate:\n    fs::wpath path_;\n    uintmax_t size_;\n    std::optional<xxh::hash64_t> hash_;\n};\n\nusing vector_type = std::vector<file_entry>;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n    size_t found = 0, ignored = 0;\n    if (!fs::is_directory(path)) {\n        std::cerr << path << \" is not a directory!\" << std::endl;\n    }\n    else {\n        std::cerr << \"Searching \" << path << std::endl;\n\n        for (auto& e : fs::recursive_directory_iterator(path)) {\n            ++found;\n            if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n                file_vector.emplace_back(e);\n            else ++ignored;\n        }\n    }\n    return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n    vector_type files;\n    for (auto i = 1; i < argn; ++i) {\n        fs::wpath path(argv[i]);\n        auto [found, ignored] = find_files_in_dir(path, files);\n        std::cerr << boost::format{\n            \"  %1$6d files found\\n\"\n            \"  %2$6d files ignored\\n\"\n            \"  %3$6d files added\\n\" } % found % ignored % (found - ignored) \n            << std::endl;\n    }\n\n    std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n    \n    std::sort(std::execution::par_unseq, files.begin(), files.end()\n        , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n    );\n    for_each_adjacent_range(\n        std::begin(files)\n        , std::end(files)\n        , [](vector_type::value_type const& f) { return f.size(); }\n        , [](auto start, auto end, auto file_size) {\n            \n            size_t nr_of_files = std::distance(start, end);\n            if (nr_of_files > 1) {\n                \n                std::sort(start, end, [](auto& a, auto& b) { \n                    auto const& ha = a.get_hash();\n                    auto const& hb = b.get_hash();\n                    auto const& pa = a.path();\n                    auto const& pb = b.path();\n                    return std::tie(ha, pa) < std::tie(hb, pb); \n                    });\n                for_each_adjacent_range(\n                    start\n                    , end\n                    , [](vector_type::value_type& f) { return f.get_hash(); }\n                    , [file_size](auto hstart, auto hend, auto hash) {\n                        \n                        \n                        size_t hnr_of_files = std::distance(hstart, hend);\n                        if (hnr_of_files > 1) {\n                            std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n                                % hnr_of_files % file_size % hash;\n                            std::for_each(hstart, hend, [hash, file_size](auto& e) {\n                                std::cout << '\\t' << e.path() << '\\n';\n                                }\n                            );\n                        }\n                    }\n                );\n            }\n        }\n    );\n    \n    return 0;\n}\n"}
{"id": 57256, "name": "Substring primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(499)\n    var sprimes []int\n    for _, p := range primes {\n        digits := rcu.Digits(p, 10)\n        var b1 = true\n        for _, d := range digits {\n            if !rcu.IsPrime(d) {\n                b1 = false\n                break\n            }\n        }\n        if b1 {\n            if len(digits) < 3 {\n                sprimes = append(sprimes, p)\n            } else {\n                b2 := rcu.IsPrime(digits[0]*10 + digits[1])\n                b3 := rcu.IsPrime(digits[1]*10 + digits[2])\n                if b2 && b3 {\n                    sprimes = append(sprimes, p)\n                }\n            }\n        }\n    }\n    fmt.Println(\"Found\", len(sprimes), \"primes < 500 where all substrings are also primes, namely:\")\n    fmt.Println(sprimes)\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(size_t limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (size_t i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (size_t p = 3; ; p += 2) {\n        size_t q = p * p;\n        if (q >= limit)\n            break;\n        if (sieve[p]) {\n            size_t inc = 2 * p;\n            for (; q < limit; q += inc)\n                sieve[q] = false;\n        }\n    }\n    return sieve;\n}\n\nbool substring_prime(const std::vector<bool>& sieve, unsigned int n) {\n    for (; n != 0; n /= 10) {\n        if (!sieve[n])\n            return false;\n        for (unsigned int p = 10; p < n; p *= 10) {\n            if (!sieve[n % p])\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::vector<bool> sieve = prime_sieve(limit);\n    for (unsigned int i = 2; i < limit; ++i) {\n        if (substring_prime(sieve, i))\n            std::cout << i << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57257, "name": "Substring primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(499)\n    var sprimes []int\n    for _, p := range primes {\n        digits := rcu.Digits(p, 10)\n        var b1 = true\n        for _, d := range digits {\n            if !rcu.IsPrime(d) {\n                b1 = false\n                break\n            }\n        }\n        if b1 {\n            if len(digits) < 3 {\n                sprimes = append(sprimes, p)\n            } else {\n                b2 := rcu.IsPrime(digits[0]*10 + digits[1])\n                b3 := rcu.IsPrime(digits[1]*10 + digits[2])\n                if b2 && b3 {\n                    sprimes = append(sprimes, p)\n                }\n            }\n        }\n    }\n    fmt.Println(\"Found\", len(sprimes), \"primes < 500 where all substrings are also primes, namely:\")\n    fmt.Println(sprimes)\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(size_t limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (size_t i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (size_t p = 3; ; p += 2) {\n        size_t q = p * p;\n        if (q >= limit)\n            break;\n        if (sieve[p]) {\n            size_t inc = 2 * p;\n            for (; q < limit; q += inc)\n                sieve[q] = false;\n        }\n    }\n    return sieve;\n}\n\nbool substring_prime(const std::vector<bool>& sieve, unsigned int n) {\n    for (; n != 0; n /= 10) {\n        if (!sieve[n])\n            return false;\n        for (unsigned int p = 10; p < n; p *= 10) {\n            if (!sieve[n % p])\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::vector<bool> sieve = prime_sieve(limit);\n    for (unsigned int i = 2; i < limit; ++i) {\n        if (substring_prime(sieve, i))\n            std::cout << i << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57258, "name": "Sylvester's sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    two := big.NewInt(2)\n    next := new(big.Int)\n    sylvester := []*big.Int{two}\n    prod := new(big.Int).Set(two)\n    count := 1\n    for count < 10 {\n        next.Add(prod, one)\n        sylvester = append(sylvester, new(big.Int).Set(next))\n        count++\n        prod.Mul(prod, next)\n    }\n    fmt.Println(\"The first 10 terms in the Sylvester sequence are:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sylvester[i])\n    }\n\n    sumRecip := new(big.Rat)\n    for _, s := range sylvester {\n        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))\n    }\n    fmt.Println(\"\\nThe sum of their reciprocals as a rational number is:\")\n    fmt.Println(sumRecip)\n    fmt.Println(\"\\nThe sum of their reciprocals as a decimal number (to 211 places) is:\")\n    fmt.Println(sumRecip.FloatString(211))\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing integer = boost::multiprecision::cpp_int;\nusing rational = boost::rational<integer>;\n\ninteger sylvester_next(const integer& n) {\n    return n * n - n + 1;\n}\n\nint main() {\n    std::cout << \"First 10 elements in Sylvester's sequence:\\n\";\n    integer term = 2;\n    rational sum = 0;\n    for (int i = 1; i <= 10; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        sum += rational(1, term);\n        term = sylvester_next(term);\n    }\n    std::cout << \"Sum of reciprocals: \" << sum << '\\n';\n}\n"}
{"id": 57259, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 57260, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "C++": "#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace std;\n\nstruct node\n{\n    int val;\n    unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n    nSolver()\n    {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] =  2;\n\tdx[2] =  1; dy[2] = -2; dx[3] =  1; dy[3] =  2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] =  1; \n\tdx[6] =  2; dy[6] = -1; dx[7] =  2; dy[7] =  1;\n    }\n\n    void solve( vector<string>& puzz, int max_wid )\n    {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t    arr[c].val = atoi( ( *i ).c_str() );\n\t    c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t    if( ( *i ) == \".\" )\n\t    {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t    }\n\t    c++;\n\t}\n\tdelete [] arr;\n    }\n\nprivate:\n    bool search( int x, int y, int w )\n    {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t    if( n->neighbors & ( 1 << d ) )\n\t    {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t    arr[a + b * wid].val = w;\n\t\t    if( search( a, b, w + 1 ) ) return true;\n\t\t    arr[a + b * wid].val = 0;\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n\n    unsigned char getNeighbors( int x, int y )\n    {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t    a = x + dx[xx], b = y + dy[xx];\n\t    if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t    if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n    }\n\n    void solveIt()\n    {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n    }\n\n    void findStart( int& x, int& y, int& z )\n    {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t    for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t    x = a; y = b;\n\t\t    z = arr[a + wid * b].val;\n\t\t}\n\n    }\n\n    int wid, hei, max, dx[8], dy[8];\n    node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n    int wid; string p;\n    \n    p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n    istringstream iss( p ); vector<string> puzz;\n    copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );\n    nSolver s; s.solve( puzz, wid );\n    int c = 0;\n    for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )\n    {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t    if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t    cout << ( *i ) << \" \";\n        }\n\telse cout << \"   \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n    }\n    cout << endl << endl;\n    return system( \"pause\" );\n}\n"}
{"id": 57261, "name": "Order disjoint list items", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype indexSort struct {\n\tval sort.Interface\n\tind []int\n}\n\nfunc (s indexSort) Len() int           { return len(s.ind) }\nfunc (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }\nfunc (s indexSort) Swap(i, j int) {\n\ts.val.Swap(s.ind[i], s.ind[j])\n\ts.ind[i], s.ind[j] = s.ind[j], s.ind[i]\n}\n\nfunc disjointSliceSort(m, n []string) []string {\n\ts := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}\n\tused := make(map[int]bool)\n\tfor _, nw := range n {\n\t\tfor i, mw := range m {\n\t\t\tif used[i] || mw != nw {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tused[i] = true\n\t\t\ts.ind = append(s.ind, i)\n\t\t\tbreak\n\t\t}\n\t}\n\tsort.Sort(s)\n\treturn s.val.(sort.StringSlice)\n}\n\nfunc disjointStringSort(m, n string) string {\n\treturn strings.Join(\n\t\tdisjointSliceSort(strings.Fields(m), strings.Fields(n)), \" \")\n}\n\nfunc main() {\n\tfor _, data := range []struct{ m, n string }{\n\t\t{\"the cat sat on the mat\", \"mat cat\"},\n\t\t{\"the cat sat on the mat\", \"cat mat\"},\n\t\t{\"A B C A B C A B C\", \"C A C A\"},\n\t\t{\"A B C A B D A B E\", \"E A D A\"},\n\t\t{\"A B\", \"B\"},\n\t\t{\"A B\", \"B A\"},\n\t\t{\"A B B A\", \"B A\"},\n\t} {\n\t\tmp := disjointStringSort(data.m, data.n)\n\t\tfmt.Printf(\"%s → %s » %s\\n\", data.m, data.n, mp)\n\t}\n\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\ntemplate <typename T>\nvoid print(const std::vector<T> v) {\n  std::cout << \"{ \";\n  for (const auto& e : v) {\n    std::cout << e << \" \";\n  }\n  std::cout << \"}\";\n}\n\ntemplate <typename T>\nauto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {\n  std::vector<T*> M_p(std::size(M));\n  for (auto i = 0; i < std::size(M_p); ++i) {\n    M_p[i] = &M[i];\n  }\n  for (auto e : N) {\n    auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {\n      if (c != nullptr) {\n        if (*c == e) return true;\n      }\n      return false;\n    });\n    if (i != std::end(M_p)) {\n      *i = nullptr;\n    }\n  }\n  for (auto i = 0; i < std::size(N); ++i) {\n    auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {\n      return c == nullptr;\n    });\n    if (j != std::end(M_p)) {\n      *j = &M[std::distance(std::begin(M_p), j)];\n      **j = N[i];\n    }\n  }\n  return M;\n}\n\nint main() {\n  std::vector<std::vector<std::vector<std::string>>> l = {\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" }, { \"mat\", \"cat\" } },\n    { { \"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\" },{ \"cat\", \"mat\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"C\", \"A\", \"B\", \"C\" },{ \"C\", \"A\", \"C\", \"A\" } },\n    { { \"A\", \"B\", \"C\", \"A\", \"B\", \"D\", \"A\", \"B\", \"E\" },{ \"E\", \"A\", \"D\", \"A\" } },\n    { { \"A\", \"B\" },{ \"B\" } },\n    { { \"A\", \"B\" },{ \"B\", \"A\" } },\n    { { \"A\", \"B\", \"B\", \"A\" },{ \"B\", \"A\" } }\n  };\n  for (const auto& e : l) {\n    std::cout << \"M: \";\n    print(e[0]);\n    std::cout << \", N: \";\n    print(e[1]);\n    std::cout << \", M': \";\n    auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);\n    print(res);\n    std::cout << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 57262, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 57263, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "C++": "#include <iostream> \n\nint main()\n{\n  std::cout <<\nR\"EOF(  A  raw  string  begins  with  R,  then a double-quote (\"),  then an optional\nidentifier (here I've used \"EOF\"),  then an opening parenthesis ('(').  If you\nuse  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot\ncontain a space,  either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n  It  ends with a closing parenthesis (')'),  the identifer (if you used one),\nand a double-quote.\n\n  All  characters are okay in a raw string,  no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}\n"}
{"id": 57264, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 57265, "name": "Ramanujan primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n"}
{"id": 57266, "name": "Ramanujan primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n"}
{"id": 57267, "name": "Ramanujan primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n", "C++": "#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nclass prime_counter {\npublic:\n    explicit prime_counter(int limit);\n    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }\n\nprivate:\n    std::vector<int> count_;\n};\n\nprime_counter::prime_counter(int limit) : count_(limit, 1) {\n    if (limit > 0)\n        count_[0] = 0;\n    if (limit > 1)\n        count_[1] = 0;\n    for (int i = 4; i < limit; i += 2)\n        count_[i] = 0;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (count_[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                count_[q] = 0;\n        }\n        sq += (p + 1) << 2;\n    }\n    std::partial_sum(count_.begin(), count_.end(), count_.begin());\n}\n\nint ramanujan_max(int n) {\n    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));\n}\n\nint ramanujan_prime(const prime_counter& pc, int n) {\n    int max = ramanujan_max(n);\n    for (int i = max; i >= 0; --i) {\n        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)\n            return i + 1;\n    }\n    return 0;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    prime_counter pc(1 + ramanujan_max(100000));\n    for (int i = 1; i <= 100; ++i) {\n        std::cout << std::setw(5) << ramanujan_prime(pc, i)\n                  << (i % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (int n = 1000; n <= 100000; n *= 10) {\n        std::cout << \"The \" << n << \"th Ramanujan prime is \" << ramanujan_prime(pc, n)\n              << \".\\n\";\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\nElapsed time: \"\n              << std::chrono::duration<double>(end - start).count() * 1000\n              << \" milliseconds\\n\";\n}\n"}
{"id": 57268, "name": "Achilles numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 57269, "name": "Achilles numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\ntemplate <typename T> void unique_sort(std::vector<T>& vector) {\n    std::sort(vector.begin(), vector.end());\n    vector.erase(std::unique(vector.begin(), vector.end()), vector.end());\n}\n\nauto perfect_powers(uint128_t n) {\n    std::vector<uint128_t> result;\n    for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)\n        for (uint128_t p = i * i; p < n; p *= i)\n            result.push_back(p);\n    unique_sort(result);\n    return result;\n}\n\nauto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {\n    std::vector<uint128_t> result;\n    auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));\n    auto s = sqrt(to / 8);\n    for (uint128_t b = 2; b <= c; ++b) {\n        uint128_t b3 = b * b * b;\n        for (uint128_t a = 2; a <= s; ++a) {\n            uint128_t p = b3 * a * a;\n            if (p >= to)\n                break;\n            if (p >= from && !binary_search(pps.begin(), pps.end(), p))\n                result.push_back(p);\n        }\n    }\n    unique_sort(result);\n    return result;\n}\n\nuint128_t totient(uint128_t n) {\n    uint128_t tot = n;\n    if ((n & 1) == 0) {\n        while ((n & 1) == 0)\n            n >>= 1;\n        tot -= tot >> 1;\n    }\n    for (uint128_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0) {\n            while (n % p == 0)\n                n /= p;\n            tot -= tot / p;\n        }\n    }\n    if (n > 1)\n        tot -= tot / n;\n    return tot;\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n\n    const uint128_t limit = 1000000000000000;\n\n    auto pps = perfect_powers(limit);\n    auto ach = achilles(1, 1000000, pps);\n\n    std::cout << \"First 50 Achilles numbers:\\n\";\n    for (size_t i = 0; i < 50 && i < ach.size(); ++i)\n        std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n\n    std::cout << \"\\nFirst 50 strong Achilles numbers:\\n\";\n    for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)\n        if (binary_search(ach.begin(), ach.end(), totient(ach[i])))\n            std::cout << std::setw(6) << ach[i]\n                      << (++count % 10 == 0 ? '\\n' : ' ');\n\n    int digits = 2;\n    std::cout << \"\\nNumber of Achilles numbers with:\\n\";\n    for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {\n        size_t count = achilles(from, to, pps).size();\n        std::cout << std::setw(2) << digits << \" digits: \" << count << '\\n';\n        from = to;\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 57270, "name": "Odd squarefree semiprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n"}
{"id": 57271, "name": "Odd squarefree semiprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool odd_square_free_semiprime(int n) {\n    if ((n & 1) == 0)\n        return false;\n    int count = 0;\n    for (int i = 3; i * i <= n; i += 2) {\n        for (; n % i == 0; n /= i) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return count == 1;\n}\n\nint main() {\n    const int n = 1000;\n    std::cout << \"Odd square-free semiprimes < \" << n << \":\\n\";\n    int count = 0;\n    for (int i = 1; i < n; i += 2) {\n        if (odd_square_free_semiprime(i)) {\n            ++count;\n            std::cout << std::setw(4) << i;\n            if (count % 20 == 0)\n                std::cout << '\\n';\n        }\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return 0;\n}\n"}
{"id": 57272, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n"}
{"id": 57273, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length/std::sqrt(2.0);\n    y_ = 2 * x_;\n    angle_ = 45;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F--XF--F--XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF+G+XF--F--XF+G+X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ -= length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n        case 'G':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 45) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 45) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_curve s;\n    s.write(out, 545, 7, 5);\n    return 0;\n}\n"}
{"id": 57274, "name": "Most frequent k chars distance", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n", "C++": "#include <string>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <sstream>\n\nstd::string mostFreqKHashing ( const std::string & input , int k ) {\n   std::ostringstream oss ;\n   std::map<char, int> frequencies ;\n   for ( char c : input ) {\n      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;\n   }\n   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;\n   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,\n\t         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; \n\t         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }\n\t         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;\n   for ( int i = 0 ; i < letters.size( ) ; i++ ) {\n      oss << std::get<0>( letters[ i ] ) ;\n      oss << std::get<1>( letters[ i ] ) ;\n   }\n   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;\n   if ( letters.size( ) >= k ) {\n      return output ;\n   }\n   else {\n      return output.append( \"NULL0\" ) ;\n   }\n}\n\nint mostFreqKSimilarity ( const std::string & first , const std::string & second ) {\n   int i = 0 ;\n   while ( i < first.length( ) - 1  ) {\n      auto found = second.find_first_of( first.substr( i , 2 ) ) ;\n      if ( found != std::string::npos ) \n\t return std::stoi ( first.substr( i , 2 )) ;\n      else \n\t i += 2 ;\n   }\n   return 0 ;\n}\n\nint mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {\n   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;\n}\n\nint main( ) {\n   std::string s1(\"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\" ) ;\n   std::string s2( \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\" ) ;\n   std::cout << \"MostFreqKHashing( s1 , 2 ) = \" << mostFreqKHashing( s1 , 2 ) << '\\n' ;\n   std::cout << \"MostFreqKHashing( s2 , 2 ) = \" << mostFreqKHashing( s2 , 2 ) << '\\n' ;\n   return 0 ;\n}\n"}
{"id": 57275, "name": "Palindromic primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n"}
{"id": 57276, "name": "Palindromic primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nunsigned int reverse(unsigned int base, unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= base)\n        rev = rev * base + (n % base);\n    return rev;\n}\n\nclass palindrome_generator {\npublic:\n    explicit palindrome_generator(unsigned int base)\n        : base_(base), upper_(base) {}\n    unsigned int next_palindrome();\n\nprivate:\n    unsigned int base_;\n    unsigned int lower_ = 1;\n    unsigned int upper_;\n    unsigned int next_ = 0;\n    bool even_ = false;\n};\n\nunsigned int palindrome_generator::next_palindrome() {\n    ++next_;\n    if (next_ == upper_) {\n        if (even_) {\n            lower_ = upper_;\n            upper_ *= base_;\n        }\n        next_ = lower_;\n        even_ = !even_;\n    }\n    return even_ ? next_ * upper_ + reverse(base_, next_)\n                 : next_ * lower_ + reverse(base_, next_ / base_);\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\nstd::string to_string(unsigned int base, unsigned int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nvoid print_palindromic_primes(unsigned int base, unsigned int limit) {\n    auto width =\n        static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));\n    unsigned int count = 0;\n    auto columns = 80 / (width + 1);\n    std::cout << \"Base \" << base << \" palindromic primes less than \" << limit\n              << \":\\n\";\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit) {\n        if (is_prime(palindrome)) {\n            ++count;\n            std::cout << std::setw(width) << to_string(base, palindrome)\n                      << (count % columns == 0 ? '\\n' : ' ');\n        }\n    }\n    if (count % columns != 0)\n        std::cout << '\\n';\n    std::cout << \"Count: \" << count << '\\n';\n}\n\nvoid count_palindromic_primes(unsigned int base, unsigned int limit) {\n    unsigned int count = 0;\n    palindrome_generator pgen(base);\n    unsigned int palindrome;\n    while ((palindrome = pgen.next_palindrome()) < limit)\n        if (is_prime(palindrome))\n            ++count;\n    std::cout << \"Number of base \" << base << \" palindromic primes less than \"\n              << limit << \": \" << count << '\\n';\n}\n\nint main() {\n    print_palindromic_primes(10, 1000);\n    std::cout << '\\n';\n    print_palindromic_primes(10, 100000);\n    std::cout << '\\n';\n    count_palindromic_primes(10, 1000000000);\n    std::cout << '\\n';\n    print_palindromic_primes(16, 500);\n}\n"}
{"id": 57277, "name": "Find words which contains all the vowels", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Words which contain all 5 vowels once in\", wordList, \"\\b:\\n\")\n    for _, word := range words {\n        ca, ce, ci, co, cu := 0, 0, 0, 0, 0\n        for _, r := range word {\n            switch r {\n            case 'a':\n                ca++\n            case 'e':\n                ce++\n            case 'i':\n                ci++\n            case 'o':\n                co++\n            case 'u':\n                cu++\n            }\n        }\n        if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {\n            count++\n            fmt.Printf(\"%2d: %s\\n\", count, word)\n        }\n    }\n}\n", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\nbool contains_all_vowels_once(const std::string& word) {\n    std::bitset<5> vowels;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        size_t bit = 0;\n        switch (ch) {\n        case 'a': bit = 0; break;\n        case 'e': bit = 1; break;\n        case 'i': bit = 2; break;\n        case 'o': bit = 3; break;\n        case 'u': bit = 4; break;\n        default: continue;\n        }\n        if (vowels.test(bit))\n            return false;\n        vowels.set(bit);\n    }\n    return vowels.all();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        if (word.size() > 10 && contains_all_vowels_once(word))\n            std::cout << std::setw(2) << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57278, "name": "Text completion", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n)\n\nfunc levenshtein(s, t string) int {\n    d := make([][]int, len(s)+1)\n    for i := range d {\n        d[i] = make([]int, len(t)+1)\n    }\n    for i := range d {\n        d[i][0] = i\n    }\n    for j := range d[0] {\n        d[0][j] = j\n    }\n    for j := 1; j <= len(t); j++ {\n        for i := 1; i <= len(s); i++ {\n            if s[i-1] == t[j-1] {\n                d[i][j] = d[i-1][j-1]\n            } else {\n                min := d[i-1][j]\n                if d[i][j-1] < min {\n                    min = d[i][j-1]\n                }\n                if d[i-1][j-1] < min {\n                    min = d[i-1][j-1]\n                }\n                d[i][j] = min + 1\n            }\n        }\n\n    }\n    return d[len(s)][len(t)]\n}\n\nfunc main() {\n    search := \"complition\"\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Fields(b)\n    var lev [4][]string\n    for _, word := range words {\n        s := string(word)\n        ld := levenshtein(search, s)\n        if ld < 4 {\n            lev[ld] = append(lev[ld], s)\n        }\n    }\n    fmt.Printf(\"Input word: %s\\n\\n\", search)\n    for i := 1; i < 4; i++ {\n        length := float64(len(search))\n        similarity := (length - float64(i)) * 100 / length\n        fmt.Printf(\"Words which are %4.1f%% similar:\\n\", similarity)\n        fmt.Println(lev[i])\n        fmt.Println()\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\n\nint levenshtein_distance(const std::string& str1, const std::string& str2) {\n    size_t m = str1.size(), n = str2.size();\n    std::vector<int> cost(n + 1);\n    std::iota(cost.begin(), cost.end(), 0);\n    for (size_t i = 0; i < m; ++i) {\n        cost[0] = i + 1;\n        int prev = i;\n        for (size_t j = 0; j < n; ++j) {\n            int c = (str1[i] == str2[j]) ? prev\n                : 1 + std::min(std::min(cost[j + 1], cost[j]), prev);\n            prev = cost[j + 1];\n            cost[j + 1] = c;\n        }\n    }\n    return cost[n];\n}\n\ntemplate <typename T>\nvoid print_vector(const std::vector<T>& vec) {\n    auto i = vec.begin();\n    if (i == vec.end())\n        return;\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 3) {\n        std::cerr << \"usage: \" << argv[0] << \" dictionary word\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ifstream in(argv[1]);\n    if (!in) {\n        std::cerr << \"Cannot open file \" << argv[1] << '\\n';\n        return EXIT_FAILURE;\n    }\n    std::string word(argv[2]);\n    if (word.empty()) {\n        std::cerr << \"Word must not be empty\\n\";\n        return EXIT_FAILURE;\n    }\n    constexpr size_t max_dist = 4;\n    std::vector<std::string> matches[max_dist + 1];\n    std::string match;\n    while (getline(in, match)) {\n        int distance = levenshtein_distance(word, match);\n        if (distance <= max_dist)\n            matches[distance].push_back(match);\n    }\n    for (size_t dist = 0; dist <= max_dist; ++dist) {\n        if (matches[dist].empty())\n            continue;\n        std::cout << \"Words at Levenshtein distance of \" << dist\n            << \" (\" << 100 - (100 * dist)/word.size()\n            << \"% similarity) from '\" << word << \"':\\n\";\n        print_vector(matches[dist]);\n        std::cout << \"\\n\\n\";\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57279, "name": "Anaprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = int(1e10)\n    const maxIndex = 9\n    primes := rcu.Primes(limit)\n    anaprimes := make(map[int][]int)\n    for _, p := range primes {\n        digs := rcu.Digits(p, 10)\n        key := 1\n        for _, dig := range digs {\n            key *= primes[dig]\n        }\n        if _, ok := anaprimes[key]; ok {\n            anaprimes[key] = append(anaprimes[key], p)\n        } else {\n            anaprimes[key] = []int{p}\n        }\n    }\n    largest := make([]int, maxIndex+1)\n    groups := make([][][]int, maxIndex+1)\n    for key := range anaprimes {\n        v := anaprimes[key]\n        nd := len(rcu.Digits(v[0], 10))\n        c := len(v)\n        if c > largest[nd-1] {\n            largest[nd-1] = c\n            groups[nd-1] = [][]int{v}\n        } else if c == largest[nd-1] {\n            groups[nd-1] = append(groups[nd-1], v)\n        }\n    }\n    j := 1000\n    for i := 2; i <= maxIndex; i++ {\n        js := rcu.Commatize(j)\n        ls := rcu.Commatize(largest[i])\n        fmt.Printf(\"Largest group(s) of anaprimes before %s: %s members:\\n\", js, ls)\n        sort.Slice(groups[i], func(k, l int) bool {\n            return groups[i][k][0] < groups[i][l][0]\n        })\n        for _, g := range groups[i] {\n            fmt.Printf(\"  First: %s  Last: %s\\n\", rcu.Commatize(g[0]), rcu.Commatize(g[len(g)-1]))\n        }\n        j *= 10\n        fmt.Println()\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <primesieve.hpp>\n\nusing digit_set = std::array<int, 10>;\n\ndigit_set get_digits(uint64_t n) {\n    digit_set result = {};\n    for (; n > 0; n /= 10)\n        ++result[n % 10];\n    return result;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    primesieve::iterator pi;\n    using map_type =\n        std::map<digit_set, std::vector<uint64_t>, std::greater<digit_set>>;\n    map_type anaprimes;\n    for (uint64_t limit = 1000; limit <= 10000000000;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > limit) {\n            size_t max_length = 0;\n            std::vector<map_type::iterator> groups;\n            for (auto i = anaprimes.begin(); i != anaprimes.end(); ++i) {\n                if (i->second.size() > max_length) {\n                    groups.clear();\n                    max_length = i->second.size();\n                }\n                if (max_length == i->second.size())\n                    groups.push_back(i);\n            }\n            std::cout << \"Largest group(s) of anaprimes before \" << limit\n                      << \": \" << max_length << \" members:\\n\";\n            for (auto i : groups) {\n                std::cout << \"  First: \" << i->second.front()\n                          << \"  Last: \" << i->second.back() << '\\n';\n            }\n            std::cout << '\\n';\n            anaprimes.clear();\n            limit *= 10;\n        }\n        anaprimes[get_digits(prime)].push_back(prime);\n    }\n}\n"}
{"id": 57280, "name": "Tropical algebra overloading", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar MinusInf = math.Inf(-1)\n\ntype MaxTropical struct{ r float64 }\n\nfunc newMaxTropical(r float64) MaxTropical {\n    if math.IsInf(r, 1) || math.IsNaN(r) {\n        log.Fatal(\"Argument must be a real number or negative infinity.\")\n    }\n    return MaxTropical{r}\n}\n\nfunc (t MaxTropical) eq(other MaxTropical) bool {\n    return t.r == other.r\n}\n\n\nfunc (t MaxTropical) add(other MaxTropical) MaxTropical {\n    if t.r == MinusInf {\n        return other\n    }\n    if other.r == MinusInf {\n        return t\n    }\n    return newMaxTropical(math.Max(t.r, other.r))\n}\n\n\nfunc (t MaxTropical) mul(other MaxTropical) MaxTropical {\n    if t.r == 0 {\n        return other\n    }\n    if other.r == 0 {\n        return t\n    }\n    return newMaxTropical(t.r + other.r)\n}\n\n\nfunc (t MaxTropical) pow(e int) MaxTropical {\n    if e < 1 {\n        log.Fatal(\"Exponent must be a positive integer.\")\n    }\n    if e == 1 {\n        return t\n    }\n    p := t\n    for i := 2; i <= e; i++ {\n        p = p.mul(t)\n    }\n    return p\n}\n\nfunc (t MaxTropical) String() string {\n    return fmt.Sprintf(\"%g\", t.r)\n}\n\nfunc main() {\n    \n    data := [][]float64{\n        {2, -2, 1},\n        {-0.001, MinusInf, 0},\n        {0, MinusInf, 1},\n        {1.5, -1, 0},\n        {-0.5, 0, 1},\n    }\n    for _, d := range data {\n        a := newMaxTropical(d[0])\n        b := newMaxTropical(d[1])\n        if d[2] == 0 {\n            fmt.Printf(\"%s ⊕ %s = %s\\n\", a, b, a.add(b))\n        } else {\n            fmt.Printf(\"%s ⊗ %s = %s\\n\", a, b, a.mul(b))\n        }\n    }\n\n    c := newMaxTropical(5)\n    fmt.Printf(\"%s ^ 7 = %s\\n\", c, c.pow(7))\n\n    d := newMaxTropical(8)\n    e := newMaxTropical(7)\n    f := c.mul(d.add(e))\n    g := c.mul(d).add(c.mul(e))\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) = %s\\n\", c, d, e, f)\n    fmt.Printf(\"%s ⊗ %s ⊕ %s ⊗ %s = %s\\n\", c, d, c, e, g)\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\\n\", c, d, e, c, d, c, e, f.eq(g))\n}\n", "C++": "#include <iostream>\n#include <optional>\n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n    \n    optional<double> m_value;\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n    \n    \n    TropicalAlgebra() = default;\n\n    \n    explicit TropicalAlgebra(double value) noexcept\n        : m_value{value} {}\n\n    \n    \n    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            *this = rhs;\n        }\n        else if (!rhs.m_value)\n        {\n            \n        }\n        else\n        {\n            \n            *m_value = max(*rhs.m_value, *m_value);\n        }\n\n        return *this;\n    }\n    \n    \n    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n    {\n        if(!m_value)\n        {\n            \n            \n        }\n        else if (!rhs.m_value)\n        {\n            \n            *this = rhs;\n        }\n        else\n        {\n            *m_value += *rhs.m_value;\n        }\n\n        return *this;\n    }\n};\n\n\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n    \n    lhs += rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n    auto result = base;\n    for(unsigned int i = 1; i < exponent; i++)\n    {\n        \n        result *= base;\n    }\n    return result;\n}\n\n\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n    if(!pt.m_value) cout << \"-Inf\\n\";\n    else cout << *pt.m_value << \"\\n\";\n    return os;\n}\n\nint main(void) {\n    const TropicalAlgebra a(-2);\n    const TropicalAlgebra b(-1);\n    const TropicalAlgebra c(-0.5);\n    const TropicalAlgebra d(-0.001);\n    const TropicalAlgebra e(0);\n    const TropicalAlgebra h(1.5);\n    const TropicalAlgebra i(2);\n    const TropicalAlgebra j(5);\n    const TropicalAlgebra k(7);\n    const TropicalAlgebra l(8);\n    const TropicalAlgebra m; \n    \n    cout << \"2 * -2 == \" << i * a;\n    cout << \"-0.001 + -Inf == \" << d + m;\n    cout << \"0 * -Inf == \" << e * m;\n    cout << \"1.5 + -1 == \" << h + b;\n    cout << \"-0.5 * 0 == \" << c * e;\n    cout << \"pow(5, 7) == \" << pow(j, 7);\n    cout << \"5 * (8 + 7)) == \" << j * (l + k);\n    cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n"}
{"id": 57281, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 57282, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n\nenum Moves { ROLL, HOLD };\n\n\nclass player\n{\npublic:\n    player()                     { current_score = round_score = 0; }\n    void addCurrScore()          { current_score += round_score; }\n    int getCurrScore()           { return current_score; }\n    int getRoundScore()          { return round_score; }\n    void addRoundScore( int rs ) { round_score += rs; }\n    void zeroRoundScore()        { round_score = 0; }\n    virtual int getMove() = 0;\n    virtual ~player() {}\n\nprotected:\n    int current_score, round_score;\n};\n\nclass RAND_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n    }\n};\n\nclass Q2WIN_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass AL20T_Player : public player\n{\n    virtual int getMove()\n    {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n    }\n};\n\nclass Auto_pigGame\n{\npublic:\n    Auto_pigGame() \n    {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n        _players[3] = new AL20T_Player();\n    }\n\n    ~Auto_pigGame()\n    {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n        delete _players[3];\n    }\n\n    void play()\n    {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t    switch( _players[p]->getMove() )\n\t    {\n\t\tcase ROLL:\n\t    \t    die = rand() % 6 + 1;\n\t\t    if( die == 1 )\n\t\t    {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t    }\n\t\t    _players[p]->addRoundScore( die );\n\t\t    cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t    \t    _players[p]->addCurrScore();\n\t\t    cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t    if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t    else nextTurn( p );\n\n\t    }\n\t}\n\tshowScore();\n    }\n\nprivate:\n    void nextTurn( int& p )\n    {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n    }\n\n    void showScore()\n    {\n\tcout << endl;\n\tcout << \"Player   I (RAND): \"  << _players[0]->getCurrScore() << endl;\n\tcout << \"Player  II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n        cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player  IV (AL20T): \"  << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n    }\n\n    player*\t_players[PLAYERS];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    Auto_pigGame pg;\n    pg.play();\n    return 0;\n}\n\n"}
{"id": 57283, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n1, continued fraction n2)", "Go": "package cf\n\nimport \"math\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG8 struct {\n\tA12, A1, A2, A int64\n\tB12, B1, B2, B int64\n}\n\n\nvar (\n\tNG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}\n\tNG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}\n\tNG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}\n\tNG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}\n)\n\nfunc (ng *NG8) needsIngest() bool {\n\tif ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {\n\t\treturn true\n\t}\n\tx := ng.A / ng.B\n\treturn ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x\n}\n\nfunc (ng *NG8) isDone() bool {\n\treturn ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0\n}\n\nfunc (ng *NG8) ingestWhich() bool { \n\tif ng.B == 0 && ng.B2 == 0 {\n\t\treturn true\n\t}\n\tif ng.B == 0 || ng.B2 == 0 {\n\t\treturn false\n\t}\n\tx1 := float64(ng.A1) / float64(ng.B1)\n\tx2 := float64(ng.A2) / float64(ng.B2)\n\tx := float64(ng.A) / float64(ng.B)\n\treturn math.Abs(x1-x) > math.Abs(x2-x)\n}\n\nfunc (ng *NG8) ingest(isN1 bool, t int64) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,\n\t\t\tng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,\n\t\t\tng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2\n\t}\n}\n\nfunc (ng *NG8) ingestInfinite(isN1 bool) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A2, ng.A, ng.B2, ng.B =\n\t\t\tng.A12, ng.A1,\n\t\t\tng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A1, ng.A, ng.B1, ng.B =\n\t\t\tng.A12, ng.A2,\n\t\t\tng.B12, ng.B2\n\t}\n}\n\nfunc (ng *NG8) egest(t int64) {\n\t\n\t\n\tng.A12, ng.A1, ng.A2, ng.A,\n\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\tng.B12, ng.B1, ng.B2, ng.B,\n\t\tng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t\n}\n\n\n\n\n\nfunc (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext1, next2 := N1(), N2()\n\t\tdone := false\n\t\tsinceEgest := 0\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tsinceEgest++\n\t\t\t\tif sinceEgest > limit {\n\t\t\t\t\tdone = true\n\t\t\t\t\treturn 0, false\n\t\t\t\t}\n\t\t\t\tisN1 := ng.ingestWhich()\n\t\t\t\tnext := next2\n\t\t\t\tif isN1 {\n\t\t\t\t\tnext = next1\n\t\t\t\t}\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(isN1, t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite(isN1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsinceEgest = 0\n\t\t\tt := ng.A / ng.B\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n", "C++": "\nclass NG_8 : public matrixNG {\n  private: int a12, a1, a2, a, b12, b1, b2, b, t;\n           double ab, a1b1, a2b2, a12b12;\n  const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}\n  const bool needTerm() {\n    if (b1==0 and b==0 and b2==0 and b12==0) return false;\n    if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;\n    if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;\n    if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;\n    if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;\n    thisTerm = (int)ab;\n    if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;\n      haveTerm = true; return false;\n    }\n    cfn = chooseCFN();\n    return true;\n  }\n  void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}\n  void consumeTerm(int n){\n    if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}\n    else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}\n  }\n  public:\n  NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){\n}};\n"}
{"id": 57284, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n1, continued fraction n2)", "Go": "package cf\n\nimport \"math\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG8 struct {\n\tA12, A1, A2, A int64\n\tB12, B1, B2, B int64\n}\n\n\nvar (\n\tNG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}\n\tNG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}\n\tNG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}\n\tNG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}\n)\n\nfunc (ng *NG8) needsIngest() bool {\n\tif ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {\n\t\treturn true\n\t}\n\tx := ng.A / ng.B\n\treturn ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x\n}\n\nfunc (ng *NG8) isDone() bool {\n\treturn ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0\n}\n\nfunc (ng *NG8) ingestWhich() bool { \n\tif ng.B == 0 && ng.B2 == 0 {\n\t\treturn true\n\t}\n\tif ng.B == 0 || ng.B2 == 0 {\n\t\treturn false\n\t}\n\tx1 := float64(ng.A1) / float64(ng.B1)\n\tx2 := float64(ng.A2) / float64(ng.B2)\n\tx := float64(ng.A) / float64(ng.B)\n\treturn math.Abs(x1-x) > math.Abs(x2-x)\n}\n\nfunc (ng *NG8) ingest(isN1 bool, t int64) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,\n\t\t\tng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A12, ng.A1, ng.A2, ng.A,\n\t\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\t\tng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,\n\t\t\tng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2\n\t}\n}\n\nfunc (ng *NG8) ingestInfinite(isN1 bool) {\n\tif isN1 {\n\t\t\n\t\t\n\t\tng.A2, ng.A, ng.B2, ng.B =\n\t\t\tng.A12, ng.A1,\n\t\t\tng.B12, ng.B1\n\t} else {\n\t\t\n\t\t\n\t\tng.A1, ng.A, ng.B1, ng.B =\n\t\t\tng.A12, ng.A2,\n\t\t\tng.B12, ng.B2\n\t}\n}\n\nfunc (ng *NG8) egest(t int64) {\n\t\n\t\n\tng.A12, ng.A1, ng.A2, ng.A,\n\t\tng.B12, ng.B1, ng.B2, ng.B =\n\t\tng.B12, ng.B1, ng.B2, ng.B,\n\t\tng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t\n}\n\n\n\n\n\nfunc (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext1, next2 := N1(), N2()\n\t\tdone := false\n\t\tsinceEgest := 0\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tsinceEgest++\n\t\t\t\tif sinceEgest > limit {\n\t\t\t\t\tdone = true\n\t\t\t\t\treturn 0, false\n\t\t\t\t}\n\t\t\t\tisN1 := ng.ingestWhich()\n\t\t\t\tnext := next2\n\t\t\t\tif isN1 {\n\t\t\t\t\tnext = next1\n\t\t\t\t}\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(isN1, t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite(isN1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsinceEgest = 0\n\t\t\tt := ng.A / ng.B\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n", "C++": "\nclass NG_8 : public matrixNG {\n  private: int a12, a1, a2, a, b12, b1, b2, b, t;\n           double ab, a1b1, a2b2, a12b12;\n  const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}\n  const bool needTerm() {\n    if (b1==0 and b==0 and b2==0 and b12==0) return false;\n    if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;\n    if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;\n    if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;\n    if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;\n    thisTerm = (int)ab;\n    if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;\n      haveTerm = true; return false;\n    }\n    cfn = chooseCFN();\n    return true;\n  }\n  void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}\n  void consumeTerm(int n){\n    if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}\n    else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}\n  }\n  public:\n  NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){\n}};\n"}
{"id": 57285, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n"}
{"id": 57286, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <vector>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty())\n        return;\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\nint main() {\n    std::map<integer, std::pair<bool, integer>> cache;\n    std::vector<integer> seeds, related, palindromes;\n    for (integer n = 1; n <= 10000; ++n) {\n        std::pair<bool, integer> p(true, n);\n        std::vector<integer> seen;\n        integer rev = reverse(n);\n        integer sum = n;\n        for (int i = 0; i < 500; ++i) {\n            sum += rev;\n            rev = reverse(sum);\n            if (rev == sum) {\n                p.first = false;\n                p.second = 0;\n                break;\n            }\n            auto iter = cache.find(sum);\n            if (iter != cache.end()) {\n                p = iter->second;\n                break;\n            }\n            seen.push_back(sum);\n        }\n        for (integer s : seen)\n            cache.emplace(s, p);\n        if (!p.first)\n            continue;\n        if (p.second == n)\n            seeds.push_back(n);\n        else\n            related.push_back(n);\n        if (n == reverse(n))\n            palindromes.push_back(n);\n    }\n    std::cout << \"number of seeds: \" << seeds.size() << '\\n';\n    std::cout << \"seeds: \";\n    print_vector(seeds);\n    std::cout << \"number of related: \" << related.size() << '\\n';\n    std::cout << \"palindromes: \";\n    print_vector(palindromes);\n    return 0;\n}\n"}
{"id": 57287, "name": "Base 16 numbers needing a to f", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n"}
{"id": 57288, "name": "Base 16 numbers needing a to f", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\n\nbool nondecimal(unsigned int n) {\n    for (; n > 0; n >>= 4) {\n        if ((n & 0xF) > 9)\n            return true;\n    }\n    return false;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 0; n < 501; ++n) {\n        if (nondecimal(n)) {\n            ++count;\n            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\n\\n\" << count << \" such numbers found.\\n\";\n}\n"}
{"id": 57289, "name": "Erdös-Selfridge categorization of primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nvar limit = int(math.Log(1e6) * 1e6 * 1.2) \nvar primes = rcu.Primes(limit)\n\nvar prevCats = make(map[int]int)\n\nfunc cat(p int) int {\n    if v, ok := prevCats[p]; ok {\n        return v\n    }\n    pf := rcu.PrimeFactors(p + 1)\n    all := true\n    for _, f := range pf {\n        if f != 2 && f != 3 {\n            all = false\n            break\n        }\n    }\n    if all {\n        return 1\n    }\n    if p > 2 {\n        len := len(pf)\n        for i := len - 1; i >= 1; i-- {\n            if pf[i-1] == pf[i] {\n                pf = append(pf[:i], pf[i+1:]...)\n            }\n        }\n    }\n    for c := 2; c <= 11; c++ {\n        all := true\n        for _, f := range pf {\n            if cat(f) >= c {\n                all = false\n                break\n            }\n        }\n        if all {\n            prevCats[p] = c\n            return c\n        }\n    }\n    return 12\n}\n\nfunc main() {\n    es := make([][]int, 12)\n    fmt.Println(\"First 200 primes:\\n\")\n    for _, p := range primes[0:200] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 6; c++ {\n        if len(es[c-1]) > 0 {\n            fmt.Println(\"Category\", c, \"\\b:\")\n            fmt.Println(es[c-1])\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"First million primes:\\n\")\n    for _, p := range primes[200:1e6] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 12; c++ {\n        e := es[c-1]\n        if len(e) > 0 {\n            format := \"Category %-2d: First = %7d  Last = %8d  Count = %6d\\n\"\n            fmt.Printf(format, c, e[0], e[len(e)-1], len(e))\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <primesieve.hpp>\n\nclass erdos_selfridge {\npublic:\n    explicit erdos_selfridge(int limit);\n    uint64_t get_prime(int index) const { return primes_[index].first; }\n    int get_category(int index);\n\nprivate:\n    std::vector<std::pair<uint64_t, int>> primes_;\n    size_t get_index(uint64_t prime) const;\n};\n\nerdos_selfridge::erdos_selfridge(int limit) {\n    primesieve::iterator iter;\n    for (int i = 0; i < limit; ++i)\n        primes_.emplace_back(iter.next_prime(), 0);\n}\n\nint erdos_selfridge::get_category(int index) {\n    auto& pair = primes_[index];\n    if (pair.second != 0)\n        return pair.second;\n    int max_category = 0;\n    uint64_t n = pair.first + 1;\n    for (int i = 0; n > 1; ++i) {\n        uint64_t p = primes_[i].first;\n        if (p * p > n)\n            break;\n        int count = 0;\n        for (; n % p == 0; ++count)\n            n /= p;\n        if (count != 0) {\n            int category = (p <= 3) ? 1 : 1 + get_category(i);\n            max_category = std::max(max_category, category);\n        }\n    }\n    if (n > 1) {\n        int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));\n        max_category = std::max(max_category, category);\n    }\n    pair.second = max_category;\n    return max_category;\n}\n\nsize_t erdos_selfridge::get_index(uint64_t prime) const {\n    auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,\n                               [](const std::pair<uint64_t, int>& p,\n                                  uint64_t n) { return p.first < n; });\n    assert(it != primes_.end());\n    assert(it->first == prime);\n    return std::distance(primes_.begin(), it);\n}\n\nauto get_primes_by_category(erdos_selfridge& es, int limit) {\n    std::map<int, std::vector<uint64_t>> primes_by_category;\n    for (int i = 0; i < limit; ++i) {\n        uint64_t prime = es.get_prime(i);\n        int category = es.get_category(i);\n        primes_by_category[category].push_back(prime);\n    }\n    return primes_by_category;\n}\n\nint main() {\n    const int limit1 = 200, limit2 = 1000000;\n\n    erdos_selfridge es(limit2);\n\n    std::cout << \"First 200 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit1)) {\n        std::cout << \"Category \" << p.first << \":\\n\";\n        for (size_t i = 0, n = p.second.size(); i != n; ++i) {\n            std::cout << std::setw(4) << p.second[i]\n                      << ((i + 1) % 15 == 0 ? '\\n' : ' ');\n        }\n        std::cout << \"\\n\\n\";\n    }\n\n    std::cout << \"First 1,000,000 primes:\\n\";\n    for (const auto& p : get_primes_by_category(es, limit2)) {\n        const auto& v = p.second;\n        std::cout << \"Category \" << std::setw(2) << p.first << \": \"\n                  << \"first = \" << std::setw(7) << v.front()\n                  << \"  last = \" << std::setw(8) << v.back()\n                  << \"  count = \" << v.size() << '\\n';\n    }\n}\n"}
{"id": 57290, "name": "Range modifications", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype rng struct{ from, to int }\n\ntype fn func(rngs *[]rng, n int)\n\nfunc (r rng) String() string { return fmt.Sprintf(\"%d-%d\", r.from, r.to) }\n\nfunc rangesAdd(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        rngs = append(rngs, rng{n, n})\n        return rngs\n    }\n    for i, r := range rngs {\n        if n < r.from-1 {\n            rngs = append(rngs, rng{})\n            copy(rngs[i+1:], rngs[i:])\n            rngs[i] = rng{n, n}\n            return rngs\n        } else if n == r.from-1 {\n            rngs[i] = rng{n, r.to}\n            return rngs\n        } else if n <= r.to {\n            return rngs\n        } else if n == r.to+1 {\n            rngs[i] = rng{r.from, n}\n            if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) {\n                rngs[i] = rng{r.from, rngs[i+1].to}\n                copy(rngs[i+1:], rngs[i+2:])\n                rngs[len(rngs)-1] = rng{}\n                rngs = rngs[:len(rngs)-1]\n            }\n            return rngs\n        } else if i == len(rngs)-1 {\n            rngs = append(rngs, rng{n, n})\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc rangesRemove(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        return rngs\n    }\n    for i, r := range rngs {\n        if n <= r.from-1 {\n            return rngs\n        } else if n == r.from && n == r.to {\n            copy(rngs[i:], rngs[i+1:])\n            rngs[len(rngs)-1] = rng{}\n            rngs = rngs[:len(rngs)-1]\n            return rngs\n        } else if n == r.from {\n            rngs[i] = rng{n + 1, r.to}\n            return rngs\n        } else if n < r.to {\n            rngs[i] = rng{r.from, n - 1}\n            rngs = append(rngs, rng{})\n            copy(rngs[i+2:], rngs[i+1:])\n            rngs[i+1] = rng{n + 1, r.to}\n            return rngs\n        } else if n == r.to {\n            rngs[i] = rng{r.from, n - 1}\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc standard(rngs []rng) string {\n    if len(rngs) == 0 {\n        return \"\"\n    }\n    var sb strings.Builder\n    for _, r := range rngs {\n        sb.WriteString(fmt.Sprintf(\"%s,\", r))\n    }\n    s := sb.String()\n    return s[:len(s)-1]\n}\n\nfunc main() {\n    const add = 0\n    const remove = 1\n    fns := []fn{\n        func(prngs *[]rng, n int) {\n            *prngs = rangesAdd(*prngs, n)\n            fmt.Printf(\"       add %2d => %s\\n\", n, standard(*prngs))\n        },\n        func(prngs *[]rng, n int) {\n            *prngs = rangesRemove(*prngs, n)\n            fmt.Printf(\"    remove %2d => %s\\n\", n, standard(*prngs))\n        },\n    }\n\n    var rngs []rng\n    ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}}\n    fmt.Printf(\"Start: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 3}, {5, 5}}\n    ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 5}, {10, 25}, {27, 30}}\n    ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n}\n", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <list>\n\nstruct range {\n    range(int lo, int hi) : low(lo), high(hi) {}\n    int low;\n    int high;\n};\n\nstd::ostream& operator<<(std::ostream& out, const range& r) {\n    return out << r.low << '-' << r.high;\n}\n\nclass ranges {\npublic:\n    ranges() {}\n    explicit ranges(std::initializer_list<range> init) : ranges_(init) {}\n    void add(int n);\n    void remove(int n);\n    bool empty() const { return ranges_.empty(); }\nprivate:\n    friend std::ostream& operator<<(std::ostream& out, const ranges& r);\n    std::list<range> ranges_;\n};\n\nvoid ranges::add(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n + 1 < i->low) {\n            ranges_.emplace(i, n, n);\n            return;\n        }\n        if (n > i->high + 1)\n            continue;\n        if (n + 1 == i->low)\n            i->low = n;\n        else if (n == i->high + 1)\n            i->high = n;\n        else\n            return;\n        if (i != ranges_.begin()) {\n            auto prev = std::prev(i);\n            if (prev->high + 1 == i->low) {\n                i->low = prev->low;\n                ranges_.erase(prev);\n            }\n        }\n        auto next = std::next(i);\n        if (next != ranges_.end() && next->low - 1 == i->high) {\n            i->high = next->high;\n            ranges_.erase(next);\n        }\n        return;\n    }\n    ranges_.emplace_back(n, n);\n}\n\nvoid ranges::remove(int n) {\n    for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {\n        if (n < i->low)\n            return;\n        if (n == i->low) {\n            if (++i->low > i->high)\n                ranges_.erase(i);\n            return;\n        }\n        if (n == i->high) {\n            if (--i->high < i->low)\n                ranges_.erase(i);\n            return;\n        }\n        if (n > i->low & n < i->high) {\n            int low = i->low;\n            i->low = n + 1;\n            ranges_.emplace(i, low, n - 1);\n            return;\n        }\n    }\n}\n\nstd::ostream& operator<<(std::ostream& out, const ranges& r) {\n    if (!r.empty()) {\n        auto i = r.ranges_.begin();\n        out << *i++;\n        for (; i != r.ranges_.end(); ++i)\n            out << ',' << *i;\n    }\n    return out;\n}\n\nvoid test_add(ranges& r, int n) {\n    r.add(n);\n    std::cout << \"       add \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test_remove(ranges& r, int n) {\n    r.remove(n);\n    std::cout << \"    remove \" << std::setw(2) << n << \" => \" << r << '\\n';\n}\n\nvoid test1() {\n    ranges r;\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 77);\n    test_add(r, 79);\n    test_add(r, 78);\n    test_remove(r, 77);\n    test_remove(r, 78);\n    test_remove(r, 79);\n}\n\nvoid test2() {\n    ranges r{{1,3}, {5,5}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 1);\n    test_remove(r, 4);\n    test_add(r, 7);\n    test_add(r, 8);\n    test_add(r, 6);\n    test_remove(r, 7);\n}\n\nvoid test3() {\n    ranges r{{1,5}, {10,25}, {27,30}};\n    std::cout << \"Start: \\\"\" << r << \"\\\"\\n\";\n    test_add(r, 26);\n    test_add(r, 9);\n    test_add(r, 7);\n    test_remove(r, 26);\n    test_remove(r, 9);\n    test_remove(r, 7);\n}\n\nint main() {\n    test1();\n    std::cout << '\\n';\n    test2();\n    std::cout << '\\n';\n    test3();\n    return 0;\n}\n"}
{"id": 57291, "name": "Juggler sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n"}
{"id": 57292, "name": "Juggler sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n", "C++": "#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nauto juggler(int n) {\n    assert(n >= 1);\n    int count = 0, max_count = 0;\n    big_int a = n, max = n;\n    while (a != 1) {\n        if (a % 2 == 0)\n            a = sqrt(a);\n        else\n            a = sqrt(big_int(a * a * a));\n        ++count;\n        if (a > max) {\n            max = a;\n            max_count = count;\n        }\n    }\n    return std::make_tuple(count, max_count, max, max.get_str().size());\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"n    l[n]  i[n]   h[n]\\n\";\n    std::cout << \"--------------------------------\\n\";\n    for (int n = 20; n < 40; ++n) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(2) << n << \"    \" << std::setw(2) << count\n                  << \"    \" << std::setw(2) << max_count << \"    \" << max\n                  << '\\n';\n    }\n    std::cout << '\\n';\n    std::cout << \"       n       l[n]   i[n]   d[n]\\n\";\n    std::cout << \"----------------------------------------\\n\";\n    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,\n                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,\n                  92502777, 172376627, 604398963}) {\n        auto [count, max_count, max, digits] = juggler(n);\n        std::cout << std::setw(11) << n << \"    \" << std::setw(3) << count\n                  << \"    \" << std::setw(3) << max_count << \"    \" << digits\n                  << '\\n';\n    }\n}\n"}
{"id": 57293, "name": "Sierpinski square curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n"}
{"id": 57294, "name": "Powerful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 57295, "name": "Powerful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_square_free(uint64_t n) {\n    static constexpr uint64_t primes[] {\n        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97\n    }; \n    for (auto p : primes) {\n        auto p2 = p * p;\n        if (p2 > n)\n            break;\n        if (n % p2 == 0)\n            return false;\n    }\n    return true;\n}\n\nuint64_t iroot(uint64_t n, uint64_t r) {\n    \n    static constexpr double adj = 1e-6;\n    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);\n}\n\nuint64_t ipow(uint64_t n, uint64_t p) {\n    uint64_t prod = 1;\n    for (; p > 0; p >>= 1) {\n        if (p & 1)\n            prod *= n;\n        n *= n;\n    }\n    return prod;\n}\n\nstd::vector<uint64_t> powerful(uint64_t n, uint64_t k) {\n    std::vector<uint64_t> result;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r < k) {\n            result.push_back(m);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))\n                continue;\n            f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    std::sort(result.begin(), result.end());\n    return result;\n}\n\nuint64_t powerful_count(uint64_t n, uint64_t k) {\n    uint64_t count = 0;\n    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {\n        if (r <= k) {\n            count += iroot(n/m, r);\n            return;\n        }\n        uint64_t root = iroot(n/m, r);\n        for (uint64_t v = 1; v <= root; ++v) {\n            if (is_square_free(v) && std::gcd(m, v) == 1)\n                f(m * ipow(v, r), r - 1);\n        }\n    };\n    f(1, 2*k - 1);\n    return count;\n}\n\nint main() {\n    const size_t max = 5;\n    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {\n        auto result = powerful(p, k);\n        std::cout << result.size() << \" \" << k\n            << \"-powerful numbers <= 10^\" << k << \":\";\n        for (size_t i = 0; i < result.size(); ++i) {\n            if (i == max)\n                std::cout << \" ...\";\n            else if (i < max || i + max >= result.size())\n                std::cout << ' ' << result[i];\n        }\n        std::cout << '\\n';\n    }\n    std::cout << '\\n';\n    for (uint64_t k = 2; k <= 10; ++k) {\n        std::cout << \"Count of \" << k << \"-powerful numbers <= 10^j for 0 <= j < \"\n            << k + 10 << \":\";\n        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)\n            std::cout << ' ' << powerful_count(p, k);\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 57296, "name": "Fixed length records", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc reverseBytes(bytes []byte) {\n    for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {\n        bytes[i], bytes[j] = bytes[j], bytes[i]\n    }\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    in, err := os.Open(\"infile.dat\")\n    check(err)\n    defer in.Close()\n\n    out, err := os.Create(\"outfile.dat\")\n    check(err)\n\n    record := make([]byte, 80)\n    empty := make([]byte, 80)\n    for {\n        n, err := in.Read(record)\n        if err != nil {\n            if n == 0 {\n                break \n            } else {\n                out.Close()\n                log.Fatal(err)\n            }\n        }\n        reverseBytes(record)\n        out.Write(record)\n        copy(record, empty)\n    }\n    out.Close()\n\n    \n    \n    cmd := exec.Command(\"dd\", \"if=outfile.dat\", \"cbs=80\", \"conv=unblock\")\n    bytes, err := cmd.Output()\n    check(err)\n    fmt.Println(string(bytes))\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nvoid reverse(std::istream& in, std::ostream& out) {\n    constexpr size_t record_length = 80;\n    char record[record_length];\n    while (in.read(record, record_length)) {\n        std::reverse(std::begin(record), std::end(record));\n        out.write(record, record_length);\n    }\n    out.flush();\n}\n\nint main(int argc, char** argv) {\n    std::ifstream in(\"infile.dat\", std::ios_base::binary);\n    if (!in) {\n        std::cerr << \"Cannot open input file\\n\";\n        return EXIT_FAILURE;\n    }\n    std::ofstream out(\"outfile.dat\", std::ios_base::binary);\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    try {\n        in.exceptions(std::ios_base::badbit);\n        out.exceptions(std::ios_base::badbit);\n        reverse(in, out);\n    } catch (const std::exception& ex) {\n        std::cerr << \"I/O error: \" << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57297, "name": "Find words whose first and last three letters are equal", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    count := 0\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {\n            count++\n            fmt.Printf(\"%d: %s\\n\", count, s)\n        }\n    }\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        const size_t len = word.size();\n        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)\n            std::cout << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57298, "name": "Giuga numbers", "Go": "package main\n\nimport \"fmt\"\n\nvar factors []int\nvar inc = []int{4, 2, 4, 2, 4, 6, 2, 6}\n\n\n\nfunc primeFactors(n int) {\n    factors = factors[:0]\n    factors = append(factors, 2)\n    last := 2\n    n /= 2\n    for n%3 == 0 {\n        if last == 3 {\n            factors = factors[:0]\n            return\n        }\n        last = 3\n        factors = append(factors, 3)\n        n /= 3\n    }\n    for n%5 == 0 {\n        if last == 5 {\n            factors = factors[:0]\n            return\n        }\n        last = 5\n        factors = append(factors, 5)\n        n /= 5\n    }\n    for k, i := 7, 0; k*k <= n; {\n        if n%k == 0 {\n            if last == k {\n                factors = factors[:0]\n                return\n            }\n            last = k\n            factors = append(factors, k)\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        factors = append(factors, n)\n    }\n}\n\nfunc main() {\n    const limit = 5\n    var giuga []int\n    \n    for n := 6; len(giuga) < limit; n += 4 {\n        primeFactors(n)\n        \n        if len(factors) > 2 {\n            isGiuga := true\n            for _, f := range factors {\n                if (n/f-1)%f != 0 {\n                    isGiuga = false\n                    break\n                }\n            }\n            if isGiuga {\n                giuga = append(giuga, n)\n            }\n        }\n    }\n    fmt.Println(\"The first\", limit, \"Giuga numbers are:\")\n    fmt.Println(giuga)\n}\n", "C++": "#include <iostream>\n\n\nbool is_giuga(unsigned int n) {\n    unsigned int m = n / 2;\n    auto test_factor = [&m, n](unsigned int p) -> bool {\n        if (m % p != 0)\n            return true;\n        m /= p;\n        return m % p != 0 && (n / p - 1) % p == 0;\n    };\n    if (!test_factor(3) || !test_factor(5))\n        return false;\n    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n    for (unsigned int p = 7, i = 0; p * p <= m; ++i) {\n        if (!test_factor(p))\n            return false;\n        p += wheel[i & 7];\n    }\n    return m == 1 || (n / m - 1) % m == 0;\n}\n\nint main() {\n    std::cout << \"First 5 Giuga numbers:\\n\";\n    \n    for (unsigned int i = 0, n = 6; i < 5; n += 4) {\n        if (is_giuga(n)) {\n            std::cout << n << '\\n';\n            ++i;\n        }\n    }\n}\n"}
{"id": 57299, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 57300, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n\n\n\nstd::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)\n{\n\tstd::string r = \"\";\n\n\tif (remainder) \n\t{\n\t\tr = \" r: \" + std::to_string(polynomial.back());\n\t\tpolynomial.pop_back();\n\t}\n\n\tstd::string formatted = \"\";\n\t\n\tint degree = polynomial.size() - 1;\n\tint d = degree;\n\n\tfor (int i : polynomial)\n\t{\n\t\tif (d < degree)\n\t\t{\n\t\t\tif (i >= 0) \n\t\t\t{\n\t\t\t\tformatted += \" + \";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tformatted += \" - \";\n\t\t\t}\n\t\t}\n\n\t\tformatted += std::to_string(abs(i));\n\n\t\tif (d > 1)\n\t\t{\n\t\t\tformatted += \"x^\" + std::to_string(d);\n\t\t}\n\t\telse if (d == 1)\n\t\t{\n\t\t\tformatted += \"x\";\n\t\t}\n\n\t\td--;\n\t}\n\n\treturn formatted;\n}\n\n\n\nstd::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)\n{\n\tstd::vector<int> quotient;\n\tquotient = dividend;\n\n\tint normalizer = divisor[0];\n\t\n\tfor (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)\n\t{\n\t\tquotient[i] /= normalizer;\n\t\tint coef = quotient[i];\n\n\t\tif (coef != 0) \n\t\t{\n\t\t\tfor (int j = 1; j < divisor.size(); j++)\n\t\t\t{\n\t\t\t\tquotient[i + j] += -divisor[j] * coef;\n\t\t\t}\n        }\n\n\t}\n\n\treturn quotient;\n}\n\n\n\nint main(int argc, char **argv) \n{\n\tstd::vector<int> dividend{ 1, -12, 0, -42};\n\tstd::vector<int> divisor{ 1, -3};\n\n\tstd::cout << frmtPolynomial(dividend) << \"\\n\";\n\tstd::cout << frmtPolynomial(divisor) << \"\\n\";\n\n\tstd::vector<int> quotient = syntheticDiv(dividend, divisor);\n\n\tstd::cout << frmtPolynomial(quotient, true) << \"\\n\";\n\n}\n"}
{"id": 57301, "name": "Numbers whose count of divisors is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    for ; i*i <= n; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const limit = 1e5\n    var results []int\n    for i := 2; i * i < limit; i++ {\n        n := countDivisors(i * i)\n        if n > 2 && rcu.IsPrime(n) {\n            results = append(results, i * i)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Positive integers under %7s whose number of divisors is an odd prime:\\n\", climit)\n    under1000 := 0\n    for i, n := range results {\n        fmt.Printf(\"%7s\", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        if n < 1000 {\n            under1000++\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such integers (%d under 1,000).\\n\", len(results), under1000)\n}\n", "C++": "#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n\nint divisor_count(int n) {\n    int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    for (int p = 3; p * p <= n; p += 2) {\n        int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nbool is_prime(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 (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(int argc, char** argv) {\n    int limit = 1000;\n    switch (argc) {\n    case 1:\n        break;\n    case 2:\n        limit = std::strtol(argv[1], nullptr, 10);\n        if (limit <= 0) {\n            std::cerr << \"Invalid limit\\n\";\n            return EXIT_FAILURE;\n        }\n        break;\n    default:\n        std::cerr << \"usage: \" << argv[0] << \" [limit]\\n\";\n        return EXIT_FAILURE;\n    }\n    int width = static_cast<int>(std::ceil(std::log10(limit)));\n    int count = 0;\n    for (int i = 1;; ++i) {\n        int n = i * i;\n        if (n >= limit)\n            break;\n        int divisors = divisor_count(n);\n        if (divisors != 2 && is_prime(divisors))\n            std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57302, "name": "Numbers whose count of divisors is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    for ; i*i <= n; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const limit = 1e5\n    var results []int\n    for i := 2; i * i < limit; i++ {\n        n := countDivisors(i * i)\n        if n > 2 && rcu.IsPrime(n) {\n            results = append(results, i * i)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Positive integers under %7s whose number of divisors is an odd prime:\\n\", climit)\n    under1000 := 0\n    for i, n := range results {\n        fmt.Printf(\"%7s\", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        if n < 1000 {\n            under1000++\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such integers (%d under 1,000).\\n\", len(results), under1000)\n}\n", "C++": "#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n\nint divisor_count(int n) {\n    int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    for (int p = 3; p * p <= n; p += 2) {\n        int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nbool is_prime(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 (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(int argc, char** argv) {\n    int limit = 1000;\n    switch (argc) {\n    case 1:\n        break;\n    case 2:\n        limit = std::strtol(argv[1], nullptr, 10);\n        if (limit <= 0) {\n            std::cerr << \"Invalid limit\\n\";\n            return EXIT_FAILURE;\n        }\n        break;\n    default:\n        std::cerr << \"usage: \" << argv[0] << \" [limit]\\n\";\n        return EXIT_FAILURE;\n    }\n    int width = static_cast<int>(std::ceil(std::log10(limit)));\n    int count = 0;\n    for (int i = 1;; ++i) {\n        int n = i * i;\n        if (n >= limit)\n            break;\n        int divisors = divisor_count(n);\n        if (divisors != 2 && is_prime(divisors))\n            std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\\n' : ' ');\n    }\n    std::cout << \"\\nCount: \" << count << '\\n';\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57303, "name": "Odd words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing word_list = std::vector<std::pair<std::string, std::string>>;\n\nvoid print_words(std::ostream& out, const word_list& words) {\n    int n = 1;\n    for (const auto& pair : words) {\n        out << std::right << std::setw(2) << n++ << \": \"\n            << std::left << std::setw(14) << pair.first\n            << pair.second << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    const int min_length = 5;\n    std::string line;\n    std::set<std::string> dictionary;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            dictionary.insert(line);\n    }\n\n    word_list odd_words, even_words;\n\n    for (const std::string& word : dictionary) {\n        if (word.size() < min_length + 2*(min_length/2))\n            continue;\n        std::string odd_word, even_word;\n        for (auto w = word.begin(); w != word.end(); ++w) {\n            odd_word += *w;\n            if (++w == word.end())\n                break;\n            even_word += *w;\n        }\n\n        if (dictionary.find(odd_word) != dictionary.end())\n            odd_words.emplace_back(word, odd_word);\n\n        if (dictionary.find(even_word) != dictionary.end())\n            even_words.emplace_back(word, even_word);\n    }\n\n    std::cout << \"Odd words:\\n\";\n    print_words(std::cout, odd_words);\n\n    std::cout << \"\\nEven words:\\n\";\n    print_words(std::cout, even_words);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57304, "name": "Tree datastructures", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n    if level == 0 {\n        fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n    }\n    fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\"  \", level), n.name)\n    for _, c := range n.children {\n        fmt.Fprintf(w, \"%s\", strings.Repeat(\"  \", level+1))\n        printNest(c, level+1, w)\n    }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n    fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n    for _, n := range iNodes {\n        fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n    }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n    *iNodes = append(*iNodes, iNode{level, n.name})\n    for _, c := range n.children {\n        toIndent(c, level+1, iNodes)\n    }\n}\n\nfunc main() {\n    n1 := nNode{\"RosettaCode\", nil}\n    n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n    n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n    n1.children = append(n1.children, n2, n3)\n\n    var sb strings.Builder\n    printNest(n1, 0, &sb)\n    s1 := sb.String()\n    fmt.Print(s1)\n\n    var iNodes []iNode\n    toIndent(n1, 0, &iNodes)\n    printIndent(iNodes, os.Stdout)\n\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    sb.Reset()\n    printNest(n, 0, &sb)\n    s2 := sb.String()\n    fmt.Print(s2)\n\n    fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n#include <utility>\n#include <vector>\n\nclass nest_tree;\n\nbool operator==(const nest_tree&, const nest_tree&);\n\nclass nest_tree {\npublic:\n    explicit nest_tree(const std::string& name) : name_(name) {}\n    nest_tree& add_child(const std::string& name) {\n        children_.emplace_back(name);\n        return children_.back();\n    }\n    void print(std::ostream& out) const {\n        print(out, 0);\n    }\n    const std::string& name() const {\n        return name_;\n    }\n    const std::list<nest_tree>& children() const {\n        return children_;\n    }\n    bool equals(const nest_tree& n) const {\n        return name_ == n.name_ && children_ == n.children_;\n    }\nprivate:\n    void print(std::ostream& out, int level) const {\n        std::string indent(level * 4, ' ');\n        out << indent << name_ << '\\n';\n        for (const nest_tree& child : children_)\n            child.print(out, level + 1);\n    }\n    std::string name_;\n    std::list<nest_tree> children_;\n};\n\nbool operator==(const nest_tree& a, const nest_tree& b) {\n    return a.equals(b);\n}\n\nclass indent_tree {\npublic:\n    explicit indent_tree(const nest_tree& n) {\n        items_.emplace_back(0, n.name());\n        from_nest(n, 0);\n    }\n    void print(std::ostream& out) const {\n        for (const auto& item : items_)\n            std::cout << item.first << ' ' << item.second << '\\n';\n    }\n    nest_tree to_nest() const {\n        nest_tree n(items_[0].second);\n        to_nest_(n, 1, 0);\n        return n;\n    }\nprivate:\n    void from_nest(const nest_tree& n, int level) {\n        for (const nest_tree& child : n.children()) {\n            items_.emplace_back(level + 1, child.name());\n            from_nest(child, level + 1);\n        }\n    }\n    size_t to_nest_(nest_tree& n, size_t pos, int level) const {\n        while (pos < items_.size() && items_[pos].first == level + 1) {\n            nest_tree& child = n.add_child(items_[pos].second);\n            pos = to_nest_(child, pos + 1, level + 1);\n        }\n        return pos;\n    }\n    std::vector<std::pair<int, std::string>> items_;\n};\n\nint main() {\n    nest_tree n(\"RosettaCode\");\n    auto& child1 = n.add_child(\"rocks\");\n    auto& child2 = n.add_child(\"mocks\");\n    child1.add_child(\"code\");\n    child1.add_child(\"comparison\");\n    child1.add_child(\"wiki\");\n    child2.add_child(\"trolling\");\n    \n    std::cout << \"Initial nest format:\\n\";\n    n.print(std::cout);\n    \n    indent_tree i(n);\n    std::cout << \"\\nIndent format:\\n\";\n    i.print(std::cout);\n    \n    nest_tree n2(i.to_nest());\n    std::cout << \"\\nFinal nest format:\\n\";\n    n2.print(std::cout);\n\n    std::cout << \"\\nAre initial and final nest formats equal? \"\n        << std::boolalpha << n.equals(n2) << '\\n';\n    \n    return 0;\n}\n"}
{"id": 57305, "name": "Selectively replace multiple instances of a character within a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n"}
{"id": 57306, "name": "Selectively replace multiple instances of a character within a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n", "C++": "#include <map>\n#include <iostream>\n#include <string>\n\nint main()\n{\n  std::map<char, std::string> rep = \n    {{'a', \"DCaBA\"}, \n     {'b', \"E\"},\n     {'r', \"Fr\"}};\n\n  std::string magic = \"abracadabra\";\n\n  for(auto it = magic.begin(); it != magic.end(); ++it)\n  {\n    if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n    {\n      *it = f->second.back();\n      f->second.pop_back();\n    }\n  }\n\n  std::cout << magic << \"\\n\";\n}\n"}
{"id": 57307, "name": "Repunit primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 57308, "name": "Repunit primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n", "C++": "#include <future>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <gmpxx.h>\n#include <primesieve.hpp>\n\nstd::vector<uint64_t> repunit_primes(uint32_t base,\n                                     const std::vector<uint64_t>& primes) {\n    std::vector<uint64_t> result;\n    for (uint64_t prime : primes) {\n        mpz_class repunit(std::string(prime, '1'), base);\n        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)\n            result.push_back(prime);\n    }\n    return result;\n}\n\nint main() {\n    std::vector<uint64_t> primes;\n    const uint64_t limit = 2700;\n    primesieve::generate_primes(limit, &primes);\n    std::vector<std::future<std::vector<uint64_t>>> futures;\n    for (uint32_t base = 2; base <= 36; ++base) {\n        futures.push_back(std::async(repunit_primes, base, primes));\n    }\n    std::cout << \"Repunit prime digits (up to \" << limit << \") in:\\n\";\n    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {\n        std::cout << \"Base \" << std::setw(2) << base << ':';\n        for (auto digits : futures[i].get())\n            std::cout << ' ' << digits;\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 57309, "name": "Curzon numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 57310, "name": "Curzon numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n    if (mod == 1)\n        return 0;\n    uint64_t result = 1;\n    base %= mod;\n    for (; exp > 0; exp >>= 1) {\n        if ((exp & 1) == 1)\n            result = (result * base) % mod;\n        base = (base * base) % mod;\n    }\n    return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n    const uint64_t r = k * n;\n    return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n    for (uint64_t k = 2; k <= 10; k += 2) {\n        std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n        uint64_t count = 0, n = 1;\n        for (; count < 50; ++n) {\n            if (is_curzon(n, k)) {\n                std::cout << std::setw(4) << n\n                          << (++count % 10 == 0 ? '\\n' : ' ');\n            }\n        }\n        for (;;) {\n            if (is_curzon(n, k))\n                ++count;\n            if (count == 1000)\n                break;\n            ++n;\n        }\n        std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n                  << \"\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 57311, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57312, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57313, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing big_float = boost::multiprecision::cpp_dec_float_100;\n\nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n\nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 57314, "name": "Respond to an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n", "C++": "class animal {\npublic:\n  virtual void bark() \n  {\n    throw \"implement me: do not know how to bark\";\n  }\n};\n\nclass elephant : public animal \n{\n};\n\nint main()\n{\n  elephant e;\n  e.bark();  \n}\n"}
{"id": 57315, "name": "Word break problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n"}
{"id": 57316, "name": "Brilliant numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 57317, "name": "Brilliant numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n", "C++": "#include <algorithm>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <vector>\n\n#include <primesieve.hpp>\n\nauto get_primes_by_digits(uint64_t limit) {\n    primesieve::iterator pi;\n    std::vector<std::vector<uint64_t>> primes_by_digits;\n    std::vector<uint64_t> primes;\n    for (uint64_t p = 10; p <= limit;) {\n        uint64_t prime = pi.next_prime();\n        if (prime > p) {\n            primes_by_digits.push_back(std::move(primes));\n            p *= 10;\n        }\n        primes.push_back(prime);\n    }\n    return primes_by_digits;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    auto primes_by_digits = get_primes_by_digits(1000000000);\n\n    std::cout << \"First 100 brilliant numbers:\\n\";\n    std::vector<uint64_t> brilliant_numbers;\n    for (const auto& primes : primes_by_digits) {\n        for (auto i = primes.begin(); i != primes.end(); ++i)\n            for (auto j = i; j != primes.end(); ++j)\n                brilliant_numbers.push_back(*i * *j);\n        if (brilliant_numbers.size() >= 100)\n            break;\n    }\n    std::sort(brilliant_numbers.begin(), brilliant_numbers.end());\n    for (size_t i = 0; i < 100; ++i) {\n        std::cout << std::setw(5) << brilliant_numbers[i]\n                  << ((i + 1) % 10 == 0 ? '\\n' : ' ');\n    }\n\n    std::cout << '\\n';\n    uint64_t power = 10;\n    size_t count = 0;\n    for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {\n        const auto& primes = primes_by_digits[p / 2];\n        size_t position = count + 1;\n        uint64_t min_product = 0;\n        for (auto i = primes.begin(); i != primes.end(); ++i) {\n            uint64_t p1 = *i;\n            auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);\n            if (j != primes.end()) {\n                uint64_t p2 = *j;\n                uint64_t product = p1 * p2;\n                if (min_product == 0 || product < min_product)\n                    min_product = product;\n                position += std::distance(i, j);\n                if (p1 >= p2)\n                    break;\n            }\n        }\n        std::cout << \"First brilliant number >= 10^\" << p << \" is \"\n                  << min_product << \" at position \" << position << '\\n';\n        power *= 10;\n        if (p % 2 == 1) {\n            size_t size = primes.size();\n            count += size * (size + 1) / 2;\n        }\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 57318, "name": "Word ladder", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n", "C++": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n\nbool one_away(const std::string& s1, const std::string& s2) {\n    if (s1.size() != s2.size())\n        return false;\n    bool result = false;\n    for (size_t i = 0, n = s1.size(); i != n; ++i) {\n        if (s1[i] != s2[i]) {\n            if (result)\n                return false;\n            result = true;\n        }\n    }\n    return result;\n}\n\n\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n                 separator_type separator) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += separator;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\n\n\n\nbool word_ladder(const word_map& words, const std::string& from,\n                 const std::string& to) {\n    auto w = words.find(from.size());\n    if (w != words.end()) {\n        auto poss = w->second;\n        std::vector<std::vector<std::string>> queue{{from}};\n        while (!queue.empty()) {\n            auto curr = queue.front();\n            queue.erase(queue.begin());\n            for (auto i = poss.begin(); i != poss.end();) {\n                if (!one_away(*i, curr.back())) {\n                    ++i;\n                    continue;\n                }\n                if (to == *i) {\n                    curr.push_back(to);\n                    std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n                    return true;\n                }\n                std::vector<std::string> temp(curr);\n                temp.push_back(*i);\n                queue.push_back(std::move(temp));\n                i = poss.erase(i);\n            }\n        }\n    }\n    std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n    return false;\n}\n\nint main() {\n    word_map words;\n    std::ifstream in(\"unixdict.txt\");\n    if (!in) {\n        std::cerr << \"Cannot open file unixdict.txt.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    while (getline(in, word))\n        words[word.size()].push_back(word);\n    word_ladder(words, \"boy\", \"man\");\n    word_ladder(words, \"girl\", \"lady\");\n    word_ladder(words, \"john\", \"jane\");\n    word_ladder(words, \"child\", \"adult\");\n    word_ladder(words, \"cat\", \"dog\");\n    word_ladder(words, \"lead\", \"gold\");\n    word_ladder(words, \"white\", \"black\");\n    word_ladder(words, \"bubble\", \"tickle\");\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57319, "name": "Equal prime and composite sums", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc ord(n int) string {\n    if n < 0 {\n        log.Fatal(\"Argument must be a non-negative integer.\")\n    }\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%sth\", rcu.Commatize(n))\n    }\n    m %= 10\n    suffix := \"th\"\n    if m == 1 {\n        suffix = \"st\"\n    } else if m == 2 {\n        suffix = \"nd\"\n    } else if m == 3 {\n        suffix = \"rd\"\n    }\n    return fmt.Sprintf(\"%s%s\", rcu.Commatize(n), suffix)\n}\n\nfunc main() {\n    limit := int(4 * 1e8)\n    c := rcu.PrimeSieve(limit-1, true)\n    var compSums []int\n    var primeSums []int\n    csum := 0\n    psum := 0\n    for i := 2; i < limit; i++ {\n        if c[i] {\n            csum += i\n            compSums = append(compSums, csum)\n        } else {\n            psum += i\n            primeSums = append(primeSums, psum)\n        }\n    }\n\n    for i := 0; i < len(primeSums); i++ {\n        ix := sort.SearchInts(compSums, primeSums[i])\n        if ix < len(compSums) && compSums[ix] == primeSums[i] {\n            cps := rcu.Commatize(primeSums[i])\n            fmt.Printf(\"%21s - %12s prime sum, %12s composite sum\\n\", cps, ord(i+1), ord(ix+1))\n        }\n    }\n}\n", "C++": "#include <primesieve.hpp>\n\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n\nclass composite_iterator {\npublic:\n    composite_iterator();\n    uint64_t next_composite();\n\nprivate:\n    uint64_t composite;\n    uint64_t prime;\n    primesieve::iterator pi;\n};\n\ncomposite_iterator::composite_iterator() {\n    composite = prime = pi.next_prime();\n    for (; composite == prime; ++composite)\n        prime = pi.next_prime();\n}\n\nuint64_t composite_iterator::next_composite() {\n    uint64_t result = composite;\n    while (++composite == prime)\n        prime = pi.next_prime();\n    return result;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    auto start = std::chrono::high_resolution_clock::now();\n    composite_iterator ci;\n    primesieve::iterator pi;\n    uint64_t prime_sum = pi.next_prime();\n    uint64_t composite_sum = ci.next_composite();\n    uint64_t prime_index = 1, composite_index = 1;\n    std::cout << \"Sum                   | Prime Index  | Composite Index\\n\";\n    std::cout << \"------------------------------------------------------\\n\";\n    for (int count = 0; count < 11;) {\n        if (prime_sum == composite_sum) {\n            std::cout << std::right << std::setw(21) << prime_sum << \" | \"\n                      << std::setw(12) << prime_index << \" | \" << std::setw(15)\n                      << composite_index << '\\n';\n            composite_sum += ci.next_composite();\n            prime_sum += pi.next_prime();\n            ++prime_index;\n            ++composite_index;\n            ++count;\n        } else if (prime_sum < composite_sum) {\n            prime_sum += pi.next_prime();\n            ++prime_index;\n        } else {\n            composite_sum += ci.next_composite();\n            ++composite_index;\n        }\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 57320, "name": "Joystick position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"github.com/simulatedsimian/joystick\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc printAt(x, y int, s string) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)\n        x++\n    }\n}\n\nfunc readJoystick(js joystick.Joystick, hidden bool) {\n    jinfo, err := js.Read()\n    check(err)\n\n    w, h := termbox.Size()\n    tbcd := termbox.ColorDefault\n    termbox.Clear(tbcd, tbcd)\n    printAt(1, h-1, \"q - quit\")\n    if hidden {\n        printAt(11, h-1, \"s - show buttons:\")\n    } else {\n        bs := \"\"\n        printAt(11, h-1, \"h - hide buttons:\")\n        for button := 0; button < js.ButtonCount(); button++ {\n            if jinfo.Buttons&(1<<uint32(button)) != 0 {\n                \n                bs += fmt.Sprintf(\" %X\", button+1)\n            }\n        }\n        printAt(28, h-1, bs)\n    }\n\n    \n    x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)\n    y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)\n    printAt(x, y, \"+\") \n    termbox.Flush()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    \n    \n    jsid := 0\n    \n    if len(os.Args) > 1 {\n        i, err := strconv.Atoi(os.Args[1])\n        check(err)\n        jsid = i\n    }\n\n    js, jserr := joystick.Open(jsid)\n    check(jserr)\n \n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    ticker := time.NewTicker(time.Millisecond * 40)\n    hidden := false \n\n    for doQuit := false; !doQuit; {\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'q' {\n                    doQuit = true\n                } else if ev.Ch == 'h' {\n                    hidden = true\n                } else if ev.Ch == 's' {\n                    hidden = false\n                }\n            }\n            if ev.Type == termbox.EventResize {\n                termbox.Flush()\n            }\n        case <-ticker.C:\n            readJoystick(js, hidden)\n        }\n    }\n}\n", "C++": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid clear() {\n\tfor(int n = 0;n < 10; n++) {\n\t\tprintf(\"\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\r\\n\\r\\n\\r\\n\");\n\t}\n}\n\n#define UP    \"00^00\\r\\n00|00\\r\\n00000\\r\\n\"\n#define DOWN  \"00000\\r\\n00|00\\r\\n00v00\\r\\n\"\n#define LEFT  \"00000\\r\\n<--00\\r\\n00000\\r\\n\"\n#define RIGHT \"00000\\r\\n00-->\\r\\n00000\\r\\n\"\n#define HOME  \"00000\\r\\n00+00\\r\\n00000\\r\\n\"\n\nint main() {\n\tclear();\n\tsystem(\"stty raw\");\n\n\tprintf(HOME);\n\tprintf(\"space to exit; wasd to move\\r\\n\");\n\tchar c = 1;\n\n\twhile(c) {\n\t\tc = getc(stdin);\n\t\tclear();\n\n\t\tswitch (c)\n\t\t{\n\t\t\tcase 'a':\n\t\t\t\tprintf(LEFT);\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tprintf(RIGHT);\n\t\t\t\tbreak;\n\t\t\tcase 'w':\n\t\t\t\tprintf(UP);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tprintf(DOWN);\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tc = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprintf(HOME);\n\t\t};\n\n\t\tprintf(\"space to exit; wasd key to move\\r\\n\");\n\t}\n\n\tsystem(\"stty cooked\");\n\tsystem(\"clear\"); \n\treturn 1;\n}\n"}
{"id": 57321, "name": "Earliest difference between prime gaps", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <locale>\n#include <unordered_map>\n\n#include <primesieve.hpp>\n\nclass prime_gaps {\npublic:\n    prime_gaps() { last_prime_ = iterator_.next_prime(); }\n    uint64_t find_gap_start(uint64_t gap);\nprivate:\n    primesieve::iterator iterator_;\n    uint64_t last_prime_;\n    std::unordered_map<uint64_t, uint64_t> gap_starts_;\n};\n\nuint64_t prime_gaps::find_gap_start(uint64_t gap) {\n    auto i = gap_starts_.find(gap);\n    if (i != gap_starts_.end())\n        return i->second;\n    for (;;) {\n        uint64_t prev = last_prime_;\n        last_prime_ = iterator_.next_prime();\n        uint64_t diff = last_prime_ - prev;\n        gap_starts_.emplace(diff, prev);\n        if (gap == diff)\n            return prev;\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const uint64_t limit = 100000000000;\n    prime_gaps pg;\n    for (uint64_t pm = 10, gap1 = 2;;) {\n        uint64_t start1 = pg.find_gap_start(gap1);\n        uint64_t gap2 = gap1 + 2;\n        uint64_t start2 = pg.find_gap_start(gap2);\n        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;\n        if (diff > pm) {\n            std::cout << \"Earliest difference > \" << pm\n                      << \" between adjacent prime gap starting primes:\\n\"\n                      << \"Gap \" << gap1 << \" starts at \" << start1 << \", gap \"\n                      << gap2 << \" starts at \" << start2 << \", difference is \"\n                      << diff << \".\\n\\n\";\n            if (pm == limit)\n                break;\n            pm *= 10;\n        } else {\n            gap1 = gap2;\n        }\n    }\n}\n"}
{"id": 57322, "name": "Latin Squares in reduced form", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 57323, "name": "Ormiston pairs", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e9\n    primes := rcu.Primes(limit)\n    var orm30 [][2]int\n    j := int(1e5)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-1; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        if (p2-p1)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 == key2 {\n            if count < 30 {\n                orm30 = append(orm30, [2]int{p1, p2})\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"First 30 Ormiston pairs:\")\n    for i := 0; i < 30; i++ {\n        fmt.Printf(\"%5v \", orm30[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e5)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston pairs before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n    }\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <utility>\n\n#include <primesieve.hpp>\n\nclass ormiston_pair_generator {\npublic:\n    ormiston_pair_generator() { prime_ = pi_.next_prime(); }\n    std::pair<uint64_t, uint64_t> next_pair() {\n        for (;;) {\n            uint64_t prime = prime_;\n            auto digits = digits_;\n            prime_ = pi_.next_prime();\n            digits_ = get_digits(prime_);\n            if (digits_ == digits)\n                return std::make_pair(prime, prime_);\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    uint64_t prime_;\n    std::array<int, 10> digits_;\n};\n\nint main() {\n    ormiston_pair_generator generator;\n    int count = 0;\n    std::cout << \"First 30 Ormiston pairs:\\n\";\n    for (; count < 30; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        std::cout << '(' << std::setw(5) << p1 << \", \" << std::setw(5) << p2\n                  << ')' << ((count + 1) % 3 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {\n        auto [p1, p2] = generator.next_pair();\n        if (p1 > limit) {\n            std::cout << \"Number of Ormiston pairs < \" << limit << \": \" << count\n                      << '\\n';\n            limit *= 10;\n        }\n    }\n}\n"}
{"id": 57324, "name": "UPC", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n"}
{"id": 57325, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 57326, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 57327, "name": "Harmonic series", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc harmonic(n int) *big.Rat {\n    sum := new(big.Rat)\n    for i := int64(1); i <= int64(n); i++ {\n        r := big.NewRat(1, i)\n        sum.Add(sum, r)\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The first 20 harmonic numbers and the 100th, expressed in rational form, are:\")\n    numbers := make([]int, 21)\n    for i := 1; i <= 20; i++ {\n        numbers[i-1] = i\n    }\n    numbers[20] = 100\n    for _, i := range numbers {\n        fmt.Printf(\"%3d : %s\\n\", i, harmonic(i))\n    }\n\n    fmt.Println(\"\\nThe first harmonic number to exceed the following integers is:\")\n    const limit = 10\n    for i, n, h := 1, 1, 0.0; i <= limit; n++ {\n        h += 1.0 / float64(n)\n        if h > float64(i) {\n            fmt.Printf(\"integer = %2d  -> n = %6d  ->  harmonic number = %9.6f (to 6dp)\\n\", i, n, h)\n            i++\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\nusing integer = boost::multiprecision::mpz_int;\nusing rational = boost::rational<integer>;\n\nclass harmonic_generator {\npublic:\n    rational next() {\n        rational result = term_;\n        term_ += rational(1, ++n_);\n        return result;\n    }\n    void reset() {\n        n_ = 1;\n        term_ = 1;\n    }\nprivate:\n    integer n_ = 1;\n    rational term_ = 1;\n};\n\nint main() {\n    std::cout << \"First 20 harmonic numbers:\\n\";\n    harmonic_generator hgen;\n    for (int i = 1; i <= 20; ++i)\n        std::cout << std::setw(2) << i << \". \" << hgen.next() << '\\n';\n    \n    rational h;\n    for (int i = 1; i <= 80; ++i)\n        h = hgen.next();\n    std::cout << \"\\n100th harmonic number: \" << h << \"\\n\\n\";\n\n    int n = 1;\n    hgen.reset();\n    for (int i = 1; n <= 10; ++i) {\n        if (hgen.next() > n)\n            std::cout << \"Position of first term > \" << std::setw(2) << n++ << \": \" << i << '\\n';\n    }\n}\n"}
{"id": 57328, "name": "External sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n"}
{"id": 57329, "name": "External sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n", "C++": "\n\n \n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <algorithm>\n#include <cstdio>\n\n\n\n\nint main(int argc, char* argv[]);\nvoid write_vals(int* const, const size_t, const size_t);\nstd::string mergeFiles(size_t); \n\n\n\n\nstruct Compare\n{\n  \n  bool operator() ( std::pair<int, int>& p1,  std::pair<int, int>& p2 )\n  {\n    return p1.first >= p2.first; \n  }\n};\n\n\n \n\n\n \nusing ipair = std::pair<int,int>;\n\nusing pairvector = std::vector<ipair>;\n\nusing MinHeap = std::priority_queue< ipair, pairvector, Compare >;\n\n\n\n\n\n\nconst size_t memsize = 32;                        \n\nconst size_t chunksize = memsize / sizeof(int);   \n\nconst std::string tmp_prefix{\"tmp_out_\"};  \n\nconst std::string tmp_suffix{\".txt\"};      \n\nconst std::string merged_file{\"merged.txt\"}; \n\n\n\n\n\n\nvoid write_vals( int* const values, const size_t size, const size_t chunk )\n{\n \n  \n  std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);\n    \n  std::ofstream ofs(output_file.c_str()); \n\n  for (int i=0; i<size; i++)  \n    ofs << values[i] << '\\t';\n  \n    ofs << '\\n';\n\n  ofs.close();\n}\n\n\n\n\n\nstd::string mergeFiles(size_t chunks, const std::string& merge_file ) \n{\n\n  std::ofstream ofs( merge_file.c_str() );\n    \n  MinHeap  minHeap;\n\n  \n  std::ifstream* ifs_tempfiles = new std::ifstream[chunks];\n \n  for (size_t i = 1; i<=chunks; i++) \n    {\n      int topval = 0;\t\n\n      \n      std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);\n       \n      \n      ifs_tempfiles[i-1].open( sorted_file.c_str() ); \n\n      \n      if (ifs_tempfiles[i-1].is_open()) \n\t{\n\t  ifs_tempfiles[i-1] >> topval; \n\n\t  ipair top(topval, (i-1)); \n\t\t\t      \n\t  minHeap.push( top );   \n\t}\n    }\n  \n\n  while (minHeap.size() > 0) \n    {\n      int next_val = 0;\n\n      ipair min_pair = minHeap.top(); \n\n      minHeap.pop();\n\n      ofs << min_pair.first << ' ';  \n  \n      std::flush(ofs);\n\n      if ( ifs_tempfiles[min_pair.second] >> next_val) \n\t{\n\n\t  ipair np( next_val, min_pair.second );\n\n\t  minHeap.push( np );\n\t}\n\n    }\n \n\n  \n  for (int i = 1; i <= chunks; i++) \n    {\n      ifs_tempfiles[i-1].close();\n    }\n\n  ofs << '\\n';\n  ofs.close();\n    \n  delete[] ifs_tempfiles; \n \n  return merged_file;  \n}\n \n\n\n\nint main(int argc, char* argv[] ) \n{\n\n  if (argc < 2)\n    {\n      std::cerr << \"usage:  ExternalSort <filename> \\n\";\n      return 1;\n    }\n\n  \n\n  std::ifstream ifs( argv[1] );  \n  \n  if ( ifs.fail() )\n    {\n      std::cerr << \"error opening \" << argv[1] << \"\\n\";\n      return 2;\n    }\n\n\n  \n  int* inputValues = new int[chunksize];\n \n  int chunk = 1;    \n\n  int val = 0;      \n\n  int count = 0;    \n\n  bool done = false; \n\n  std::cout << \"internal buffer is \" << memsize << \" bytes\" << \"\\n\"; \n\n  \n  while (ifs >> val) \n    {\n      done = false;\n\n      inputValues[count] = val;\n\t\n      count++;\n\n      if (count == chunksize) \n\t{\n\n\t  std::sort(inputValues, inputValues + count);\n\n\t  write_vals(inputValues, count, chunk); \n\n\t  chunk ++;\n\n\t  count = 0;\n\n\t  done = true;\n\t}\n\n    } \n\n\n  if (! done)  \n    {\n      std::sort(inputValues, inputValues + count);\n    \n      write_vals(inputValues, count, chunk); \n    }\n  else \n    {\n      chunk --;  \n    }\n\n \n\n  ifs.close();   \n    \n\n  delete[] inputValues; \n    \n\n  \n  if ( chunk == 0 ) \n    std::cout << \"no data found\\n\";\n  else\n    std::cout << \"Sorted output is in file: \" << mergeFiles(chunk, merged_file ) << \"\\n\";\n     \n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n"}
{"id": 57330, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n)", "Go": "package cf\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG4 struct {\n\tA1, A int64\n\tB1, B int64\n}\n\nfunc (ng NG4) needsIngest() bool {\n\tif ng.isDone() {\n\t\tpanic(\"b₁==b==0\")\n\t}\n\treturn ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B\n}\n\nfunc (ng NG4) isDone() bool {\n\treturn ng.B1 == 0 && ng.B == 0\n}\n\nfunc (ng *NG4) ingest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.A+ng.A1*t, ng.A1,\n\t\tng.B+ng.B1*t, ng.B1\n}\n\nfunc (ng *NG4) ingestInfinite() {\n\t\n\t\n\tng.A, ng.B = ng.A1, ng.B1\n}\n\nfunc (ng *NG4) egest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.B1, ng.B,\n\t\tng.A1-ng.B1*t, ng.A-ng.B*t\n}\n\n\n\nfunc (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext := cf()\n\t\tdone := false\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite()\n\t\t\t\t}\n\t\t\t}\n\t\t\tt := ng.A1 / ng.B1\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n", "C++": "\nclass matrixNG {\n  private:\n  virtual void consumeTerm(){}\n  virtual void consumeTerm(int n){}\n  virtual const bool needTerm(){}\n  protected: int cfn = 0, thisTerm;\n             bool haveTerm = false;\n  friend class NG;\n};\n\nclass NG_4 : public matrixNG {\n  private: int a1, a, b1, b, t;\n  const bool needTerm() {\n    if (b1==0 and b==0) return false;\n    if (b1==0 or b==0) return true; else thisTerm = a/b;\n    if (thisTerm==(int)(a1/b1)){\n      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;\n      haveTerm=true; return false;\n    }\n    return true;\n  }\n  void consumeTerm(){a=a1; b=b1;}\n  void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}\n  public:\n  NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}\n};\n\nclass NG : public ContinuedFraction {\n  private:\n   matrixNG* ng;\n   ContinuedFraction* n[2];\n  public:\n  NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}\n  NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}\n  const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}\n  const bool moreTerms(){\n    while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();\n    return ng->haveTerm;\n  }\n};\n"}
{"id": 57331, "name": "Calkin-Wilf sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n"}
{"id": 57332, "name": "Calkin-Wilf sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <boost/rational.hpp>\n\nusing rational = boost::rational<unsigned long>;\n\nunsigned long floor(const rational& r) {\n    return r.numerator()/r.denominator();\n}\n\nrational calkin_wilf_next(const rational& term) {\n    return 1UL/(2UL * floor(term) + 1UL - term);\n}\n\nstd::vector<unsigned long> continued_fraction(const rational& r) {\n    unsigned long a = r.numerator();\n    unsigned long b = r.denominator();\n    std::vector<unsigned long> result;\n    do {\n        result.push_back(a/b);\n        unsigned long c = a;\n        a = b;\n        b = c % b;\n    } while (a != 1);\n    if (result.size() > 0 && result.size() % 2 == 0) {\n        --result.back();\n        result.push_back(1);\n    }\n    return result;\n}\n\nunsigned long term_number(const rational& r) {\n    unsigned long result = 0;\n    unsigned long d = 1;\n    unsigned long p = 0;\n    for (unsigned long n : continued_fraction(r)) {\n        for (unsigned long i = 0; i < n; ++i, ++p)\n            result |= (d << p);\n        d = !d;\n    }\n    return result;\n}\n\nint main() {\n    rational term = 1;\n    std::cout << \"First 20 terms of the Calkin-Wilf sequence are:\\n\";\n    for (int i = 1; i <= 20; ++i) {\n        std::cout << std::setw(2) << i << \": \" << term << '\\n';\n        term = calkin_wilf_next(term);\n    }\n    rational r(83116, 51639);\n    std::cout << r << \" is the \" << term_number(r) << \"th term of the sequence.\\n\";\n}\n"}
{"id": 57333, "name": "Distribution of 0 digits in factorial series", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nfunc main() {\n    fact  := big.NewInt(1)\n    sum   := 0.0\n    first := int64(0)\n    firstRatio := 0.0    \n    fmt.Println(\"The mean proportion of zero digits in factorials up to the following are:\")\n    for n := int64(1); n <= 50000; n++  {\n        fact.Mul(fact, big.NewInt(n))\n        bytes  := []byte(fact.String())\n        digits := len(bytes)\n        zeros  := 0\n        for _, b := range bytes {\n            if b == '0' {\n                zeros++\n            }\n        }\n        sum += float64(zeros)/float64(digits)\n        ratio := sum / float64(n)\n        if n == 100 || n == 1000 || n == 10000 {\n            fmt.Printf(\"%6s = %12.10f\\n\", rcu.Commatize(int(n)), ratio)\n        } \n        if first > 0 && ratio >= 0.16 {\n            first = 0\n            firstRatio = 0.0\n        } else if first == 0 && ratio < 0.16 {\n            first = n\n            firstRatio = ratio           \n        }\n    }\n    fmt.Printf(\"%6s = %12.10f\", rcu.Commatize(int(first)), firstRatio)\n    fmt.Println(\" (stays below 0.16 after this)\")\n    fmt.Printf(\"%6s = %12.10f\\n\", \"50,000\", sum / 50000)\n}\n", "C++": "#include <array>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nauto init_zc() {\n    std::array<int, 1000> zc;\n    zc.fill(0);\n    zc[0] = 3;\n    for (int x = 1; x <= 9; ++x) {\n        zc[x] = 2;\n        zc[10 * x] = 2;\n        zc[100 * x] = 2;\n        for (int y = 10; y <= 90; y += 10) {\n            zc[y + x] = 1;\n            zc[10 * y + x] = 1;\n            zc[10 * (y + x)] = 1;\n        }\n    }\n    return zc;\n}\n\ntemplate <typename clock_type>\nauto elapsed(const std::chrono::time_point<clock_type>& t0) {\n    auto t1 = clock_type::now();\n    auto duration =\n        std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);\n    return duration.count();\n}\n\nint main() {\n    auto zc = init_zc();\n    auto t0 = std::chrono::high_resolution_clock::now();\n    int trail = 1, first = 0;\n    double total = 0;\n    std::vector<int> rfs{1};\n    std::cout << std::fixed << std::setprecision(10);\n    for (int f = 2; f <= 50000; ++f) {\n        int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();\n        for (int j = trail - 1; j < len || carry != 0; ++j) {\n            if (j < len)\n                carry += rfs[j] * f;\n            d999 = carry % 1000;\n            if (j < len)\n                rfs[j] = d999;\n            else\n                rfs.push_back(d999);\n            zeroes += zc[d999];\n            carry /= 1000;\n        }\n        while (rfs[trail - 1] == 0)\n            ++trail;\n        d999 = rfs.back();\n        d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;\n        zeroes -= d999;\n        int digits = rfs.size() * 3 - d999;\n        total += double(zeroes) / digits;\n        double ratio = total / f;\n        if (ratio >= 0.16)\n            first = 0;\n        else if (first == 0)\n            first = f;\n        if (f == 100 || f == 1000 || f == 10000) {\n            std::cout << \"Mean proportion of zero digits in factorials to \" << f\n                      << \" is \" << ratio << \". (\" << elapsed(t0) << \"ms)\\n\";\n        }\n    }\n    std::cout << \"The mean proportion dips permanently below 0.16 at \" << first\n              << \". (\" << elapsed(t0) << \"ms)\\n\";\n}\n"}
{"id": 57334, "name": "Closest-pair problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n"}
{"id": 57335, "name": "Address of a variable", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n", "C++": "int i;\nvoid* address_of_i = &i;\n"}
{"id": 57336, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 57337, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "C++": "#include <map>\n"}
{"id": 57338, "name": "Wilson primes of order n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n)\n\nfunc main() {\n    const LIMIT = 11000\n    primes := rcu.Primes(LIMIT)\n    facts := make([]*big.Int, LIMIT)\n    facts[0] = big.NewInt(1)\n    for i := int64(1); i < LIMIT; i++ {\n        facts[i] = new(big.Int)\n        facts[i].Mul(facts[i-1], big.NewInt(i))\n    }\n    sign := int64(1)\n    f := new(big.Int)\n    zero := new(big.Int)\n    fmt.Println(\" n:  Wilson primes\")\n    fmt.Println(\"--------------------\")\n    for n := 1; n < 12; n++ {\n        fmt.Printf(\"%2d:  \", n)\n        sign = -sign\n        for _, p := range primes {\n            if p < n {\n                continue\n            }\n            f.Mul(facts[n-1], facts[p-n])\n            f.Sub(f, big.NewInt(sign))\n            p2 := int64(p * p)\n            bp2 := big.NewInt(p2)\n            if f.Rem(f, bp2).Cmp(zero) == 0 {\n                fmt.Printf(\"%d \", p)\n            }\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\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\nint main() {\n    using big_int = mpz_class;\n    const int limit = 11000;\n    std::vector<big_int> f{1};\n    f.reserve(limit);\n    big_int factorial = 1;\n    for (int i = 1; i < limit; ++i) {\n        factorial *= i;\n        f.push_back(factorial);\n    }\n    std::vector<int> primes = generate_primes(limit);\n    std::cout << \" n | Wilson primes\\n--------------------\\n\";\n    for (int n = 1, s = -1; n <= 11; ++n, s = -s) {\n        std::cout << std::setw(2) << n << \" |\";\n        for (int p : primes) {\n            if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)\n                std::cout << ' ' << p;\n        }\n        std::cout << '\\n';\n    }\n}\n"}
{"id": 57339, "name": "Multi-base primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nvar maxDepth = 6\nvar maxBase = 36\nvar c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)\nvar digits = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nvar maxStrings [][][]int\nvar mostBases = -1\n\nfunc maxSlice(a []int) int {\n    max := 0\n    for _, e := range a {\n        if e > max {\n            max = e\n        }\n    }\n    return max\n}\n\nfunc maxInt(a, b int) int {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nfunc process(indices []int) {\n    minBase := maxInt(2, maxSlice(indices)+1)\n    if maxBase - minBase + 1 < mostBases {\n        return  \n    }\n    var bases []int\n    for b := minBase; b <= maxBase; b++ {\n        n := 0\n        for _, i := range indices {\n            n = n*b + i\n        }\n        if !c[n] {\n            bases = append(bases, b)\n        }\n    }\n    count := len(bases)\n    if count > mostBases {\n        mostBases = count\n        indices2 := make([]int, len(indices))\n        copy(indices2, indices)\n        maxStrings = [][][]int{[][]int{indices2, bases}}\n    } else if count == mostBases {\n        indices2 := make([]int, len(indices))\n        copy(indices2, indices)\n        maxStrings = append(maxStrings, [][]int{indices2, bases})\n    }\n}\n\nfunc printResults() {\n    fmt.Printf(\"%d\\n\", len(maxStrings[0][1]))\n    for _, m := range maxStrings {\n        s := \"\"\n        for _, i := range m[0] {\n            s = s + string(digits[i])\n        }\n        fmt.Printf(\"%s -> %v\\n\", s, m[1])\n    }\n}\n\nfunc nestedFor(indices []int, length, level int) {\n    if level == len(indices) {\n        process(indices)\n    } else {\n        indices[level] = 0\n        if level == 0 {\n            indices[level] = 1\n        }\n        for indices[level] < length {\n            nestedFor(indices, length, level+1)\n            indices[level]++\n        }\n    }\n}\n\nfunc main() {\n    for depth := 1; depth <= maxDepth; depth++ {\n        fmt.Print(depth, \" character strings which are prime in most bases: \")\n        maxStrings = maxStrings[:0]\n        mostBases = -1\n        indices := make([]int, depth)\n        nestedFor(indices, maxBase, 0)\n        printResults()\n        fmt.Println()\n    }\n}\n", "C++": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <primesieve.hpp>\n\nclass prime_sieve {\npublic:\n    explicit prime_sieve(uint64_t limit);\n    bool is_prime(uint64_t n) const {\n        return n == 2 || ((n & 1) == 1 && sieve[n >> 1]);\n    }\n\nprivate:\n    std::vector<bool> sieve;\n};\n\nprime_sieve::prime_sieve(uint64_t limit) : sieve((limit + 1) / 2, false) {\n    primesieve::iterator iter;\n    uint64_t prime = iter.next_prime(); \n    while ((prime = iter.next_prime()) <= limit) {\n        sieve[prime >> 1] = true;\n    }\n}\n\ntemplate <typename T> void print(std::ostream& out, const std::vector<T>& v) {\n    if (!v.empty()) {\n        out << '[';\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << \", \" << *i;\n        out << ']';\n    }\n}\n\nstd::string to_string(const std::vector<unsigned int>& v) {\n    static constexpr char digits[] =\n        \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (auto i : v)\n        str += digits[i];\n    return str;\n}\n\nbool increment(std::vector<unsigned int>& digits, unsigned int max_base) {\n    for (auto i = digits.rbegin(); i != digits.rend(); ++i) {\n        if (*i + 1 != max_base) {\n            ++*i;\n            return true;\n        }\n        *i = 0;\n    }\n    return false;\n}\n\nvoid multi_base_primes(unsigned int max_base, unsigned int max_length) {\n    prime_sieve sieve(static_cast<uint64_t>(std::pow(max_base, max_length)));\n    for (unsigned int length = 1; length <= max_length; ++length) {\n        std::cout << length\n                  << \"-character strings which are prime in most bases: \";\n        unsigned int most_bases = 0;\n        std::vector<\n            std::pair<std::vector<unsigned int>, std::vector<unsigned int>>>\n            max_strings;\n        std::vector<unsigned int> digits(length, 0);\n        digits[0] = 1;\n        std::vector<unsigned int> bases;\n        do {\n            auto max = std::max_element(digits.begin(), digits.end());\n            unsigned int min_base = 2;\n            if (max != digits.end())\n                min_base = std::max(min_base, *max + 1);\n            if (most_bases > max_base - min_base + 1)\n                continue;\n            bases.clear();\n            for (unsigned int b = min_base; b <= max_base; ++b) {\n                if (max_base - b + 1 + bases.size() < most_bases)\n                    break;\n                uint64_t n = 0;\n                for (auto d : digits)\n                    n = n * b + d;\n                if (sieve.is_prime(n))\n                    bases.push_back(b);\n            }\n            if (bases.size() > most_bases) {\n                most_bases = bases.size();\n                max_strings.clear();\n            }\n            if (bases.size() == most_bases)\n                max_strings.emplace_back(digits, bases);\n        } while (increment(digits, max_base));\n        std::cout << most_bases << '\\n';\n        for (const auto& m : max_strings) {\n            std::cout << to_string(m.first) << \" -> \";\n            print(std::cout, m.second);\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n}\n\nint main(int argc, char** argv) {\n    unsigned int max_base = 36;\n    unsigned int max_length = 4;\n    for (int arg = 1; arg + 1 < argc; ++arg) {\n        if (strcmp(argv[arg], \"-max_base\") == 0)\n            max_base = strtoul(argv[++arg], nullptr, 10);\n        else if (strcmp(argv[arg], \"-max_length\") == 0)\n            max_length = strtoul(argv[++arg], nullptr, 10);\n    }\n    if (max_base > 62) {\n        std::cerr << \"Max base cannot be greater than 62.\\n\";\n        return EXIT_FAILURE;\n    }\n    if (max_base < 2) {\n        std::cerr << \"Max base cannot be less than 2.\\n\";\n        return EXIT_FAILURE;\n    }\n    multi_base_primes(max_base, max_length);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57340, "name": "Color wheel", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 57341, "name": "Plasma effect", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n", "C++": "#include <windows.h>\n#include <math.h>\n#include <string>\n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n        ZeroMemory( dwpBits, 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 )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    DWORD* bits()          { return ( DWORD* )pBits; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int width, height, wid;\n    DWORD    clr;\n};\nclass plasma\n{\npublic:\n    plasma() {\n        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n        int i, j, dst = 0;\n        double temp;\n        for( j = 0; j < BMP_SIZE * 2; j++ ) {\n            for( i = 0; i < BMP_SIZE * 2; i++ ) {\n                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n                dst++;\n            }\n        }\n    }\n    void update() {\n        DWORD dst;\n        BYTE a, c1,c2, c3;\n        currentTime += ( double )( rand() % 2 + 1 );\n\n        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),\n            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),\n            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),\n            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),\n            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n        \n        DWORD* bits = _bmp.bits();\n        for( int j = 0; j < BMP_SIZE; j++ ) {\n            dst = j * BMP_SIZE;\n            for( int i= 0; i < BMP_SIZE; i++ ) {\n                a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n                c1 = a << 1; c2 = a << 2; c3 = a << 3;\n                bits[dst + i] = RGB( c1, c2, c3 );\n                src1++; src2++; src3++;\n            }\n            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n        }\n        draw();\n    }\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n    void draw() {\n        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n        ReleaseDC( _hwnd, wdc );\n    }\n    myBitmap _bmp; HWND _hwnd; float _ang;\n    BYTE *plasma1, *plasma2;\n    double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst ) {\n        _hInst = hInst; _hwnd = InitAll();\n        SetTimer( _hwnd, MY_TIMER, 15, NULL );\n        _plasma.setHWND( _hwnd );\n        ShowWindow( _hwnd, SW_SHOW );\n        UpdateWindow( _hwnd );\n        MSG msg;\n        ZeroMemory( &msg, sizeof( msg ) );\n        while( msg.message != WM_QUIT ) {\n            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n                TranslateMessage( &msg );\n                DispatchMessage( &msg );\n            }\n        }\n        return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n    }\nprivate:\n    void wnd::doPaint( HDC dc ) { _plasma.update(); }\n    void wnd::doTimer()         { _plasma.update(); }\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n        switch( msg ) {\n            case WM_PAINT: {\n                    PAINTSTRUCT ps;\n                    _inst->doPaint( BeginPaint( hWnd, &ps ) );\n                    EndPaint( hWnd, &ps );\n                    return 0;\n                }\n            case WM_DESTROY: PostQuitMessage( 0 ); break;\n            case WM_TIMER: _inst->doTimer(); break;\n            default: return DefWindowProc( hWnd, msg, wParam, lParam );\n        }\n        return 0;\n    }\n    HWND InitAll() {\n        WNDCLASSEX wcex;\n        ZeroMemory( &wcex, sizeof( wcex ) );\n        wcex.cbSize        = sizeof( WNDCLASSEX );\n        wcex.style         = CS_HREDRAW | CS_VREDRAW;\n        wcex.lpfnWndProc   = ( WNDPROC )WndProc;\n        wcex.hInstance     = _hInst;\n        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n        wcex.lpszClassName = \"_MY_PLASMA_\";\n\n        RegisterClassEx( &wcex );\n\n        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n        int w = rc.right - rc.left, h = rc.bottom - rc.top;\n        return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n    wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n"}
{"id": 57342, "name": "Abelian sandpile model_Identity", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n"}
{"id": 57343, "name": "Abelian sandpile model_Identity", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <initializer_list>\n#include <iostream>\n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n    friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n    abelian_sandpile();\n    explicit abelian_sandpile(std::initializer_list<int> init);\n    void stabilize();\n    bool is_stable() const;\n    void topple();\n    abelian_sandpile& operator+=(const abelian_sandpile&);\n    bool operator==(const abelian_sandpile&);\n\nprivate:\n    int& cell_value(size_t row, size_t column) {\n        return cells_[cell_index(row, column)];\n    }\n    static size_t cell_index(size_t row, size_t column) {\n        return row * sp_columns + column;\n    }\n    static size_t row_index(size_t cell_index) {\n        return cell_index/sp_columns;\n    }\n    static size_t column_index(size_t cell_index) {\n        return cell_index % sp_columns;\n    }\n\n    std::array<int, sp_cells> cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n    cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {\n    assert(init.size() == sp_cells);\n    std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n    for (size_t i = 0; i < sp_cells; ++i)\n        cells_[i] += other.cells_[i];\n    stabilize();\n    return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n    return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n    return std::none_of(cells_.begin(), cells_.end(),\n                        [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (cells_[i] >= sp_limit) {\n            cells_[i] -= sp_limit;\n            size_t row = row_index(i);\n            size_t column = column_index(i);\n            if (row > 0)\n                ++cell_value(row - 1, column);\n            if (row + 1 < sp_rows)\n                ++cell_value(row + 1, column);\n            if (column > 0)\n                ++cell_value(row, column - 1);\n            if (column + 1 < sp_columns)\n                ++cell_value(row, column + 1);\n            break;\n        }\n    }\n}\n\nvoid abelian_sandpile::stabilize() {\n    while (!is_stable())\n        topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n    abelian_sandpile c(a);\n    c += b;\n    return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n    for (size_t i = 0; i < sp_cells; ++i) {\n        if (i > 0)\n            out << (as.column_index(i) == 0 ? '\\n' : ' ');\n        out << as.cells_[i];\n    }\n    return out << '\\n';\n}\n\nint main() {\n    std::cout << std::boolalpha;\n\n    std::cout << \"Avalanche:\\n\";\n    abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n    while (!sp.is_stable()) {\n        std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n        sp.topple();\n    }\n    std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n    std::cout << \"Commutativity:\\n\";\n    abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n    abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n    abelian_sandpile sum1(s1 + s2);\n    abelian_sandpile sum2(s2 + s1);\n    std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n    std::cout << \"s1 + s2 = \\n\" << sum1;\n    std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n    std::cout << '\\n';\n\n    std::cout << \"Identity:\\n\";\n    abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n    abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n    abelian_sandpile sum3(s3 + s3_id);\n    abelian_sandpile sum4(s3_id + s3_id);\n    std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n    std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n    std::cout << \"s3 + s3_id = \\n\" << sum3;\n    std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n    return 0;\n}\n"}
{"id": 57344, "name": "Rhonda numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc contains(a []int, n int) bool {\n    for _, e := range a {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    for b := 2; b <= 36; b++ {\n        if rcu.IsPrime(b) {\n            continue\n        }\n        count := 0\n        var rhonda []int\n        for n := 1; count < 15; n++ {\n            digits := rcu.Digits(n, b)\n            if !contains(digits, 0) {\n                var anyEven = false\n                for _, d := range digits {\n                    if d%2 == 0 {\n                        anyEven = true\n                        break\n                    }\n                }\n                if b != 10 || (contains(digits, 5) && anyEven) {\n                    calc1 := 1\n                    for _, d := range digits {\n                        calc1 *= d\n                    }\n                    calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))\n                    if calc1 == calc2 {\n                        rhonda = append(rhonda, n)\n                        count++\n                    }\n                }\n            }\n        }\n        if len(rhonda) > 0 {\n            fmt.Printf(\"\\nFirst 15 Rhonda numbers in base %d:\\n\", b)\n            rhonda2 := make([]string, len(rhonda))\n            counts2 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda2[i] = fmt.Sprintf(\"%d\", r)\n                counts2[i] = len(rhonda2[i])\n            }\n            rhonda3 := make([]string, len(rhonda))\n            counts3 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda3[i] = strconv.FormatInt(int64(r), b)\n                counts3[i] = len(rhonda3[i])\n            }\n            maxLen2 := rcu.MaxInts(counts2)\n            maxLen3 := rcu.MaxInts(counts3)\n            maxLen := maxLen2\n            if maxLen3 > maxLen {\n                maxLen = maxLen3\n            }\n            maxLen++\n            fmt.Printf(\"In base 10: %*s\\n\", maxLen, rhonda2)\n            fmt.Printf(\"In base %-2d: %*s\\n\", b, maxLen, rhonda3)\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n\nint digit_product(int base, int n) {\n    int product = 1;\n    for (; n != 0; n /= base)\n        product *= n % base;\n    return product;\n}\n\nint prime_factor_sum(int n) {\n    int sum = 0;\n    for (; (n & 1) == 0; n >>= 1)\n        sum += 2;\n    for (int p = 3; p * p <= n; p += 2)\n        for (; n % p == 0; n /= p)\n            sum += p;\n    if (n > 1)\n        sum += n;\n    return sum;\n}\n\nbool is_prime(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 (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\nbool is_rhonda(int base, int n) {\n    return digit_product(base, n) == base * prime_factor_sum(n);\n}\n\nstd::string to_string(int base, int n) {\n    assert(base <= 36);\n    static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    std::string str;\n    for (; n != 0; n /= base)\n        str += digits[n % base];\n    std::reverse(str.begin(), str.end());\n    return str;\n}\n\nint main() {\n    const int limit = 15;\n    for (int base = 2; base <= 36; ++base) {\n        if (is_prime(base))\n            continue;\n        std::cout << \"First \" << limit << \" Rhonda numbers to base \" << base\n                  << \":\\n\";\n        int numbers[limit];\n        for (int n = 1, count = 0; count < limit; ++n) {\n            if (is_rhonda(base, n))\n                numbers[count++] = n;\n        }\n        std::cout << \"In base 10:\";\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << numbers[i];\n        std::cout << \"\\nIn base \" << base << ':';\n        for (int i = 0; i < limit; ++i)\n            std::cout << ' ' << to_string(base, numbers[i]);\n        std::cout << \"\\n\\n\";\n    }\n}\n"}
{"id": 57345, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "C++": "#include <cstdio>\n#include <cstdlib>\n\nclass Point {\nprotected:\n    int x, y;\n\npublic:\n    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}\n    Point(const Point &p) : x(p.x), y(p.y) {}\n    virtual ~Point() {}\n    const Point& operator=(const Point &p) {\n        if (this != &p) {\n            x = p.x;\n            y = p.y;\n        }\n        return *this;\n    }\n    int getX() { return x; }\n    int getY() { return y; }\n    void setX(int x0) { x = x0; }\n    void setY(int y0) { y = y0; }\n    virtual void print() { printf(\"Point\\n\"); }\n};\n\nclass Circle: public Point {\nprivate:\n    int r;\n\npublic:\n    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}\n    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}\n    virtual ~Circle() {}\n    const Circle& operator=(const Circle &c) {\n        if (this != &c) {\n            x = c.x;\n            y = c.y;\n            r = c.r;\n        }\n        return *this;\n    }\n    int getR() { return r; }\n    void setR(int r0) { r = r0; }\n    virtual void print() { printf(\"Circle\\n\"); }\n};\n\nint main() {\n    Point *p = new Point();\n    Point *c = new Circle();\n    p->print();\n    c->print();\n    delete p;\n    delete c;\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57346, "name": "Create an object_Native demonstration", "Go": "package romap\n\ntype Romap struct{ imap map[byte]int }\n\n\nfunc New(m map[byte]int) *Romap {\n    if m == nil {\n        return nil\n    }\n    return &Romap{m}\n}\n\n\nfunc (rom *Romap) Get(key byte) (int, bool) {\n    i, ok := rom.imap[key]\n    return i, ok\n}\n\n\nfunc (rom *Romap) Reset(key byte) {\n    _, ok := rom.imap[key]\n    if ok {\n        rom.imap[key] = 0 \n    }\n}\n", "C++": "#include <iostream>\n#include <map>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nclass FixedMap : private T\n{\n    \n    \n    \n    \n    \n    T m_defaultValues;\n    \npublic:\n    FixedMap(T map)\n    : T(map), m_defaultValues(move(map)){}\n    \n    \n    using T::cbegin;\n    using T::cend;\n    using T::empty;\n    using T::find;\n    using T::size;\n\n    \n    using T::at;\n    using T::begin;\n    using T::end;\n    \n    \n    \n    auto& operator[](typename T::key_type&& key)\n    {\n        \n        return this->at(forward<typename T::key_type>(key));\n    }\n    \n    \n    \n    void erase(typename T::key_type&& key)\n    {\n        T::operator[](key) = m_defaultValues.at(key);\n    }\n\n    \n    void clear()\n    {\n        \n        T::operator=(m_defaultValues);\n    }\n    \n};\n\n\nauto PrintMap = [](const auto &map)\n{\n    for(auto &[key, value] : map)\n    {\n        cout << \"{\" << key << \" : \" << value << \"} \";\n    }\n    cout << \"\\n\\n\";\n};\n\nint main(void) \n{\n    \n    cout << \"Map intialized with values\\n\";\n    FixedMap<map<string, int>> fixedMap ({\n        {\"a\", 1},\n        {\"b\", 2}});\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values of the keys\\n\";\n    fixedMap[\"a\"] = 55;\n    fixedMap[\"b\"] = 56;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset the 'a' key\\n\";\n    fixedMap.erase(\"a\");\n    PrintMap(fixedMap);\n    \n    cout << \"Change the values the again\\n\";\n    fixedMap[\"a\"] = 88;\n    fixedMap[\"b\"] = 99;\n    PrintMap(fixedMap);\n    \n    cout << \"Reset all keys\\n\";\n    fixedMap.clear();\n    PrintMap(fixedMap);\n  \n    try\n    {\n        \n        cout << \"Try to add a new key\\n\";\n        fixedMap[\"newKey\"] = 99;\n    }\n    catch (exception &ex)\n    {\n        cout << \"error: \" << ex.what();\n    }\n}\n"}
{"id": 57347, "name": "Find words which contain the most consonants", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57348, "name": "Prime words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57349, "name": "Prime words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57350, "name": "Prime words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57351, "name": "Prime words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include \"prime_sieve.hpp\"\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    prime_sieve sieve(UCHAR_MAX);\n    auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };\n    int n = 0;\n    while (getline(in, line)) {\n        if (std::all_of(line.begin(), line.end(), is_prime)) {\n            ++n;\n            std::cout << std::right << std::setw(2) << n << \": \"\n                << std::left << std::setw(10) << line;\n            if (n % 4 == 0)\n                std::cout << '\\n';\n        }\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 57352, "name": "Numbers which are the cube roots of the product of their proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc divisorCount(n int) int {\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    count := 0\n    sqrt := int(math.Sqrt(float64(n)))\n    for i := 1; i <= sqrt; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    var numbers50 []int\n    count := 0\n    for n := 1; count < 50000; n++ {\n        dc := divisorCount(n)\n        if n == 1 || dc == 8 {\n            count++\n            if count <= 50 {\n                numbers50 = append(numbers50, n)\n                if count == 50 {\n                    rcu.PrintTable(numbers50, 10, 3, false)\n                }\n            } else if count == 500 {\n                fmt.Printf(\"\\n500th   : %s\", rcu.Commatize(n))\n            } else if count == 5000 {\n                fmt.Printf(\"\\n5,000th : %s\", rcu.Commatize(n))\n            } else if count == 50000 {\n                fmt.Printf(\"\\n50,000th: %s\\n\", rcu.Commatize(n))\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\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    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    std::cout << \"First 50 numbers which are the cube roots of the products of \"\n                 \"their proper divisors:\\n\";\n    for (unsigned int n = 1, count = 0; count < 50000; ++n) {\n        if (n == 1 || divisor_count(n) == 8) {\n            ++count;\n            if (count <= 50)\n                std::cout << std::setw(3) << n\n                          << (count % 10 == 0 ? '\\n' : ' ');\n            else if (count == 500 || count == 5000 || count == 50000)\n                std::cout << std::setw(6) << count << \"th: \" << n << '\\n';\n        }\n    }\n}\n"}
{"id": 57353, "name": "Ormiston triples", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e10\n    primes := rcu.Primes(limit)\n    var orm25 []int\n    j := int(1e9)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-2; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        p3 := primes[i+2]\n        if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 != key2 {\n            continue\n        }\n        key3 := 1\n        for _, dig := range rcu.Digits(p3, 10) {\n            key3 *= primes[dig]\n        }\n        if key2 == key3 {\n            if count < 25 {\n                orm25 = append(orm25, p1)\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"Smallest members of first 25 Ormiston triples:\")\n    for i := 0; i < 25; i++ {\n        fmt.Printf(\"%8v \", orm25[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e9)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston triples before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n        fmt.Println()\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\n#include <primesieve.hpp>\n\nclass ormiston_triple_generator {\npublic:\n    ormiston_triple_generator() {\n        for (int i = 0; i < 2; ++i) {\n            primes_[i] = pi_.next_prime();\n            digits_[i] = get_digits(primes_[i]);\n        }\n    }\n    std::array<uint64_t, 3> next_triple() {\n        for (;;) {\n            uint64_t prime = pi_.next_prime();\n            auto digits = get_digits(prime);\n            bool is_triple = digits == digits_[0] && digits == digits_[1];\n            uint64_t prime0 = primes_[0];\n            primes_[0] = primes_[1];\n            primes_[1] = prime;\n            digits_[0] = digits_[1];\n            digits_[1] = digits;\n            if (is_triple)\n                return {prime0, primes_[0], primes_[1]};\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    std::array<uint64_t, 2> primes_;\n    std::array<std::array<int, 10>, 2> digits_;\n};\n\nint main() {\n    ormiston_triple_generator generator;\n    int count = 0;\n    std::cout << \"Smallest members of first 25 Ormiston triples:\\n\";\n    for (; count < 25; ++count) {\n        auto primes = generator.next_triple();\n        std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {\n        auto primes = generator.next_triple();\n        if (primes[2] > limit) {\n            std::cout << \"Number of Ormiston triples < \" << limit << \": \"\n                      << count << '\\n';\n            limit *= 10;\n        }\n    }\n}\n"}
{"id": 57354, "name": "Ormiston triples", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e10\n    primes := rcu.Primes(limit)\n    var orm25 []int\n    j := int(1e9)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-2; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        p3 := primes[i+2]\n        if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 != key2 {\n            continue\n        }\n        key3 := 1\n        for _, dig := range rcu.Digits(p3, 10) {\n            key3 *= primes[dig]\n        }\n        if key2 == key3 {\n            if count < 25 {\n                orm25 = append(orm25, p1)\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"Smallest members of first 25 Ormiston triples:\")\n    for i := 0; i < 25; i++ {\n        fmt.Printf(\"%8v \", orm25[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e9)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston triples before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n        fmt.Println()\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n\n#include <primesieve.hpp>\n\nclass ormiston_triple_generator {\npublic:\n    ormiston_triple_generator() {\n        for (int i = 0; i < 2; ++i) {\n            primes_[i] = pi_.next_prime();\n            digits_[i] = get_digits(primes_[i]);\n        }\n    }\n    std::array<uint64_t, 3> next_triple() {\n        for (;;) {\n            uint64_t prime = pi_.next_prime();\n            auto digits = get_digits(prime);\n            bool is_triple = digits == digits_[0] && digits == digits_[1];\n            uint64_t prime0 = primes_[0];\n            primes_[0] = primes_[1];\n            primes_[1] = prime;\n            digits_[0] = digits_[1];\n            digits_[1] = digits;\n            if (is_triple)\n                return {prime0, primes_[0], primes_[1]};\n        }\n    }\n\nprivate:\n    static std::array<int, 10> get_digits(uint64_t n) {\n        std::array<int, 10> result = {};\n        for (; n > 0; n /= 10)\n            ++result[n % 10];\n        return result;\n    }\n    primesieve::iterator pi_;\n    std::array<uint64_t, 2> primes_;\n    std::array<std::array<int, 10>, 2> digits_;\n};\n\nint main() {\n    ormiston_triple_generator generator;\n    int count = 0;\n    std::cout << \"Smallest members of first 25 Ormiston triples:\\n\";\n    for (; count < 25; ++count) {\n        auto primes = generator.next_triple();\n        std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    std::cout << '\\n';\n    for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {\n        auto primes = generator.next_triple();\n        if (primes[2] > limit) {\n            std::cout << \"Number of Ormiston triples < \" << limit << \": \"\n                      << count << '\\n';\n            limit *= 10;\n        }\n    }\n}\n"}
{"id": 57355, "name": "Elementary cellular automaton_Infinite length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc evolve(l, rule int) {\n    fmt.Printf(\" Rule #%d:\\n\", rule)\n    cells := \"O\"\n    for x := 0; x < l; x++ {\n        cells = addNoCells(cells)\n        width := 40 + (len(cells) >> 1)\n        fmt.Printf(\"%*s\\n\", width, cells)\n        cells = step(cells, rule)\n    }\n}\n\nfunc step(cells string, rule int) string {\n    newCells := new(strings.Builder)\n    for i := 0; i < len(cells)-2; i++ {\n        bin := 0\n        b := uint(2)\n        for n := i; n < i+3; n++ {\n            bin += btoi(cells[n] == 'O') << b\n            b >>= 1\n        }\n        a := '.'\n        if rule&(1<<uint(bin)) != 0 {\n            a = 'O'\n        }\n        newCells.WriteRune(a)\n    }\n    return newCells.String()\n}\n\nfunc addNoCells(cells string) string {\n    l, r := \"O\", \"O\"\n    if cells[0] == 'O' {\n        l = \".\"\n    }\n    if cells[len(cells)-1] == 'O' {\n        r = \".\"\n    }\n    cells = l + cells + r\n    cells = l + cells + r\n    return cells\n}\n\nfunc main() {\n    for _, r := range []int{90, 30} {\n        evolve(25, r)\n        fmt.Println()\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <string>\n\nclass oo {\npublic:\n    void evolve( int l, int rule ) {\n        std::string    cells = \"O\";\n        std::cout << \" Rule #\" << rule << \":\\n\";\n        for( int x = 0; x < l; x++ ) {\n            addNoCells( cells );\n            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n            step( cells, rule );\n        }\n    }\nprivate:\n    void step( std::string& cells, int rule ) {\n        int bin;\n        std::string newCells;\n        for( size_t i = 0; i < cells.length() - 2; i++ ) {\n            bin = 0;\n            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n            }\n            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n        }\n        cells = newCells;\n    }\n    void addNoCells( std::string& s ) {\n        char l = s.at( 0 ) == 'O' ? '.' : 'O',\n             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n        s = l + s + r;\n        s = l + s + r;\n    }\n};\nint main( int argc, char* argv[] ) {\n    oo o;\n    o.evolve( 35, 90 );\n    std::cout << \"\\n\";\n    return 0;\n}\n"}
{"id": 57356, "name": "Elementary cellular automaton_Infinite length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc evolve(l, rule int) {\n    fmt.Printf(\" Rule #%d:\\n\", rule)\n    cells := \"O\"\n    for x := 0; x < l; x++ {\n        cells = addNoCells(cells)\n        width := 40 + (len(cells) >> 1)\n        fmt.Printf(\"%*s\\n\", width, cells)\n        cells = step(cells, rule)\n    }\n}\n\nfunc step(cells string, rule int) string {\n    newCells := new(strings.Builder)\n    for i := 0; i < len(cells)-2; i++ {\n        bin := 0\n        b := uint(2)\n        for n := i; n < i+3; n++ {\n            bin += btoi(cells[n] == 'O') << b\n            b >>= 1\n        }\n        a := '.'\n        if rule&(1<<uint(bin)) != 0 {\n            a = 'O'\n        }\n        newCells.WriteRune(a)\n    }\n    return newCells.String()\n}\n\nfunc addNoCells(cells string) string {\n    l, r := \"O\", \"O\"\n    if cells[0] == 'O' {\n        l = \".\"\n    }\n    if cells[len(cells)-1] == 'O' {\n        r = \".\"\n    }\n    cells = l + cells + r\n    cells = l + cells + r\n    return cells\n}\n\nfunc main() {\n    for _, r := range []int{90, 30} {\n        evolve(25, r)\n        fmt.Println()\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <string>\n\nclass oo {\npublic:\n    void evolve( int l, int rule ) {\n        std::string    cells = \"O\";\n        std::cout << \" Rule #\" << rule << \":\\n\";\n        for( int x = 0; x < l; x++ ) {\n            addNoCells( cells );\n            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n            step( cells, rule );\n        }\n    }\nprivate:\n    void step( std::string& cells, int rule ) {\n        int bin;\n        std::string newCells;\n        for( size_t i = 0; i < cells.length() - 2; i++ ) {\n            bin = 0;\n            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n            }\n            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n        }\n        cells = newCells;\n    }\n    void addNoCells( std::string& s ) {\n        char l = s.at( 0 ) == 'O' ? '.' : 'O',\n             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n        s = l + s + r;\n        s = l + s + r;\n    }\n};\nint main( int argc, char* argv[] ) {\n    oo o;\n    o.evolve( 35, 90 );\n    std::cout << \"\\n\";\n    return 0;\n}\n"}
{"id": 57357, "name": "Execute CopyPasta Language", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n\n#include <stdlib.h>\n\nusing namespace std;\n\n\nvoid fatal_error(string errtext, char *argv[])\n{\n\tcout << \"%\" << errtext << endl;\n\tcout << \"usage: \" << argv[0] << \" [filename.cp]\" << endl;\n\texit(1);\n}\n\n\n\nstring& ltrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(0, str.find_first_not_of(chars));\n\treturn str;\n}\nstring& rtrim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\tstr.erase(str.find_last_not_of(chars) + 1);\n\treturn str;\n}\nstring& trim(string& str, const string& chars = \"\\t\\n\\v\\f\\r \")\n{\n\treturn ltrim(rtrim(str, chars), chars);\n}\n\nint main(int argc, char *argv[])\n{\n\t\n\tstring fname = \"\";\n\tstring source = \"\";\n\ttry\n\t{\n\t\tfname = argv[1];\n\t\tifstream t(fname);\n\n\t\tt.seekg(0, ios::end);\n\t\tsource.reserve(t.tellg());\n\t\tt.seekg(0, ios::beg);\n\n\t\tsource.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t}\n\tcatch(const exception& e)\n\t{\n\t\tfatal_error(\"error while trying to read from specified file\", argv);\n\t}\n\n\t\n\tstring clipboard = \"\";\n\n\t\n\tint loc = 0;\n\tstring remaining = source;\n\tstring line = \"\";\n\tstring command = \"\";\n\tstringstream ss;\n\twhile(remaining.find(\"\\n\") != string::npos)\n\t{\n\t\t\n\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\tcommand = trim(line);\n\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\n\t\ttry\n\t\t{\n\t\t\tif(line == \"Copy\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tclipboard += line;\n\t\t\t}\n\t\t\telse if(line == \"CopyFile\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tif(line == \"TheF*ckingCode\")\n\t\t\t\t\tclipboard += source;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring filetext = \"\";\n\t\t\t\t\tifstream t(line);\n\n\t\t\t\t\tt.seekg(0, ios::end);\n\t\t\t\t\tfiletext.reserve(t.tellg());\n\t\t\t\t\tt.seekg(0, ios::beg);\n\n\t\t\t\t\tfiletext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());\n\t\t\t\t\tclipboard += filetext;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Duplicate\")\n\t\t\t{\n\t\t\t\tline = remaining.substr(0, remaining.find(\"\\n\"));\n\t\t\t\tremaining = remaining.substr(remaining.find(\"\\n\") + 1);\n\t\t\t\tint amount = stoi(line);\n\t\t\t\tstring origClipboard = clipboard;\n\t\t\t\tfor(int i = 0; i < amount - 1; i++) {\n\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(line == \"Pasta!\")\n\t\t\t{\n\t\t\t\tcout << clipboard << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tss << (loc + 1);\n\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encounter on line \" + ss.str(), argv);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception& e)\n\t\t{\n\t\t\tss << (loc + 1);\n\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + ss.str(), argv);\n\t\t}\n\n\t\t\n\t\tloc += 2;\n\t}\n\n\t\n\treturn 0;\n}\n"}
{"id": 57358, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst limit = 100000 \n\nfunc nonTwinSums(twins []int) []int {\n    sieve := make([]bool, limit+1)\n    for i := 0; i < len(twins); i++ {\n        for j := i; j < len(twins); j++ {\n            sum := twins[i] + twins[j]\n            if sum > limit {\n                break\n            }\n            sieve[sum] = true\n        }\n    }\n    var res []int\n    for i := 2; i < limit; i += 2 {\n        if !sieve[i] {\n            res = append(res, i)\n        }\n    }\n    return res\n}\n\nfunc main() {\n    primes := rcu.Primes(limit)[2:] \n    twins := []int{3}\n    for i := 0; i < len(primes)-1; i++ {\n        if primes[i+1]-primes[i] == 2 {\n            if twins[len(twins)-1] != primes[i] {\n                twins = append(twins, primes[i])\n            }\n            twins = append(twins, primes[i+1])\n        }\n    }\n    fmt.Println(\"Non twin prime sums:\")\n    ntps := nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n\n    fmt.Println(\"\\nNon twin prime sums (including 1):\")\n    twins = append([]int{1}, twins...)\n    ntps = nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nvoid print_non_twin_prime_sums(const std::vector<bool>& sums) {\n    int count = 0;\n    for (size_t i = 2; i < sums.size(); i += 2) {\n        if (!sums[i]) {\n            ++count;\n            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nFound \" << count << '\\n';\n}\n\nint main() {\n    const int limit = 100001;\n\n    std::vector<bool> sieve = prime_sieve(limit + 2);\n    \n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))\n            sieve[i] = false;\n    }\n\n    std::vector<bool> twin_prime_sums(limit, false);\n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i]) {\n            for (size_t j = i; i + j < limit; ++j) {\n                if (sieve[j])\n                    twin_prime_sums[i + j] = true;\n            }\n        }\n    }\n\n    std::cout << \"Non twin prime sums:\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n\n    sieve[1] = true;\n    for (size_t i = 1; i + 1 < limit; ++i) {\n        if (sieve[i])\n            twin_prime_sums[i + 1] = true;\n    }\n\n    std::cout << \"\\nNon twin prime sums (including 1):\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n}\n"}
{"id": 57359, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst limit = 100000 \n\nfunc nonTwinSums(twins []int) []int {\n    sieve := make([]bool, limit+1)\n    for i := 0; i < len(twins); i++ {\n        for j := i; j < len(twins); j++ {\n            sum := twins[i] + twins[j]\n            if sum > limit {\n                break\n            }\n            sieve[sum] = true\n        }\n    }\n    var res []int\n    for i := 2; i < limit; i += 2 {\n        if !sieve[i] {\n            res = append(res, i)\n        }\n    }\n    return res\n}\n\nfunc main() {\n    primes := rcu.Primes(limit)[2:] \n    twins := []int{3}\n    for i := 0; i < len(primes)-1; i++ {\n        if primes[i+1]-primes[i] == 2 {\n            if twins[len(twins)-1] != primes[i] {\n                twins = append(twins, primes[i])\n            }\n            twins = append(twins, primes[i+1])\n        }\n    }\n    fmt.Println(\"Non twin prime sums:\")\n    ntps := nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n\n    fmt.Println(\"\\nNon twin prime sums (including 1):\")\n    twins = append([]int{1}, twins...)\n    ntps = nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(int limit) {\n    std::vector<bool> sieve(limit, true);\n    if (limit > 0)\n        sieve[0] = false;\n    if (limit > 1)\n        sieve[1] = false;\n    for (int i = 4; i < limit; i += 2)\n        sieve[i] = false;\n    for (int p = 3, sq = 9; sq < limit; p += 2) {\n        if (sieve[p]) {\n            for (int q = sq; q < limit; q += p << 1)\n                sieve[q] = false;\n        }\n        sq += (p + 1) << 2;\n    }\n    return sieve;\n}\n\nvoid print_non_twin_prime_sums(const std::vector<bool>& sums) {\n    int count = 0;\n    for (size_t i = 2; i < sums.size(); i += 2) {\n        if (!sums[i]) {\n            ++count;\n            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\\n' : ' ');\n        }\n    }\n    std::cout << \"\\nFound \" << count << '\\n';\n}\n\nint main() {\n    const int limit = 100001;\n\n    std::vector<bool> sieve = prime_sieve(limit + 2);\n    \n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))\n            sieve[i] = false;\n    }\n\n    std::vector<bool> twin_prime_sums(limit, false);\n    for (size_t i = 0; i < limit; ++i) {\n        if (sieve[i]) {\n            for (size_t j = i; i + j < limit; ++j) {\n                if (sieve[j])\n                    twin_prime_sums[i + j] = true;\n            }\n        }\n    }\n\n    std::cout << \"Non twin prime sums:\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n\n    sieve[1] = true;\n    for (size_t i = 1; i + 1 < limit; ++i) {\n        if (sieve[i])\n            twin_prime_sums[i + 1] = true;\n    }\n\n    std::cout << \"\\nNon twin prime sums (including 1):\\n\";\n    print_non_twin_prime_sums(twin_prime_sums);\n}\n"}
{"id": 57360, "name": "Kosaraju", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 57361, "name": "Monads_Writer monad", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct LoggingMonad\n{\n    double Value;\n    string Log;\n};\n\n\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n    auto result = f(monad.Value);\n    return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n\nauto MakeWriter = [](auto f, string message)\n{\n    return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n    \n    auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n    cout << result.Log << \"\\nResult: \" << result.Value;\n}\n"}
{"id": 57362, "name": "Nested templated data", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"text/template\"\n)\n\nfunc main() {\n    const t = `[[[{{index .P 1}}, {{index .P 2}}],\n  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n  {{index .P 5}}]]\n`\n    type S struct {\n        P map[int]string\n    }\n\n    var s S\n    s.P = map[int]string{\n        0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n        4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n    }\n    tmpl := template.Must(template.New(\"\").Parse(t))\n    tmpl.Execute(os.Stdout, s)\n\n    var unused []int\n    for k, _ := range s.P {\n        if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n            unused = append(unused, k)\n        }\n    }\n    sort.Ints(unused)\n    fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}\n", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n"}
{"id": 57363, "name": "Inner classes", "Go": "package main\n\nimport \"fmt\"\n\ntype Outer struct {\n    field int\n    Inner struct {\n        field int\n    }\n}\n\nfunc (o *Outer) outerMethod() {\n    fmt.Println(\"Outer's field has a value of\", o.field)\n}\n\nfunc (o *Outer) innerMethod() {\n    fmt.Println(\"Inner's field has a value of\", o.Inner.field)\n}\n\nfunc main() {\n    o := &Outer{field: 43}\n    o.Inner.field = 42\n    o.innerMethod()\n    o.outerMethod()\n    \n    p := &Outer{\n        field: 45,\n        Inner: struct {\n            field int\n        }{\n            field: 44,\n        },\n    }\n    p.innerMethod()\n    p.outerMethod()\n}\n", "C++": "#include <iostream>\n#include <vector>\n\nclass Outer\n{\n    int m_privateField;\n    \npublic:\n    \n    Outer(int value) : m_privateField{value}{}\n    \n    \n    class Inner\n    {\n        int m_innerValue;\n        \n    public:\n        \n        Inner(int innerValue) : m_innerValue{innerValue}{}\n        \n        \n        int AddOuter(Outer outer) const\n        {\n            \n            return outer.m_privateField + m_innerValue;\n        }\n    };\n};\n\nint main()\n{\n    \n    \n    Outer::Inner inner{42};\n    \n    \n    Outer outer{1};  \n    auto sum = inner.AddOuter(outer);\n    std::cout << \"sum: \" << sum << \"\\n\";\n    \n    \n    std::vector<int> vec{1,2,3};\n    std::vector<int>::iterator itr = vec.begin();\n    std::cout << \"vec[0] = \" << *itr << \"\\n\";\n}\n"}
{"id": 57364, "name": "Special pythagorean triplet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    start := time.Now()\n    for a := 3; ; a++ {\n        for b := a + 1; ; b++ {\n            c := 1000 - a - b\n            if c <= b {\n                break\n            }\n            if a*a+b*b == c*c {\n                fmt.Printf(\"a = %d, b = %d, c = %d\\n\", a, b, c)\n                fmt.Println(\"a + b + c =\", a+b+c)\n                fmt.Println(\"a * b * c =\", a*b*c)\n                fmt.Println(\"\\nTook\", time.Since(start))\n                return\n            }\n        }\n    }\n}\n", "C++": "#include <cmath>\n#include <concepts>\n#include <iostream>\n#include <numeric>\n#include <optional>\n#include <tuple>\n \nusing namespace std;\n\noptional<tuple<int, int ,int>> FindPerimeterTriplet(int perimeter)\n{\n    unsigned long long perimeterULL = perimeter;\n    auto max_M = (unsigned long long)sqrt(perimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n\n            \n            \n            \n            \n \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto primitive = a + b + c;\n\n            \n            auto factor = perimeterULL / primitive;\n            if(primitive * factor == perimeterULL)\n            {\n              \n              if(b<a) swap(a, b);\n              return tuple{a * factor, b * factor, c * factor};\n            }\n        }\n    }\n\n    \n    return nullopt;\n}\n \nint main()\n{\n  auto t1 = FindPerimeterTriplet(1000);\n  if(t1)\n  {\n    auto [a, b, c] = *t1;\n    cout << \"[\" << a << \", \" << b << \", \" << c << \"]\\n\";\n    cout << \"a * b * c = \" << a * b * c << \"\\n\";\n  }\n  else\n  {\n    cout << \"Perimeter not found\\n\";\n  }\n}\n"}
{"id": 57365, "name": "Mastermind", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <ctime>\n#include <string>\n#include <vector>\n\ntypedef std::vector<char> vecChar;\n\nclass master {\npublic:\n    master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {\n        std::string color = \"ABCDEFGHIJKLMNOPQRST\";\n\n        if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;\n        if( !rpt && clr_count < code_len ) clr_count = code_len; \n        if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;\n        if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;\n        \n        codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;\n\n        for( size_t s = 0; s < colorsCnt; s++ ) {\n            colors.append( 1, color.at( s ) );\n        }\n    }\n    void play() {\n        bool win = false;\n        combo = getCombo();\n\n        while( guessCnt ) {\n            showBoard();\n            if( checkInput( getInput() ) ) {\n                win = true;\n                break;\n            }\n            guessCnt--;\n        }\n        if( win ) {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"Very well done!\\nYou found the code: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        } else {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"I am sorry, you couldn't make it!\\nThe code was: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        }\n    }\nprivate:\n    void showBoard() {\n        vecChar::iterator y;\n        for( int x = 0; x < guesses.size(); x++ ) {\n            std::cout << \"\\n--------------------------------\\n\";\n            std::cout << x + 1 << \": \";\n            for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            std::cout << \" :  \";\n            for( y = results[x].begin(); y != results[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            int z = codeLen - results[x].size();\n            if( z > 0 ) {\n                for( int x = 0; x < z; x++ ) std::cout << \"- \";\n            }\n        }\n        std::cout << \"\\n\\n\";\n    }\n    std::string getInput() {\n        std::string a;\n        while( true ) {\n            std::cout << \"Enter your guess (\" << colors << \"): \";\n            a = \"\"; std::cin >> a;\n            std::transform( a.begin(), a.end(), a.begin(), ::toupper );\n            if( a.length() > codeLen ) a.erase( codeLen );\n            bool r = true;\n            for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n                if( colors.find( *x ) == std::string::npos ) {\n                    r = false;\n                    break;\n                }\n            }\n            if( r ) break;\n        }\n        return a;\n    }\n    bool checkInput( std::string a ) {\n        vecChar g;\n        for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n            g.push_back( *x );\n        }\n        guesses.push_back( g );\n        \n        int black = 0, white = 0;\n        std::vector<bool> gmatch( codeLen, false );\n        std::vector<bool> cmatch( codeLen, false );\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if( a.at( i ) == combo.at( i ) ) {\n                gmatch[i] = true;\n                cmatch[i] = true;\n                black++;\n            }\n        }\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if (gmatch[i]) continue;\n            for( int j = 0; j < codeLen; j++ ) {\n                if (i == j || cmatch[j]) continue;\n                if( a.at( i ) == combo.at( j ) ) {\n                    cmatch[j] = true;\n                    white++;\n                    break;\n                }\n            }\n        }\n       \n        vecChar r;\n        for( int b = 0; b < black; b++ ) r.push_back( 'X' );\n        for( int w = 0; w < white; w++ ) r.push_back( 'O' );\n        results.push_back( r );\n\n        return ( black == codeLen );\n    }\n    std::string getCombo() {\n        std::string c, clr = colors;\n        int l, z;\n\n        for( size_t s = 0; s < codeLen; s++ ) {\n            z = rand() % ( int )clr.length();\n            c.append( 1, clr[z] );\n            if( !repeatClr ) clr.erase( z, 1 );\n        }\n        return c;\n    }\n\n    size_t codeLen, colorsCnt, guessCnt;\n    bool repeatClr;\n    std::vector<vecChar> guesses, results;\n    std::string colors, combo;\n};\n\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    master m( 4, 8, 12, false );\n    m.play();\n    return 0;\n}\n"}
{"id": 57366, "name": "Mastermind", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <ctime>\n#include <string>\n#include <vector>\n\ntypedef std::vector<char> vecChar;\n\nclass master {\npublic:\n    master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {\n        std::string color = \"ABCDEFGHIJKLMNOPQRST\";\n\n        if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;\n        if( !rpt && clr_count < code_len ) clr_count = code_len; \n        if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;\n        if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;\n        \n        codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;\n\n        for( size_t s = 0; s < colorsCnt; s++ ) {\n            colors.append( 1, color.at( s ) );\n        }\n    }\n    void play() {\n        bool win = false;\n        combo = getCombo();\n\n        while( guessCnt ) {\n            showBoard();\n            if( checkInput( getInput() ) ) {\n                win = true;\n                break;\n            }\n            guessCnt--;\n        }\n        if( win ) {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"Very well done!\\nYou found the code: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        } else {\n            std::cout << \"\\n\\n--------------------------------\\n\" <<\n                \"I am sorry, you couldn't make it!\\nThe code was: \" << combo <<\n                \"\\n--------------------------------\\n\\n\";\n        }\n    }\nprivate:\n    void showBoard() {\n        vecChar::iterator y;\n        for( int x = 0; x < guesses.size(); x++ ) {\n            std::cout << \"\\n--------------------------------\\n\";\n            std::cout << x + 1 << \": \";\n            for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            std::cout << \" :  \";\n            for( y = results[x].begin(); y != results[x].end(); y++ ) {\n                std::cout << *y << \" \";\n            }\n\n            int z = codeLen - results[x].size();\n            if( z > 0 ) {\n                for( int x = 0; x < z; x++ ) std::cout << \"- \";\n            }\n        }\n        std::cout << \"\\n\\n\";\n    }\n    std::string getInput() {\n        std::string a;\n        while( true ) {\n            std::cout << \"Enter your guess (\" << colors << \"): \";\n            a = \"\"; std::cin >> a;\n            std::transform( a.begin(), a.end(), a.begin(), ::toupper );\n            if( a.length() > codeLen ) a.erase( codeLen );\n            bool r = true;\n            for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n                if( colors.find( *x ) == std::string::npos ) {\n                    r = false;\n                    break;\n                }\n            }\n            if( r ) break;\n        }\n        return a;\n    }\n    bool checkInput( std::string a ) {\n        vecChar g;\n        for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {\n            g.push_back( *x );\n        }\n        guesses.push_back( g );\n        \n        int black = 0, white = 0;\n        std::vector<bool> gmatch( codeLen, false );\n        std::vector<bool> cmatch( codeLen, false );\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if( a.at( i ) == combo.at( i ) ) {\n                gmatch[i] = true;\n                cmatch[i] = true;\n                black++;\n            }\n        }\n \n        for( int i = 0; i < codeLen; i++ ) {\n            if (gmatch[i]) continue;\n            for( int j = 0; j < codeLen; j++ ) {\n                if (i == j || cmatch[j]) continue;\n                if( a.at( i ) == combo.at( j ) ) {\n                    cmatch[j] = true;\n                    white++;\n                    break;\n                }\n            }\n        }\n       \n        vecChar r;\n        for( int b = 0; b < black; b++ ) r.push_back( 'X' );\n        for( int w = 0; w < white; w++ ) r.push_back( 'O' );\n        results.push_back( r );\n\n        return ( black == codeLen );\n    }\n    std::string getCombo() {\n        std::string c, clr = colors;\n        int l, z;\n\n        for( size_t s = 0; s < codeLen; s++ ) {\n            z = rand() % ( int )clr.length();\n            c.append( 1, clr[z] );\n            if( !repeatClr ) clr.erase( z, 1 );\n        }\n        return c;\n    }\n\n    size_t codeLen, colorsCnt, guessCnt;\n    bool repeatClr;\n    std::vector<vecChar> guesses, results;\n    std::string colors, combo;\n};\n\nint main( int argc, char* argv[] ) {\n    srand( unsigned( time( 0 ) ) );\n    master m( 4, 8, 12, false );\n    m.play();\n    return 0;\n}\n"}
{"id": 57367, "name": "Untouchable numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i := 1 + k; i*i <= n; i += k {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n    }\n    return sum\n}\n\nfunc sieve(n int) []bool {\n    n++\n    s := make([]bool, n+1) \n    for i := 6; i <= n; i++ {\n        sd := sumDivisors(i)\n        if sd <= n {\n            s[sd] = true\n        }\n    }\n    return s\n}\n\nfunc primeSieve(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 main() {    \n    limit := 1000000\n    c := primeSieve(limit)\n    s := sieve(63 * limit)\n    untouchable := []int{2, 5}\n    for n := 6; n <= limit; n += 2 {\n        if !s[n] && c[n-1] && c[n-3] {\n            untouchable = append(untouchable, n)\n        }\n    }\n    fmt.Println(\"List of untouchable numbers <= 2,000:\")\n    count := 0\n    for i := 0; untouchable[i] <= 2000; i++ {\n        fmt.Printf(\"%6s\", commatize(untouchable[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        count++\n    }\n    fmt.Printf(\"\\n\\n%7s untouchable numbers were found  <=     2,000\\n\", commatize(count))\n    p := 10\n    count = 0\n    for _, n := range untouchable {\n        count++\n        if n > p {\n            cc := commatize(count - 1)\n            cp := commatize(p)\n            fmt.Printf(\"%7s untouchable numbers were found  <= %9s\\n\", cc, cp)\n            p = p * 10\n            if p == limit {\n                break\n            }\n        }\n    }\n    cu := commatize(len(untouchable))\n    cl := commatize(limit)\n    fmt.Printf(\"%7s untouchable numbers were found  <= %s\\n\", cu, cl)\n}\n", "C++": "\n#include <functional>\n#include <bitset> \n#include <iostream>\n#include <cmath>\nusing namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;\nconst int maxUT{3000000}, dL{(int)log2(maxUT)};\nstruct uT{\n  bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};\n  void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}\n  Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}\n  Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}\n  Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}\n  void fL(Z3 n, int g){for(;;){\n    if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}\n    if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}\n  }\n  int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}\n  uT(const int n):mUT{n}{\n    N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();\n    N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);\n  }\n};\n"}
{"id": 57368, "name": "Untouchable numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i := 1 + k; i*i <= n; i += k {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n    }\n    return sum\n}\n\nfunc sieve(n int) []bool {\n    n++\n    s := make([]bool, n+1) \n    for i := 6; i <= n; i++ {\n        sd := sumDivisors(i)\n        if sd <= n {\n            s[sd] = true\n        }\n    }\n    return s\n}\n\nfunc primeSieve(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 main() {    \n    limit := 1000000\n    c := primeSieve(limit)\n    s := sieve(63 * limit)\n    untouchable := []int{2, 5}\n    for n := 6; n <= limit; n += 2 {\n        if !s[n] && c[n-1] && c[n-3] {\n            untouchable = append(untouchable, n)\n        }\n    }\n    fmt.Println(\"List of untouchable numbers <= 2,000:\")\n    count := 0\n    for i := 0; untouchable[i] <= 2000; i++ {\n        fmt.Printf(\"%6s\", commatize(untouchable[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n        count++\n    }\n    fmt.Printf(\"\\n\\n%7s untouchable numbers were found  <=     2,000\\n\", commatize(count))\n    p := 10\n    count = 0\n    for _, n := range untouchable {\n        count++\n        if n > p {\n            cc := commatize(count - 1)\n            cp := commatize(p)\n            fmt.Printf(\"%7s untouchable numbers were found  <= %9s\\n\", cc, cp)\n            p = p * 10\n            if p == limit {\n                break\n            }\n        }\n    }\n    cu := commatize(len(untouchable))\n    cl := commatize(limit)\n    fmt.Printf(\"%7s untouchable numbers were found  <= %s\\n\", cu, cl)\n}\n", "C++": "\n#include <functional>\n#include <bitset> \n#include <iostream>\n#include <cmath>\nusing namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;\nconst int maxUT{3000000}, dL{(int)log2(maxUT)};\nstruct uT{\n  bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};\n  void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}\n  Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}\n  Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}\n  Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}\n  void fL(Z3 n, int g){for(;;){\n    if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}\n    if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}\n    if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}\n  }\n  int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}\n  uT(const int n):mUT{n}{\n    N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();\n    N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);\n  }\n};\n"}
{"id": 57369, "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", "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": 57370, "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", "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": 57371, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 57372, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 57373, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 57374, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 57375, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 57376, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 57377, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 57378, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 57379, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 57380, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 57381, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 57382, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 57383, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 57384, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 57385, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 57386, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 57387, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 57388, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 57389, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 57390, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 57391, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 57392, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 57393, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 57394, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 57395, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 57396, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 57397, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 57398, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 57399, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 57400, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 57401, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 57402, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 57403, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 57404, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 57405, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 57406, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 57407, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 57408, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 57409, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 57410, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 57411, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 57412, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 57413, "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", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 57414, "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", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 57415, "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", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 57416, "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", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 57417, "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", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 57418, "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", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 57419, "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", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 57420, "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", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 57421, "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", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 57422, "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", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 57423, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 57424, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 57425, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 57426, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 57427, "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", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 57428, "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", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 57429, "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", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 57430, "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", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 57431, "name": "Stack", "Go": "var intStack []int\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 57432, "name": "Stack", "Go": "var intStack []int\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 57433, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 57434, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 57435, "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", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 57436, "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", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 57437, "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", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 57438, "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", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 57439, "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", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 57440, "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", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 57441, "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", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 57442, "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", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 57443, "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", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 57444, "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", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 57445, "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", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 57446, "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", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 57447, "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", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 57448, "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", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 57449, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 57450, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 57451, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 57452, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 57453, "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", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 57454, "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", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 57455, "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", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 57456, "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", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 57457, "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", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 57458, "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", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 57459, "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", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 57460, "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", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 57461, "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", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 57462, "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", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 57463, "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", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 57464, "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", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 57465, "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", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 57466, "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", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 57467, "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", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 57468, "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", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 57469, "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", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 57470, "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", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 57471, "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", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 57472, "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", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 57473, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 57474, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 57475, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 57476, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 57477, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 57478, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 57479, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 57480, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 57481, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 57482, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 57483, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 57484, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 57485, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 57486, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 57487, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 57488, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 57489, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 57490, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 57491, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 57492, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 57493, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 57494, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 57495, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 57496, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 57497, "name": "Table creation_Postal addresses", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 57498, "name": "Table creation_Postal addresses", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 57499, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "PHP": "include(\"file.php\")\n"}
{"id": 57500, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "PHP": "include(\"file.php\")\n"}
{"id": 57501, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "PHP": "include(\"file.php\")\n"}
{"id": 57502, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "PHP": "include(\"file.php\")\n"}
{"id": 57503, "name": "Soundex", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 57504, "name": "Soundex", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 57505, "name": "Bitmap_Histogram", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 57506, "name": "Bitmap_Histogram", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 57507, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 57508, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 57509, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 57510, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 57511, "name": "SOAP", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n"}
{"id": 57512, "name": "SOAP", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n"}
{"id": 57513, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 57514, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 57515, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 57516, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 57517, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 57518, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 57519, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 57520, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 57521, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 57522, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 57523, "name": "Calendar - for _REAL_ programmers", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n"}
{"id": 57524, "name": "Calendar - for _REAL_ programmers", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n"}
{"id": 57525, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "PHP": "while(1)\n    echo \"SPAM\\n\";\n"}
{"id": 57526, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "PHP": "while(1)\n    echo \"SPAM\\n\";\n"}
{"id": 57527, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 57528, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 57529, "name": "Active Directory_Search for a user", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 57530, "name": "Active Directory_Search for a user", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 57531, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 57532, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 57533, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 57534, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 57535, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 57536, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 57537, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 57538, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 57539, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 57540, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 57541, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 57542, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 57543, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 57544, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 57545, "name": "Bitmap_Bézier curves_Cubic", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n"}
{"id": 57546, "name": "Bitmap_Bézier curves_Cubic", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n"}
{"id": 57547, "name": "Active Directory_Connect", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 57548, "name": "Active Directory_Connect", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 57549, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 57550, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 57551, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 57552, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 57553, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 57554, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 57555, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 57556, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 57557, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 57558, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 57559, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 57560, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 57561, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 57562, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 57563, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 57564, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 57565, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 57566, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 57567, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 57568, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 57569, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 57570, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 57571, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 57572, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 57573, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 57574, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 57575, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 57576, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 57577, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 57578, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 57579, "name": "Respond to an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 57580, "name": "Respond to an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 57581, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 57582, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 57583, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 57584, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 57585, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 57586, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 57587, "name": "Reflection_List properties", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 57588, "name": "Reflection_List properties", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 57589, "name": "Align columns", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 57590, "name": "Align columns", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 57591, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 57592, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 57593, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 57594, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 57595, "name": "Dynamic variable names", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 57596, "name": "Dynamic variable names", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 57597, "name": "Reflection_List methods", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 57598, "name": "Reflection_List methods", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 57599, "name": "Send an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 57600, "name": "Send an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 57601, "name": "Variables", "Go": "x := 3\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 57602, "name": "Variables", "Go": "x := 3\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 57603, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 57604, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 57605, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 57606, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 57607, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 57608, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 57609, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 57610, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 57611, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 57612, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 57613, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 57614, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 57615, "name": "OpenWebNet password", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n    start := true\n    num1 := uint32(0)\n    num2 := num1\n    i, _ := strconv.Atoi(password)\n    pwd := uint32(i)\n    for _, c := range nonce {\n        if c != '0' {\n            if start {\n                num2 = pwd\n            }\n            start = false\n        }\n        switch c {\n        case '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        case '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        case '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        case '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        case '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        case '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        case '7':\n            num3 := num2 & 0x0000FF00\n            num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n            num1 = num3 | num4\n            num2 = (num2 & 0xFF000000) >> 8\n        case '8':\n            num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n            num2 = (num2 & 0x00FF0000) >> 8\n        case '9':\n            num1 = ^num2\n        default:\n            num1 = num2\n        }\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if c != '0' && c != '9' {\n            num1 |= num2\n        }\n        num2 = num1\n    }\n    return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n    res := ownCalcPass(password, nonce)\n    m := fmt.Sprintf(\"%s  %s  %-10d  %-10d\", password, nonce, res, expected)\n    if res == expected {\n        fmt.Println(\"PASS\", m)\n    } else {\n        fmt.Println(\"FAIL\", m)\n    }\n}\n\nfunc main() {\n    testPasswordCalc(\"12345\", \"603356072\", 25280520)\n    testPasswordCalc(\"12345\", \"410501656\", 119537670)\n    testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}\n", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n"}
{"id": 57616, "name": "OpenWebNet password", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n    start := true\n    num1 := uint32(0)\n    num2 := num1\n    i, _ := strconv.Atoi(password)\n    pwd := uint32(i)\n    for _, c := range nonce {\n        if c != '0' {\n            if start {\n                num2 = pwd\n            }\n            start = false\n        }\n        switch c {\n        case '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        case '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        case '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        case '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        case '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        case '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        case '7':\n            num3 := num2 & 0x0000FF00\n            num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n            num1 = num3 | num4\n            num2 = (num2 & 0xFF000000) >> 8\n        case '8':\n            num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n            num2 = (num2 & 0x00FF0000) >> 8\n        case '9':\n            num1 = ^num2\n        default:\n            num1 = num2\n        }\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if c != '0' && c != '9' {\n            num1 |= num2\n        }\n        num2 = num1\n    }\n    return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n    res := ownCalcPass(password, nonce)\n    m := fmt.Sprintf(\"%s  %s  %-10d  %-10d\", password, nonce, res, expected)\n    if res == expected {\n        fmt.Println(\"PASS\", m)\n    } else {\n        fmt.Println(\"FAIL\", m)\n    }\n}\n\nfunc main() {\n    testPasswordCalc(\"12345\", \"603356072\", 25280520)\n    testPasswordCalc(\"12345\", \"410501656\", 119537670)\n    testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}\n", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n"}
{"id": 57617, "name": "Monads_Writer monad", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n"}
{"id": 57618, "name": "Monads_Writer monad", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n"}
{"id": 57619, "name": "Canny edge detector", "Go": "package main\n\nimport (\n    ed \"github.com/Ernyoke/Imger/edgedetection\"\n    \"github.com/Ernyoke/Imger/imgio\"\n    \"log\"\n)\n\nfunc main() {\n    img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not read image\", err)\n    }\n\n    cny, err := ed.CannyRGBA(img, 15, 45, 5)\n    if err != nil {\n        log.Fatal(\"Could not perform Canny Edge detection\")\n    }\n\n    err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not write Canny image to disk\")\n    }\n}\n", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n"}
{"id": 57620, "name": "Canny edge detector", "Go": "package main\n\nimport (\n    ed \"github.com/Ernyoke/Imger/edgedetection\"\n    \"github.com/Ernyoke/Imger/imgio\"\n    \"log\"\n)\n\nfunc main() {\n    img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not read image\", err)\n    }\n\n    cny, err := ed.CannyRGBA(img, 15, 45, 5)\n    if err != nil {\n        log.Fatal(\"Could not perform Canny Edge detection\")\n    }\n\n    err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not write Canny image to disk\")\n    }\n}\n", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n"}
{"id": 57621, "name": "Add a variable to a class instance at runtime", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n"}
{"id": 57622, "name": "Add a variable to a class instance at runtime", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n"}
{"id": 57623, "name": "Find URI in text", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n"}
{"id": 57624, "name": "Find URI in text", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n"}
{"id": 57625, "name": "Find URI in text", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n"}
{"id": 57626, "name": "Find URI in text", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre\"\n)\n\nvar pattern = \n    \"(*UTF)(*UCP)\" +                    \n    \"[a-z][-a-z0-9+.]*:\" +              \n    \"(?=[/\\\\w])\" +                      \n    \"(?:\n    \"[-\\\\w.~/%!$&'()*+,;=]*\" +          \n    \"(?:\\\\?[-\\\\w.~%!$&'()*+,;=/?]*)?\" + \n    \"(?:\\\\#[-\\\\w.~%!$&'()*+,;=/?]*)?\"   \n\nfunc main() {\n    text := `\nthis URI contains an illegal character, parentheses and a misplaced full stop:\nhttp:\nand another one just to confuse the parser: http:\n\")\" is handled the wrong way by the mediawiki parser.\nftp:\nftp:\nftp:\nleading junk ftp:\nleading junk ftp:\nif you have other interesting URIs for testing, please add them here:\nhttp:\nhttp:\n`\n    descs := []string{\"URIs:-\", \"IRIs:-\"}\n    patterns := []string{pattern[12:], pattern}\n    for i := 0; i <= 1; i++ {\n        fmt.Println(descs[i])\n        re := pcre.MustCompile(patterns[i], 0)\n        t := text\n        for {\n            se := re.FindIndex([]byte(t), 0)\n            if se == nil {\n                break\n            }\n            fmt.Println(t[se[0]:se[1]])\n            t = t[se[1]:]\n        }\n        fmt.Println()\n    }\n}\n", "PHP": "$tests = array(\n    'this URI contains an illegal character, parentheses and a misplaced full stop:',\n    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',\n    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',\n    '\")\" is handled the wrong way by the mediawiki parser.',\n    'ftp://domain.name/path(balanced_brackets)/foo.html',\n    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',\n    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',\n    'leading junk ftp://domain.name/path/embedded?punct/uation.',\n    'leading junk ftp://domain.name/dangling_close_paren)',\n    'if you have other interesting URIs for testing, please add them here:',\n    'http://www.example.org/foo.html#includes_fragment',\n    'http://www.example.org/foo.html#enthält_Unicode-Fragment',\n    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',\n    'blah (foo://domain.hld/))))',\n    'https://haxor.ur:4592/~mama/####&?foo'\n);\n\nforeach ( $tests as $test ) {\n    foreach( explode( ' ', $test ) as $uri ) {\n        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )\n            echo $uri, PHP_EOL;\n    }\n}\n"}
{"id": 57627, "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", "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": 57628, "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", "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": 57629, "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", "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": 57630, "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", "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": 57631, "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", "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": 57632, "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", "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": 57633, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 57634, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 57635, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\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": 57636, "name": "Peano curve", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\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": 57637, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\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": 57638, "name": "Extensible prime generator", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n", "Python": "islice(count(7), 0, None, 2)\n"}
{"id": 57639, "name": "Create a two-dimensional array at runtime", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\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": 57640, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 57641, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 57642, "name": "Pi", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\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": 57643, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 57644, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 57645, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 57646, "name": "Return multiple values", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 57647, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 57648, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 57649, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 57650, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 57651, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n", "Python": "for i in range(1, 11):\n    if i % 5 == 0:\n        print(i)\n        continue\n    print(i, end=', ')\n"}
{"id": 57652, "name": "LU decomposition", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\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": 57653, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\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": 57654, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\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": 57655, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\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": 57656, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\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": 57657, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\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": 57658, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\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": 57659, "name": "Text processing_1", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\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": 57660, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\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": 57661, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\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": 57662, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\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": 57663, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\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": 57664, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\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": 57665, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\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": 57666, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\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": 57667, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\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": 57668, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 57669, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\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": 57670, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n"}
{"id": 57671, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\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": 57672, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\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": 57673, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\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": 57674, "name": "Fractran", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\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": 57675, "name": "Read a configuration file", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\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": 57676, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\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": 57677, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\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": 57678, "name": "List comprehensions", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\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": 57679, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\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": 57680, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\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": 57681, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\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": 57682, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\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": 57683, "name": "Case-sensitivity of identifiers", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\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": 57684, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n"}
{"id": 57685, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 57686, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 57687, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \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": 57688, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \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": 57689, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\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": 57690, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\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": 57691, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\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": 57692, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 57693, "name": "Pell's equation", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\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": 57694, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\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": 57695, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\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": 57696, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\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": 57697, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 57698, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 57699, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\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": 57700, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\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": 57701, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\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": 57702, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 57703, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 57704, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n"}
{"id": 57705, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 57706, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 57707, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n"}
{"id": 57708, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n"}
{"id": 57709, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n"}
{"id": 57710, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n"}
{"id": 57711, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 57712, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n"}
{"id": 57713, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 57714, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 57715, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n"}
{"id": 57716, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n"}
{"id": 57717, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n"}
{"id": 57718, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"}
{"id": 57719, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n"}
{"id": 57720, "name": "Jaro similarity", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 57721, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n"}
{"id": 57722, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n"}
{"id": 57723, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n"}
{"id": 57724, "name": "Trabb Pardo–Knuth algorithm", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n"}
{"id": 57725, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n"}
{"id": 57726, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 57727, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n"}
{"id": 57728, "name": "Biorhythms", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"}
{"id": 57729, "name": "Biorhythms", "VB": "Function Biorhythm(Birthdate As Date, Targetdate As Date) As String\n\n\nTextArray = Array(Array(\"up and rising\", \"peak\"), Array(\"up but falling\", \"transition\"), Array(\"down and falling\", \"valley\"), Array(\"down but rising\", \"transition\"))\n\nDaysBetween = Targetdate - Birthdate\n\npositionP = DaysBetween Mod 23\npositionE = DaysBetween Mod 28\npositionM = DaysBetween Mod 33\n\n\nBiorhythm = CStr(positionP) & \"/\" & CStr(positionE) & \"/\" & CStr(positionM)\n\nquadrantP = Int(4 * positionP / 23)\nquadrantE = Int(4 * positionE / 28)\nquadrantM = Int(4 * positionM / 33)\n\npercentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)\npercentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)\npercentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)\n\ntransitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP\ntransitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE\ntransitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM\n\nSelect Case True\n    Case percentageP > 95\n        textP = \"Physical day \" & positionP & \" : \" & \"peak\"\n    Case percentageP < -95\n        textP = \"Physical day \" & positionP & \" : \" & \"valley\"\n    Case percentageP < 5 And percentageP > -5\n        textP = \"Physical day \" & positionP & \" : \" & \"critical transition\"\n    Case Else\n        textP = \"Physical day \" & positionP & \" : \" & percentageP & \"% (\" & TextArray(quadrantP)(0) & \", next \" & TextArray(quadrantP)(1) & \" \" & transitionP & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageE > 95\n        textE = \"Emotional day \" & positionE & \" : \" & \"peak\"\n    Case percentageE < -95\n        textE = \"Emotional day \" & positionE & \" : \" & \"valley\"\n    Case percentageE < 5 And percentageE > -5\n        textE = \"Emotional day \" & positionE & \" : \" & \"critical transition\"\n    Case Else\n        textE = \"Emotional day \" & positionE & \" : \" & percentageE & \"% (\" & TextArray(quadrantE)(0) & \", next \" & TextArray(quadrantE)(1) & \" \" & transitionE & \")\"\nEnd Select\n\nSelect Case True\n    Case percentageM > 95\n        textM = \"Mental day \" & positionM & \" : \" & \"peak\"\n    Case percentageM < -95\n        textM = \"Mental day \" & positionM & \" : \" & \"valley\"\n    Case percentageM < 5 And percentageM > -5\n        textM = \"Mental day \" & positionM & \" : \" & \"critical transition\"\n    Case Else\n        textM = \"Mental day \" & positionM & \" : \" & percentageM & \"% (\" & TextArray(quadrantM)(0) & \", next \" & TextArray(quadrantM)(1) & \" \" & transitionM & \")\"\nEnd Select\n\nHeader1Text = \"Born \" & Birthdate & \", Target \" & Targetdate\nHeader2Text = \"Day \" & DaysBetween\n\n\nDebug.Print Header1Text\nDebug.Print Header2Text\nDebug.Print textP\nDebug.Print textE\nDebug.Print textM\nDebug.Print \"\"\n\nEnd Function\n", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"}
{"id": 57730, "name": "Table creation_Postal addresses", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n"}
{"id": 57731, "name": "Stern-Brocot sequence", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n"}
{"id": 57732, "name": "Soundex", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n"}
{"id": 57733, "name": "Chat server", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n"}
{"id": 57734, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 57735, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n"}
{"id": 57736, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 57737, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 57738, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n"}
{"id": 57739, "name": "Terminal control_Dimensions", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n"}
{"id": 57740, "name": "Terminal control_Dimensions", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n"}
{"id": 57741, "name": "Finite state machine", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n"}
{"id": 57742, "name": "Finite state machine", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n"}
{"id": 57743, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 57744, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n"}
{"id": 57745, "name": "Sierpinski pentagon", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n"}
{"id": 57746, "name": "Rep-string", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n"}
{"id": 57747, "name": "Literals_String", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n"}
{"id": 57748, "name": "GUI_Maximum window dimensions", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n"}
{"id": 57749, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n"}
{"id": 57750, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 57751, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n"}
{"id": 57752, "name": "Parse an IP Address", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n"}
{"id": 57753, "name": "Textonyms", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n"}
{"id": 57754, "name": "Range extraction", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n"}
{"id": 57755, "name": "Maximum triangle path sum", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n"}
{"id": 57756, "name": "Zhang-Suen thinning algorithm", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n"}
{"id": 57757, "name": "Variable declaration reset", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n"}
{"id": 57758, "name": "Koch 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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n"}
{"id": 57759, "name": "Draw a pixel", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n"}
{"id": 57760, "name": "Words from neighbour ones", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n"}
{"id": 57761, "name": "UTF-8 encode and decode", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n"}
{"id": 57762, "name": "Magic squares of doubly even order", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n"}
{"id": 57763, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n"}
{"id": 57764, "name": "Execute a system command", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n"}
{"id": 57765, "name": "XML validation", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n"}
{"id": 57766, "name": "Longest increasing subsequence", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n"}
{"id": 57767, "name": "Death Star", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n"}
{"id": 57768, "name": "Total circles area", "VB": "Public c As Variant\nPublic pi As Double\nDim arclists() As Variant\nPublic Enum circles_\n    xc = 0\n    yc\n    rc\nEnd Enum\nPublic Enum arclists_\n    rho\n    x_\n    y_\n    i_\nEnd Enum\nPublic Enum shoelace_axis\n    u = 0\n    v\nEnd Enum\nPrivate Sub give_a_list_of_circles()\n    c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _\n    Array(-1.4944608174, 1.2077959613, 1.1039549836), _\n    Array(0.6110294452, -0.6907087527, 0.9089162485), _\n    Array(0.3844862411, 0.2923344616, 0.2375743054), _\n    Array(-0.249589295, -0.3832854473, 1.0845181219), _\n    Array(1.7813504266, 1.6178237031, 0.8162655711), _\n    Array(-0.1985249206, -0.8343333301, 0.0538864941), _\n    Array(-1.7011985145, -0.1263820964, 0.4776976918), _\n    Array(-0.4319462812, 1.4104420482, 0.7886291537), _\n    Array(0.2178372997, -0.9499557344, 0.0357871187), _\n    Array(-0.6294854565, -1.3078893852, 0.7653357688), _\n    Array(1.7952608455, 0.6281269104, 0.2727652452), _\n    Array(1.4168575317, 1.0683357171, 1.1016025378), _\n    Array(1.4637371396, 0.9463877418, 1.1846214562), _\n    Array(-0.5263668798, 1.7315156631, 1.4428514068), _\n    Array(-1.2197352481, 0.9144146579, 1.0727263474), _\n    Array(-0.1389358881, 0.109280578, 0.7350208828), _\n    Array(1.5293954595, 0.0030278255, 1.2472867347), _\n    Array(-0.5258728625, 1.3782633069, 1.3495508831), _\n    Array(-0.1403562064, 0.2437382535, 1.3804956588), _\n    Array(0.8055826339, -0.0482092025, 0.3327165165), _\n    Array(-0.6311979224, 0.7184578971, 0.2491045282), _\n    Array(1.4685857879, -0.8347049536, 1.3670667538), _\n    Array(-0.6855727502, 1.6465021616, 1.0593087096), _\n    Array(0.0152957411, 0.0638919221, 0.9771215985))\n    pi = WorksheetFunction.pi()\nEnd Sub\nPrivate Function shoelace(s As Collection) As Double\n    \n    \n    \n    \n    \n    \n    Dim t As Double\n    If s.Count > 2 Then\n        s.Add s(1)\n        For i = 1 To s.Count - 1\n            t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v)\n        Next i\n    End If\n    shoelace = t / 2\nEnd Function\nPrivate Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _\n    f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer)\n    \n    \n    If acol.Count = 0 Then Exit Sub \n    Debug.Assert acol.Count Mod 2 = 0\n    Debug.Assert f0 <> f1\n    If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1\n    If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0\n    If f0 < f1 Then\n        \n        \n        \n        If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub \n        i = acol.Count + 1\n        start = 1\n        Do\n            i = i - 1\n        Loop Until f1 > acol(i)(rho)\n        If i Mod 2 = start Then\n            acol.Add Array(f1, u1, v1, j), after:=i\n        End If\n        i = 0\n        Do\n            i = i + 1\n        Loop Until f0 < acol(i)(rho)\n        If i Mod 2 = 1 - start Then\n            acol.Add Array(f0, u0, v0, j), before:=i\n            i = i + 1\n        End If\n        Do While acol(i)(rho) < f1\n            acol.Remove i\n            If i > acol.Count Then Exit Do\n        Loop\n    Else\n        start = 1\n        If f0 > acol(1)(rho) Then\n            i = acol.Count + 1\n            Do\n                i = i - 1\n            Loop While f0 < acol(i)(0)\n            If f0 = pi Then\n                acol.Add Array(f0, u0, v0, j), before:=i\n            Else\n                If i Mod 2 = start Then\n                    acol.Add Array(f0, u0, v0, j), after:=i\n                End If\n            End If\n        End If\n        If f1 <= acol(acol.Count)(rho) Then\n            i = 0\n            Do\n                i = i + 1\n            Loop While f1 > acol(i)(rho)\n            If f1 + pi < 5E-16 Then\n                acol.Add Array(f1, u1, v1, j), after:=i\n            Else\n                If i Mod 2 = 1 - start Then\n                    acol.Add Array(f1, u1, v1, j), before:=i\n                End If\n            End If\n        End If\n        Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1\n            acol.Remove acol.Count\n            If acol.Count = 0 Then Exit Do\n        Loop\n        If acol.Count > 0 Then\n            Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this)\n                acol.Remove 1\n                If acol.Count = 0 Then Exit Do\n            Loop\n        End If\n    End If\nEnd Sub\nPrivate Sub circle_cross()\n    ReDim arclists(LBound(c) To UBound(c))\n    Dim alpha As Double, beta As Double\n    Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double\n    Dim i As Integer, j As Integer\n    For i = LBound(c) To UBound(c)\n        Dim arccol As New Collection\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i)\n        arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1)\n        For j = LBound(c) To UBound(c)\n            If i <> j Then\n                x0 = c(i)(xc)\n                y0 = c(i)(yc)\n                r0 = c(i)(rc)\n                x1 = c(j)(xc)\n                y1 = c(j)(yc)\n                r1 = c(j)(rc)\n                d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2)\n                \n                If d >= r0 + r1 Or d <= Abs(r0 - r1) Then\n                    \n                Else\n                    a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d)\n                    h = Sqr(r0 ^ 2 - a ^ 2)\n                    x2 = x0 + a * (x1 - x0) / d\n                    y2 = y0 + a * (y1 - y0) / d\n                    x3 = x2 + h * (y1 - y0) / d\n                    y3 = y2 - h * (x1 - x0) / d\n                    alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0)\n                    x4 = x2 - h * (y1 - y0) / d\n                    y4 = y2 + h * (x1 - x0) / d\n                    beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0)\n                    \n                    \n                    \n                    \n                    arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j\n                End If\n            End If\n        Next j\n        Set arclists(i) = arccol\n        Set arccol = Nothing\n    Next i\nEnd Sub\nPrivate Sub make_path()\n    Dim pathcol As New Collection, arcsum As Double\n    i0 = UBound(arclists)\n    finished = False\n    Do While True\n        arcsum = 0\n        Do While arclists(i0).Count = 0\n            i0 = i0 - 1\n        Loop\n        j0 = arclists(i0).Count\n        next_i = i0\n        next_j = j0\n        Do While True\n            x = arclists(next_i)(next_j)(x_)\n            y = arclists(next_i)(next_j)(y_)\n            pathcol.Add Array(x, y)\n            prev_i = next_i\n            prev_j = next_j\n            If arclists(next_i)(next_j - 1)(i_) = next_i Then\n                \n                next_j = arclists(next_i).Count - 1\n                If next_j = 1 Then Exit Do \n            Else\n                next_j = next_j - 1\n            End If\n            \n            r = c(next_i)(rc)\n            a1 = arclists(next_i)(prev_j)(rho)\n            a2 = arclists(next_i)(next_j)(rho)\n            If a1 > a2 Then\n                alpha = a1 - a2\n            Else\n                alpha = 2 * pi - a2 + a1\n            End If\n            arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2\n            \n            next_i = arclists(next_i)(next_j)(i_)\n            next_j = arclists(next_i).Count\n            If next_j = 0 Then Exit Do \n            Do While arclists(next_i)(next_j)(i_) <> prev_i\n                \n                next_j = next_j - 1\n            Loop\n            If next_i = i0 And next_j = j0 Then\n                finished = True\n                Exit Do\n            End If\n        Loop\n        If finished Then Exit Do\n        i0 = i0 - 1\n        Set pathcol = Nothing\n    Loop\n    Debug.Print shoelace(pathcol) + arcsum\nEnd Sub\nPublic Sub total_circles()\n    give_a_list_of_circles\n    circle_cross\n    make_path\nEnd Sub\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 57769, "name": "Total circles area", "VB": "Public c As Variant\nPublic pi As Double\nDim arclists() As Variant\nPublic Enum circles_\n    xc = 0\n    yc\n    rc\nEnd Enum\nPublic Enum arclists_\n    rho\n    x_\n    y_\n    i_\nEnd Enum\nPublic Enum shoelace_axis\n    u = 0\n    v\nEnd Enum\nPrivate Sub give_a_list_of_circles()\n    c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _\n    Array(-1.4944608174, 1.2077959613, 1.1039549836), _\n    Array(0.6110294452, -0.6907087527, 0.9089162485), _\n    Array(0.3844862411, 0.2923344616, 0.2375743054), _\n    Array(-0.249589295, -0.3832854473, 1.0845181219), _\n    Array(1.7813504266, 1.6178237031, 0.8162655711), _\n    Array(-0.1985249206, -0.8343333301, 0.0538864941), _\n    Array(-1.7011985145, -0.1263820964, 0.4776976918), _\n    Array(-0.4319462812, 1.4104420482, 0.7886291537), _\n    Array(0.2178372997, -0.9499557344, 0.0357871187), _\n    Array(-0.6294854565, -1.3078893852, 0.7653357688), _\n    Array(1.7952608455, 0.6281269104, 0.2727652452), _\n    Array(1.4168575317, 1.0683357171, 1.1016025378), _\n    Array(1.4637371396, 0.9463877418, 1.1846214562), _\n    Array(-0.5263668798, 1.7315156631, 1.4428514068), _\n    Array(-1.2197352481, 0.9144146579, 1.0727263474), _\n    Array(-0.1389358881, 0.109280578, 0.7350208828), _\n    Array(1.5293954595, 0.0030278255, 1.2472867347), _\n    Array(-0.5258728625, 1.3782633069, 1.3495508831), _\n    Array(-0.1403562064, 0.2437382535, 1.3804956588), _\n    Array(0.8055826339, -0.0482092025, 0.3327165165), _\n    Array(-0.6311979224, 0.7184578971, 0.2491045282), _\n    Array(1.4685857879, -0.8347049536, 1.3670667538), _\n    Array(-0.6855727502, 1.6465021616, 1.0593087096), _\n    Array(0.0152957411, 0.0638919221, 0.9771215985))\n    pi = WorksheetFunction.pi()\nEnd Sub\nPrivate Function shoelace(s As Collection) As Double\n    \n    \n    \n    \n    \n    \n    Dim t As Double\n    If s.Count > 2 Then\n        s.Add s(1)\n        For i = 1 To s.Count - 1\n            t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v)\n        Next i\n    End If\n    shoelace = t / 2\nEnd Function\nPrivate Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _\n    f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer)\n    \n    \n    If acol.Count = 0 Then Exit Sub \n    Debug.Assert acol.Count Mod 2 = 0\n    Debug.Assert f0 <> f1\n    If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1\n    If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0\n    If f0 < f1 Then\n        \n        \n        \n        If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub \n        i = acol.Count + 1\n        start = 1\n        Do\n            i = i - 1\n        Loop Until f1 > acol(i)(rho)\n        If i Mod 2 = start Then\n            acol.Add Array(f1, u1, v1, j), after:=i\n        End If\n        i = 0\n        Do\n            i = i + 1\n        Loop Until f0 < acol(i)(rho)\n        If i Mod 2 = 1 - start Then\n            acol.Add Array(f0, u0, v0, j), before:=i\n            i = i + 1\n        End If\n        Do While acol(i)(rho) < f1\n            acol.Remove i\n            If i > acol.Count Then Exit Do\n        Loop\n    Else\n        start = 1\n        If f0 > acol(1)(rho) Then\n            i = acol.Count + 1\n            Do\n                i = i - 1\n            Loop While f0 < acol(i)(0)\n            If f0 = pi Then\n                acol.Add Array(f0, u0, v0, j), before:=i\n            Else\n                If i Mod 2 = start Then\n                    acol.Add Array(f0, u0, v0, j), after:=i\n                End If\n            End If\n        End If\n        If f1 <= acol(acol.Count)(rho) Then\n            i = 0\n            Do\n                i = i + 1\n            Loop While f1 > acol(i)(rho)\n            If f1 + pi < 5E-16 Then\n                acol.Add Array(f1, u1, v1, j), after:=i\n            Else\n                If i Mod 2 = 1 - start Then\n                    acol.Add Array(f1, u1, v1, j), before:=i\n                End If\n            End If\n        End If\n        Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1\n            acol.Remove acol.Count\n            If acol.Count = 0 Then Exit Do\n        Loop\n        If acol.Count > 0 Then\n            Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this)\n                acol.Remove 1\n                If acol.Count = 0 Then Exit Do\n            Loop\n        End If\n    End If\nEnd Sub\nPrivate Sub circle_cross()\n    ReDim arclists(LBound(c) To UBound(c))\n    Dim alpha As Double, beta As Double\n    Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double\n    Dim i As Integer, j As Integer\n    For i = LBound(c) To UBound(c)\n        Dim arccol As New Collection\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i)\n        arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1)\n        For j = LBound(c) To UBound(c)\n            If i <> j Then\n                x0 = c(i)(xc)\n                y0 = c(i)(yc)\n                r0 = c(i)(rc)\n                x1 = c(j)(xc)\n                y1 = c(j)(yc)\n                r1 = c(j)(rc)\n                d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2)\n                \n                If d >= r0 + r1 Or d <= Abs(r0 - r1) Then\n                    \n                Else\n                    a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d)\n                    h = Sqr(r0 ^ 2 - a ^ 2)\n                    x2 = x0 + a * (x1 - x0) / d\n                    y2 = y0 + a * (y1 - y0) / d\n                    x3 = x2 + h * (y1 - y0) / d\n                    y3 = y2 - h * (x1 - x0) / d\n                    alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0)\n                    x4 = x2 - h * (y1 - y0) / d\n                    y4 = y2 + h * (x1 - x0) / d\n                    beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0)\n                    \n                    \n                    \n                    \n                    arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j\n                End If\n            End If\n        Next j\n        Set arclists(i) = arccol\n        Set arccol = Nothing\n    Next i\nEnd Sub\nPrivate Sub make_path()\n    Dim pathcol As New Collection, arcsum As Double\n    i0 = UBound(arclists)\n    finished = False\n    Do While True\n        arcsum = 0\n        Do While arclists(i0).Count = 0\n            i0 = i0 - 1\n        Loop\n        j0 = arclists(i0).Count\n        next_i = i0\n        next_j = j0\n        Do While True\n            x = arclists(next_i)(next_j)(x_)\n            y = arclists(next_i)(next_j)(y_)\n            pathcol.Add Array(x, y)\n            prev_i = next_i\n            prev_j = next_j\n            If arclists(next_i)(next_j - 1)(i_) = next_i Then\n                \n                next_j = arclists(next_i).Count - 1\n                If next_j = 1 Then Exit Do \n            Else\n                next_j = next_j - 1\n            End If\n            \n            r = c(next_i)(rc)\n            a1 = arclists(next_i)(prev_j)(rho)\n            a2 = arclists(next_i)(next_j)(rho)\n            If a1 > a2 Then\n                alpha = a1 - a2\n            Else\n                alpha = 2 * pi - a2 + a1\n            End If\n            arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2\n            \n            next_i = arclists(next_i)(next_j)(i_)\n            next_j = arclists(next_i).Count\n            If next_j = 0 Then Exit Do \n            Do While arclists(next_i)(next_j)(i_) <> prev_i\n                \n                next_j = next_j - 1\n            Loop\n            If next_i = i0 And next_j = j0 Then\n                finished = True\n                Exit Do\n            End If\n        Loop\n        If finished Then Exit Do\n        i0 = i0 - 1\n        Set pathcol = Nothing\n    Loop\n    Debug.Print shoelace(pathcol) + arcsum\nEnd Sub\nPublic Sub total_circles()\n    give_a_list_of_circles\n    circle_cross\n    make_path\nEnd Sub\n", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n"}
{"id": 57770, "name": "Verify distribution uniformity_Chi-squared test", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n"}
{"id": 57771, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n"}
{"id": 57772, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 57773, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n"}
{"id": 57774, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n"}
{"id": 57775, "name": "One of n lines in a file", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n"}
{"id": 57776, "name": "Spelling of ordinal numbers", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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"}
{"id": 57777, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n"}
{"id": 57778, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n"}
{"id": 57779, "name": "Repeat", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n"}
{"id": 57780, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n"}
{"id": 57781, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n"}
{"id": 57782, "name": "Hello world_Web server", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n"}
{"id": 57783, "name": "Own digits power sum", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\n\n\n\nModule OwnDigitsPowerSum\n\n    Public Sub Main\n\n        \n        Dim used(9) As Integer\n        Dim check(9) As Integer\n        Dim power(9, 9) As Long\n        For i As Integer = 0 To 9\n            check(i) = 0\n        Next i\n        For i As Integer = 1 To 9\n            power(1,  i) = i\n        Next i\n        For j As Integer =  2 To 9\n            For i As Integer = 1 To 9\n                power(j, i) = power(j - 1, i) * i\n            Next i\n        Next j\n        \n        \n        Dim lowestDigit(9) As Integer\n        lowestDigit(1) = -1\n        lowestDigit(2) = -1\n        Dim p10 As Long = 100\n        For i As Integer = 3 To 9\n            For p As Integer = 2 To 9\n                Dim np As Long = power(i, p) * i\n                If Not ( np < p10) Then Exit For\n                lowestDigit(i) = p\n            Next p\n            p10 *= 10\n        Next i\n        \n        Dim maxZeros(9, 9) As Integer\n        For i As Integer = 1 To 9\n            For j As Integer = 1 To 9\n                maxZeros(i, j) = 0\n            Next j\n        Next i\n        p10 = 1000\n        For w As Integer = 3 To 9\n            For d As Integer = lowestDigit(w) To 9\n                Dim nz As Integer = 9\n                Do\n                    If nz < 0 Then\n                        Exit Do\n                    Else\n                        Dim np As Long = power(w, d) * nz\n                        IF Not ( np > p10) Then Exit Do\n                    End If\n                    nz -= 1\n                Loop\n                maxZeros(w, d) = If(nz > w, 0, w - nz)\n            Next d\n            p10 *= 10\n        Next w\n        \n        \n        Dim numbers(100) As Long     \n        Dim nCount As Integer = 0    \n        Dim tryCount As Integer = 0  \n        Dim digits(9) As Integer     \n        For d As Integer = 1 To 9\n             digits(d) = 9\n        Next d\n        For d As Integer = 0 To 8\n            used(d) = 0\n        Next d\n        used(9) = 9\n        Dim width As Integer = 9     \n        Dim last As Integer = width  \n        p10 = 100000000              \n        Do While width > 2\n            tryCount += 1\n            Dim dps As Long = 0      \n            check(0) = used(0)\n            For i As Integer = 1 To 9\n                check(i) = used(i)\n                If used(i) <> 0 Then\n                    dps += used(i) * power(width, i)\n                End If\n            Next i\n            \n            Dim n As Long = dps\n            Do\n                check(CInt(n Mod 10)) -= 1 \n                n \\= 10\n            Loop Until n <= 0\n            Dim reduceWidth As Boolean = dps <= p10\n            If Not reduceWidth Then\n                \n                \n                \n                Dim zCount As Integer = 0\n                For i As Integer = 0 To 9\n                    If check(i) <> 0 Then Exit For\n                    zCount+= 1\n                Next i\n                If zCount = 10 Then\n                    nCount += 1\n                    numbers(nCount) = dps\n                End If\n                \n                used(digits(last)) -= 1\n                digits(last) -= 1\n                If digits(last) = 0 Then\n                    \n                    If used(0) >= maxZeros(width, digits(1)) Then\n                        \n                        digits(last) = -1\n                    End If\n                End If\n                If digits(last) >= 0 Then\n                    \n                    used(digits(last)) += 1\n                Else\n                    \n                    Dim prev As Integer = last\n                    Do\n                        prev -= 1\n                        If prev < 1 Then\n                            Exit Do\n                        Else\n                            used(digits(prev)) -= 1\n                            digits(prev) -= 1\n                            IF digits(prev) >= 0 Then Exit Do\n                        End If\n                    Loop\n                    If prev > 0 Then\n                        \n                        If prev = 1 Then\n                            If digits(1) <= lowestDigit(width) Then\n                               \n                               prev = 0\n                            End If\n                        End If\n                        If prev <> 0 Then\n                           \n                            used(digits(prev)) += 1\n                            For i As Integer = prev + 1 To width\n                                digits(i) = digits(prev)\n                                used(digits(prev)) += 1\n                            Next i\n                        End If\n                    End If\n                    If prev <= 0 Then\n                        \n                        reduceWidth = True\n                    End If\n                End If\n            End If\n            If reduceWidth Then\n                \n                last -= 1\n                width = last\n                If last > 0 Then\n                    \n                    For d As Integer = 1 To last\n                        digits(d) = 9\n                    Next d\n                    For d As Integer = last + 1 To 9\n                        digits(d) = -1\n                    Next d\n                    For d As Integer = 0 To 8\n                        used(d) = 0\n                    Next d\n                    used(9) = last\n                    p10 \\= 10\n                End If\n            End If\n        Loop\n        \n        Console.Out.WriteLine(\"Own digits power sums for N = 3 to 9 inclusive:\")\n        For i As Integer = nCount To 1 Step -1\n            Console.Out.WriteLine(numbers(i))\n        Next i\n        Console.Out.WriteLine(\"Considered \" & tryCount & \" digit combinations\")\n\n    End Sub\n\n\nEnd Module\n", "Python": "\n\ndef isowndigitspowersum(integer):\n    \n    digits = [int(c) for c in str(integer)]\n    exponent = len(digits)\n    return sum(x ** exponent for x in digits) == integer\n\nprint(\"Own digits power sums for N = 3 to 9 inclusive:\")\nfor i in range(100, 1000000000):\n    if isowndigitspowersum(i):\n        print(i)\n"}
{"id": 57784, "name": "Klarner-Rado sequence", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n"}
{"id": 57785, "name": "Klarner-Rado sequence", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule KlarnerRado\n\n    Private Const bitsWidth As Integer = 31\n\n    Private bitMask() As Integer = _\n        New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _\n                     , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _\n                     , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _\n                     , 16777216, 33554432, 67108864, 134217728, 268435456 _\n                     , 536870912, 1073741824 _\n                     }\n\n    Private Const maxElement As Integer = 1100000000\n\n\n    Private Function BitSet(bit As Integer, v As Integer) As Boolean\n        Return (v And bitMask(bit - 1)) <> 0\n    End Function\n\n    Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer\n        Return b Or bitMask(bit - 1)\n    End Function\n\n    Public Sub Main\n        Dim  kr(maxElement \\ bitsWidth) As Integer\n\n        For i As Integer = 0 To kr.Count() - 1\n            kr(i) = 0\n        Next  i\n\n        Dim krCount As Integer =  0    \n        Dim n21 As Integer = 3         \n        Dim n31 As Integer = 4         \n        Dim p10 As Integer = 1000      \n        Dim iBit As Integer = 0        \n        Dim iOverBw As Integer = 0     \n        \n        Dim p2Bit As Integer = 1       \n        Dim p2OverBw As Integer = 0    \n        \n        Dim p3Bit As Integer = 1       \n        Dim p3OverBw As Integer = 0    \n\n        kr(0) = SetBit(1, kr(0))\n        Dim kri As Boolean = True\n        Dim lastI As Integer = 0\n        For i As Integer = 1 To  maxElement\n            iBit += 1\n            If iBit > bitsWidth Then\n                iBit = 1\n                iOverBw += 1\n            End If\n            If i = n21 Then            \n                If BitSet(p2Bit, kr(p2OverBw)) Then\n                    kri = True\n                End If\n                p2Bit += 1\n                If p2Bit > bitsWidth Then\n                    p2Bit = 1\n                    p2OverBw += 1\n                End If\n                n21 += 2\n            End If\n            If i = n31 Then            \n                If BitSet(p3Bit, kr(p3OverBw)) Then\n                    kri = True\n                End If\n                p3Bit += 1\n                If p3Bit > bitsWidth Then\n                    p3Bit = 1\n                    p3OverBw += 1\n                End If\n                n31 += 3\n            End If\n            If kri Then\n                lastI = i\n                kr(iOverBw) = SetBit(iBit, kr(iOverBw))\n                krCount += 1\n                If krCount <= 100 Then\n                    Console.Out.Write(\" \" & i.ToString().PadLeft(3))\n                    If krCount Mod 20 = 0 Then\n                        Console.Out.WriteLine()\n                    End If\n                ElseIf krCount = p10 Then\n                    Console.Out.WriteLine(\"Element \" & p10.ToString().PadLeft(10) & \" is \" & i.ToString().PadLeft(10))\n                    p10 *= 10\n                End If\n                kri = False\n            End If\n        Next  i\n        Console.Out.WriteLine(\"Element \" & krCount.ToString().PadLeft(10) & \" is \" & lastI.ToString().PadLeft(10))\n\n    End Sub\n\nEnd Module\n", "Python": "def KlarnerRado(N):\n    K = [1]\n    for i in range(N):\n        j = K[i]\n        firstadd, secondadd = 2 * j + 1, 3 * j + 1\n        if firstadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < firstadd < K[pos + 1]:\n                    K.insert(pos + 1, firstadd)\n                    break\n        elif firstadd > K[-1]:\n            K.append(firstadd)\n        if secondadd < K[-1]:\n            for pos in range(len(K)-1, 1, -1):\n                if K[pos] < secondadd < K[pos + 1]:\n                    K.insert(pos + 1, secondadd)\n                    break\n        elif secondadd > K[-1]:\n            K.append(secondadd)\n\n    return K\n\nkr1m = KlarnerRado(100_000)\n\nprint('First 100 Klarner-Rado sequence numbers:')\nfor idx, v in enumerate(kr1m[:100]):\n    print(f'{v: 4}', end='\\n' if (idx + 1) % 20 == 0 else '')\nfor n in [1000, 10_000, 100_000]:\n    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')\n"}
{"id": 57786, "name": "Sorting algorithms_Pancake sort", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n"}
{"id": 57787, "name": "Chemical calculator", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n"}
{"id": 57788, "name": "Pythagorean quadruples", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n"}
{"id": 57789, "name": "Long stairs", "VB": "Option Explicit\nRandomize Timer\n\nFunction pad(s,n) \n  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If \nEnd Function\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\nFunction Rounds(maxsecs,wiz,a)\n  Dim mystep,maxstep,toend,j,i,x,d \n  If IsArray(a) Then d=True: print \"seconds behind pending\"   \n  maxstep=100\n  For j=1 To maxsecs\n    For i=1 To wiz\n      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1\n      maxstep=maxstep+1  \n    Next \n    mystep=mystep+1 \n    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function\n    If d Then\n      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)\n    End If     \n  Next \n  Rounds=Array(maxsecs,maxstep)\nEnd Function\n\n\nDim n,r,a,sumt,sums,ntests,t,maxsecs\nntests=10000\nmaxsecs=7000\nt=timer\na=Array(600,609)\nFor n=1 To ntests\n  r=Rounds(maxsecs,5,a)\n  If r(0)<>maxsecs Then \n    sumt=sumt+r(0)\n    sums=sums+r(1)\n  End if  \n  a=\"\"\nNext  \n\nprint vbcrlf & \"Done \" & ntests & \" tests in \" & Timer-t & \" seconds\" \nprint \"escaped in \" & sumt/ntests  & \" seconds with \" & sums/ntests & \" stairs\"\n", "Python": "\n\nfrom numpy import mean\nfrom random import sample\n\ndef gen_long_stairs(start_step, start_length, climber_steps, add_steps):\n    secs, behind, total = 0, start_step, start_length\n    while True:\n        behind += climber_steps\n        behind += sum([behind > n for n in sample(range(total), add_steps)])\n        total += add_steps\n        secs += 1\n        yield (secs, behind, total)\n        \n\nls = gen_long_stairs(1, 100, 1, 5)\n\nprint(\"Seconds  Behind  Ahead\\n----------------------\")\nwhile True:\n    secs, pos, len = next(ls)\n    if 600 <= secs < 610:\n        print(secs, \"     \", pos, \"   \", len - pos)\n    elif secs == 610:\n        break\n\nprint(\"\\nTen thousand trials to top:\")\ntimes, heights = [], []\nfor trial in range(10_000):\n    trialstairs = gen_long_stairs(1, 100, 1, 5)\n    while True:\n        sec, step, height = next(trialstairs)\n        if step >= height:\n            times.append(sec)\n            heights.append(height)\n            break\n\nprint(\"Mean time:\", mean(times), \"secs. Mean height:\", mean(heights))\n"}
{"id": 57790, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 57791, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n"}
{"id": 57792, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n"}
{"id": 57793, "name": "Zebra puzzle", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n"}
{"id": 57794, "name": "Rosetta Code_Find unimplemented tasks", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n"}
{"id": 57795, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 57796, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n"}
{"id": 57797, "name": "Practical numbers", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n"}
{"id": 57798, "name": "Literals_Floating point", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n"}
{"id": 57799, "name": "Word search", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n"}
{"id": 57800, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 57801, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n"}
{"id": 57802, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 57803, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n"}
{"id": 57804, "name": "Long year", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 57805, "name": "Zumkeller numbers", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n"}
{"id": 57806, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 57807, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n"}
{"id": 57808, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 57809, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n"}
{"id": 57810, "name": "Dijkstra's algorithm", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n"}
{"id": 57811, "name": "Geometric algebra", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n"}
{"id": 57812, "name": "Associative array_Iteration", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n"}
{"id": 57813, "name": "Define a primitive data type", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n"}
{"id": 57814, "name": "Hash join", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n"}
{"id": 57815, "name": "Sierpinski square 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n"}
{"id": 57816, "name": "Find words whose first and last three letters are equal", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\nset d= createobject(\"Scripting.Dictionary\")\nfor each aa in a\n  x=trim(aa)\n  l=len(x)\n  if l>5 then\n   d.removeall\n   for i=1 to 3\n     m=mid(x,i,1)\n     if not d.exists(m) then d.add m,null\n   next\n   res=true\n   for i=l-2 to l\n     m=mid(x,i,1)\n     if not d.exists(m) then \n       res=false:exit for \n      else\n        d.remove(m)\n      end if        \n   next \n   if res then \n     wscript.stdout.write left(x & space(15),15)\n     if left(x,3)=right(x,3) then  wscript.stdout.write \"*\"\n     wscript.stdout.writeline\n    end if \n  end if\nnext\n", "Python": "import urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>5 and word[:3].lower()==word[-3:].lower():\n        print(word)\n"}
{"id": 57817, "name": "Word break problem", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 57818, "name": "Latin Squares in reduced form", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n"}
{"id": 57819, "name": "UPC", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 57820, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 57821, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n"}
{"id": 57822, "name": "Closest-pair problem", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 57823, "name": "Closest-pair problem", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n"}
{"id": 57824, "name": "Address of a variable", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n"}
{"id": 57825, "name": "Inheritance_Single", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n"}
{"id": 57826, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n"}
{"id": 57827, "name": "Color wheel", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n"}
{"id": 57828, "name": "Rare numbers", "VB": "Imports System.Console\nImports DT = System.DateTime\nImports Lsb = System.Collections.Generic.List(Of SByte)\nImports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte))\nImports UI = System.UInt64\n\nModule Module1\n    Const MxD As SByte = 15\n\n    Public Structure term\n        Public coeff As UI : Public a, b As SByte\n        Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer)\n            coeff = c : a = CSByte(a_) : b = CSByte(b_)\n        End Sub\n    End Structure\n\n    Dim nd, nd2, count As Integer, digs, cnd, di As Integer()\n    Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term))\n    Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst)\n    Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI\n\n    \n    Function ToDif() As UI\n        Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i)\n        Next : Return r\n    End Function\n\n    \n    Function ToSum() As UI\n        Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i)\n        Next : Return Dif + (r << 1)\n    End Function\n\n    \n    Function IsSquare(nmbr As UI) As Boolean\n        If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _\n            Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False\n    End Function\n\n    \n    Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb\n        Dim res As Lsb = New Lsb()\n        For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res\n    End Function\n\n    \n    Sub Fnpr(ByVal lev As Integer)\n        If lev = dis.Count Then\n            digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1)\n            Dim le As Integer = di.Length, i As Integer = 1\n            If odd Then le -= 1 : digs(nd >> 1) = di(le)\n            For Each d As SByte In di.Skip(1).Take(le - 1)\n                digs(ixs(i)(0)) = dmd(cnd(i))(d)(0)\n                digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next\n            If Not IsSquare(ToSum()) Then Return\n            res.Add(ToDif()) : count += 1\n            WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\", (DT.Now - st).TotalMilliseconds, count, res.Last())\n        Else\n            For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next\n        End If\n    End Sub\n\n    \n    Sub Fnmr(ByVal list As Lst, ByVal lev As Integer)\n        If lev = list.Count Then\n            Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2)\n                If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _\n                              Else Dif += t.coeff * CULng(cnd(i))\n                i += 1 : Next\n            If Dif <= 0 OrElse Not IsSquare(Dif) Then Return\n            dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)}\n            For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next\n            If odd Then dis.Add(il)\n            di = New Integer(dis.Count - 1) {} : Fnpr(0)\n        Else\n            For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next\n        End If\n    End Sub\n\n    Sub init()\n        Dim pow As UI = 1\n        \n        tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD)\n            Dim terms As List(Of term) = New List(Of term)()\n            pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1\n            Dim i1 As Integer = 0, i2 As Integer = r - 1\n            While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2))\n                p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While\n            tLst.Add(terms) : Next\n        \n        fml = New Dictionary(Of Integer, Lst)() From {\n            {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}},\n            {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}},\n            {4, New Lst() From {New Lsb() From {4, 0}}},\n            {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}}\n        \n        dmd = New Dictionary(Of Integer, Lst)()\n        For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i\n            While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _\n                Else dmd(d) = New Lst From {New Lsb From {i, j}}\n                j += 1 : d -= 1 : End While : Next\n        dl = Seq(-9, 9)    \n        zl = Seq(0, 0)     \n        el = Seq(-8, 8, 2) \n        ol = Seq(-9, 9, 2) \n        il = Seq(0, 9)\n        lists = New List(Of Lst)()\n        For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next\n    End Sub\n\n    Sub Main(ByVal args As String())\n        init() : res = New List(Of UI)() : st = DT.Now : count = 0\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Rare Numbers\")\n        nd = 2 : nd2 = 0 : odd = False : While nd <= MxD\n            digs = New Integer(nd - 1) {} : If nd = 4 Then\n                lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol)\n            ElseIf tLst(nd2).Count > lists(0).Count Then\n                For Each list As Lst In lists : list.Add(dl) : Next : End If\n            ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next\n            For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds)\n            nd += 1 : nd2 += 1 : odd = Not odd : End While\n        res.Sort() : WriteLine(vbLf & \"The {0} rare numbers with up to {1} digits are:\", res.Count, MxD)\n        count = 0 : For Each rare In res : count += 1 : WriteLine(\"{0,2}:{1,27:n0}\", count, rare) : Next\n        If System.Diagnostics.Debugger.IsAttached Then ReadKey()\n    End Sub\nEnd Module\n", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n"}
{"id": 57829, "name": "Find words which contain the most consonants", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n"}
{"id": 57830, "name": "Find words which contain the most consonants", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n"}
{"id": 57831, "name": "Minesweeper game", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n"}
{"id": 57832, "name": "Primes with digits in nondecreasing order", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 57833, "name": "Primes with digits in nondecreasing order", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 57834, "name": "Reflection_List properties", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n"}
{"id": 57835, "name": "Align columns", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n"}
{"id": 57836, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 57837, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 57838, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n"}
{"id": 57839, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 57840, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n"}
{"id": 57841, "name": "Commatizing numbers", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n"}
{"id": 57842, "name": "Arithmetic coding_As a generalized change of radix", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n"}
{"id": 57843, "name": "Kosaraju", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n"}
{"id": 57844, "name": "Pentomino tiling", "VB": "Module Module1\n\n    Dim symbols As Char() = \"XYPFTVNLUZWI█\".ToCharArray(),\n        nRows As Integer = 8, nCols As Integer = 8,\n        target As Integer = 12, blank As Integer = 12,\n        grid As Integer()() = New Integer(nRows - 1)() {},\n        placed As Boolean() = New Boolean(target - 1) {},\n        pens As List(Of List(Of Integer())), rand As Random,\n        seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}\n\n    Sub Main()\n        Unpack(seeds) : rand = New Random() : ShuffleShapes(2)\n        For r As Integer = 0 To nRows - 1\n            grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next\n        For i As Integer = 0 To 3\n            Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)\n            Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank\n        Next\n        If Solve(0, 0) Then\n            PrintResult()\n        Else\n            Console.WriteLine(\"no solution for this configuration:\") : PrintResult()\n        End If\n        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\n    Sub ShuffleShapes(count As Integer) \n        For i As Integer = 0 To count : For j = 0 To pens.Count - 1\n                Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j\n                Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp\n                Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch\n            Next : Next\n    End Sub\n\n    Sub PrintResult() \n        For Each r As Integer() In grid : For Each i As Integer In r\n                Console.Write(\"{0} \", If(i < 0, \".\", symbols(i)))\n            Next : Console.WriteLine() : Next\n    End Sub\n\n    \n    Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean\n        If numPlaced = target Then Return True\n        Dim row As Integer = pos \\ nCols, col As Integer = pos Mod nCols\n        If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)\n        For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then\n                For Each orientation As Integer() In pens(i)\n                    If Not TPO(orientation, row, col, i) Then Continue For\n                    placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True\n                    RmvO(orientation, row, col) : placed(i) = False\n                Next : End If : Next : Return False\n    End Function\n\n    \n    Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)\n        grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = -1 : Next\n    End Sub\n\n    \n    Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,\n                 ByVal sIdx As Integer) As Boolean\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)\n            If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse\n                grid(y)(x) <> -1 Then Return False\n        Next : grid(row)(col) = sIdx\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = sIdx\n        Next : Return True\n    End Function\n\n    \n    \n    \n    \n\n    Sub Unpack(sv As Integer()) \n        pens = New List(Of List(Of Integer())) : For Each item In sv\n            Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),\n                fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7\n                If i = 4 Then Mir(exi) Else Rot(exi)\n                fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))\n            Next : pens.Add(Gen) : Next\n    End Sub\n\n    \n    Function Expand(i As Integer) As List(Of Integer)\n        Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next\n    End Function\n\n    \n    Function ToP(p As List(Of Integer)) As Integer()\n        Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)\n            tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next\n        tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next\n        Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)\n            Dim adj = If((item And 7) > 4, 8, 0)\n            res.Add((adj + item) \\ 8) : res.Add((item And 7) - adj)\n        Next : Return res.ToArray()\n    End Function\n\n    \n    Function TheSame(a As Integer(), b As Integer()) As Boolean\n        For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False\n        Next : Return True\n    End Function\n\n    Sub Rot(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next\n    End Sub\n\n    Sub Mir(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next\n    End Sub\n\nEnd Module\n", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n"}
{"id": 57845, "name": "Variables", "VB": "Dim variable As datatype\nDim var1,var2,... As datatype\n", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n"}
{"id": 57846, "name": "Make a backup file", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 57847, "name": "Make a backup file", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n"}
{"id": 57848, "name": "Check Machin-like formulas", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n"}
{"id": 57849, "name": "Check Machin-like formulas", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n"}
{"id": 57850, "name": "Solve triangle solitare puzzle", "VB": "Imports System, Microsoft.VisualBasic.DateAndTime\n\nPublic Module Module1\n    Const n As Integer = 5 \n    Dim Board As String \n    Dim Starting As Integer = 1 \n    Dim Target As Integer = 13 \n    Dim Moves As Integer() \n    Dim bi() As Integer \n    Dim ib() As Integer \n    Dim nl As Char = Convert.ToChar(10) \n\n    \n    Public Function Dou(s As String) As String\n        Dou = \"\" : Dim b As Boolean = True\n        For Each ch As Char In s\n            If b Then b = ch <> \" \"\n            If b Then Dou &= ch & \" \" Else Dou = \" \" & Dou\n        Next : Dou = Dou.TrimEnd()\n    End Function\n\n    \n    Public Function Fmt(s As String) As String\n        If s.Length < Board.Length Then Return s\n        Fmt = \"\" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &\n                If(i = n, s.Substring(Board.Length), \"\") & nl\n        Next\n    End Function\n\n    \n    Public Function Triangle(n As Integer) As Integer\n        Return (n * (n + 1)) / 2\n    End Function\n\n    \n    Public Function Init(s As String, pos As Integer) As String\n        Init = s : Mid(Init, pos, 1) = \"0\"\n    End Function\n\n    \n    Public Sub InitIndex()\n        ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0\n        For i As Integer = 0 To ib.Length - 1\n            If i = 0 Then\n                ib(i) = 0 : bi(j) = 0 : j += 1\n            Else\n                If Board(i - 1) = \"1\" Then ib(i) = j : bi(j) = i : j += 1\n            End If\n        Next\n    End Sub\n\n    \n    Public Function solve(brd As String, pegsLeft As Integer) As String\n        If pegsLeft = 1 Then \n            If Target = 0 Then Return \"Completed\" \n            If brd(bi(Target) - 1) = \"1\" Then Return \"Completed\" Else Return \"fail\"\n        End If\n        For i = 1 To Board.Length \n            If brd(i - 1) = \"1\" Then \n                For Each mj In Moves \n                    Dim over As Integer = i + mj \n                    Dim land As Integer = i + 2 * mj \n                    \n                    If land >= 1 AndAlso land <= brd.Length _\n                                AndAlso brd(land - 1) = \"0\" _\n                                AndAlso brd(over - 1) = \"1\" Then\n                        setPegs(brd, \"001\", i, over, land) \n                        \n                        Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)\n                        \n                        If Res.Length <> 4 Then _\n                            Return brd & info(i, over, land) & nl & Res\n                        setPegs(brd, \"110\", i, over, land) \n                    End If\n                Next\n            End If\n        Next\n        Return \"fail\"\n    End Function\n\n    \n    Function info(frm As Integer, over As Integer, dest As Integer) As String\n        Return \"  Peg from \" & ib(frm).ToString() & \" goes to \" & ib(dest).ToString() &\n            \", removing peg at \" & ib(over).ToString()\n    End Function\n\n    \n    Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)\n        Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)\n    End Sub\n\n    \n    Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)\n        x = Math.Max(Math.Min(x, hi), lo)\n    End Sub\n\n    Public Sub Main()\n        Dim t As Integer = Triangle(n) \n        LimitIt(Starting, 1, t) \n        LimitIt(Target, 0, t)\n        Dim stime As Date = Now() \n        Moves = {-n - 1, -n, -1, 1, n, n + 1} \n        Board = New String(\"1\", n * n) \n        For i As Integer = 0 To n - 2 \n            Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(\" \", n - 1 - i)\n        Next\n        InitIndex() \n        Dim B As String = Init(Board, bi(Starting)) \n        Console.WriteLine(Fmt(B & \"  Starting with peg removed from \" & Starting.ToString()))\n        Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)\n        Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & \" ms.\"\n        If res(0).Length = 4 Then\n            If Target = 0 Then\n                Console.WriteLine(\"Unable to find a solution with last peg left anywhere.\")\n            Else\n                Console.WriteLine(\"Unable to find a solution with last peg left at \" &\n                                  Target.ToString() & \".\")\n            End If\n            Console.WriteLine(\"Computation time: \" & ts)\n        Else\n            For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next\n            Console.WriteLine(\"Computation time to first found solution: \" & ts)\n        End If\n        If Diagnostics.Debugger.IsAttached Then Console.ReadLine()\n    End Sub\nEnd Module\n", "Python": "\n\n\ndef DrawBoard(board):\n  peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n  for n in xrange(1,16):\n    peg[n] = '.'\n    if n in board:\n      peg[n] = \"%X\" % n\n  print \"     %s\" % peg[1]\n  print \"    %s %s\" % (peg[2],peg[3])\n  print \"   %s %s %s\" % (peg[4],peg[5],peg[6])\n  print \"  %s %s %s %s\" % (peg[7],peg[8],peg[9],peg[10])\n  print \" %s %s %s %s %s\" % (peg[11],peg[12],peg[13],peg[14],peg[15])\n\n\n\ndef RemovePeg(board,n):\n  board.remove(n)\n\n\ndef AddPeg(board,n):\n  board.append(n)\n\n\ndef IsPeg(board,n):\n  return n in board\n\n\n\nJumpMoves = { 1: [ (2,4),(3,6) ],  \n              2: [ (4,7),(5,9)  ],\n              3: [ (5,8),(6,10) ],\n              4: [ (2,1),(5,6),(7,11),(8,13) ],\n              5: [ (8,12),(9,14) ],\n              6: [ (3,1),(5,4),(9,13),(10,15) ],\n              7: [ (4,2),(8,9)  ],\n              8: [ (5,3),(9,10) ],\n              9: [ (5,2),(8,7)  ],\n             10: [ (9,8) ],\n             11: [ (12,13) ],\n             12: [ (8,5),(13,14) ],\n             13: [ (8,4),(9,6),(12,11),(14,15) ],\n             14: [ (9,5),(13,12)  ],\n             15: [ (10,6),(14,13) ]\n            }\n\nSolution = []\n\n\n\ndef Solve(board):\n  \n  if len(board) == 1:\n    return board \n  \n  for peg in xrange(1,16): \n    if IsPeg(board,peg):\n      movelist = JumpMoves[peg]\n      for over,land in movelist:\n        if IsPeg(board,over) and not IsPeg(board,land):\n          saveboard = board[:] \n          RemovePeg(board,peg)\n          RemovePeg(board,over)\n          AddPeg(board,land) \n\n          Solution.append((peg,over,land))\n\n          board = Solve(board)\n          if len(board) == 1:\n            return board\n        \n          board = saveboard[:] \n          del Solution[-1] \n  return board\n\n\n\n\ndef InitSolve(empty):\n  board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n  RemovePeg(board,empty_start)\n  Solve(board)\n\n\nempty_start = 1\nInitSolve(empty_start)\n\nboard = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nRemovePeg(board,empty_start)\nfor peg,over,land in Solution:\n  RemovePeg(board,peg)\n  RemovePeg(board,over)\n  AddPeg(board,land) \n  DrawBoard(board)\n  print \"Peg %X jumped over %X to land on %X\\n\" % (peg,over,land)\n"}
{"id": 57851, "name": "Twelve statements", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n"}
{"id": 57852, "name": "Suffixation of decimal numbers", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n"}
{"id": 57853, "name": "Suffixation of decimal numbers", "VB": "Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String\n    Dim suffix As String, parts() As String, exponent As String\n    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean\n    flag = False\n    fractiondigits = Val(sfractiondigits)\n    suffixes = \" KMGTPEZYXWVU\"\n    number = Replace(number, \",\", \"\", 1)\n    Dim c As Currency\n    Dim sign As Integer\n    \n    If Left(number, 1) = \"-\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"-\"\n    End If\n    If Left(number, 1) = \"+\" Then\n        number = Right(number, Len(number) - 1)\n        outstring = \"+\"\n    End If\n    \n    parts = Split(number, \"e\")\n    number = parts(0)\n    If UBound(parts) > 0 Then exponent = parts(1)\n    \n    parts = Split(number, \".\")\n    number = parts(0)\n    If UBound(parts) > 0 Then frac = parts(1)\n    If base = \"2\" Then\n        Dim cnumber As Currency\n        cnumber = Val(number)\n        nsuffix = 0\n        Dim dnumber As Double\n        If cnumber > 1023 Then\n            cnumber = cnumber / 1024@\n            nsuffix = nsuffix + 1\n            dnumber = cnumber\n            Do While dnumber > 1023\n                dnumber = dnumber / 1024@ \n                nsuffix = nsuffix + 1\n            Loop\n            number = CStr(dnumber)\n        Else\n            number = CStr(cnumber)\n        End If\n        leadingstring = Int(number)\n        number = Replace(number, \",\", \"\")\n        \n        leading = Len(leadingstring)\n        suffix = Mid(suffixes, nsuffix + 1, 1)\n    Else\n        \n        nsuffix = (Len(number) + Val(exponent) - 1) \\ 3\n        If nsuffix < 13 Then\n            suffix = Mid(suffixes, nsuffix + 1, 1)\n            leading = (Len(number) - 1) Mod 3 + 1\n            leadingstring = Left(number, leading)\n        Else\n            flag = True\n            If nsuffix > 32 Then\n                suffix = \"googol\"\n                leading = Len(number) + Val(exponent) - 99\n                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), \"0\")\n            Else\n                suffix = \"U\"\n                leading = Len(number) + Val(exponent) - 35\n                If Val(exponent) > 36 Then\n                    leadingstring = number & String$(Val(exponent) - 36, \"0\")\n                Else\n                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))\n                End If\n            End If\n        End If\n    End If\n    \n    If fractiondigits > 0 Then\n        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then\n            fraction = Mid(number, leading + 1, fractiondigits - 1) & _\n                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)\n        Else\n            fraction = Mid(number, leading + 1, fractiondigits)\n        End If\n    Else\n        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> \"\" And sfractiondigits <> \",\" Then\n            leadingstring = Mid(number, 1, leading - 1) & _\n                CStr(Val(Mid(number, leading, 1)) + 1)\n        End If\n    End If\n    If flag Then\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = \"\"\n        End If\n    Else\n        If sfractiondigits = \"\" Or sfractiondigits = \",\" Then\n            fraction = Right(number, Len(number) - leading)\n        End If\n    End If\n    outstring = outstring & leadingstring\n    If Len(fraction) > 0 Then\n        outstring = outstring & \".\" & fraction\n    End If\n    If base = \"2\" Then\n        outstring = outstring & suffix & \"i\"\n    Else\n        outstring = outstring & suffix\n    End If\n    suffize = outstring\nEnd Function\nSub program()\n    Dim s(10) As String, t As String, f As String, r As String\n    Dim tt() As String, temp As String\n    s(0) = \"               87,654,321\"\n    s(1) = \"          -998,877,665,544,332,211,000      3\"\n    s(2) = \"          +112,233                          0\"\n    s(3) = \"           16,777,216                       1\"\n    s(4) = \"           456,789,100,000,000              2\"\n    s(5) = \"           456,789,100,000,000              2      10\"\n    s(6) = \"           456,789,100,000,000              5       2\"\n    s(7) = \"           456,789,100,000.000e+00          0      10\"\n    s(8) = \"          +16777216                         ,       2\"\n    s(9) = \"           1.2e101\"\n    For i = 0 To 9\n        ReDim tt(0)\n        t = Trim(s(i))\n        Do\n            temp = t\n            t = Replace(t, \"  \", \" \")\n        Loop Until temp = t\n        tt = Split(t, \" \")\n        If UBound(tt) > 0 Then f = tt(1) Else f = \"\"\n        If UBound(tt) > 1 Then r = tt(2) Else r = \"\"\n        Debug.Print String$(48, \"-\")\n        Debug.Print \"     input number = \"; tt(0)\n        Debug.Print \"    fraction digs = \"; f\n        Debug.Print \"  specified radix = \"; r\n        Debug.Print \"       new number = \"; suffize(tt(0), f, r)\n    Next i\nEnd Sub\n", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n"}
{"id": 57854, "name": "Nested templated data", "VB": "Public Sub test()\n    Dim t(2) As Variant\n    t(0) = [{1,2}]\n    t(1) = [{3,4,1}]\n    t(2) = 5\n    p = [{\"Payload#0\",\"Payload#1\",\"Payload#2\",\"Payload#3\",\"Payload#4\",\"Payload#5\",\"Payload#6\"}]\n    Dim q(6) As Boolean\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            For j = LBound(t(i)) To UBound(t(i))\n                q(t(i)(j)) = True\n                t(i)(j) = p(t(i)(j) + 1)\n            Next j\n        Else\n            q(t(i)) = True\n            t(i) = p(t(i) + 1)\n        End If\n    Next i\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            Debug.Print Join(t(i), \", \")\n        Else\n            Debug.Print t(i)\n        End If\n    Next i\n    For i = LBound(q) To UBound(q)\n        If Not q(i) Then Debug.Print p(i + 1); \" is not used\"\n    Next i\nEnd Sub\n", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n"}
{"id": 57855, "name": "Solve hanging lantern problem", "VB": "Dim n As Integer, c As Integer\nDim a() As Integer\n\nPrivate Sub Command1_Click()\n    Dim res As Integer\n    If c < n Then Label3.Caption = \"Please input completely.\": Exit Sub\n    res = getLantern(a())\n    Label3.Caption = \"Result：\" + Str(res)\nEnd Sub\n\nPrivate Sub Text1_Change()\n    If Val(Text1.Text) <> 0 Then\n        n = Val(Text1.Text)\n        ReDim a(1 To n) As Integer\n    End If\nEnd Sub\n\n\nPrivate Sub Text2_KeyPress(KeyAscii As Integer)\n    If KeyAscii = Asc(vbCr) Then\n        If Val(Text2.Text) = 0 Then Exit Sub\n        c = c + 1\n        If c > n Then Exit Sub\n        a(c) = Val(Text2.Text)\n        List1.AddItem Str(a(c))\n        Text2.Text = \"\"\n    End If\nEnd Sub\n\nFunction getLantern(arr() As Integer) As Integer\n    Dim res As Integer, i As Integer\n    For i = 1 To n\n        If arr(i) <> 0 Then\n            arr(i) = arr(i) - 1\n            res = res + getLantern(arr())\n            arr(i) = arr(i) + 1\n        End If\n    Next i\n    If res = 0 Then res = 1\n    getLantern = res\nEnd Function\n", "Python": "def getLantern(arr):\n    res = 0\n    for i in range(0, n):\n        if arr[i] != 0:\n            arr[i] -= 1\n            res += getLantern(arr)\n            arr[i] += 1\n    if res == 0:\n        res = 1\n    return res\n\na = []\nn = int(input())\nfor i in range(0, n):\n    a.append(int(input()))\nprint(getLantern(a))\n"}
{"id": 57856, "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": 57857, "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", "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": 57858, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 57859, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 57860, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 57861, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\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": 57862, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\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": 57863, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\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": 57864, "name": "Magnanimous numbers", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\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": 57865, "name": "Create a two-dimensional array at runtime", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\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": 57866, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 57867, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 57868, "name": "Pi", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\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": 57869, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 57870, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 57871, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 57872, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 57873, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 57874, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 57875, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 57876, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 57877, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 57878, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 57879, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 57880, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 57881, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 57882, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 57883, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 57884, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 57885, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 57886, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 57887, "name": "List comprehensions", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 57888, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 57889, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 57890, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 57891, "name": "Loops_Downward for", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 57892, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n"}
{"id": 57893, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 57894, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 57895, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 57896, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n"}
{"id": 57897, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 57898, "name": "Pell's equation", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n"}
{"id": 57899, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 57900, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 57901, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 57902, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 57903, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 57904, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 57905, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 57906, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 57907, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 57908, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 57909, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 57910, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 57911, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 57912, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 57913, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 57914, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 57915, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 57916, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 57917, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 57918, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 57919, "name": "Stern-Brocot sequence", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 57920, "name": "Chat server", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 57921, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 57922, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 57923, "name": "Terminal control_Dimensions", "VB": "Module Module1\n\n    Sub Main()\n        Dim bufferHeight = Console.BufferHeight\n        Dim bufferWidth = Console.BufferWidth\n        Dim windowHeight = Console.WindowHeight\n        Dim windowWidth = Console.WindowWidth\n\n        Console.Write(\"Buffer Height: \")\n        Console.WriteLine(bufferHeight)\n        Console.Write(\"Buffer Width: \")\n        Console.WriteLine(bufferWidth)\n        Console.Write(\"Window Height: \")\n        Console.WriteLine(windowHeight)\n        Console.Write(\"Window Width: \")\n        Console.WriteLine(windowWidth)\n    End Sub\n\nEnd Module\n", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n"}
{"id": 57924, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 57925, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 57926, "name": "Literals_String", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n"}
{"id": 57927, "name": "GUI_Maximum window dimensions", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n"}
{"id": 57928, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 57929, "name": "Knapsack problem_Unbounded", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n"}
{"id": 57930, "name": "Range extraction", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 57931, "name": "Type detection", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n"}
{"id": 57932, "name": "Maximum triangle path sum", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n"}
{"id": 57933, "name": "UTF-8 encode and decode", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n"}
{"id": 57934, "name": "Magic squares of doubly even order", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n"}
{"id": 57935, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 57936, "name": "Execute a system command", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 57937, "name": "XML validation", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n"}
{"id": 57938, "name": "Longest increasing subsequence", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 57939, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n"}
{"id": 57940, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n"}
{"id": 57941, "name": "One of n lines in a file", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 57942, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n"}
{"id": 57943, "name": "Repeat", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 57944, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 57945, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 57946, "name": "Hello world_Web server", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 57947, "name": "Chemical calculator", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\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 ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n"}
{"id": 57948, "name": "Pythagorean quadruples", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 57949, "name": "Zebra puzzle", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n"}
{"id": 57950, "name": "Zebra puzzle", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n"}
{"id": 57951, "name": "Rosetta Code_Find unimplemented tasks", "VB": "Set http= CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\n\nstart=\"https://rosettacode.org\"\nConst lang=\"VBScript\"\nDim oHF \n\ngettaskslist \"about:/wiki/Category:Programming_Tasks\" ,True\nprint odic.Count\ngettaskslist \"about:/wiki/Category:Draft_Programming_Tasks\",True\nprint \"total tasks \" & odic.Count\ngettaskslist \"about:/wiki/Category:\"&lang,False\nprint \"total tasks  not in \" & lang & \" \" &odic.Count & vbcrlf\nFor Each d In odic.keys\n   print d &vbTab &  Replace(odic(d),\"about:\", start)\nnext\nWScript.Quit(1)\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\nFunction getpage(name)\n  Set oHF=Nothing\n  Set oHF = CreateObject(\"HTMLFILE\")\n  http.open \"GET\",name,False  \n  http.send \n  oHF.write \"<html><body></body></html>\"\n  oHF.body.innerHTML = http.responsetext \n  Set getpage=Nothing\nEnd Function\n\nSub gettaskslist(b,build)\n  nextpage=b\n  While nextpage <>\"\"\n  \n    nextpage=Replace(nextpage,\"about:\", start) \n    WScript.Echo nextpage\n    getpage(nextpage)\n    Set xtoc = oHF.getElementbyId(\"mw-pages\")\n    nextpage=\"\"\n    For Each ch In xtoc.children\n      If  ch.innertext= \"next page\" Then \n        nextpage=ch.attributes(\"href\").value\n        \n      ElseIf ch.attributes(\"class\").value=\"mw-content-ltr\" Then\n        Set ytoc=ch.children(0) \n        \n        Exit For\n      End If   \n    Next\n    For Each ch1 In ytoc.children \n      \n      For Each ch2 In ch1.children(1).children \n        Set ch=ch2.children(0)\n        If build Then\n           odic.Add ch.innertext , ch.attributes(\"href\").value\n        else    \n           odic.Remove ch.innertext\n        End if   \n           \n      Next \n    Next\n  Wend  \nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n"}
{"id": 57952, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 57953, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 57954, "name": "Practical numbers", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n"}
{"id": 57955, "name": "Literals_Floating point", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n"}
{"id": 57956, "name": "Literals_Floating point", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n"}
{"id": 57957, "name": "Word search", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n"}
{"id": 57958, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 57959, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 57960, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 57961, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 57962, "name": "Long year", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 57963, "name": "Zumkeller numbers", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 57964, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 57965, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 57966, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 57967, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 57968, "name": "Dijkstra's algorithm", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n"}
{"id": 57969, "name": "Geometric algebra", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n"}
{"id": 57970, "name": "Associative array_Iteration", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 57971, "name": "Define a primitive data type", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n"}
{"id": 57972, "name": "Hash join", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n"}
{"id": 57973, "name": "Latin Squares in reduced form", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n"}
{"id": 57974, "name": "Latin Squares in reduced form", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n"}
{"id": 57975, "name": "Closest-pair problem", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n"}
{"id": 57976, "name": "Address of a variable", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n", "C#": "int i = 5;\nint* p = &i;\n"}
{"id": 57977, "name": "Inheritance_Single", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n"}
{"id": 57978, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n"}
{"id": 57979, "name": "Color wheel", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n"}
{"id": 57980, "name": "Rare numbers", "VB": "Imports System.Console\nImports DT = System.DateTime\nImports Lsb = System.Collections.Generic.List(Of SByte)\nImports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte))\nImports UI = System.UInt64\n\nModule Module1\n    Const MxD As SByte = 15\n\n    Public Structure term\n        Public coeff As UI : Public a, b As SByte\n        Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer)\n            coeff = c : a = CSByte(a_) : b = CSByte(b_)\n        End Sub\n    End Structure\n\n    Dim nd, nd2, count As Integer, digs, cnd, di As Integer()\n    Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term))\n    Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst)\n    Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI\n\n    \n    Function ToDif() As UI\n        Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i)\n        Next : Return r\n    End Function\n\n    \n    Function ToSum() As UI\n        Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i)\n        Next : Return Dif + (r << 1)\n    End Function\n\n    \n    Function IsSquare(nmbr As UI) As Boolean\n        If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _\n            Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False\n    End Function\n\n    \n    Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb\n        Dim res As Lsb = New Lsb()\n        For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res\n    End Function\n\n    \n    Sub Fnpr(ByVal lev As Integer)\n        If lev = dis.Count Then\n            digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1)\n            Dim le As Integer = di.Length, i As Integer = 1\n            If odd Then le -= 1 : digs(nd >> 1) = di(le)\n            For Each d As SByte In di.Skip(1).Take(le - 1)\n                digs(ixs(i)(0)) = dmd(cnd(i))(d)(0)\n                digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next\n            If Not IsSquare(ToSum()) Then Return\n            res.Add(ToDif()) : count += 1\n            WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\", (DT.Now - st).TotalMilliseconds, count, res.Last())\n        Else\n            For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next\n        End If\n    End Sub\n\n    \n    Sub Fnmr(ByVal list As Lst, ByVal lev As Integer)\n        If lev = list.Count Then\n            Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2)\n                If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _\n                              Else Dif += t.coeff * CULng(cnd(i))\n                i += 1 : Next\n            If Dif <= 0 OrElse Not IsSquare(Dif) Then Return\n            dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)}\n            For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next\n            If odd Then dis.Add(il)\n            di = New Integer(dis.Count - 1) {} : Fnpr(0)\n        Else\n            For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next\n        End If\n    End Sub\n\n    Sub init()\n        Dim pow As UI = 1\n        \n        tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD)\n            Dim terms As List(Of term) = New List(Of term)()\n            pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1\n            Dim i1 As Integer = 0, i2 As Integer = r - 1\n            While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2))\n                p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While\n            tLst.Add(terms) : Next\n        \n        fml = New Dictionary(Of Integer, Lst)() From {\n            {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}},\n            {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}},\n            {4, New Lst() From {New Lsb() From {4, 0}}},\n            {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}}\n        \n        dmd = New Dictionary(Of Integer, Lst)()\n        For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i\n            While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _\n                Else dmd(d) = New Lst From {New Lsb From {i, j}}\n                j += 1 : d -= 1 : End While : Next\n        dl = Seq(-9, 9)    \n        zl = Seq(0, 0)     \n        el = Seq(-8, 8, 2) \n        ol = Seq(-9, 9, 2) \n        il = Seq(0, 9)\n        lists = New List(Of Lst)()\n        For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next\n    End Sub\n\n    Sub Main(ByVal args As String())\n        init() : res = New List(Of UI)() : st = DT.Now : count = 0\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Rare Numbers\")\n        nd = 2 : nd2 = 0 : odd = False : While nd <= MxD\n            digs = New Integer(nd - 1) {} : If nd = 4 Then\n                lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol)\n            ElseIf tLst(nd2).Count > lists(0).Count Then\n                For Each list As Lst In lists : list.Add(dl) : Next : End If\n            ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next\n            For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds)\n            nd += 1 : nd2 += 1 : odd = Not odd : End While\n        res.Sort() : WriteLine(vbLf & \"The {0} rare numbers with up to {1} digits are:\", res.Count, MxD)\n        count = 0 : For Each rare In res : count += 1 : WriteLine(\"{0,2}:{1,27:n0}\", count, rare) : Next\n        If System.Diagnostics.Debugger.IsAttached Then ReadKey()\n    End Sub\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nusing UI = System.UInt64;\nusing LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;\nusing Lst = System.Collections.Generic.List<sbyte>;\nusing DT = System.DateTime;\n\nclass Program {\n\n    const sbyte MxD = 19;\n\n    public struct term { public UI coeff; public sbyte a, b;\n        public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } }\n\n    static int[] digs;   static List<UI> res;   static sbyte count = 0;\n    static DT st; static List<List<term>> tLst; static List<LST> lists;\n    static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il;\n    static bool odd; static int nd, nd2; static LST ixs;\n    static int[] cnd, di; static LST dis; static UI Dif;\n\n    \n    static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++)\n            r = r * 10 + (uint)digs[i]; return r; }\n    \n    \n    static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--)\n            r = r * 10 + (uint)digs[i]; return Dif + (r << 1); }\n\n    \n    static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0)\n        { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; }\n\n    \n    static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst();\n        for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; }\n\n    \n    static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0];\n            digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1;\n            if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) {\n                digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; }\n            if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\",\n                (DT.Now - st).TotalMilliseconds, ++count, res.Last()); }\n        else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } }\n\n    \n    static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0;\n            foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]);\n                else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return;\n            dis = new LST { Seq(0, fml[cnd[0]].Count - 1) };\n            foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1));\n            if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0);\n        } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } }\n\n    static void init() { UI pow = 1;\n        \n        tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) {\n            List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1;\n            for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) {\n                terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; }\n            tLst.Add(terms); }\n        \n        fml = new Dictionary<int, LST> {\n            [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } },\n            [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } },\n            [4] = new LST { new Lst { 4, 0 } },\n            [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } };\n        \n        dmd = new Dictionary<int, LST>();\n        for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) {\n                if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j });\n                else dmd[d] = new LST { new Lst { i, j } }; }\n        dl = Seq(-9, 9);    \n        zl = Seq( 0, 0);    \n        el = Seq(-8, 8, 2); \n        ol = Seq(-9, 9, 2); \n        il = Seq( 0, 9); lists = new List<LST>();\n        foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); }\n\n    static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0;\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Unordered Rare Numbers\");\n        for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd];\n            if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); }\n            else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl);\n            ixs = new LST(); \n            foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b });\n            foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); }\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds); }\n        res.Sort();\n        WriteLine(\"\\nThe {0} rare numbers with up to {1} digits are:\", res.Count, MxD);\n        count = 0; foreach (var rare in res) WriteLine(\"{0,2}:{1,27:n0}\", ++count, rare);\n        if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }\n}\n"}
{"id": 57981, "name": "Minesweeper game", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MineFieldModel\n{\n    public int RemainingMinesCount{\n        get{\n            var count = 0;\n            ForEachCell((i,j)=>{\n                if (Mines[i,j] && !Marked[i,j])\n                    count++;\n            });\n            return count;\n        }\n    }\n\n    public bool[,] Mines{get; private set;}\n    public bool[,] Opened{get;private set;}\n    public bool[,] Marked{get; private set;}\n    public int[,] Values{get;private set; }\n    public int Width{ get{return Mines.GetLength(1);} } \n    public int Height{ get{return Mines.GetLength(0);} }\n\n    public MineFieldModel(bool[,] mines)\n    {\n        this.Mines = mines;\n        this.Opened = new bool[Height, Width]; \n        this.Marked = new bool[Height, Width];\n        this.Values = CalculateValues();\n    }\n    \n    private int[,] CalculateValues()\n    {\n        int[,] values = new int[Height, Width];\n        ForEachCell((i,j) =>{\n            var value = 0;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (Mines[i1,j1])\n                    value++;\n            });\n            values[i,j] = value;\n        });\n        return values;\n    }\n\n    \n    public void ForEachCell(Action<int,int> action)\n    {\n        for (var i = 0; i < Height; i++)\n        for (var j = 0; j < Width; j++)\n            action(i,j);\n    }\n\n    \n    public void ForEachNeighbor(int i, int j, Action<int,int> action)\n    {\n        for (var i1 = i-1; i1 <= i+1; i1++)\n        for (var j1 = j-1; j1 <= j+1; j1++)               \n            if (InBounds(j1, i1) && !(i1==i && j1 ==j))\n                action(i1, j1);\n    }\n\n    private bool InBounds(int x, int y)\n    {\n        return y >= 0 && y < Height && x >=0 && x < Width;\n    }\n\n    public event Action Exploded = delegate{};\n    public event Action Win = delegate{};\n    public event Action Updated = delegate{};\n\n    public void OpenCell(int i, int j){\n        if(!Opened[i,j]){\n            if (Mines[i,j])\n                Exploded();\n            else{\n                OpenCellsStartingFrom(i,j);\n                Updated();\n                CheckForVictory();\n            }\n        }\n    }\n\n    void OpenCellsStartingFrom(int i, int j)\n    {\n            Opened[i,j] = true;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1])\n                    OpenCellsStartingFrom(i1, j1);\n            });\n    }\n    \n    void CheckForVictory(){\n        int notMarked = 0;\n        int wrongMarked = 0;\n        ForEachCell((i,j)=>{\n            if (Mines[i,j] && !Marked[i,j])\n                notMarked++;\n            if (!Mines[i,j] && Marked[i,j])\n                wrongMarked++;\n        }); \n        if (notMarked == 0 && wrongMarked == 0)\n            Win();\n    }\n\n    public void Mark(int i, int j){\n        if (!Opened[i,j])\n            Marked[i,j] = true;\n            Updated();\n            CheckForVictory();\n    }\n}\n\nclass MineFieldView: UserControl{\n    public const int CellSize = 40;\n\n    MineFieldModel _model;\n    public MineFieldModel Model{\n        get{ return _model; }\n        set\n        { \n            _model = value; \n            this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2);\n        }\n    }\n    \n    public MineFieldView(){\n        \n        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true);\n        this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);\n\n        this.MouseUp += (o,e)=>{\n            Point cellCoords = GetCell(e.Location);\n            if (Model != null)\n            {\n                if (e.Button == MouseButtons.Left)\n                    Model.OpenCell(cellCoords.Y, cellCoords.X);\n                else if (e.Button == MouseButtons.Right)\n                    Model.Mark(cellCoords.Y, cellCoords.X);\n            }\n        };\n    }\n\n    Point GetCell(Point coords)\n    {\n        var rgn = ClientRectangle;\n        var x = (coords.X - rgn.X)/CellSize;\n        var y = (coords.Y - rgn.Y)/CellSize;\n        return new Point(x,y);\n    }\n         \n    static readonly Brush MarkBrush = new SolidBrush(Color.Blue);\n    static readonly Brush ValueBrush = new SolidBrush(Color.Black);\n    static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control);\n    static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark);\n\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        var g = e.Graphics;\n        if (Model != null)\n        {\n            Model.ForEachCell((i,j)=>\n            {\n                var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize);\n                if (Model.Opened[i,j])\n                {\n                    g.FillRectangle(OpenBrush, bounds);\n                    if (Model.Values[i,j] > 0)\n                    {\n                        DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds);\n                    }\n                } \n                else \n                {\n                    g.FillRectangle(UnexploredBrush, bounds);\n                    if (Model.Marked[i,j])\n                    {\n                        DrawStringInCenter(g, \"?\", MarkBrush, bounds);\n                    }\n                    var outlineOffset = 1;\n                    var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset);\n                    g.DrawRectangle(Pens.Gray, outline);\n                }\n                g.DrawRectangle(Pens.Black, bounds);\n            });\n        }\n\n    }\n\n    static readonly StringFormat FormatCenter = new StringFormat\n                            {\n                                LineAlignment = StringAlignment.Center,\n                                Alignment=StringAlignment.Center\n                            };\n\n    void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds)\n    {\n        PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2);\n        g.DrawString(s, this.Font, brush, center, FormatCenter);\n    }\n\n}\n\nclass MineSweepForm: Form\n{\n\n    MineFieldModel CreateField(int width, int height)\n{\n        var field = new bool[height, width];\n        int mineCount = (int)(0.2 * height * width);\n        var rnd = new Random();\n        while(mineCount > 0)\n        {\n            var x = rnd.Next(width);\n            var y = rnd.Next(height);\n            if (!field[y,x])\n            {\n                field[y,x] = true;\n                mineCount--;\n            }\n        }\n        return new MineFieldModel(field);\n    }\n\n    public MineSweepForm()\n    {\n        var model = CreateField(6, 4);\n        var counter = new Label{ };\n        counter.Text = model.RemainingMinesCount.ToString();\n        var view = new MineFieldView\n                        { \n                            Model = model, BorderStyle = BorderStyle.FixedSingle,\n                        };\n        var stackPanel = new FlowLayoutPanel\n                        {\n                            Dock = DockStyle.Fill,\n                            FlowDirection = FlowDirection.TopDown,\n                            Controls = {counter, view}\n                        };\n        this.Controls.Add(stackPanel);\n        model.Updated += delegate{\n            view.Invalidate();\n            counter.Text = model.RemainingMinesCount.ToString();\n        };\n        model.Exploded += delegate {\n            MessageBox.Show(\"FAIL!\");\n            Close();\n        };\n        model.Win += delegate {\n            MessageBox.Show(\"WIN!\");\n            view.Enabled = false;\n        };\n\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Application.Run(new MineSweepForm());\n    }\n}\n"}
{"id": 57982, "name": "Square root by hand", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n"}
{"id": 57983, "name": "Square root by hand", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n"}
{"id": 57984, "name": "Primes with digits in nondecreasing order", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 57985, "name": "Primes with digits in nondecreasing order", "VB": "Imports System.Linq\nImports System.Collections.Generic\nImports System.Console\nImports System.Math\n\nModule Module1\n    Dim ba As Integer\n    Dim chars As String = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)\n        Dim flags(lim) As Boolean, j As Integer : Yield 2\n        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3\n        Dim d As Integer = 8, sq As Integer = 9\n        While sq <= lim\n            If Not flags(j) Then\n                Yield j : Dim i As Integer = j << 1\n                For k As Integer = sq To lim step i : flags(k) = True : Next\n            End If\n            j += 2 : d += 8 : sq += d : End While\n        While j <= lim\n            If Not flags(j) Then Yield j\n            j += 2 : End While\n    End Function\n\n    \n    Function from10(ByVal b As Integer) As String\n        Dim res As String = \"\", re As Integer\n        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res\n    End Function\n\n    \n    Function to10(ByVal s As String) As Integer\n        Dim res As Integer = 0\n        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res\n    End Function\n\n    \n    Function nd(ByVal s As String) As Boolean\n        If s.Length < 2 Then Return True\n        Dim l As Char = s(0)\n        For i As Integer = 1 To s.Length - 1\n            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)\n        Next : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim c As Integer, lim As Integer = 1000, s As String\n        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }\n            ba = b : c = 0 : For Each a As Integer In Primes(lim)\n                s = from10(a) : If nd(s) Then c += 1 : Write(\"{0,4} {1}\", s, If(c Mod 20 = 0, vbLf, \"\"))\n            Next\n            WriteLine(vbLf & \"Base {0}: found {1} non-decreasing primes under {2:n0}\" & vbLf, b, c, from10(lim))\n        Next\n    End Sub\nEnd Module\n", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 57986, "name": "Reflection_List properties", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n"}
{"id": 57987, "name": "Align columns", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n"}
{"id": 57988, "name": "Align columns", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n"}
{"id": 57989, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 57990, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 57991, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 57992, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 57993, "name": "Data Encryption Standard", "VB": "Imports System.IO\nImports System.Security.Cryptography\n\nModule Module1\n\n    \n    Function ByteArrayToString(ba As Byte()) As String\n        Return BitConverter.ToString(ba).Replace(\"-\", \"\")\n    End Function\n\n    \n    \n    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateEncryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(messageBytes, 0, messageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim encryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n\n        Return encryptedMessageBytes\n    End Function\n\n    \n    \n    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateDecryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim decryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)\n\n        Return decryptedMessageBytes\n    End Function\n\n    Sub Main()\n        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}\n        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}\n\n        Dim encStr = Encrypt(plainBytes, keyBytes)\n        Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr))\n\n        Dim decStr = Decrypt(encStr, keyBytes)\n        Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decStr))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace DES {\n    class Program {\n        \n        static string ByteArrayToString(byte[] ba) {\n            return BitConverter.ToString(ba).Replace(\"-\", \"\");\n        }\n\n        \n        \n        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(messageBytes, 0, messageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] encryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n\n            return encryptedMessageBytes;\n        }\n\n        \n        \n        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] decryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);\n\n            return decryptedMessageBytes;\n        }\n\n        static void Main(string[] args) {\n            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };\n            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };\n\n            byte[] encStr = Encrypt(plainBytes, keyBytes);\n            Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr));\n\n            byte[] decBytes = Decrypt(encStr, keyBytes);\n            Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decBytes));\n        }\n    }\n}\n"}
{"id": 57994, "name": "Commatizing numbers", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n"}
{"id": 57995, "name": "Arithmetic coding_As a generalized change of radix", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 57996, "name": "Kosaraju", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 57997, "name": "Twelve statements", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n"}
{"id": 57998, "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": 57999, "name": "Carmichael 3 strong pseudoprimes", "Python": "class Isprime():\n    \n    multiples = {2}\n    primes = [2]\n    nmax = 2\n    \n    def __init__(self, nmax):\n        if nmax > self.nmax:\n            self.check(nmax)\n\n    def check(self, n):\n        if type(n) == float:\n            if not n.is_integer(): return False\n            n = int(n)\n        multiples = self.multiples\n        if n <= self.nmax:\n            return n not in multiples\n        else:\n            \n            primes, nmax = self.primes, self.nmax\n            newmax = max(nmax*2, n)\n            for p in primes:\n                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))\n            for i in range(nmax+1, newmax+1):\n                if i not in multiples:\n                    primes.append(i)\n                    multiples.update(range(i*2, newmax+1, i))\n            self.nmax = newmax\n            return n not in multiples\n\n    __call__ = check\n            \n        \ndef carmichael(p1):\n    ans = []\n    if isprime(p1):\n        for h3 in range(2, p1):\n            g = h3 + p1\n            for d in range(1, g):\n                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:\n                    p2 = 1 + ((p1 - 1)* g // d)\n                    if isprime(p2):\n                        p3 = 1 + (p1 * p2 // h3)\n                        if isprime(p3):\n                            if (p2 * p3) % (p1 - 1) == 1:\n                                \n                                ans += [tuple(sorted((p1, p2, p3)))]\n    return ans\n                \nisprime = Isprime(2)\n \nans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))\nprint(',\\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n"}
{"id": 58000, "name": "Image noise", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n"}
{"id": 58001, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 58002, "name": "Keyboard input_Obtain a Y or N response", "Python": "\n\ntry:\n    from msvcrt import getch\nexcept ImportError:\n    def getch():\n        import sys, tty, termios\n        fd = sys.stdin.fileno()\n        old_settings = termios.tcgetattr(fd)\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nprint \"Press Y or N to continue\"\nwhile True:\n    char = getch()\n    if char.lower() in (\"y\", \"n\"):\n        print char\n        break\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n"}
{"id": 58003, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n"}
{"id": 58004, "name": "Conjugate transpose", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n"}
{"id": 58005, "name": "Conjugate transpose", "Python": "def conjugate_transpose(m):\n    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n    'Complex Identity matrix'\n    sz = range(size)\n    m = [[0 + 0j for i in sz] for j in sz]\n    for i in range(size):\n        m[i][i] = 1 + 0j\n    return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n    first, rest = vector[0], vector[1:]\n    return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n    first, rest = vector[0], vector[1:]\n    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n               for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n    'Check any number of matrices for equality within eps'\n    x = [len(m) for m in matrices]\n    if not __allsame(x): return False\n    y = [len(m[0]) for m in matrices]\n    if not __allsame(y): return False\n    for s in range(x[0]):\n        for t in range(y[0]):\n            if not __allnearsame([m[s][t] for m in matrices], eps): return False\n    return True\n    \n\ndef ishermitian(m, ct):\n    return isequal([m, ct])\n\ndef isnormal(m, ct):\n    return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n    mct, ctm = mmul(m, ct), mmul(ct, m)\n    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n    ident = mi(mctx)\n    return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n    print(comment)\n    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n    width = max(max(len(f) for f in row) for row in fields)\n    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n    print('\\n'.join(lines))\n\nif __name__ == '__main__':\n    for matrix in [\n            ((( 3.000+0.000j), (+2.000+1.000j)), \n            (( 2.000-1.000j), (+1.000+0.000j))),\n\n            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n        printm('\\nMatrix:', matrix)\n        ct = conjugate_transpose(matrix)\n        printm('Its conjugate transpose:', ct)\n        print('Hermitian? %s.' % ishermitian(matrix, ct))\n        print('Normal?    %s.' % isnormal(matrix, ct))\n        print('Unitary?   %s.' % isunitary(matrix, ct))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n"}
{"id": 58006, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 58007, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 58008, "name": "Jacobsthal numbers", "Python": "\nfrom math import floor, pow\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef odd(n):\n    return n and 1 != 0\n    \ndef jacobsthal(n):\n    return floor((pow(2,n)+odd(n))/3)\n\ndef jacobsthal_lucas(n):\n    return int(pow(2,n)+pow(-1,n))\n\ndef jacobsthal_oblong(n):\n    return jacobsthal(n)*jacobsthal(n+1)\n\n\nif __name__ == '__main__':\n    print(\"First 30 Jacobsthal numbers:\")\n    for j in range(0, 30):\n        print(jacobsthal(j), end=\"  \")\n\n    print(\"\\n\\nFirst 30 Jacobsthal-Lucas numbers: \")\n    for j in range(0, 30):\n        print(jacobsthal_lucas(j), end = '\\t')\n\n    print(\"\\n\\nFirst 20 Jacobsthal oblong numbers: \")\n    for j in range(0, 20):\n        print(jacobsthal_oblong(j), end=\"  \")\n\n    print(\"\\n\\nFirst 10 Jacobsthal primes: \")\n    for j in range(3, 33):\n        if isPrime(jacobsthal(j)):\n            print(jacobsthal(j))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n"}
{"id": 58009, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n"}
{"id": 58010, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 58011, "name": "Cistercian numerals", "Python": "\n\n\n\n\ndef _init():\n    \"digit sections for forming numbers\"\n    digi_bits = .strip()\n\n    lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n             for ln in digi_bits.strip().split('\\n')\n             if '\n    formats = '<2 >2 <2 >2'.split()\n    digits = [[f\"{dig:{f}}\" for dig in line]\n              for f, line in zip(formats, lines)]\n\n    return digits\n\n_digits = _init()\n\n\n\ndef _to_digits(n):\n    assert 0 <= n < 10_000 and int(n) == n\n    \n    return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n    global _digits\n    d = _to_digits(n)\n    lines = [\n        ''.join((_digits[1][d[1]], '┃',  _digits[0][d[0]])),\n        ''.join((_digits[0][   0], '┃',  _digits[0][   0])),\n        ''.join((_digits[3][d[3]], '┃',  _digits[2][d[2]])),\n        ]\n    \n    return lines\n\ndef cjoin(c1, c2, spaces='   '):\n    return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n\nif __name__ == '__main__':\n    \n    \n    \n    \n    for pow10 in range(4):    \n        step = 10 ** pow10\n        print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n        lines = num_to_lines(step)\n        for n in range(step*2, step*10, step):\n            lines = cjoin(lines, num_to_lines(n))\n        print('\\n'.join(lines))\n    \n\n    numbers = [0, 5555, 6789, 6666]\n    print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n    lines = num_to_lines(numbers[0])\n    for n in numbers[1:]:\n        lines = cjoin(lines, num_to_lines(n))\n    print('\\n'.join(lines))\n", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n"}
{"id": 58012, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n"}
{"id": 58013, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 58014, "name": "Draw a sphere", "Python": "import math\n\nshades = ('.',':','!','*','o','e','&','\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": 58015, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n"}
{"id": 58016, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 58017, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n"}
{"id": 58018, "name": "Fermat numbers", "Python": "def factors(x):\n    factors = []\n    i = 2\n    s = int(x ** 0.5)\n    while i < s:\n        if x % i == 0:\n            factors.append(i)\n            x = int(x / i)\n            s = int(x ** 0.5)\n        i += 1\n    factors.append(x)\n    return factors\n\nprint(\"First 10 Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    print(\"F{} = {}\".format(chr(i + 0x2080) , fermat))\n\nprint(\"\\nFactors of first few Fermat numbers:\")\nfor i in range(10):\n    fermat = 2 ** 2 ** i + 1\n    fac = factors(fermat)\n    if len(fac) == 1:\n        print(\"F{} -> IS PRIME\".format(chr(i + 0x2080)))\n    else:\n        print(\"F{} -> FACTORS: {}\".format(chr(i + 0x2080), fac))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/jbarham/primegen\"\n    \"math\"\n    \"math/big\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst (\n    maxCurves = 10000\n    maxRnd    = 1 << 31\n    maxB1     = uint64(43 * 1e7)\n    maxB2     = uint64(2 * 1e10)\n)\n\nvar (\n    zero  = big.NewInt(0)\n    one   = big.NewInt(1)\n    two   = big.NewInt(2)\n    three = big.NewInt(3)\n    four  = big.NewInt(4)\n    five  = big.NewInt(5)\n)\n\n\nfunc pollardRho(n *big.Int) (*big.Int, error) {\n    \n    g := func(x, n *big.Int) *big.Int {\n        x2 := new(big.Int)\n        x2.Mul(x, x)\n        x2.Add(x2, one)\n        return x2.Mod(x2, n)\n    }\n    x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one)\n    t, z := new(big.Int), new(big.Int).Set(one)\n    count := 0\n    for {\n        x = g(x, n)\n        y = g(g(y, n), n)\n        t.Sub(x, y)\n        t.Abs(t)\n        t.Mod(t, n)\n        z.Mul(z, t)\n        count++\n        if count == 100 {\n            d.GCD(nil, nil, z, n)\n            if d.Cmp(one) != 0 {\n                break\n            }\n            z.Set(one)\n            count = 0\n        }\n    }\n    if d.Cmp(n) == 0 {\n        return nil, fmt.Errorf(\"Pollard's rho failure\")\n    }\n    return d, nil\n}\n\n\nfunc getPrimes(n uint64) []uint64 {\n    pg := primegen.New()\n    var primes []uint64\n    for {\n        prime := pg.Next()\n        if prime < n {\n            primes = append(primes, prime)\n        } else {\n            break\n        }\n    }\n    return primes\n}\n\n\nfunc computeBounds(n *big.Int) (uint64, uint64) {\n    le := len(n.String())\n    var b1, b2 uint64\n    switch {\n    case le <= 30:\n        b1, b2 = 2000, 147396\n    case le <= 40:\n        b1, b2 = 11000, 1873422\n    case le <= 50:\n        b1, b2 = 50000, 12746592\n    case le <= 60:\n        b1, b2 = 250000, 128992510\n    case le <= 70:\n        b1, b2 = 1000000, 1045563762\n    case le <= 80:\n        b1, b2 = 3000000, 5706890290\n    default:\n        b1, b2 = maxB1, maxB2\n    }\n    return b1, b2\n}\n\n\nfunc pointAdd(px, pz, qx, qz, rx, rz, n *big.Int) (*big.Int, *big.Int) {\n    t := new(big.Int).Sub(px, pz)\n    u := new(big.Int).Add(qx, qz)\n    u.Mul(t, u)\n    t.Add(px, pz)\n    v := new(big.Int).Sub(qx, qz)\n    v.Mul(t, v)\n    upv := new(big.Int).Add(u, v)\n    umv := new(big.Int).Sub(u, v)\n    x := new(big.Int).Mul(upv, upv)\n    x.Mul(x, rz)\n    if x.Cmp(n) >= 0 {\n        x.Mod(x, n)\n    }\n    z := new(big.Int).Mul(umv, umv)\n    z.Mul(z, rx)\n    if z.Cmp(n) >= 0 {\n        z.Mod(z, n)\n    }\n    return x, z\n}\n\n\nfunc pointDouble(px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {\n    u2 := new(big.Int).Add(px, pz)\n    u2.Mul(u2, u2)\n    v2 := new(big.Int).Sub(px, pz)\n    v2.Mul(v2, v2)\n    t := new(big.Int).Sub(u2, v2)\n    x := new(big.Int).Mul(u2, v2)\n    if x.Cmp(n) >= 0 {\n        x.Mod(x, n)\n    }\n    z := new(big.Int).Mul(a24, t)\n    z.Add(v2, z)\n    z.Mul(t, z)\n    if z.Cmp(n) >= 0 {\n        z.Mod(z, n)\n    }\n    return x, z\n}\n\n\nfunc scalarMultiply(k, px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {\n    sk := fmt.Sprintf(\"%b\", k)\n    lk := len(sk)\n    qx := new(big.Int).Set(px)\n    qz := new(big.Int).Set(pz)\n    rx, rz := pointDouble(px, pz, n, a24)\n    for i := 1; i < lk; i++ {\n        if sk[i] == '1' {\n            qx, qz = pointAdd(rx, rz, qx, qz, px, pz, n)\n            rx, rz = pointDouble(rx, rz, n, a24)\n\n        } else {\n            rx, rz = pointAdd(qx, qz, rx, rz, px, pz, n)\n            qx, qz = pointDouble(qx, qz, n, a24)\n        }\n    }\n    return qx, qz\n}\n\n\nfunc ecm(n *big.Int) (*big.Int, error) {\n    if n.Cmp(one) == 0 || n.ProbablyPrime(10) {\n        return n, nil\n    }\n    b1, b2 := computeBounds(n)\n    dd := uint64(math.Sqrt(float64(b2)))\n    beta := make([]*big.Int, dd+1)\n    for i := 0; i < len(beta); i++ {\n        beta[i] = new(big.Int)\n    }\n    s := make([]*big.Int, 2*dd+2)\n    for i := 0; i < len(s); i++ {\n        s[i] = new(big.Int)\n    }\n\n    \n    curves := 0\n    logB1 := math.Log(float64(b1))\n    primes := getPrimes(b2)\n    numPrimes := len(primes)\n    idxB1 := sort.Search(len(primes), func(i int) bool { return primes[i] >= b1 })\n\n    \n    k := big.NewInt(1)\n    for i := 0; i < idxB1; i++ {\n        p := primes[i]\n        bp := new(big.Int).SetUint64(p)\n        t := uint64(logB1 / math.Log(float64(p)))\n        bt := new(big.Int).SetUint64(t)\n        bt.Exp(bp, bt, nil)\n        k.Mul(k, bt)\n    }\n    g := big.NewInt(1)\n    for (g.Cmp(one) == 0 || g.Cmp(n) == 0) && curves <= maxCurves {\n        curves++\n        st := int64(6 + rand.Intn(maxRnd-5))\n        sigma := big.NewInt(st)\n\n        \n        u := new(big.Int).Mul(sigma, sigma)\n        u.Sub(u, five)\n        u.Mod(u, n)\n        v := new(big.Int).Mul(four, sigma)\n        v.Mod(v, n)\n        vmu := new(big.Int).Sub(v, u)\n        a := new(big.Int).Mul(vmu, vmu)\n        a.Mul(a, vmu)\n        t := new(big.Int).Mul(three, u)\n        t.Add(t, v)\n        a.Mul(a, t)\n        t.Mul(four, u)\n        t.Mul(t, u)\n        t.Mul(t, u)\n        t.Mul(t, v)\n        a.Quo(a, t)\n        a.Sub(a, two)\n        a.Mod(a, n)\n        a24 := new(big.Int).Add(a, two)\n        a24.Quo(a24, four)\n\n        \n        px := new(big.Int).Mul(u, u)\n        px.Mul(px, u)\n        t.Mul(v, v)\n        t.Mul(t, v)\n        px.Quo(px, t)\n        px.Mod(px, n)\n        pz := big.NewInt(1)\n        qx, qz := scalarMultiply(k, px, pz, n, a24)\n        g.GCD(nil, nil, n, qz)\n\n        \n        \n        if g.Cmp(one) != 0 && g.Cmp(n) != 0 {\n            return g, nil\n        }\n\n        \n        s[1], s[2] = pointDouble(qx, qz, n, a24)\n        s[3], s[4] = pointDouble(s[1], s[2], n, a24)\n        beta[1].Mul(s[1], s[2])\n        beta[1].Mod(beta[1], n)\n        beta[2].Mul(s[3], s[4])\n        beta[2].Mod(beta[2], n)\n        for d := uint64(3); d <= dd; d++ {\n            d2 := 2 * d\n            s[d2-1], s[d2] = pointAdd(s[d2-3], s[d2-2], s[1], s[2], s[d2-5], s[d2-4], n)\n            beta[d].Mul(s[d2-1], s[d2])\n            beta[d].Mod(beta[d], n)\n        }\n        g.SetUint64(1)\n        b := new(big.Int).SetUint64(b1 - 1)\n        rx, rz := scalarMultiply(b, qx, qz, n, a24)\n        t.Mul(two, new(big.Int).SetUint64(dd))\n        t.Sub(b, t)\n        tx, tz := scalarMultiply(t, qx, qz, n, a24)\n        q, step := idxB1, 2*dd\n        for r := b1 - 1; r < b2; r += step {\n            alpha := new(big.Int).Mul(rx, rz)\n            alpha.Mod(alpha, n)\n            limit := r + step\n            for q < numPrimes && primes[q] <= limit {\n                d := (primes[q] - r) / 2\n                t := new(big.Int).Sub(rx, s[2*d-1])\n                f := new(big.Int).Add(rz, s[2*d])\n                f.Mul(t, f)\n                f.Sub(f, alpha)\n                f.Add(f, beta[d])\n                g.Mul(g, f)\n                g.Mod(g, n)\n                q++\n            }\n            trx := new(big.Int).Set(rx)\n            trz := new(big.Int).Set(rz)\n            rx, rz = pointAdd(rx, rz, s[2*dd-1], s[2*dd], tx, tz, n)\n            tx.Set(trx)\n            tz.Set(trz)\n        }\n        g.GCD(nil, nil, n, g)\n    }\n\n    \n    if curves > maxCurves {\n        return zero, fmt.Errorf(\"maximum curves exceeded before a factor was found\")\n    }\n    return g, nil\n}\n\n\nfunc primeFactors(n *big.Int) ([]*big.Int, error) {\n    var res []*big.Int\n    if n.ProbablyPrime(10) {\n        return append(res, n), nil\n    }\n    le := len(n.String())\n    var factor1 *big.Int\n    var err error\n    if le > 20 && le <= 60 {\n        factor1, err = ecm(n)\n    } else {\n        factor1, err = pollardRho(n)\n    }\n    if err != nil {\n        return nil, err\n    }\n    if !factor1.ProbablyPrime(10) {\n        return nil, fmt.Errorf(\"first factor is not prime\")\n    }\n    factor2 := new(big.Int)\n    factor2.Quo(n, factor1)\n    if !factor2.ProbablyPrime(10) {\n        return nil, fmt.Errorf(\"%d (second factor is not prime)\", factor1)\n    }\n    return append(res, factor1, factor2), nil\n}\n\nfunc fermatNumbers(n int) (res []*big.Int) {\n    f := new(big.Int).SetUint64(3) \n    for i := 0; i < n; i++ {\n        t := new(big.Int).Set(f)\n        res = append(res, t)\n        f.Sub(f, one)\n        f.Mul(f, f)\n        f.Add(f, one)\n    }\n    return res\n}\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n    fns := fermatNumbers(10)\n    fmt.Println(\"First 10 Fermat numbers:\")\n    for i, f := range fns {\n        fmt.Printf(\"F%c = %d\\n\", 0x2080+i, f)\n    }\n\n    fmt.Println(\"\\nFactors of first 10 Fermat numbers:\")\n    for i, f := range fns {\n        fmt.Printf(\"F%c = \", 0x2080+i)\n        factors, err := primeFactors(f)\n        if err != nil {\n            fmt.Println(err)\n            continue\n        }\n        for _, factor := range factors {\n            fmt.Printf(\"%d \", factor)\n        }\n        if len(factors) == 1 {\n            fmt.Println(\"- prime\")\n        } else {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nTook %s\\n\", time.Since(start))\n}\n"}
{"id": 58019, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n"}
{"id": 58020, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 58021, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n"}
{"id": 58022, "name": "Water collected between towers", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n"}
{"id": 58023, "name": "Descending primes", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58024, "name": "Square-free integers", "Python": "import math\n\ndef SquareFree ( _number ) :\n\tmax = (int) (math.sqrt ( _number ))\n\n\tfor root in range ( 2, max+1 ):\t\t\t\t\t\n\t\tif 0 == _number % ( root * root ):\n\t\t\treturn False\n\n\treturn True\n\ndef ListSquareFrees( _start, _end ):\n\tcount = 0\n\tfor i in range ( _start, _end+1 ):\n\t\tif True == SquareFree( i ):\n\t\t\tprint ( \"{}\\t\".format(i), end=\"\" )\n\t\t\tcount += 1\n\n\tprint ( \"\\n\\nTotal count of square-free numbers between {} and {}: {}\".format(_start, _end, count))\n\nListSquareFrees( 1, 100 )\nListSquareFrees( 1000000000000, 1000000000145 )\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n"}
{"id": 58025, "name": "Jaro similarity", "Python": "\n\nfrom __future__ import division\n\n\ndef jaro(s, t):\n    \n    s_len = len(s)\n    t_len = len(t)\n\n    if s_len == 0 and t_len == 0:\n        return 1\n\n    match_distance = (max(s_len, t_len) // 2) - 1\n\n    s_matches = [False] * s_len\n    t_matches = [False] * t_len\n\n    matches = 0\n    transpositions = 0\n\n    for i in range(s_len):\n        start = max(0, i - match_distance)\n        end = min(i + match_distance + 1, t_len)\n\n        for j in range(start, end):\n            if t_matches[j]:\n                continue\n            if s[i] != t[j]:\n                continue\n            s_matches[i] = True\n            t_matches[j] = True\n            matches += 1\n            break\n\n    if matches == 0:\n        return 0\n\n    k = 0\n    for i in range(s_len):\n        if not s_matches[i]:\n            continue\n        while not t_matches[k]:\n            k += 1\n        if s[i] != t[k]:\n            transpositions += 1\n        k += 1\n\n    return ((matches / s_len) +\n            (matches / t_len) +\n            ((matches - transpositions / 2) / matches)) / 3\n\n\ndef main():\n    \n\n    for s, t in [('MARTHA', 'MARHTA'),\n                 ('DIXON', 'DICKSONX'),\n                 ('JELLYFISH', 'SMELLYFISH')]:\n        print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n"}
{"id": 58026, "name": "Sum and product puzzle", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n"}
{"id": 58027, "name": "Fairshare between two and more", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n    \n    if num == 0:\n        return [0]\n    result = []\n    while num != 0:\n        num, d = divmod(num, b)\n        result.append(d)\n    return result[::-1]\n\ndef fairshare(b=2):\n    for i in count():\n        yield sum(_basechange_int(i, b)) % b\n\nif __name__ == '__main__':\n    for b in (2, 3, 5, 11):\n        print(f\"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n"}
{"id": 58028, "name": "Two bullet roulette", "Python": "\nimport numpy as np\n\nclass Revolver:\n    \n\n    def __init__(self):\n        \n        self.cylinder = np.array([False] * 6)\n\n    def unload(self):\n        \n        self.cylinder[:] = False\n\n    def load(self):\n        \n        while self.cylinder[1]:\n            self.cylinder[:] = np.roll(self.cylinder, 1)\n        self.cylinder[1] = True\n\n    def spin(self):\n        \n        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))\n\n    def fire(self):\n        \n        shot = self.cylinder[0]\n        self.cylinder[:] = np.roll(self.cylinder, 1)\n        return shot\n\n    def LSLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LSLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.spin()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n    def LLSFSF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        self.spin()\n        if self.fire():\n            return True\n        return False\n\n    def LLSFF(self):\n        \n        self.unload()\n        self.load()\n        self.load()\n        self.spin()\n        if self.fire():\n            return True\n        if self.fire():\n            return True\n        return False\n\n\nif __name__ == '__main__':\n\n    REV = Revolver()\n    TESTCOUNT = 100000\n    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],\n                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],\n                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],\n                           ['load, load, spin, fire, fire', REV.LLSFF]]:\n\n        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT\n        print(\"Method\", name, \"produces\", percentage, \"per cent deaths.\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n    t := cylinder[5]\n    for i := 4; i >= 0; i-- {\n        cylinder[i+1] = cylinder[i]\n    }\n    cylinder[0] = t\n}\n\nfunc unload() {\n    for i := 0; i < 6; i++ {\n        cylinder[i] = false\n    }\n}\n\nfunc load() {\n    for cylinder[0] {\n        rshift()\n    }\n    cylinder[0] = true\n    rshift()\n}\n\nfunc spin() {\n    var lim = 1 + rand.Intn(6)\n    for i := 1; i < lim; i++ {\n        rshift()\n    }\n}\n\nfunc fire() bool {\n    shot := cylinder[0]\n    rshift()\n    return shot\n}\n\nfunc method(s string) int {\n    unload()\n    for _, c := range s {\n        switch c {\n        case 'L':\n            load()\n        case 'S':\n            spin()\n        case 'F':\n            if fire() {\n                return 1\n            }\n        }\n    }\n    return 0\n}\n\nfunc mstring(s string) string {\n    var l []string\n    for _, c := range s {\n        switch c {\n        case 'L':\n            l = append(l, \"load\")\n        case 'S':\n            l = append(l, \"spin\")\n        case 'F':\n            l = append(l, \"fire\")\n        }\n    }\n    return strings.Join(l, \", \")\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := 100000\n    for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n        sum := 0\n        for t := 1; t <= tests; t++ {\n            sum += method(m)\n        }\n        pc := float64(sum) * 100 / float64(tests)\n        fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n    }\n}\n"}
{"id": 58029, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 58030, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n"}
{"id": 58031, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n"}
{"id": 58032, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n"}
{"id": 58033, "name": "Sequence_ nth number with exactly n divisors", "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 primes():\n    ii = 1\n    while True:\n        ii += 1\n        if is_prime(ii):\n            yield ii\n\n\ndef prime(n):\n    generator = primes()\n    for ii in range(n - 1):\n        generator.__next__()\n    return generator.__next__()\n\n\ndef n_divisors(n):\n    ii = 0\n    while True:\n        ii += 1\n        if len(divisors(ii)) == n:\n            yield ii\n\n\ndef sequence(max_n=None):\n    if max_n is not None:\n        for ii in range(1, max_n + 1):\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n    else:\n        ii = 1\n        while True:\n            ii += 1\n            if is_prime(ii):\n                yield prime(ii) ** (ii - 1)\n            else:\n                generator = n_divisors(ii)\n                for jj, out in zip(range(ii - 1), generator):\n                    pass\n                yield generator.__next__()\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 58034, "name": "Sequence_ smallest number with exactly n divisors", "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 sequence(max_n=None):\n    n = 0\n    while True:\n        n += 1\n        ii = 0\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n"}
{"id": 58035, "name": "Pancake numbers", "Python": "\nimport time\n\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Tuple\n\nPancakes = Tuple[int, ...]\n\n\ndef flip(pancakes: Pancakes, position: int) -> Pancakes:\n    \n    return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n    \n    init_stack = tuple(range(1, n + 1))\n    stack_flips = {init_stack: 0}\n    queue = deque([init_stack])\n\n    while queue:\n        stack = queue.popleft()\n        flips = stack_flips[stack] + 1\n\n        for i in range(2, n + 1):\n            flipped = flip(stack, i)\n            if flipped not in stack_flips:\n                stack_flips[flipped] = flips\n                queue.append(flipped)\n\n    return max(stack_flips.items(), key=itemgetter(1))\n\n\nif __name__ == \"__main__\":\n    start = time.time()\n\n    for n in range(1, 10):\n        pancakes, p = pancake(n)\n        print(f\"pancake({n}) = {p:>2}. Example: {list(pancakes)}\")\n\n    print(f\"\\nTook {time.time() - start:.3} seconds.\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58036, "name": "Generate random chess position", "Python": "import random\n\nboard = [[\" \" for x in range(8)] for y in range(8)]\npiece_list = [\"R\", \"N\", \"B\", \"Q\", \"P\"]\n\n\ndef place_kings(brd):\n\twhile True:\n\t\trank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)\n\t\tdiff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]\n\t\tif sum(diff_list) > 2 or set(diff_list) == set([0, 2]):\n\t\t\tbrd[rank_white][file_white], brd[rank_black][file_black] = \"K\", \"k\"\n\t\t\tbreak\n\ndef populate_board(brd, wp, bp):\n\tfor x in range(2):\n\t\tif x == 0:\n\t\t\tpiece_amount = wp\n\t\t\tpieces = piece_list\n\t\telse:\n\t\t\tpiece_amount = bp\n\t\t\tpieces = [s.lower() for s in piece_list]\n\t\twhile piece_amount != 0:\n\t\t\tpiece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)\n\t\t\tpiece = random.choice(pieces)\n\t\t\tif brd[piece_rank][piece_file] == \" \" and pawn_on_promotion_square(piece, piece_rank) == False:\n\t\t\t\tbrd[piece_rank][piece_file] = piece\n\t\t\t\tpiece_amount -= 1\n\ndef fen_from_board(brd):\n\tfen = \"\"\n\tfor x in brd:\n\t\tn = 0\n\t\tfor y in x:\n\t\t\tif y == \" \":\n\t\t\t\tn += 1\n\t\t\telse:\n\t\t\t\tif n != 0:\n\t\t\t\t\tfen += str(n)\n\t\t\t\tfen += y\n\t\t\t\tn = 0\n\t\tif n != 0:\n\t\t\tfen += str(n)\n\t\tfen += \"/\" if fen.count(\"/\") < 7 else \"\"\n\tfen += \" w - - 0 1\\n\"\n\treturn fen\n\ndef pawn_on_promotion_square(pc, pr):\n\tif pc == \"P\" and pr == 0:\n\t\treturn True\n\telif pc == \"p\" and pr == 7:\n\t\treturn True\n\treturn False\n\n\ndef start():\n\tpiece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)\n\tplace_kings(board)\n\tpopulate_board(board, piece_amount_white, piece_amount_black)\n\tprint(fen_from_board(board))\n\tfor x in board:\n\t\tprint(x)\n\n\nstart()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n"}
{"id": 58037, "name": "Esthetic numbers", "Python": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str  \n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n    \n    queue: deque[tuple[int, int]] = deque()\n    queue.extendleft((d, d) for d in range(1, base))\n    while True:\n        num, lsd = queue.pop()\n        yield num\n        new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n        num *= base  \n        queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n    \n    digits: list[str] = []\n    while num:\n        num, d = divmod(num, base)\n        digits.append(\"0123456789abcdef\"[d])\n    return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n    \n    joined = \", \".join(it)\n    lines = wrap(joined, width=width - indent)\n    for line in lines:\n        print(f\"{indent*' '}{line}\")\n    print()\n\n\ndef task_2() -> None:\n    nums: Iterator[int]\n    for base in range(2, 16 + 1):\n        start, stop = 4 * base, 6 * base\n        nums = esthetic_nums(base)\n        nums = islice(nums, start - 1, stop)  \n        print(\n            f\"Base-{base} esthetic numbers from \"\n            f\"index {start} through index {stop} inclusive:\\n\"\n        )\n        pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n    nums: Iterator[int] = esthetic_nums(base)\n    nums = dropwhile(lambda num: num < lower, nums)\n    nums = takewhile(lambda num: num <= upper, nums)\n    print(\n        f\"Base-{base} esthetic numbers with \"\n        f\"magnitude between {lower:,} and {upper:,}:\\n\"\n    )\n    pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n    print(\"======\\nTask 2\\n======\\n\")\n    task_2()\n\n    print(\"======\\nTask 3\\n======\\n\")\n    task_3(1_000, 9_999)\n\n    print(\"======\\nTask 4\\n======\\n\")\n    task_3(100_000_000, 130_000_000)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n"}
{"id": 58038, "name": "Topswops", "Python": ">>> from itertools import permutations\n>>> def f1(p):\n\ti = 0\n\twhile True:\n\t\tp0  = p[0]\n\t\tif p0 == 1: break\n\t\tp[:p0] = p[:p0][::-1]\n\t\ti  += 1\n\treturn i\n\n>>> def fannkuch(n):\n\treturn max(f1(list(p)) for p in permutations(range(1, n+1)))\n\n>>> for n in range(1, 11): print(n,fannkuch(n))\n\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n>>>\n", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n"}
{"id": 58039, "name": "Old Russian measure of length", "Python": "from sys import argv\n \nunit2mult = {\"arshin\": 0.7112, \"centimeter\": 0.01,     \"diuym\":   0.0254,\n             \"fut\":    0.3048, \"kilometer\":  1000.0,   \"liniya\":  0.00254,\n             \"meter\":  1.0,    \"milia\":      7467.6,   \"piad\":    0.1778,\n             \"sazhen\": 2.1336, \"tochka\":     0.000254, \"vershok\": 0.04445,\n             \"versta\": 1066.8}\n \nif __name__ == '__main__':\n    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'\n    try:\n        value = float(argv[1])\n    except:\n        print('ERROR. First argument must be a (float) number')\n        raise\n    unit = argv[2]\n    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' \n                                + ' '.join(unit2mult.keys()) )\n\n    print(\"%g %s to:\" % (value, unit))\n    for unt, mlt in sorted(unit2mult.items()):\n        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n"}
{"id": 58040, "name": "Rate counter", "Python": "import subprocess\nimport time\n\nclass Tlogger(object):\n    def __init__(self):\n        self.counts = 0\n        self.tottime = 0.0\n        self.laststart = 0.0\n        self.lastreport = time.time()\n\n    def logstart(self):\n        self.laststart = time.time()\n\n    def logend(self):\n        self.counts +=1\n        self.tottime += (time.time()-self.laststart)\n        if (time.time()-self.lastreport)>5.0:   \n           self.report()\n\n    def report(self):\n        if ( self.counts > 4*self.tottime):\n            print \"Subtask execution rate: %f times/second\"% (self.counts/self.tottime);\n        else:\n            print \"Average execution time: %f seconds\"%(self.tottime/self.counts);\n        self.lastreport = time.time()\n\n\ndef taskTimer( n, subproc_args ):\n    logger = Tlogger()\n\n    for x in range(n):\n        logger.logstart()\n        p = subprocess.Popen(subproc_args)\n        p.wait()\n        logger.logend()\n    logger.report()\n\n\nimport timeit\nimport sys\n\ndef main( ):\n\n    \n    s = \n    timer = timeit.Timer(s)\n    rzlts = timer.repeat(5, 5000)\n    for t in rzlts:\n        print \"Time for 5000 executions of statement = \",t\n    \n    \n    print \"\n    print \"Command:\",sys.argv[2:]\n    print \"\"\n    for k in range(3):\n       taskTimer( int(sys.argv[1]), sys.argv[2:])\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n"}
{"id": 58041, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "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 sequence(max_n=None):\n    previous = 0\n    n = 0\n    while True:\n        n += 1\n        ii = previous\n        if max_n is not None:\n            if n > max_n:\n                break\n        while True:\n            ii += 1\n            if len(divisors(ii)) == n:\n                yield ii\n                previous = ii\n                break\n\n\nif __name__ == '__main__':\n    for item in sequence(15):\n        print(item)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58042, "name": "Padovan sequence", "Python": "from math import floor\nfrom collections import deque\nfrom typing import Dict, Generator\n\n\ndef padovan_r() -> Generator[int, None, None]:\n    last = deque([1, 1, 1], 4)\n    while True:\n        last.append(last[-2] + last[-3])\n        yield last.popleft()\n\n_p, _s = 1.324717957244746025960908854, 1.0453567932525329623\n\ndef padovan_f(n: int) -> int:\n    return floor(_p**(n-1) / _s + .5)\n\ndef padovan_l(start: str='A',\n             rules: Dict[str, str]=dict(A='B', B='C', C='AB')\n             ) -> Generator[str, None, None]:\n    axiom = start\n    while True:\n        yield axiom\n        axiom = ''.join(rules[ch] for ch in axiom)\n\n\nif __name__ == \"__main__\":\n    from itertools import islice\n\n    print(\"The first twenty terms of the sequence.\")\n    print(str([padovan_f(n) for n in range(20)])[1:-1])\n\n    r_generator = padovan_r()\n    if all(next(r_generator) == padovan_f(n) for n in range(64)):\n        print(\"\\nThe recurrence and floor based algorithms match to n=63 .\")\n    else:\n        print(\"\\nThe recurrence and floor based algorithms DIFFER!\")\n\n    print(\"\\nThe first 10 L-system string-lengths and strings\")\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    print('\\n'.join(f\"  {len(string):3} {repr(string)}\"\n                    for string in islice(l_generator, 10)))\n\n    r_generator = padovan_r()\n    l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))\n    if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)\n           for n in range(32)):\n        print(\"\\nThe L-system, recurrence and floor based algorithms match to n=31 .\")\n    else:\n        print(\"\\nThe L-system, recurrence and floor based algorithms DIFFER!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n"}
{"id": 58043, "name": "Pythagoras tree", "Python": "def setup():\n    size(800, 400)\n    background(255)\n    stroke(0, 255, 0)\n    tree(width / 2.3, height, width / 1.8, height, 10)\n\n\ndef tree(x1, y1, x2, y2, depth):\n    if depth <= 0: return\n    dx = (x2 - x1)\n    dy = (y1 - y2)\n\n    x3 = (x2 - dy)\n    y3 = (y2 - dx)\n    x4 = (x1 - dy)\n    y4 = (y1 - dx)\n    x5 = (x4 + 0.5 * (dx - dy))\n    y5 = (y4 - 0.5 * (dx + dy))\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x1, y1)\n    vertex(x2, y2)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x1, y1)\n    endShape()\n\n    \n    beginShape()\n    fill(0.0, 255.0 / depth, 0.0)\n    vertex(x3, y3)\n    vertex(x4, y4)\n    vertex(x5, y5)\n    vertex(x3, y3)\n    endShape()\n\n    tree(x4, y4, x5, y5, depth - 1)\n    tree(x5, y5, x3, y3, depth - 1)\n", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n"}
{"id": 58044, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n"}
{"id": 58045, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Python": "\na1 = [0, 1403580, -810728]\nm1 = 2**32 - 209\n\na2 = [527612, 0, -1370589]\nm2 = 2**32 - 22853\n\nd = m1 + 1\n\nclass MRG32k3a():\n    \n    def __init__(self, seed_state=123):\n        self.seed(seed_state)\n    \n    def seed(self, seed_state):\n        assert 0 <seed_state < d, f\"Out of Range 0 x < {d}\"\n        self.x1 = [seed_state, 0, 0]\n        self.x2 = [seed_state, 0, 0]\n        \n    def next_int(self):\n        \"return random int in range 0..d\"\n        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1\n        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2\n        self.x1 = [x1i] + self.x1[:2]\n        self.x2 = [x2i] + self.x2[:2]\n\n        z = (x1i - x2i) % m1\n        answer = (z + 1)\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / d\n    \n\nif __name__ == '__main__':\n    random_gen = MRG32k3a()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 58046, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 58047, "name": "Colorful numbers", "Python": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n    if 0 <= n < 10:\n        return True\n    dig = [int(c) for c in str(n)]\n    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n        return False\n    products = list(set(dig))\n    for i in range(len(dig)):\n        for j in range(i+2, len(dig)+1):\n            p = prod(dig[i:j])\n            if p in products:\n                return False\n            products.append(p)\n\n    largest[0] = max(n, largest[0])\n    return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n    for j in range(25):\n        if iscolorful(i + j):\n            print(f'{i + j: 5,}', end='')\n    print()\n\ncsum = 0\nfor i in range(8):\n    j = 0 if i == 0 else 10**i\n    k = 10**(i+1) - 1\n    n = sum(iscolorful(x) for x in range(j, k+1))\n    csum += n\n    print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 58048, "name": "Biorhythms", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n"}
{"id": 58049, "name": "Biorhythms", "Python": "\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n    \n    \n    \n    \n    print(\"Born: \"+birthdate+\" Target: \"+targetdate)    \n    \n    \n    \n    birthdate = date.fromisoformat(birthdate)\n    targetdate = date.fromisoformat(targetdate)\n    \n    \n    \n    days = (targetdate - birthdate).days\n    \n    print(\"Day: \"+str(days))\n    \n    \n    \n    cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n    cycle_lengths = [23, 28, 33]\n    quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n                   (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n    \n    for i in range(3):\n        label = cycle_labels[i]\n        length = cycle_lengths[i]\n        position = days % length\n        quadrant = int(floor((4 * position) / length))\n        percentage = int(round(100 * sin(2 * pi * position / length),0))\n        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n        trend, next = quadrants[quadrant]\n        \n        if percentage > 95:\n            description = \"peak\"\n        elif percentage < -95:\n             description = \"valley\"\n        elif abs(percentage) < 5:\n             description = \"critical transition\"\n        else:\n             description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n        print(label+\" day \"+str(position)+\": \"+description)\n    \n    \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n"}
{"id": 58050, "name": "Table creation_Postal addresses", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n"}
{"id": 58051, "name": "Sine wave", "Python": "\n\nimport os\nfrom math import pi, sin\n\n\nau_header = bytearray(\n            [46, 115, 110, 100,   \n              0,   0,   0,  24,   \n            255, 255, 255, 255,   \n              0,   0,   0,   3,   \n              0,   0, 172,  68,   \n              0,   0,   0,   1])  \n\ndef f(x, freq):\n    \"Compute sine wave as 16-bit integer\"\n    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536\n\ndef play_sine(freq=440, duration=5, oname=\"pysine.au\"):\n    \"Play a sine wave for `duration` seconds\"\n    out = open(oname, 'wb')\n    out.write(au_header)\n    v = [f(x, freq) for x in range(duration * 44100 + 1)]\n    s = []\n    for i in v:\n        s.append(i >> 8)\n        s.append(i % 256)\n    out.write(bytearray(s))\n    out.close()\n    os.system(\"vlc \" + oname)   \n\nplay_sine()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os/exec\"\n)\n\nfunc main() {\n    synthType := \"sine\"\n    duration := \"5\"\n    frequency := \"440\"\n    cmd := exec.Command(\"play\", \"-n\", \"synth\", duration, synthType, frequency)\n    err := cmd.Run()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58052, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n"}
{"id": 58053, "name": "Compiler_code generator", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"\n        return None\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n"}
{"id": 58054, "name": "Include a file", "Python": "import one \n\n\n\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 58055, "name": "Include a file", "Python": "import one \n\n\n\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n"}
{"id": 58056, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n"}
{"id": 58057, "name": "Numeric error propagation", "Python": "from collections import namedtuple\nimport math\n \nclass I(namedtuple('Imprecise', 'value, delta')):\n    'Imprecise type: I(value=0.0, delta=0.0)' \n \n    __slots__ = () \n \n    def __new__(_cls, value=0.0, delta=0.0):\n        'Defaults to 0.0 ± delta'\n        return super().__new__(_cls, float(value), abs(float(delta)))\n \n    def reciprocal(self):\n        return I(1. / self.value, self.delta / (self.value**2)) \n \n    def __str__(self):\n        'Shorter form of Imprecise as string'\n        return 'I(%g, %g)' % self\n \n    def __neg__(self):\n        return I(-self.value, self.delta)\n \n    def __add__(self, other):\n        if type(other) == I:\n            return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value + c, self.delta)\n\n    def __sub__(self, other):\n        return self + (-other)\n \n    def __radd__(self, other):\n        return I.__add__(self, other)\n \n    def __mul__(self, other):\n        if type(other) == I:\n            \n            \n            a1,b1 = self\n            a2,b2 = other\n            f = a1 * a2\n            return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value * c, self.delta * c)\n \n    def __pow__(self, other):\n        if type(other) == I:\n            return NotImplemented\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        f = self.value ** c\n        return I(f, f * c * (self.delta / self.value))\n \n    def __rmul__(self, other):\n        return I.__mul__(self, other)\n \n    def __truediv__(self, other):\n        if type(other) == I:\n            return self.__mul__(other.reciprocal())\n        try:\n            c = float(other)\n        except:\n            return NotImplemented\n        return I(self.value / c, self.delta / c)\n \n    def __rtruediv__(self, other):\n        return other * self.reciprocal()\n \n    __div__, __rdiv__ = __truediv__, __rtruediv__\n \nImprecise = I\n\ndef distance(p1, p2):\n    x1, y1 = p1\n    x2, y2 = p2\n    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n \nx1 = I(100, 1.1)\nx2 = I(200, 2.2)\ny1 = I( 50, 1.2)\ny2 = I(100, 2.3)\n\np1, p2 = (x1, y1), (x2, y2)\nprint(\"Distance between points\\n  p1: %s\\n  and p2: %s\\n  = %r\" % (\n      p1, p2, distance(p1, p2)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n"}
{"id": 58058, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n"}
{"id": 58059, "name": "List rooted trees", "Python": "def bags(n,cache={}):\n\tif not n: return [(0, \"\")]\n\n\tupto = sum([bags(x) for x in range(n-1, 0, -1)], [])\n\treturn [(c+1, '('+s+')') for c,s in bagchain((0, \"\"), n-1, upto)]\n\ndef bagchain(x, n, bb, start=0):\n\tif not n: return [x]\n\n\tout = []\n\tfor i in range(start, len(bb)):\n\t\tc,s = bb[i]\n\t\tif c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)\n\treturn out\n\n\ndef replace_brackets(s):\n\tdepth,out = 0,[]\n\tfor c in s:\n\t\tif c == '(':\n\t\t\tout.append(\"([{\"[depth%3])\n\t\t\tdepth += 1\n\t\telse:\n\t\t\tdepth -= 1\n\t\t\tout.append(\")]}\"[depth%3])\n\treturn \"\".join(out)\n\nfor x in bags(5): print(replace_brackets(x[1]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n"}
{"id": 58060, "name": "Documentation", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n"}
{"id": 58061, "name": "Table creation", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n"}
{"id": 58062, "name": "Table creation", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute()\n<sqlite3.Cursor object at 0x013263B0>\n>>> \nc.execute()\n\n<sqlite3.Cursor object at 0x013263B0>\n>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n         ]:\n\tc.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\t\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n<sqlite3.Cursor object at 0x013263B0>\n>>> \n>>> c = conn.cursor()\n>>> c.execute('select * from stocks order by price')\n<sqlite3.Cursor object at 0x01326530>\n>>> for row in c:\n\tprint row\n\n\t\n(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)\n(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)\n(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)\n(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)\n>>>\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n"}
{"id": 58063, "name": "Problem of Apollonius", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n"}
{"id": 58064, "name": "Append numbers at same position in strings", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n"}
{"id": 58065, "name": "Append numbers at same position in strings", "Python": "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]\nlist3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]\n\nprint([\n    ''.join(str(n) for n in z) for z\n    in zip(list1, list2, list3)\n])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n"}
{"id": 58066, "name": "Longest common suffix", "Python": "\n\nfrom itertools import takewhile\nfrom functools import reduce\n\n\n\ndef longestCommonSuffix(xs):\n    \n    def allSame(cs):\n        h = cs[0]\n        return all(h == c for c in cs[1:])\n\n    def firstCharPrepended(s, cs):\n        return cs[0] + s\n    return reduce(\n        firstCharPrepended,\n        takewhile(\n            allSame,\n            zip(*(reversed(x) for x in xs))\n        ),\n        ''\n    )\n\n\n\n\ndef main():\n    \n\n    samples = [\n        [\n            \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n            \"Thursday\", \"Friday\", \"Saturday\"\n        ], [\n            \"Sondag\", \"Maandag\", \"Dinsdag\", \"Woensdag\",\n            \"Donderdag\", \"Vrydag\", \"Saterdag\"\n        ]\n    ]\n    for xs in samples:\n        print(\n            longestCommonSuffix(xs)\n        )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n"}
{"id": 58067, "name": "Chat server", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n"}
{"id": 58068, "name": "Idiomatically determine all the lowercase and uppercase letters", "Python": "classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,\n           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,\n           str.isspace, str.istitle)\n\nfor stringclass in classes:\n    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))\n    print('\\nString class %s has %i characters the first of which are:\\n  %r'\n          % (stringclass.__name__, len(chars), chars[:100]))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n"}
{"id": 58069, "name": "Sum of elements below main diagonal of matrix", "Python": "from numpy import array, tril, sum\n\nA = [[1,3,7,8,10],\n    [2,4,16,14,4],\n    [3,1,9,18,11],\n    [12,14,17,18,20],\n    [7,1,3,9,5]]\n\nprint(sum(tril(A, -1)))   \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n"}
{"id": 58070, "name": "Retrieve and search chat history", "Python": "\nimport datetime\nimport re\nimport urllib.request\nimport sys\n\ndef get(url):\n    with urllib.request.urlopen(url) as response:\n       html = response.read().decode('utf-8')\n    if re.match(r'<!Doctype HTML[\\s\\S]*<Title>URL Not Found</Title>', html):\n        return None\n    return html\n\ndef main():\n    template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'\n    today = datetime.datetime.utcnow()\n    back = 10\n    needle = sys.argv[1]\n    \n    \n    \n    for i in range(-back, 2):\n        day = today + datetime.timedelta(days=i)\n        url = day.strftime(template)\n        haystack = get(url)\n        if haystack:\n            mentions = [x for x in haystack.split('\\n') if needle in x]\n            if mentions:\n                print('{}\\n------\\n{}\\n------\\n'\n                          .format(url, '\\n'.join(mentions)))\n\nmain()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc get(url string) (res string, err error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n\nfunc grep(needle string, haystack string) (res []string) {\n\tfor _, line := range strings.Split(haystack, \"\\n\") {\n\t\tif strings.Contains(line, needle) {\n\t\t\tres = append(res, line)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc genUrl(i int, loc *time.Location) string {\n\tdate := time.Now().In(loc).AddDate(0, 0, i)\n\treturn date.Format(\"http:\n}\n\nfunc main() {\n\tneedle := os.Args[1]\n\tback := -10\n\tserverLoc, err := time.LoadLocation(\"Europe/Berlin\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor i := back; i <= 0; i++ {\n\t\turl := genUrl(i, serverLoc)\n\t\tcontents, err := get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfound := grep(needle, contents)\n\t\tif len(found) > 0 {\n\t\t\tfmt.Printf(\"%v\\n------\\n\", url)\n\t\t\tfor _, line := range found {\n\t\t\t\tfmt.Printf(\"%v\\n\", line)\n\t\t\t}\n\t\t\tfmt.Printf(\"------\\n\\n\")\n\t\t}\n\t}\n}\n"}
{"id": 58071, "name": "Rosetta Code_Rank languages by number of users", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n"}
{"id": 58072, "name": "Rosetta Code_Rank languages by number of users", "Python": "\n\nimport requests\n\n\nURL = \"http://rosettacode.org/mw/api.php\"\n\n\nPARAMS = {\n    \"action\": \"query\",\n    \"format\": \"json\",\n    \"formatversion\": 2,\n    \"generator\": \"categorymembers\",\n    \"gcmtitle\": \"Category:Language users\",\n    \"gcmlimit\": 500,\n    \"prop\": \"categoryinfo\",\n}\n\n\ndef fetch_data():\n    counts = {}\n    continue_ = {\"continue\": \"\"}\n\n    \n    \n    while continue_:\n        resp = requests.get(URL, params={**PARAMS, **continue_})\n        resp.raise_for_status()\n\n        data = resp.json()\n\n        \n        counts.update(\n            {\n                p[\"title\"]: p.get(\"categoryinfo\", {}).get(\"size\", 0)\n                for p in data[\"query\"][\"pages\"]\n            }\n        )\n\n        continue_ = data.get(\"continue\", {})\n\n    return counts\n\n\nif __name__ == \"__main__\":\n    \n    counts = fetch_data()\n\n    \n    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]\n\n    \n    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)\n\n    \n    for i, lang in enumerate(top_languages):\n        print(f\"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n"}
{"id": 58073, "name": "Multiline shebang", "Python": "\n\"exec\" \"python\" \"$0\"\n\nprint \"Hello World\"\n", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n"}
{"id": 58074, "name": "Multiline shebang", "Python": "\n\"exec\" \"python\" \"$0\"\n\nprint \"Hello World\"\n", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n"}
{"id": 58075, "name": "Terminal control_Unicode output", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n"}
{"id": 58076, "name": "Terminal control_Unicode output", "Python": "import sys\n\nif \"UTF-8\" in sys.stdout.encoding:\n    print(\"△\")\nelse:\n    raise Exception(\"Terminal can't handle UTF-8\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n"}
{"id": 58077, "name": "Find adjacent primes which differ by a square integer", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n"}
{"id": 58078, "name": "Find adjacent primes which differ by a square integer", "Python": "import math\nprint(\"working...\")\nlimit = 1000000\nPrimes = []\noldPrime = 0\nnewPrime = 0\nx = 0\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(x):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit):\n    if isPrime(n):\n       Primes.append(n)\n\nfor n in range(2,len(Primes)):\n    pr1 = Primes[n]\n    pr2 = Primes[n-1]\n    diff = pr1 - pr2\n    flag = issquare(diff)\n    if (flag == 1 and diff > 36):\n       print(str(pr1) + \" \" + str(pr2) + \" diff = \" + str(diff))\n\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n"}
{"id": 58079, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 58080, "name": "Truncate a file", "Python": "def truncate_file(name, length):\n    if not os.path.isfile(name):\n        return False\n    if length >= os.path.getsize(name):\n        return False\n    with open(name, 'ab') as f:\n        f.truncate(length)\n    return True\n", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n"}
{"id": 58081, "name": "Video display modes", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58082, "name": "Video display modes", "Python": "import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58083, "name": "Keyboard input_Flush the keyboard buffer", "Python": "def flush_input():\n    try:\n        import msvcrt\n        while msvcrt.kbhit():\n            msvcrt.getch()\n    except ImportError:\n        import sys, termios\n        termios.tcflush(sys.stdin, termios.TCIOFLUSH)\n", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    _, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    gc.FlushInput()\n}\n"}
{"id": 58084, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 58085, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 58086, "name": "Numerical integration_Adaptive Simpson's method", "Python": "\n\n\n\nimport math\n\nimport collections\ntriple = collections.namedtuple('triple', 'm fm simp')\n\ndef _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:\n    \n    m = a + (b - a) / 2\n    fm = f(m)\n    simp = abs(b - a) / 6 * (fa + 4*fm + fb)\n    return triple(m, fm, simp,)\n \ndef _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:\n    \n    lt = _quad_simpsons_mem(f, a, fa, m, fm)\n    rt = _quad_simpsons_mem(f, m, fm, b, fb)\n    delta = lt.simp + rt.simp - whole\n    return (lt.simp + rt.simp + delta/15\n        if (abs(delta) <= eps * 15) else\n            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)\n    )\n\ndef quad_asr(f: callable, a: float, b: float, eps: float)->float:\n    \n    fa = f(a)\n    fb = f(b)\n    t = _quad_simpsons_mem(f, a, fa, b, fb)\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)\n\ndef main():\n    (a, b,) = (0.0, 1.0,)\n    sinx = quad_asr(math.sin, a, b, 1e-09);\n    print(\"Simpson's integration of sine from {} to {} = {}\\n\".format(a, b, sinx))\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n"}
{"id": 58087, "name": "FASTA format", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n"}
{"id": 58088, "name": "Cousin primes", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n"}
{"id": 58089, "name": "Cousin primes", "Python": "\n\nfrom itertools import chain, takewhile\n\n\n\ndef cousinPrimes():\n    \n    def go(x):\n        n = 4 + x\n        return [(x, n)] if isPrime(n) else []\n\n    return chain.from_iterable(\n        map(go, primes())\n    )\n\n\n\n\ndef main():\n    \n\n    pairs = list(\n        takewhile(\n            lambda ab: 1000 > ab[1],\n            cousinPrimes()\n        )\n    )\n\n    print(f'{len(pairs)} cousin pairs below 1000:\\n')\n    print(\n        spacedTable(list(\n            chunksOf(4)([\n                repr(x) for x in pairs\n            ])\n        ))\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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\ndef listTranspose(xss):\n    \n    def go(xss):\n        if xss:\n            h, *t = xss\n            return (\n                [[h[0]] + [xs[0] for xs in t if xs]] + (\n                    go([h[1:]] + [xs[1:] for xs in t])\n                )\n            ) if h and isinstance(h, list) else go(t)\n        else:\n            return []\n    return go(xss)\n\n\n\ndef spacedTable(rows):\n    \n    columnWidths = [\n        len(str(row[-1])) for row in listTranspose(rows)\n    ]\n    return '\\n'.join([\n        ' '.join(\n            map(\n                lambda w, s: s.rjust(w, ' '),\n                columnWidths, row\n            )\n        ) for row in rows\n    ])\n\n\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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n"}
{"id": 58090, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 58091, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 58092, "name": "Check input device is a terminal", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n"}
{"id": 58093, "name": "Check input device is a terminal", "Python": "from sys import stdin\nif stdin.isatty():\n    print(\"Input comes from tty.\")\nelse:\n    print(\"Input doesn't come from tty.\")\n", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n"}
{"id": 58094, "name": "Window creation_X11", "Python": "from Xlib import X, display\n\nclass Window:\n    def __init__(self, display, msg):\n        self.display = display\n        self.msg = msg\n        \n        self.screen = self.display.screen()\n        self.window = self.screen.root.create_window(\n            10, 10, 100, 100, 1,\n            self.screen.root_depth,\n            background_pixel=self.screen.white_pixel,\n            event_mask=X.ExposureMask | X.KeyPressMask,\n            )\n        self.gc = self.window.create_gc(\n            foreground = self.screen.black_pixel,\n            background = self.screen.white_pixel,\n            )\n\n        self.window.map()\n\n    def loop(self):\n        while True:\n            e = self.display.next_event()\n                \n            if e.type == X.Expose:\n                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n                self.window.draw_text(self.gc, 10, 50, self.msg)\n            elif e.type == X.KeyPress:\n                raise SystemExit\n\n                \nif __name__ == \"__main__\":\n    Window(display.Display(), \"Hello, World!\").loop()\n", "Go": "package main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"github.com/jezek/xgb\"\n    \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n    \n    X, err := xgb.NewConn()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    points := []xproto.Point{\n        {10, 10},\n        {10, 20},\n        {20, 10},\n        {20, 20}};\n\n    polyline := []xproto.Point{\n        {50, 10},\n        { 5, 20},     \n        {25,-20},\n        {10, 10}};\n\n    segments := []xproto.Segment{\n        {100, 10, 140, 30},\n        {110, 25, 130, 60}};\n\n    rectangles := []xproto.Rectangle{\n        { 10, 50, 40, 20},\n        { 80, 50, 10, 40}};\n\n    arcs := []xproto.Arc{\n        {10, 100, 60, 40, 0, 90 << 6},\n        {90, 100, 55, 40, 0, 270 << 6}};\n\n    setup := xproto.Setup(X)\n    \n    screen := setup.DefaultScreen(X)\n\n    \n    foreground, _ := xproto.NewGcontextId(X)\n    mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n    values := []uint32{screen.BlackPixel, 0}\n    xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n    \n    win, _ := xproto.NewWindowId(X)\n    winDrawable := xproto.Drawable(win)\n\n    \n    mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n    values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n    xproto.CreateWindow(X,                  \n            screen.RootDepth,               \n            win,                            \n            screen.Root,                    \n            0, 0,                           \n            150, 150,                       \n            10,                             \n            xproto.WindowClassInputOutput,  \n            screen.RootVisual,              \n            mask, values)                   \n\n    \n    xproto.MapWindow(X, win)\n\n    for {\n        evt, err := X.WaitForEvent()\n        switch evt.(type) {\n            case xproto.ExposeEvent:\n                \n                xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n                \n                xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n                \n                xproto.PolySegment(X, winDrawable, foreground, segments)\n\n                \n                xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n                \n                xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n            default:\n                \n        }\n\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    return\n}\n"}
{"id": 58095, "name": "Elementary cellular automaton_Random number generator", "Python": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n    cells = '1' + '0' * (lencells - 1)\n    gen = eca(cells, 30)\n    while True:\n        yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n    print([b for i,b in zip(range(10), rule30bytes())])\n", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n"}
{"id": 58096, "name": "Terminal control_Dimensions", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n"}
{"id": 58097, "name": "Finite state machine", "Python": "\n\nstates = {  'ready':{\n                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',\n                'responses' : ['d','q']},\n            'waiting':{\n                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',\n                'responses' : ['s','r']},\n            'dispense' : {\n                'prompt' : 'Machine dispensing: please (r)emove product',\n                'responses' : ['r']},\n            'refunding' : {\n                'prompt' : 'Refunding money',\n                'responses' : []},\n            'exit' :{}\n          }\ntransitions = { 'ready': { \n                    'd': 'waiting',\n                    'q': 'exit'},\n                'waiting' : {\n                    's' : 'dispense',\n                    'r' : 'refunding'},\n                'dispense' : {\n                    'r' : 'ready'},\n                'refunding' : {\n                    '' : 'ready'}}\n\ndef Acceptor(prompt, valids):\n    \n    if not valids: \n        print(prompt)\n        return ''\n    else:\n        while True:\n            resp = input(prompt)[0].lower()\n            if resp in valids:\n                return resp\n\ndef finite_state_machine(initial_state, exit_state):\n    response = True\n    next_state = initial_state\n    current_state = states[next_state]\n    while response != exit_state:\n        response = Acceptor(current_state['prompt'], current_state['responses'])\n        next_state = transitions[next_state][response]\n        current_state = states[next_state]\n\nif __name__ == \"__main__\":\n    finite_state_machine('ready','q')\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n"}
{"id": 58098, "name": "Vibrating rectangles", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n"}
{"id": 58099, "name": "Vibrating rectangles", "Python": "import turtle\nfrom itertools import cycle\nfrom time import sleep\n\ndef rect(t, x, y):\n    x2, y2 = x/2, y/2\n    t.setpos(-x2, -y2)\n    t.pendown()\n    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: \n        t.goto(pos)\n    t.penup()\n\ndef rects(t, colour, wait_between_rect=0.1):\n    for x in range(550, 0, -25):\n        t.color(colour)\n        rect(t, x, x*.75)\n        sleep(wait_between_rect)\n\ntl=turtle.Turtle()\nscreen=turtle.Screen()\nscreen.setup(620,620)\nscreen.bgcolor('black')\nscreen.title('Rosetta Code Vibrating Rectangles')\ntl.pensize(3)\ntl.speed(0)\ntl.penup()\ntl.ht() \ncolours = 'red green blue orange white yellow'.split()\nfor colour in cycle(colours):\n    rects(tl, colour)\n    sleep(0.5)\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n"}
{"id": 58100, "name": "Last list item", "Python": "\n\ndef add_least_reduce(lis):\n    \n    while len(lis) > 1:\n        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))\n        print('Interim list:', lis)\n    return lis\n\nLIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]\n\nprint(LIST, ' ==> ', add_least_reduce(LIST.copy()))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}\n    for len(a) > 1 {\n        sort.Ints(a)\n        fmt.Println(\"Sorted list:\", a)\n        sum := a[0] + a[1]\n        fmt.Printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum)\n        a = append(a, sum)\n        a = a[2:]\n    }\n    fmt.Println(\"Last item is\", a[0], \"\\b.\")\n}\n"}
{"id": 58101, "name": "Minimum numbers of three lists", "Python": "numbers1 = [5,45,23,21,67]\nnumbers2 = [43,22,78,46,38]\nnumbers3 = [9,98,12,98,53]\n\nnumbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]\n\nprint(numbers)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 98, 53}\n    numbers := [5]int{}\n    for n := 0; n < 5; n++ {\n        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])\n    }\n    fmt.Println(numbers)\n}\n"}
{"id": 58102, "name": "Minimum numbers of three lists", "Python": "numbers1 = [5,45,23,21,67]\nnumbers2 = [43,22,78,46,38]\nnumbers3 = [9,98,12,98,53]\n\nnumbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]\n\nprint(numbers)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 98, 53}\n    numbers := [5]int{}\n    for n := 0; n < 5; n++ {\n        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])\n    }\n    fmt.Println(numbers)\n}\n"}
{"id": 58103, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 58104, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n"}
{"id": 58105, "name": "Pseudo-random numbers_PCG32", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nCONST = 6364136223846793005\n\n\nclass PCG32():\n    \n    def __init__(self, seed_state=None, seed_sequence=None):\n        if all(type(x) == int for x in (seed_state, seed_sequence)):\n            self.seed(seed_state, seed_sequence)\n        else:\n            self.state = self.inc = 0\n    \n    def seed(self, seed_state, seed_sequence):\n        self.state = 0\n        self.inc = ((seed_sequence << 1) | 1) & mask64\n        self.next_int()\n        self.state = (self.state + seed_state)\n        self.next_int()\n        \n    def next_int(self):\n        \"return random 32 bit unsigned int\"\n        old = self.state\n        self.state = ((old * CONST) + self.inc) & mask64\n        xorshifted = (((old >> 18) ^ old) >> 27) & mask32\n        rot = (old >> 59) & mask32\n        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n        answer = answer &mask32\n        \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = PCG32()\n    random_gen.seed(42, 54)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321, 1)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 58106, "name": "Deconvolution_1D", "Python": "def ToReducedRowEchelonForm( M ):\n    if not M: return\n    lead = 0\n    rowCount = len(M)\n    columnCount = len(M[0])\n    for r in range(rowCount):\n        if lead >= columnCount:\n            return\n        i = r\n        while M[i][lead] == 0:\n            i += 1\n            if i == rowCount:\n                i = r\n                lead += 1\n                if columnCount == lead:\n                    return\n        M[i],M[r] = M[r],M[i]\n        lv = M[r][lead]\n        M[r] = [ mrx / lv for mrx in M[r]]\n        for i in range(rowCount):\n            if i != r:\n                lv = M[i][lead]\n                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]\n        lead += 1\n    return M\n \ndef pmtx(mtx):\n    print ('\\n'.join(''.join(' %4s' % col for col in row) for row in mtx))\n \ndef convolve(f, h):\n    g = [0] * (len(f) + len(h) - 1)\n    for hindex, hval in enumerate(h):\n        for findex, fval in enumerate(f):\n            g[hindex + findex] += fval * hval\n    return g\n\ndef deconvolve(g, f):\n    lenh = len(g) - len(f) + 1\n    mtx = [[0 for x in range(lenh+1)] for y in g]\n    for hindex in range(lenh):\n        for findex, fval in enumerate(f):\n            gindex = hindex + findex\n            mtx[gindex][hindex] = fval\n    for gindex, gval in enumerate(g):        \n        mtx[gindex][lenh] = gval\n    ToReducedRowEchelonForm( mtx )\n    return [mtx[i][lenh] for i in range(lenh)]  \n\nif __name__ == '__main__':\n    h = [-8,-9,-3,-1,-6,7]\n    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]\n    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]\n    assert convolve(f,h) == g\n    assert deconvolve(g, f) == h\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    h := []float64{-8, -9, -3, -1, -6, 7}\n    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n        96, 31, 55, 36, 29, -43, -7}\n    fmt.Println(h)\n    fmt.Println(deconv(g, f))\n    fmt.Println(f)\n    fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n    h := make([]float64, len(g)-len(f)+1)\n    for n := range h {\n        h[n] = g[n]\n        var lower int\n        if n >= len(f) {\n            lower = n - len(f) + 1\n        }\n        for i := lower; i < n; i++ {\n            h[n] -= h[i] * f[n-i]\n        }\n        h[n] /= f[0]\n    }\n    return h\n}\n"}
{"id": 58107, "name": "Bitmap_PPM conversion through a pipe", "Python": "\n\nfrom PIL import Image\n\nim = Image.open(\"boxes_1.ppm\")\nim.save(\"boxes_1.jpg\")\n", "Go": "package main\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    b := raster.NewBitmap(400, 300)\n    \n    b.FillRgb(0xc08040)\n    for i := 0; i < 2000; i++ {\n        b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)\n    }\n    for x := 0; x < 400; x++ {\n        for y := 240; y < 245; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for y := 260; y < 265; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n    for y := 0; y < 300; y++ {\n        for x := 80; x < 85; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for x := 95; x < 100; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n\n    \n    c := exec.Command(\"cjpeg\", \"-outfile\", \"pipeout.jpg\")\n    pipe, err := c.StdinPipe()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = c.Start()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = b.WritePpmTo(pipe)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = pipe.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58108, "name": "Bitcoin_public point to address", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n"}
{"id": 58109, "name": "Bitcoin_public point to address", "Python": "\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n    return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n    c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n    r = hashlib.new('ripemd160')\n    r.update(hashlib.sha256(c).digest())\n    c = b'\\x00' + r.digest()\n    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n    print(public_point_to_address(\n        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))\n", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n"}
{"id": 58110, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 58111, "name": "NYSIIS", "Python": "import re\n\n_vowels = 'AEIOU'\n\ndef replace_at(text, position, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text[position:].startswith(f):\n            return ''.join([text[:position],\n                            t,\n                            text[position+len(f):]])\n    return text\n\ndef replace_end(text, fromlist, tolist):\n    for f, t in zip(fromlist, tolist):\n        if text.endswith(f):\n            return text[:-len(f)] + t\n    return text\n\ndef nysiis(name):\n    name = re.sub(r'\\W', '', name).upper()\n    name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],\n                               ['MCC', 'N',  'C', 'FF', 'FF', 'SSS'])\n    name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],\n                             ['Y',  'Y',  'D',  'D',  'D',  'D',  'D'])\n    key, key1 = name[0], ''\n    i = 1\n    while i < len(name):\n        \n        n_1, n = name[i-1], name[i]\n        n1_ = name[i+1] if i+1 < len(name) else ''\n        name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)\n        name = replace_at(name, i, 'QZM', 'GSN')\n        name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])\n        name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])\n        if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):\n            name = ''.join([name[:i], n_1, name[i+1:]])\n        if n == 'W' and n_1 in _vowels:\n            name = ''.join([name[:i], 'A', name[i+1:]])\n        if key and key[-1] != name[i]:\n            key += name[i]\n        i += 1\n    key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])\n    return key1 + key\n\nif __name__ == '__main__':\n    names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',\n             'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',\n             'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',\n             'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',\n             \"O'Banion\", \"O'Brien\", 'Richards', 'Silva', 'Watkins',\n             'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',\n             'knight', 'mitchell', \"o'daniel\"]\n    for name in names:\n        print('%15s: %s' % (name, nysiis(name)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n"}
{"id": 58112, "name": "Disarium numbers", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58113, "name": "Disarium numbers", "Python": "\n\ndef isDisarium(n):\n    digitos = len(str(n))\n    suma = 0\n    x = n\n    while x != 0:\n        suma += (x % 10) ** digitos\n        digitos -= 1\n        x //= 10\n    if suma == n:\n        return True\n    else:\n        return False\n\nif __name__ == '__main__':\n    limite = 19\n    cont = 0\n    n = 0\n    print(\"The first\",limite,\"Disarium numbers are:\")\n    while cont < limite:\n        if isDisarium(n):\n            print(n, end = \" \")\n            cont += 1\n        n += 1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58114, "name": "Sierpinski pentagon", "Python": "from turtle import *\nimport math\nspeed(0)      \nhideturtle()  \n\npart_ratio = 2 * math.cos(math.radians(72))\nside_ratio = 1 / (part_ratio + 2)\n\nhide_turtles = True   \npath_color = \"black\"  \nfill_color = \"black\"  \n\n\ndef pentagon(t, s):\n  t.color(path_color, fill_color)\n  t.pendown()\n  t.right(36)\n  t.begin_fill()\n  for i in range(5):\n    t.forward(s)\n    t.right(72)\n  t.end_fill()\n\n\ndef sierpinski(i, t, s):\n  t.setheading(0)\n  new_size = s * side_ratio\n  \n  if i > 1:\n    i -= 1\n    \n    \n    for j in range(4):\n      t.right(36)\n      short = s * side_ratio / part_ratio\n      dist = [short, s, s, short][j]\n      \n      \n      spawn = Turtle()\n      if hide_turtles:spawn.hideturtle()\n      spawn.penup()\n      spawn.setposition(t.position())\n      spawn.setheading(t.heading())\n      spawn.forward(dist)\n      \n      \n      sierpinski(i, spawn, new_size)\n    \n    \n    sierpinski(i, t, new_size)\n    \n  else:\n    \n    pentagon(t, s)\n    \n    del t\n\ndef main():\n  t = Turtle()\n  t.hideturtle()\n  t.penup()\n  screen = t.getscreen()\n  y = screen.window_height()\n  t.goto(0, y/2-20)\n  \n  i = 5       \n  size = 300  \n  \n  \n  size *= part_ratio\n  \n  \n  sierpinski(i, t, size)\n\nmain()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n"}
{"id": 58115, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n"}
{"id": 58116, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n"}
{"id": 58117, "name": "Padovan n-step number sequences", "Python": "def pad_like(max_n=8, t=15):\n    \n    start = [[], [1, 1, 1]]     \n    for n in range(2, max_n+1):\n        this = start[n-1][:n+1]     \n        while len(this) < t:\n            this.append(sum(this[i] for i in range(-2, -n - 2, -1)))\n        start.append(this)\n    return start[2:]\n\ndef pr(p):\n    print(.strip())\n    for n, seq in enumerate(p, 2):\n        print(f\"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\\n|-\")\n    print('|}')\n\nif __name__ == '__main__':\n    p = pad_like()\n    pr(p)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc padovanN(n, t int) []int {\n    if n < 2 || t < 3 {\n        ones := make([]int, t)\n        for i := 0; i < t; i++ {\n            ones[i] = 1\n        }\n        return ones\n    }\n    p := padovanN(n-1, t)\n    for i := n + 1; i < t; i++ {\n        p[i] = 0\n        for j := i - 2; j >= i-n-1; j-- {\n            p[i] += p[j]\n        }\n    }\n    return p\n}\n\nfunc main() {\n    t := 15\n    fmt.Println(\"First\", t, \"terms of the Padovan n-step number sequences:\")\n    for n := 2; n <= 8; n++ {\n        fmt.Printf(\"%d: %3d\\n\", n, padovanN(n, t))\n    }\n}\n"}
{"id": 58118, "name": "Mutex", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n"}
{"id": 58119, "name": "Mutex", "Python": "import threading\nfrom time import sleep\n\n\n\nres = 2\nsema = threading.Semaphore(res)\n\nclass res_thread(threading.Thread):\n    def run(self):\n        global res\n        n = self.getName()\n        for i in range(1, 4):\n            \n            \n            \n            sema.acquire()\n            res = res - 1\n            print n, \"+  res count\", res\n            sleep(2)\n\n                        \n            res = res + 1\n            print n, \"-  res count\", res\n            sema.release()\n\n\nfor i in range(1, 5):\n    t = res_thread()\n    t.start()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n"}
{"id": 58120, "name": "Metronome", "Python": "\nimport time\n\ndef main(bpm = 72, bpb = 4):\n    sleep = 60.0 / bpm\n    counter = 0\n    while True:\n        counter += 1\n        if counter % bpb:\n            print 'tick'\n        else:\n            print 'TICK'\n        time.sleep(sleep)\n        \n\n\nmain()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 \n\tvar bpb = 4    \n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}\n"}
{"id": 58121, "name": "Native shebang", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n"}
{"id": 58122, "name": "Native shebang", "Python": "\n\n\nimport sys\nprint \" \".join(sys.argv[1:])\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n"}
{"id": 58123, "name": "EKG sequence convergence", "Python": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n    \n    c = count(start + 1)\n    last, so_far = start, list(range(2, start))\n    yield 1, []\n    yield last, []\n    while True:\n        for index, sf in enumerate(so_far):\n            if gcd(last, sf) > 1:\n                last = so_far.pop(index)\n                yield last, so_far[::]\n                break\n        else:\n            so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n    \"Returns the convergence point or zero if not found within the limit\"\n    ekg = [EKG_gen(n) for n in ekgs]\n    for e in ekg:\n        next(e)    \n    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),\n                                  zip(*ekg))))\n\nif __name__ == '__main__':\n    for start in 2, 5, 7, 9, 10:\n        print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n    print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n    for _, j := range a {\n        if j == b {\n            return true\n        }\n    }\n    return false\n}\n\nfunc gcd(a, b int) int {\n    for a != b {\n        if a > b {\n            a -= b\n        } else {\n            b -= a\n        }\n    }\n    return a\n}\n\nfunc areSame(s, t []int) bool {\n    le := len(s)\n    if le != len(t) {\n        return false\n    }\n    sort.Ints(s)\n    sort.Ints(t)\n    for i := 0; i < le; i++ {\n        if s[i] != t[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100\n    starts := [5]int{2, 5, 7, 9, 10}\n    var ekg [5][limit]int\n\n    for s, start := range starts {\n        ekg[s][0] = 1\n        ekg[s][1] = start\n        for n := 2; n < limit; n++ {\n            for i := 2; ; i++ {\n                \n                \n                if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n                    ekg[s][n] = i\n                    break\n                }\n            }\n        }\n        fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n    }   \n\n    \n    for i := 2; i < limit; i++ {\n        if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n            fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n            return\n        }\n    }\n    fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}\n"}
{"id": 58124, "name": "Rep-string", "Python": "def is_repeated(text):\n    'check if the first part of the string is repeated throughout the string'\n    for x in range(len(text)//2, 0, -1):\n        if text.startswith(text[x:]): return x\n    return 0\n\nmatchstr = \nfor line in matchstr.split():\n    ln = is_repeated(line)\n    print('%r has a repetition length of %i i.e. %s' \n           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n"}
{"id": 58125, "name": "Terminal control_Preserve screen", "Python": "\n\nimport time\n\nprint \"\\033[?1049h\\033[H\"\nprint \"Alternate buffer!\"\n\nfor i in xrange(5, 0, -1):\n    print \"Going back in:\", i\n    time.sleep(1)\n\nprint \"\\033[?1049l\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"\\033[?1049h\\033[H\")\n    fmt.Println(\"Alternate screen buffer\\n\")\n    s := \"s\"\n    for i := 5; i > 0; i-- {\n        if i == 1 {\n            s = \"\"\n        }\n        fmt.Printf(\"\\rgoing back in %d second%s...\", i, s)\n        time.Sleep(time.Second)\n    }\n    fmt.Print(\"\\033[?1049l\")\n}\n"}
{"id": 58126, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n"}
{"id": 58127, "name": "Changeable words", "Python": "from collections import defaultdict, Counter\n\n\ndef getwords(minlength=11, fname='unixdict.txt'):\n    \"Return set of lowercased words of > given number of characters\"\n    with open(fname) as f:\n        words = f.read().strip().lower().split()\n    return {w for w in words if len(w) > minlength}\n\nwords11 = getwords()\nword_minus_1 = defaultdict(list)    \nminus_1_to_word = defaultdict(list) \n\nfor w in words11:\n    for i in range(len(w)):\n        minus_1 = w[:i] + w[i+1:]\n        word_minus_1[minus_1].append((w, i))   \n        if minus_1 in words11:\n            minus_1_to_word[minus_1].append(w)\n    \ncwords = set()  \nfor _, v in word_minus_1.items():\n    if len(v) >1:\n        change_indices = Counter(i for wrd, i in v)\n        change_words = set(wrd for wrd, i in v)\n        words_changed = None\n        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:\n            words_changed = [wrd for wrd, i in v\n                             if change_indices[i] > 1]\n        if words_changed:\n            cwords.add(tuple(sorted(words_changed)))\n\nprint(f\"{len(minus_1_to_word)} words that are from deleting a char from other words:\")\nfor k, v in sorted(minus_1_to_word.items()):\n    print(f\"  {k:12} From {', '.join(v)}\")\n\nprint(f\"\\n{len(cwords)} words that are from changing a char from other words:\")\nfor v in sorted(cwords):\n    print(f\"  {v[0]:12} From {', '.join(v[1:])}\")\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n"}
{"id": 58128, "name": "Window management", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 58129, "name": "Window management", "Python": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\n\troot.iconify()\n\t\ndef delete():\n\t\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 58130, "name": "Monads_List monad", "Python": "\nfrom __future__ import annotations\nfrom itertools import chain\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\nfrom typing import TypeVar\n\n\nT = TypeVar(\"T\")\n\n\nclass MList(List[T]):\n    @classmethod\n    def unit(cls, value: Iterable[T]) -> MList[T]:\n        return cls(value)\n\n    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return MList(chain.from_iterable(map(func, self)))\n\n    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:\n        return self.bind(func)\n\n\nif __name__ == \"__main__\":\n    \n    print(\n        MList([1, 99, 4])\n        .bind(lambda val: MList([val + 1]))\n        .bind(lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList([1, 99, 4])\n        >> (lambda val: MList([val + 1]))\n        >> (lambda val: MList([f\"${val}.00\"]))\n    )\n\n    \n    print(\n        MList(range(1, 6)).bind(\n            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))\n        )\n    )\n\n    \n    print(\n        MList(range(1, 26)).bind(\n            lambda x: MList(range(x + 1, 26)).bind(\n                lambda y: MList(range(y + 1, 26)).bind(\n                    lambda z: MList([(x, y, z)])\n                    if x * x + y * y == z * z\n                    else MList([])\n                )\n            )\n        )\n    )\n", "Go": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n    return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n    return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = v + 1\n    }\n    return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = 2 * v\n    }\n    return unit(lst2)\n}\n\nfunc main() {\n    ml1 := unit([]int{3, 4, 5})\n    ml2 := ml1.bind(increment).bind(double)\n    fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}\n"}
{"id": 58131, "name": "Find squares n where n+1 is prime", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n"}
{"id": 58132, "name": "Find squares n where n+1 is prime", "Python": "limit = 1000\nprint(\"working...\")\n\ndef isprime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\ndef issquare(x):\n\tfor n in range(1,x+1):\n\t\tif (x == n*n):\n\t\t\treturn 1\n\treturn 0\n\nfor n in range(limit-1):\n\tif issquare(n) and isprime(n+1):\n\t\tprint(n,end=\" \")\n\nprint()\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n"}
{"id": 58133, "name": "Next special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 58134, "name": "Next special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 3\n    i = 2\n\n    print(\"2 3\", end = \" \");\n    while True:\n        if isPrime(p + i) == 1:\n            p += i\n            print(p, end = \" \");\n        i += 2\n        if p + i >= 1050:\n            break\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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n"}
{"id": 58135, "name": "Mayan numerals", "Python": "\n\nfrom functools import (reduce)\n\n\n\n\n\ndef mayanNumerals(n):\n    \n    return showIntAtBase(20)(\n        mayanDigit\n    )(n)([])\n\n\n\ndef mayanDigit(n):\n    \n    if 0 < n:\n        r = n % 5\n        return [\n            (['●' * r] if 0 < r else []) +\n            (['━━'] * (n // 5))\n        ]\n    else:\n        return ['Θ']\n\n\n\ndef mayanFramed(n):\n    \n    return 'Mayan ' + str(n) + ':\\n\\n' + (\n        wikiTable({\n            'class': 'wikitable',\n            'style': cssFromDict({\n                'text-align': 'center',\n                'background-color': '\n                'color': '\n                'border': '2px solid silver'\n            }),\n            'colwidth': '3em',\n            'cell': 'vertical-align: bottom;'\n        })([[\n            '<br>'.join(col) for col in mayanNumerals(n)\n        ]])\n    )\n\n\n\n\n\ndef main():\n    \n    print(\n        main.__doc__ + ':\\n\\n' +\n        '\\n'.join(mayanFramed(n) for n in [\n            4005, 8017, 326205, 886205, 1081439556,\n            1000000, 1000000000\n        ])\n    )\n\n\n\n\n\ndef wikiTable(opts):\n    \n    def colWidth():\n        return 'width:' + opts['colwidth'] + '; ' if (\n            'colwidth' in opts\n        ) else ''\n\n    def cellStyle():\n        return opts['cell'] if 'cell' in opts else ''\n\n    return lambda rows: '{| ' + reduce(\n        lambda a, k: (\n            a + k + '=\"' + opts[k] + '\" ' if (\n                k in opts\n            ) else a\n        ),\n        ['class', 'style'],\n        ''\n    ) + '\\n' + '\\n|-\\n'.join(\n        '\\n'.join(\n            ('|' if (\n                0 != i and ('cell' not in opts)\n            ) else (\n                '|style=\"' + colWidth() + cellStyle() + '\"|'\n            )) + (\n                str(x) or ' '\n            ) for x in row\n        ) for i, row in enumerate(rows)\n    ) + '\\n|}\\n\\n'\n\n\n\n\n\ndef cssFromDict(dct):\n    \n    return reduce(\n        lambda a, k: a + k + ':' + dct[k] + '; ',\n        dct.keys(),\n        ''\n    )\n\n\n\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst (\n    ul = \"╔\"\n    uc = \"╦\"\n    ur = \"╗\"\n    ll = \"╚\"\n    lc = \"╩\"\n    lr = \"╝\"\n    hb = \"═\"\n    vb = \"║\"\n)\n\nvar mayan = [5]string{\n    \"    \",\n    \" ∙  \",\n    \" ∙∙ \",\n    \"∙∙∙ \",\n    \"∙∙∙∙\",\n}\n\nconst (\n    m0 = \" Θ  \"\n    m5 = \"────\"\n)\n\nfunc dec2vig(n uint64) []uint64 {\n    vig := strconv.FormatUint(n, 20)\n    res := make([]uint64, len(vig))\n    for i, d := range vig {\n        res[i], _ = strconv.ParseUint(string(d), 20, 64)\n    }\n    return res\n}\n\nfunc vig2quin(n uint64) [4]string {\n    if n >= 20 {\n        panic(\"Cant't convert a number >= 20\")\n    }\n    res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}\n    if n == 0 {\n        res[3] = m0\n        return res\n    }\n    fives := n / 5\n    rem := n % 5\n    res[3-fives] = mayan[rem]\n    for i := 3; i > 3-int(fives); i-- {\n        res[i] = m5\n    }\n    return res\n}\n\nfunc draw(mayans [][4]string) {\n    lm := len(mayans)\n    fmt.Print(ul)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(uc)\n        } else {\n            fmt.Println(ur)\n        }\n    }\n    for i := 1; i < 5; i++ {\n        fmt.Print(vb)\n        for j := 0; j < lm; j++ {\n            fmt.Print(mayans[j][i-1])\n            fmt.Print(vb)\n        }\n        fmt.Println()\n    }\n    fmt.Print(ll)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(lc)\n        } else {\n            fmt.Println(lr)\n        }\n    }\n}\n\nfunc main() {\n    numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}\n    for _, n := range numbers {\n        fmt.Printf(\"Converting %d to Mayan:\\n\", n)\n        vigs := dec2vig(n)\n        lv := len(vigs)\n        mayans := make([][4]string, lv)\n        for i, vig := range vigs {\n            mayans[i] = vig2quin(vig)\n        }\n        draw(mayans)\n        fmt.Println()\n    }\n}\n"}
{"id": 58136, "name": "Special factorials", "Python": "\n\nfrom math import prod\n\ndef superFactorial(n):\n    return prod([prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef hyperFactorial(n):\n    return prod([i**i for i in range(1,n+1)])\n\ndef alternatingFactorial(n):\n    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])\n\ndef exponentialFactorial(n):\n    if n in [0,1]:\n        return 1\n    else:\n        return n**exponentialFactorial(n-1)\n        \ndef inverseFactorial(n):\n    i = 1\n    while True:\n        if n == prod(range(1,i)):\n            return i-1\n        elif n < prod(range(1,i)):\n            return \"undefined\"\n        i+=1\n\nprint(\"Superfactorials for [0,9] :\")\nprint({\"sf(\" + str(i) + \") \" : superFactorial(i) for i in range(0,10)})\n\nprint(\"\\nHyperfactorials for [0,9] :\")\nprint({\"H(\" + str(i) + \") \"  : hyperFactorial(i) for i in range(0,10)})\n\nprint(\"\\nAlternating factorials for [0,9] :\")\nprint({\"af(\" + str(i) + \") \" : alternatingFactorial(i) for i in range(0,10)})\n\nprint(\"\\nExponential factorials for [0,4] :\")\nprint({str(i) + \"$ \" : exponentialFactorial(i) for i in range(0,5)})\n\nprint(\"\\nDigits in 5$ : \" , len(str(exponentialFactorial(5))))\n\nfactorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\n\nprint(\"\\nInverse factorials for \" , factorialSet)\nprint({\"rf(\" + str(i) + \") \":inverseFactorial(i) for i in factorialSet})\n\nprint(\"\\nrf(119) : \" + inverseFactorial(119))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc sf(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    sfact := big.NewInt(1)\n    fact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        sfact.Mul(sfact, fact)\n    }\n    return sfact\n}\n\nfunc H(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    hfact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        bi := big.NewInt(int64(i))\n        hfact.Mul(hfact, bi.Exp(bi, bi, nil))\n    }\n    return hfact\n}\n\nfunc af(n int) *big.Int {\n    if n < 1 {\n        return new(big.Int)\n    }\n    afact := new(big.Int)\n    fact := big.NewInt(1)\n    sign := new(big.Int)\n    if n%2 == 0 {\n        sign.SetInt64(-1)\n    } else {\n        sign.SetInt64(1)\n    }\n    t := new(big.Int)\n    for i := 1; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        afact.Add(afact, t.Mul(fact, sign))\n        sign.Neg(sign)\n    }\n    return afact\n}\n\nfunc ef(n int) *big.Int {\n    if n < 1 {\n        return big.NewInt(1)\n    }\n    t := big.NewInt(int64(n))\n    return t.Exp(t, ef(n-1), nil)\n}\n\nfunc rf(n *big.Int) int {\n    i := 0\n    fact := big.NewInt(1)\n    for {\n        if fact.Cmp(n) == 0 {\n            return i\n        }\n        if fact.Cmp(n) > 0 {\n            return -1\n        }\n        i++\n        fact.Mul(fact, big.NewInt(int64(i)))\n    }\n}\n\nfunc main() {\n    fmt.Println(\"First 10 superfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sf(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 hyperfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(H(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 alternating factorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Print(af(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 exponential factorials:\")\n    for i := 0; i <= 4; i++ {\n        fmt.Print(ef(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nThe number of digits in 5$ is\", len(ef(5).String()))\n\n    fmt.Println(\"\\nReverse factorials:\")\n    facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}\n    for _, fact := range facts {\n        bfact := big.NewInt(fact)\n        rfact := rf(bfact)\n        srfact := fmt.Sprintf(\"%d\", rfact)\n        if rfact == -1 {\n            srfact = \"none\"\n        }\n        fmt.Printf(\"%4s <- rf(%d)\\n\", srfact, fact)\n    }\n}\n"}
{"id": 58137, "name": "Special neighbor primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n"}
{"id": 58138, "name": "Special neighbor primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef nextPrime(n):\n    \n    if n == 0:\n        return 2\n    if n < 3:\n        return n + 1\n    q = n + 2\n    while not isPrime(q):\n        q += 2\n    return q\n\n\nif __name__ == \"__main__\":\n    for p1 in range(3,100,2):\n        p2 = nextPrime(p1)\n        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):\n            print(p1,'\\t', p2,'\\t', p1 + p2 - 1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n"}
{"id": 58139, "name": "Ramsey's theorem", "Python": "range17 = range(17)\na = [['0'] * 17 for i in range17]\nidx = [0] * 4\n\n\ndef find_group(mark, min_n, max_n, depth=1):\n    if (depth == 4):\n        prefix = \"\" if (mark == '1') else \"un\"\n        print(\"Fail, found totally {}connected group:\".format(prefix))\n        for i in range(4):\n            print(idx[i])\n        return True\n\n    for i in range(min_n, max_n):\n        n = 0\n        while (n < depth):\n            if (a[idx[n]][i] != mark):\n                break\n            n += 1\n\n        if (n == depth):\n            idx[n] = i\n            if (find_group(mark, 1, max_n, depth + 1)):\n                return True\n\n    return False\n\n\nif __name__ == '__main__':\n    for i in range17:\n        a[i][i] = '-'\n    for k in range(4):\n        for i in range17:\n            j = (i + pow(2, k)) % 17\n            a[i][j] = a[j][i] = '1'\n\n    \n    \n\n    for row in a:\n        print(' '.join(row))\n\n    for i in range17:\n        idx[0] = i\n        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):\n            print(\"no good\")\n            exit()\n\n    print(\"all good\")\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n"}
{"id": 58140, "name": "GUI_Maximum window dimensions", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n"}
{"id": 58141, "name": "Terminal control_Inverse video", "Python": "\n\nprint \"\\033[7mReversed\\033[m Normal\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    tput(\"rev\")\n    fmt.Print(\"Rosetta\")\n    tput(\"sgr0\")\n    fmt.Println(\" Code\")\n}\n\nfunc tput(arg string) error {\n    cmd := exec.Command(\"tput\", arg)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n"}
{"id": 58142, "name": "Four is magic", "Python": "import random\nfrom collections import OrderedDict\n\nnumbers = {  \n    1: 'one',\n    2: 'two',\n    3: 'three',\n    4: 'four',\n    5: 'five',\n    6: 'six',\n    7: 'seven',\n    8: 'eight',\n    9: 'nine',\n    10: 'ten',\n    11: 'eleven',\n    12: 'twelve',\n    13: 'thirteen',\n    14: 'fourteen',\n    15: 'fifteen',\n    16: 'sixteen',\n    17: 'seventeen',\n    18: 'eighteen',\n    19: 'nineteen',\n    20: 'twenty',\n    30: 'thirty',\n    40: 'forty',\n    50: 'fifty',\n    60: 'sixty',\n    70: 'seventy',\n    80: 'eighty',\n    90: 'ninety',\n    100: 'hundred',\n    1000: 'thousand',\n    10 ** 6: 'million',\n    10 ** 9: 'billion',\n    10 ** 12: 'trillion',\n    10 ** 15: 'quadrillion',\n    10 ** 18: 'quintillion',\n    10 ** 21: 'sextillion',\n    10 ** 24: 'septillion',\n    10 ** 27: 'octillion',\n    10 ** 30: 'nonillion',\n    10 ** 33: 'decillion',\n    10 ** 36: 'undecillion',\n    10 ** 39: 'duodecillion',\n    10 ** 42: 'tredecillion',\n    10 ** 45: 'quattuordecillion',\n    10 ** 48: 'quinquadecillion',\n    10 ** 51: 'sedecillion',\n    10 ** 54: 'septendecillion',\n    10 ** 57: 'octodecillion',\n    10 ** 60: 'novendecillion',\n    10 ** 63: 'vigintillion',\n    10 ** 66: 'unvigintillion',\n    10 ** 69: 'duovigintillion',\n    10 ** 72: 'tresvigintillion',\n    10 ** 75: 'quattuorvigintillion',\n    10 ** 78: 'quinquavigintillion',\n    10 ** 81: 'sesvigintillion',\n    10 ** 84: 'septemvigintillion',\n    10 ** 87: 'octovigintillion',\n    10 ** 90: 'novemvigintillion',\n    10 ** 93: 'trigintillion',\n    10 ** 96: 'untrigintillion',\n    10 ** 99: 'duotrigintillion',\n    10 ** 102: 'trestrigintillion',\n    10 ** 105: 'quattuortrigintillion',\n    10 ** 108: 'quinquatrigintillion',\n    10 ** 111: 'sestrigintillion',\n    10 ** 114: 'septentrigintillion',\n    10 ** 117: 'octotrigintillion',\n    10 ** 120: 'noventrigintillion',\n    10 ** 123: 'quadragintillion',\n    10 ** 153: 'quinquagintillion',\n    10 ** 183: 'sexagintillion',\n    10 ** 213: 'septuagintillion',\n    10 ** 243: 'octogintillion',\n    10 ** 273: 'nonagintillion',\n    10 ** 303: 'centillion',\n    10 ** 306: 'uncentillion',\n    10 ** 309: 'duocentillion',\n    10 ** 312: 'trescentillion',\n    10 ** 333: 'decicentillion',\n    10 ** 336: 'undecicentillion',\n    10 ** 363: 'viginticentillion',\n    10 ** 366: 'unviginticentillion',\n    10 ** 393: 'trigintacentillion',\n    10 ** 423: 'quadragintacentillion',\n    10 ** 453: 'quinquagintacentillion',\n    10 ** 483: 'sexagintacentillion',\n    10 ** 513: 'septuagintacentillion',\n    10 ** 543: 'octogintacentillion',\n    10 ** 573: 'nonagintacentillion',\n    10 ** 603: 'ducentillion',\n    10 ** 903: 'trecentillion',\n    10 ** 1203: 'quadringentillion',\n    10 ** 1503: 'quingentillion',\n    10 ** 1803: 'sescentillion',\n    10 ** 2103: 'septingentillion',\n    10 ** 2403: 'octingentillion',\n    10 ** 2703: 'nongentillion',\n    10 ** 3003: 'millinillion'\n}\nnumbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))\n\n\ndef string_representation(i: int) -> str:\n    \n    if i == 0:\n        return 'zero'\n\n    words = ['negative'] if i < 0 else []\n    working_copy = abs(i)\n\n    for key, value in numbers.items():\n        if key <= working_copy:\n            times = int(working_copy / key)\n\n            if key >= 100:\n                words.append(string_representation(times))\n\n            words.append(value)\n            working_copy -= times * key\n\n        if working_copy == 0:\n            break\n\n    return ' '.join(words)\n\n\ndef next_phrase(i: int):\n    \n    while not i == 4:  \n        str_i = string_representation(i)\n        len_i = len(str_i)\n\n        yield str_i, 'is', string_representation(len_i)\n\n        i = len_i\n\n    \n    yield string_representation(i), 'is', 'magic'\n\n\ndef magic(i: int) -> str:\n    phrases = []\n\n    for phrase in next_phrase(i):\n        phrases.append(' '.join(phrase))\n\n    return f'{\", \".join(phrases)}.'.capitalize()\n\n\nif __name__ == '__main__':\n\n    for j in (random.randint(0, 10 ** 3) for i in range(5)):\n        print(j, ':\\n', magic(j), '\\n')\n\n    for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):\n        print(j, ':\\n', magic(j), '\\n')\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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": 58143, "name": "Getting the number of decimals", "Python": "In [6]: def dec(n):\n   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0\n\nIn [7]: dec('12.345')\nOut[7]: 3\n\nIn [8]: dec('12.3450')\nOut[8]: 4\n\nIn [9]:\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n"}
{"id": 58144, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n"}
{"id": 58145, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 58146, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 58147, "name": "Paraffins", "Python": "try:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\nMAX_N = 300\nBRANCH = 4\n\nra = [0] * MAX_N\nunrooted = [0] * MAX_N\n\ndef tree(br, n, l, sum = 1, cnt = 1):\n    global ra, unrooted, MAX_N, BRANCH\n    for b in xrange(br + 1, BRANCH + 1):\n        sum += n\n        if sum >= MAX_N:\n            return\n\n        \n        if l * 2 >= sum and b >= BRANCH:\n            return\n\n        if b == br + 1:\n            c = ra[n] * cnt\n        else:\n            c = c * (ra[n] + (b - br - 1)) / (b - br)\n\n        if l * 2 < sum:\n            unrooted[sum] += c\n\n        if b < BRANCH:\n            ra[sum] += c;\n            for m in range(1, n):\n                tree(b, m, l, sum, c)\n\ndef bicenter(s):\n    global ra, unrooted\n    if not (s & 1):\n        aux = ra[s / 2]\n        unrooted[s] += aux * (aux + 1) / 2\n\n\ndef main():\n    global ra, unrooted, MAX_N\n    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1\n\n    for n in xrange(1, MAX_N):\n        tree(0, n, n)\n        bicenter(n)\n        print \"%d: %d\" % (n, unrooted[n])\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n"}
{"id": 58148, "name": "Minimum number of cells after, before, above and below NxN squares", "Python": "def min_cells_matrix(siz):\n    return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]\n\ndef display_matrix(mat):\n    siz = len(mat)\n    spaces = 2 if siz < 20 else 3 if siz < 200 else 4\n    print(f\"\\nMinimum number of cells after, before, above and below {siz} x {siz} square:\")\n    for row in range(siz):\n        print(\"\".join([f\"{n:{spaces}}\" for n in mat[row]]))\n\ndef test_min_mat():\n    for siz in [23, 10, 9, 2, 1]:\n        display_matrix(min_cells_matrix(siz))\n\nif __name__ == \"__main__\":\n    test_min_mat()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc printMinCells(n int) {\n    fmt.Printf(\"Minimum number of cells after, before, above and below %d x %d square:\\n\", n, n)\n    p := 1\n    if n > 20 {\n        p = 2\n    }\n    for r := 0; r < n; r++ {\n        cells := make([]int, n)\n        for c := 0; c < n; c++ {\n            nums := []int{n - r - 1, r, c, n - c - 1}\n            min := n\n            for _, num := range nums {\n                if num < min {\n                    min = num\n                }\n            }\n            cells[c] = min\n        }\n        fmt.Printf(\"%*d \\n\", p, cells)\n    }\n}\n\nfunc main() {\n    for _, n := range []int{23, 10, 9, 2, 1} {\n        printMinCells(n)\n        fmt.Println()\n    }\n}\n"}
{"id": 58149, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 58150, "name": "Pentagram", "Python": "import turtle\n\nturtle.bgcolor(\"green\")\nt = turtle.Turtle()\nt.color(\"red\", \"blue\")\nt.begin_fill()\nfor i in range(0, 5):\n    t.forward(200)\n    t.right(144)\nt.end_fill()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n"}
{"id": 58151, "name": "Parse an IP Address", "Python": "from ipaddress import ip_address\nfrom urllib.parse import urlparse\n\ntests = [\n    \"127.0.0.1\",\n    \"127.0.0.1:80\",\n    \"::1\",\n    \"[::1]:80\",\n    \"::192.168.0.1\",\n    \"2605:2700:0:3::4713:93e3\",\n    \"[2605:2700:0:3::4713:93e3]:80\" ]\n\ndef parse_ip_port(netloc):\n    try:\n        ip = ip_address(netloc)\n        port = None\n    except ValueError:\n        parsed = urlparse('//{}'.format(netloc))\n        ip = ip_address(parsed.hostname)\n        port = parsed.port\n    return ip, port\n\nfor address in tests:\n    ip, port = parse_ip_port(address)\n    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))\n    print(\"{:39s}  {:>32s}  IPv{}  port={}\".format(\n        str(ip), hex_ip, ip.version, port ))\n", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n"}
{"id": 58152, "name": "Matrix digital rain", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n"}
{"id": 58153, "name": "Matrix digital rain", "Python": "import curses\nimport random\nimport time\n\n\n\n\n\nROW_DELAY=.0001\n\ndef get_rand_in_range(min, max):\n    return random.randrange(min,max+1)\n\ntry:\n    \n    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n    \n    total_chars = len(chars)\n        \n    stdscr = curses.initscr()\n    curses.noecho()\n    curses.curs_set(False)\n        \n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    stdscr.attron(curses.color_pair(1))\n    \n    max_x = curses.COLS - 1\n    max_y = curses.LINES - 1\n    \n         \n    \n    \n    \n    \n    columns_row = []\n    \n    \n    \n    \n    columns_active = []\n    \n    for i in range(max_x+1):\n        columns_row.append(-1)\n        columns_active.append(0)\n        \n    while(True):\n        for i in range(max_x):\n            if columns_row[i] == -1:\n                \n                \n                columns_row[i] = get_rand_in_range(0, max_y)\n                columns_active[i] = get_rand_in_range(0, 1)\n     \n        \n        \n        for i in range(max_x):\n            if columns_active[i] == 1:\n                \n                char_index = get_rand_in_range(0, total_chars-1)\n                \n                stdscr.addstr(columns_row[i], i, chars[char_index])\n            else:\n                \n                \n                stdscr.addstr(columns_row[i], i, \" \");\n                \n     \n            columns_row[i]+=1\n     \n            \n            if columns_row[i] >= max_y:\n                columns_row[i] = -1\n    \n            \n            if get_rand_in_range(0, 1000) == 0:\n                if columns_active[i] == 0:      \n                    columns_active[i] = 1\n                else:\n                    columns_active[i] = 0\n     \n            time.sleep(ROW_DELAY)\n            stdscr.refresh()\n    \nexcept KeyboardInterrupt as err:\n    curses.endwin()\n", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n"}
{"id": 58154, "name": "Mind boggling card trick", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n"}
{"id": 58155, "name": "Mind boggling card trick", "Python": "import random\n\n\nn = 52\nBlack, Red = 'Black', 'Red'\nblacks = [Black] * (n // 2) \nreds = [Red] * (n // 2)\npack = blacks + reds\n\nrandom.shuffle(pack)\n\n\nblack_stack, red_stack, discard = [], [], []\nwhile pack:\n    top = pack.pop()\n    if top == Black:\n        black_stack.append(pack.pop())\n    else:\n        red_stack.append(pack.pop())\n    discard.append(top)\nprint('(Discards:', ' '.join(d[0] for d in discard), ')\\n')\n\n\n\nmax_swaps = min(len(black_stack), len(red_stack))\n\nswap_count = random.randint(0, max_swaps)\nprint('Swapping', swap_count)\n\ndef random_partition(stack, count):\n    \"Partition the stack into 'count' randomly selected members and the rest\"\n    sample = random.sample(stack, count)\n    rest = stack[::]\n    for card in sample:\n        rest.remove(card)\n    return rest, sample\n\nblack_stack, black_swap = random_partition(black_stack, swap_count)\nred_stack, red_swap = random_partition(red_stack, swap_count)\n\n\nblack_stack += red_swap\nred_stack += black_swap\n\n\nif black_stack.count(Black) == red_stack.count(Red):\n    print('Yeha! The mathematicians assertion is correct.')\nelse:\n    print('Whoops - The mathematicians (or my card manipulations) are flakey')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n"}
{"id": 58156, "name": "Textonyms", "Python": "from collections import defaultdict\nimport urllib.request\n\nCH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}\nURL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'\n\n\ndef getwords(url):\n return urllib.request.urlopen(url).read().decode(\"utf-8\").lower().split()\n\ndef mapnum2words(words):\n    number2words = defaultdict(list)\n    reject = 0\n    for word in words:\n        try:\n            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)\n        except KeyError:\n            \n            reject += 1\n    return dict(number2words), reject\n\ndef interactiveconversions():\n    global inp, ch, num\n    while True:\n        inp = input(\"\\nType a number or a word to get the translation and textonyms: \").strip().lower()\n        if inp:\n            if all(ch in '23456789' for ch in inp):\n                if inp in num2words:\n                    print(\"  Number {0} has the following textonyms in the dictionary: {1}\".format(inp, ', '.join(\n                        num2words[inp])))\n                else:\n                    print(\"  Number {0} has no textonyms in the dictionary.\".format(inp))\n            elif all(ch in CH2NUM for ch in inp):\n                num = ''.join(CH2NUM[ch] for ch in inp)\n                print(\"  Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}\".format(\n                    inp, ('' if inp in wordset else \"n't\"), num, ', '.join(num2words[num])))\n            else:\n                print(\"  I don't understand %r\" % inp)\n        else:\n            print(\"Thank you\")\n            break\n\n\nif __name__ == '__main__':\n    words = getwords(URL)\n    print(\"Read %i words from %r\" % (len(words), URL))\n    wordset = set(words)\n    num2words, reject = mapnum2words(words)\n    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)\n    maxwordpernum = max(len(values) for values in num2words.values())\n    print(.format(len(words) - reject, URL, len(num2words), morethan1word))\n\n    print(\"\\nThe numbers mapping to the most words map to %i words each:\" % maxwordpernum)\n    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)\n    for num, wrds in maxwpn:\n        print(\"  %s maps to: %s\" % (num, ', '.join(wrds)))\n\n    interactiveconversions()\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n"}
{"id": 58157, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 58158, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n"}
{"id": 58159, "name": "Teacup rim text", "Python": "\n\nfrom itertools import chain, groupby\nfrom os.path import expanduser\nfrom functools import reduce\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        concatMap(circularGroup)(\n            anagrams(3)(\n                \n                lines(readFile('~/mitWords.txt'))\n            )\n        )\n    ))\n\n\n\ndef anagrams(n):\n    \n    def go(ws):\n        def f(xs):\n            return [\n                [snd(x) for x in xs]\n            ] if n <= len(xs) >= len(xs[0][0]) else []\n        return concatMap(f)(groupBy(fst)(sorted(\n            [(''.join(sorted(w)), w) for w in ws],\n            key=fst\n        )))\n    return go\n\n\n\ndef circularGroup(ws):\n    \n    lex = set(ws)\n    iLast = len(ws) - 1\n    \n    \n    (i, blnCircular) = until(\n        lambda tpl: tpl[1] or (tpl[0] > iLast)\n    )(\n        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))\n    )(\n        (0, False)\n    )\n    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []\n\n\n\ndef isCircular(lexicon):\n    \n    def go(w):\n        def f(tpl):\n            (i, _, x) = tpl\n            return (1 + i, x in lexicon, rotated(x))\n\n        iLast = len(w) - 1\n        return until(\n            lambda tpl: iLast < tpl[0] or (not tpl[1])\n        )(f)(\n            (0, True, rotated(w))\n        )[1]\n    return go\n\n\n\ndef allRotations(w):\n    \n    return takeIterate(len(w) - 1)(\n        rotated\n    )(w)\n\n\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef fst(tpl):\n    \n    return tpl[0]\n\n\n\ndef groupBy(f):\n    \n    def go(xs):\n        return [\n            list(x[1]) for x in groupby(xs, key=f)\n        ]\n    return go\n\n\n\ndef lines(s):\n    \n    return s.splitlines()\n\n\n\ndef mapAccumL(f):\n    \n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n\ndef readFile(fp):\n    \n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n\ndef rotated(s):\n    \n    return s[1:] + s[0]\n\n\n\ndef snd(tpl):\n    \n    return tpl[1]\n\n\n\ndef takeIterate(n):\n    \n    def go(f):\n        def g(x):\n            def h(a, i):\n                v = f(a) if i else x\n                return (v, v)\n            return mapAccumL(h)(x)(\n                range(0, 1 + n)\n            )[1]\n        return g\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58160, "name": "Increasing gaps between consecutive Niven numbers", "Python": "\n\n\n\n\n\ndef digit_sum(n, sum):\n    sum += 1\n    while n > 0 and n % 10 == 0:\n        sum -= 9\n        n /= 10\n    \n    return sum\n    \nprevious = 1\ngap = 0\nsum = 0\nniven_index = 0\ngap_index = 1\n \nprint(\"Gap index  Gap    Niven index    Niven number\")\n\nniven = 1\n\nwhile gap_index <= 22:\n    sum = digit_sum(niven, sum)\n    if niven % sum == 0:\n        if niven > previous + gap:\n            gap = niven - previous;\n            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))\n            gap_index += 1\n        previous = niven\n        niven_index += 1\n    niven += 1\n", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n"}
{"id": 58161, "name": "Print debugging statement", "Python": "import logging, logging.handlers\n\nLOG_FILENAME = \"logdemo.log\"\nFORMAT_STRING = \"%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s\"\nLOGLEVEL = logging.DEBUG\n\n\ndef print_squares(number):\n    logger.info(\"In print_squares\")\n    for i in range(number):\n        print(\"square of {0} is {1}\".format(i , i*i))\n        logger.debug(f'square of {i} is {i*i}')\n\ndef print_cubes(number):\n    logger.info(\"In print_cubes\")\n    for j in range(number):\n        print(\"cube of {0} is {1}\".format(j, j*j*j))\n        logger.debug(f'cube of {j} is {j*j*j}')\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(\"logdemo\")\n    logger.setLevel(LOGLEVEL)\n    handler = logging.FileHandler(LOG_FILENAME)\n    handler.setFormatter(logging.Formatter(FORMAT_STRING))\n    logger.addHandler(handler)\n\n    print_squares(10)\n    print_cubes(10)\n\n    logger.info(\"All done\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n"}
{"id": 58162, "name": "Find prime n such that reversed n is also prime", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n"}
{"id": 58163, "name": "Find prime n such that reversed n is also prime", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n"}
{"id": 58164, "name": "Find prime n such that reversed n is also prime", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef isBackPrime(n):\n    if not isPrime(n):\n        return False\n    m = 0\n    while n:\n        m *= 10\n        m += n % 10\n        n //= 10\n    return isPrime(m)\n\nif __name__ == '__main__':\n    for n in range(2, 499):\n        if isBackPrime(n):\n            print(n, end=' ');\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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n"}
{"id": 58165, "name": "Superellipse", "Python": "\n\n\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\ndef sgn(x):\n\treturn ((x>0)-(x<0))*1\n\na,b,n=200,200,2.5 \nna=2/n\nstep=100 \npiece=(pi*2)/step\nxp=[];yp=[]\n\nt=0\nfor t1 in range(step+1):\n\t\n\tx=(abs((cos(t)))**na)*a*sgn(cos(t))\n\ty=(abs((sin(t)))**na)*b*sgn(sin(t))\n\txp.append(x);yp.append(y)\n\tt+=piece\n\nplt.plot(xp,yp) \nplt.title(\"Superellipse with parameter \"+str(n))\nplt.show()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n"}
{"id": 58166, "name": "Permutations_Rank of a permutation", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n"}
{"id": 58167, "name": "Permutations_Rank of a permutation", "Python": "from math import factorial as fact\nfrom random import randrange\nfrom textwrap import wrap\n\ndef identity_perm(n): \n    return list(range(n))\n\ndef unranker1(n, r, pi):\n    while n > 0:\n        n1, (rdivn, rmodn) = n-1, divmod(r, n)\n        pi[n1], pi[rmodn] = pi[rmodn], pi[n1]\n        n = n1\n        r = rdivn\n    return pi\n\ndef init_pi1(n, pi): \n    pi1 = [-1] * n\n    for i in range(n): \n        pi1[pi[i]] = i\n    return pi1\n\ndef ranker1(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s + n * ranker1(n1, pi, pi1)\n\ndef unranker2(n, r, pi):\n    while n > 0:\n        n1 = n-1\n        s, rmodf = divmod(r, fact(n1))\n        pi[n1], pi[s] = pi[s], pi[n1]\n        n = n1\n        r = rmodf\n    return pi\n\ndef ranker2(n, pi, pi1):\n    if n == 1: \n        return 0\n    n1 = n-1\n    s = pi[n1]\n    pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]\n    pi1[s], pi1[n1] = pi1[n1], pi1[s]\n    return s * fact(n1) + ranker2(n1, pi, pi1)\n\ndef get_random_ranks(permsize, samplesize):    \n    perms = fact(permsize)\n    ranks = set()\n    while len(ranks) < samplesize:\n        ranks |= set( randrange(perms) \n                      for r in range(samplesize - len(ranks)) )\n    return ranks    \n\ndef test1(comment, unranker, ranker):    \n    n, samplesize, n2 = 3, 4, 12\n    print(comment)\n    perms = []\n    for r in range(fact(n)):\n        pi = identity_perm(n)\n        perm = unranker(n, r, pi)\n        perms.append((r, perm))\n    for r, pi in perms:\n        pi1 = init_pi1(n, pi)\n        print('  From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))\n    print('\\n  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))\n    print('')\n\ndef test2(comment, unranker):    \n    samplesize, n2 = 4, 144\n    print(comment)\n    print('  %i random individual samples of %i items:' % (samplesize, n2))\n    for r in get_random_ranks(n2, samplesize):\n        pi = identity_perm(n2)\n        print('    ' + '\\n      '.join(wrap(repr(unranker(n2, r, pi)))))\n    print('')\n\nif __name__ == '__main__':\n    test1('First ordering:', unranker1, ranker1)\n    test1('Second ordering:', unranker2, ranker2)\n    test2('First ordering, large number of perms:', unranker1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n"}
{"id": 58168, "name": "Banker's algorithm", "Python": "def main():\n    resources = int(input(\"Cantidad de recursos: \"))\n    processes = int(input(\"Cantidad de procesos: \"))\n    max_resources = [int(i) for i in input(\"Recursos máximos: \").split()]\n\n    print(\"\\n-- recursos asignados para cada proceso  --\")\n    currently_allocated = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    print(\"\\n--- recursos máximos para cada proceso  ---\")\n    max_need = [[int(i) for i in input(f\"proceso {j + 1}: \").split()] for j in range(processes)]\n\n    allocated = [0] * resources\n    for i in range(processes):\n        for j in range(resources):\n            allocated[j] += currently_allocated[i][j]\n    print(f\"\\nRecursos totales asignados  : {allocated}\")\n\n    available = [max_resources[i] - allocated[i] for i in range(resources)]\n    print(f\"Recursos totales disponibles: {available}\\n\")\n\n    running = [True] * processes\n    count = processes\n    while count != 0:\n        safe = False\n        for i in range(processes):\n            if running[i]:\n                executing = True\n                for j in range(resources):\n                    if max_need[i][j] - currently_allocated[i][j] > available[j]:\n                        executing = False\n                        break\n                if executing:\n                    print(f\"proceso {i + 1} ejecutándose\")\n                    running[i] = False\n                    count -= 1\n                    safe = True\n                    for j in range(resources):\n                        available[j] += currently_allocated[i][j]\n                    break\n        if not safe:\n            print(\"El proceso está en un estado inseguro.\")\n            break\n\n        print(f\"El proceso está en un estado seguro.\\nRecursos disponibles: {available}\\n\")\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package bank\n\nimport (\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n    \"sort\"\n    \"sync\"\n)\n\ntype PID string\ntype RID string\ntype RMap map[RID]int\n\n\nfunc (m RMap) String() string {\n    rs := make([]string, len(m))\n    i := 0\n    for r := range m {\n        rs[i] = string(r)\n        i++\n    }\n    sort.Strings(rs)\n    var b bytes.Buffer\n    b.WriteString(\"{\")\n    for _, r := range rs {\n        fmt.Fprintf(&b, \"%q: %d, \", r, m[RID(r)])\n    }\n    bb := b.Bytes()\n    if len(bb) > 1 {\n        bb[len(bb)-2] = '}'\n    }\n    return string(bb)\n}\n\ntype Bank struct {\n    available  RMap\n    max        map[PID]RMap\n    allocation map[PID]RMap\n    sync.Mutex\n}\n\nfunc (b *Bank) need(p PID, r RID) int {\n    return b.max[p][r] - b.allocation[p][r]\n}\n\nfunc New(available RMap) (b *Bank, err error) {\n    for r, a := range available {\n        if a < 0 {\n            return nil, fmt.Errorf(\"negative resource %s: %d\", r, a)\n        }\n    }\n    return &Bank{\n        available:  available,\n        max:        map[PID]RMap{},\n        allocation: map[PID]RMap{},\n    }, nil\n}\n\nfunc (b *Bank) NewProcess(p PID, max RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[p]; ok {\n        return fmt.Errorf(\"process %s already registered\", p)\n    }\n    for r, m := range max {\n        switch a, ok := b.available[r]; {\n        case !ok:\n            return fmt.Errorf(\"resource %s unknown\", r)\n        case m > a:\n            return fmt.Errorf(\"resource %s: process %s max %d > available %d\",\n                r, p, m, a)\n        }\n    }\n    b.max[p] = max\n    b.allocation[p] = RMap{}\n    return\n}\n\nfunc (b *Bank) Request(pid PID, change RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[pid]; !ok {\n        return fmt.Errorf(\"process %s unknown\", pid)\n    }\n    for r, c := range change {\n        if c < 0 {\n            return errors.New(\"decrease not allowed\")\n        }\n        if _, ok := b.available[r]; !ok {\n            return fmt.Errorf(\"resource %s unknown\", r)\n        }\n        if c > b.need(pid, r) {\n            return errors.New(\"increase exceeds declared max\")\n        }\n    }\n    \n    \n    for r, c := range change {\n        b.allocation[pid][r] += c \n    }\n    defer func() {\n        if err != nil { \n            for r, c := range change {\n                b.allocation[pid][r] -= c \n            }\n        }\n    }()\n    \n    \n    cash := RMap{}\n    for r, a := range b.available {\n        cash[r] = a\n    }\n    perm := make([]PID, len(b.allocation))\n    i := 1\n    for pr, a := range b.allocation {\n        if pr == pid {\n            perm[0] = pr\n        } else {\n            perm[i] = pr\n            i++\n        }\n        for r, a := range a {\n            cash[r] -= a\n        }\n    }\n    ret := RMap{}  \n    m := len(perm) \n    for {\n        \n        h := 0\n    h:\n        for ; ; h++ {\n            if h == m {\n                \n                return errors.New(\"request would make deadlock possible\")\n            }\n            for r := range b.available {\n                if b.need(perm[h], r) > cash[r]+ret[r] {\n                    \n                    continue h\n                }\n            }\n            \n            log.Println(\" \", perm[h], \"could terminate\")\n            \n            break\n        }\n        if h == 0 { \n            \n            \n            return nil\n        }\n        for r, a := range b.allocation[perm[h]] {\n            ret[r] += a\n        }\n        m--\n        perm[h] = perm[m]\n    }\n}\n"}
{"id": 58169, "name": "Range extraction", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n"}
{"id": 58170, "name": "Machine code", "Python": "import ctypes\nimport os\nfrom ctypes import c_ubyte, c_int\n\ncode = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])\n\ncode_size = len(code)\n\nif (os.name == 'posix'):\n    import mmap\n    executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)\n    \n    executable_map.write(code)\n    \n    \n    func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))\nelif (os.name == 'nt'):\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    PAGE_EXECUTE_READWRITE = 0x40  \n    MEM_COMMIT = 0x1000\n    executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)\n    if (executable_buffer_address == 0):\n        print('Warning: Failed to enable code execution, call will likely cause a protection fault.')\n        func_address = ctypes.addressof(code_buffer)\n    else:\n        ctypes.memmove(executable_buffer_address, code_buffer, code_size)\n        func_address = executable_buffer_address\nelse:\n    \n    code_buffer = ctypes.create_string_buffer(code)\n    func_address = ctypes.addressof(code_buffer)\n\nprototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) \nfunc = prototype(func_address)                        \nres = func(7,12)\nprint(res)\n", "Go": "package main\n\nimport \"fmt\"\n\n\nimport \"C\"\n\nfunc main() {\n    code := []byte{\n        0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,\n        0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,\n        0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,\n        0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,\n    }\n    le := len(code)\n    buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,\n        C.MAP_PRIVATE|C.MAP_ANON, -1, 0)\n    codePtr := C.CBytes(code)\n    C.memcpy(buf, codePtr, C.size_t(le))\n    var a, b byte = 7, 12\n    fmt.Printf(\"%d + %d = \", a, b)\n    C.runMachineCode(buf, C.byte(a), C.byte(b))\n    C.munmap(buf, C.size_t(le))\n    C.free(codePtr)\n}\n"}
{"id": 58171, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n"}
{"id": 58172, "name": "Zhang-Suen thinning algorithm", "Python": "\n\n\nbeforeTxt = \n\n\nsmallrc01 = \n\nrc01 = \n\ndef intarray(binstring):\n    \n    return [[1 if ch == '1' else 0 for ch in line] \n            for line in binstring.strip().split()]\n\ndef chararray(intmatrix):\n    \n    return '\\n'.join(''.join(str(p) for p in row) for row in intmatrix)\n\ndef toTxt(intmatrix):\n    Return 8-neighbours of point p1 of picture, in order'''\n    i = image\n    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1\n    \n    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  \n            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  \n\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]    \n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))\n\ndef zhangSuen(image):\n    changing1 = changing2 = [(-1, -1)]\n    while changing1 or changing2:\n        \n        changing1 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P4 * P6 * P8 == 0 and   \n                    P2 * P4 * P6 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing1.append((x,y))\n        for x, y in changing1: image[y][x] = 0\n        \n        changing2 = []\n        for y in range(1, len(image) - 1):\n            for x in range(1, len(image[0]) - 1):\n                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)\n                if (image[y][x] == 1 and    \n                    P2 * P6 * P8 == 0 and   \n                    P2 * P4 * P8 == 0 and   \n                    transitions(n) == 1 and \n                    2 <= sum(n) <= 6):      \n                    changing2.append((x,y))\n        for x, y in changing2: image[y][x] = 0\n        \n        \n    return image\n            \n\nif __name__ == '__main__':\n    for picture in (beforeTxt, smallrc01, rc01):\n        image = intarray(picture)\n        print('\\nFrom:\\n%s' % toTxt(image))\n        after = zhangSuen(image)\n        print('\\nTo thinned:\\n%s' % toTxt(after))\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n"}
{"id": 58173, "name": "Median filter", "Python": "import Image, ImageFilter\nim = Image.open('image.ppm')\n\nmedian = im.filter(ImageFilter.MedianFilter(3))\nmedian.save('image2.ppm')\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"raster\"\n)\n\nvar g0, g1 *raster.Grmap\nvar ko [][]int\nvar kc []uint16\nvar mid int\n\nfunc init() {\n    \n    ko = [][]int{\n        {-1, -1}, {0, -1}, {1, -1},\n        {-1,  0}, {0,  0}, {1,  0},\n        {-1,  1}, {0,  1}, {1,  1}}\n    kc = make([]uint16, len(ko))\n    mid = len(ko) / 2\n}\n\nfunc main() {\n    \n    \n    \n    \n    \n    b, err := raster.ReadPpmFile(\"Lenna50.ppm\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    g0 = b.Grmap()\n    w, h := g0.Extent()\n    g1 = raster.NewGrmap(w, h)\n    for y := 0; y < h; y++ {\n        for x := 0; x < w; x++ {\n            g1.SetPx(x, y, median(x, y))\n        }\n    }\n    \n    \n    err = g1.Bitmap().WritePpmFile(\"median.ppm\")\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc median(x, y int) uint16 {\n    var n int\n    \n    \n    \n    for _, o := range ko {\n        \n        c, ok := g0.GetPx(x+o[0], y+o[1])\n        if !ok {\n            continue\n        }\n        \n        var i int\n        for ; i < n; i++ {\n            if c < kc[i] {\n                for j := n; j > i; j-- {\n                    kc[j] = kc[j-1]\n                }\n                break\n            }\n        }\n        kc[i] = c\n        n++\n    }\n    \n    switch {\n    case n == len(kc): \n        return kc[mid]\n    case n%2 == 1: \n        return kc[n/2]\n    }\n    \n    m := n / 2\n    return (kc[m-1] + kc[m]) / 2\n}\n"}
{"id": 58174, "name": "Median filter", "Python": "import Image, ImageFilter\nim = Image.open('image.ppm')\n\nmedian = im.filter(ImageFilter.MedianFilter(3))\nmedian.save('image2.ppm')\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"raster\"\n)\n\nvar g0, g1 *raster.Grmap\nvar ko [][]int\nvar kc []uint16\nvar mid int\n\nfunc init() {\n    \n    ko = [][]int{\n        {-1, -1}, {0, -1}, {1, -1},\n        {-1,  0}, {0,  0}, {1,  0},\n        {-1,  1}, {0,  1}, {1,  1}}\n    kc = make([]uint16, len(ko))\n    mid = len(ko) / 2\n}\n\nfunc main() {\n    \n    \n    \n    \n    \n    b, err := raster.ReadPpmFile(\"Lenna50.ppm\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    g0 = b.Grmap()\n    w, h := g0.Extent()\n    g1 = raster.NewGrmap(w, h)\n    for y := 0; y < h; y++ {\n        for x := 0; x < w; x++ {\n            g1.SetPx(x, y, median(x, y))\n        }\n    }\n    \n    \n    err = g1.Bitmap().WritePpmFile(\"median.ppm\")\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc median(x, y int) uint16 {\n    var n int\n    \n    \n    \n    for _, o := range ko {\n        \n        c, ok := g0.GetPx(x+o[0], y+o[1])\n        if !ok {\n            continue\n        }\n        \n        var i int\n        for ; i < n; i++ {\n            if c < kc[i] {\n                for j := n; j > i; j-- {\n                    kc[j] = kc[j-1]\n                }\n                break\n            }\n        }\n        kc[i] = c\n        n++\n    }\n    \n    switch {\n    case n == len(kc): \n        return kc[mid]\n    case n%2 == 1: \n        return kc[n/2]\n    }\n    \n    m := n / 2\n    return (kc[m-1] + kc[m]) / 2\n}\n"}
{"id": 58175, "name": "Run as a daemon or service", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n"}
{"id": 58176, "name": "Run as a daemon or service", "Python": "\nimport posix\nimport os\nimport sys\n\npid = posix.fork()\nif pid != 0:\n    print(\"Child process detached with pid %s\" % pid)\n    sys.exit(0)\n\nold_stdin = sys.stdin\nold_stdout = sys.stdout\nold_stderr = sys.stderr\n\nsys.stdin = open('/dev/null', 'rt')\nsys.stdout = open('/tmp/dmn.log', 'wt')\nsys.stderr = sys.stdout\n\nold_stdin.close()\nold_stdout.close()\nold_stderr.close()\n\nposix.setsid()\n\nimport time\nt = time.time()\nwhile time.time() < t + 10:\n    print(\"timer running, %s seconds\" % str(time.time() - t))\n    time.sleep(1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n"}
{"id": 58177, "name": "Coprime triplets", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n"}
{"id": 58178, "name": "Coprime triplets", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\ndef Gcd(v1, v2):\n    a, b = v1, v2\n    if (a < b):\n        a, b = v2, v1\n    r = 1\n    while (r != 0):\n        r = a % b\n        if (r != 0):\n            a = b\n            b = r\n    return b\n\n\na = [1, 2]\n\nn = 3\n\nwhile (n < 50):\n    gcd1 = Gcd(n, a[-1])\n    gcd2 = Gcd(n, a[-2])\n    \n    \n    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):\n        \n        a.append(n)\n        n = 3\n    else:\n        \n        n += 1\n\n\nfor i in range(0, len(a)):\n    if (i % 10 == 0):\n        print('')\n    print(\"%4d\" % a[i], end = '');\n    \n\nprint(\"\\n\\nNumber of elements in coprime triplets = \" + str(len(a)), end = \"\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n"}
{"id": 58179, "name": "Variable declaration reset", "Python": "s = [1, 2, 2, 3, 4, 4, 5]\n \nfor i in range(len(s)):\n    curr = s[i]\n    if i > 0 and curr == prev:\n        print(i)\n    prev = curr\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n"}
{"id": 58180, "name": "SOAP", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n"}
{"id": 58181, "name": "Pragmatic directives", "Python": "Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> import __future__\n>>> __future__.all_feature_names\n['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']\n>>>\n", "Go": "\n"}
{"id": 58182, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n"}
{"id": 58183, "name": "Find first and last set bit of a long integer", "Python": "def msb(x):\n    return x.bit_length() - 1\n\ndef lsb(x):\n    return msb(x & -x)\n\nfor i in range(6):\n    x = 42 ** i\n    print(\"%10d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n\nfor i in range(6):\n    x = 1302 ** i\n    print(\"%20d MSB: %2d LSB: %2d\" % (x, msb(x), lsb(x)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n"}
{"id": 58184, "name": "Numbers with equal rises and falls", "Python": "import itertools\n\ndef riseEqFall(num):\n    \n    height = 0\n    d1 = num % 10\n    num //= 10\n    while num:\n        d2 = num % 10\n        height += (d1<d2) - (d1>d2)\n        d1 = d2\n        num //= 10\n    return height == 0\n    \ndef sequence(start, fn):\n    \n    num=start-1\n    while True:\n        num += 1\n        while not fn(num): num += 1\n        yield num\n\na296712 = sequence(1, riseEqFall)\n\n\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n\n\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n"}
{"id": 58185, "name": "Terminal control_Cursor movement", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc main() {\n    tput(\"clear\") \n    tput(\"cup\", \"6\", \"3\") \n    time.Sleep(1 * time.Second)\n    tput(\"cub1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuf1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuu1\") \n    time.Sleep(1 * time.Second)\n    \n    tput(\"cud\", \"1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cr\") \n    time.Sleep(1 * time.Second)\n    \n    var h, w int\n    cmd := exec.Command(\"stty\", \"size\")\n    cmd.Stdin = os.Stdin\n    d, _ := cmd.Output()\n    fmt.Sscan(string(d), &h, &w)\n    \n    tput(\"hpa\", strconv.Itoa(w-1))\n    time.Sleep(2 * time.Second)\n    \n    tput(\"home\")\n    time.Sleep(2 * time.Second)\n    \n    tput(\"cup\", strconv.Itoa(h-1), strconv.Itoa(w-1))\n    time.Sleep(3 * time.Second)\n}\n\nfunc tput(args ...string) error {\n    cmd := exec.Command(\"tput\", args...)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n"}
{"id": 58186, "name": "Summation of primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    suma = 2\n    n = 1\n    for i in range(3, 2000000, 2):\n        if isPrime(i):\n            suma += i\n            n+=1 \n    print(suma)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    sum := 0\n    for _, p := range rcu.Primes(2e6 - 1) {\n        sum += p\n    }\n    fmt.Printf(\"The sum of all primes below 2 million is %s.\\n\", rcu.Commatize(sum))\n}\n"}
{"id": 58187, "name": "Koch curve", "Python": "l = 300\n\ndef setup():\n    size(400, 400)\n    background(0, 0, 255)\n    stroke(255)\n    \n    translate(width / 2.0, height / 2.0)\n    \n    translate(-l / 2.0, l * sqrt(3) / 6.0)\n    for i in range(4):\n        kcurve(0, l)\n        rotate(radians(120))\n        translate(-l, 0)\n\n\ndef kcurve(x1, x2):\n    s = (x2 - x1) / 3.0\n    if s < 5:\n        pushMatrix()\n        translate(x1, 0)\n        line(0, 0, s, 0)\n        line(2 * s, 0, 3 * s, 0)\n        translate(s, 0)\n        rotate(radians(60))\n        line(0, 0, s, 0)\n        translate(s, 0)\n        rotate(radians(-120))\n        line(0, 0, s, 0)\n        popMatrix()\n        return\n\n    pushMatrix()\n    translate(x1, 0)\n    kcurve(0, s)\n    kcurve(2 * s, 3 * s)\n    translate(s, 0)\n    rotate(radians(60))\n    kcurve(0, s)\n    translate(s, 0)\n    rotate(radians(-120))\n    kcurve(0, s)\n    popMatrix()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n"}
{"id": 58188, "name": "Draw pixel 2", "Python": "import Tkinter,random\ndef draw_pixel_2 ( sizex=640,sizey=480 ):\n    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )\n    root = Tkinter.Tk()\n    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )\n    can.create_rectangle( pos*2,outline='yellow' )\n    can.pack()\n    root.title('press ESCAPE to quit')\n    root.bind('<Escape>',lambda e : root.quit())\n    root.mainloop()\n\ndraw_pixel_2()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 640, 480)\n    img := image.NewRGBA(rect)\n\n    \n    blue := color.RGBA{0, 0, 255, 255}\n    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)\n\n    \n    yellow := color.RGBA{255, 255, 0, 255}\n    width := img.Bounds().Dx()\n    height := img.Bounds().Dy()\n    rand.Seed(time.Now().UnixNano())\n    x := rand.Intn(width)\n    y := rand.Intn(height)\n    img.Set(x, y, yellow)\n\n    \n    cmap := map[color.Color]string{blue: \"blue\", yellow: \"yellow\"}\n    for i := 0; i < width; i++ {\n        for j := 0; j < height; j++ {\n            c := img.At(i, j)\n            if cmap[c] == \"yellow\" {\n                fmt.Printf(\"The color of the pixel at (%d, %d) is yellow\\n\", i, j)\n            }\n        }\n    }\n}\n"}
{"id": 58189, "name": "Count how many vowels and consonants occur in a string", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n"}
{"id": 58190, "name": "Count how many vowels and consonants occur in a string", "Python": "def isvowel(c):\n    \n    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', \"I\", 'O', 'U']\n\ndef isletter(c):\n    \n    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\ndef isconsonant(c):\n    \n    return  not isvowel(c) and isletter(c)\n\ndef vccounts(s):\n    \n    a = list(s.lower())\n    au = set(a)\n    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \\\n        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])\n\ndef testvccount():\n    teststrings = [\n        \"Forever Python programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\"]\n    for s in teststrings:\n        vcnt, ccnt, vu, cu = vccounts(s)\n        print(f\"String: {s}\\n    Vowels: {vcnt} (distinct {vu})\\n    Consonants: {ccnt} (distinct {cu})\\n\")\n\ntestvccount()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n"}
{"id": 58191, "name": "Compiler_syntax analyzer", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n"}
{"id": 58192, "name": "Compiler_syntax analyzer", "Python": "def expr(p)\n    if tok is \"(\"\n        x = paren_expr()\n    elif tok in [\"-\", \"+\", \"!\"]\n        gettok()\n        y = expr(precedence of operator)\n        if operator was \"+\"\n            x = y\n        else\n            x = make_node(operator, y)\n    elif tok is an Identifier\n        x = make_leaf(Identifier, variable name)\n        gettok()\n    elif tok is an Integer constant\n        x = make_leaf(Integer, integer value)\n        gettok()\n    else\n        error()\n\n    while tok is a binary operator and precedence of tok >= p\n        save_tok = tok\n        gettok()\n        q = precedence of save_tok\n        if save_tok is not right associative\n            q += 1\n        x = make_node(Operator save_tok represents, x, expr(q))\n\n    return x\n\ndef paren_expr()\n    expect(\"(\")\n    x = expr(0)\n    expect(\")\")\n    return x\n\ndef stmt()\n    t = NULL\n    if accept(\"if\")\n        e = paren_expr()\n        s = stmt()\n        t = make_node(If, e, make_node(If, s, accept(\"else\") ? stmt() : NULL))\n    elif accept(\"putc\")\n        t = make_node(Prtc, paren_expr())\n        expect(\";\")\n    elif accept(\"print\")\n        expect(\"(\")\n        repeat\n            if tok is a string\n                e = make_node(Prts, make_leaf(String, the string))\n                gettok()\n            else\n                e = make_node(Prti, expr(0))\n\n            t = make_node(Sequence, t, e)\n        until not accept(\",\")\n        expect(\")\")\n        expect(\";\")\n    elif tok is \";\"\n        gettok()\n    elif tok is an Identifier\n        v = make_leaf(Identifier, variable name)\n        gettok()\n        expect(\"=\")\n        t = make_node(Assign, v, expr(0))\n        expect(\";\")\n    elif accept(\"while\")\n        e = paren_expr()\n        t = make_node(While, e, stmt()\n    elif accept(\"{\")\n        while tok not equal \"}\" and tok not equal end-of-file\n            t = make_node(Sequence, t, stmt())\n        expect(\"}\")\n    elif tok is end-of-file\n        pass\n    else\n        error()\n    return t\n\ndef parse()\n    t = NULL\n    gettok()\n    repeat\n        t = make_node(Sequence, t, stmt())\n    until tok is end-of-file\n    return t\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n"}
{"id": 58193, "name": "Draw a pixel", "Python": "from PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n"}
{"id": 58194, "name": "Numbers whose binary and ternary digit sums are prime", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n"}
{"id": 58195, "name": "Numbers whose binary and ternary digit sums are prime", "Python": "\n\n\n\ndef digitSumsPrime(n):\n    \n    def go(bases):\n        return all(\n            isPrime(digitSum(b)(n))\n            for b in bases\n        )\n    return go\n\n\n\ndef digitSum(base):\n    \n    def go(n):\n        q, r = divmod(n, base)\n        return go(q) + r if n else 0\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 200)\n        if digitSumsPrime(n)([2, 3])\n    ]\n    print(f'{len(xs)} matches in [1..199]\\n')\n    print(table(10)(xs))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\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 table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n"}
{"id": 58196, "name": "Words from neighbour ones", "Python": "\n\nimport urllib.request\nfrom collections import Counter\n \nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n \ndictionary = open(\"unixdict.txt\",\"r\")\n \nwordList = dictionary.read().split('\\n')\n \ndictionary.close()\n \nfilteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]\n\nfor word in filteredWords[:-9]:\n  position = filteredWords.index(word)\n  newWord = \"\".join([filteredWords[position+i][i] for i in range(0,9)])\n  if newWord in filteredWords:\n   print(newWord)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n"}
{"id": 58197, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "Python": "\n\nfrom functools import reduce\nfrom operator import mul\n\n\n\ndef p(n):\n    \n    digits = [int(c) for c in str(n)]\n    return not 0 in digits and (\n        0 != (n % reduce(mul, digits, 1))\n    ) and all(0 == n % d for d in digits)\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1000)\n        if p(n)\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matching numbers:\\n')\n    print('\\n'.join(\n        ' '.join(cell.rjust(w, ' ') for cell in row)\n        for row in chunksOf(10)(xs)\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var res []int\n    for n := 1; n < 1000; n++ {\n        digits := rcu.Digits(n, 10)\n        var all = true\n        for _, d := range digits {\n            if d == 0 || n%d != 0 {\n                all = false\n                break\n            }\n        }\n        if all {\n            prod := 1\n            for _, d := range digits {\n                prod *= d\n            }\n            if prod > 0 && n%prod != 0 {\n                res = append(res, n)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 1000 divisible by their digits, but not by the product thereof:\")\n    for i, n := range res {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such numbers found\\n\", len(res))\n}\n"}
{"id": 58198, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 58199, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n"}
{"id": 58200, "name": "Magic squares of singly even order", "Python": "import math\nfrom sys import stdout\n\nLOG_10 = 2.302585092994\n\n\n\ndef build_oms(s):\n    if s % 2 == 0:\n        s += 1\n    q = [[0 for j in range(s)] for i in range(s)]\n    p = 1\n    i = s // 2\n    j = 0\n    while p <= (s * s):\n        q[i][j] = p\n        ti = i + 1\n        if ti >= s: ti = 0\n        tj = j - 1\n        if tj < 0: tj = s - 1\n        if q[ti][tj] != 0:\n            ti = i\n            tj = j + 1\n        i = ti\n        j = tj\n        p = p + 1\n\n    return q, s\n\n\n\ndef build_sems(s):\n    if s % 2 == 1:\n        s += 1\n    while s % 4 == 0:\n        s += 2\n\n    q = [[0 for j in range(s)] for i in range(s)]\n    z = s // 2\n    b = z * z\n    c = 2 * b\n    d = 3 * b\n    o = build_oms(z)\n\n    for j in range(0, z):\n        for i in range(0, z):\n            a = o[0][i][j]\n            q[i][j] = a\n            q[i + z][j + z] = a + b\n            q[i + z][j] = a + c\n            q[i][j + z] = a + d\n\n    lc = z // 2\n    rc = lc\n    for j in range(0, z):\n        for i in range(0, s):\n            if i < lc or i > s - rc or (i == lc and j == lc):\n                if not (i == 0 and j == lc):\n                    t = q[i][j]\n                    q[i][j] = q[i][j + z]\n                    q[i][j + z] = t\n\n    return q, s\n\n\ndef format_sqr(s, l):\n    for i in range(0, l - len(s)):\n        s = \"0\" + s\n    return s + \" \"\n\n\ndef display(q):\n    s = q[1]\n    print(\" - {0} x {1}\\n\".format(s, s))\n    k = 1 + math.floor(math.log(s * s) / LOG_10)\n    for j in range(0, s):\n        for i in range(0, s):\n            stdout.write(format_sqr(\"{0}\".format(q[0][i][j]), k))\n        print()\n    print(\"Magic sum: {0}\\n\".format(s * ((s * s) + 1) // 2))\n\n\nstdout.write(\"Singly Even Magic Square\")\ndisplay(build_sems(6))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n"}
{"id": 58201, "name": "Generate Chess960 starting position", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n"}
{"id": 58202, "name": "Generate Chess960 starting position", "Python": ">>> from itertools import permutations\n>>> pieces = 'KQRrBbNN'\n>>> starts = {''.join(p).upper() for p in permutations(pieces)\n                     if p.index('B') % 2 != p.index('b') % 2 \t\t\n                     and ( p.index('r') < p.index('K') < p.index('R')\t\n                           or p.index('R') < p.index('K') < p.index('r') ) }\n>>> len(starts)\n960\n>>> starts.pop()\n'QNBRNKRB'\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n"}
{"id": 58203, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 58204, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n"}
{"id": 58205, "name": "Perlin noise", "Python": "import math\n\ndef perlin_noise(x, y, z):\n    X = math.floor(x) & 255                  \n    Y = math.floor(y) & 255                  \n    Z = math.floor(z) & 255\n    x -= math.floor(x)                                \n    y -= math.floor(y)                                \n    z -= math.floor(z)\n    u = fade(x)                                \n    v = fade(y)                                \n    w = fade(z)\n    A = p[X  ]+Y; AA = p[A]+Z; AB = p[A+1]+Z      \n    B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z      \n \n    return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                   grad(p[BA  ], x-1, y  , z   )), \n                           lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                   grad(p[BB  ], x-1, y-1, z   ))),\n                   lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                   grad(p[BA+1], x-1, y  , z-1 )), \n                           lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                   grad(p[BB+1], x-1, y-1, z-1 ))))\n                                   \ndef fade(t): \n    return t ** 3 * (t * (t * 6 - 15) + 10)\n    \ndef lerp(t, a, b):\n    return a + t * (b - a)\n    \ndef grad(hash, x, y, z):\n    h = hash & 15                      \n    u = x if h<8 else y                \n    v = y if h<4 else (x if h in (12, 14) else z)\n    return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)\n\np = [None] * 512\npermutation = [151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]\nfor i in range(256):\n    p[256+i] = p[i] = permutation[i]\n\nif __name__ == '__main__':\n    print(\"%1.17f\" % perlin_noise(3.14, 42, 7))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n    X := int(math.Floor(x)) & 255\n    Y := int(math.Floor(y)) & 255\n    Z := int(math.Floor(z)) & 255\n    x -= math.Floor(x)\n    y -= math.Floor(y)\n    z -= math.Floor(z)\n    u := fade(x)\n    v := fade(y)\n    w := fade(z)\n    A := p[X] + Y\n    AA := p[A] + Z\n    AB := p[A+1] + Z\n    B := p[X+1] + Y\n    BA := p[B] + Z\n    BB := p[B+1] + Z\n    return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n        grad(p[BA], x-1, y, z)),\n        lerp(u, grad(p[AB], x, y-1, z),\n            grad(p[BB], x-1, y-1, z))),\n        lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n            grad(p[BA+1], x-1, y, z-1)),\n            lerp(u, grad(p[AB+1], x, y-1, z-1),\n                grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n    \n    \n    \n    switch hash & 15 {\n    case 0, 12:\n        return x + y\n    case 1, 14:\n        return y - x\n    case 2:\n        return x - y\n    case 3:\n        return -x - y\n    case 4:\n        return x + z\n    case 5:\n        return z - x\n    case 6:\n        return x - z\n    case 7:\n        return -x - z\n    case 8:\n        return y + z\n    case 9, 13:\n        return z - y\n    case 10:\n        return y - z\n    }\n    \n    return -y - z\n}\n\nvar permutation = []int{\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n    140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n    247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n    57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n    74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n    60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n    65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n    200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n    52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n    207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n    119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n    129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n    218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n    81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n    184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n    222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)\n"}
{"id": 58206, "name": "File size distribution", "Python": "import sys, os\nfrom collections import Counter\n\ndef dodir(path):\n    global h\n\n    for name in os.listdir(path):\n        p = os.path.join(path, name)\n\n        if os.path.islink(p):\n            pass\n        elif os.path.isfile(p):\n            h[os.stat(p).st_size] += 1\n        elif os.path.isdir(p):\n            dodir(p)\n        else:\n            pass\n\ndef main(arg):\n    global h\n    h = Counter()\n    for dir in arg:\n        dodir(dir)\n\n    s = n = 0\n    for k, v in sorted(h.items()):\n        print(\"Size %d -> %d file(s)\" % (k, v))\n        n += v\n        s += k * v\n    print(\"Total %d bytes for %d files\" % (s, n))\n\nmain(sys.argv[1:])\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc commatize(n int64) 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 fileSizeDistribution(root string) {\n    var sizes [12]int\n    files := 0\n    directories := 0\n    totalSize := int64(0)\n    walkFunc := func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        files++\n        if info.IsDir() {\n            directories++\n        }\n        size := info.Size()\n        if size == 0 {\n            sizes[0]++\n            return nil\n        }\n        totalSize += size\n        logSize := math.Log10(float64(size))\n        index := int(math.Floor(logSize))\n        sizes[index+1]++\n        return nil\n    }\n    err := filepath.Walk(root, walkFunc)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n    for i := 0; i < len(sizes); i++ {\n        if i == 0 {\n            fmt.Print(\"  \")\n        } else {\n            fmt.Print(\"+ \")\n        }\n        fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n    }\n    fmt.Println(\"                                  -----\")\n    fmt.Printf(\"= Total number of files         : %5d\\n\", files)\n    fmt.Printf(\"  including directories         : %5d\\n\", directories)\n    c := commatize(totalSize)\n    fmt.Println(\"\\n  Total size of files           :\", c, \"bytes\")\n}\n\nfunc main() {\n    fileSizeDistribution(\"./\")\n}\n"}
{"id": 58207, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n"}
{"id": 58208, "name": "Rendezvous", "Python": "\nfrom __future__ import annotations\n\nimport asyncio\nimport sys\n\nfrom typing import Optional\nfrom typing import TextIO\n\n\nclass OutOfInkError(Exception):\n    \n\n\nclass Printer:\n    def __init__(self, name: str, backup: Optional[Printer]):\n        self.name = name\n        self.backup = backup\n\n        self.ink_level: int = 5\n        self.output_stream: TextIO = sys.stdout\n\n    async def print(self, msg):\n        if self.ink_level <= 0:\n            if self.backup:\n                await self.backup.print(msg)\n            else:\n                raise OutOfInkError(self.name)\n        else:\n            self.ink_level -= 1\n            self.output_stream.write(f\"({self.name}): {msg}\\n\")\n\n\nasync def main():\n    reserve = Printer(\"reserve\", None)\n    main = Printer(\"main\", reserve)\n\n    humpty_lines = [\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men,\",\n        \"Couldn't put Humpty together again.\",\n    ]\n\n    goose_lines = [\n        \"Old Mother Goose,\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air,\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n    ]\n\n    async def print_humpty():\n        for line in humpty_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Humpty Dumpty out of ink!\")\n                break\n\n    async def print_goose():\n        for line in goose_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Mother Goose out of ink!\")\n                break\n\n    await asyncio.gather(print_goose(), print_humpty())\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main(), debug=True)\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n    \"sync\"\n)\n\nvar hdText = `Humpty Dumpty sat on a wall.\nHumpty Dumpty had a great fall.\nAll the king's horses and all the king's men,\nCouldn't put Humpty together again.`\n\nvar mgText = `Old Mother Goose,\nWhen she wanted to wander,\nWould ride through the air,\nOn a very fine gander.\nJack's mother came in,\nAnd caught the goose soon,\nAnd mounting its back,\nFlew up to the moon.`\n\nfunc main() {\n    reservePrinter := startMonitor(newPrinter(5), nil)\n    mainPrinter := startMonitor(newPrinter(5), reservePrinter)\n    var busy sync.WaitGroup\n    busy.Add(2)\n    go writer(mainPrinter, \"hd\", hdText, &busy)\n    go writer(mainPrinter, \"mg\", mgText, &busy)\n    busy.Wait()\n}\n\n\n\n\ntype printer func(string) error\n\n\n\n\n\nfunc newPrinter(ink int) printer {\n    return func(line string) error {\n        if ink == 0 {\n            return eOutOfInk\n        }\n        for _, c := range line {\n            fmt.Printf(\"%c\", c)\n        }\n        fmt.Println()\n        ink--\n        return nil\n    }\n}\n\nvar eOutOfInk = errors.New(\"out of ink\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype rSync struct {\n    call     chan string\n    response chan error\n}\n\n\n\n\n\n\nfunc (r *rSync) print(data string) error {\n    r.call <- data      \n    return <-r.response \n}\n\n\n\n\nfunc monitor(hardPrint printer, entry, reserve *rSync) {\n    for {\n        \n        \n        data := <-entry.call\n        \n        \n        \n\n        \n        switch err := hardPrint(data); {\n\n        \n        case err == nil:\n            entry.response <- nil \n\n        case err == eOutOfInk && reserve != nil:\n            \n            \n            \n            \n            entry.response <- reserve.print(data)\n\n        default:\n            entry.response <- err \n        }\n        \n    }\n}\n\n\n\n\n\n\nfunc startMonitor(p printer, reservePrinter *rSync) *rSync {\n    entry := &rSync{make(chan string), make(chan error)}\n    go monitor(p, entry, reservePrinter)\n    return entry\n}\n\n\n\n\n\n\nfunc writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {\n    for _, line := range strings.Split(text, \"\\n\") {\n        if err := printMonitor.print(line); err != nil {\n            fmt.Printf(\"**** writer task %q terminated: %v ****\\n\", id, err)\n            break\n        }\n    }\n    busy.Done()\n}\n"}
{"id": 58209, "name": "Rendezvous", "Python": "\nfrom __future__ import annotations\n\nimport asyncio\nimport sys\n\nfrom typing import Optional\nfrom typing import TextIO\n\n\nclass OutOfInkError(Exception):\n    \n\n\nclass Printer:\n    def __init__(self, name: str, backup: Optional[Printer]):\n        self.name = name\n        self.backup = backup\n\n        self.ink_level: int = 5\n        self.output_stream: TextIO = sys.stdout\n\n    async def print(self, msg):\n        if self.ink_level <= 0:\n            if self.backup:\n                await self.backup.print(msg)\n            else:\n                raise OutOfInkError(self.name)\n        else:\n            self.ink_level -= 1\n            self.output_stream.write(f\"({self.name}): {msg}\\n\")\n\n\nasync def main():\n    reserve = Printer(\"reserve\", None)\n    main = Printer(\"main\", reserve)\n\n    humpty_lines = [\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men,\",\n        \"Couldn't put Humpty together again.\",\n    ]\n\n    goose_lines = [\n        \"Old Mother Goose,\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air,\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n    ]\n\n    async def print_humpty():\n        for line in humpty_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Humpty Dumpty out of ink!\")\n                break\n\n    async def print_goose():\n        for line in goose_lines:\n            try:\n                task = asyncio.Task(main.print(line))\n                await task\n            except OutOfInkError:\n                print(\"\\t Mother Goose out of ink!\")\n                break\n\n    await asyncio.gather(print_goose(), print_humpty())\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main(), debug=True)\n", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n    \"sync\"\n)\n\nvar hdText = `Humpty Dumpty sat on a wall.\nHumpty Dumpty had a great fall.\nAll the king's horses and all the king's men,\nCouldn't put Humpty together again.`\n\nvar mgText = `Old Mother Goose,\nWhen she wanted to wander,\nWould ride through the air,\nOn a very fine gander.\nJack's mother came in,\nAnd caught the goose soon,\nAnd mounting its back,\nFlew up to the moon.`\n\nfunc main() {\n    reservePrinter := startMonitor(newPrinter(5), nil)\n    mainPrinter := startMonitor(newPrinter(5), reservePrinter)\n    var busy sync.WaitGroup\n    busy.Add(2)\n    go writer(mainPrinter, \"hd\", hdText, &busy)\n    go writer(mainPrinter, \"mg\", mgText, &busy)\n    busy.Wait()\n}\n\n\n\n\ntype printer func(string) error\n\n\n\n\n\nfunc newPrinter(ink int) printer {\n    return func(line string) error {\n        if ink == 0 {\n            return eOutOfInk\n        }\n        for _, c := range line {\n            fmt.Printf(\"%c\", c)\n        }\n        fmt.Println()\n        ink--\n        return nil\n    }\n}\n\nvar eOutOfInk = errors.New(\"out of ink\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype rSync struct {\n    call     chan string\n    response chan error\n}\n\n\n\n\n\n\nfunc (r *rSync) print(data string) error {\n    r.call <- data      \n    return <-r.response \n}\n\n\n\n\nfunc monitor(hardPrint printer, entry, reserve *rSync) {\n    for {\n        \n        \n        data := <-entry.call\n        \n        \n        \n\n        \n        switch err := hardPrint(data); {\n\n        \n        case err == nil:\n            entry.response <- nil \n\n        case err == eOutOfInk && reserve != nil:\n            \n            \n            \n            \n            entry.response <- reserve.print(data)\n\n        default:\n            entry.response <- err \n        }\n        \n    }\n}\n\n\n\n\n\n\nfunc startMonitor(p printer, reservePrinter *rSync) *rSync {\n    entry := &rSync{make(chan string), make(chan error)}\n    go monitor(p, entry, reservePrinter)\n    return entry\n}\n\n\n\n\n\n\nfunc writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {\n    for _, line := range strings.Split(text, \"\\n\") {\n        if err := printMonitor.print(line); err != nil {\n            fmt.Printf(\"**** writer task %q terminated: %v ****\\n\", id, err)\n            break\n        }\n    }\n    busy.Done()\n}\n"}
{"id": 58210, "name": "First class environments", "Python": "environments = [{'cnt':0, 'seq':i+1} for i in range(12)]\n\ncode = \n\nwhile any(env['seq'] > 1 for env in environments):\n    for env in environments:\n        exec(code, globals(), env)\n    print()\n\nprint('Counts')\nfor env in environments:\n    print('% 4d' % env['cnt'], end='')\nprint()\n", "Go": "package main\n\nimport \"fmt\"\n\nconst jobs = 12\n\ntype environment struct{ seq, cnt int }\n\nvar (\n    env      [jobs]environment\n    seq, cnt *int\n)\n\nfunc hail() {\n    fmt.Printf(\"% 4d\", *seq)\n    if *seq == 1 {\n        return\n    }\n    (*cnt)++\n    if *seq&1 != 0 {\n        *seq = 3*(*seq) + 1\n    } else {\n        *seq /= 2\n    }\n}\n\nfunc switchTo(id int) {\n    seq = &env[id].seq\n    cnt = &env[id].cnt\n}\n\nfunc main() {\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        env[i].seq = i + 1\n    }\n\nagain:\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        hail()\n    }\n    fmt.Println()\n\n    for j := 0; j < jobs; j++ {\n        switchTo(j)\n        if *seq != 1 {\n            goto again\n        }\n    }\n    fmt.Println()\n\n    fmt.Println(\"COUNTS:\")\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        fmt.Printf(\"% 4d\", *cnt)\n    }\n    fmt.Println()\n}\n"}
{"id": 58211, "name": "UTF-8 encode and decode", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n"}
{"id": 58212, "name": "UTF-8 encode and decode", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n"}
{"id": 58213, "name": "Xiaolin Wu's line algorithm", "Python": "\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n    return x - int(x)\n\ndef _rfpart(x):\n    return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n    \n    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n    c = compose_color(img.getpixel(xy), color)\n    img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n    \n    x1, y1 = p1\n    x2, y2 = p2\n    dx, dy = x2-x1, y2-y1\n    steep = abs(dx) < abs(dy)\n    p = lambda px, py: ((px,py), (py,px))[steep]\n\n    if steep:\n        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n    if x2 < x1:\n        x1, x2, y1, y2 = x2, x1, y2, y1\n\n    grad = dy/dx\n    intery = y1 + _rfpart(x1) * grad\n    def draw_endpoint(pt):\n        x, y = pt\n        xend = round(x)\n        yend = y + grad * (xend - x)\n        xgap = _rfpart(x + 0.5)\n        px, py = int(xend), int(yend)\n        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n        return px\n\n    xstart = draw_endpoint(p(*p1)) + 1\n    xend = draw_endpoint(p(*p2))\n\n    for x in range(xstart, xend):\n        y = int(intery)\n        putpixel(img, p(x, y), color, _rfpart(intery))\n        putpixel(img, p(x, y+1), color, _fpart(intery))\n        intery += grad\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print 'usage: python xiaolinwu.py [output-file]'\n        sys.exit(-1)\n\n    blue = (0, 0, 255)\n    yellow = (255, 255, 0)\n    img = Image.new(\"RGB\", (500,500), blue)\n    for a in range(10, 431, 60):\n        draw_line(img, (10, 10), (490, a), yellow)\n        draw_line(img, (10, 10), (a, 490), yellow)\n    draw_line(img, (10, 10), (490, 490), yellow)\n    filename = sys.argv[1]\n    img.save(filename)\n    print 'image saved to', filename\n", "Go": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n    return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n    return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n    return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n    return 1 - fpart(x)\n}\n\n\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n    \n    dx := x2 - x1\n    dy := y2 - y1\n    ax := dx\n    if ax < 0 {\n        ax = -ax\n    }\n    ay := dy\n    if ay < 0 {\n        ay = -ay\n    }\n    \n    var plot func(int, int, float64)\n    if ax < ay {\n        x1, y1 = y1, x1\n        x2, y2 = y2, x2\n        dx, dy = dy, dx\n        plot = func(x, y int, c float64) {\n            g.SetPx(y, x, uint16(c*math.MaxUint16))\n        }\n    } else {\n        plot = func(x, y int, c float64) {\n            g.SetPx(x, y, uint16(c*math.MaxUint16))\n        }\n    }\n    if x2 < x1 {\n        x1, x2 = x2, x1\n        y1, y2 = y2, y1\n    }\n    gradient := dy / dx\n\n    \n    xend := round(x1)\n    yend := y1 + gradient*(xend-x1)\n    xgap := rfpart(x1 + .5)\n    xpxl1 := int(xend) \n    ypxl1 := int(ipart(yend))\n    plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n    intery := yend + gradient \n\n    \n    xend = round(x2)\n    yend = y2 + gradient*(xend-x2)\n    xgap = fpart(x2 + 0.5)\n    xpxl2 := int(xend) \n    ypxl2 := int(ipart(yend))\n    plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n    \n    for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n        plot(x, int(ipart(intery)), rfpart(intery))\n        plot(x, int(ipart(intery))+1, fpart(intery))\n        intery = intery + gradient\n    }\n}\n"}
{"id": 58214, "name": "Keyboard macros", "Python": "\nimport curses\n\ndef print_message():\n    stdscr.addstr('This is the message.\\n')\n\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.addstr('CTRL+P for message or q to quit.\\n')\nwhile True:\n    c = stdscr.getch()\n    if c == 16: print_message()\n    elif c == ord('q'): break\n\ncurses.nocbreak()\nstdscr.keypad(0)\ncurses.echo()\ncurses.endwin()\n", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"unsafe\"\n\nfunc main() {\n    d := C.XOpenDisplay(nil)\n    f7, f6 := C.CString(\"F7\"), C.CString(\"F6\")\n    defer C.free(unsafe.Pointer(f7))\n    defer C.free(unsafe.Pointer(f6))\n\n    if d != nil {\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),\n            C.Mod1Mask, \n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),\n            C.Mod1Mask,\n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n\n        var event C.XEvent\n        for {\n            C.XNextEvent(d, &event)\n            if C.getXEvent_type(event) == C.KeyPress {\n                xkeyEvent := C.getXEvent_xkey(event)\n                s := C.XLookupKeysym(&xkeyEvent, 0)\n                if s == C.XK_F7 {\n                    fmt.Println(\"something's happened\")\n                } else if s == C.XK_F6 {\n                    break\n                }\n            }\n        }\n\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n    } else {\n        fmt.Println(\"XOpenDisplay did not succeed\")\n    }\n}\n"}
{"id": 58215, "name": "McNuggets problem", "Python": ">>> from itertools import product\n>>> nuggets = set(range(101))\n>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):\n\tnuggets.discard(6*s + 9*n + 20*t)\n\n\t\n>>> max(nuggets)\n43\n>>>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n    sv := make([]bool, limit+1) \n    for s := 0; s <= limit; s += 6 {\n        for n := s; n <= limit; n += 9 {\n            for t := n; t <= limit; t += 20 {\n                sv[t] = true\n            }\n        }\n    }\n    for i := limit; i >= 0; i-- {\n        if !sv[i] {\n            fmt.Println(\"Maximum non-McNuggets number is\", i)\n            return\n        }\n    }\n}\n\nfunc main() {\n    mcnugget(100)\n}\n"}
{"id": 58216, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"}
{"id": 58217, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 58218, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 58219, "name": "Extreme floating point values", "Python": ">>> \n>>> inf = 1e234 * 1e234\n>>> _inf = 1e234 * -1e234\n>>> _zero = 1 / _inf\n>>> nan = inf + _inf\n>>> inf, _inf, _zero, nan\n(inf, -inf, -0.0, nan)\n>>> \n>>> for value in (inf, _inf, _zero, nan): print (value)\n\ninf\n-inf\n-0.0\nnan\n>>> \n>>> float('nan')\nnan\n>>> float('inf')\ninf\n>>> float('-inf')\n-inf\n>>> -0.\n-0.0\n>>> \n>>> nan == nan\nFalse\n>>> nan is nan\nTrue\n>>> 0. == -0.\nTrue\n>>> 0. is -0.\nFalse\n>>> inf + _inf\nnan\n>>> 0.0 * nan\nnan\n>>> nan * 0.0\nnan\n>>> 0.0 * inf\nnan\n>>> inf * 0.0\nnan\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n"}
{"id": 58220, "name": "Pseudo-random numbers_Xorshift star", "Python": "mask64 = (1 << 64) - 1\nmask32 = (1 << 32) - 1\nconst = 0x2545F4914F6CDD1D\n\n\n\nclass Xorshift_star():\n    \n    def __init__(self, seed=0):\n        self.state = seed & mask64\n\n    def seed(self, num):\n        self.state =  num & mask64\n    \n    def next_int(self):\n        \"return random int between 0 and 2**32\"\n        x = self.state\n        x = (x ^ (x >> 12)) & mask64\n        x = (x ^ (x << 25)) & mask64\n        x = (x ^ (x >> 27)) & mask64\n        self.state = x\n        answer = (((x * const) & mask64) >> 32) & mask32 \n        return answer\n    \n    def  next_float(self):\n        \"return random float between 0 and 1\"\n        return self.next_int() / (1 << 32)\n    \n\nif __name__ == '__main__':\n    random_gen = Xorshift_star()\n    random_gen.seed(1234567)\n    for i in range(5):\n        print(random_gen.next_int())\n        \n    random_gen.seed(987654321)\n    hist = {i:0 for i in range(5)}\n    for i in range(100_000):\n        hist[int(random_gen.next_float() *5)] += 1\n    print(hist)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n"}
{"id": 58221, "name": "Four is the number of letters in the ...", "Python": "\n\n\n\n\nimport inflect\n\ndef count_letters(word):\n    \n    count = 0\n    for letter in word:\n        if letter != ',' and letter !='-' and letter !=' ':\n            count += 1\n            \n    return count\n    \ndef split_with_spaces(sentence):\n    \n    sentence_list = []\n    curr_word = \"\"\n    for c in sentence:\n        if c == \" \" and curr_word != \"\":\n            \n            \n            sentence_list.append(curr_word+\" \")\n            curr_word = \"\"\n        else:\n            curr_word += c\n    \n    \n    \n    if len(curr_word) > 0:\n        sentence_list.append(curr_word)\n    \n    return sentence_list\n    \ndef my_num_to_words(p, my_number):\n    \n    \n    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')\n    \n    number_string = number_string_list[0]\n    \n    for i in range(1,len(number_string_list)):\n        number_string += \" \" + number_string_list[i]\n    \n    return number_string\n        \ndef build_sentence(p, max_words):\n    \n    \n    \n    \n    sentence_list = split_with_spaces(\"Four is the number of letters in the first word of this sentence,\")\n      \n    num_words = 13\n    \n    \n    \n    \n    word_number = 2\n    \n    \n    \n    while num_words < max_words:\n        \n        \n        \n        \n        \n        ordinal_string = my_num_to_words(p, p.ordinal(word_number))\n        \n        \n        \n        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))\n        \n        \n        \n        new_string = \" \"+word_number_string+\" in the \"+ordinal_string+\",\"\n\n        new_list = split_with_spaces(new_string)\n        \n        sentence_list += new_list\n\n        \n        \n        num_words += len(new_list)\n        \n        \n        \n        word_number += 1\n        \n    return sentence_list, num_words\n    \ndef word_and_counts(word_num):\n    \n        \n    sentence_list, num_words = build_sentence(p, word_num)\n    \n    word_str = sentence_list[word_num - 1].strip(' ,')\n    \n    num_letters = len(word_str)\n    \n    num_characters = 0\n    \n    for word in sentence_list:\n       num_characters += len(word)\n       \n    print('Word {0:8d} is \"{1}\", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))\n   \n    \np = inflect.engine()\n\nsentence_list, num_words = build_sentence(p, 201)\n\nprint(\" \")\nprint(\"The lengths of the first 201 words are:\")\nprint(\" \")\n\nprint('{0:3d}:  '.format(1),end='')\n\ntotal_characters = 0\n\nfor word_index in range(201):\n\n    word_length = count_letters(sentence_list[word_index])\n    \n    total_characters += len(sentence_list[word_index])\n    \n    print('{0:2d}'.format(word_length),end='')\n    if (word_index+1) % 20 == 0:\n        \n        print(\" \")\n        print('{0:3d}:  '.format(word_index + 2),end='')\n    else:\n        print(\" \",end='')\n \nprint(\" \")\nprint(\" \")\nprint(\"Length of the sentence so far: \"+str(total_characters))\nprint(\" \")\n\n\n\nword_and_counts(1000)\nword_and_counts(10000)\nword_and_counts(100000)\nword_and_counts(1000000)\nword_and_counts(10000000)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n"}
{"id": 58222, "name": "ASCII art diagram converter", "Python": "\n\ndef validate(diagram):\n\n    \n    \n    rawlines = diagram.splitlines()\n    lines = []\n    for line in rawlines:\n        if line != '':\n            lines.append(line)\n            \n    \n            \n    if len(lines) == 0:\n        print('diagram has no non-empty lines!')\n        return None\n        \n    width = len(lines[0])\n    cols = (width - 1) // 3\n    \n    if cols not in [8, 16, 32, 64]: \n        print('number of columns should be 8, 16, 32 or 64')\n        return None\n        \n    if len(lines)%2 == 0:\n        print('number of non-empty lines should be odd')\n        return None\n    \n    if lines[0] != (('+--' * cols)+'+'):\n            print('incorrect header line')\n            return None\n\n    for i in range(len(lines)):\n        line=lines[i]\n        if i == 0:\n            continue\n        elif i%2 == 0:\n            if line != lines[0]:\n                print('incorrect separator line')\n                return None\n        elif len(line) != width:\n            print('inconsistent line widths')\n            return None\n        elif line[0] != '|' or line[width-1] != '|':\n            print(\"non-separator lines must begin and end with '|'\")    \n            return None\n    \n    return lines\n\n\n\ndef decode(lines):\n    print(\"Name     Bits  Start  End\")\n    print(\"=======  ====  =====  ===\")\n    \n    startbit = 0\n    \n    results = []\n    \n    for line in lines:\n        infield=False\n        for c in line:\n            if not infield and c == '|':\n                infield = True\n                spaces = 0\n                name = ''\n            elif infield:\n                if c == ' ':\n                    spaces += 1\n                elif c != '|':\n                    name += c\n                else:\n                    bits = (spaces + len(name) + 1) // 3\n                    endbit = startbit + bits - 1\n                    print('{0:7}    {1:2d}     {2:2d}   {3:2d}'.format(name, bits, startbit, endbit))\n                    reslist = [name, bits, startbit, endbit]\n                    results.append(reslist)\n                    spaces = 0\n                    name = ''\n                    startbit += bits\n                    \n    return results\n                        \ndef unpack(results, hex):\n    print(\"\\nTest string in hex:\")\n    print(hex)\n    print(\"\\nTest string in binary:\")\n    bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n    print(bin)\n    print(\"\\nUnpacked:\\n\")\n    print(\"Name     Size  Bit pattern\")\n    print(\"=======  ====  ================\")\n    for r in results:\n        name = r[0]\n        size = r[1]\n        startbit = r[2]\n        endbit = r[3]\n        bitpattern = bin[startbit:endbit+1]\n        print('{0:7}    {1:2d}  {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \n\nlines = validate(diagram)\n\nif lines == None:\n    print(\"No lines returned\")\nelse:\n    print(\" \")\n    print(\"Diagram after trimming whitespace and removal of blank lines:\")\n    print(\" \")\n    for line in lines:\n        print(line)\n        \n    print(\" \")\n    print(\"Decoded:\")\n    print(\" \")\n\n    results = decode(lines)    \n    \n    \n    \n    hex = \"78477bbf5496e12e1bf169a4\" \n    \n    unpack(results, hex)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n"}
{"id": 58223, "name": "Levenshtein distance_Alignment", "Python": "from difflib import ndiff\n\ndef levenshtein(str1, str2):\n    result = \"\"\n    pos, removed = 0, 0\n    for x in ndiff(str1, str2):\n        if pos<len(str1) and str1[pos] == x[2]:\n          pos += 1\n          result += x[2]\n          if x[0] == \"-\":\n              removed += 1\n          continue\n        else:\n          if removed > 0:\n            removed -=1\n          else:\n            result += \"-\"\n    print(result)\n\nlevenshtein(\"place\",\"palace\")\nlevenshtein(\"rosettacode\",\"raisethysword\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"github.com/biogo/biogo/align\"\n    ab \"github.com/biogo/biogo/alphabet\"\n    \"github.com/biogo/biogo/feat\"\n    \"github.com/biogo/biogo/seq/linear\"\n)\n\nfunc main() {\n    \n    \n    lc := ab.Must(ab.NewAlphabet(\"-abcdefghijklmnopqrstuvwxyz\",\n        feat.Undefined, '-', 0, true))\n    \n    \n    \n    \n    nw := make(align.NW, lc.Len())\n    for i := range nw {\n        r := make([]int, lc.Len())\n        nw[i] = r\n        for j := range r {\n            if j != i {\n                r[j] = -1\n            }\n        }\n    }\n    \n    a := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"rosettacode\"))}\n    a.Alpha = lc\n    b := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"raisethysword\"))}\n    b.Alpha = lc\n    \n    aln, err := nw.Align(a, b)\n    \n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fa := align.Format(a, b, aln, '-')\n    fmt.Printf(\"%s\\n%s\\n\", fa[0], fa[1])\n    aa := fmt.Sprint(fa[0])\n    ba := fmt.Sprint(fa[1])\n    ma := make([]byte, len(aa))\n    for i := range ma {\n        if aa[i] == ba[i] {\n            ma[i] = ' '\n        } else {\n            ma[i] = '|'\n        }\n    }\n    fmt.Println(string(ma))\n}\n"}
{"id": 58224, "name": "Compare sorting algorithms' performance", "Python": "def builtinsort(x):\n    x.sort()\n\ndef partition(seq, pivot):\n   low, middle, up = [], [], []\n   for x in seq:\n       if x < pivot:\n           low.append(x)\n       elif x == pivot:\n           middle.append(x)\n       else:\n           up.append(x)\n   return low, middle, up\nimport random\ndef qsortranpart(seq):\n   size = len(seq)\n   if size < 2: return seq\n   low, middle, up = partition(seq, random.choice(seq))\n   return qsortranpart(low) + middle + qsortranpart(up)\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"math/rand\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/gonum/plot\"\n    \"github.com/gonum/plot/plotter\"\n    \"github.com/gonum/plot/plotutil\"\n    \"github.com/gonum/plot/vg\"\n)\n\n\n\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\nfunc insertionsort(a []int) {\n    for i := 1; i < len(a); i++ {\n        value := a[i]\n        j := i - 1\n        for j >= 0 && a[j] > value {\n            a[j+1] = a[j]\n            j = j - 1\n        }\n        a[j+1] = value\n    }\n}\n\nfunc quicksort(a []int) {\n    var pex func(int, int)\n    pex = func(lower, upper int) {\n        for {\n            switch upper - lower {\n            case -1, 0:\n                return\n            case 1:\n                if a[upper] < a[lower] {\n                    a[upper], a[lower] = a[lower], a[upper]\n                }\n                return\n            }\n            bx := (upper + lower) / 2\n            b := a[bx]\n            lp := lower\n            up := upper\n        outer:\n            for {\n                for lp < upper && !(b < a[lp]) {\n                    lp++\n                }\n                for {\n                    if lp > up {\n                        break outer\n                    }\n                    if a[up] < b {\n                        break\n                    }\n                    up--\n                }\n                a[lp], a[up] = a[up], a[lp]\n                lp++\n                up--\n            }\n            if bx < lp {\n                if bx < lp-1 {\n                    a[bx], a[lp-1] = a[lp-1], b\n                }\n                up = lp - 2\n            } else {\n                if bx > lp {\n                    a[bx], a[lp] = a[lp], b\n                }\n                up = lp - 1\n                lp++\n            }\n            if up-lower < upper-lp {\n                pex(lower, up)\n                lower = lp\n            } else {\n                pex(lp, upper)\n                upper = up\n            }\n        }\n    }\n    pex(0, len(a)-1)\n}\n\n\n\nfunc ones(n int) []int {\n    s := make([]int, n)\n    for i := range s {\n        s[i] = 1\n    }\n    return s\n}\n\nfunc ascending(n int) []int {\n    s := make([]int, n)\n    v := 1\n    for i := 0; i < n; {\n        if rand.Intn(3) == 0 {\n            s[i] = v\n            i++\n        }\n        v++\n    }\n    return s\n}\n\nfunc shuffled(n int) []int {\n    return rand.Perm(n)\n}\n\n\n\n\n\n\nconst (\n    nPts = 7    \n    inc  = 1000 \n)\n\nvar (\n    p        *plot.Plot\n    sortName = []string{\"Bubble sort\", \"Insertion sort\", \"Quicksort\"}\n    sortFunc = []func([]int){bubblesort, insertionsort, quicksort}\n    dataName = []string{\"Ones\", \"Ascending\", \"Shuffled\"}\n    dataFunc = []func(int) []int{ones, ascending, shuffled}\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    var err error\n    p, err = plot.New()\n    if err != nil {\n        log.Fatal(err)\n    }\n    p.X.Label.Text = \"Data size\"\n    p.Y.Label.Text = \"microseconds\"\n    p.Y.Scale = plot.LogScale{}\n    p.Y.Tick.Marker = plot.LogTicks{}\n    p.Y.Min = .5 \n\n    for dx, name := range dataName {\n        s, err := plotter.NewScatter(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        s.Shape = plotutil.DefaultGlyphShapes[dx]\n        p.Legend.Add(name, s)\n    }\n    for sx, name := range sortName {\n        l, err := plotter.NewLine(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        l.Color = plotutil.DarkColors[sx]\n        p.Legend.Add(name, l)\n    }\n    for sx := range sortFunc {\n        bench(sx, 0, 1) \n        bench(sx, 1, 5) \n        bench(sx, 2, 5) \n    }\n\n    if err := p.Save(5*vg.Inch, 5*vg.Inch, \"comp.png\"); err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc bench(sx, dx, rep int) {\n    log.Println(\"bench\", sortName[sx], dataName[dx], \"x\", rep)\n    pts := make(plotter.XYs, nPts)\n    sf := sortFunc[sx]\n    for i := range pts {\n        x := (i + 1) * inc\n        \n        \n        \n        s0 := dataFunc[dx](x) \n        s := make([]int, x)   \n        var tSort int64\n        for j := 0; j < rep; j++ {\n            tSort += testing.Benchmark(func(b *testing.B) {\n                for i := 0; i < b.N; i++ {\n                    copy(s, s0)\n                    sf(s)\n                }\n            }).NsPerOp()\n        }\n        tSort /= int64(rep)\n        log.Println(x, \"items\", tSort, \"ns\") \n        pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001}\n    }\n    pl, ps, err := plotter.NewLinePoints(pts) \n    if err != nil {\n        log.Fatal(err)\n    }\n    pl.Color = plotutil.DarkColors[sx]\n    ps.Color = plotutil.DarkColors[sx]\n    ps.Shape = plotutil.DefaultGlyphShapes[dx]\n    p.Add(pl, ps)\n}\n"}
{"id": 58225, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n"}
{"id": 58226, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n"}
{"id": 58227, "name": "Parse command-line arguments", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n"}
{"id": 58228, "name": "Parse command-line arguments", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n"}
{"id": 58229, "name": "Parse command-line arguments", "Python": "from optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n                  help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n                  action=\"store_false\", dest=\"verbose\", default=True,\n                  help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\nexample:\n\n<yourscript> --file=outfile -q\n", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n"}
{"id": 58230, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n"}
{"id": 58231, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n"}
{"id": 58232, "name": "Simulate input_Keyboard", "Python": "import autopy\nautopy.key.type_string(\"Hello, world!\") \nautopy.key.type_string(\"Hello, world!\", wpm=60) \nautopy.key.tap(autopy.key.Code.RETURN)\nautopy.key.tap(autopy.key.Code.F1)\nautopy.key.tap(autopy.key.Code.LEFT_ARROW)\n", "Go": "package main\n\nimport (\n    \"github.com/micmonay/keybd_event\"\n    \"log\"\n    \"runtime\"\n    \"time\"\n)\n\nfunc main() {\n    kb, err := keybd_event.NewKeyBonding()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    if runtime.GOOS == \"linux\" {\n        time.Sleep(2 * time.Second)\n    }\n\n    \n    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)\n\n    \n    err = kb.Launching()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58233, "name": "Peaceful chess queen armies", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n"}
{"id": 58234, "name": "Loops_Infinite", "Python": "while 1:\n   print \"SPAM\"\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n"}
{"id": 58235, "name": "Metaprogramming", "Python": "from macropy.core.macros import *\nfrom macropy.core.quotes import macros, q, ast, u\n\nmacros = Macros()\n\n@macros.expr\ndef expand(tree, **kw):\n    addition = 10\n    return q[lambda x: x * ast[tree] + u[addition]]\n", "Go": "package main\n\nimport \"fmt\"\n\ntype person struct{\n    name string\n    age int\n}\n\nfunc copy(p person) person {\n    return person{p.name, p.age}\n}\n\nfunc main() {\n    p := person{\"Dave\", 40}\n    fmt.Println(p)\n    q := copy(p)\n    fmt.Println(q)\n     \n}\n"}
{"id": 58236, "name": "Numbers with same digit set in base 10 and base 16", "Python": "col = 0\nfor i in range(100000):\n    if set(str(i)) == set(hex(i)[2:]):\n        col += 1\n        print(\"{:7}\".format(i), end='\\n'[:col % 10 == 0])\nprint()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n"}
{"id": 58237, "name": "Largest prime factor", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    n = 600851475143\n    j = 3\n    while not isPrime(n):\n        if n % j == 0:\n            n /= j\n        j += 2\n    print(n);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestPrimeFactor(n uint64) uint64 {\n    if n < 2 {\n        return 1\n    }\n    inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}\n    max := uint64(1)\n    for n%2 == 0 {\n        max = 2\n        n /= 2\n    }\n    for n%3 == 0 {\n        max = 3\n        n /= 3\n    }\n    for n%5 == 0 {\n        max = 5\n        n /= 5\n    }\n    k := uint64(7)\n    i := 0\n    for k*k <= n {\n        if n%k == 0 {\n            max = k\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        return n\n    }\n    return max\n}\n\nfunc main() {\n    n := uint64(600851475143)\n    fmt.Println(\"The largest prime factor of\", n, \"is\", largestPrimeFactor(n), \"\\b.\")\n}\n"}
{"id": 58238, "name": "Largest proper divisor of n", "Python": "def lpd(n):\n    for i in range(n-1,0,-1):\n        if n%i==0: return i\n    return 1\n\nfor i in range(1,101):\n    print(\"{:3}\".format(lpd(i)), end=i%10==0 and '\\n' or '')\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            return n / i\n        }\n    }\n    return 1\n}\n\nfunc main() {\n    fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n    fmt.Print(\" 1  \")\n    for n := 2; n <= 100; n++ {\n        if n%2 == 0 {\n            fmt.Printf(\"%2d  \", n/2)\n        } else {\n            fmt.Printf(\"%2d  \", largestProperDivisor(n))\n        }\n        if n%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 58239, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 58240, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n"}
{"id": 58241, "name": "Active Directory_Search for a user", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n"}
{"id": 58242, "name": "Singular value decomposition", "Python": "from numpy import *\nA = matrix([[3, 0], [4, 5]])\nU, Sigma, VT = linalg.svd(A)\nprint(U)\nprint(Sigma)\nprint(VT)\n", "Go": "<package main\n\nimport (\n    \"fmt\"\n    \"gonum.org/v1/gonum/mat\"\n    \"log\"\n)\n\nfunc matPrint(m mat.Matrix) {\n    fa := mat.Formatted(m, mat.Prefix(\"\"), mat.Squeeze())\n    fmt.Printf(\"%13.10f\\n\", fa)\n}\n\nfunc main() {\n    var svd mat.SVD\n    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})\n    ok := svd.Factorize(a, mat.SVDFull)\n    if !ok {\n        log.Fatal(\"Something went wrong!\")\n    }\n    u := mat.NewDense(2, 2, nil)\n    svd.UTo(u)\n    fmt.Println(\"U:\")\n    matPrint(u)\n    values := svd.Values(nil)\n    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})\n    fmt.Println(\"\\nΣ:\")\n    matPrint(sigma)\n    vt := mat.NewDense(2, 2, nil)\n    svd.VTo(vt)\n    fmt.Println(\"\\nVT:\")\n    matPrint(vt)\n}\n"}
{"id": 58243, "name": "Sum of first n cubes", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n"}
{"id": 58244, "name": "Test integerness", "Python": ">>> def isint(f): \n    return complex(f).imag == 0 and complex(f).real.is_integer()\n\n>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]\n[True, True, True, False, False, False]\n\n>>> \n...\n>>> isint(25.000000)\nTrue\n>>> isint(24.999999)\nFalse\n>>> isint(25.000100)\nFalse\n>>> isint(-2.1e120)\nTrue\n>>> isint(-5e-2)\nFalse\n>>> isint(float('nan'))\nFalse\n>>> isint(float('inf'))\nFalse\n>>> isint(5.0+0.0j)\nTrue\n>>> isint(5-5j)\nFalse\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n"}
{"id": 58245, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58246, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n"}
{"id": 58247, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n"}
{"id": 58248, "name": "Death Star", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": 58249, "name": "Death Star", "Python": "import sys, math, collections\n\nSphere = collections.namedtuple(\"Sphere\", \"cx cy cz r\")\nV3 = collections.namedtuple(\"V3\", \"x y z\")\n\ndef normalize((x, y, z)):\n    len = math.sqrt(x**2 + y**2 + z**2)\n    return V3(x / len, y / len, z / len)\n\ndef dot(v1, v2):\n    d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z\n    return -d if d < 0 else 0.0\n\ndef hit_sphere(sph, x0, y0):\n    x = x0 - sph.cx\n    y = y0 - sph.cy\n    zsq = sph.r ** 2 - (x ** 2 + y ** 2)\n    if zsq < 0:\n        return (False, 0, 0)\n    szsq = math.sqrt(zsq)\n    return (True, sph.cz - szsq, sph.cz + szsq)\n\ndef draw_sphere(k, ambient, light):\n    shades = \".:!*oe&\n    pos = Sphere(20.0, 20.0, 0.0, 20.0)\n    neg = Sphere(1.0, 1.0, -6.0, 20.0)\n\n    for i in xrange(int(math.floor(pos.cy - pos.r)),\n                    int(math.ceil(pos.cy + pos.r) + 1)):\n        y = i + 0.5\n        for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),\n                        int(math.ceil(pos.cx + 2 * pos.r) + 1)):\n            x = (j - pos.cx) / 2.0 + 0.5 + pos.cx\n\n            (h, zb1, zb2) = hit_sphere(pos, x, y)\n            if not h:\n                hit_result = 0\n            else:\n                (h, zs1, zs2) = hit_sphere(neg, x, y)\n                if not h:\n                    hit_result = 1\n                elif zs1 > zb1:\n                    hit_result = 1\n                elif zs2 > zb2:\n                    hit_result = 0\n                elif zs2 > zb1:\n                    hit_result = 2\n                else:\n                    hit_result = 1\n\n            if hit_result == 0:\n                sys.stdout.write(' ')\n                continue\n            elif hit_result == 1:\n                vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)\n            elif hit_result == 2:\n                vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)\n            vec = normalize(vec)\n\n            b = dot(light, vec) ** k + ambient\n            intensity = int((1 - b) * len(shades))\n            intensity = min(len(shades), max(0, intensity))\n            sys.stdout.write(shades[intensity])\n        print\n\nlight = normalize(V3(-50, 30, 50))\ndraw_sphere(2, 0.5, light)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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": 58250, "name": "Lucky and even lucky numbers", "Python": "from __future__ import print_function\n\ndef lgen(even=False, nmax=1000000):\n    start = 2 if even else 1\n    n, lst = 1, list(range(start, nmax + 1, 2))\n    lenlst = len(lst)\n    yield lst[0]\n    while n < lenlst and lst[n] < lenlst:\n        yield lst[n]\n        n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]\n        lenlst = len(lst)\n    \n    for i in lst[n:]:\n        yield i\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n    for i := 0; i < luckySize; i++ {\n        luckyOdd[i] = i*2 + 1\n        luckyEven[i] = i*2 + 2\n    }\n}\n\nfunc filterLuckyOdd() {\n    for n := 2; n < len(luckyOdd); n++ {\n        m := luckyOdd[n-1]\n        end := (len(luckyOdd)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyOdd[j:], luckyOdd[j+1:])\n            luckyOdd = luckyOdd[:len(luckyOdd)-1]\n        }\n    }\n}\n\nfunc filterLuckyEven() {\n    for n := 2; n < len(luckyEven); n++ {\n        m := luckyEven[n-1]\n        end := (len(luckyEven)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyEven[j:], luckyEven[j+1:])\n            luckyEven = luckyEven[:len(luckyEven)-1]\n        }\n    }\n}\n\nfunc printSingle(j int, odd bool) error {\n    if odd {\n        if j >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n    } else {\n        if j >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n    }\n    return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n    if odd {\n        if k >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyOdd[j-1 : k])\n    } else {\n        if k >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyEven[j-1 : k])\n    }\n    return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n    var r []int\n    if odd {\n        max := luckyOdd[len(luckyOdd)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyOdd {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    } else {\n        max := luckyEven[len(luckyEven)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyEven {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    }\n    return nil\n}\n\nfunc main() {\n    nargs := len(os.Args)\n    if nargs < 2 || nargs > 4 {\n        log.Fatal(\"there must be between 1 and 3 command line arguments\")\n    }\n    filterLuckyOdd()\n    filterLuckyEven()\n    j, err := strconv.Atoi(os.Args[1])\n    if err != nil || j < 1 {\n        log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n    }\n    if nargs == 2 {\n        if err := printSingle(j, true); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    if nargs == 3 {\n        k, err := strconv.Atoi(os.Args[2])\n        if err != nil {\n            log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n        }\n        if k >= 0 {\n            if j > k {\n                log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n            }\n            if err := printRange(j, k, true); err != nil {\n                log.Fatal(err)\n            }\n        } else {\n            l := -k\n            if j > l {\n                log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n            }\n            if err := printBetween(j, l, true); err != nil {\n                log.Fatal(err)\n            }\n        }\n        return\n    }\n\n    var odd bool\n    switch lucky := strings.ToLower(os.Args[3]); lucky {\n    case \"lucky\":\n        odd = true\n    case \"evenlucky\":\n        odd = false\n    default:\n        log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n    }\n    if os.Args[2] == \",\" {\n        if err := printSingle(j, odd); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    k, err := strconv.Atoi(os.Args[2])\n    if err != nil {\n        log.Fatal(\"second argument must be an integer or a comma\")\n    }\n    if k >= 0 {\n        if j > k {\n            log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n        }\n        if err := printRange(j, k, odd); err != nil {\n            log.Fatal(err)\n        }\n    } else {\n        l := -k\n        if j > l {\n            log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n        }\n        if err := printBetween(j, l, odd); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n"}
{"id": 58251, "name": "Simple database", "Python": "\n\n\n\nimport argparse\nfrom argparse import Namespace\nimport datetime\nimport shlex\n\n\ndef parse_args():\n    'Set up, parse, and return arguments'\n    \n    parser = argparse.ArgumentParser(epilog=globals()['__doc__'])\n\n    parser.add_argument('command', choices='add pl plc pa'.split(),\n                        help=)\n    parser.add_argument('-d', '--description',\n                        help='A description of the item. (e.g., title, name)')\n    parser.add_argument('-t', '--tag',\n                        help=(\n                              ))\n    parser.add_argument('-f', '--field', nargs=2, action='append', \n                        help='Other optional fields with value (can be repeated)')\n\n    return parser\n\ndef do_add(args, dbname):\n    'Add a new entry'\n    if args.description is None:\n        args.description = ''\n    if args.tag is None:\n        args.tag = ''\n    del args.command\n    print('Writing record to %s' % dbname)\n    with open(dbname, 'a') as db:\n        db.write('%r\\n' % args)\n    \ndef do_pl(args, dbname):\n    'Print the latest entry'\n    print('Getting last record from %s' % dbname)\n    with open(dbname, 'r') as db:\n        for line in db: pass\n    record = eval(line)\n    del record._date\n    print(str(record))\n    \ndef do_plc(args, dbname):\n    'Print the latest entry for each category/tag'\n    print('Getting latest record for each tag from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    tags = set(record.tag for record in records)\n    records.reverse()\n    for record in records:\n        if record.tag in tags:\n            del record._date\n            print(str(record))\n            tags.discard(record.tag)\n            if not tags: break\n\ndef do_pa(args, dbname):\n    'Print all entries sorted by a date'\n    print('Getting all records by date from %s' % dbname)\n    with open(dbname, 'r') as db:\n        records = [eval(line) for line in db]\n    for record in records:\n        del record._date\n        print(str(record))\n\ndef test():\n    import time\n    parser = parse_args()\n    for cmdline in [\n                    ,\n                    ,\n                    ,\n                    ,\n                    ,\n                    ]:\n        args = parser.parse_args(shlex.split(cmdline))\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n        time.sleep(0.5)\n\n\n    \ndo_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)\ndbname = '_simple_db_db.py'\n\n\nif __name__ == '__main__':\n    if 0:\n        test()\n    else:\n        parser = parse_args()\n        args = parser.parse_args()\n        now = datetime.datetime.utcnow()\n        args._date = now.isoformat()\n        do_command[args.command](args, dbname)\n", "Go": "package main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n    \"unicode\"\n)\n\n\n\ntype Item struct {\n    Stamp time.Time\n    Name  string\n    Tags  []string `json:\",omitempty\"`\n    Notes string   `json:\",omitempty\"`\n}\n\n\nfunc (i *Item) String() string {\n    s := i.Stamp.Format(time.ANSIC) + \"\\n  Name:  \" + i.Name\n    if len(i.Tags) > 0 {\n        s = fmt.Sprintf(\"%s\\n  Tags:  %v\", s, i.Tags)\n    }\n    if i.Notes > \"\" {\n        s += \"\\n  Notes: \" + i.Notes\n    }\n    return s\n}\n\n\ntype db []*Item\n\n\nfunc (d db) Len() int           { return len(d) }\nfunc (d db) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }\nfunc (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) }\n\n\nconst fn = \"sdb.json\"\n\nfunc main() {\n    if len(os.Args) == 1 {\n        latest()\n        return\n    }\n    switch os.Args[1] {\n    case \"add\":\n        add()\n    case \"latest\":\n        latest()\n    case \"tags\":\n        tags()\n    case \"all\":\n        all()\n    case \"help\":\n        help()\n    default:\n        usage(\"unrecognized command\")\n    }\n}\n\nfunc usage(err string) {\n    if err > \"\" {\n        fmt.Println(err)\n    }\n    fmt.Println(`usage:  sdb [command] [data]\n    where command is one of add, latest, tags, all, or help.`)\n}\n\nfunc help() {\n    usage(\"\")\n    fmt.Println(`\nCommands must be in lower case.\nIf no command is specified, the default command is latest.\n\nLatest prints the latest item.\nAll prints all items in chronological order.\nTags prints the lastest item for each tag.\nHelp prints this message.\n\nAdd adds data as a new record.  The format is,\n\n  name [tags] [notes]\n\nName is the name of the item and is required for the add command.\n\nTags are optional.  A tag is a single word.\nA single tag can be specified without enclosing brackets.\nMultiple tags can be specified by enclosing them in square brackets.\n\nText remaining after tags is taken as notes.  Notes do not have to be\nenclosed in quotes or brackets.  The brackets above are only showing\nthat notes are optional.\n\nQuotes may be useful however--as recognized by your operating system shell\nor command line--to allow entry of arbitrary text.  In particular, quotes\nor escape characters may be needed to prevent the shell from trying to\ninterpret brackets or other special characters.\n\nExamples:\nsdb add Bookends                        \nsdb add Bookends rock my favorite       \nsdb add Bookends [rock folk]            \nsdb add Bookends [] \"Simon & Garfunkel\" \nsdb add \"Simon&Garfunkel [artist]\"      \n    \nAs shown in the last example, if you use features of your shell to pass\nall data as a single string, the item name and tags will still be identified\nby separating whitespace.\n    \nThe database is stored in JSON format in the file \"sdb.json\"\n`)  \n}\n\n\nfunc load() (db, bool) {\n    d, f, ok := open()\n    if ok {\n        f.Close()\n        if len(d) == 0 {\n            fmt.Println(\"no items\")\n            ok = false\n        }\n    }\n    return d, ok\n}\n\n\nfunc open() (d db, f *os.File, ok bool) {\n    var err error\n    f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)\n    if err != nil {\n        fmt.Println(\"cant open??\")\n        fmt.Println(err)\n        return\n    }\n    jd := json.NewDecoder(f)\n    err = jd.Decode(&d)\n    \n    if err != nil && err != io.EOF {\n        fmt.Println(err)\n        f.Close()\n        return\n    }\n    ok = true\n    return\n}\n\n\nfunc latest() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    fmt.Println(d[len(d)-1])\n}\n\n\nfunc all() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    for _, i := range d {\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(i)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n\n\nfunc tags() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    \n    \n    \n    latest := make(map[string]*Item)\n    for _, item := range d {\n        for _, tag := range item.Tags {\n            li, ok := latest[tag]\n            if !ok || item.Stamp.After(li.Stamp) {\n                latest[tag] = item\n            }\n        }\n    }\n    \n    \n    type itemTags struct {\n        item *Item\n        tags []string\n    }\n    inv := make(map[*Item][]string)\n    for tag, item := range latest {\n        inv[item] = append(inv[item], tag)\n    }\n    \n    li := make(db, len(inv))\n    i := 0\n    for item := range inv {\n        li[i] = item\n        i++\n    }\n    sort.Sort(li)\n    \n    for _, item := range li {\n        tags := inv[item]\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(\"Latest item with tags\", tags)\n        fmt.Println(item)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n    \n\nfunc add() { \n    if len(os.Args) < 3 {\n        usage(\"add command requires data\")\n        return\n    } else if len(os.Args) == 3 {\n        add1()\n    } else {\n        add4()\n    }\n}   \n\n\nfunc add1() {\n    data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace)\n    if data == \"\" {\n        \n        usage(\"invalid name\")\n        return \n    }\n    sep := strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(data, nil, \"\")\n        return\n    }\n    name := data[:sep]\n    data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace)\n    if data == \"\" {\n        \n        addItem(name, nil, \"\")\n        return\n    }\n    if data[0] == '[' {\n        sep = strings.Index(data, \"]\")\n        if sep < 0 {\n            \n            addItem(name, strings.Fields(data[1:]), \"\")\n        } else {\n            \n            addItem(name, strings.Fields(data[1:sep]),\n                strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n        }\n        return\n    }\n    sep = strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(name, []string{data}, \"\")\n    } else {\n        \n        addItem(name, []string{data[:sep]},\n            strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n    }\n}\n\n\nfunc add4() {\n    name := os.Args[2]\n    tag1 := os.Args[3]\n    if tag1[0] != '[' {\n        \n        addItem(name, []string{tag1}, strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    if tag1[len(tag1)-1] == ']' {\n        \n        addItem(name, strings.Fields(tag1[1:len(tag1)-1]),\n            strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    \n    var tags []string\n    if tag1 > \"[\" {\n        tags = []string{tag1[1:]}\n    }\n    for x, tag := range os.Args[4:] {\n        if tag[len(tag)-1] != ']' {\n            tags = append(tags, tag)\n        } else {\n            \n            if tag > \"]\" {\n                tags = append(tags, tag[:len(tag)-1])\n            }\n            addItem(name, tags, strings.Join(os.Args[5+x:], \" \"))\n            return\n        }\n    }\n    \n    addItem(name, tags, \"\")\n}\n\n\nfunc addItem(name string, tags []string, notes string) {\n    db, f, ok := open()\n    if !ok {\n        return\n    }\n    defer f.Close()\n    \n    db = append(db, &Item{time.Now(), name, tags, notes})\n    sort.Sort(db)\n    js, err := json.MarshalIndent(db, \"\", \"  \")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if _, err = f.Seek(0, 0); err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Truncate(0)\n    if _, err = f.Write(js); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58252, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "Go": "package main\n\nimport (\n        \"flag\"\n        \"fmt\"\n        \"math\"\n        \"runtime\"\n        \"sort\"\n)\n\n\n\n\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n        \n        return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n        return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n        return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n        nw := c.ContainsPt(r.NW())\n        ne := c.ContainsPt(r.NE())\n        sw := c.ContainsPt(r.SW())\n        se := c.ContainsPt(r.SE())\n        return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64)  { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64)  { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64          { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n        return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n        return r.X1 <= x && x < r.X2 &&\n                r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { \n        return r.ContainsPt(c.North()) ||\n                r.ContainsPt(c.South()) ||\n                r.ContainsPt(c.West()) ||\n                r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n        return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n        Δx, Δy := x2-x1, y2-y1\n        return (Δx * Δx) + (Δy * Δy)\n}\n\ntype CircleSet []Circle\n\n\nfunc (s CircleSet) Len() int           { return len(s) }\nfunc (s CircleSet) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n        s := *sp\n        sort.Sort(s)\n        for i := 0; i < len(s); i++ {\n                for j := i + 1; j < len(s); {\n                        if s[i].ContainsC(s[j]) {\n                                s[j], s[len(s)-1] = s[len(s)-1], s[j]\n                                s = s[:len(s)-1]\n                        } else {\n                                j++\n                        }\n                }\n        }\n        *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n        x1 := s[0].X - s[0].R\n        x2 := s[0].X + s[0].R\n        y1 := s[0].Y - s[0].R\n        y2 := s[0].Y + s[0].R\n        for _, c := range s[1:] {\n                x1 = math.Min(x1, c.X-c.R)\n                x2 = math.Max(x2, c.X+c.R)\n                y1 = math.Min(y1, c.Y-c.R)\n                y2 = math.Max(y2, c.Y+c.R)\n        }\n        return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(ε float64) (min, max float64) {\n        sort.Sort(s)\n        stop := make(chan bool)\n        inside := make(chan Rect)\n        outside := make(chan Rect)\n        unknown := make(chan Rect, 5e7) \n\n        for i := 0; i < nWorkers; i++ {\n                go s.worker(stop, unknown, inside, outside)\n        }\n        r := s.Bounds()\n        max = r.Area()\n        unknown <- r\n        for max-min > ε {\n                select {\n                case r = <-inside:\n                        min += r.Area()\n                case r = <-outside:\n                        max -= r.Area()\n                }\n        }\n        close(stop)\n        return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n        for {\n                select {\n                case <-stop:\n                        return\n                case r := <-unk:\n                        inside, outside := s.CategorizeR(r)\n                        switch {\n                        case inside:\n                                in <- r\n                        case outside:\n                                out <- r\n                        default:\n                                \n                                midX, midY := r.Centre()\n                                unk <- Rect{r.X1, r.Y1, midX, midY}\n                                unk <- Rect{midX, r.Y1, r.X2, midY}\n                                unk <- Rect{r.X1, midY, midX, r.Y2}\n                                unk <- Rect{midX, midY, r.X2, r.Y2}\n                        }\n                }\n        }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n        anyCorner := false\n        for _, c := range s {\n                full, corner := c.ContainsR(r)\n                if full {\n                        return true, false \n                }\n                anyCorner = anyCorner || corner\n        }\n        if anyCorner {\n                return false, false \n        }\n        for _, c := range s {\n                if r.ContainsPC(c) {\n                        return false, false \n                }\n        }\n        return false, true \n}\n\nfunc main() {\n        flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n        maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n        flag.Parse()\n\n        if *maxproc > 0 {\n                runtime.GOMAXPROCS(*maxproc)\n        } else {\n                *maxproc = runtime.GOMAXPROCS(0)\n        }\n\n        circles := CircleSet{\n                NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n                NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n                NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n                NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n                NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n                NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n                NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n                NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n                NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n                NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n                NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n                NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n                NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n                NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n                NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n                NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n                NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n                NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n                NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n                NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n                NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n                NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n                NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n                NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n                NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n        }\n        fmt.Println(\"Starting with\", len(circles), \"circles.\")\n        circles.RemoveContainedC()\n        fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n        fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n        const ε = 0.0001\n        min, max := circles.UnionArea(ε)\n        avg := (min + max) / 2.0\n        rng := max - min\n        fmt.Printf(\"Area = %v±%v\\n\", avg, rng)\n        fmt.Printf(\"Area ≈ %.*f\\n\", 5, avg)\n}\n"}
{"id": 58253, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "Go": "package main\n\nimport (\n        \"flag\"\n        \"fmt\"\n        \"math\"\n        \"runtime\"\n        \"sort\"\n)\n\n\n\n\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n        \n        return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n        return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n        return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n        nw := c.ContainsPt(r.NW())\n        ne := c.ContainsPt(r.NE())\n        sw := c.ContainsPt(r.SW())\n        se := c.ContainsPt(r.SE())\n        return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64)  { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64)  { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64          { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n        return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n        return r.X1 <= x && x < r.X2 &&\n                r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { \n        return r.ContainsPt(c.North()) ||\n                r.ContainsPt(c.South()) ||\n                r.ContainsPt(c.West()) ||\n                r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n        return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n        Δx, Δy := x2-x1, y2-y1\n        return (Δx * Δx) + (Δy * Δy)\n}\n\ntype CircleSet []Circle\n\n\nfunc (s CircleSet) Len() int           { return len(s) }\nfunc (s CircleSet) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n        s := *sp\n        sort.Sort(s)\n        for i := 0; i < len(s); i++ {\n                for j := i + 1; j < len(s); {\n                        if s[i].ContainsC(s[j]) {\n                                s[j], s[len(s)-1] = s[len(s)-1], s[j]\n                                s = s[:len(s)-1]\n                        } else {\n                                j++\n                        }\n                }\n        }\n        *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n        x1 := s[0].X - s[0].R\n        x2 := s[0].X + s[0].R\n        y1 := s[0].Y - s[0].R\n        y2 := s[0].Y + s[0].R\n        for _, c := range s[1:] {\n                x1 = math.Min(x1, c.X-c.R)\n                x2 = math.Max(x2, c.X+c.R)\n                y1 = math.Min(y1, c.Y-c.R)\n                y2 = math.Max(y2, c.Y+c.R)\n        }\n        return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(ε float64) (min, max float64) {\n        sort.Sort(s)\n        stop := make(chan bool)\n        inside := make(chan Rect)\n        outside := make(chan Rect)\n        unknown := make(chan Rect, 5e7) \n\n        for i := 0; i < nWorkers; i++ {\n                go s.worker(stop, unknown, inside, outside)\n        }\n        r := s.Bounds()\n        max = r.Area()\n        unknown <- r\n        for max-min > ε {\n                select {\n                case r = <-inside:\n                        min += r.Area()\n                case r = <-outside:\n                        max -= r.Area()\n                }\n        }\n        close(stop)\n        return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n        for {\n                select {\n                case <-stop:\n                        return\n                case r := <-unk:\n                        inside, outside := s.CategorizeR(r)\n                        switch {\n                        case inside:\n                                in <- r\n                        case outside:\n                                out <- r\n                        default:\n                                \n                                midX, midY := r.Centre()\n                                unk <- Rect{r.X1, r.Y1, midX, midY}\n                                unk <- Rect{midX, r.Y1, r.X2, midY}\n                                unk <- Rect{r.X1, midY, midX, r.Y2}\n                                unk <- Rect{midX, midY, r.X2, r.Y2}\n                        }\n                }\n        }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n        anyCorner := false\n        for _, c := range s {\n                full, corner := c.ContainsR(r)\n                if full {\n                        return true, false \n                }\n                anyCorner = anyCorner || corner\n        }\n        if anyCorner {\n                return false, false \n        }\n        for _, c := range s {\n                if r.ContainsPC(c) {\n                        return false, false \n                }\n        }\n        return false, true \n}\n\nfunc main() {\n        flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n        maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n        flag.Parse()\n\n        if *maxproc > 0 {\n                runtime.GOMAXPROCS(*maxproc)\n        } else {\n                *maxproc = runtime.GOMAXPROCS(0)\n        }\n\n        circles := CircleSet{\n                NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n                NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n                NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n                NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n                NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n                NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n                NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n                NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n                NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n                NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n                NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n                NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n                NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n                NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n                NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n                NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n                NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n                NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n                NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n                NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n                NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n                NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n                NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n                NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n                NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n        }\n        fmt.Println(\"Starting with\", len(circles), \"circles.\")\n        circles.RemoveContainedC()\n        fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n        fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n        const ε = 0.0001\n        min, max := circles.UnionArea(ε)\n        avg := (min + max) / 2.0\n        rng := max - min\n        fmt.Printf(\"Area = %v±%v\\n\", avg, rng)\n        fmt.Printf(\"Area ≈ %.*f\\n\", 5, avg)\n}\n"}
{"id": 58254, "name": "Total circles area", "Python": "from collections import namedtuple\n\nCircle = namedtuple(\"Circle\", \"x y r\")\n\ncircles = [\n    Circle( 1.6417233788,  1.6121789534, 0.0848270516),\n    Circle(-1.4944608174,  1.2077959613, 1.1039549836),\n    Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n    Circle( 0.3844862411,  0.2923344616, 0.2375743054),\n    Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n    Circle( 1.7813504266,  1.6178237031, 0.8162655711),\n    Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n    Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n    Circle(-0.4319462812,  1.4104420482, 0.7886291537),\n    Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n    Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n    Circle( 1.7952608455,  0.6281269104, 0.2727652452),\n    Circle( 1.4168575317,  1.0683357171, 1.1016025378),\n    Circle( 1.4637371396,  0.9463877418, 1.1846214562),\n    Circle(-0.5263668798,  1.7315156631, 1.4428514068),\n    Circle(-1.2197352481,  0.9144146579, 1.0727263474),\n    Circle(-0.1389358881,  0.1092805780, 0.7350208828),\n    Circle( 1.5293954595,  0.0030278255, 1.2472867347),\n    Circle(-0.5258728625,  1.3782633069, 1.3495508831),\n    Circle(-0.1403562064,  0.2437382535, 1.3804956588),\n    Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n    Circle(-0.6311979224,  0.7184578971, 0.2491045282),\n    Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n    Circle(-0.6855727502,  1.6465021616, 1.0593087096),\n    Circle( 0.0152957411,  0.0638919221, 0.9771215985)]\n\ndef main():\n    \n    x_min = min(c.x - c.r for c in circles)\n    x_max = max(c.x + c.r for c in circles)\n    y_min = min(c.y - c.r for c in circles)\n    y_max = max(c.y + c.r for c in circles)\n\n    box_side = 500\n\n    dx = (x_max - x_min) / box_side\n    dy = (y_max - y_min) / box_side\n\n    count = 0\n\n    for r in xrange(box_side):\n        y = y_min + r * dy\n        for c in xrange(box_side):\n            x = x_min + c * dx\n            if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)\n                   for circle in circles):\n                count += 1\n\n    print \"Approximated area:\", count * dx * dy\n\nmain()\n", "Go": "package main\n\nimport (\n        \"flag\"\n        \"fmt\"\n        \"math\"\n        \"runtime\"\n        \"sort\"\n)\n\n\n\n\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n        \n        return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n        return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n        return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n        nw := c.ContainsPt(r.NW())\n        ne := c.ContainsPt(r.NE())\n        sw := c.ContainsPt(r.SW())\n        se := c.ContainsPt(r.SE())\n        return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64)  { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64)  { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64          { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n        return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n        return r.X1 <= x && x < r.X2 &&\n                r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { \n        return r.ContainsPt(c.North()) ||\n                r.ContainsPt(c.South()) ||\n                r.ContainsPt(c.West()) ||\n                r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n        return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n        Δx, Δy := x2-x1, y2-y1\n        return (Δx * Δx) + (Δy * Δy)\n}\n\ntype CircleSet []Circle\n\n\nfunc (s CircleSet) Len() int           { return len(s) }\nfunc (s CircleSet) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n        s := *sp\n        sort.Sort(s)\n        for i := 0; i < len(s); i++ {\n                for j := i + 1; j < len(s); {\n                        if s[i].ContainsC(s[j]) {\n                                s[j], s[len(s)-1] = s[len(s)-1], s[j]\n                                s = s[:len(s)-1]\n                        } else {\n                                j++\n                        }\n                }\n        }\n        *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n        x1 := s[0].X - s[0].R\n        x2 := s[0].X + s[0].R\n        y1 := s[0].Y - s[0].R\n        y2 := s[0].Y + s[0].R\n        for _, c := range s[1:] {\n                x1 = math.Min(x1, c.X-c.R)\n                x2 = math.Max(x2, c.X+c.R)\n                y1 = math.Min(y1, c.Y-c.R)\n                y2 = math.Max(y2, c.Y+c.R)\n        }\n        return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(ε float64) (min, max float64) {\n        sort.Sort(s)\n        stop := make(chan bool)\n        inside := make(chan Rect)\n        outside := make(chan Rect)\n        unknown := make(chan Rect, 5e7) \n\n        for i := 0; i < nWorkers; i++ {\n                go s.worker(stop, unknown, inside, outside)\n        }\n        r := s.Bounds()\n        max = r.Area()\n        unknown <- r\n        for max-min > ε {\n                select {\n                case r = <-inside:\n                        min += r.Area()\n                case r = <-outside:\n                        max -= r.Area()\n                }\n        }\n        close(stop)\n        return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n        for {\n                select {\n                case <-stop:\n                        return\n                case r := <-unk:\n                        inside, outside := s.CategorizeR(r)\n                        switch {\n                        case inside:\n                                in <- r\n                        case outside:\n                                out <- r\n                        default:\n                                \n                                midX, midY := r.Centre()\n                                unk <- Rect{r.X1, r.Y1, midX, midY}\n                                unk <- Rect{midX, r.Y1, r.X2, midY}\n                                unk <- Rect{r.X1, midY, midX, r.Y2}\n                                unk <- Rect{midX, midY, r.X2, r.Y2}\n                        }\n                }\n        }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n        anyCorner := false\n        for _, c := range s {\n                full, corner := c.ContainsR(r)\n                if full {\n                        return true, false \n                }\n                anyCorner = anyCorner || corner\n        }\n        if anyCorner {\n                return false, false \n        }\n        for _, c := range s {\n                if r.ContainsPC(c) {\n                        return false, false \n                }\n        }\n        return false, true \n}\n\nfunc main() {\n        flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n        maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n        flag.Parse()\n\n        if *maxproc > 0 {\n                runtime.GOMAXPROCS(*maxproc)\n        } else {\n                *maxproc = runtime.GOMAXPROCS(0)\n        }\n\n        circles := CircleSet{\n                NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n                NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n                NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n                NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n                NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n                NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n                NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n                NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n                NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n                NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n                NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n                NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n                NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n                NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n                NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n                NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n                NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n                NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n                NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n                NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n                NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n                NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n                NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n                NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n                NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n        }\n        fmt.Println(\"Starting with\", len(circles), \"circles.\")\n        circles.RemoveContainedC()\n        fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n        fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n        const ε = 0.0001\n        min, max := circles.UnionArea(ε)\n        avg := (min + max) / 2.0\n        rng := max - min\n        fmt.Printf(\"Area = %v±%v\\n\", avg, rng)\n        fmt.Printf(\"Area ≈ %.*f\\n\", 5, avg)\n}\n"}
{"id": 58255, "name": "Hough transform", "Python": "from math import hypot, pi, cos, sin\nfrom PIL import Image\n\n\ndef hough(im, ntx=460, mry=360):\n    \"Calculate Hough transform.\"\n    pim = im.load()\n    nimx, mimy = im.size\n    mry = int(mry/2)*2          \n    him = Image.new(\"L\", (ntx, mry), 255)\n    phim = him.load()\n\n    rmax = hypot(nimx, mimy)\n    dr = rmax / (mry/2)\n    dth = pi / ntx\n\n    for jx in xrange(nimx):\n        for iy in xrange(mimy):\n            col = pim[jx, iy]\n            if col == 255: continue\n            for jtx in xrange(ntx):\n                th = dth * jtx\n                r = jx*cos(th) + iy*sin(th)\n                iry = mry/2 + int(r/dr+0.5)\n                phim[jtx, iry] -= 1\n    return him\n\n\ndef test():\n    \"Test Hough transform with pentagon.\"\n    im = Image.open(\"pentagon.png\").convert(\"L\")\n    him = hough(im)\n    him.save(\"ho5.bmp\")\n\n\nif __name__ == \"__main__\": test()\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\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58256, "name": "Verify distribution uniformity_Chi-squared test", "Python": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n    a1 = a-1\n    a2 = a-2\n    def f0( t ):\n        return t**a1*math.exp(-t)\n\n    def df0(t):\n        return (a1-t)*t**a2*math.exp(-t)\n    \n    y = a1\n    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n    if y > x: y = x\n\n    h = 3.0e-4\n    n = int(y/h)\n    h = y/n\n    hh = 0.5*h\n    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n    return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n    global c\n    a = 12\n\n    if c is None:\n       k1_factrl = 1.0\n       c = []\n       c.append(math.sqrt(2.0*math.pi))\n       for k in range(1,a):\n          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n          k1_factrl *= -k\n    \n    accm = c[0]\n    for k in range(1,a):\n        accm += c[k] / (z+k)\n    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n    return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n    expected = sum(dataSet)*1.0/len(dataSet)\n    cntrd = (d-expected for d in dataSet)\n    return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n    dof = len(dataSet)-1\n    dist = chi2UniformDistance(dataSet)\n    return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979,  71531,  21461 ]\n\nfor ds in (dset1, dset2):\n    print \"Data set:\", ds\n    dof = len(ds)-1\n    distance =chi2UniformDistance(ds)\n    print \"dof: %d distance: %.4f\" % (dof, distance),\n    prob = chi2Probability( dof, distance)\n    print \"probability: %.4f\"%prob,\n    print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n"}
{"id": 58257, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n"}
{"id": 58258, "name": "Welch's t-test", "Python": "import numpy as np\nimport scipy as sp\nimport scipy.stats\n\ndef welch_ttest(x1, x2):\n    n1 = x1.size\n    n2 = x2.size\n    m1 = np.mean(x1)\n    m2 = np.mean(x2)\n    v1 = np.var(x1, ddof=1)\n    v2 = np.var(x2, ddof=1)\n    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)\n    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))\n    p = 2 * sp.stats.t.cdf(-abs(t), df)\n    return t, df, p\n\nwelch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))\n(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n"}
{"id": 58259, "name": "Topological sort_Extracted top item", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n"}
{"id": 58260, "name": "Topological sort_Extracted top item", "Python": "try:\n    from functools import reduce\nexcept: pass\n\n\ndef topx(data, tops=None):\n    'Extract the set of top-level(s) in topological order'\n    for k, v in data.items():\n        v.discard(k) \n    if tops is None:\n        tops = toplevels(data)\n    return _topx(data, tops, [], set())\n\ndef _topx(data, tops, _sofar, _sofar_set):\n    'Recursive topological extractor'\n    _sofar += [tops] \n    _sofar_set.union(tops)\n    depends = reduce(set.union, (data.get(top, set()) for top in tops))\n    if depends:\n        _topx(data, depends, _sofar, _sofar_set)\n    ordered, accum = [], set()\n    for s in _sofar[::-1]:\n        ordered += [sorted(s - accum)]\n        accum |= s\n    return ordered\n\ndef printorder(order):\n    'Prettyprint topological ordering'\n    if order:\n        print(\"First: \" + ', '.join(str(s) for s in order[0]))\n    for o in order[1:]:\n        print(\" Then: \" + ', '.join(str(s) for s in o))\n\ndef toplevels(data):\n    \n    for k, v in data.items():\n        v.discard(k) \n    dependents = reduce(set.union, data.values())\n    return  set(data.keys()) - dependents\n\nif __name__ == '__main__':\n    data = dict(\n        top1  = set('ip1 des1 ip2'.split()),\n        top2  = set('ip2 des1 ip3'.split()),\n        des1  = set('des1a des1b des1c'.split()),\n        des1a = set('des1a1 des1a2'.split()),\n        des1c = set('des1c1 extra1'.split()),\n        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),\n        ip1   = set('ip1a ipcommon extra1'.split()),\n        )\n\n    tops = toplevels(data)\n    print(\"The top levels of the dependency graph are: \" + ' '.join(tops))\n\n    for t in sorted(tops):\n        print(\"\\nThe compile order for top level: %s is...\" % t)\n        printorder(topx(data, set([t])))\n    if len(tops) > 1:\n        print(\"\\nThe compile order for top levels: %s is...\"\n              % ' and '.join(str(s) for s in sorted(tops)) )\n        printorder(topx(data, tops))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n"}
{"id": 58261, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n"}
{"id": 58262, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 58263, "name": "Call a function", "Python": "def no_args():\n    pass\n\nno_args()\n\ndef fixed_args(x, y):\n    print('x=%r, y=%r' % (x, y))\n\nfixed_args(1, 2)        \n\n\nfixed_args(y=2, x=1)\n\n\nmyargs=(1,2) \nfixed_args(*myargs)\n\ndef opt_args(x=1):\n    print(x)\n\nopt_args()              \nopt_args(3.141)         \n\ndef var_args(*v):\n    print(v)\n\nvar_args(1, 2, 3)       \nvar_args(1, (2,3))      \nvar_args()              \n\n\nfixed_args(y=2, x=1)    \n\n\nif 1:\n    no_args()\n\n\nassert no_args() is None\n\ndef return_something():\n    return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n\nis_builtin(pow)         \nis_builtin(is_builtin)  \n\n\n\ndef takes_anything(*args, **kwargs):\n    for each in args:\n        print(each)\n    for key, value in sorted(kwargs.items()):\n        print(\"%s:%s\" % (key, value))\n    \n    wrapped_fn(*args, **kwargs)\n    \n    \n\n\n\n\n\n\n\n\n\n", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n"}
{"id": 58264, "name": "Superpermutation minimisation", "Python": "\"Generate a short Superpermutation of n characters A... as a string using various algorithms.\"\n\n\nfrom __future__ import print_function, division\n\nfrom itertools import permutations\nfrom math import factorial\nimport string\nimport datetime\nimport gc\n\n\n\nMAXN = 7\n\n\ndef s_perm0(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in permutations(allchars)]\n    sp, tofind = allperms[0], set(allperms[1:])\n    while tofind:\n        for skip in range(1, n):\n            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):\n                \n                trial_perm = (sp + trial_add)[-n:]\n                if trial_perm in tofind:\n                    \n                    sp += trial_add\n                    tofind.discard(trial_perm)\n                    trial_add = None    \n                    break\n            if trial_add is None:\n                break\n    assert all(perm in sp for perm in allperms) \n    return sp\n\ndef s_perm1(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop()\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm2(n):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        nxt = perms.pop(0)\n        if nxt not in sp:\n            sp += nxt\n        if perms:\n            nxt = perms.pop(-1)\n            if nxt not in sp:\n                sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef _s_perm3(n, cmp):\n    \n    allchars = string.ascii_uppercase[:n]\n    allperms = [''.join(p) for p in sorted(permutations(allchars))]\n    perms, sp = allperms[::], ''\n    while perms:\n        lastn = sp[-n:]\n        nxt = cmp(perms,\n                  key=lambda pm:\n                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))\n        perms.remove(nxt)\n        if nxt not in sp:\n            sp += nxt\n    assert all(perm in sp for perm in allperms)\n    return sp\n\ndef s_perm3_max(n):\n    \n    return _s_perm3(n, max)\n\ndef s_perm3_min(n):\n    \n    return _s_perm3(n, min)\n\n\nlongest = [factorial(n) * n for n in range(MAXN + 1)]\nweight, runtime = {}, {}\nprint(__doc__)\nfor algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:\n    print('\\n\n    print(algo.__doc__)\n    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)\n    for n in range(1, MAXN + 1):\n        gc.collect()\n        gc.disable()\n        t = datetime.datetime.now()\n        sp = algo(n)\n        t = datetime.datetime.now() - t\n        gc.enable()\n        runtime[algo.__name__] += t\n        lensp = len(sp)\n        wt = (lensp / longest[n]) ** 2\n        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'\n              % (n, lensp, longest[n], wt))\n        weight[algo.__name__] *= wt\n    weight[algo.__name__] **= 1 / n  \n    weight[algo.__name__] = 1 / weight[algo.__name__]\n    print('%*s Overall Weight: %5.2f in %.1f seconds.'\n          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))\n\nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % kv for kv in\n                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))\n      \nprint('\\n\nprint('\\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in\n                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))\n", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n"}
{"id": 58265, "name": "GUI component interaction", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 58266, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n"}
{"id": 58267, "name": "Summarize and say sequence", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n"}
{"id": 58268, "name": "Summarize and say sequence", "Python": "from itertools import groupby, permutations\n\ndef A036058(number):\n    return ''.join( str(len(list(g))) + k\n                    for k,g in groupby(sorted(str(number), reverse=True)) )\n\ndef A036058_length(numberstring='0', printit=False):\n    iterations, last_three, queue_index = 1, ([None] * 3), 0\n\n    def A036058(number):\n        \n        return ''.join( str(len(list(g))) + k\n                        for k,g in groupby(number) )\n\n    while True:\n        if printit:\n            print(\"  %2i %s\" % (iterations, numberstring))\n        numberstring = ''.join(sorted(numberstring, reverse=True))\n        if numberstring in last_three:\n            break\n        assert iterations < 1000000\n        last_three[queue_index], numberstring = numberstring, A036058(numberstring)\n        iterations += 1\n        queue_index +=1\n        queue_index %=3\n    return iterations\n    \ndef max_A036058_length( start_range=range(11) ):\n    already_done = set()\n    max_len = (-1, [])\n    for n in start_range:\n        sn = str(n)\n        sns = tuple(sorted(sn, reverse=True))\n        if sns not in already_done:\n            already_done.add(sns)\n            size = A036058_length(sns)\n            if size > max_len[0]:\n                max_len = (size, [n])\n            elif size == max_len[0]:\n                max_len[1].append(n)\n    return max_len\n\nlenmax, starts = max_A036058_length( range(1000000) )\n\n\nallstarts = []\nfor n in starts:\n    allstarts += [int(''.join(x))\n                  for x in set(k\n                               for k in permutations(str(n), 4)\n                               if k[0] != '0')]\nallstarts = [x for x in sorted(allstarts) if x < 1000000]\n\nprint (  % (lenmax, allstarts)   )\n\nprint (  )\n\nfor n in starts:\n    print()\n    A036058_length(str(n), printit=True)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n"}
{"id": 58269, "name": "Spelling of ordinal numbers", "Python": "irregularOrdinals = {\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\ndef num2ordinal(n):\n    conversion = int(float(n))\n    num = spell_integer(conversion)\n    hyphen = num.rsplit(\"-\", 1)\n    num = num.rsplit(\" \", 1)\n    delim = \" \"\n    if len(num[-1]) > len(hyphen[-1]):\n        num = hyphen\n        delim = \"-\"\n    \n    if num[-1] in irregularOrdinals:\n        num[-1] = delim + irregularOrdinals[num[-1]]\n    elif num[-1].endswith(\"y\"):\n        num[-1] = delim + num[-1][:-1] + \"ieth\"\n    else:\n        num[-1] = delim + num[-1] + \"th\"\n    return \"\".join(num)\n    \nif __name__ == \"__main__\":\n    tests = \"1  2  3  4  5  11  65  100  101  272  23456  8007006005004003 123   00123.0   1.23e2\".split()\n    for num in tests:\n        print(\"{} => {}\".format(num, num2ordinal(num)))\n\n\n\n\nTENS = [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", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": 58270, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 58271, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n"}
{"id": 58272, "name": "Addition chains", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n"}
{"id": 58273, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n"}
{"id": 58274, "name": "Sparkline in unicode", "Python": "\n\n\nbar = '▁▂▃▄▅▆▇█'\nbarcount = len(bar)\n\ndef sparkline(numbers):\n    mn, mx = min(numbers), max(numbers)\n    extent = mx - mn\n    sparkline = ''.join(bar[min([barcount - 1,\n                                 int((n - mn) / extent * barcount)])]\n                        for n in numbers)\n    return mn, mx, sparkline\n\nif __name__ == '__main__':\n    import re\n    \n    for line in (\"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;\"\n                 \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;\"\n                 \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \").split(';'):\n        print(\"\\nNumbers:\", line)\n        numbers = [float(n) for n in re.split(r'[\\s,]+', line.strip())]\n        mn, mx, sp = sparkline(numbers)\n        print('  min: %5f; max: %5f' % (mn, mx))\n        print(\"  \" + sp)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n"}
{"id": 58275, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 58276, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 58277, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 58278, "name": "Compiler_AST interpreter", "Python": "def load_ast()\n    line = readline()\n    \n    line_list = tokenize the line, respecting double quotes\n\n    text = line_list[0] \n\n    if text == \";\"   \n        return NULL\n\n    node_type = text \n\n    \n    \n    \n    if len(line_list) > 1\n        return make_leaf(node_type, line_list[1])\n\n    left = load_ast()\n    right = load_ast()\n    return make_node(node_type, left, right)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n"}
{"id": 58279, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n"}
{"id": 58280, "name": "Simulate input_Mouse", "Python": "import ctypes\n\ndef click():\n    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    \n    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    \n\nclick()\n", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n"}
{"id": 58281, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"}
{"id": 58282, "name": "Sunflower fractal", "Python": "from turtle import *\nfrom math import *\n\n\n\niter = 3000\ndiskRatio = .5\n\nfactor = .5 + sqrt(1.25)\n\nscreen = getscreen()\n\n(winWidth, winHeight) = screen.screensize()\n\n\n\n\n\nx = 0.0\ny = 0.0\n\nmaxRad = pow(iter,factor)/iter;\n\nbgcolor(\"light blue\")\n\nhideturtle()\n\ntracer(0, 0)\n\nfor i in range(iter+1):\n    r = pow(i,factor)/iter;\n    \n    if r/maxRad < diskRatio:\n        pencolor(\"black\")\n    else:\n        pencolor(\"yellow\")\n \n    theta = 2*pi*factor*i;\n        \n    up()\n    \n    setposition(x + r*sin(theta), y + r*cos(theta))\n    \n    down()\n       \n    circle(10.0 * i/(1.0*iter))\n    \nupdate()\n\ndone()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n"}
{"id": 58283, "name": "Vogel's approximation method", "Python": "from collections import defaultdict\n\ncosts  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},\n          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},\n          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},\n          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}\ndemand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}\ncols = sorted(demand.iterkeys())\nsupply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}\nres = dict((k, defaultdict(int)) for k in costs)\ng = {}\nfor x in supply:\n    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])\nfor x in demand:\n    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])\n\nwhile g:\n    d = {}\n    for x in demand:\n        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]\n    s = {}\n    for x in supply:\n        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]\n    f = max(d, key=lambda n: d[n])\n    t = max(s, key=lambda n: s[n])\n    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)\n    v = min(supply[f], demand[t])\n    res[f][t] += v\n    demand[t] -= v\n    if demand[t] == 0:\n        for k, n in supply.iteritems():\n            if n != 0:\n                g[k].remove(t)\n        del g[t]\n        del demand[t]\n    supply[f] -= v\n    if supply[f] == 0:\n        for k, n in demand.iteritems():\n            if n != 0:\n                g[k].remove(f)\n        del g[f]\n        del supply[f]\n\nfor n in cols:\n    print \"\\t\", n,\nprint\ncost = 0\nfor g in sorted(costs):\n    print g, \"\\t\",\n    for n in cols:\n        y = res[g][n]\n        if y != 0:\n            print y,\n        cost += y * costs[g][n]\n        print \"\\t\",\n    print\nprint \"\\n\\nTotal Cost = \", cost\n", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 58284, "name": "Air mass", "Python": "\n\nfrom math import sqrt, cos, exp\n\nDEG = 0.017453292519943295769236907684886127134  \nRE = 6371000                                     \ndd = 0.001      \nFIN = 10000000  \n \ndef rho(a):\n    \n    return exp(-a / 8500.0)\n \ndef height(a, z, d):\n     \n    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE\n \ndef column_density(a, z):\n    \n    dsum, d = 0.0, 0.0\n    while d < FIN:\n        delta = max(dd, (dd)*d)  \n        dsum += rho(height(a, z, d + 0.5 * delta)) * delta\n        d += delta\n    return dsum\n\ndef airmass(a, z):\n    return column_density(a, z) / column_density(a, 0)\n\nprint('Angle           0 m          13700 m\\n', '-' * 36)\nfor z in range(0, 91, 5):\n    print(f\"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    RE  = 6371000 \n    DD  = 0.001   \n    FIN = 1e7     \n)\n\n\nfunc rho(a float64) float64 { return math.Exp(-a / 8500) }\n\n\nfunc radians(degrees float64) float64 { return degrees * math.Pi / 180 }\n\n\n\n\nfunc height(a, z, d float64) float64 {\n    aa := RE + a\n    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))\n    return hh - RE\n}\n\n\nfunc columnDensity(a, z float64) float64 {\n    sum := 0.0\n    d := 0.0\n    for d < FIN {\n        delta := math.Max(DD, DD*d) \n        sum += rho(height(a, z, d+0.5*delta)) * delta\n        d += delta\n    }\n    return sum\n}\n\nfunc airmass(a, z float64) float64 {\n    return columnDensity(a, z) / columnDensity(a, 0)\n}\n\nfunc main() {\n    fmt.Println(\"Angle     0 m              13700 m\")\n    fmt.Println(\"------------------------------------\")\n    for z := 0; z <= 90; z += 5 {\n        fz := float64(z)\n        fmt.Printf(\"%2d      %11.8f      %11.8f\\n\", z, airmass(0, fz), airmass(13700, fz))\n    }\n}\n"}
{"id": 58285, "name": "Formal power series", "Python": "\n\nfrom itertools import islice\nfrom fractions import Fraction\nfrom functools import reduce\ntry:\n    from itertools import izip as zip \nexcept:\n    pass\n\ndef head(n):\n    \n    return lambda seq: islice(seq, n)\n\ndef pipe(gen, *cmds):\n    \n    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)\n\ndef sinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    zero = 0\n    yield zero\n    while True:\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\n        sign = -sign\n        n +=1\n        fac *= n\n        yield zero\ndef cosinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    yield Fraction(1,fac)\n    zero = 0\n    while True:\n        n +=1\n        fac *= n\n        yield zero\n        sign = -sign\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\ndef pluspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield sum(elements)\ndef minuspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield elements[0] - sum(elements[1:])\ndef mulpower(fgen,ggen):\n    'From: http://en.wikipedia.org/wiki/Power_series\n    a,b = [],[]\n    for f,g in zip(fgen, ggen):\n        a.append(f)\n        b.append(g)\n        yield sum(f*g for f,g in zip(a, reversed(b)))\ndef constpower(n):\n    yield n\n    while True:\n        yield 0\ndef diffpower(gen):\n    'differentiatiate power series'\n    next(gen)\n    for n, an in enumerate(gen, start=1):\n        yield an*n\ndef intgpower(k=0):\n    'integrate power series with constant k'\n    def _intgpower(gen):\n        yield k\n        for n, an in enumerate(gen, start=1):\n            yield an * Fraction(1,n)\n    return _intgpower\n\n\nprint(\"cosine\")\nc = list(pipe(cosinepower(), head(10)))\nprint(c)\nprint(\"sine\")\ns = list(pipe(sinepower(), head(10)))\nprint(s)\n\nintegc = list(pipe(cosinepower(),intgpower(0), head(10)))\n\nintegs1 = list(minuspower(pipe(constpower(1), head(10)),\n                          pipe(sinepower(),intgpower(0), head(10))))\n\nassert s == integc, \"The integral of cos should be sin\"\nassert c == integs1, \"1 minus the integral of sin should be cos\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype fps interface {\n    extract(int) float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc one() fps {\n    return &oneFps{}\n}\n\nfunc add(s1, s2 fps) fps {\n    return &sum{s1: s1, s2: s2}\n}\n\nfunc sub(s1, s2 fps) fps {\n    return &diff{s1: s1, s2: s2}\n}\n\nfunc mul(s1, s2 fps) fps {\n    return &prod{s1: s1, s2: s2}\n}\n\nfunc div(s1, s2 fps) fps {\n    return &quo{s1: s1, s2: s2}\n}\n\nfunc differentiate(s1 fps) fps {\n    return &deriv{s1: s1}\n}\n\nfunc integrate(s1 fps) fps {\n    return &integ{s1: s1}\n}\n\n\n\n\n\n\n\nfunc sinCos() (fps, fps) {\n    sin := &integ{}\n    cos := sub(one(), integrate(sin))\n    sin.s1 = cos\n    return sin, cos\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype oneFps struct{}\n\n\n\nfunc (*oneFps) extract(n int) float64 {\n    if n == 0 {\n        return 1\n    }\n    return 0\n}\n\n\n\ntype sum struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *sum) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\n\n\n\n\ntype diff struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *diff) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\ntype prod struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *prod) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 0; k <= i; k++ {\n            c += s.s1.extract(k) * s.s1.extract(n-k)\n        }\n        s.s = append(s.s, c)\n    }\n    return s.s[n]\n}\n\n\n\ntype quo struct {\n    s1, s2 fps\n    inv    float64   \n    c      []float64 \n    s      []float64\n}\n\n\n\n\nfunc (s *quo) extract(n int) float64 {\n    switch {\n    case len(s.s) > 0:\n    case !math.IsInf(s.inv, 1):\n        a0 := s.s2.extract(0)\n        s.inv = 1 / a0\n        if a0 != 0 {\n            break\n        }\n        fallthrough\n    default:\n        return math.NaN()\n    }\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 1; k <= i; k++ {\n            c += s.s2.extract(k) * s.c[n-k]\n        }\n        c = s.s1.extract(i) - c*s.inv\n        s.c = append(s.c, c)\n        s.s = append(s.s, c*s.inv)\n    }\n    return s.s[n]\n}\n\n\n\n\ntype deriv struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *deriv) extract(n int) float64 {\n    for i := len(s.s); i <= n; {\n        i++\n        s.s = append(s.s, float64(i)*s.s1.extract(i))\n    }\n    return s.s[n]\n}\n\ntype integ struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *integ) extract(n int) float64 {\n    if n == 0 {\n        return 0 \n    }\n    \n    for i := len(s.s) + 1; i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i-1)/float64(i))\n    }\n    return s.s[n-1]\n}\n\n\nfunc main() {\n    \n    partialSeries := func(f fps) (s string) {\n        for i := 0; i < 6; i++ {\n            s = fmt.Sprintf(\"%s %8.5f \", s, f.extract(i))\n        }\n        return\n    }\n    sin, cos := sinCos()\n    fmt.Println(\"sin:\", partialSeries(sin))\n    fmt.Println(\"cos:\", partialSeries(cos))\n}\n"}
{"id": 58286, "name": "Formal power series", "Python": "\n\nfrom itertools import islice\nfrom fractions import Fraction\nfrom functools import reduce\ntry:\n    from itertools import izip as zip \nexcept:\n    pass\n\ndef head(n):\n    \n    return lambda seq: islice(seq, n)\n\ndef pipe(gen, *cmds):\n    \n    return reduce(lambda gen, cmd: cmd(gen), cmds, gen)\n\ndef sinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    zero = 0\n    yield zero\n    while True:\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\n        sign = -sign\n        n +=1\n        fac *= n\n        yield zero\ndef cosinepower():\n    n = 0\n    fac = 1\n    sign = +1\n    yield Fraction(1,fac)\n    zero = 0\n    while True:\n        n +=1\n        fac *= n\n        yield zero\n        sign = -sign\n        n +=1\n        fac *= n\n        yield Fraction(1, fac*sign)\ndef pluspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield sum(elements)\ndef minuspower(*powergenerators):\n    for elements in zip(*powergenerators):\n        yield elements[0] - sum(elements[1:])\ndef mulpower(fgen,ggen):\n    'From: http://en.wikipedia.org/wiki/Power_series\n    a,b = [],[]\n    for f,g in zip(fgen, ggen):\n        a.append(f)\n        b.append(g)\n        yield sum(f*g for f,g in zip(a, reversed(b)))\ndef constpower(n):\n    yield n\n    while True:\n        yield 0\ndef diffpower(gen):\n    'differentiatiate power series'\n    next(gen)\n    for n, an in enumerate(gen, start=1):\n        yield an*n\ndef intgpower(k=0):\n    'integrate power series with constant k'\n    def _intgpower(gen):\n        yield k\n        for n, an in enumerate(gen, start=1):\n            yield an * Fraction(1,n)\n    return _intgpower\n\n\nprint(\"cosine\")\nc = list(pipe(cosinepower(), head(10)))\nprint(c)\nprint(\"sine\")\ns = list(pipe(sinepower(), head(10)))\nprint(s)\n\nintegc = list(pipe(cosinepower(),intgpower(0), head(10)))\n\nintegs1 = list(minuspower(pipe(constpower(1), head(10)),\n                          pipe(sinepower(),intgpower(0), head(10))))\n\nassert s == integc, \"The integral of cos should be sin\"\nassert c == integs1, \"1 minus the integral of sin should be cos\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype fps interface {\n    extract(int) float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc one() fps {\n    return &oneFps{}\n}\n\nfunc add(s1, s2 fps) fps {\n    return &sum{s1: s1, s2: s2}\n}\n\nfunc sub(s1, s2 fps) fps {\n    return &diff{s1: s1, s2: s2}\n}\n\nfunc mul(s1, s2 fps) fps {\n    return &prod{s1: s1, s2: s2}\n}\n\nfunc div(s1, s2 fps) fps {\n    return &quo{s1: s1, s2: s2}\n}\n\nfunc differentiate(s1 fps) fps {\n    return &deriv{s1: s1}\n}\n\nfunc integrate(s1 fps) fps {\n    return &integ{s1: s1}\n}\n\n\n\n\n\n\n\nfunc sinCos() (fps, fps) {\n    sin := &integ{}\n    cos := sub(one(), integrate(sin))\n    sin.s1 = cos\n    return sin, cos\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype oneFps struct{}\n\n\n\nfunc (*oneFps) extract(n int) float64 {\n    if n == 0 {\n        return 1\n    }\n    return 0\n}\n\n\n\ntype sum struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *sum) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\n\n\n\n\ntype diff struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *diff) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\ntype prod struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *prod) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 0; k <= i; k++ {\n            c += s.s1.extract(k) * s.s1.extract(n-k)\n        }\n        s.s = append(s.s, c)\n    }\n    return s.s[n]\n}\n\n\n\ntype quo struct {\n    s1, s2 fps\n    inv    float64   \n    c      []float64 \n    s      []float64\n}\n\n\n\n\nfunc (s *quo) extract(n int) float64 {\n    switch {\n    case len(s.s) > 0:\n    case !math.IsInf(s.inv, 1):\n        a0 := s.s2.extract(0)\n        s.inv = 1 / a0\n        if a0 != 0 {\n            break\n        }\n        fallthrough\n    default:\n        return math.NaN()\n    }\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 1; k <= i; k++ {\n            c += s.s2.extract(k) * s.c[n-k]\n        }\n        c = s.s1.extract(i) - c*s.inv\n        s.c = append(s.c, c)\n        s.s = append(s.s, c*s.inv)\n    }\n    return s.s[n]\n}\n\n\n\n\ntype deriv struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *deriv) extract(n int) float64 {\n    for i := len(s.s); i <= n; {\n        i++\n        s.s = append(s.s, float64(i)*s.s1.extract(i))\n    }\n    return s.s[n]\n}\n\ntype integ struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *integ) extract(n int) float64 {\n    if n == 0 {\n        return 0 \n    }\n    \n    for i := len(s.s) + 1; i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i-1)/float64(i))\n    }\n    return s.s[n-1]\n}\n\n\nfunc main() {\n    \n    partialSeries := func(f fps) (s string) {\n        for i := 0; i < 6; i++ {\n            s = fmt.Sprintf(\"%s %8.5f \", s, f.extract(i))\n        }\n        return\n    }\n    sin, cos := sinCos()\n    fmt.Println(\"sin:\", partialSeries(sin))\n    fmt.Println(\"cos:\", partialSeries(cos))\n}\n"}
{"id": 58287, "name": "Own digits power sum", "Python": "\n\ndef isowndigitspowersum(integer):\n    \n    digits = [int(c) for c in str(integer)]\n    exponent = len(digits)\n    return sum(x ** exponent for x in digits) == integer\n\nprint(\"Own digits power sums for N = 3 to 9 inclusive:\")\nfor i in range(100, 1000000000):\n    if isowndigitspowersum(i):\n        print(i)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n    fmt.Println(\"Own digits power sums for N = 3 to 9 inclusive:\")\n    for n := 3; n < 10; n++ {\n        for d := 2; d < 10; d++ {\n            powers[d] *= d\n        }\n        i := int(math.Pow(10, float64(n-1)))\n        max := i * 10\n        lastDigit := 0\n        sum := 0\n        var digits []int\n        for i < max {\n            if lastDigit == 0 {\n                digits = rcu.Digits(i, 10)\n                sum = 0\n                for _, d := range digits {\n                    sum += powers[d]\n                }\n            } else if lastDigit == 1 {\n                sum++\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1]\n            }\n            if sum == i {\n                fmt.Println(i)\n                if lastDigit == 0 {\n                    fmt.Println(i + 1)\n                }\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if sum > i {\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if lastDigit < 9 {\n                i++\n                lastDigit++\n            } else {\n                i++\n                lastDigit = 0\n            }\n        }\n    }\n}\n"}
{"id": 58288, "name": "Compiler_virtual machine interpreter", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\nvar codeMap = map[string]code{\n    \"fetch\": fetch,\n    \"store\": store,\n    \"push\":  push,\n    \"add\":   add,\n    \"sub\":   sub,\n    \"mul\":   mul,\n    \"div\":   div,\n    \"mod\":   mod,\n    \"lt\":    lt,\n    \"gt\":    gt,\n    \"le\":    le,\n    \"ge\":    ge,\n    \"eq\":    eq,\n    \"ne\":    ne,\n    \"and\":   and,\n    \"or\":    or,\n    \"neg\":   neg,\n    \"not\":   not,\n    \"jmp\":   jmp,\n    \"jz\":    jz,\n    \"prtc\":  prtc,\n    \"prts\":  prts,\n    \"prti\":  prti,\n    \"halt\":  halt,\n}\n\nvar (\n    err        error\n    scanner    *bufio.Scanner\n    object     []code\n    stringPool []string\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int32 {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int32) bool {\n    if i != 0 {\n        return true\n    }\n    return false\n}\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\n\nfunc runVM(dataSize int) {\n    stack := make([]int32, dataSize+1)\n    pc := int32(0)\n    for {\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, stack[x])\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            ln := len(stack)\n            stack[x] = stack[ln-1]\n            stack = stack[:ln-1]\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, x)\n            pc += 4\n        case add:\n            ln := len(stack)\n            stack[ln-2] += stack[ln-1]\n            stack = stack[:ln-1]\n        case sub:\n            ln := len(stack)\n            stack[ln-2] -= stack[ln-1]\n            stack = stack[:ln-1]\n        case mul:\n            ln := len(stack)\n            stack[ln-2] *= stack[ln-1]\n            stack = stack[:ln-1]\n        case div:\n            ln := len(stack)\n            stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))\n            stack = stack[:ln-1]\n        case mod:\n            ln := len(stack)\n            stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))\n            stack = stack[:ln-1]\n        case lt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])\n            stack = stack[:ln-1]\n        case gt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])\n            stack = stack[:ln-1]\n        case le:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])\n            stack = stack[:ln-1]\n        case ge:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])\n            stack = stack[:ln-1]\n        case eq:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])\n            stack = stack[:ln-1]\n        case ne:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])\n            stack = stack[:ln-1]\n        case and:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case or:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case neg:\n            ln := len(stack)\n            stack[ln-1] = -stack[ln-1]\n        case not:\n            ln := len(stack)\n            stack[ln-1] = btoi(!itob(stack[ln-1]))\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            pc += x\n        case jz:\n            ln := len(stack)\n            v := stack[ln-1]\n            stack = stack[:ln-1]\n            if v != 0 {\n                pc += 4\n            } else {\n                x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n                pc += x\n            }\n        case prtc:\n            ln := len(stack)\n            fmt.Printf(\"%c\", stack[ln-1])\n            stack = stack[:ln-1]\n        case prts:\n            ln := len(stack)\n            fmt.Printf(\"%s\", stringPool[stack[ln-1]])\n            stack = stack[:ln-1]\n        case prti:\n            ln := len(stack)\n            fmt.Printf(\"%d\", stack[ln-1])\n            stack = stack[:ln-1]\n        case halt:\n            return\n        default:\n            reportError(fmt.Sprintf(\"Unknown opcode %d\\n\", op))\n        }\n    }\n}\n\nfunc translate(s string) string {\n    var d strings.Builder\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    return d.String()\n}\n\nfunc loadCode() int {\n    var dataSize int\n    firstLine := true\n    for scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        if len(line) == 0 {\n            if firstLine {\n                reportError(\"empty line\")\n            } else {\n                break\n            }\n        }\n        lineList := strings.Fields(line)\n        if firstLine {\n            dataSize, err = strconv.Atoi(lineList[1])\n            check(err)\n            nStrings, err := strconv.Atoi(lineList[3])\n            check(err)\n            for i := 0; i < nStrings; i++ {\n                scanner.Scan()\n                s := strings.Trim(scanner.Text(), \"\\\"\\n\")\n                stringPool = append(stringPool, translate(s))\n            }\n            firstLine = false\n            continue\n        }\n        offset, err := strconv.Atoi(lineList[0])\n        check(err)\n        instr := lineList[1]\n        opCode, ok := codeMap[instr]\n        if !ok {\n            reportError(fmt.Sprintf(\"Unknown instruction %s at %d\", instr, opCode))\n        }\n        emitByte(opCode)\n        switch opCode {\n        case jmp, jz:\n            p, err := strconv.Atoi(lineList[3])\n            check(err)\n            emitWord(p - offset - 1)\n        case push:\n            value, err := strconv.Atoi(lineList[2])\n            check(err)\n            emitWord(value)\n        case fetch, store:\n            value, err := strconv.Atoi(strings.Trim(lineList[2], \"[]\"))\n            check(err)\n            emitWord(value)\n        }\n    }\n    check(scanner.Err())\n    return dataSize\n}\n\nfunc main() {\n    codeGen, err := os.Open(\"codegen.txt\")\n    check(err)\n    defer codeGen.Close()\n    scanner = bufio.NewScanner(codeGen)\n    runVM(loadCode())\n}\n"}
{"id": 58289, "name": "Compiler_virtual machine interpreter", "Python": "def run_vm(data_size)\n    int stack[data_size + 1000]\n    set stack[0..data_size - 1] to 0\n    int pc = 0\n    while True:\n        op = code[pc]\n        pc += 1\n\n        if op == FETCH:\n            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n            pc += word_size\n        elif op == STORE:\n            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n            pc += word_size\n        elif op == PUSH:\n            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n            pc += word_size\n        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()\n        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()\n        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()\n        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()\n        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()\n        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()\n        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()\n        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()\n        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()\n        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()\n        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()\n        elif op == NEG:   stack[-1] = -stack[-1]\n        elif op == NOT:   stack[-1] = not stack[-1]\n        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n        elif op == PRTC:  print stack[-1] as a character; stack.pop()\n        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()\n        elif op == PRTI:  print stack[-1] as an integer; stack.pop()\n        elif op == HALT:  break\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\nvar codeMap = map[string]code{\n    \"fetch\": fetch,\n    \"store\": store,\n    \"push\":  push,\n    \"add\":   add,\n    \"sub\":   sub,\n    \"mul\":   mul,\n    \"div\":   div,\n    \"mod\":   mod,\n    \"lt\":    lt,\n    \"gt\":    gt,\n    \"le\":    le,\n    \"ge\":    ge,\n    \"eq\":    eq,\n    \"ne\":    ne,\n    \"and\":   and,\n    \"or\":    or,\n    \"neg\":   neg,\n    \"not\":   not,\n    \"jmp\":   jmp,\n    \"jz\":    jz,\n    \"prtc\":  prtc,\n    \"prts\":  prts,\n    \"prti\":  prti,\n    \"halt\":  halt,\n}\n\nvar (\n    err        error\n    scanner    *bufio.Scanner\n    object     []code\n    stringPool []string\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int32 {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int32) bool {\n    if i != 0 {\n        return true\n    }\n    return false\n}\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\n\nfunc runVM(dataSize int) {\n    stack := make([]int32, dataSize+1)\n    pc := int32(0)\n    for {\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, stack[x])\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            ln := len(stack)\n            stack[x] = stack[ln-1]\n            stack = stack[:ln-1]\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            stack = append(stack, x)\n            pc += 4\n        case add:\n            ln := len(stack)\n            stack[ln-2] += stack[ln-1]\n            stack = stack[:ln-1]\n        case sub:\n            ln := len(stack)\n            stack[ln-2] -= stack[ln-1]\n            stack = stack[:ln-1]\n        case mul:\n            ln := len(stack)\n            stack[ln-2] *= stack[ln-1]\n            stack = stack[:ln-1]\n        case div:\n            ln := len(stack)\n            stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))\n            stack = stack[:ln-1]\n        case mod:\n            ln := len(stack)\n            stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))\n            stack = stack[:ln-1]\n        case lt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])\n            stack = stack[:ln-1]\n        case gt:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])\n            stack = stack[:ln-1]\n        case le:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])\n            stack = stack[:ln-1]\n        case ge:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])\n            stack = stack[:ln-1]\n        case eq:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])\n            stack = stack[:ln-1]\n        case ne:\n            ln := len(stack)\n            stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])\n            stack = stack[:ln-1]\n        case and:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case or:\n            ln := len(stack)\n            stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))\n            stack = stack[:ln-1]\n        case neg:\n            ln := len(stack)\n            stack[ln-1] = -stack[ln-1]\n        case not:\n            ln := len(stack)\n            stack[ln-1] = btoi(!itob(stack[ln-1]))\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            pc += x\n        case jz:\n            ln := len(stack)\n            v := stack[ln-1]\n            stack = stack[:ln-1]\n            if v != 0 {\n                pc += 4\n            } else {\n                x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n                pc += x\n            }\n        case prtc:\n            ln := len(stack)\n            fmt.Printf(\"%c\", stack[ln-1])\n            stack = stack[:ln-1]\n        case prts:\n            ln := len(stack)\n            fmt.Printf(\"%s\", stringPool[stack[ln-1]])\n            stack = stack[:ln-1]\n        case prti:\n            ln := len(stack)\n            fmt.Printf(\"%d\", stack[ln-1])\n            stack = stack[:ln-1]\n        case halt:\n            return\n        default:\n            reportError(fmt.Sprintf(\"Unknown opcode %d\\n\", op))\n        }\n    }\n}\n\nfunc translate(s string) string {\n    var d strings.Builder\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    return d.String()\n}\n\nfunc loadCode() int {\n    var dataSize int\n    firstLine := true\n    for scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        if len(line) == 0 {\n            if firstLine {\n                reportError(\"empty line\")\n            } else {\n                break\n            }\n        }\n        lineList := strings.Fields(line)\n        if firstLine {\n            dataSize, err = strconv.Atoi(lineList[1])\n            check(err)\n            nStrings, err := strconv.Atoi(lineList[3])\n            check(err)\n            for i := 0; i < nStrings; i++ {\n                scanner.Scan()\n                s := strings.Trim(scanner.Text(), \"\\\"\\n\")\n                stringPool = append(stringPool, translate(s))\n            }\n            firstLine = false\n            continue\n        }\n        offset, err := strconv.Atoi(lineList[0])\n        check(err)\n        instr := lineList[1]\n        opCode, ok := codeMap[instr]\n        if !ok {\n            reportError(fmt.Sprintf(\"Unknown instruction %s at %d\", instr, opCode))\n        }\n        emitByte(opCode)\n        switch opCode {\n        case jmp, jz:\n            p, err := strconv.Atoi(lineList[3])\n            check(err)\n            emitWord(p - offset - 1)\n        case push:\n            value, err := strconv.Atoi(lineList[2])\n            check(err)\n            emitWord(value)\n        case fetch, store:\n            value, err := strconv.Atoi(strings.Trim(lineList[2], \"[]\"))\n            check(err)\n            emitWord(value)\n        }\n    }\n    check(scanner.Err())\n    return dataSize\n}\n\nfunc main() {\n    codeGen, err := os.Open(\"codegen.txt\")\n    check(err)\n    defer codeGen.Close()\n    scanner = bufio.NewScanner(codeGen)\n    runVM(loadCode())\n}\n"}
{"id": 58290, "name": "Bitmap_Bézier curves_Cubic", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n"}
{"id": 58291, "name": "Sorting algorithms_Pancake sort", "Python": "tutor = False\n\ndef pancakesort(data):\n    if len(data) <= 1:\n        return data\n    if tutor: print()\n    for size in range(len(data), 1, -1):\n        maxindex = max(range(size), key=data.__getitem__)\n        if maxindex+1 != size:\n            \n            if maxindex != 0:\n                \n                if tutor: print('With: %r doflip  %i'\n                                % ( ' '.join(str(x) for x in data), maxindex+1 ))\n                data[:maxindex+1] = reversed(data[:maxindex+1])\n            \n            if tutor: print('With: %r  doflip %i'\n                                % ( ' '.join(str(x) for x in data), size ))\n            data[:size] = reversed(data[:size])\n    if tutor: print()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n"}
{"id": 58292, "name": "Largest five adjacent number", "Python": "\n\nfrom random import seed,randint\nfrom datetime import datetime\n\nseed(str(datetime.now()))\n\nlargeNum = [randint(1,9)]\n\nfor i in range(1,1000):\n    largeNum.append(randint(0,9))\n\nmaxNum,minNum = 0,99999\n\nfor i in range(0,994):\n    num = int(\"\".join(map(str,largeNum[i:i+5])))\n    if num > maxNum:\n        maxNum = num\n    elif num < minNum:\n        minNum = num\n\nprint(\"Largest 5-adjacent number found \", maxNum)\nprint(\"Smallest 5-adjacent number found \", minNum)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"rcu\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var sb strings.Builder\n    for i := 0; i < 1000; i++ {\n        sb.WriteByte(byte(rand.Intn(10) + 48))\n    }\n    number := sb.String()\n    for i := 99999; i >= 0; i-- {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The largest  number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            break\n        }\n    }\n    for i := 0; i <= 99999; i++ {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The smallest number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            return\n        }\n    }\n}\n"}
{"id": 58293, "name": "Sum of square and cube digits of an integer are primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\ndef digSum(n, b):\n    s = 0\n    while n:\n        s += (n % b)\n        n = n // b\n    return s\n\nif __name__ == '__main__':\n    for n in range(11, 99):\n        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):\n            print(n, end = \"  \")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    for i := 1; i < 100; i++ {\n        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {\n            continue\n        }\n        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {\n            fmt.Printf(\"%d \", i)\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58294, "name": "The sieve of Sundaram", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nfunc sos(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        p := 2*i + 3\n        s := (p*p - 3) / 2\n        for j := s; j < k; j += p {\n            marked[j] = true\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\n\nfunc soe(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        if !marked[i] {\n            p := 2*i + 3\n            s := (p*p - 3) / 2\n            for j := s; j < k; j += p {\n                marked[j] = true\n            }\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\nfunc main() {\n    const limit = int(16e6) \n    start := time.Now()\n    primes := sos(limit)\n    elapsed := int(time.Since(start).Milliseconds())\n    climit := rcu.Commatize(limit)\n    celapsed := rcu.Commatize(elapsed)\n    million := rcu.Commatize(1e6)\n    millionth := rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"Using the Sieve of Sundaram generated primes up to %s in %s ms.\\n\\n\", climit, celapsed)\n    fmt.Println(\"First 100 odd primes generated by the Sieve of Sundaram:\")\n    for i, p := range primes[0:100] {\n        fmt.Printf(\"%3d \", p)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThe %s Sundaram prime is %s\\n\", million, millionth)\n\n    start = time.Now()\n    primes = soe(limit)\n    elapsed = int(time.Since(start).Milliseconds())\n    celapsed = rcu.Commatize(elapsed)\n    millionth = rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"\\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\\n\", celapsed)\n    fmt.Printf(\"\\nAs a check, the %s Sundaram prime would again have been %s\\n\", million, millionth)\n}\n"}
{"id": 58295, "name": "Chemical calculator", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n"}
{"id": 58296, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n"}
{"id": 58297, "name": "Exactly three adjacent 3 in lists", "Python": "\n\nfrom itertools import dropwhile, takewhile\n\n\n\ndef nnPeers(n):\n    \n    def p(x):\n        return n == x\n\n    def go(xs):\n        fromFirstMatch = list(dropwhile(\n            lambda v: not p(v),\n            xs\n        ))\n        ns = list(takewhile(p, fromFirstMatch))\n        rest = fromFirstMatch[len(ns):]\n\n        return p(len(ns)) and (\n            not any(p(x) for x in rest)\n        )\n\n    return go\n\n\n\n\ndef main():\n    \n    print(\n        '\\n'.join([\n            f'{xs} -> {nnPeers(3)(xs)}' for xs in [\n                [9, 3, 3, 3, 2, 1, 7, 8, 5],\n                [5, 2, 9, 3, 3, 7, 8, 4, 1],\n                [1, 4, 3, 6, 7, 3, 8, 3, 2],\n                [1, 2, 3, 4, 5, 6, 7, 8, 9],\n                [4, 6, 8, 7, 2, 3, 3, 3, 1]\n            ]\n        ])\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    lists := [][]int{\n        {9, 3, 3, 3, 2, 1, 7, 8, 5},\n        {5, 2, 9, 3, 3, 7, 8, 4, 1},\n        {1, 4, 3, 6, 7, 3, 8, 3, 2},\n        {1, 2, 3, 4, 5, 6, 7, 8, 9},\n        {4, 6, 8, 7, 2, 3, 3, 3, 1},\n        {3, 3, 3, 1, 2, 4, 5, 1, 3},\n        {0, 3, 3, 3, 3, 7, 2, 2, 6},\n        {3, 3, 3, 3, 3, 4, 4, 4, 4},\n    }\n    for d := 1; d <= 4; d++ {\n        fmt.Printf(\"Exactly %d adjacent %d's:\\n\", d, d)\n        for _, list := range lists {\n            var indices []int\n            for i, e := range list {\n                if e == d {\n                    indices = append(indices, i)\n                }\n            }\n            adjacent := false\n            if len(indices) == d {\n                adjacent = true\n                for i := 1; i < len(indices); i++ {\n                    if indices[i]-indices[i-1] != 1 {\n                        adjacent = false\n                        break\n                    }\n                }\n            }\n            fmt.Printf(\"%v -> %t\\n\", list, adjacent)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58298, "name": "Permutations by swapping", "Python": "from operator import itemgetter\n \nDEBUG = False \n \ndef spermutations(n):\n    \n    sign = 1\n    p = [[i, 0 if i == 0 else -1] \n         for i in range(n)]\n \n    if DEBUG: print ' \n    yield tuple(pp[0] for pp in p), sign\n \n    while any(pp[1] for pp in p): \n        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),\n                           key=itemgetter(1))\n        sign *= -1\n        if d1 == -1:\n            \n            i2 = i1 - 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == 0 or p[i2 - 1][0] > n1:\n                \n                p[i2][1] = 0\n        elif d1 == 1:\n            \n            i2 = i1 + 1\n            p[i1], p[i2] = p[i2], p[i1]\n            \n            \n            \n            if i2 == n - 1 or p[i2 + 1][0] > n1:\n                \n                p[i2][1] = 0\n        if DEBUG: print ' \n        yield tuple(pp[0] for pp in p), sign\n \n        for i3, pp in enumerate(p):\n            n3, d3 = pp\n            if n3 > n1:\n                pp[1] = 1 if i3 < i2 else -1\n                if DEBUG: print ' \n \n \nif __name__ == '__main__':\n    from itertools import permutations\n \n    for n in (3, 4):\n        print '\\nPermutations and sign of %i items' % n\n        sp = set()\n        for i in spermutations(n):\n            sp.add(i[0])\n            print('Perm: %r Sign: %2i' % i)\n            \n        \n        p = set(permutations(range(n)))\n        assert sp == p, 'Two methods of generating permutations do not agree'\n", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n"}
{"id": 58299, "name": "Minimum multiple of m where digital sum equals m", "Python": "\n\nfrom itertools import count, islice\n\n\n\ndef a131382():\n    \n    return (\n        elemIndex(x)(\n            productDigitSums(x)\n        ) for x in count(1)\n    )\n\n\n\ndef productDigitSums(n):\n    \n    return (digitSum(n * x) for x in count(0))\n\n\n\n\ndef main():\n    \n\n    print(\n        table(10)([\n            str(x) for x in islice(\n                a131382(),\n                40\n            )\n        ])\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitSum(n):\n    \n    return sum(int(x) for x in list(str(n)))\n\n\n\ndef elemIndex(x):\n    \n    def go(xs):\n        try:\n            return next(\n                i for i, v in enumerate(xs) if x == v\n            )\n        except StopIteration:\n            return None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n"}
{"id": 58300, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n"}
{"id": 58301, "name": "Verhoeff algorithm", "Python": "MULTIPLICATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),\n    (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),\n    (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),\n    (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),\n    (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),\n    (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),\n    (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),\n    (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),\n    (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),\n]\n\nINV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)\n\nPERMUTATION_TABLE = [\n    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n    (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),\n    (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),\n    (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),\n    (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),\n    (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),\n    (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),\n    (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),\n]\n\ndef verhoeffchecksum(n, validate=True, terse=True, verbose=False):\n    \n    if verbose:\n        print(f\"\\n{'Validation' if validate else 'Check digit'}\",\\\n            f\"calculations for {n}:\\n\\n i  nᵢ  p[i,nᵢ]   c\\n------------------\")\n    \n    c, dig = 0, list(str(n if validate else 10 * n))\n    for i, ni in enumerate(dig[::-1]):\n        p = PERMUTATION_TABLE[i % 8][int(ni)]\n        c = MULTIPLICATION_TABLE[c][p]\n        if verbose:\n            print(f\"{i:2}  {ni}      {p}    {c}\")\n\n    if verbose and not validate:\n        print(f\"\\ninv({c}) = {INV[c]}\")\n    if not terse:\n        print(f\"\\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}.\"\\\n              if validate else f\"\\nThe check digit for '{n}' is {INV[c]}.\")\n    return c == 0 if validate else INV[c]\n\nif __name__ == '__main__':\n\n    for n, va, t, ve in [\n        (236, False, False, True), (2363, True, False, True), (2369, True, False, True),\n        (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),\n        (123456789012, False, False, False), (1234567890120, True, False, False),\n        (1234567890129, True, False, False)]:\n        verhoeffchecksum(n, va, t, ve)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar d = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},\n    {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},\n    {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},\n    {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},\n    {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n}\n\nvar inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}\n\nvar p = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},\n    {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},\n    {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},\n    {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n}\n\nfunc verhoeff(s string, validate, table bool) interface{} {\n    if table {\n        t := \"Check digit\"\n        if validate {\n            t = \"Validation\"\n        }\n        fmt.Printf(\"%s calculations for '%s':\\n\\n\", t, s)\n        fmt.Println(\" i  nᵢ  p[i,nᵢ]  c\")\n        fmt.Println(\"------------------\")\n    }\n    if !validate {\n        s = s + \"0\"\n    }\n    c := 0\n    le := len(s) - 1\n    for i := le; i >= 0; i-- {\n        ni := int(s[i] - 48)\n        pi := p[(le-i)%8][ni]\n        c = d[c][pi]\n        if table {\n            fmt.Printf(\"%2d  %d      %d     %d\\n\", le-i, ni, pi, c)\n        }\n    }\n    if table && !validate {\n        fmt.Printf(\"\\ninv[%d] = %d\\n\", c, inv[c])\n    }\n    if !validate {\n        return inv[c]\n    }\n    return c == 0\n}\n\nfunc main() {\n    ss := []string{\"236\", \"12345\", \"123456789012\"}\n    ts := []bool{true, true, false, true}\n    for i, s := range ss {\n        c := verhoeff(s, false, ts[i]).(int)\n        fmt.Printf(\"\\nThe check digit for '%s' is '%d'\\n\\n\", s, c)\n        for _, sc := range []string{s + string(c+48), s + \"9\"} {\n            v := verhoeff(sc, true, ts[i]).(bool)\n            ans := \"correct\"\n            if !v {\n                ans = \"incorrect\"\n            }\n            fmt.Printf(\"\\nThe validation for '%s' is %s\\n\\n\", sc, ans)\n        }\n    }\n}\n"}
{"id": 58302, "name": "Steady squares", "Python": "print(\"working...\")\nprint(\"Steady squares under 10.000 are:\")\nlimit = 10000\n\nfor n in range(1,limit):\n    nstr = str(n)\n    nlen = len(nstr)\n    square = str(pow(n,2))\n    rn = square[-nlen:]\n    if nstr == rn:\n       print(str(n) + \" \" + str(square))\n\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc contains(list []int, s int) bool {\n    for _, e := range list {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"Steady squares under 10,000:\")\n    finalDigits := []int{1, 5, 6}\n    for i := 1; i < 10000; i++ {\n        if !contains(finalDigits, i%10) {\n            continue\n        }\n        sq := i * i\n        sqs := strconv.Itoa(sq)\n        is := strconv.Itoa(i)\n        if strings.HasSuffix(sqs, is) {\n            fmt.Printf(\"%5s -> %10s\\n\", rcu.Commatize(i), rcu.Commatize(sq))\n        }\n    }\n}\n"}
{"id": 58303, "name": "Numbers in base 10 that are palindromic in bases 2, 4, and 16", "Python": "def reverse(n, base):\n    r = 0\n    while n > 0:\n        r = r*base + n%base\n        n = n//base\n    return r\n    \ndef palindrome(n, base):\n    return n == reverse(n, base)\n    \ncnt = 0\nfor i in range(25000):\n    if all(palindrome(i, base) for base in (2,4,16)):\n        cnt += 1\n        print(\"{:5}\".format(i), end=\" \\n\"[cnt % 12 == 0])\n\nprint()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc reverse(s string) string {\n    chars := []rune(s)\n    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n        chars[i], chars[j] = chars[j], chars[i]\n    }\n    return string(chars)\n}\n\nfunc main() {\n    fmt.Println(\"Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:\")\n    var numbers []int\n    for i := int64(0); i < 25000; i++ {\n        b2 := strconv.FormatInt(i, 2)\n        if b2 == reverse(b2) {\n            b4 := strconv.FormatInt(i, 4)\n            if b4 == reverse(b4) {\n                b16 := strconv.FormatInt(i, 16)\n                if b16 == reverse(b16) {\n                    numbers = append(numbers, int(i))\n                }\n            }\n        }\n    }\n    for i, n := range numbers {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(numbers), \"such numbers.\")\n}\n"}
{"id": 58304, "name": "Long stairs", "Python": "\n\nfrom numpy import mean\nfrom random import sample\n\ndef gen_long_stairs(start_step, start_length, climber_steps, add_steps):\n    secs, behind, total = 0, start_step, start_length\n    while True:\n        behind += climber_steps\n        behind += sum([behind > n for n in sample(range(total), add_steps)])\n        total += add_steps\n        secs += 1\n        yield (secs, behind, total)\n        \n\nls = gen_long_stairs(1, 100, 1, 5)\n\nprint(\"Seconds  Behind  Ahead\\n----------------------\")\nwhile True:\n    secs, pos, len = next(ls)\n    if 600 <= secs < 610:\n        print(secs, \"     \", pos, \"   \", len - pos)\n    elif secs == 610:\n        break\n\nprint(\"\\nTen thousand trials to top:\")\ntimes, heights = [], []\nfor trial in range(10_000):\n    trialstairs = gen_long_stairs(1, 100, 1, 5)\n    while True:\n        sec, step, height = next(trialstairs)\n        if step >= height:\n            times.append(sec)\n            heights.append(height)\n            break\n\nprint(\"Mean time:\", mean(times), \"secs. Mean height:\", mean(heights))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    totalSecs := 0\n    totalSteps := 0\n    fmt.Println(\"Seconds    steps behind    steps ahead\")\n    fmt.Println(\"-------    ------------    -----------\")\n    for trial := 1; trial < 10000; trial++ {\n        sbeh := 0\n        slen := 100\n        secs := 0\n        for sbeh < slen {\n            sbeh++\n            for wiz := 1; wiz < 6; wiz++ {\n                if rand.Intn(slen) < sbeh {\n                    sbeh++\n                }\n                slen++\n            }\n            secs++\n            if trial == 1 && secs > 599 && secs < 610 {\n                fmt.Printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh)\n            }\n        }\n        totalSecs += secs\n        totalSteps += slen\n    }\n    fmt.Println(\"\\nAverage secs taken:\", float64(totalSecs)/10000)\n    fmt.Println(\"Average final length of staircase:\", float64(totalSteps)/10000)\n}\n"}
{"id": 58305, "name": "Terminal control_Positional read", "Python": "import curses\nfrom random import randint\n\n\n\nstdscr = curses.initscr()\nfor rows in range(10):\n    line = ''.join([chr(randint(41, 90)) for i in range(10)])\n    stdscr.addstr(line + '\\n')\n\n\nicol = 3 - 1\nirow = 6 - 1\nch = stdscr.instr(irow, icol, 1).decode(encoding=\"utf-8\")\n\n\nstdscr.move(irow, icol + 10)\nstdscr.addstr('Character at column 3, row 6 = ' + ch + '\\n')\nstdscr.getch()\n\ncurses.endwin()\n", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i < 80*25; i++ {\n        fmt.Print(\"A\")  \n    }\n    fmt.Println()\n    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)\n    info := C.CONSOLE_SCREEN_BUFFER_INFO{}\n    pos := C.COORD{}\n    C.GetConsoleScreenBufferInfo(conOut, &info)\n    pos.X = info.srWindow.Left + 3 \n    pos.Y = info.srWindow.Top + 6  \n    var c C.wchar_t\n    var le C.ulong\n    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)\n    if ret == 0 || le <= 0 {\n        fmt.Println(\"Something went wrong!\")\n        return\n    }\n    fmt.Printf(\"The character at column 3, row 6 is '%c'\\n\", c) \n}\n"}
{"id": 58306, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 58307, "name": "Pseudo-random numbers_Middle-square method", "Python": "seed = 675248\ndef random():\n    global seed\n    seed = int(str(seed ** 2).zfill(12)[3:9])\n    return seed\nfor _ in range(5):\n    print(random())\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n"}
{"id": 58308, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n"}
{"id": 58309, "name": "Image convolution", "Python": "\nfrom PIL import Image, ImageFilter\n\nif __name__==\"__main__\":\n\tim = Image.open(\"test.jpg\")\n\n\tkernelValues = [-2,-1,0,-1,1,1,0,1,2] \n\tkernel = ImageFilter.Kernel((3,3), kernelValues)\n\n\tim2 = im.filter(kernel)\n\n\tim2.show()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/jpeg\"\n    \"math\"\n    \"os\"\n)\n\n\n\nfunc kf3(k *[9]float64, src, dst *image.Gray) {\n    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {\n        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {\n            var sum float64\n            var i int\n            for yo := y - 1; yo <= y+1; yo++ {\n                for xo := x - 1; xo <= x+1; xo++ {\n                    if (image.Point{xo, yo}).In(src.Rect) {\n                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)\n                    } else {\n                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)\n                    }\n                    i++\n                }\n            }\n            dst.SetGray(x, y,\n                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})\n        }\n    }\n}\n\nvar blur = [9]float64{\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9}\n\n\n\nfunc blurY(src *image.YCbCr) *image.YCbCr {\n    dst := *src\n\n    \n    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {\n        return &dst\n    }\n\n    \n    srcGray := image.Gray{src.Y, src.YStride, src.Rect}\n    dstGray := srcGray\n    dstGray.Pix = make([]uint8, len(src.Y))\n    kf3(&blur, &srcGray, &dstGray) \n\n    \n    dst.Y = dstGray.Pix                   \n    dst.Cb = append([]uint8{}, src.Cb...) \n    dst.Cr = append([]uint8{}, src.Cr...)\n    return &dst\n}\n\nfunc main() {\n    \n    \n    f, err := os.Open(\"Lenna100.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    img, err := jpeg.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n    y, ok := img.(*image.YCbCr)\n    if !ok {\n        fmt.Println(\"expected color jpeg\")\n        return\n    }\n    f, err = os.Create(\"blur.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58310, "name": "Deconvolution_2D+", "Python": "\n\nimport numpy\nimport pprint\n\nh =  [\n      [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], \n      [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf =  [\n      [[-9, 5, -8], [3, 5, 1]], \n      [[-1, -7, 2], [-5, -6, 6]], \n      [[8, 5, 8],[-2, -6, -4]]]\ng =  [\n      [\n         [54, 42, 53, -42, 85, -72], \n         [45, -170, 94, -36, 48, 73], \n         [-39, 65, -112, -16, -78, -72], \n         [6, -11, -6, 62, 49, 8]], \n      [\n         [-57, 49, -23, 52, -135, 66], \n         [-23, 127, -58, -5, -118, 64], \n         [87, -16, 121, 23, -41, -12], \n         [-19, 29, 35, -148, -11, 45]], \n      [\n         [-55, -147, -146, -31, 55, 60], \n         [-88, -45, -28, 46, -26, -144], \n         [-12, -107, -34, 150, 249, 66], \n         [11, -15, -34, 27, -78, -50]], \n      [\n         [56, 67, 108, 4, 2, -48], \n         [58, 67, 89, 32, 32, -8], \n         [-42, -31, -103, -30, -23, -8],\n         [6, 4, -26, -10, 26, 12]]]\n      \ndef trim_zero_empty(x):\n    \n    \n    if len(x) > 0:\n        if type(x[0]) != numpy.ndarray:\n            \n            return list(numpy.trim_zeros(x))\n        else:\n            \n            new_x = []\n            for l in x:\n               tl = trim_zero_empty(l)\n               if len(tl) > 0:\n                   new_x.append(tl)\n            return new_x\n    else:\n        \n        return x\n       \ndef deconv(a, b):\n    \n    \n    \n\n    ffta = numpy.fft.fftn(a)\n    \n    \n    \n    \n    ashape = numpy.shape(a)\n    \n    \n    \n\n    fftb = numpy.fft.fftn(b,ashape)\n    \n    \n\n    fftquotient = ffta / fftb\n    \n    \n    \n\n    c = numpy.fft.ifftn(fftquotient)\n    \n    \n    \n\n    trimmedc = numpy.around(numpy.real(c),decimals=6)\n    \n    \n    \n    \n    cleanc = trim_zero_empty(trimmedc)\n                \n    return cleanc\n    \nprint(\"deconv(g,h)=\")\n\npprint.pprint(deconv(g,h))\n\nprint(\" \")\n\nprint(\"deconv(g,f)=\")\n\npprint.pprint(deconv(g,f))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\nfunc fft(buf []complex128, n int) {\n    out := make([]complex128, n)\n    copy(out, buf)\n    fft2(buf, out, n, 1)\n}\n\nfunc fft2(buf, out []complex128, n, step int) {\n    if step < n {\n        fft2(out, buf, n, step*2)\n        fft2(out[step:], buf[step:], n, step*2)\n        for j := 0; j < n; j += 2 * step {\n            fj, fn := float64(j), float64(n)\n            t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step]\n            buf[j/2] = out[j] + t\n            buf[(j+n)/2] = out[j] - t\n        }\n    }\n}\n\n\nfunc padTwo(g []float64, le int, ns *int) []complex128 {\n    n := 1\n    if *ns != 0 {\n        n = *ns\n    } else {\n        for n < le {\n            n *= 2\n        }\n    }\n    buf := make([]complex128, n)\n    for i := 0; i < le; i++ {\n        buf[i] = complex(g[i], 0)\n    }\n    *ns = n\n    return buf\n}\n\nfunc deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) {\n    ns := 0\n    g2 := padTwo(g, lg, &ns)\n    f2 := padTwo(f, lf, &ns)\n    fft(g2, ns)\n    fft(f2, ns)\n    h := make([]complex128, ns)\n    for i := 0; i < ns; i++ {\n        h[i] = g2[i] / f2[i]\n    }\n    fft(h, ns)\n    for i := 0; i < ns; i++ {\n        if math.Abs(real(h[i])) < 1e-10 {\n            h[i] = 0\n        }\n    }\n    for i := 0; i > lf-lg-rowLe; i-- {\n        out[-i] = real(h[(i+ns)%ns] / 32)\n    }\n}\n\nfunc unpack2(m [][]float64, rows, le, toLe int) []float64 {\n    buf := make([]float64, rows*toLe)\n    for i := 0; i < rows; i++ {\n        for j := 0; j < le; j++ {\n            buf[i*toLe+j] = m[i][j]\n        }\n    }\n    return buf\n}\n\nfunc pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) {\n    for i := 0; i < rows; i++ {\n        for j := 0; j < toLe; j++ {\n            out[i][j] = buf[i*fromLe+j] / 4\n        }\n    }\n}\n\nfunc deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) {\n    g2 := unpack2(g, rowG, colG, colG)\n    f2 := unpack2(f, rowF, colF, colG)\n    ff := make([]float64, (rowG-rowF+1)*colG)\n    deconv(g2, rowG*colG, f2, rowF*colG, ff, colG)\n    pack2(ff, rowG-rowF+1, colG, colG-colF+1, out)\n}\n\nfunc unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 {\n    buf := make([]float64, x*toY*toZ)\n    for i := 0; i < x; i++ {\n        for j := 0; j < y; j++ {\n            for k := 0; k < z; k++ {\n                buf[(i*toY+j)*toZ+k] = m[i][j][k]\n            }\n        }\n    }\n    return buf\n}\n\nfunc pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) {\n    for i := 0; i < x; i++ {\n        for j := 0; j < toY; j++ {\n            for k := 0; k < toZ; k++ {\n                out[i][j][k] = buf[(i*y+j)*z+k] / 4\n            }\n        }\n    }\n}\n\nfunc deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) {\n    g2 := unpack3(g, gx, gy, gz, gy, gz)\n    f2 := unpack3(f, fx, fy, fz, gy, gz)\n    ff := make([]float64, (gx-fx+1)*gy*gz)\n    deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)\n    pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)\n}\n\nfunc main() {\n    f := [][][]float64{\n        {{-9, 5, -8}, {3, 5, 1}},\n        {{-1, -7, 2}, {-5, -6, 6}},\n        {{8, 5, 8}, {-2, -6, -4}},\n    }\n    fx, fy, fz := len(f), len(f[0]), len(f[0][0])\n\n    g := [][][]float64{\n        {{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73},\n            {-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}},\n        {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64},\n            {87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}},\n        {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144},\n            {-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}},\n        {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8},\n            {-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12},\n        },\n    }\n    gx, gy, gz := len(g), len(g[0]), len(g[0][0])\n\n    h := [][][]float64{\n        {{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}},\n        {{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}},\n    }\n    hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1\n\n    h2 := make([][][]float64, hx)\n    for i := 0; i < hx; i++ {\n        h2[i] = make([][]float64, hy)\n        for j := 0; j < hy; j++ {\n            h2[i][j] = make([]float64, hz)\n        }\n    }\n    deconv3(g, gx, gy, gz, f, fx, fy, fz, h2)\n    fmt.Println(\"deconv3(g, f):\\n\")\n    for i := 0; i < hx; i++ {\n        for j := 0; j < hy; j++ {\n            for k := 0; k < hz; k++ {\n                fmt.Printf(\"% .10g  \", h2[i][j][k])\n            }\n            fmt.Println()\n        }\n        if i < hx-1 {\n            fmt.Println()\n        }\n    }\n\n    kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1\n    f2 := make([][][]float64, kx)\n    for i := 0; i < kx; i++ {\n        f2[i] = make([][]float64, ky)\n        for j := 0; j < ky; j++ {\n            f2[i][j] = make([]float64, kz)\n        }\n    }\n    deconv3(g, gx, gy, gz, h, hx, hy, hz, f2)\n    fmt.Println(\"\\ndeconv(g, h):\\n\")\n    for i := 0; i < kx; i++ {\n        for j := 0; j < ky; j++ {\n            for k := 0; k < kz; k++ {\n                fmt.Printf(\"% .10g  \", f2[i][j][k])\n            }\n            fmt.Println()\n        }\n        if i < kx-1 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 58311, "name": "Dice game probabilities", "Python": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n    counts = [0] * ((n_faces + 1) * n_dice)\n    for t in product(range(1, n_faces + 1), repeat=n_dice):\n        counts[sum(t)] += 1\n    return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n    c1, p1 = gen_dict(n_sides1, n_dice1)\n    c2, p2 = gen_dict(n_sides2, n_dice2)\n    p12 = float(p1 * p2)\n\n    return sum(p[1] * q[1] / p12\n               for p, q in product(enumerate(c1), enumerate(c2))\n               if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)\n", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n"}
{"id": 58312, "name": "Zebra puzzle", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"log\"\n        \"strings\"\n)\n\n\n\ntype HouseSet [5]*House\ntype House struct {\n        n Nationality\n        c Colour\n        a Animal\n        d Drink\n        s Smoke\n}\ntype Nationality int8\ntype Colour int8\ntype Animal int8\ntype Drink int8\ntype Smoke int8\n\n\n\nconst (\n        English Nationality = iota\n        Swede\n        Dane\n        Norwegian\n        German\n)\nconst (\n        Red Colour = iota\n        Green\n        White\n        Yellow\n        Blue\n)\nconst (\n        Dog Animal = iota\n        Birds\n        Cats\n        Horse\n        Zebra\n)\nconst (\n        Tea Drink = iota\n        Coffee\n        Milk\n        Beer\n        Water\n)\nconst (\n        PallMall Smoke = iota\n        Dunhill\n        Blend\n        BlueMaster\n        Prince\n)\n\n\n\nvar nationalities = [...]string{\"English\", \"Swede\", \"Dane\", \"Norwegian\", \"German\"}\nvar colours = [...]string{\"red\", \"green\", \"white\", \"yellow\", \"blue\"}\nvar animals = [...]string{\"dog\", \"birds\", \"cats\", \"horse\", \"zebra\"}\nvar drinks = [...]string{\"tea\", \"coffee\", \"milk\", \"beer\", \"water\"}\nvar smokes = [...]string{\"Pall Mall\", \"Dunhill\", \"Blend\", \"Blue Master\", \"Prince\"}\n\nfunc (n Nationality) String() string { return nationalities[n] }\nfunc (c Colour) String() string      { return colours[c] }\nfunc (a Animal) String() string      { return animals[a] }\nfunc (d Drink) String() string       { return drinks[d] }\nfunc (s Smoke) String() string       { return smokes[s] }\nfunc (h House) String() string {\n        return fmt.Sprintf(\"%-9s  %-6s  %-5s  %-6s  %s\", h.n, h.c, h.a, h.d, h.s)\n}\nfunc (hs HouseSet) String() string {\n        lines := make([]string, 0, len(hs))\n        for i, h := range hs {\n                s := fmt.Sprintf(\"%d  %s\", i, h)\n                lines = append(lines, s)\n        }\n        return strings.Join(lines, \"\\n\")\n}\n\n\n\nfunc simpleBruteForce() (int, HouseSet) {\n        var v []House\n        for n := range nationalities {\n                for c := range colours {\n                        for a := range animals {\n                                for d := range drinks {\n                                        for s := range smokes {\n                                                h := House{\n                                                        n: Nationality(n),\n                                                        c: Colour(c),\n                                                        a: Animal(a),\n                                                        d: Drink(d),\n                                                        s: Smoke(s),\n                                                }\n                                                if !h.Valid() {\n                                                        continue\n                                                }\n                                                v = append(v, h)\n                                        }\n                                }\n                        }\n                }\n        }\n        n := len(v)\n        log.Println(\"Generated\", n, \"valid houses\")\n\n        combos := 0\n        first := 0\n        valid := 0\n        var validSet HouseSet\n        for a := 0; a < n; a++ {\n                if v[a].n != Norwegian { \n                        continue\n                }\n                for b := 0; b < n; b++ {\n                        if b == a {\n                                continue\n                        }\n                        if v[b].anyDups(&v[a]) {\n                                continue\n                        }\n                        for c := 0; c < n; c++ {\n                                if c == b || c == a {\n                                        continue\n                                }\n                                if v[c].d != Milk { \n                                        continue\n                                }\n                                if v[c].anyDups(&v[b], &v[a]) {\n                                        continue\n                                }\n                                for d := 0; d < n; d++ {\n                                        if d == c || d == b || d == a {\n                                                continue\n                                        }\n                                        if v[d].anyDups(&v[c], &v[b], &v[a]) {\n                                                continue\n                                        }\n                                        for e := 0; e < n; e++ {\n                                                if e == d || e == c || e == b || e == a {\n                                                        continue\n                                                }\n                                                if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {\n                                                        continue\n                                                }\n                                                combos++\n                                                set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}\n                                                if set.Valid() {\n                                                        valid++\n                                                        if valid == 1 {\n                                                                first = combos\n                                                        }\n                                                        validSet = set\n                                                        \n                                                }\n                                        }\n                                }\n                        }\n                }\n        }\n        log.Println(\"Tested\", first, \"different combinations of valid houses before finding solution\")\n        log.Println(\"Tested\", combos, \"different combinations of valid houses in total\")\n        return valid, validSet\n}\n\n\nfunc (h *House) anyDups(list ...*House) bool {\n        for _, b := range list {\n                if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {\n                        return true\n                }\n        }\n        return false\n}\n\nfunc (h *House) Valid() bool {\n        \n        if h.n == English && h.c != Red || h.n != English && h.c == Red {\n                return false\n        }\n        \n        if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {\n                return false\n        }\n        \n        if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {\n                return false\n        }\n        \n        if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {\n                return false\n        }\n        \n        if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {\n                return false\n        }\n        \n        if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {\n                return false\n        }\n        \n        if h.a == Cats && h.s == Blend {\n                return false\n        }\n        \n        if h.a == Horse && h.s == Dunhill {\n                return false\n        }\n        \n        if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {\n                return false\n        }\n        \n        if h.n == German && h.s != Prince || h.n != German && h.s == Prince {\n                return false\n        }\n        \n        if h.n == Norwegian && h.c == Blue {\n                return false\n        }\n        \n        if h.d == Water && h.s == Blend {\n                return false\n        }\n        return true\n}\n\nfunc (hs *HouseSet) Valid() bool {\n        ni := make(map[Nationality]int, 5)\n        ci := make(map[Colour]int, 5)\n        ai := make(map[Animal]int, 5)\n        di := make(map[Drink]int, 5)\n        si := make(map[Smoke]int, 5)\n        for i, h := range hs {\n                ni[h.n] = i\n                ci[h.c] = i\n                ai[h.a] = i\n                di[h.d] = i\n                si[h.s] = i\n        }\n        \n        if ci[Green]+1 != ci[White] {\n                return false\n        }\n        \n        if dist(ai[Cats], si[Blend]) != 1 {\n                return false\n        }\n        \n        if dist(ai[Horse], si[Dunhill]) != 1 {\n                return false\n        }\n        \n        if dist(ni[Norwegian], ci[Blue]) != 1 {\n                return false\n        }\n        \n        if dist(di[Water], si[Blend]) != 1 {\n                return false\n        }\n\n        \n        if hs[2].d != Milk {\n                return false\n        }\n        \n        if hs[0].n != Norwegian {\n                return false\n        }\n        return true\n}\n\nfunc dist(a, b int) int {\n        if a > b {\n                return a - b\n        }\n        return b - a\n}\n\nfunc main() {\n        log.SetFlags(0)\n        n, sol := simpleBruteForce()\n        fmt.Println(n, \"solution found\")\n        fmt.Println(sol)\n}\n"}
{"id": 58313, "name": "Rosetta Code_Find unimplemented tasks", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n"}
{"id": 58314, "name": "First-class functions_Use numbers analogously", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 58315, "name": "First-class functions_Use numbers analogously", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 2.\n    xi := .5\n    y := 4.\n    yi := .25\n    z := x + y\n    zi := 1 / (x + y)\n    \n\n    numbers := []float64{x, y, z}\n    inverses := []float64{xi, yi, zi}\n    \n\n    mfs := make([]func(float64) float64, len(numbers))\n    for i := range mfs {\n        mfs[i] = multiplier(numbers[i], inverses[i])\n    }\n    \n\n    for _, mf := range mfs {\n        fmt.Println(mf(1))\n    }\n}\n\nfunc multiplier(n1, n2 float64) func(float64) float64 {\n    \n    n1n2 := n1 * n2\n    \n    return func(m float64) float64 {\n        return n1n2 * m\n    }\n}\n"}
{"id": 58316, "name": "Sokoban", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n"}
{"id": 58317, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 58318, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 58319, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n    t1 := big.NewInt(32)\n    t1.Mul(factorial(6*n), t1)\n    t2 := big.NewInt(532*n*n + 126*n + 9)\n    t3 := new(big.Int)\n    t3.Exp(factorial(n), six, nil)\n    t3.Mul(t3, three)\n    ip := new(big.Int)\n    ip.Mul(t1, t2)\n    ip.Quo(ip, t3)\n    pw := 6*n + 3\n    t1.SetInt64(pw)\n    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n    if print {\n        fmt.Printf(\"%d  %44d  %3d  %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n    }\n    return tm\n}\n\nfunc main() {\n    fmt.Println(\"N                               Integer Portion  Pow  Nth Term (33 dp)\")\n    fmt.Println(strings.Repeat(\"-\", 89))\n    for n := int64(0); n < 10; n++ {\n        almkvistGiullera(n, true)\n    }\n\n    sum := new(big.Rat)\n    prev := new(big.Rat)\n    pow70 := new(big.Int).Exp(ten, seventy, nil)\n    prec := new(big.Rat).SetFrac(one, pow70)\n    n := int64(0)\n    for {\n        term := almkvistGiullera(n, false)\n        sum.Add(sum, term)\n        z := new(big.Rat).Sub(sum, prev)\n        z.Abs(z)\n        if z.Cmp(prec) < 0 {\n            break\n        }\n        prev.Set(sum)\n        n++\n    }\n    sum.Inv(sum)\n    pi := new(big.Float).SetPrec(256).SetRat(sum)\n    pi.Sqrt(pi)\n    fmt.Println(\"\\nPi to 70 decimal places is:\")\n    fmt.Println(pi.Text('f', 70))\n}\n"}
{"id": 58320, "name": "Practical numbers", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n"}
{"id": 58321, "name": "Consecutive primes with ascending or descending differences", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst LIMIT = 999999\n\nvar primes = rcu.Primes(LIMIT)\n\nfunc longestSeq(dir string) {\n    pd := 0\n    longSeqs := [][]int{{2}}\n    currSeq := []int{2}\n    for i := 1; i < len(primes); i++ {\n        d := primes[i] - primes[i-1]\n        if (dir == \"ascending\" && d <= pd) || (dir == \"descending\" && d >= pd) {\n            if len(currSeq) > len(longSeqs[0]) {\n                longSeqs = [][]int{currSeq}\n            } else if len(currSeq) == len(longSeqs[0]) {\n                longSeqs = append(longSeqs, currSeq)\n            }\n            currSeq = []int{primes[i-1], primes[i]}\n        } else {\n            currSeq = append(currSeq, primes[i])\n        }\n        pd = d\n    }\n    if len(currSeq) > len(longSeqs[0]) {\n        longSeqs = [][]int{currSeq}\n    } else if len(currSeq) == len(longSeqs[0]) {\n        longSeqs = append(longSeqs, currSeq)\n    }\n    fmt.Println(\"Longest run(s) of primes with\", dir, \"differences is\", len(longSeqs[0]), \":\")\n    for _, ls := range longSeqs {\n        var diffs []int\n        for i := 1; i < len(ls); i++ {\n            diffs = append(diffs, ls[i]-ls[i-1])\n        }\n        for i := 0; i < len(ls)-1; i++ {\n            fmt.Print(ls[i], \" (\", diffs[i], \") \")\n        }\n        fmt.Println(ls[len(ls)-1])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    fmt.Println(\"For primes < 1 million:\\n\")\n    for _, dir := range []string{\"ascending\", \"descending\"} {\n        longestSeq(dir)\n    }\n}\n"}
{"id": 58322, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 58323, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n"}
{"id": 58324, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 58325, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n"}
{"id": 58326, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 58327, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 58328, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n"}
{"id": 58329, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 58330, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n"}
{"id": 58331, "name": "Word search", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n"}
{"id": 58332, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 58333, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n"}
{"id": 58334, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n"}
{"id": 58335, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 58336, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n"}
{"id": 58337, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n"}
{"id": 58338, "name": "Zumkeller numbers", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58339, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 58340, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 58341, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n"}
{"id": 58342, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 58343, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n"}
{"id": 58344, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\n}\n"}
{"id": 58345, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n"}
{"id": 58346, "name": "Geometric algebra", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n"}
{"id": 58347, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 58348, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n"}
{"id": 58349, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n"}
{"id": 58350, "name": "Define a primitive data type", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n"}
{"id": 58351, "name": "Arithmetic derivative", "Python": "from sympy.ntheory import factorint\n\ndef D(n):\n    if n < 0:\n        return -D(-n)\n    elif n < 2:\n        return 0\n    else:\n        fdict = factorint(n)\n        if len(fdict) == 1 and 1 in fdict: \n            return 1\n        return sum([n * e // p for p, e in fdict.items()])\n\nfor n in range(-99, 101):\n    print('{:5}'.format(D(n)), end='\\n' if n % 10 == 0 else '')\n\nprint()\nfor m in range(1, 21):\n    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc D(n float64) float64 {\n    if n < 0 {\n        return -D(-n)\n    }\n    if n < 2 {\n        return 0\n    }\n    var f []int\n    if n < 1e19 {\n        f = rcu.PrimeFactors(int(n))\n    } else {\n        g := int(n / 100)\n        f = rcu.PrimeFactors(g)\n        f = append(f, []int{2, 2, 5, 5}...)\n    }\n    c := len(f)\n    if c == 1 {\n        return 1\n    }\n    if c == 2 {\n        return float64(f[0] + f[1])\n    }\n    d := n / float64(f[0])\n    return D(d)*float64(f[0]) + d\n}\n\nfunc main() {\n    ad := make([]int, 200)\n    for n := -99; n < 101; n++ {\n        ad[n+99] = int(D(float64(n)))\n    }\n    rcu.PrintTable(ad, 10, 4, false)\n    fmt.Println()\n    pow := 1.0\n    for m := 1; m < 21; m++ {\n        pow *= 10\n        fmt.Printf(\"D(10^%-2d) / 7 = %.0f\\n\", m, D(pow)/7)\n    }\n}\n"}
{"id": 58352, "name": "Permutations with some identical elements", "Python": "\n\nfrom itertools import permutations\n\nnumList = [2,3,1]\n\nbaseList = []\n\nfor i in numList:\n    for j in range(0,i):\n        baseList.append(i)\n\nstringDict = {'A':2,'B':3,'C':1}\n\nbaseString=\"\"\n\nfor i in stringDict:\n    for j in range(0,stringDict[i]):\n        baseString+=i\n\nprint(\"Permutations for \" + str(baseList) + \" : \")\n[print(i) for i in set(permutations(baseList))]\n\nprint(\"Permutations for \" + baseString + \" : \")\n[print(i) for i in set(permutations(baseString))]\n", "Go": "package main\n\nimport \"fmt\"\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 createSlice(nums []int, charSet string) []byte {\n    var chars []byte\n    for i := 0; i < len(nums); i++ {\n        for j := 0; j < nums[i]; j++ {\n            chars = append(chars, charSet[i])\n        }\n    }\n    return chars\n}\n\nfunc main() {\n    var res, res2, res3 []string\n    nums := []int{2, 1}\n    s := createSlice(nums, \"12\")\n    findPerms(s, 0, len(s), &res)\n    fmt.Println(res)\n    fmt.Println()\n\n    nums = []int{2, 3, 1}\n    s = createSlice(nums, \"123\")\n    findPerms(s, 0, len(s), &res2)\n    fmt.Println(res2)\n    fmt.Println()\n\n    s = createSlice(nums, \"ABC\")\n    findPerms(s, 0, len(s), &res3)\n    fmt.Println(res3)\n}\n"}
{"id": 58353, "name": "Penrose tiling", "Python": "def penrose(depth):\n    print(\t<g id=\"A{d+1}\" transform=\"translate(100, 0) scale(0.6180339887498949)\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n\t<g id=\"B{d+1}\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\t<g id=\"G\">\n\t\t<use href=\"\n\t\t<use href=\"\n\t</g>\n  </defs>\n  <g transform=\"scale(2, 2)\">\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n\t<use href=\"\n  </g>\n</svg>''')\n\npenrose(6)\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\ntype tiletype int\n\nconst (\n    kite tiletype = iota\n    dart\n)\n\ntype tile struct {\n    tt          tiletype\n    x, y        float64\n    angle, size float64\n}\n\nvar gr = (1 + math.Sqrt(5)) / 2 \n\nconst theta = math.Pi / 5 \n\nfunc setupPrototiles(w, h int) []tile {\n    var proto []tile\n    \n    for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {\n        ww := float64(w / 2)\n        hh := float64(h / 2)\n        proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})\n    }\n    return proto\n}\n\nfunc distinctTiles(tls []tile) []tile {\n    tileset := make(map[tile]bool)\n    for _, tl := range tls {\n        tileset[tl] = true\n    }\n    distinct := make([]tile, len(tileset))\n    for tl, _ := range tileset {\n        distinct = append(distinct, tl)\n    }\n    return distinct\n}\n\nfunc deflateTiles(tls []tile, gen int) []tile {\n    if gen <= 0 {\n        return tls\n    }\n    var next []tile\n    for _, tl := range tls {\n        x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr\n        var nx, ny float64\n        if tl.tt == dart {\n            next = append(next, tile{kite, x, y, a + 5*theta, size})\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                nx = x + math.Cos(a-4*theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-4*theta*sign)*gr*tl.size\n                next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})\n            }\n        } else {\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                next = append(next, tile{dart, x, y, a - 4*theta*sign, size})\n                nx = x + math.Cos(a-theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-theta*sign)*gr*tl.size\n                next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})\n            }\n        }\n    }\n    \n    tls = distinctTiles(next)\n    return deflateTiles(tls, gen-1)\n}\n\nfunc drawTiles(dc *gg.Context, tls []tile) {\n    dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}\n    for _, tl := range tls {\n        angle := tl.angle - theta\n        dc.MoveTo(tl.x, tl.y)\n        ord := tl.tt\n        for i := 0; i < 3; i++ {\n            x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)\n            y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)\n            dc.LineTo(x, y)\n            angle += theta\n        }\n        dc.ClosePath()\n        if ord == kite {\n            dc.SetHexColor(\"FFA500\") \n        } else {\n            dc.SetHexColor(\"FFFF00\") \n        }\n        dc.FillPreserve()\n        dc.SetHexColor(\"A9A9A9\") \n        dc.SetLineWidth(1)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    w, h := 700, 450\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    tiles := deflateTiles(setupPrototiles(w, h), 5)\n    drawTiles(dc, tiles)\n    dc.SavePNG(\"penrose_tiling.png\")\n}\n"}
{"id": 58354, "name": "Sphenic numbers", "Python": "\n\n\nfrom sympy import factorint\n\nsphenics1m, sphenic_triplets1m = [], []\n\nfor i in range(3, 1_000_000):\n    d = factorint(i)\n    if len(d) == 3 and sum(d.values()) == 3:\n        sphenics1m.append(i)\n        if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:\n            sphenic_triplets1m.append(i)\n\nprint('Sphenic numbers less than 1000:')\nfor i, n in enumerate(sphenics1m):\n    if n < 1000:\n        print(f'{n : 5}', end='\\n' if (i + 1) % 15 == 0 else '')\n    else:\n        break\n\nprint('\\n\\nSphenic triplets less than 10_000:')\nfor i, n in enumerate(sphenic_triplets1m):\n    if n < 10_000:\n        print(f'({n - 2} {n - 1} {n})', end='\\n' if (i + 1) % 3 == 0 else '  ')\n    else:\n        break\n\nprint('\\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),\n      'sphenic triplets less than 1 million.')\n\nS2HK = sphenics1m[200_000 - 1]\nT5K = sphenic_triplets1m[5000 - 1]\nprint(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')\nprint(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = 1000000\n    limit2 := int(math.Cbrt(limit)) \n    primes := rcu.Primes(limit / 6)\n    pc := len(primes)\n    var sphenic []int\n    fmt.Println(\"Sphenic numbers less than 1,000:\")\n    for i := 0; i < pc-2; i++ {\n        if primes[i] > limit2 {\n            break\n        }\n        for j := i + 1; j < pc-1; j++ {\n            prod := primes[i] * primes[j]\n            if prod+primes[j+1] >= limit {\n                break\n            }\n            for k := j + 1; k < pc; k++ {\n                res := prod * primes[k]\n                if res >= limit {\n                    break\n                }\n                sphenic = append(sphenic, res)\n            }\n        }\n    }\n    sort.Ints(sphenic)\n    ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })\n    rcu.PrintTable(sphenic[:ix], 15, 3, false)\n    fmt.Println(\"\\nSphenic triplets less than 10,000:\")\n    var triplets [][3]int\n    for i := 0; i < len(sphenic)-2; i++ {\n        s := sphenic[i]\n        if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {\n            triplets = append(triplets, [3]int{s, s + 1, s + 2})\n        }\n    }\n    ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })\n    for i := 0; i < ix; i++ {\n        fmt.Printf(\"%4d \", triplets[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThere are %s sphenic numbers less than 1,000,000.\\n\", rcu.Commatize(len(sphenic)))\n    fmt.Printf(\"There are %s sphenic triplets less than 1,000,000.\\n\", rcu.Commatize(len(triplets)))\n    s := sphenic[199999]\n    pf := rcu.PrimeFactors(s)\n    fmt.Printf(\"The 200,000th sphenic number is %s (%d*%d*%d).\\n\", rcu.Commatize(s), pf[0], pf[1], pf[2])\n    fmt.Printf(\"The 5,000th sphenic triplet is %v.\\n.\", triplets[4999])\n}\n"}
{"id": 58355, "name": "Tree from nesting levels", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n"}
{"id": 58356, "name": "Tree from nesting levels", "Python": "def to_tree(x, index=0, depth=1):\n   so_far = []\n   while index < len(x):\n       this = x[index]\n       if this == depth:\n           so_far.append(this)\n       elif this > depth:\n           index, deeper = to_tree(x, index, depth + 1)\n           so_far.append(deeper)\n       else: \n           index -=1\n           break\n       index += 1\n   return (index, so_far) if depth > 1 else so_far\n\n\nif __name__ ==  \"__main__\":\n    from pprint import pformat\n\n    def pnest(nest:list, width: int=9) -> str:\n        text = pformat(nest, width=width).replace('\\n', '\\n    ')\n        print(f\" OR {text}\\n\")\n\n    exercises = [\n        [],\n        [1, 2, 4],\n        [3, 1, 3, 1],\n        [1, 2, 3, 1],\n        [3, 2, 1, 3],\n        [3, 3, 3, 1, 1, 3, 3, 3],\n        ]\n    for flat in exercises:\n        nest = to_tree(flat)\n        print(f\"{flat} NESTS TO: {nest}\")\n        pnest(nest)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int) any {\n    s := []any{[]any{}}\n    for _, n := range list {\n        for n != len(s) {\n            if n > len(s) {\n                inner := []any{}\n                s[len(s)-1] = append(s[len(s)-1].([]any), inner)\n                s = append(s, inner)\n            } else {\n                s = s[0 : len(s)-1]\n            }\n        }\n        s[len(s)-1] = append(s[len(s)-1].([]any), n)\n        for i := len(s) - 2; i >= 0; i-- {\n            le := len(s[i].([]any))\n            s[i].([]any)[le-1] = s[i+1]\n        }\n    }\n    return s[0]\n}\n\nfunc main() {\n    tests := [][]int{\n        {},\n        {1, 2, 4},\n        {3, 1, 3, 1},\n        {1, 2, 3, 1},\n        {3, 2, 1, 3},\n        {3, 3, 3, 1, 1, 3, 3, 3},\n    }\n    for _, test := range tests {\n        nest := toTree(test)\n        fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n    }\n}\n"}
{"id": 58357, "name": "Find duplicate files", "Python": "from __future__ import print_function\nimport os\nimport hashlib\nimport datetime\n\ndef FindDuplicateFiles(pth, minSize = 0, hashName = \"md5\"):\n    knownFiles = {}\n\n    \n    for root, dirs, files in os.walk(pth):\n        for fina in files:\n            fullFina = os.path.join(root, fina)\n            isSymLink = os.path.islink(fullFina)\n            if isSymLink:\n                continue \n            si = os.path.getsize(fullFina)\n            if si < minSize:\n                continue\n            if si not in knownFiles:\n                knownFiles[si] = {}\n            h = hashlib.new(hashName)\n            h.update(open(fullFina, \"rb\").read())\n            hashed = h.digest()\n            if hashed in knownFiles[si]:\n                fileRec = knownFiles[si][hashed]\n                fileRec.append(fullFina)\n            else:\n                knownFiles[si][hashed] = [fullFina]\n\n    \n    sizeList = list(knownFiles.keys())\n    sizeList.sort(reverse=True)\n    for si in sizeList:\n        filesAtThisSize = knownFiles[si]\n        for hashVal in filesAtThisSize:\n            if len(filesAtThisSize[hashVal]) < 2:\n                continue\n            fullFinaLi = filesAtThisSize[hashVal]\n            print (\"=======Duplicate=======\")\n            for fullFina in fullFinaLi:\n                st = os.stat(fullFina)\n                isHardLink = st.st_nlink > 1 \n                infoStr = []\n                if isHardLink:\n                    infoStr.append(\"(Hard linked)\")\n                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')\n                print (fmtModTime, si, os.path.relpath(fullFina, pth), \" \".join(infoStr))\n\nif __name__==\"__main__\":\n\n    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"crypto/md5\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"path/filepath\"\n    \"sort\"\n    \"time\"\n)\n\ntype fileData struct {\n    filePath string\n    info     os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc checksum(filePath string) hash {\n    bytes, err := ioutil.ReadFile(filePath)\n    check(err)\n    return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n    var dups [][2]fileData\n    m := make(map[hash]fileData)\n    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        if !info.IsDir() && info.Size() >= minSize {\n            h := checksum(path)\n            fd, ok := m[h]\n            fd2 := fileData{path, info}\n            if !ok {\n                m[h] = fd2\n            } else {\n                dups = append(dups, [2]fileData{fd, fd2})\n            }\n        }\n        return nil\n    })\n    check(werr)\n    return dups\n}\n\nfunc main() {\n    dups := findDuplicates(\".\", 1)\n    fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n    fmt.Println(\"File name                 Size      Date last modified\")\n    fmt.Println(\"==========================================================\")\n    sort.Slice(dups, func(i, j int) bool {\n        return dups[i][0].info.Size() > dups[j][0].info.Size() \n    })\n    for _, dup := range dups {\n        for i := 0; i < 2; i++ {\n            d := dup[i]\n            fmt.Printf(\"%-20s  %8d    %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58358, "name": "Sylvester's sequence", "Python": "\n\nfrom functools import reduce\nfrom itertools import count, islice\n\n\n\ndef sylvester():\n    \n    def go(n):\n        return 1 + reduce(\n            lambda a, x: a * go(x),\n            range(0, n),\n            1\n        ) if 0 != n else 2\n\n    return map(go, count(0))\n\n\n\n\ndef main():\n    \n\n    print(\"First 10 terms of OEIS A000058:\")\n    xs = list(islice(sylvester(), 10))\n    print('\\n'.join([\n        str(x) for x in xs\n    ]))\n\n    print(\"\\nSum of the reciprocals of the first 10 terms:\")\n    print(\n        reduce(lambda a, x: a + 1 / x, xs, 0)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    two := big.NewInt(2)\n    next := new(big.Int)\n    sylvester := []*big.Int{two}\n    prod := new(big.Int).Set(two)\n    count := 1\n    for count < 10 {\n        next.Add(prod, one)\n        sylvester = append(sylvester, new(big.Int).Set(next))\n        count++\n        prod.Mul(prod, next)\n    }\n    fmt.Println(\"The first 10 terms in the Sylvester sequence are:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sylvester[i])\n    }\n\n    sumRecip := new(big.Rat)\n    for _, s := range sylvester {\n        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))\n    }\n    fmt.Println(\"\\nThe sum of their reciprocals as a rational number is:\")\n    fmt.Println(sumRecip)\n    fmt.Println(\"\\nThe sum of their reciprocals as a decimal number (to 211 places) is:\")\n    fmt.Println(sumRecip.FloatString(211))\n}\n"}
{"id": 58359, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 58360, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n"}
{"id": 58361, "name": "Order disjoint list items", "Python": "from __future__ import print_function\n\ndef order_disjoint_list_items(data, items):\n    \n    itemindices = []\n    for item in set(items):\n        itemcount = items.count(item)\n        \n        lastindex = [-1]\n        for i in range(itemcount):\n            lastindex.append(data.index(item, lastindex[-1] + 1))\n        itemindices += lastindex[1:]\n    itemindices.sort()\n    for index, item in zip(itemindices, items):\n        data[index] = item\n\nif __name__ == '__main__':\n    tostring = ' '.join\n    for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),\n                         (str.split('the cat sat on the mat'), str.split('cat mat')),\n                         (list('ABCABCABC'), list('CACA')),\n                         (list('ABCABDABE'), list('EADA')),\n                         (list('AB'), list('B')),\n                         (list('AB'), list('BA')),\n                         (list('ABBA'), list('BA')),\n                         (list(''), list('')),\n                         (list('A'), list('A')),\n                         (list('AB'), list('')),\n                         (list('ABBA'), list('AB')),\n                         (list('ABAB'), list('AB')),\n                         (list('ABAB'), list('BABA')),\n                         (list('ABCCBA'), list('ACAC')),\n                         (list('ABCCBA'), list('CACA')),\n                       ]:\n        print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')\n        order_disjoint_list_items(data, items)\n        print(\"-> M' %r\" % tostring(data))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype indexSort struct {\n\tval sort.Interface\n\tind []int\n}\n\nfunc (s indexSort) Len() int           { return len(s.ind) }\nfunc (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }\nfunc (s indexSort) Swap(i, j int) {\n\ts.val.Swap(s.ind[i], s.ind[j])\n\ts.ind[i], s.ind[j] = s.ind[j], s.ind[i]\n}\n\nfunc disjointSliceSort(m, n []string) []string {\n\ts := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}\n\tused := make(map[int]bool)\n\tfor _, nw := range n {\n\t\tfor i, mw := range m {\n\t\t\tif used[i] || mw != nw {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tused[i] = true\n\t\t\ts.ind = append(s.ind, i)\n\t\t\tbreak\n\t\t}\n\t}\n\tsort.Sort(s)\n\treturn s.val.(sort.StringSlice)\n}\n\nfunc disjointStringSort(m, n string) string {\n\treturn strings.Join(\n\t\tdisjointSliceSort(strings.Fields(m), strings.Fields(n)), \" \")\n}\n\nfunc main() {\n\tfor _, data := range []struct{ m, n string }{\n\t\t{\"the cat sat on the mat\", \"mat cat\"},\n\t\t{\"the cat sat on the mat\", \"cat mat\"},\n\t\t{\"A B C A B C A B C\", \"C A C A\"},\n\t\t{\"A B C A B D A B E\", \"E A D A\"},\n\t\t{\"A B\", \"B\"},\n\t\t{\"A B\", \"B A\"},\n\t\t{\"A B B A\", \"B A\"},\n\t} {\n\t\tmp := disjointStringSort(data.m, data.n)\n\t\tfmt.Printf(\"%s → %s » %s\\n\", data.m, data.n, mp)\n\t}\n\n}\n"}
{"id": 58362, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n"}
{"id": 58363, "name": "Achilles numbers", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n"}
{"id": 58364, "name": "Achilles numbers", "Python": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n    p = factorint(n).values()\n    return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n    return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n    \n    print('First', nachilles, 'Achilles numbers:')\n    n, found = 0, 0\n    while found < nachilles:\n        if is_Achilles(n):\n            found += 1\n            print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n    n, found = 0, 0\n    while found < nstrongachilles:\n        if is_strong_Achilles(n):\n            found += 1\n            print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n        n += 1\n\n    \n    print('\\nCount of Achilles numbers for various intervals:')\n    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n    for interval in intervals:\n        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc totient(n int) int {\n    tot := n\n    i := 2\n    for i*i <= n {\n        if n%i == 0 {\n            for n%i == 0 {\n                n /= i\n            }\n            tot -= tot / i\n        }\n        if i == 2 {\n            i = 1\n        }\n        i += 2\n    }\n    if n > 1 {\n        tot -= tot / n\n    }\n    return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n    upper := math.Pow(10, float64(maxExp))\n    for i := 2; i <= int(math.Sqrt(upper)); i++ {\n        fi := float64(i)\n        p := fi\n        for {\n            p *= fi\n            if p >= upper {\n                break\n            }\n            pps[int(p)] = true\n        }\n    }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n    lower := math.Pow(10, float64(minExp))\n    upper := math.Pow(10, float64(maxExp))\n    achilles := make(map[int]bool)\n    for b := 1; b <= int(math.Cbrt(upper)); b++ {\n        b3 := b * b * b\n        for a := 1; a <= int(math.Sqrt(upper)); a++ {\n            p := b3 * a * a\n            if p >= int(upper) {\n                break\n            }\n            if p >= int(lower) {\n                if _, ok := pps[p]; !ok {\n                    achilles[p] = true\n                }\n            }\n        }\n    }\n    return achilles\n}\n\nfunc main() {\n    maxDigits := 15\n    getPerfectPowers(maxDigits)\n    achillesSet := getAchilles(1, 5) \n    achilles := make([]int, len(achillesSet))\n    i := 0\n    for k := range achillesSet {\n        achilles[i] = k\n        i++\n    }\n    sort.Ints(achilles)\n\n    fmt.Println(\"First 50 Achilles numbers:\")\n    for i = 0; i < 50; i++ {\n        fmt.Printf(\"%4d \", achilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n    var strongAchilles []int\n    count := 0\n    for n := 0; count < 30; n++ {\n        tot := totient(achilles[n])\n        if _, ok := achillesSet[tot]; ok {\n            strongAchilles = append(strongAchilles, achilles[n])\n            count++\n        }\n    }\n    for i = 0; i < 30; i++ {\n        fmt.Printf(\"%5d \", strongAchilles[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nNumber of Achilles numbers with:\")\n    for d := 2; d <= maxDigits; d++ {\n        ac := len(getAchilles(d-1, d))\n        fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n    }\n}\n"}
{"id": 58365, "name": "Odd squarefree semiprimes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n"}
{"id": 58366, "name": "Odd squarefree semiprimes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(333)\n    var oss []int\n    for i := 1; i < len(primes)-1; i++ {\n        for j := i + 1; j < len(primes); j++ {\n            n := primes[i] * primes[j]\n            if n >= 1000 {\n                break\n            }\n            oss = append(oss, n)\n        }\n    }\n    sort.Ints(oss)\n    fmt.Println(\"Odd squarefree semiprimes under 1,000:\")\n    for i, n := range oss {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", len(oss))\n}\n"}
{"id": 58367, "name": "Sierpinski curve", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 58368, "name": "Sierpinski curve", "Python": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import hsv_to_rgb as hsv\n\ndef curve(axiom, rules, angle, depth):\n    for _ in range(depth):\n        axiom = ''.join(rules[c] if c in rules else c for c in axiom)\n\n    a, x, y = 0, [0], [0]\n    for c in axiom:\n        match c:\n            case '+':\n                a += 1\n            case '-':\n                a -= 1\n            case 'F' | 'G':\n                x.append(x[-1] + np.cos(a*angle*np.pi/180))\n                y.append(y[-1] + np.sin(a*angle*np.pi/180))\n\n    l = len(x)\n    \n    for i in range(l - 1):\n        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))\n    plt.gca().set_aspect(1)\n    plt.show()\n\ncurve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)\n\n\n\n\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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n"}
{"id": 58369, "name": "Most frequent k chars distance", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n"}
{"id": 58370, "name": "Most frequent k chars distance", "Python": "import collections\ndef MostFreqKHashing(inputString, K):\n    occuDict = collections.defaultdict(int)\n    for c in inputString:\n        occuDict[c] += 1\n    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)\n    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])\n    return outputStr \n\n\ndef MostFreqKSimilarity(inputStr1, inputStr2):\n    similarity = 0\n    for i in range(0, len(inputStr1), 2):\n        c = inputStr1[i]\n        cnt1 = int(inputStr1[i + 1])\n        for j in range(0, len(inputStr2), 2):\n            if inputStr2[j] == c:\n                cnt2 = int(inputStr2[j + 1])\n                similarity += cnt1 + cnt2\n                break\n    return similarity\n\ndef MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):\n    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n"}
{"id": 58371, "name": "Palindromic primes", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n"}
{"id": 58372, "name": "Palindromic primes", "Python": "\n\nfrom itertools import takewhile\n\n\n\ndef palindromicPrimes():\n    \n    def p(n):\n        s = str(n)\n        return s == s[::-1]\n    return (n for n in primes() if p(n))\n\n\n\ndef main():\n    \n    print('\\n'.join(\n        str(x) for x in takewhile(\n            lambda n: 1000 > n,\n            palindromicPrimes()\n        )\n    ))\n\n\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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    primes := rcu.Primes(99999)\n    var pals []int\n    for _, p := range primes {\n        if p == reversed(p) {\n            pals = append(pals, p)\n        }\n    }\n    fmt.Println(\"Palindromic primes under 1,000:\")\n    var smallPals, bigPals []int\n    for _, p := range pals {\n        if p < 1000 {\n            smallPals = append(smallPals, p)\n        } else {\n            bigPals = append(bigPals, p)\n        }\n    }\n    rcu.PrintTable(smallPals, 10, 3, false)\n    fmt.Println()\n    fmt.Println(len(smallPals), \"such primes found.\")\n\n    fmt.Println(\"\\nAdditional palindromic primes under 100,000:\")\n    rcu.PrintTable(bigPals, 10, 6, true)\n    fmt.Println()\n    fmt.Println(len(bigPals), \"such primes found,\", len(pals), \"in all.\")\n}\n"}
{"id": 58373, "name": "Find words which contains all the vowels", "Python": "import urllib.request\nfrom collections import Counter\n\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>10:\n        frequency = Counter(word.lower())\n        if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:\n            print(word)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Words which contain all 5 vowels once in\", wordList, \"\\b:\\n\")\n    for _, word := range words {\n        ca, ce, ci, co, cu := 0, 0, 0, 0, 0\n        for _, r := range word {\n            switch r {\n            case 'a':\n                ca++\n            case 'e':\n                ce++\n            case 'i':\n                ci++\n            case 'o':\n                co++\n            case 'u':\n                cu++\n            }\n        }\n        if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {\n            count++\n            fmt.Printf(\"%2d: %s\\n\", count, word)\n        }\n    }\n}\n"}
{"id": 58374, "name": "Tropical algebra overloading", "Python": "from numpy import Inf\n\nclass MaxTropical:\n    \n    def __init__(self, x=0):\n        self.x = x\n\n    def __str__(self):\n        return str(self.x)\n\n    def __add__(self, other):\n        return MaxTropical(max(self.x, other.x))\n\n    def __mul__(self, other):\n        return MaxTropical(self.x + other.x)\n\n    def __pow__(self, other):\n        assert other.x // 1 == other.x and other.x > 0, \"Invalid Operation\" \n        return MaxTropical(self.x * other.x)\n\n    def __eq__(self, other):\n        return self.x == other.x\n\n\nif __name__ == \"__main__\":\n    a = MaxTropical(-2)\n    b = MaxTropical(-1)\n    c = MaxTropical(-0.5)\n    d = MaxTropical(-0.001)\n    e = MaxTropical(0)\n    f = MaxTropical(0.5)\n    g = MaxTropical(1)\n    h = MaxTropical(1.5)\n    i = MaxTropical(2)\n    j = MaxTropical(5)\n    k = MaxTropical(7)\n    l = MaxTropical(8)\n    m = MaxTropical(-Inf)\n\n    print(\"2 * -2 == \", i * a)\n    print(\"-0.001 + -Inf == \", d + m)\n    print(\"0 * -Inf == \", e * m)\n    print(\"1.5 + -1 == \", h + b)\n    print(\"-0.5 * 0 == \", c * e)\n    print(\"5**7 == \", j**k)\n    print(\"5 * (8 + 7)) == \", j * (l + k))\n    print(\"5 * 8 + 5 * 7 == \", j * l + j * k)\n    print(\"5 * (8 + 7) == 5 * 8 + 5 * 7\", j * (l + k) == j * l + j * k)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar MinusInf = math.Inf(-1)\n\ntype MaxTropical struct{ r float64 }\n\nfunc newMaxTropical(r float64) MaxTropical {\n    if math.IsInf(r, 1) || math.IsNaN(r) {\n        log.Fatal(\"Argument must be a real number or negative infinity.\")\n    }\n    return MaxTropical{r}\n}\n\nfunc (t MaxTropical) eq(other MaxTropical) bool {\n    return t.r == other.r\n}\n\n\nfunc (t MaxTropical) add(other MaxTropical) MaxTropical {\n    if t.r == MinusInf {\n        return other\n    }\n    if other.r == MinusInf {\n        return t\n    }\n    return newMaxTropical(math.Max(t.r, other.r))\n}\n\n\nfunc (t MaxTropical) mul(other MaxTropical) MaxTropical {\n    if t.r == 0 {\n        return other\n    }\n    if other.r == 0 {\n        return t\n    }\n    return newMaxTropical(t.r + other.r)\n}\n\n\nfunc (t MaxTropical) pow(e int) MaxTropical {\n    if e < 1 {\n        log.Fatal(\"Exponent must be a positive integer.\")\n    }\n    if e == 1 {\n        return t\n    }\n    p := t\n    for i := 2; i <= e; i++ {\n        p = p.mul(t)\n    }\n    return p\n}\n\nfunc (t MaxTropical) String() string {\n    return fmt.Sprintf(\"%g\", t.r)\n}\n\nfunc main() {\n    \n    data := [][]float64{\n        {2, -2, 1},\n        {-0.001, MinusInf, 0},\n        {0, MinusInf, 1},\n        {1.5, -1, 0},\n        {-0.5, 0, 1},\n    }\n    for _, d := range data {\n        a := newMaxTropical(d[0])\n        b := newMaxTropical(d[1])\n        if d[2] == 0 {\n            fmt.Printf(\"%s ⊕ %s = %s\\n\", a, b, a.add(b))\n        } else {\n            fmt.Printf(\"%s ⊗ %s = %s\\n\", a, b, a.mul(b))\n        }\n    }\n\n    c := newMaxTropical(5)\n    fmt.Printf(\"%s ^ 7 = %s\\n\", c, c.pow(7))\n\n    d := newMaxTropical(8)\n    e := newMaxTropical(7)\n    f := c.mul(d.add(e))\n    g := c.mul(d).add(c.mul(e))\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) = %s\\n\", c, d, e, f)\n    fmt.Printf(\"%s ⊗ %s ⊕ %s ⊗ %s = %s\\n\", c, d, c, e, g)\n    fmt.Printf(\"%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\\n\", c, d, e, c, d, c, e, f.eq(g))\n}\n"}
{"id": 58375, "name": "Pig the dice game_Player", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 58376, "name": "Pig the dice game_Player", "Python": "\n\n\n\nfrom random import randint\nfrom collections import namedtuple\nimport random\nfrom pprint import pprint as pp\nfrom collections import Counter\n\n\nplayercount = 2\nmaxscore = 100\nmaxgames = 100000\n\n\nGame = namedtuple('Game', 'players, maxscore, rounds')\nRound = namedtuple('Round', 'who, start, scores, safe')\n\n\nclass Player():\n    def __init__(self, player_index):\n        self.player_index = player_index\n\n    def __repr__(self):\n        return '%s(%i)' % (self.__class__.__name__, self.player_index)\n\n    def __call__(self, safescore, scores, game):\n        'Returns boolean True to roll again'\n        pass\n\nclass RandPlay(Player):\n    def __call__(self, safe, scores, game):\n        'Returns random boolean choice of whether to roll again'\n        return bool(random.randint(0, 1))\n\nclass RollTo20(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and(sum(scores) < 20))                                  \n\nclass Desparat(Player):\n    def __call__(self, safe, scores, game):\n        'Roll again if this rounds score < 20 or someone is within 20 of winning'\n        return (((sum(scores) + safe[self.player_index]) < maxscore)    \n                and( (sum(scores) < 20)                                 \n                     or max(safe) >= (maxscore - 20)))                  \n\n\ndef game__str__(self):\n    'Pretty printer for Game class'\n    return (\"Game(players=%r, maxscore=%i,\\n  rounds=[\\n    %s\\n  ])\"\n            % (self.players, self.maxscore,\n               ',\\n    '.join(repr(round) for round in self.rounds)))\nGame.__str__ = game__str__\n\n\ndef winningorder(players, safescores):\n    'Return (players in winning order, their scores)'\n    return tuple(zip(*sorted(zip(players, safescores),\n                            key=lambda x: x[1], reverse=True)))\n\ndef playpig(game):\n    \n    players, maxscore, rounds = game\n    playercount = len(players)\n    safescore = [0] * playercount   \n    player = 0                      \n    scores=[]                       \n\n    while max(safescore) < maxscore:\n        startscore = safescore[player]\n        rolling = players[player](safescore, scores, game)\n        if rolling:\n            rolled = randint(1, 6)\n            scores.append(rolled)\n            if rolled == 1:\n                \n                round = Round(who=players[player],\n                              start=startscore,\n                              scores=scores,\n                              safe=safescore[player])\n                rounds.append(round)\n                scores, player = [], (player + 1) % playercount\n        else:\n            \n            safescore[player] += sum(scores)\n            round = Round(who=players[player],\n                          start=startscore,\n                          scores=scores,\n                          safe=safescore[player])\n            rounds.append(round)\n            if safescore[player] >= maxscore:\n                break\n            scores, player = [], (player + 1) % playercount\n\n    \n    return winningorder(players, safescore)\n\nif __name__ == '__main__':\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=20,\n                rounds=[])\n    print('ONE GAME')\n    print('Winning order: %r; Respective scores: %r\\n' % playpig(game))\n    print(game)\n    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),\n                maxscore=maxscore,\n                rounds=[])\n    algos = (RollTo20, RandPlay, Desparat)\n    print('\\n\\nMULTIPLE STATISTICS using %r\\n  for %i GAMES'\n          % (', '.join(p.__name__ for p in algos), maxgames,))\n    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)\n                                                               for i in range(playercount)),\n                                                 rounds=[]))[0])\n                      for i in range(maxgames))\n    print('  Players(position) winning on left; occurrences on right:\\n    %s'\n          % ',\\n    '.join(str(w) for w in winners.most_common()))\n", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n"}
{"id": 58377, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 58378, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 58379, "name": "Lychrel numbers", "Python": "from __future__ import print_function\n\ndef add_reverse(num, max_iter=1000):\n    i, nums = 0, {num}\n    while True:\n        i, num = i+1, num + reverse_int(num)\n        nums.add(num)\n        if reverse_int(num) == num or i >= max_iter:\n            break\n    return nums\n    \n\ndef reverse_int(num):\n    return int(str(num)[::-1])\n\ndef split_roots_from_relateds(roots_and_relateds):\n    roots = roots_and_relateds[::]\n    i = 1\n    while i < len(roots):\n        this = roots[i]\n        if any(this.intersection(prev) for prev in roots[:i]):\n            del roots[i]\n        else:\n            i += 1\n    root = [min(each_set) for each_set in roots]\n    related = [min(each_set) for each_set in roots_and_relateds]\n    related = [n for n in related if n not in root]\n    return root, related\n\ndef find_lychrel(maxn, max_reversions):\n    'Lychrel number generator'\n    series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]\n    roots_and_relateds = [s for s in series if len(s) > max_reversions]\n    return split_roots_from_relateds(roots_and_relateds)\n\n\nif __name__ == '__main__':\n    maxn, reversion_limit = 10000, 500\n    print(\"Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds\"\n          % (maxn, reversion_limit))\n    lychrel, l_related = find_lychrel(maxn, reversion_limit)\n    print('  Number of Lychrel numbers:', len(lychrel))\n    print('    Lychrel numbers:', ', '.join(str(n) for n in lychrel))\n    print('  Number of Lychrel related:', len(l_related))\n    \n    pals = [x for x in lychrel + l_related  if x == reverse_int(x)]\n    print('  Number of Lychrel palindromes:', len(pals))\n    print('    Lychrel palindromes:', ', '.join(str(n) for n in pals))\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n"}
{"id": 58380, "name": "Base 16 numbers needing a to f", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n"}
{"id": 58381, "name": "Base 16 numbers needing a to f", "Python": "\n\n\n\ndef p(n):\n    \n    return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in range(1, 1 + 500)\n        if p(n)\n    ]\n    print(f'{len(xs)} matches for the predicate:\\n')\n    print(\n        table(6)(xs)\n    )\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef table(n):\n    \n    def go(xs):\n        w = len(xs[-1])\n        return '\\n'.join(\n            ' '.join(row) for row in chunksOf(n)([\n                s.rjust(w, ' ') for s in xs\n            ])\n        )\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    const nondecimal = \"abcdef\"\n    c := 0\n    for i := int64(0); i <= 500; i++ {\n        hex := strconv.FormatInt(i, 16)\n        if strings.ContainsAny(nondecimal, hex) {\n            fmt.Printf(\"%3d \", i)\n            c++\n            if c%15 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", c)\n}\n"}
{"id": 58382, "name": "Range modifications", "Python": "class Sequence():\n    \n    def __init__(self, sequence_string):\n        self.ranges = self.to_ranges(sequence_string)\n        assert self.ranges == sorted(self.ranges), \"Sequence order error\"\n        \n    def to_ranges(self, txt):\n        return [[int(x) for x in r.strip().split('-')]\n                for r in txt.strip().split(',') if r]\n    \n    def remove(self, rem):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= rem <= r[1]:\n                if r[0] == rem:     \n                    if r[1] > rem:\n                        r[0] += 1\n                    else:\n                        del ranges[i]\n                elif r[1] == rem:   \n                    if r[0] < rem:\n                        r[1] -= 1\n                    else:\n                        del ranges[i]\n                else:               \n                    r[1], splitrange = rem - 1, [rem + 1, r[1]]\n                    ranges.insert(i + 1, splitrange)\n                break\n            if r[0] > rem:  \n                break\n        return self\n            \n    def add(self, add):\n        ranges = self.ranges\n        for i, r in enumerate(ranges):\n            if r[0] <= add <= r[1]:     \n                break\n            elif r[0] - 1 == add:      \n                r[0] = add\n                break\n            elif r[1] + 1 == add:      \n                r[1] = add\n                break\n            elif r[0] > add:      \n                ranges.insert(i, [add, add])\n                break\n        else:\n            ranges.append([add, add])\n            return self\n        return self.consolidate()\n    \n    def consolidate(self):\n        \"Combine overlapping ranges\"\n        ranges = self.ranges\n        for this, that in zip(ranges, ranges[1:]):\n            if this[1] + 1 >= that[0]:  \n                if this[1] >= that[1]:  \n                    this[:], that[:] = [], this\n                else:   \n                    this[:], that[:] = [], [this[0], that[1]]\n        ranges[:] = [r for r in ranges if r]\n        return self\n    def __repr__(self):\n        rr = self.ranges\n        return \",\".join(f\"{r[0]}-{r[1]}\" for r in rr)\n\ndef demo(opp_txt):\n    by_line = opp_txt.strip().split('\\n')\n    start = by_line.pop(0)\n    ex = Sequence(start.strip().split()[-1][1:-1])    \n    lines = [line.strip().split() for line in by_line]\n    opps = [((ex.add if word[0] == \"add\" else ex.remove), int(word[1]))\n            for word in lines]\n    print(f\"Start: \\\"{ex}\\\"\")\n    for op, val in opps:\n        print(f\"    {op.__name__:>6} {val:2} => {op(val)}\")\n    print()\n                    \nif __name__ == '__main__':\n    demo()\n    demo()\n    demo()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype rng struct{ from, to int }\n\ntype fn func(rngs *[]rng, n int)\n\nfunc (r rng) String() string { return fmt.Sprintf(\"%d-%d\", r.from, r.to) }\n\nfunc rangesAdd(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        rngs = append(rngs, rng{n, n})\n        return rngs\n    }\n    for i, r := range rngs {\n        if n < r.from-1 {\n            rngs = append(rngs, rng{})\n            copy(rngs[i+1:], rngs[i:])\n            rngs[i] = rng{n, n}\n            return rngs\n        } else if n == r.from-1 {\n            rngs[i] = rng{n, r.to}\n            return rngs\n        } else if n <= r.to {\n            return rngs\n        } else if n == r.to+1 {\n            rngs[i] = rng{r.from, n}\n            if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) {\n                rngs[i] = rng{r.from, rngs[i+1].to}\n                copy(rngs[i+1:], rngs[i+2:])\n                rngs[len(rngs)-1] = rng{}\n                rngs = rngs[:len(rngs)-1]\n            }\n            return rngs\n        } else if i == len(rngs)-1 {\n            rngs = append(rngs, rng{n, n})\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc rangesRemove(rngs []rng, n int) []rng {\n    if len(rngs) == 0 {\n        return rngs\n    }\n    for i, r := range rngs {\n        if n <= r.from-1 {\n            return rngs\n        } else if n == r.from && n == r.to {\n            copy(rngs[i:], rngs[i+1:])\n            rngs[len(rngs)-1] = rng{}\n            rngs = rngs[:len(rngs)-1]\n            return rngs\n        } else if n == r.from {\n            rngs[i] = rng{n + 1, r.to}\n            return rngs\n        } else if n < r.to {\n            rngs[i] = rng{r.from, n - 1}\n            rngs = append(rngs, rng{})\n            copy(rngs[i+2:], rngs[i+1:])\n            rngs[i+1] = rng{n + 1, r.to}\n            return rngs\n        } else if n == r.to {\n            rngs[i] = rng{r.from, n - 1}\n            return rngs\n        }\n    }\n    return rngs\n}\n\nfunc standard(rngs []rng) string {\n    if len(rngs) == 0 {\n        return \"\"\n    }\n    var sb strings.Builder\n    for _, r := range rngs {\n        sb.WriteString(fmt.Sprintf(\"%s,\", r))\n    }\n    s := sb.String()\n    return s[:len(s)-1]\n}\n\nfunc main() {\n    const add = 0\n    const remove = 1\n    fns := []fn{\n        func(prngs *[]rng, n int) {\n            *prngs = rangesAdd(*prngs, n)\n            fmt.Printf(\"       add %2d => %s\\n\", n, standard(*prngs))\n        },\n        func(prngs *[]rng, n int) {\n            *prngs = rangesRemove(*prngs, n)\n            fmt.Printf(\"    remove %2d => %s\\n\", n, standard(*prngs))\n        },\n    }\n\n    var rngs []rng\n    ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}}\n    fmt.Printf(\"Start: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 3}, {5, 5}}\n    ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n\n    rngs = []rng{{1, 5}, {10, 25}, {27, 30}}\n    ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}}\n    fmt.Printf(\"\\nStart: %q\\n\", standard(rngs))\n    for _, op := range ops {\n        fns[op[0]](&rngs, op[1])\n    }\n}\n"}
{"id": 58383, "name": "Juggler sequence", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n"}
{"id": 58384, "name": "Juggler sequence", "Python": "from math import isqrt\n\ndef juggler(k, countdig=True, maxiters=1000):\n    m, maxj, maxjpos = k, k, 0\n    for i in range(1, maxiters):\n        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)\n        if m >= maxj:\n            maxj, maxjpos  = m, i\n        if m == 1:\n            print(f\"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}\")\n            return i\n\n    print(\"ERROR: Juggler series starting with $k did not converge in $maxiters iterations\")\n\n\nprint(\"       n    l(n)  i(n)       h(n) or d(n)\\n-------------------------------------------\")\nfor k in range(20, 40):\n    juggler(k, False)\n\nfor k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:\n    juggler(k)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\n\nfunc juggler(n int64) (int, int, *big.Int, int) {\n    if n < 1 {\n        log.Fatal(\"Starting value must be a positive integer.\")\n    }\n    count := 0\n    maxCount := 0\n    a := big.NewInt(n)\n    max := big.NewInt(n)\n    tmp := new(big.Int)\n    for a.Cmp(one) != 0 {\n        if tmp.Rem(a, two).Cmp(zero) == 0 {\n            a.Sqrt(a)\n        } else {\n            tmp.Mul(a, a)\n            tmp.Mul(tmp, a)\n            a.Sqrt(tmp)\n        }\n        count++\n        if a.Cmp(max) > 0 {\n            max.Set(a)\n            maxCount = count\n        }\n    }\n    return count, maxCount, max, len(max.String())\n}\n\nfunc main() {\n    fmt.Println(\"n    l[n]  i[n]  h[n]\")\n    fmt.Println(\"-----------------------------------\")\n    for n := int64(20); n < 40; n++ {\n        count, maxCount, max, _ := juggler(n)\n        cmax := rcu.Commatize(int(max.Int64()))\n        fmt.Printf(\"%2d    %2d   %2d    %s\\n\", n, count, maxCount, cmax)\n    }\n    fmt.Println()\n    nums := []int64{\n        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,\n        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,\n    }\n    fmt.Println(\"       n      l[n]   i[n]   d[n]\")\n    fmt.Println(\"-------------------------------------\")\n    for _, n := range nums {\n        count, maxCount, _, digits := juggler(n)\n        cn := rcu.Commatize(int(n))\n        fmt.Printf(\"%11s   %3d    %3d    %s\\n\", cn, count, maxCount, rcu.Commatize(digits))\n    }\n}\n"}
{"id": 58385, "name": "Sierpinski square curve", "Python": "import matplotlib.pyplot as plt\nimport math\n\n\ndef nextPoint(x, y, angle):\n    a = math.pi * angle / 180\n    x2 = (int)(round(x + (1 * math.cos(a))))\n    y2 = (int)(round(y + (1 * math.sin(a))))\n    return x2, y2\n\n\ndef expand(axiom, rules, level):\n    for l in range(0, level):\n        a2 = \"\"\n        for c in axiom:\n            if c in rules:\n                a2 += rules[c]\n            else:\n                a2 += c\n        axiom = a2\n    return axiom\n\n\ndef draw_lsystem(axiom, rules, angle, iterations):\n    xp = [1]\n    yp = [1]\n    direction = 0\n    for c in expand(axiom, rules, iterations):\n        if c == \"F\":\n            xn, yn = nextPoint(xp[-1], yp[-1], direction)\n            xp.append(xn)\n            yp.append(yn)\n        elif c == \"-\":\n            direction = direction - angle\n            if direction < 0:\n                direction = 360 + direction\n        elif c == \"+\":\n            direction = (direction + angle) % 360\n\n    plt.plot(xp, yp)\n    plt.show()\n\n\nif __name__ == '__main__':\n    \n    s_axiom = \"F+XF+F+XF\"\n    s_rules = {\"X\": \"XF-F+F-XF+F+XF-F+F-X\"}\n    s_angle = 90\n\n    draw_lsystem(s_axiom, s_rules, s_angle, 3)\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n"}
{"id": 58386, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n"}
{"id": 58387, "name": "Powerful numbers", "Python": "from primesieve import primes \nimport math\n\ndef primepowers(k, upper_bound):\n    ub = int(math.pow(upper_bound, 1/k) + .5)\n    res = [(1,)]\n\n    for p in primes(ub):\n        a = [p**k]\n        u = upper_bound // a[-1]\n        while u >= p:\n            a.append(a[-1]*p)\n            u //= p\n        res.append(tuple(a))\n\n    return res\n\ndef kpowerful(k, upper_bound, count_only=True):\n    ps = primepowers(k, upper_bound)\n\n    def accu(i, ub):\n        c = 0 if count_only else [] \n        for p in ps[i]:\n            u = ub//p\n            if not u: break\n\n            c += 1 if count_only else [p]\n\n            for j in range(i + 1, len(ps)):\n                if u < ps[j][0]:\n                    break\n                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]\n        return c\n\n    res = accu(0, upper_bound)\n    return res if count_only else sorted(res)\n\nfor k in range(2, 11):\n    res = kpowerful(k, 10**k, count_only=False)\n    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',\n        ' '.join(str(x) for x in res[:5]),\n        '...',\n        ' '.join(str(x) for x in res[-5:])\n        )\n\nfor k in range(2, 11):\n    res = [kpowerful(k, 10**n) for n in range(k+10)]\n    print(f'{k}-powerful up to 10^{k+10}:',\n        ' '.join(str(x) for x in res))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n"}
{"id": 58388, "name": "Fixed length records", "Python": "infile = open('infile.dat', 'rb')\noutfile = open('outfile.dat', 'wb')\n\nwhile True:\n    onerecord = infile.read(80)\n    if len(onerecord) < 80:\n        break\n    onerecordreversed = bytes(reversed(onerecord))\n    outfile.write(onerecordreversed)\n\ninfile.close()\noutfile.close()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc reverseBytes(bytes []byte) {\n    for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {\n        bytes[i], bytes[j] = bytes[j], bytes[i]\n    }\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    in, err := os.Open(\"infile.dat\")\n    check(err)\n    defer in.Close()\n\n    out, err := os.Create(\"outfile.dat\")\n    check(err)\n\n    record := make([]byte, 80)\n    empty := make([]byte, 80)\n    for {\n        n, err := in.Read(record)\n        if err != nil {\n            if n == 0 {\n                break \n            } else {\n                out.Close()\n                log.Fatal(err)\n            }\n        }\n        reverseBytes(record)\n        out.Write(record)\n        copy(record, empty)\n    }\n    out.Close()\n\n    \n    \n    cmd := exec.Command(\"dd\", \"if=outfile.dat\", \"cbs=80\", \"conv=unblock\")\n    bytes, err := cmd.Output()\n    check(err)\n    fmt.Println(string(bytes))\n}\n"}
{"id": 58389, "name": "Find words whose first and last three letters are equal", "Python": "import urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\nfor word in wordList:\n    if len(word)>5 and word[:3].lower()==word[-3:].lower():\n        print(word)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    count := 0\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {\n            count++\n            fmt.Printf(\"%d: %s\\n\", count, s)\n        }\n    }\n}\n"}
{"id": 58390, "name": "Giuga numbers", "Python": "\n\nfrom math import sqrt\n\ndef isGiuga(m):\n    n = m\n    f = 2\n    l = sqrt(n)\n    while True:\n        if n % f == 0:\n            if ((m / f) - 1) % f != 0:\n                return False\n            n /= f\n            if f > n:\n                return True\n        else:\n            f += 1\n            if f > l:\n                return False\n\n\nif __name__ == '__main__':\n    n = 3\n    c = 0\n    print(\"The first 4 Giuga numbers are: \")\n    while c < 4:\n        if isGiuga(n):\n            c += 1\n            print(n)\n        n += 1\n", "Go": "package main\n\nimport \"fmt\"\n\nvar factors []int\nvar inc = []int{4, 2, 4, 2, 4, 6, 2, 6}\n\n\n\nfunc primeFactors(n int) {\n    factors = factors[:0]\n    factors = append(factors, 2)\n    last := 2\n    n /= 2\n    for n%3 == 0 {\n        if last == 3 {\n            factors = factors[:0]\n            return\n        }\n        last = 3\n        factors = append(factors, 3)\n        n /= 3\n    }\n    for n%5 == 0 {\n        if last == 5 {\n            factors = factors[:0]\n            return\n        }\n        last = 5\n        factors = append(factors, 5)\n        n /= 5\n    }\n    for k, i := 7, 0; k*k <= n; {\n        if n%k == 0 {\n            if last == k {\n                factors = factors[:0]\n                return\n            }\n            last = k\n            factors = append(factors, k)\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        factors = append(factors, n)\n    }\n}\n\nfunc main() {\n    const limit = 5\n    var giuga []int\n    \n    for n := 6; len(giuga) < limit; n += 4 {\n        primeFactors(n)\n        \n        if len(factors) > 2 {\n            isGiuga := true\n            for _, f := range factors {\n                if (n/f-1)%f != 0 {\n                    isGiuga = false\n                    break\n                }\n            }\n            if isGiuga {\n                giuga = append(giuga, n)\n            }\n        }\n    }\n    fmt.Println(\"The first\", limit, \"Giuga numbers are:\")\n    fmt.Println(giuga)\n}\n"}
{"id": 58391, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 58392, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n"}
{"id": 58393, "name": "Odd words", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n"}
{"id": 58394, "name": "Odd words", "Python": "\n\nimport urllib.request\nurllib.request.urlretrieve(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"unixdict.txt\")\n\ndictionary = open(\"unixdict.txt\",\"r\")\n\nwordList = dictionary.read().split('\\n')\n\ndictionary.close()\n\noddWordSet = set({})\n\nfor word in wordList:\n    if len(word)>=9 and word[::2] in wordList:\n        oddWordSet.add(word[::2])\n\n[print(i) for i in sorted(oddWordSet)]\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n"}
{"id": 58395, "name": "Tree datastructures", "Python": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n    if flat is None:\n        flat = []\n    if node:\n        flat.append((depth, node[0]))\n    for child in node[1]:\n        to_indent(child, depth + 1, flat)\n    return flat\n\ndef to_nest(lst, depth=0, level=None):\n    if level is None:\n        level = []\n    while lst:\n        d, name = lst[0]\n        if d == depth:\n            children = []\n            level.append((name, children))\n            lst.pop(0)\n        elif d > depth:  \n            to_nest(lst, d, children)\n        elif d < depth:  \n            return\n    return level[0] if level else None\n                    \nif __name__ == '__main__':\n    print('Start Nest format:')\n    nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n                            ('mocks', [('trolling', [])])])\n    pp(nest, width=25)\n\n    print('\\n... To Indent format:')\n    as_ind = to_indent(nest)\n    pp(as_ind, width=25)\n\n    print('\\n... To Nest format:')\n    as_nest = to_nest(as_ind)\n    pp(as_nest, width=25)\n\n    if nest != as_nest:\n        print(\"Whoops round-trip issues\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n    if level == 0 {\n        fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n    }\n    fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\"  \", level), n.name)\n    for _, c := range n.children {\n        fmt.Fprintf(w, \"%s\", strings.Repeat(\"  \", level+1))\n        printNest(c, level+1, w)\n    }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n    fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n    for _, n := range iNodes {\n        fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n    }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n    *iNodes = append(*iNodes, iNode{level, n.name})\n    for _, c := range n.children {\n        toIndent(c, level+1, iNodes)\n    }\n}\n\nfunc main() {\n    n1 := nNode{\"RosettaCode\", nil}\n    n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n    n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n    n1.children = append(n1.children, n2, n3)\n\n    var sb strings.Builder\n    printNest(n1, 0, &sb)\n    s1 := sb.String()\n    fmt.Print(s1)\n\n    var iNodes []iNode\n    toIndent(n1, 0, &iNodes)\n    printIndent(iNodes, os.Stdout)\n\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    sb.Reset()\n    printNest(n, 0, &sb)\n    s2 := sb.String()\n    fmt.Print(s2)\n\n    fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}\n"}
{"id": 58396, "name": "Tree datastructures", "Python": "from pprint import pprint as pp\n\ndef to_indent(node, depth=0, flat=None):\n    if flat is None:\n        flat = []\n    if node:\n        flat.append((depth, node[0]))\n    for child in node[1]:\n        to_indent(child, depth + 1, flat)\n    return flat\n\ndef to_nest(lst, depth=0, level=None):\n    if level is None:\n        level = []\n    while lst:\n        d, name = lst[0]\n        if d == depth:\n            children = []\n            level.append((name, children))\n            lst.pop(0)\n        elif d > depth:  \n            to_nest(lst, d, children)\n        elif d < depth:  \n            return\n    return level[0] if level else None\n                    \nif __name__ == '__main__':\n    print('Start Nest format:')\n    nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), \n                            ('mocks', [('trolling', [])])])\n    pp(nest, width=25)\n\n    print('\\n... To Indent format:')\n    as_ind = to_indent(nest)\n    pp(as_ind, width=25)\n\n    print('\\n... To Nest format:')\n    as_nest = to_nest(as_ind)\n    pp(as_nest, width=25)\n\n    if nest != as_nest:\n        print(\"Whoops round-trip issues\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n    if level == 0 {\n        fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n    }\n    fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\"  \", level), n.name)\n    for _, c := range n.children {\n        fmt.Fprintf(w, \"%s\", strings.Repeat(\"  \", level+1))\n        printNest(c, level+1, w)\n    }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n    fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n    for _, n := range iNodes {\n        fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n    }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n    *iNodes = append(*iNodes, iNode{level, n.name})\n    for _, c := range n.children {\n        toIndent(c, level+1, iNodes)\n    }\n}\n\nfunc main() {\n    n1 := nNode{\"RosettaCode\", nil}\n    n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n    n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n    n1.children = append(n1.children, n2, n3)\n\n    var sb strings.Builder\n    printNest(n1, 0, &sb)\n    s1 := sb.String()\n    fmt.Print(s1)\n\n    var iNodes []iNode\n    toIndent(n1, 0, &iNodes)\n    printIndent(iNodes, os.Stdout)\n\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    sb.Reset()\n    printNest(n, 0, &sb)\n    s2 := sb.String()\n    fmt.Print(s2)\n\n    fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}\n"}
{"id": 58397, "name": "Selectively replace multiple instances of a character within a string", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n"}
{"id": 58398, "name": "Selectively replace multiple instances of a character within a string", "Python": "from collections import defaultdict\n\nrep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}\n \ndef trstring(oldstring, repdict):\n    seen, newchars = defaultdict(lambda:1, {}), []\n    for c in oldstring:\n        i = seen[c]\n        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)\n        seen[c] += 1\n    return ''.join(newchars)\n\nprint('abracadabra ->', trstring('abracadabra', rep))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"abracadabra\"\n    ss := []byte(s)\n    var ixs []int\n    for ix, c := range s {\n        if c == 'a' {\n            ixs = append(ixs, ix)\n        }\n    }\n    repl := \"ABaCD\"\n    for i := 0; i < 5; i++ {\n        ss[ixs[i]] = repl[i]\n    }\n    s = string(ss)\n    s = strings.Replace(s, \"b\", \"E\", 1)\n    s = strings.Replace(s, \"r\", \"F\", 2)\n    s = strings.Replace(s, \"F\", \"r\", 1)\n    fmt.Println(s)\n}\n"}
{"id": 58399, "name": "Repunit primes", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n"}
{"id": 58400, "name": "Repunit primes", "Python": "from sympy import isprime\nfor b in range(2, 17):\n    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 2700\n    primes := rcu.Primes(limit)\n    s := new(big.Int)\n    for b := 2; b <= 36; b++ {\n        var rPrimes []int\n        for _, p := range primes {\n            s.SetString(strings.Repeat(\"1\", p), b)\n            if s.ProbablyPrime(15) {\n                rPrimes = append(rPrimes, p)\n            }\n        }\n        fmt.Printf(\"Base %2d: %v\\n\", b, rPrimes)\n    }\n}\n"}
{"id": 58401, "name": "Curzon numbers", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58402, "name": "Curzon numbers", "Python": "def is_Curzon(n, k):\n    r = k * n\n    return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n    n, curzons = 1, []\n    while len(curzons) < 1000:\n        if is_Curzon(n, k):\n            curzons.append(n)\n        n += 1\n    print(f'Curzon numbers with k = {k}:')\n    for i, c in enumerate(curzons[:50]):\n        print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\\n')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    zero := big.NewInt(0)\n    one := big.NewInt(1)\n    for k := int64(2); k <= 10; k += 2 {\n        bk := big.NewInt(k)\n        fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n        count := 0\n        n := int64(1)\n        pow := big.NewInt(k)\n        z := new(big.Int)\n        var curzon50 []int64\n        for {\n            z.Add(pow, one)\n            d := k*n + 1\n            bd := big.NewInt(d)\n            if z.Rem(z, bd).Cmp(zero) == 0 {\n                if count < 50 {\n                    curzon50 = append(curzon50, n)\n                }\n                count++\n                if count == 50 {\n                    for i := 0; i < len(curzon50); i++ {\n                        fmt.Printf(\"%4d \", curzon50[i])\n                        if (i+1)%10 == 0 {\n                            fmt.Println()\n                        }\n                    }\n                    fmt.Print(\"\\nOne thousandth: \")\n                }\n                if count == 1000 {\n                    fmt.Println(n)\n                    break\n                }\n            }\n            n++\n            pow.Mul(pow, bk)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58403, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 58404, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 58405, "name": "Ramanujan's constant", "Python": "from mpmath import mp\nheegner = [19,43,67,163]\nmp.dps = 50\nx = mp.exp(mp.pi*mp.sqrt(163))\nprint(\"calculated Ramanujan's constant: {}\".format(x))\nprint(\"Heegner numbers yielding 'almost' integers:\")\nfor i in heegner:\n    print(\" for {}: {} ~ {} error: {}\".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n"}
{"id": 58406, "name": "Respond to an unknown method call", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\nfunc (example) Foo() int {\n    return 42\n}\n\n\nfunc (e example) CallMethod(n string) int {\n    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {\n        \n        return int(m.Call(nil)[0].Int())\n    }\n    \n    fmt.Println(\"Unknown method:\", n)\n    return 0\n}\n\nfunc main() {\n    var e example\n    fmt.Println(e.CallMethod(\"Foo\"))\n    fmt.Println(e.CallMethod(\"Bar\"))\n}\n"}
{"id": 58407, "name": "Word break problem", "Python": "\n\nfrom itertools import (chain)\n\n\n\ndef stringParse(lexicon):\n    \n    return lambda s: Node(s)(\n        tokenTrees(lexicon)(s)\n    )\n\n\n\ndef tokenTrees(wds):\n    \n    def go(s):\n        return [Node(s)([])] if s in wds else (\n            concatMap(nxt(s))(wds)\n        )\n\n    def nxt(s):\n        return lambda w: parse(\n            w, go(s[len(w):])\n        ) if s.startswith(w) else []\n\n    def parse(w, xs):\n        return [Node(w)(xs)] if xs else xs\n\n    return lambda s: go(s)\n\n\n\ndef showParse(tree):\n    \n    def showTokens(x):\n        xs = x['nest']\n        return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')\n    parses = tree['nest']\n    return tree['root'] + ':\\n' + (\n        '\\n'.join(\n            map(showTokens, parses)\n        ) if parses else ' ( Not parseable in terms of these words )'\n    )\n\n\n\n\ndef main():\n    \n\n    lexicon = 'a bc abc cd b'.split()\n    testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()\n\n    print(unlines(\n        map(\n            showParse,\n            map(\n                stringParse(lexicon),\n                testSamples\n            )\n        )\n    ))\n\n\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n\ndef concatMap(f):\n    \n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n\ndef unlines(xs):\n    \n    return '\\n'.join(xs)\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n"}
{"id": 58408, "name": "Brilliant numbers", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n"}
{"id": 58409, "name": "Brilliant numbers", "Python": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n    pos = 1\n    root = isqrt(lb)\n\n    for blk in blocks:\n        n = len(blk)\n        if blk[-1]*blk[-1] < lb:\n            pos += n*(n + 1)//2\n            continue\n\n        i = np.searchsorted(blk, root, 'left')\n        i += blk[i]*blk[i] < lb\n\n        if not i:\n            return blk[0]*blk[0], pos\n\n        p = blk[:i + 1]\n        q = (lb - 1)//p\n        idx = np.searchsorted(blk, q, 'right')\n\n        sel = idx < n\n        p, idx = p[sel], idx[sel]\n        q = blk[idx]\n\n        sel = q >= p\n        p, q, idx = p[sel], q[sel], idx[sel]\n\n        pos += np.sum(idx - np.arange(len(idx)))\n        return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n    p, _ = smallest_brilliant(p + 1)\n    res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n    thresh = 10**i\n    p, pos = smallest_brilliant(thresh)\n    print(f'Above 10^{i:2d}: {p:20d} at \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n"}
{"id": 58410, "name": "Word ladder", "Python": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n    for c in str :\n        x = ( x*33 + ord( c )) & 0xffffffffff\n    return x  \n\ndef cache ( func,*param ):\n    n = 'cache_%x.bin'%abs( h( repr( param )))\n    try    : return eval( zlib.decompress( open( n,'rb' ).read()))\n    except : pass\n    s = func( *param )\n    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n    return s\n\ndico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url  = lambda url   : urllib.request.urlopen( url ).read()\nload_dico = lambda url   : tuple( cache( read_url,url ).split( b'\\n'))\nisnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n    map = [(w.decode('ascii'),[]) for w in words]\n    for i1,(w1,n1) in enumerate( map ):\n        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n            if isnext( w1,w2 ):\n                n1.append( i2 )\n                n2.append( i1 )\n    return map\n\ndef find_path ( words,w1,w2 ):\n    i = [w[0] for w in words].index( w1 )\n    front,done,res  = [i],{i:-1},[]\n    while front :\n        i = front.pop(0)\n        word,next = words[i]\n        for n in next :\n            if n in done : continue\n            done[n] = i\n            if words[n][0] == w2 :\n                while n >= 0 :\n                    res = [words[n][0]] + res\n                    n = done[n]\n                return ' '.join( res )\n            front.append( n )\n    return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n"}
{"id": 58411, "name": "Joystick position", "Python": "import sys\nimport pygame\n\npygame.init()\n\n\nclk = pygame.time.Clock()\n\n\nif pygame.joystick.get_count() == 0:\n    raise IOError(\"No joystick detected\")\njoy = pygame.joystick.Joystick(0)\njoy.init()\n\n\nsize = width, height = 600, 600\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Joystick Tester\")\n\n\nframeRect = pygame.Rect((45, 45), (510, 510))\n\n\ncrosshair = pygame.surface.Surface((10, 10))\ncrosshair.fill(pygame.Color(\"magenta\"))\npygame.draw.circle(crosshair, pygame.Color(\"blue\"), (5,5), 5, 0)\ncrosshair.set_colorkey(pygame.Color(\"magenta\"), pygame.RLEACCEL)\ncrosshair = crosshair.convert()\n\n\nwriter = pygame.font.Font(pygame.font.get_default_font(), 15)\nbuttons = {}\nfor b in range(joy.get_numbuttons()):\n    buttons[b] = [\n        writer.render(\n            hex(b)[2:].upper(),\n            1,\n            pygame.Color(\"red\"),\n            pygame.Color(\"black\")\n        ).convert(),\n        \n        \n        ((15*b)+45, 560)\n    ]\n\nwhile True:\n    \n    pygame.event.pump()\n    for events in pygame.event.get():\n        if events.type == pygame.QUIT:\n            pygame.quit()\n            sys.exit()\n\n    \n    screen.fill(pygame.Color(\"black\"))\n\n    \n    x = joy.get_axis(0)\n    y = joy.get_axis(1)\n\n    \n    \n    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))\n    pygame.draw.rect(screen, pygame.Color(\"red\"), frameRect, 1)\n\n    \n    for b in range(joy.get_numbuttons()):\n        if joy.get_button(b):\n            screen.blit(buttons[b][0], buttons[b][1])\n\n    \n    pygame.display.flip()\n    clk.tick(40) \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/nsf/termbox-go\"\n    \"github.com/simulatedsimian/joystick\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc printAt(x, y int, s string) {\n    for _, r := range s {\n        termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)\n        x++\n    }\n}\n\nfunc readJoystick(js joystick.Joystick, hidden bool) {\n    jinfo, err := js.Read()\n    check(err)\n\n    w, h := termbox.Size()\n    tbcd := termbox.ColorDefault\n    termbox.Clear(tbcd, tbcd)\n    printAt(1, h-1, \"q - quit\")\n    if hidden {\n        printAt(11, h-1, \"s - show buttons:\")\n    } else {\n        bs := \"\"\n        printAt(11, h-1, \"h - hide buttons:\")\n        for button := 0; button < js.ButtonCount(); button++ {\n            if jinfo.Buttons&(1<<uint32(button)) != 0 {\n                \n                bs += fmt.Sprintf(\" %X\", button+1)\n            }\n        }\n        printAt(28, h-1, bs)\n    }\n\n    \n    x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)\n    y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)\n    printAt(x, y, \"+\") \n    termbox.Flush()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    \n    \n    jsid := 0\n    \n    if len(os.Args) > 1 {\n        i, err := strconv.Atoi(os.Args[1])\n        check(err)\n        jsid = i\n    }\n\n    js, jserr := joystick.Open(jsid)\n    check(jserr)\n \n    err := termbox.Init()\n    check(err)\n    defer termbox.Close()\n\n    eventQueue := make(chan termbox.Event)\n    go func() {\n        for {\n            eventQueue <- termbox.PollEvent()\n        }\n    }()\n\n    ticker := time.NewTicker(time.Millisecond * 40)\n    hidden := false \n\n    for doQuit := false; !doQuit; {\n        select {\n        case ev := <-eventQueue:\n            if ev.Type == termbox.EventKey {\n                if ev.Ch == 'q' {\n                    doQuit = true\n                } else if ev.Ch == 'h' {\n                    hidden = true\n                } else if ev.Ch == 's' {\n                    hidden = false\n                }\n            }\n            if ev.Type == termbox.EventResize {\n                termbox.Flush()\n            }\n        case <-ticker.C:\n            readJoystick(js, hidden)\n        }\n    }\n}\n"}
{"id": 58412, "name": "Earliest difference between prime gaps", "Python": "\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n    if pri[i] - pri[i - 1] not in gapstarts:\n        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n    while GAP1 not in gapstarts:\n        GAP1 += 2\n    start1 = gapstarts[GAP1]\n    GAP2 = GAP1 + 2\n    if GAP2 not in gapstarts:\n        GAP1 = GAP2 + 2\n        continue\n    start2 = gapstarts[GAP2]\n    diff = abs(start2 - start1)\n    if diff > PM:\n        print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n        print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n        if PM == LIMIT:\n            break\n        PM *= 10\n    else:\n        GAP1 = GAP2\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n"}
{"id": 58413, "name": "Latin Squares in reduced form", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n"}
{"id": 58414, "name": "Ormiston pairs", "Python": "\n\nfrom sympy import primerange\n\n\nPRIMES1M = list(primerange(1, 1_000_000))\nASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M]\nORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M))\n             if ASBASE10SORT[i - 1] == ASBASE10SORT[i]]\n\nprint('First 30 Ormiston pairs:')\nfor (i, o) in enumerate(ORMISTONS):\n    if i < 30:\n        print(f'({o[0] : 6} {o[1] : 6} )',\n              end='\\n' if (i + 1) % 5 == 0 else '  ')\n    else:\n        break\n\nprint(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e9\n    primes := rcu.Primes(limit)\n    var orm30 [][2]int\n    j := int(1e5)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-1; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        if (p2-p1)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 == key2 {\n            if count < 30 {\n                orm30 = append(orm30, [2]int{p1, p2})\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"First 30 Ormiston pairs:\")\n    for i := 0; i < 30; i++ {\n        fmt.Printf(\"%5v \", orm30[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e5)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston pairs before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n    }\n}\n"}
{"id": 58415, "name": "UPC", "Python": "\nimport itertools\nimport re\n\nRE_BARCODE = re.compile(\n    r\"^(?P<s_quiet> +)\"  \n    r\"(?P<s_guard>\n    r\"(?P<left>[ \n    r\"(?P<m_guard> \n    r\"(?P<right>[ \n    r\"(?P<e_guard>\n    r\"(?P<e_quiet> +)$\"  \n)\n\nLEFT_DIGITS = {\n    (0, 0, 0, 1, 1, 0, 1): 0,\n    (0, 0, 1, 1, 0, 0, 1): 1,\n    (0, 0, 1, 0, 0, 1, 1): 2,\n    (0, 1, 1, 1, 1, 0, 1): 3,\n    (0, 1, 0, 0, 0, 1, 1): 4,\n    (0, 1, 1, 0, 0, 0, 1): 5,\n    (0, 1, 0, 1, 1, 1, 1): 6,\n    (0, 1, 1, 1, 0, 1, 1): 7,\n    (0, 1, 1, 0, 1, 1, 1): 8,\n    (0, 0, 0, 1, 0, 1, 1): 9,\n}\n\nRIGHT_DIGITS = {\n    (1, 1, 1, 0, 0, 1, 0): 0,\n    (1, 1, 0, 0, 1, 1, 0): 1,\n    (1, 1, 0, 1, 1, 0, 0): 2,\n    (1, 0, 0, 0, 0, 1, 0): 3,\n    (1, 0, 1, 1, 1, 0, 0): 4,\n    (1, 0, 0, 1, 1, 1, 0): 5,\n    (1, 0, 1, 0, 0, 0, 0): 6,\n    (1, 0, 0, 0, 1, 0, 0): 7,\n    (1, 0, 0, 1, 0, 0, 0): 8,\n    (1, 1, 1, 0, 1, 0, 0): 9,\n}\n\n\nMODULES = {\n    \" \": 0,\n    \"\n}\n\nDIGITS_PER_SIDE = 6\nMODULES_PER_DIGIT = 7\n\n\nclass ParityError(Exception):\n    \n\n\nclass ChecksumError(Exception):\n    \n\n\ndef group(iterable, n):\n    \n    args = [iter(iterable)] * n\n    return tuple(itertools.zip_longest(*args))\n\n\ndef parse(barcode):\n    \n    match = RE_BARCODE.match(barcode)\n\n    \n    \n    left = group((MODULES[c] for c in match.group(\"left\")), MODULES_PER_DIGIT)\n    right = group((MODULES[c] for c in match.group(\"right\")), MODULES_PER_DIGIT)\n\n    \n    left, right = check_parity(left, right)\n\n    \n    return tuple(\n        itertools.chain(\n            (LEFT_DIGITS[d] for d in left),\n            (RIGHT_DIGITS[d] for d in right),\n        )\n    )\n\n\ndef check_parity(left, right):\n    \n    \n    \n    \n    left_parity = sum(sum(d) % 2 for d in left)\n    right_parity = sum(sum(d) % 2 for d in right)\n\n    \n    \n    if left_parity == 0 and right_parity == DIGITS_PER_SIDE:\n        _left = tuple(tuple(reversed(d)) for d in reversed(right))\n        right = tuple(tuple(reversed(d)) for d in reversed(left))\n        left = _left\n    elif left_parity != DIGITS_PER_SIDE or right_parity != 0:\n        \n        error = tuple(\n            itertools.chain(\n                (LEFT_DIGITS.get(d, \"_\") for d in left),\n                (RIGHT_DIGITS.get(d, \"_\") for d in right),\n            )\n        )\n        raise ParityError(\" \".join(str(d) for d in error))\n\n    return left, right\n\n\ndef checksum(digits):\n    \n    odds = (digits[i] for i in range(0, 11, 2))\n    evens = (digits[i] for i in range(1, 10, 2))\n\n    check_digit = (sum(odds) * 3 + sum(evens)) % 10\n\n    if check_digit != 0:\n        check_digit = 10 - check_digit\n\n    if digits[-1] != check_digit:\n        raise ChecksumError(str(check_digit))\n\n    return check_digit\n\n\ndef main():\n    barcodes = [\n        \"         \n        \"        \n        \"         \n        \"       \n        \"         \n        \"          \n        \"         \n        \"        \n        \"         \n        \"        \n        \"        \n    ]\n\n    for barcode in barcodes:\n        try:\n            digits = parse(barcode)\n        except ParityError as err:\n            print(f\"{err} parity error!\")\n            continue\n\n        try:\n            check_digit = checksum(digits)\n        except ChecksumError as err:\n            print(f\"{' '.join(str(d) for d in digits)} checksum error! ({err})\")\n            continue\n\n        print(f\"{' '.join(str(d) for d in digits)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n"}
{"id": 58416, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 58417, "name": "Playfair cipher", "Python": "from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    \n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    \n    enc = {}\n\n    \n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    \n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    \n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    \n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n"}
{"id": 58418, "name": "Harmonic series", "Python": "from  fractions import Fraction\n\ndef harmonic_series():\n    n, h = Fraction(1), Fraction(1)\n    while True:\n        yield h\n        h += 1 / (n + 1)\n        n += 1\n\nif __name__ == '__main__':\n    from itertools import islice\n    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):\n        print(n, '/', d)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc harmonic(n int) *big.Rat {\n    sum := new(big.Rat)\n    for i := int64(1); i <= int64(n); i++ {\n        r := big.NewRat(1, i)\n        sum.Add(sum, r)\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The first 20 harmonic numbers and the 100th, expressed in rational form, are:\")\n    numbers := make([]int, 21)\n    for i := 1; i <= 20; i++ {\n        numbers[i-1] = i\n    }\n    numbers[20] = 100\n    for _, i := range numbers {\n        fmt.Printf(\"%3d : %s\\n\", i, harmonic(i))\n    }\n\n    fmt.Println(\"\\nThe first harmonic number to exceed the following integers is:\")\n    const limit = 10\n    for i, n, h := 1, 1, 0.0; i <= limit; n++ {\n        h += 1.0 / float64(n)\n        if h > float64(i) {\n            fmt.Printf(\"integer = %2d  -> n = %6d  ->  harmonic number = %9.6f (to 6dp)\\n\", i, n, h)\n            i++\n        }\n    }\n}\n"}
{"id": 58419, "name": "External sort", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n"}
{"id": 58420, "name": "External sort", "Python": "\n\n\n\nimport io\n\ndef sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:\n\n    \n\n    \n    mergers = []\n    while True:\n        text = list(source.read(n))\n        if not len(text):\n            break;\n        text.sort()\n        merge_me = file_opener()\n        merge_me.write(''.join(text))\n        mergers.append(merge_me)\n        merge_me.seek(0)\n\n    \n    stack_tops = [f.read(1) for f in mergers]\n    while stack_tops:\n        c = min(stack_tops)\n        sink.write(c)\n        i = stack_tops.index(c)\n        t = mergers[i].read(1)\n        if t:\n            stack_tops[i] = t\n        else:\n            del stack_tops[i]\n            mergers[i].close()\n            del mergers[i]  \n\ndef main():\n    \n\n    \n    input_file_too_large_for_memory = io.StringIO('678925341')\n\n    \n    t = list(input_file_too_large_for_memory.read())\n    t.sort()\n    expect = ''.join(t)\n    print('expect', expect)\n\n    \n    for memory_size in range(1,12):\n        input_file_too_large_for_memory.seek(0)\n        output_file_too_large_for_memory = io.StringIO()\n        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)\n        output_file_too_large_for_memory.seek(0)\n        assert(output_file_too_large_for_memory.read() == expect)\n        print('memory size {} passed'.format(memory_size))\n\nif __name__ == '__main__':\n   example = main\n   example()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype MinHeapNode struct{ element, index int }\n\ntype MinHeap struct{ nodes []MinHeapNode }\n\nfunc left(i int) int {\n    return (2*i + 1)\n}\n\nfunc right(i int) int {\n    return (2*i + 2)\n}\n\nfunc newMinHeap(nodes []MinHeapNode) *MinHeap {\n    mh := new(MinHeap)\n    mh.nodes = nodes\n    for i := (len(nodes) - 1) / 2; i >= 0; i-- {\n        mh.minHeapify(i)\n    }\n    return mh\n}\n\nfunc (mh *MinHeap) getMin() MinHeapNode {\n    return mh.nodes[0]\n}\n\nfunc (mh *MinHeap) replaceMin(x MinHeapNode) {\n    mh.nodes[0] = x\n    mh.minHeapify(0)\n}\n\nfunc (mh *MinHeap) minHeapify(i int) {\n    l, r := left(i), right(i)\n    smallest := i\n    heapSize := len(mh.nodes)\n    if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {\n        smallest = l\n    }\n    if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {\n        smallest = r\n    }\n    if smallest != i {\n        mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]\n        mh.minHeapify(smallest)\n    }\n}\n\nfunc merge(arr []int, l, m, r int) {\n    n1, n2 := m-l+1, r-m\n    tl := make([]int, n1)\n    tr := make([]int, n2)\n    copy(tl, arr[l:])\n    copy(tr, arr[m+1:])\n    i, j, k := 0, 0, l\n    for i < n1 && j < n2 {\n        if tl[i] <= tr[j] {\n            arr[k] = tl[i]\n            k++\n            i++\n        } else {\n            arr[k] = tr[j]\n            k++\n            j++\n        }\n    }\n    for i < n1 {\n        arr[k] = tl[i]\n        k++\n        i++\n    }\n    for j < n2 {\n        arr[k] = tr[j]\n        k++\n        j++\n    }\n}\n\nfunc mergeSort(arr []int, l, r int) {\n    if l < r {\n        m := l + (r-l)/2\n        mergeSort(arr, l, m)\n        mergeSort(arr, m+1, r)\n        merge(arr, l, m, r)\n    }\n}\n\n\nfunc mergeFiles(outputFile string, n, k int) {\n    in := make([]*os.File, k)\n    var err error\n    for i := 0; i < k; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        in[i], err = os.Open(fileName)\n        check(err)\n    }\n    out, err := os.Create(outputFile)\n    check(err)\n    nodes := make([]MinHeapNode, k)\n    i := 0\n    for ; i < k; i++ {\n        _, err = fmt.Fscanf(in[i], \"%d\", &nodes[i].element)\n        if err == io.EOF {\n            break\n        }\n        check(err)\n        nodes[i].index = i\n    }\n    hp := newMinHeap(nodes[:i])\n    count := 0\n    for count != i {\n        root := hp.getMin()\n        fmt.Fprintf(out, \"%d \", root.element)\n        _, err = fmt.Fscanf(in[root.index], \"%d\", &root.element)\n        if err == io.EOF {\n            root.element = math.MaxInt32\n            count++\n        } else {\n            check(err)\n        }\n        hp.replaceMin(root)\n    }\n    for j := 0; j < k; j++ {\n        in[j].Close()\n    }\n    out.Close()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\n\nfunc createInitialRuns(inputFile string, runSize, numWays int) {\n    in, err := os.Open(inputFile)\n    out := make([]*os.File, numWays)\n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i) \n        out[i], err = os.Create(fileName)\n        check(err)\n    }\n    arr := make([]int, runSize)\n    moreInput := true\n    nextOutputFile := 0\n    var i int\n    for moreInput {\n        for i = 0; i < runSize; i++ {\n            _, err := fmt.Fscanf(in, \"%d\", &arr[i])\n            if err == io.EOF {\n                moreInput = false\n                break\n            }\n            check(err)\n        }\n        mergeSort(arr, 0, i-1)\n        for j := 0; j < i; j++ {\n            fmt.Fprintf(out[nextOutputFile], \"%d \", arr[j])\n        }\n        nextOutputFile++\n    }\n    for j := 0; j < numWays; j++ {\n        out[j].Close()\n    }\n    in.Close()\n}\n\nfunc externalSort(inputFile, outputFile string, numWays, runSize int) {\n    createInitialRuns(inputFile, runSize, numWays)\n    mergeFiles(outputFile, runSize, numWays)\n}\n\nfunc main() {\n    \n    \n    numWays := 4\n    runSize := 10\n    inputFile := \"input.txt\"\n    outputFile := \"output.txt\"\n    in, err := os.Create(inputFile)\n    check(err)\n    rand.Seed(time.Now().UnixNano())\n    for i := 0; i < numWays*runSize; i++ {\n        fmt.Fprintf(in, \"%d \", rand.Intn(math.MaxInt32))\n    }\n    in.Close()\n    externalSort(inputFile, outputFile, numWays, runSize)\n    \n    for i := 0; i < numWays; i++ {\n        fileName := fmt.Sprintf(\"es%d\", i)\n        err = os.Remove(fileName)\n        check(err)\n    }\n}\n"}
{"id": 58421, "name": "Continued fraction_Arithmetic_G(matrix ng, continued fraction n)", "Python": "class NG:\n  def __init__(self, a1, a, b1, b):\n    self.a1, self.a, self.b1, self.b = a1, a, b1, b\n\n  def ingress(self, n):\n    self.a, self.a1 = self.a1, self.a + self.a1 * n\n    self.b, self.b1 = self.b1, self.b + self.b1 * n\n\n  @property\n  def needterm(self):\n    return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1\n\n  @property\n  def egress(self):\n    n = self.a // self.b\n    self.a,  self.b  = self.b,  self.a  - self.b  * n\n    self.a1, self.b1 = self.b1, self.a1 - self.b1 * n\n    return n\n\n  @property\n  def egress_done(self):\n    if self.needterm: self.a, self.b = self.a1, self.b1\n    return self.egress\n\n  @property\n  def done(self):\n    return self.b == 0 and self.b1 == 0\n", "Go": "package cf\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype NG4 struct {\n\tA1, A int64\n\tB1, B int64\n}\n\nfunc (ng NG4) needsIngest() bool {\n\tif ng.isDone() {\n\t\tpanic(\"b₁==b==0\")\n\t}\n\treturn ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B\n}\n\nfunc (ng NG4) isDone() bool {\n\treturn ng.B1 == 0 && ng.B == 0\n}\n\nfunc (ng *NG4) ingest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.A+ng.A1*t, ng.A1,\n\t\tng.B+ng.B1*t, ng.B1\n}\n\nfunc (ng *NG4) ingestInfinite() {\n\t\n\t\n\tng.A, ng.B = ng.A1, ng.B1\n}\n\nfunc (ng *NG4) egest(t int64) {\n\t\n\t\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.B1, ng.B,\n\t\tng.A1-ng.B1*t, ng.A-ng.B*t\n}\n\n\n\nfunc (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext := cf()\n\t\tdone := false\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite()\n\t\t\t\t}\n\t\t\t}\n\t\t\tt := ng.A1 / ng.B1\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}\n"}
{"id": 58422, "name": "Calkin-Wilf sequence", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n"}
{"id": 58423, "name": "Calkin-Wilf sequence", "Python": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n    a = Fraction(1)\n    while True:\n        yield a\n        a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n    num, den = rational.numerator, rational.denominator\n    while den:\n        num, (digit, den) = den, divmod(num, den)\n        yield digit\n\ndef get_term_num(rational):\n    ans, dig, pwr = 0, 1, 0\n    for n in r2cf(rational):\n        for _ in range(n):\n            ans |= dig << pwr\n            pwr += 1\n        dig ^= 1\n    return ans\n\n          \nif __name__ == '__main__':\n    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n    x = Fraction(83116, 51639)\n    print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n    cw := make([]*big.Rat, n+1)\n    cw[0] = big.NewRat(1, 1)\n    one := big.NewRat(1, 1)\n    two := big.NewRat(2, 1)\n    for i := 1; i < n; i++ {\n        t := new(big.Rat).Set(cw[i-1])\n        f, _ := t.Float64()\n        f = math.Floor(f)\n        t.SetFloat64(f)\n        t.Mul(t, two)\n        t.Sub(t, cw[i-1])\n        t.Add(t, one)\n        t.Inv(t)\n        cw[i] = new(big.Rat).Set(t)\n    }\n    return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n    a := r.Num().Int64()\n    b := r.Denom().Int64()\n    var res []int\n    for {\n        res = append(res, int(a/b))\n        t := a % b\n        a, b = b, t\n        if a == 1 {\n            break\n        }\n    }\n    le := len(res)\n    if le%2 == 0 { \n        res[le-1]--\n        res = append(res, 1)\n    }\n    return res\n}\n\nfunc getTermNumber(cf []int) int {\n    b := \"\"\n    d := \"1\"\n    for _, n := range cf {\n        b = strings.Repeat(d, n) + b\n        if d == \"1\" {\n            d = \"0\"\n        } else {\n            d = \"1\"\n        }\n    }\n    i, _ := strconv.ParseInt(b, 2, 64)\n    return int(i)\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    cw := calkinWilf(20)\n    fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n    for i := 1; i <= 20; i++ {\n        fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n    }\n    fmt.Println()\n    r := big.NewRat(83116, 51639)\n    cf := toContinued(r)\n    tn := getTermNumber(cf)\n    fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}\n"}
{"id": 58424, "name": "Distribution of 0 digits in factorial series", "Python": "def facpropzeros(N, verbose = True):\n    proportions = [0.0] * N\n    fac, psum = 1, 0.0\n    for i in range(N):\n        fac *= i + 1\n        d = list(str(fac))\n        psum += sum(map(lambda x: x == '0', d)) / len(d)\n        proportions[i] = psum / (i + 1)\n\n    if verbose:\n        print(\"The mean proportion of 0 in factorials from 1 to {} is {}.\".format(N, psum / N))\n\n    return proportions\n\n\nfor n in [100, 1000, 10000]:\n    facpropzeros(n)\n\nprops = facpropzeros(47500, False)\nn = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))\n\nprint(\"The mean proportion dips permanently below 0.16 at {}.\".format(n + 2))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"rcu\"\n)\n\nfunc main() {\n    fact  := big.NewInt(1)\n    sum   := 0.0\n    first := int64(0)\n    firstRatio := 0.0    \n    fmt.Println(\"The mean proportion of zero digits in factorials up to the following are:\")\n    for n := int64(1); n <= 50000; n++  {\n        fact.Mul(fact, big.NewInt(n))\n        bytes  := []byte(fact.String())\n        digits := len(bytes)\n        zeros  := 0\n        for _, b := range bytes {\n            if b == '0' {\n                zeros++\n            }\n        }\n        sum += float64(zeros)/float64(digits)\n        ratio := sum / float64(n)\n        if n == 100 || n == 1000 || n == 10000 {\n            fmt.Printf(\"%6s = %12.10f\\n\", rcu.Commatize(int(n)), ratio)\n        } \n        if first > 0 && ratio >= 0.16 {\n            first = 0\n            firstRatio = 0.0\n        } else if first == 0 && ratio < 0.16 {\n            first = n\n            firstRatio = ratio           \n        }\n    }\n    fmt.Printf(\"%6s = %12.10f\", rcu.Commatize(int(first)), firstRatio)\n    fmt.Println(\" (stays below 0.16 after this)\")\n    fmt.Printf(\"%6s = %12.10f\\n\", \"50,000\", sum / 50000)\n}\n"}
{"id": 58425, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n"}
{"id": 58426, "name": "Address of a variable", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tmyVar := 3.14\n\tmyPointer := &myVar\n\tfmt.Println(\"Address:\", myPointer, &myVar)\n\tfmt.Printf(\"Address: %p %p\\n\", myPointer, &myVar)\n\n\tvar addr64 int64\n\tvar addr32 int32\n\tptr := unsafe.Pointer(myPointer)\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {\n\t\taddr64 = int64(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int64: %#016x\\n\", addr64)\n\t}\n\tif unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {\n\t\t\n\t\taddr32 = int32(uintptr(ptr))\n\t\tfmt.Printf(\"Pointer stored in   int32: %#08x\\n\", addr32)\n\t}\n\taddr := uintptr(ptr)\n\tfmt.Printf(\"Pointer stored in uintptr: %#08x\\n\", addr)\n\n\tfmt.Println(\"value as float:\", myVar)\n\ti := (*int32)(unsafe.Pointer(&myVar))\n\tfmt.Printf(\"value as int32: %#08x\\n\", *i)\n}\n"}
{"id": 58427, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n"}
{"id": 58428, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n"}
{"id": 58429, "name": "Color wheel", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n"}
{"id": 58430, "name": "Plasma effect", "Python": "\n\npal = [0] * 128\nr = 42\ng = 84\nb = 126\nrd = gd = bd = False\n\ndef setup():\n    global buffer\n    size(600, 600)\n    frameRate(25)\n    buffer = [None] * width * height\n    for x in range(width):\n        for y in range(width):\n            value = int(((128 + (128 * sin(x / 32.0)))\n                         + (128 + (128 * cos(y / 32.0)))\n                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)\n            buffer[x + y * width] = value\n\ndef draw():\n    global r, g, b, rd, gd, bd\n    if r > 128: rd = True\n    if not rd: r += 1\n    else: r-=1\n    if r < 0: rd = False\n    if g > 128: gd = True\n    if not gd: g += 1\n    else: g- = 1\n    if r < 0: gd = False \n    if b > 128: bd = True\n    if not bd: b += 1\n    else: b- = 1\n    if b < 0: bd = False\n \n    for i in range(128):\n          s_1 = sin(i * PI / 25)\n          s_2 = sin(i * PI / 50 + PI / 4)\n          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)\n\n    loadPixels()\n    for i, b in enumerate(buffer):\n          pixels[i] = pal[(b + frameCount) % 127]\n    updatePixels()\n", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n"}
{"id": 58431, "name": "Abelian sandpile model_Identity", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n"}
{"id": 58432, "name": "Abelian sandpile model_Identity", "Python": "from itertools import product\nfrom collections import defaultdict\n\n\nclass Sandpile():\n    def __init__(self, gridtext):\n        array = [int(x) for x in gridtext.strip().split()]\n        self.grid = defaultdict(int,\n                                {(i //3, i % 3): x \n                                 for i, x in enumerate(array)})\n\n    _border = set((r, c) \n                  for r, c in product(range(-1, 4), repeat=2) \n                  if not 0 <= r <= 2 or not 0 <= c <= 2\n                  )\n    _cell_coords = list(product(range(3), repeat=2))\n    \n    def topple(self):\n        g = self.grid\n        for r, c in self._cell_coords:\n            if g[(r, c)] >= 4:\n                g[(r - 1, c)] += 1\n                g[(r + 1, c)] += 1\n                g[(r, c - 1)] += 1\n                g[(r, c + 1)] += 1\n                g[(r, c)] -= 4\n                return True\n        return False\n    \n    def stabilise(self):\n        while self.topple():\n            pass\n        \n        g = self.grid\n        for row_col in self._border.intersection(g.keys()):\n            del g[row_col]\n        return self\n    \n    __pos__ = stabilise     \n    \n    def __eq__(self, other):\n        g = self.grid\n        return all(g[row_col] == other.grid[row_col]\n                   for row_col in self._cell_coords)\n\n    def __add__(self, other):\n        g = self.grid\n        ans = Sandpile(\"\")\n        for row_col in self._cell_coords:\n            ans.grid[row_col] = g[row_col] + other.grid[row_col]\n        return ans.stabilise()\n       \n    def __str__(self):\n        g, txt = self.grid, []\n        for row in range(3):\n            txt.append(' '.join(str(g[(row, col)]) \n                                for col in range(3)))\n        return '\\n'.join(txt)\n    \n    def __repr__(self):\n        return f'{self.__class__.__name__}()'\n        \n\nunstable = Sandpile()\ns1 = Sandpile()\ns2 = Sandpile()\ns3 = Sandpile(\"3 3 3  3 3 3  3 3 3\")\ns3_id = Sandpile(\"2 1 2  1 0 1  2 1 2\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n    b := [9]int{}\n    for i := 0; i < 9; i++ {\n        b[i] = s.a[i] + other.a[i]\n    }\n    return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n    for _, e := range s.a {\n        if e > 3 {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (s *sandpile) topple() {\n    for i := 0; i < 9; i++ {\n        if s.a[i] > 3 {\n            s.a[i] -= 4\n            for _, j := range neighbors[i] {\n                s.a[j]++\n            }\n            return\n        }\n    }\n}\n\nfunc (s *sandpile) String() string {\n    var sb strings.Builder\n    for i := 0; i < 3; i++ {\n        for j := 0; j < 3; j++ {\n            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n        }\n        sb.WriteString(\"\\n\")\n    }\n    return sb.String()\n}\n\nfunc main() {\n    fmt.Println(\"Avalanche of topplings:\\n\")\n    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n    fmt.Println(s4)\n    for !s4.isStable() {\n        s4.topple()\n        fmt.Println(s4)\n    }\n\n    fmt.Println(\"Commutative additions:\\n\")\n    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n    s3_a := s1.plus(s2)\n    for !s3_a.isStable() {\n        s3_a.topple()\n    }\n    s3_b := s2.plus(s1)\n    for !s3_b.isStable() {\n        s3_b.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n    fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n    fmt.Println(\"Addition of identity sandpile:\\n\")\n    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n    s4 = s3.plus(s3_id)\n    for !s4.isStable() {\n        s4.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n    fmt.Println(\"Addition of identities:\\n\")\n    s5 := s3_id.plus(s3_id)\n    for !s5.isStable() {\n        s5.topple()\n    }\n    fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}\n"}
{"id": 58433, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 58434, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n"}
{"id": 58435, "name": "Create an object_Native demonstration", "Python": "from collections import UserDict\nimport copy\n\nclass Dict(UserDict):\n    \n    def __init__(self, dict=None, **kwargs):\n        self.__init = True\n        super().__init__(dict, **kwargs)\n        self.default = copy.deepcopy(self.data)\n        self.__init = False\n    \n    def __delitem__(self, key):\n        if key in self.default:\n            self.data[key] = self.default[key]\n        else:\n            raise NotImplementedError\n\n    def __setitem__(self, key, item):\n        if self.__init:\n            super().__setitem__(key, item)\n        elif key in self.data:\n            self.data[key] = item\n        else:\n            raise KeyError\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, super().__repr__())\n    \n    def fromkeys(cls, iterable, value=None):\n        if self.__init:\n            super().fromkeys(cls, iterable, value)\n        else:\n            for key in iterable:\n                if key in self.data:\n                    self.data[key] = value\n                else:\n                    raise KeyError\n\n    def clear(self):\n        self.data.update(copy.deepcopy(self.default))\n\n    def pop(self, key, default=None):\n        raise NotImplementedError\n\n    def popitem(self):\n        raise NotImplementedError\n\n    def update(self, E, **F):\n        if self.__init:\n            super().update(E, **F)\n        else:\n            haskeys = False\n            try:\n                keys = E.keys()\n                haskeys = Ture\n            except AttributeError:\n                pass\n            if haskeys:\n                for key in keys:\n                    self[key] = E[key]\n            else:\n                for key, val in E:\n                    self[key] = val\n            for key in F:\n                self[key] = F[key]\n\n    def setdefault(self, key, default=None):\n        if key not in self.data:\n            raise KeyError\n        else:\n            return super().setdefault(key, default)\n", "Go": "package romap\n\ntype Romap struct{ imap map[byte]int }\n\n\nfunc New(m map[byte]int) *Romap {\n    if m == nil {\n        return nil\n    }\n    return &Romap{m}\n}\n\n\nfunc (rom *Romap) Get(key byte) (int, bool) {\n    i, ok := rom.imap[key]\n    return i, ok\n}\n\n\nfunc (rom *Romap) Reset(key byte) {\n    _, ok := rom.imap[key]\n    if ok {\n        rom.imap[key] = 0 \n    }\n}\n"}
{"id": 58436, "name": "Rare numbers", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n    \"time\"\n)\n\ntype term struct {\n    coeff    uint64\n    ix1, ix2 int8\n}\n\nconst maxDigits = 19\n\nfunc toUint64(digits []int8, reverse bool) uint64 {\n    sum := uint64(0)\n    if !reverse {\n        for i := 0; i < len(digits); i++ {\n            sum = sum*10 + uint64(digits[i])\n        }\n    } else {\n        for i := len(digits) - 1; i >= 0; i-- {\n            sum = sum*10 + uint64(digits[i])\n        }\n    }\n    return sum\n}\n\nfunc isSquare(n uint64) bool {\n    if 0x202021202030213&(1<<(n&63)) != 0 {\n        root := uint64(math.Sqrt(float64(n)))\n        return root*root == n\n    }\n    return false\n}\n\nfunc seq(from, to, step int8) []int8 {\n    var res []int8\n    for i := from; i <= to; i += step {\n        res = append(res, i)\n    }\n    return res\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    pow := uint64(1)\n    fmt.Println(\"Aggregate timings to process all numbers up to:\")\n    \n    allTerms := make([][]term, maxDigits-1)\n    for r := 2; r <= maxDigits; r++ {\n        var terms []term\n        pow *= 10\n        pow1, pow2 := pow, uint64(1)\n        for i1, i2 := int8(0), int8(r-1); i1 < i2; i1, i2 = i1+1, i2-1 {\n            terms = append(terms, term{pow1 - pow2, i1, i2})\n            pow1 /= 10\n            pow2 *= 10\n        }\n        allTerms[r-2] = terms\n    }\n    \n    fml := map[int8][][]int8{\n        0: {{2, 2}, {8, 8}},\n        1: {{6, 5}, {8, 7}},\n        4: {{4, 0}},\n        6: {{6, 0}, {8, 2}},\n    }\n    \n    dmd := make(map[int8][][]int8)\n    for i := int8(0); i < 100; i++ {\n        a := []int8{i / 10, i % 10}\n        d := a[0] - a[1]\n        dmd[d] = append(dmd[d], a)\n    }\n    fl := []int8{0, 1, 4, 6}\n    dl := seq(-9, 9, 1) \n    zl := []int8{0}     \n    el := seq(-8, 8, 2) \n    ol := seq(-9, 9, 2) \n    il := seq(0, 9, 1)\n    var rares []uint64\n    lists := make([][][]int8, 4)\n    for i, f := range fl {\n        lists[i] = [][]int8{{f}}\n    }\n    var digits []int8\n    count := 0\n\n    \n    \n    var fnpr func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int)\n    fnpr = func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) {\n        if level == len(dis) {\n            digits[indices[0][0]] = fml[cand[0]][di[0]][0]\n            digits[indices[0][1]] = fml[cand[0]][di[0]][1]\n            le := len(di)\n            if nd%2 == 1 {\n                le--\n                digits[nd/2] = di[le]\n            }\n            for i, d := range di[1:le] {\n                digits[indices[i+1][0]] = dmd[cand[i+1]][d][0]\n                digits[indices[i+1][1]] = dmd[cand[i+1]][d][1]\n            }\n            r := toUint64(digits, true)\n            npr := nmr + 2*r\n            if !isSquare(npr) {\n                return\n            }\n            count++\n            fmt.Printf(\"     R/N %2d:\", count)\n            ms := uint64(time.Since(start).Milliseconds())\n            fmt.Printf(\"  %9s ms\", commatize(ms))\n            n := toUint64(digits, false)\n            fmt.Printf(\"  (%s)\\n\", commatize(n))\n            rares = append(rares, n)\n        } else {\n            for _, num := range dis[level] {\n                di[level] = num\n                fnpr(cand, di, dis, indices, nmr, nd, level+1)\n            }\n        }\n    }\n\n    \n    var fnmr func(cand []int8, list [][]int8, indices [][2]int8, nd, level int)\n    fnmr = func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) {\n        if level == len(list) {\n            var nmr, nmr2 uint64\n            for i, t := range allTerms[nd-2] {\n                if cand[i] >= 0 {\n                    nmr += t.coeff * uint64(cand[i])\n                } else {\n                    nmr2 += t.coeff * uint64(-cand[i])\n                    if nmr >= nmr2 {\n                        nmr -= nmr2\n                        nmr2 = 0\n                    } else {\n                        nmr2 -= nmr\n                        nmr = 0\n                    }\n                }\n            }\n            if nmr2 >= nmr {\n                return\n            }\n            nmr -= nmr2\n            if !isSquare(nmr) {\n                return\n            }\n            var dis [][]int8\n            dis = append(dis, seq(0, int8(len(fml[cand[0]]))-1, 1))\n            for i := 1; i < len(cand); i++ {\n                dis = append(dis, seq(0, int8(len(dmd[cand[i]]))-1, 1))\n            }\n            if nd%2 == 1 {\n                dis = append(dis, il)\n            }\n            di := make([]int8, len(dis))\n            fnpr(cand, di, dis, indices, nmr, nd, 0)\n        } else {\n            for _, num := range list[level] {\n                cand[level] = num\n                fnmr(cand, list, indices, nd, level+1)\n            }\n        }\n    }\n\n    for nd := 2; nd <= maxDigits; nd++ {\n        digits = make([]int8, nd)\n        if nd == 4 {\n            lists[0] = append(lists[0], zl)\n            lists[1] = append(lists[1], ol)\n            lists[2] = append(lists[2], el)\n            lists[3] = append(lists[3], ol)\n        } else if len(allTerms[nd-2]) > len(lists[0]) {\n            for i := 0; i < 4; i++ {\n                lists[i] = append(lists[i], dl)\n            }\n        }\n        var indices [][2]int8\n        for _, t := range allTerms[nd-2] {\n            indices = append(indices, [2]int8{t.ix1, t.ix2})\n        }\n        for _, list := range lists {\n            cand := make([]int8, len(list))\n            fnmr(cand, list, indices, nd, 0)\n        }\n        ms := uint64(time.Since(start).Milliseconds())\n        fmt.Printf(\"  %2d digits:  %9s ms\\n\", nd, commatize(ms))\n    }\n\n    sort.Slice(rares, func(i, j int) bool { return rares[i] < rares[j] })\n    fmt.Printf(\"\\nThe rare numbers with up to %d digits are:\\n\", maxDigits)\n    for i, rare := range rares {\n        fmt.Printf(\"  %2d:  %25s\\n\", i+1, commatize(rare))\n    }\n}\n"}
{"id": 58437, "name": "Find words which contain the most consonants", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n"}
{"id": 58438, "name": "Find words which contain the most consonants", "Python": "print('\\n'.join((f'{x[0]}: {\" \".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in\n      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)\n      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]\n      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc contains(list []int, value int) bool {\n    for _, v := range list {\n        if v == value {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 10 {\n            words = append(words, s)\n        }\n    }\n    vowelIndices := []int{0, 4, 8, 14, 20}\n    wordGroups := make([][]string, 12)\n    for _, word := range words {\n        letters := make([]int, 26)\n        for _, c := range word {\n            index := c - 97\n            if index >= 0 && index < 26 {\n                letters[index]++\n            }\n        }\n        eligible := true\n        uc := 0 \n        for i := 0; i < 26; i++ {\n            if !contains(vowelIndices, i) {\n                if letters[i] > 1 {\n                    eligible = false\n                    break\n                } else if letters[i] == 1 {\n                    uc++\n                }\n            }\n        }\n        if eligible {\n            wordGroups[uc] = append(wordGroups[uc], word)\n        }\n    }\n\n    for i := 11; i >= 0; i-- {\n        count := len(wordGroups[i])\n        if count > 0 {\n            s := \"s\"\n            if count == 1 {\n                s = \"\"\n            }\n            fmt.Printf(\"%d word%s found with %d unique consonants:\\n\", count, s, i)\n            for j := 0; j < count; j++ {\n                fmt.Printf(\"%-15s\", wordGroups[i][j])\n                if j > 0 && (j+1)%5 == 0 {\n                    fmt.Println()\n                }\n            }\n            fmt.Println()\n            if count%5 != 0 {\n                fmt.Println()\n            }\n        }\n    }\n}\n"}
{"id": 58439, "name": "Prime words", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n"}
{"id": 58440, "name": "Prime words", "Python": "for i in range(65,123):\n  check = 1\n  for j in range(2,i):\n    if i%j == 0:\n     check = 0\n  if check==1:\n   print(chr(i),end='')\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc isPrime(n int) bool {\n    if n < 2 {\n        return false\n    }\n    if n%2 == 0 {\n        return n == 2\n    }\n    if n%3 == 0 {\n        return n == 3\n    }\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\nfunc main() {\n    \n    var primeRunes []rune\n    for i := 33; i < 256; i += 2 {\n        if isPrime(i) {\n            primeRunes = append(primeRunes, rune(i))\n        }\n    }\n    primeString := string(primeRunes)\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    fmt.Println(\"Prime words in\", wordList, \"are:\")\n    for _, bword := range bwords {\n        word := string(bword)\n        ok := true\n        for _, c := range word {\n            if !strings.ContainsRune(primeString, c) {\n                ok = false\n                break\n            }\n        }\n        if ok {\n            fmt.Println(word)\n        }\n    }\n}\n"}
{"id": 58441, "name": "Numbers which are the cube roots of the product of their proper divisors", "Python": "\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n    if num * num * num == divprod:\n        FOUND += 1\n        if FOUND <= 50:\n            print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n        if FOUND == 500:\n            print(f'\\nFive hundreth: {num:,}')\n        if FOUND == 5000:\n            print(f'\\nFive thousandth: {num:,}')\n        if FOUND == 50000:\n            print(f'\\nFifty thousandth: {num:,}')\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc divisorCount(n int) int {\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    count := 0\n    sqrt := int(math.Sqrt(float64(n)))\n    for i := 1; i <= sqrt; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    var numbers50 []int\n    count := 0\n    for n := 1; count < 50000; n++ {\n        dc := divisorCount(n)\n        if n == 1 || dc == 8 {\n            count++\n            if count <= 50 {\n                numbers50 = append(numbers50, n)\n                if count == 50 {\n                    rcu.PrintTable(numbers50, 10, 3, false)\n                }\n            } else if count == 500 {\n                fmt.Printf(\"\\n500th   : %s\", rcu.Commatize(n))\n            } else if count == 5000 {\n                fmt.Printf(\"\\n5,000th : %s\", rcu.Commatize(n))\n            } else if count == 50000 {\n                fmt.Printf(\"\\n50,000th: %s\\n\", rcu.Commatize(n))\n            }\n        }\n    }\n}\n"}
{"id": 58442, "name": "Numbers which are the cube roots of the product of their proper divisors", "Python": "\n\nfrom functools import reduce\nfrom sympy import divisors\n\n\nFOUND = 0\nfor num in range(1, 1_000_000):\n    divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1\n    if num * num * num == divprod:\n        FOUND += 1\n        if FOUND <= 50:\n            print(f'{num:5}', end='\\n' if FOUND % 10 == 0 else '')\n        if FOUND == 500:\n            print(f'\\nFive hundreth: {num:,}')\n        if FOUND == 5000:\n            print(f'\\nFive thousandth: {num:,}')\n        if FOUND == 50000:\n            print(f'\\nFifty thousandth: {num:,}')\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc divisorCount(n int) int {\n    k := 1\n    if n%2 == 1 {\n        k = 2\n    }\n    count := 0\n    sqrt := int(math.Sqrt(float64(n)))\n    for i := 1; i <= sqrt; i += k {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    var numbers50 []int\n    count := 0\n    for n := 1; count < 50000; n++ {\n        dc := divisorCount(n)\n        if n == 1 || dc == 8 {\n            count++\n            if count <= 50 {\n                numbers50 = append(numbers50, n)\n                if count == 50 {\n                    rcu.PrintTable(numbers50, 10, 3, false)\n                }\n            } else if count == 500 {\n                fmt.Printf(\"\\n500th   : %s\", rcu.Commatize(n))\n            } else if count == 5000 {\n                fmt.Printf(\"\\n5,000th : %s\", rcu.Commatize(n))\n            } else if count == 50000 {\n                fmt.Printf(\"\\n50,000th: %s\\n\", rcu.Commatize(n))\n            }\n        }\n    }\n}\n"}
{"id": 58443, "name": "Ormiston triples", "Python": "import textwrap\n\nfrom itertools import pairwise\nfrom typing import Iterator\nfrom typing import List\n\nimport primesieve\n\n\ndef primes() -> Iterator[int]:\n    it = primesieve.Iterator()\n    while True:\n        yield it.next_prime()\n\n\ndef triplewise(iterable):\n    for (a, _), (b, c) in pairwise(pairwise(iterable)):\n        yield a, b, c\n\n\ndef is_anagram(a: int, b: int, c: int) -> bool:\n    return sorted(str(a)) == sorted(str(b)) == sorted(str(c))\n\n\ndef up_to_one_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 1_000_000_000:\n            break\n    return count\n\n\ndef up_to_ten_billion() -> int:\n    count = 0\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            count += 1\n        if triple[2] >= 10_000_000_000:\n            break\n    return count\n\n\ndef first_25() -> List[int]:\n    rv: List[int] = []\n    for triple in triplewise(primes()):\n        if is_anagram(*triple):\n            rv.append(triple[0])\n            if len(rv) >= 25:\n                break\n    return rv\n\n\nif __name__ == \"__main__\":\n    print(\"Smallest members of first 25 Ormiston triples:\")\n    print(textwrap.fill(\" \".join(str(i) for i in first_25())), \"\\n\")\n    print(up_to_one_billion(), \"Ormiston triples before 1,000,000,000\")\n    print(up_to_ten_billion(), \"Ormiston triples before 10,000,000,000\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    const limit = 1e10\n    primes := rcu.Primes(limit)\n    var orm25 []int\n    j := int(1e9)\n    count := 0\n    var counts []int\n    for i := 0; i < len(primes)-2; i++ {\n        p1 := primes[i]\n        p2 := primes[i+1]\n        p3 := primes[i+2]\n        if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {\n            continue\n        }\n        key1 := 1\n        for _, dig := range rcu.Digits(p1, 10) {\n            key1 *= primes[dig]\n        }\n        key2 := 1\n        for _, dig := range rcu.Digits(p2, 10) {\n            key2 *= primes[dig]\n        }\n        if key1 != key2 {\n            continue\n        }\n        key3 := 1\n        for _, dig := range rcu.Digits(p3, 10) {\n            key3 *= primes[dig]\n        }\n        if key2 == key3 {\n            if count < 25 {\n                orm25 = append(orm25, p1)\n            }\n            if p1 >= j {\n                counts = append(counts, count)\n                j *= 10\n            }\n            count++\n        }\n    }\n    counts = append(counts, count)\n    fmt.Println(\"Smallest members of first 25 Ormiston triples:\")\n    for i := 0; i < 25; i++ {\n        fmt.Printf(\"%8v \", orm25[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    j = int(1e9)\n    for i := 0; i < len(counts); i++ {\n        fmt.Printf(\"%s Ormiston triples before %s\\n\", rcu.Commatize(counts[i]), rcu.Commatize(j))\n        j *= 10\n        fmt.Println()\n    }\n}\n"}
{"id": 58444, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\ntype cell struct {\n    isMine  bool\n    display byte \n}\n\nconst lMargin = 4\n\nvar (\n    grid        [][]cell\n    mineCount   int\n    minesMarked int\n    isGameOver  bool\n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc makeGrid(n, m int) {\n    if n <= 0 || m <= 0 {\n        panic(\"Grid dimensions must be positive.\")\n    }\n    grid = make([][]cell, n)\n    for i := 0; i < n; i++ {\n        grid[i] = make([]cell, m)\n        for j := 0; j < m; j++ {\n            grid[i][j].display = '.'\n        }\n    }\n    min := int(math.Round(float64(n*m) * 0.1)) \n    max := int(math.Round(float64(n*m) * 0.2)) \n    mineCount = min + rand.Intn(max-min+1)\n    rm := mineCount\n    for rm > 0 {\n        x, y := rand.Intn(n), rand.Intn(m)\n        if !grid[x][y].isMine {\n            rm--\n            grid[x][y].isMine = true\n        }\n    }\n    minesMarked = 0\n    isGameOver = false\n}\n\nfunc displayGrid(isEndOfGame bool) {\n    if !isEndOfGame {\n        fmt.Println(\"Grid has\", mineCount, \"mine(s),\", minesMarked, \"mine(s) marked.\")\n    }\n    margin := strings.Repeat(\" \", lMargin)\n    fmt.Print(margin, \" \")\n    for i := 1; i <= len(grid); i++ {\n        fmt.Print(i)\n    }\n    fmt.Println()\n    fmt.Println(margin, strings.Repeat(\"-\", len(grid)))\n    for y := 0; y < len(grid[0]); y++ {\n        fmt.Printf(\"%*d:\", lMargin, y+1)\n        for x := 0; x < len(grid); x++ {\n            fmt.Printf(\"%c\", grid[x][y].display)\n        }\n        fmt.Println()\n    }\n}\n\nfunc endGame(msg string) {\n    isGameOver = true\n    fmt.Println(msg)\n    ans := \"\"\n    for ans != \"y\" && ans != \"n\" {\n        fmt.Print(\"Another game (y/n)? : \")\n        scanner.Scan()\n        ans = strings.ToLower(scanner.Text())\n    }\n    if scanner.Err() != nil || ans == \"n\" {\n        return\n    }\n    makeGrid(6, 4)\n    displayGrid(false)\n}\n\nfunc resign() {\n    found := 0\n    for y := 0; y < len(grid[0]); y++ {\n        for x := 0; x < len(grid); x++ {\n            if grid[x][y].isMine {\n                if grid[x][y].display == '?' {\n                    grid[x][y].display = 'Y'\n                    found++\n                } else if grid[x][y].display != 'x' {\n                    grid[x][y].display = 'N'\n                }\n            }\n        }\n    }\n    displayGrid(true)\n    msg := fmt.Sprint(\"You found \", found, \" out of \", mineCount, \" mine(s).\")\n    endGame(msg)\n}\n\nfunc usage() {\n    fmt.Println(\"h or ? - this help,\")\n    fmt.Println(\"c x y  - clear cell (x,y),\")\n    fmt.Println(\"m x y  - marks (toggles) cell (x,y),\")\n    fmt.Println(\"n      - start a new game,\")\n    fmt.Println(\"q      - quit/resign the game,\")\n    fmt.Println(\"where x is the (horizontal) column number and y is the (vertical) row number.\\n\")\n}\n\nfunc markCell(x, y int) {\n    if grid[x][y].display == '?' {\n        minesMarked--\n        grid[x][y].display = '.'\n    } else if grid[x][y].display == '.' {\n        minesMarked++\n        grid[x][y].display = '?'\n    }\n}\n\nfunc countAdjMines(x, y int) int {\n    count := 0\n    for j := y - 1; j <= y+1; j++ {\n        if j >= 0 && j < len(grid[0]) {\n            for i := x - 1; i <= x+1; i++ {\n                if i >= 0 && i < len(grid) {\n                    if grid[i][j].isMine {\n                        count++\n                    }\n                }\n            }\n        }\n    }\n    return count\n}\n\nfunc clearCell(x, y int) bool {\n    if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {\n        if grid[x][y].display == '.' {\n            if !grid[x][y].isMine {\n                count := countAdjMines(x, y)\n                if count > 0 {\n                    grid[x][y].display = string(48 + count)[0]\n                } else {\n                    grid[x][y].display = ' '\n                    clearCell(x+1, y)\n                    clearCell(x+1, y+1)\n                    clearCell(x, y+1)\n                    clearCell(x-1, y+1)\n                    clearCell(x-1, y)\n                    clearCell(x-1, y-1)\n                    clearCell(x, y-1)\n                    clearCell(x+1, y-1)\n                }\n            } else {\n                grid[x][y].display = 'x'\n                fmt.Println(\"Kaboom! You lost!\")\n                return false\n            }\n        }\n    }\n    return true\n}\n\nfunc testForWin() bool {\n    isCleared := false\n    if minesMarked == mineCount {\n        isCleared = true\n        for x := 0; x < len(grid); x++ {\n            for y := 0; y < len(grid[0]); y++ {\n                if grid[x][y].display == '.' {\n                    isCleared = false\n                }\n            }\n        }\n    }\n    if isCleared {\n        fmt.Println(\"You won!\")\n    }\n    return isCleared\n}\n\nfunc splitAction(action string) (int, int, bool) {\n    fields := strings.Fields(action)\n    if len(fields) != 3 {\n        return 0, 0, false\n    }\n    x, err := strconv.Atoi(fields[1])\n    if err != nil || x < 1 || x > len(grid) {\n        return 0, 0, false\n    }\n    y, err := strconv.Atoi(fields[2])\n    if err != nil || y < 1 || y > len(grid[0]) {\n        return 0, 0, false\n    }\n    return x, y, true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    usage()\n    makeGrid(6, 4)\n    displayGrid(false)\n    for !isGameOver {\n        fmt.Print(\"\\n>\")\n        scanner.Scan()\n        action := strings.ToLower(scanner.Text())\n        if scanner.Err() != nil || len(action) == 0 {\n            continue\n        }\n        switch action[0] {\n        case 'h', '?':\n            usage()\n        case 'n':\n            makeGrid(6, 4)\n            displayGrid(false)\n        case 'c':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            if clearCell(x-1, y-1) {\n                displayGrid(false)\n                if testForWin() {\n                    resign()\n                }\n            } else {\n                resign()\n            }\n        case 'm':\n            x, y, ok := splitAction(action)\n            if !ok {\n                continue\n            }\n            markCell(x-1, y-1)\n            displayGrid(false)\n            if testForWin() {\n                resign()\n            }\n        case 'q':\n            resign()\n        }\n    }\n}\n"}
{"id": 58445, "name": "Elementary cellular automaton_Infinite length", "Python": "def _notcell(c):\n    return '0' if c == '1' else '1'\n\ndef eca_infinite(cells, rule):\n    lencells = len(cells)\n    rulebits = '{0:08b}'.format(rule)\n    neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n    c = cells\n    while True:\n        yield c\n        c = _notcell(c[0])*2 + c + _notcell(c[-1])*2    \n\n        c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))\n        \n\nif __name__ == '__main__':\n    lines = 25\n    for rule in (90, 30):\n        print('\\nRule: %i' % rule)\n        for i, c in zip(range(lines), eca_infinite('1', rule)):\n            print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc evolve(l, rule int) {\n    fmt.Printf(\" Rule #%d:\\n\", rule)\n    cells := \"O\"\n    for x := 0; x < l; x++ {\n        cells = addNoCells(cells)\n        width := 40 + (len(cells) >> 1)\n        fmt.Printf(\"%*s\\n\", width, cells)\n        cells = step(cells, rule)\n    }\n}\n\nfunc step(cells string, rule int) string {\n    newCells := new(strings.Builder)\n    for i := 0; i < len(cells)-2; i++ {\n        bin := 0\n        b := uint(2)\n        for n := i; n < i+3; n++ {\n            bin += btoi(cells[n] == 'O') << b\n            b >>= 1\n        }\n        a := '.'\n        if rule&(1<<uint(bin)) != 0 {\n            a = 'O'\n        }\n        newCells.WriteRune(a)\n    }\n    return newCells.String()\n}\n\nfunc addNoCells(cells string) string {\n    l, r := \"O\", \"O\"\n    if cells[0] == 'O' {\n        l = \".\"\n    }\n    if cells[len(cells)-1] == 'O' {\n        r = \".\"\n    }\n    cells = l + cells + r\n    cells = l + cells + r\n    return cells\n}\n\nfunc main() {\n    for _, r := range []int{90, 30} {\n        evolve(25, r)\n        fmt.Println()\n    }\n}\n"}
{"id": 58446, "name": "Execute CopyPasta Language", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n"}
{"id": 58447, "name": "Execute CopyPasta Language", "Python": "import sys\n\n\ndef fatal_error(errtext):\n\tprint(\"%\" + errtext)\n\tprint(\"usage: \" + sys.argv[0] + \" [filename.cp]\")\n\tsys.exit(1)\n\n\nfname = None\nsource = None\ntry:\n\tfname = sys.argv[1]\n\tsource = open(fname).read()\nexcept:\n\tfatal_error(\"error while trying to read from specified file\")\n\n\nlines = source.split(\"\\n\")\n\n\nclipboard = \"\"\n\n\nloc = 0\nwhile(loc < len(lines)):\n\t\n\tcommand = lines[loc].strip()\n\n\ttry:\n\t\tif(command == \"Copy\"):\n\t\t\tclipboard += lines[loc + 1]\n\t\telif(command == \"CopyFile\"):\n\t\t\tif(lines[loc + 1] == \"TheF*ckingCode\"):\n\t\t\t\tclipboard += source\n\t\t\telse:\n\t\t\t\tfiletext = open(lines[loc+1]).read()\n\t\t\t\tclipboard += filetext\n\t\telif(command == \"Duplicate\"):\n\t\t\tclipboard += clipboard * ((int(lines[loc + 1])) - 1)\n\t\telif(command == \"Pasta!\"):\n\t\t\tprint(clipboard)\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + str(loc + 1))\n\texcept Exception as e:\n\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + str(loc + 1) + \": \" + e)\n\n\t\n\tloc += 2\n", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n"}
{"id": 58448, "name": "Even numbers which cannot be expressed as the sum of two twin primes", "Python": "\n\nfrom sympy import sieve\n\n\ndef nonpairsums(include1=False, limit=20_000):\n    \n    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)\n            for i in range(limit+2)]\n    if include1:\n        tpri[1] = True\n    twinsums = [False] * (limit * 2)\n    for i in range(limit):\n        for j in range(limit-i+1):\n            if tpri[i] and tpri[j]:\n                twinsums[i + j] = True\n\n    return [i for i in range(2, limit+1, 2) if not twinsums[i]]\n\n\nprint('Non twin prime sums:')\nfor k, p in enumerate(nonpairsums()):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n\nprint('\\n\\nNon twin prime sums (including 1):')\nfor k, p in enumerate(nonpairsums(include1=True)):\n    print(f'{p:6}', end='\\n' if (k + 1) % 10 == 0 else '')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst limit = 100000 \n\nfunc nonTwinSums(twins []int) []int {\n    sieve := make([]bool, limit+1)\n    for i := 0; i < len(twins); i++ {\n        for j := i; j < len(twins); j++ {\n            sum := twins[i] + twins[j]\n            if sum > limit {\n                break\n            }\n            sieve[sum] = true\n        }\n    }\n    var res []int\n    for i := 2; i < limit; i += 2 {\n        if !sieve[i] {\n            res = append(res, i)\n        }\n    }\n    return res\n}\n\nfunc main() {\n    primes := rcu.Primes(limit)[2:] \n    twins := []int{3}\n    for i := 0; i < len(primes)-1; i++ {\n        if primes[i+1]-primes[i] == 2 {\n            if twins[len(twins)-1] != primes[i] {\n                twins = append(twins, primes[i])\n            }\n            twins = append(twins, primes[i+1])\n        }\n    }\n    fmt.Println(\"Non twin prime sums:\")\n    ntps := nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n\n    fmt.Println(\"\\nNon twin prime sums (including 1):\")\n    twins = append([]int{1}, twins...)\n    ntps = nonTwinSums(twins)\n    rcu.PrintTable(ntps, 10, 4, false)\n    fmt.Println(\"Found\", len(ntps))\n}\n"}
{"id": 58449, "name": "Primes with digits in nondecreasing order", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n"}
{"id": 58450, "name": "Primes with digits in nondecreasing order", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc nonDescending(p int) bool {\n    var digits []int\n    for p > 0 {\n        digits = append(digits, p%10)\n        p = p / 10\n    }\n    for i := 0; i < len(digits)-1; i++ {\n        if digits[i+1] > digits[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    primes := rcu.Primes(999)\n    var nonDesc []int\n    for _, p := range primes {\n        if nonDescending(p) {\n            nonDesc = append(nonDesc, p)\n        }\n    }\n    fmt.Println(\"Primes below 1,000 with digits in non-decreasing order:\")\n    for i, n := range nonDesc {\n        fmt.Printf(\"%3d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such primes found.\\n\", len(nonDesc))\n}\n"}
{"id": 58451, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 58452, "name": "Minimal steps down to 1", "Python": "from functools import lru_cache\n\n\n\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n    \"Recursive, memoised minimised steps to 1\"\n\n    def __init__(self, divs=DIVS, subs=SUBS):\n        self.divs, self.subs = divs, subs\n\n    @lru_cache(maxsize=None)\n    def _minrec(self, n):\n        \"Recursive, memoised\"\n        if n == 1:\n            return 0, ['=1']\n        possibles = {}\n        for d in self.divs:\n            if n % d == 0:\n                possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n        for s in self.subs:\n            if n > s:\n                possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n        thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n        ret = 1 + count, [thiskind] + otherkinds\n        return ret\n\n    def __call__(self, n):\n        \"Recursive, memoised\"\n        ans = self._minrec(n)[1][:-1]\n        return len(ans), ans\n\n\nif __name__ == '__main__':\n    for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n        minrec = Minrec(DIVS, SUBS)\n        print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n        print('  Possible divisors:  ', DIVS)\n        print('  Possible decrements:', SUBS)\n        for n in range(1, 11):\n            steps, how = minrec(n)\n            print(f'    minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n        upto = 2000\n        print(f'\\n    Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n        stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n        mx = stepn[-1][0]\n        ans = [x[1] for x in stepn if x[0] == mx]\n        print('      Taking', mx, f'steps is/are the {len(ans)} numbers:',\n              ', '.join(str(n) for n in sorted(ans)))\n        \n        print()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n    divs, subs []int\n    mins       [][]string\n)\n\n\nfunc minsteps(n int) {\n    if n == 1 {\n        mins[1] = []string{}\n        return\n    }\n    min := limit\n    var p, q int\n    var op byte\n    for _, div := range divs {\n        if n%div == 0 {\n            d := n / div\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, div, '/'\n            }\n        }\n    }\n    for _, sub := range subs {\n        if d := n - sub; d >= 1 {\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, sub, '-'\n            }\n        }\n    }\n    mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n    mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n    for r := 0; r < 2; r++ {\n        divs = []int{2, 3}\n        if r == 0 {\n            subs = []int{1}\n        } else {\n            subs = []int{2}\n        }\n        mins = make([][]string, limit+1)\n        fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n        fmt.Println(\"  Minimum number of steps to diminish the following numbers down to 1 is:\")\n        for i := 1; i <= limit; i++ {\n            minsteps(i)\n            if i <= 10 {\n                steps := len(mins[i])\n                plural := \"s\"\n                if steps == 1 {\n                    plural = \" \"\n                }\n                fmt.Printf(\"    %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n            }\n        }\n        for _, lim := range []int{2000, 20000, 50000} {\n            max := 0\n            for _, min := range mins[0 : lim+1] {\n                m := len(min)\n                if m > max {\n                    max = m\n                }\n            }\n            var maxs []int\n            for i, min := range mins[0 : lim+1] {\n                if len(min) == max {\n                    maxs = append(maxs, i)\n                }\n            }\n            nums := len(maxs)\n            verb, verb2, plural := \"are\", \"have\", \"s\"\n            if nums == 1 {\n                verb, verb2, plural = \"is\", \"has\", \"\"\n            }\n            fmt.Printf(\"  There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n            fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n            fmt.Println(\"   \", maxs)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 58453, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n"}
{"id": 58454, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 58455, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 58456, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n"}
{"id": 58457, "name": "Idoneal numbers", "Python": "\n\n\ndef is_idoneal(num):\n    \n    for a in range(1, num):\n        for b in range(a + 1, num):\n            if a * b + a + b > num:\n                break\n            for c in range(b + 1, num):\n                sum3 = a * b + b * c + a * c\n                if sum3 == num:\n                    return False\n                if sum3 > num:\n                    break\n    return True\n\n\nrow = 0\nfor n in range(1, 2000):\n    if is_idoneal(n):\n        row += 1\n        print(f'{n:5}', end='\\n' if row % 13 == 0 else '')\n", "Go": "package main\n\nimport \"rcu\"\n\nfunc isIdoneal(n int) bool {\n    for a := 1; a < n; a++ {\n        for b := a + 1; b < n; b++ {\n            if a*b+a+b > n {\n                break\n            }\n            for c := b + 1; c < n; c++ {\n                sum := a*b + b*c + a*c\n                if sum == n {\n                    return false\n                }\n                if sum > n {\n                    break\n                }\n            }\n        }\n    }\n    return true\n}\n\nfunc main() {\n    var idoneals []int\n    for n := 1; n <= 1850; n++ {\n        if isIdoneal(n) {\n            idoneals = append(idoneals, n)\n        }\n    }\n    rcu.PrintTable(idoneals, 13, 4, false)\n}\n"}
{"id": 58458, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 58459, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n"}
{"id": 58460, "name": "Dynamic variable names", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n"}
{"id": 58461, "name": "Data Encryption Standard", "Python": "\n\n\n\nIP = (\n    58, 50, 42, 34, 26, 18, 10, 2,\n    60, 52, 44, 36, 28, 20, 12, 4,\n    62, 54, 46, 38, 30, 22, 14, 6,\n    64, 56, 48, 40, 32, 24, 16, 8,\n    57, 49, 41, 33, 25, 17, 9,  1,\n    59, 51, 43, 35, 27, 19, 11, 3,\n    61, 53, 45, 37, 29, 21, 13, 5,\n    63, 55, 47, 39, 31, 23, 15, 7\n)\nIP_INV = (\n    40,  8, 48, 16, 56, 24, 64, 32,\n    39,  7, 47, 15, 55, 23, 63, 31,\n    38,  6, 46, 14, 54, 22, 62, 30,\n    37,  5, 45, 13, 53, 21, 61, 29,\n    36,  4, 44, 12, 52, 20, 60, 28,\n    35,  3, 43, 11, 51, 19, 59, 27,\n    34,  2, 42, 10, 50, 18, 58, 26,\n    33,  1, 41,  9, 49, 17, 57, 25\n)\nPC1 = (\n    57, 49, 41, 33, 25, 17, 9,\n    1,  58, 50, 42, 34, 26, 18,\n    10, 2,  59, 51, 43, 35, 27,\n    19, 11, 3,  60, 52, 44, 36,\n    63, 55, 47, 39, 31, 23, 15,\n    7,  62, 54, 46, 38, 30, 22,\n    14, 6,  61, 53, 45, 37, 29,\n    21, 13, 5,  28, 20, 12, 4\n)\nPC2 = (\n    14, 17, 11, 24, 1,  5,\n    3,  28, 15, 6,  21, 10,\n    23, 19, 12, 4,  26, 8,\n    16, 7,  27, 20, 13, 2,\n    41, 52, 31, 37, 47, 55,\n    30, 40, 51, 45, 33, 48,\n    44, 49, 39, 56, 34, 53,\n    46, 42, 50, 36, 29, 32\n)\n\nE  = (\n    32, 1,  2,  3,  4,  5,\n    4,  5,  6,  7,  8,  9,\n    8,  9,  10, 11, 12, 13,\n    12, 13, 14, 15, 16, 17,\n    16, 17, 18, 19, 20, 21,\n    20, 21, 22, 23, 24, 25,\n    24, 25, 26, 27, 28, 29,\n    28, 29, 30, 31, 32, 1\n)\n\nSboxes = {\n    0: (\n        14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7,\n        0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8,\n        4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0,\n        15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13\n    ),\n    1: (\n        15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10,\n        3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5,\n        0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15,\n        13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9 \n    ),\n    2: (\n        10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8,\n        13,  7,  0,  9,  3,  4,  6, 10,  2,  8,  5, 14, 12, 11, 15,  1,\n        13,  6,  4,  9,  8, 15,  3,  0, 11,  1,  2, 12,  5, 10, 14,  7,\n        1, 10, 13,  0,  6,  9,  8,  7,  4, 15, 14,  3, 11,  5,  2, 12 \n    ),\n    3: (\n        7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15,\n        13,  8, 11,  5,  6, 15,  0,  3,  4,  7,  2, 12,  1, 10, 14,  9,\n        10,  6,  9,  0, 12, 11,  7, 13, 15,  1,  3, 14,  5,  2,  8,  4,\n        3, 15,  0,  6, 10,  1, 13,  8,  9,  4,  5, 11, 12,  7,  2, 14\n    ),\n    4: (\n        2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9,\n        14, 11,  2, 12,  4,  7, 13,  1,  5,  0, 15, 10,  3,  9,  8,  6,\n        4,  2,  1, 11, 10, 13,  7,  8, 15,  9, 12,  5,  6,  3,  0, 14,\n        11,  8, 12,  7,  1, 14,  2, 13,  6, 15,  0,  9, 10,  4,  5,  3\n    ),\n    5: (\n        12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11,\n        10, 15,  4,  2,  7, 12,  9,  5,  6,  1, 13, 14,  0, 11,  3,  8,\n        9, 14, 15,  5,  2,  8, 12,  3,  7,  0,  4, 10,  1, 13, 11,  6,\n        4,  3,  2, 12,  9,  5, 15, 10, 11, 14,  1,  7,  6,  0,  8, 13\n    ),\n    6: (\n        4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1,\n        13,  0, 11,  7,  4,  9,  1, 10, 14,  3,  5, 12,  2, 15,  8,  6,\n        1,  4, 11, 13, 12,  3,  7, 14, 10, 15,  6,  8,  0,  5,  9,  2,\n        6, 11, 13,  8,  1,  4, 10,  7,  9,  5,  0, 15, 14,  2,  3, 12\n    ),\n    7: (\n        13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7,\n        1, 15, 13,  8, 10,  3,  7,  4, 12,  5,  6, 11,  0, 14,  9,  2,\n        7, 11,  4,  1,  9, 12, 14,  2,  0,  6, 10, 13, 15,  3,  5,  8,\n        2,  1, 14,  7,  4, 10,  8, 13, 15, 12,  9,  0,  3,  5,  6, 11\n    )\n}\n\nP = (\n    16,  7, 20, 21,\n    29, 12, 28, 17,\n    1, 15, 23, 26,\n    5, 18, 31, 10,\n    2,  8, 24, 14,\n    32, 27,  3,  9,\n    19, 13, 30,  6,\n    22, 11, 4,  25\n)\n    \ndef encrypt(msg, key, decrypt=False):\n    \n    assert isinstance(msg, int) and isinstance(key, int)\n    assert not msg.bit_length() > 64\n    assert not key.bit_length() > 64\n\n    \n    key = permutation_by_table(key, 64, PC1) \n\n    \n    \n    C0 = key >> 28\n    D0 = key & (2**28-1)\n    round_keys = generate_round_keys(C0, D0) \n\n    msg_block = permutation_by_table(msg, 64, IP)\n    L0 = msg_block >> 32\n    R0 = msg_block & (2**32-1)\n\n    \n    L_last = L0\n    R_last = R0\n    for i in range(1,17):\n        if decrypt: \n            i = 17-i\n        L_round = R_last\n        R_round = L_last ^ round_function(R_last, round_keys[i])\n        L_last = L_round\n        R_last = R_round\n\n    \n    cipher_block = (R_round<<32) + L_round\n\n    \n    cipher_block = permutation_by_table(cipher_block, 64, IP_INV)\n\n    return cipher_block\n\ndef round_function(Ri, Ki):\n    \n    Ri = permutation_by_table(Ri, 32, E)\n\n    \n    Ri ^= Ki\n\n    \n    Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)]\n\n    \n    for i, block in enumerate(Ri_blocks):\n        \n        row = ((0b100000 & block) >> 4) + (0b1 & block)\n        col = (0b011110 & block) >> 1\n        \n        Ri_blocks[i] = Sboxes[i][16*row+col]\n\n    \n    Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0))\n    Ri = 0\n    for block, lshift_val in Ri_blocks:\n        Ri += (block << lshift_val)\n\n    \n    Ri = permutation_by_table(Ri, 32, P)\n\n    return Ri\n\ndef permutation_by_table(block, block_len, table):\n    \n    block_str = bin(block)[2:].zfill(block_len)\n    perm = []\n    for pos in range(len(table)):\n        perm.append(block_str[table[pos]-1])\n    return int(''.join(perm), 2)\n\ndef generate_round_keys(C0, D0):\n    \n\n    round_keys = dict.fromkeys(range(0,17))\n    lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1)\n\n    \n    lrot = lambda val, r_bits, max_bits: \\\n    (val << r_bits%max_bits) & (2**max_bits-1) | \\\n    ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))\n\n    \n    C0 = lrot(C0, 0, 28)\n    D0 = lrot(D0, 0, 28)\n    round_keys[0] = (C0, D0)\n\n    \n    for i, rot_val in enumerate(lrot_values):\n        i+=1\n        Ci = lrot(round_keys[i-1][0], rot_val, 28)\n        Di = lrot(round_keys[i-1][1], rot_val, 28)\n        round_keys[i] = (Ci, Di)\n\n    \n    \n    \n    del round_keys[0]\n\n    \n    for i, (Ci, Di) in round_keys.items():\n        Ki = (Ci << 28) + Di\n        round_keys[i] = permutation_by_table(Ki, 56, PC2) \n\n    return round_keys\n\nk = 0x0e329232ea6d0d73 \nk2 = 0x133457799BBCDFF1\nm = 0x8787878787878787\nm2 = 0x0123456789ABCDEF\n\ndef prove(key, msg):\n    print('key:       {:x}'.format(key))\n    print('message:   {:x}'.format(msg))\n    cipher_text = encrypt(msg, key)\n    print('encrypted: {:x}'.format(cipher_text))\n    plain_text = encrypt(cipher_text, key, decrypt=True)\n    print('decrypted: {:x}'.format(plain_text))\n\nprove(k, m)\nprint('----------')\nprove(k2, m2)\n", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n"}
{"id": 58462, "name": "Fibonacci matrix-exponentiation", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 58463, "name": "Fibonacci matrix-exponentiation", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n"}
{"id": 58464, "name": "Largest palindrome product", "Python": "\n\nT=[set([(0, 0)])]\n\ndef double(it):\n    for a, b in it:\n        yield a, b\n        yield b, a\n\ndef tails(n):\n    \n    if len(T)<=n:\n        l = set()\n        for i in range(10):\n            for j in range(i, 10):\n                I = i*10**(n-1)\n                J = j*10**(n-1)\n                it = tails(n-1)\n                if I!=J: it = double(it)\n                for t1, t2 in it:\n                    if ((I+t1)*(J+t2)+1)%10**n == 0:\n                        l.add((I+t1, J+t2))\n        T.append(l)\n    return T[n]\n\ndef largestPalindrome(n):\n    \n    m, tail = 0, n // 2\n    head = n - tail\n    up = 10**head\n    for L in range(1, 9*10**(head-1)+1):\n        \n        m = 0\n        sol = None\n        for i in range(1, L + 1):\n            lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)\n            hi = int(up - (up - L)**2 / (up - i))\n            for j in range(lo, hi + 1):\n                I = (up-i) * 10**tail\n                J = (up-j) * 10**tail\n                it = tails(tail)\n                if I!=J: it = double(it)\n                    for t1, t2 in it:\n                        val = (I + t1)*(J + t2)\n                        s = str(val)\n                        if s == s[::-1] and val>m:\n                            sol = (I + t1, J + t2)\n                            m = val\n\n        if m:\n            print(\"{:2d}\\t{:4d}\".format(n, m % 1337), sol, sol[0] * sol[1])\n            return m % 1337\n    return 0\n\nif __name__ == \"__main__\":\n    for k in range(1, 14):\n        largestPalindrome(k)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(n uint64) uint64 {\n    r := uint64(0)\n    for n > 0 {\n        r = n%10 + r*10\n        n /= 10\n    }\n    return r\n}\n\nfunc main() {\n    pow := uint64(10)\nnextN:\n    for n := 2; n < 10; n++ {\n        low := pow * 9\n        pow *= 10\n        high := pow - 1\n        fmt.Printf(\"Largest palindromic product of two %d-digit integers: \", n)\n        for i := high; i >= low; i-- {\n            j := reverse(i)\n            p := i*pow + j\n            \n            for k := high; k > low; k -= 2 {\n                if k % 10 == 5 {\n                    continue\n                }\n                l := p / k\n                if l > high {\n                    break\n                }\n                if p%k == 0 {\n                    fmt.Printf(\"%d x %d = %d\\n\", k, l, p)\n                    continue nextN\n                }\n            }\n        }\n    }\n}\n"}
{"id": 58465, "name": "Commatizing numbers", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n"}
{"id": 58466, "name": "Commatizing numbers", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n"}
{"id": 58467, "name": "Arithmetic coding_As a generalized change of radix", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n"}
{"id": 58468, "name": "Arithmetic coding_As a generalized change of radix", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n"}
{"id": 58469, "name": "Kosaraju", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n"}
{"id": 58470, "name": "Reflection_List methods", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n"}
{"id": 58471, "name": "Pentomino tiling", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar F = [][]int{\n    {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},\n    {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},\n    {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},\n}\n\nvar I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}\n\nvar L = [][]int{\n    {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},\n}\n\nvar N = [][]int{\n    {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},\n}\n\nvar P = [][]int{\n    {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},\n}\n\nvar T = [][]int{\n    {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},\n}\n\nvar U = [][]int{\n    {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},\n}\n\nvar V = [][]int{\n    {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},\n}\n\nvar W = [][]int{\n    {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},\n}\n\nvar X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}\n\nvar Y = [][]int{\n    {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},\n}\n\nvar Z = [][]int{\n    {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},\n}\n\nvar shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}\n\nvar symbols = []byte(\"FILNPTUVWXYZ-\")\n\nconst (\n    nRows = 8\n    nCols = 8\n    blank = 12\n)\n\nvar grid [nRows][nCols]int\nvar placed [12]bool\n\nfunc tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {\n    for i := 0; i < len(o); i += 2 {\n        x := c + o[i+1]\n        y := r + o[i]\n        if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {\n            return false\n        }\n    }\n    grid[r][c] = shapeIndex\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = shapeIndex\n    }\n    return true\n}\n\nfunc removeOrientation(o []int, r, c int) {\n    grid[r][c] = -1\n    for i := 0; i < len(o); i += 2 {\n        grid[r+o[i]][c+o[i+1]] = -1\n    }\n}\n\nfunc solve(pos, numPlaced int) bool {\n    if numPlaced == len(shapes) {\n        return true\n    }\n    row := pos / nCols\n    col := pos % nCols\n    if grid[row][col] != -1 {\n        return solve(pos+1, numPlaced)\n    }\n\n    for i := range shapes {\n        if !placed[i] {\n            for _, orientation := range shapes[i] {\n                if !tryPlaceOrientation(orientation, row, col, i) {\n                    continue\n                }\n                placed[i] = true\n                if solve(pos+1, numPlaced+1) {\n                    return true\n                }\n                removeOrientation(orientation, row, col)\n                placed[i] = false\n            }\n        }\n    }\n    return false\n}\n\nfunc shuffleShapes() {\n    rand.Shuffle(len(shapes), func(i, j int) {\n        shapes[i], shapes[j] = shapes[j], shapes[i]\n        symbols[i], symbols[j] = symbols[j], symbols[i]\n    })\n}\n\nfunc printResult() {\n    for _, r := range grid {\n        for _, i := range r {\n            fmt.Printf(\"%c \", symbols[i])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    shuffleShapes()\n    for r := 0; r < nRows; r++ {\n        for i := range grid[r] {\n            grid[r][i] = -1\n        }\n    }\n    for i := 0; i < 4; i++ {\n        var randRow, randCol int\n        for {\n            randRow = rand.Intn(nRows)\n            randCol = rand.Intn(nCols)\n            if grid[randRow][randCol] != blank {\n                break\n            }\n        }\n        grid[randRow][randCol] = blank\n    }\n    if solve(0, 0) {\n        printResult()\n    } else {\n        fmt.Println(\"No solution\")\n    }\n}\n"}
{"id": 58472, "name": "Send an unknown method call", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n"}
{"id": 58473, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "Go": "x := 3\n"}
{"id": 58474, "name": "Particle swarm optimization", "Python": "import math\nimport random\n\nINFINITY = 1 << 127\nMAX_INT = 1 << 31\n\nclass Parameters:\n    def __init__(self, omega, phip, phig):\n        self.omega = omega\n        self.phip = phip\n        self.phig = phig\n\nclass State:\n    def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):\n        self.iter = iter\n        self.gbpos = gbpos\n        self.gbval = gbval\n        self.min = min\n        self.max = max\n        self.parameters = parameters\n        self.pos = pos\n        self.vel = vel\n        self.bpos = bpos\n        self.bval = bval\n        self.nParticles = nParticles\n        self.nDims = nDims\n\n    def report(self, testfunc):\n        print \"Test Function :\", testfunc\n        print \"Iterations    :\", self.iter\n        print \"Global Best Position :\", self.gbpos\n        print \"Global Best Value    : %.16f\" % self.gbval\n\ndef uniform01():\n    v = random.random()\n    assert 0.0 <= v and v < 1.0\n    return v\n\ndef psoInit(min, max, parameters, nParticles):\n    nDims = len(min)\n    pos = [min[:]] * nParticles\n    vel = [[0.0] * nDims] * nParticles\n    bpos = [min[:]] * nParticles\n    bval = [INFINITY] * nParticles\n    iter = 0\n    gbpos = [INFINITY] * nDims\n    gbval = INFINITY\n    return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n\ndef pso(fn, y):\n    p = y.parameters\n    v = [0.0] * (y.nParticles)\n    bpos = [y.min[:]] * (y.nParticles)\n    bval = [0.0] * (y.nParticles)\n    gbpos = [0.0] * (y.nDims)\n    gbval = INFINITY\n    for j in xrange(0, y.nParticles):\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j]:\n            bpos[j] = y.pos[j][:]\n            bval[j] = v[j]\n        else:\n            bpos[j] = y.bpos[j][:]\n            bval[j] = y.bval[j]\n        if bval[j] < gbval:\n            gbval = bval[j]\n            gbpos = bpos[j][:]\n    rg = uniform01()\n    pos = [[None] * (y.nDims)] * (y.nParticles)\n    vel = [[None] * (y.nDims)] * (y.nParticles)\n    for j in xrange(0, y.nParticles):\n        \n        rp = uniform01()\n        ok = True\n        vel[j] = [0.0] * (len(vel[j]))\n        pos[j] = [0.0] * (len(pos[j]))\n        for k in xrange(0, y.nDims):\n            vel[j][k] = p.omega * y.vel[j][k] \\\n                      + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \\\n                      + p.phig * rg * (gbpos[k] - y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]\n        if not ok:\n            for k in xrange(0, y.nDims):\n                pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()\n    iter = 1 + y.iter\n    return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n\ndef iterate(fn, n, y):\n    r = y\n    old = y\n    if n == MAX_INT:\n        while True:\n            r = pso(fn, r)\n            if r == old:\n                break\n            old = r\n    else:\n        for _ in xrange(0, n):\n            r = pso(fn, r)\n    return r\n\ndef mccormick(x):\n    (a, b) = x\n    return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a\n\ndef michalewicz(x):\n    m = 10\n    d = len(x)\n    sum = 0.0\n    for i in xrange(1, d):\n        j = x[i - 1]\n        k = math.sin(i * j * j / math.pi)\n        sum += math.sin(j) * k ** (2.0 * m)\n    return -sum\n\ndef main():\n    state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)\n    state = iterate(mccormick, 40, state)\n    state.report(\"McCormick\")\n    print \"f(-.54719, -1.54719) : %.16f\" % (mccormick([-.54719, -1.54719]))\n\n    print\n\n    state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)\n    state = iterate(michalewicz, 30, state)\n    state.report(\"Michalewicz (2D)\")\n    print \"f(2.20, 1.57)        : %.16f\" % (michalewicz([2.2, 1.57]))\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype ff = func([]float64) float64\n\ntype parameters struct{ omega, phip, phig float64 }\n\ntype state struct {\n    iter       int\n    gbpos      []float64\n    gbval      float64\n    min        []float64\n    max        []float64\n    params     parameters\n    pos        [][]float64\n    vel        [][]float64\n    bpos       [][]float64\n    bval       []float64\n    nParticles int\n    nDims      int\n}\n\nfunc (s state) report(testfunc string) {\n    fmt.Println(\"Test Function        :\", testfunc)\n    fmt.Println(\"Iterations           :\", s.iter)\n    fmt.Println(\"Global Best Position :\", s.gbpos)\n    fmt.Println(\"Global Best Value    :\", s.gbval)\n}\n\nfunc psoInit(min, max []float64, params parameters, nParticles int) *state {\n    nDims := len(min)\n    pos := make([][]float64, nParticles)\n    vel := make([][]float64, nParticles)\n    bpos := make([][]float64, nParticles)\n    bval := make([]float64, nParticles)\n    for i := 0; i < nParticles; i++ {\n        pos[i] = min\n        vel[i] = make([]float64, nDims)\n        bpos[i] = min\n        bval[i] = math.Inf(1)\n    }\n    iter := 0\n    gbpos := make([]float64, nDims)\n    for i := 0; i < nDims; i++ {\n        gbpos[i] = math.Inf(1)\n    }\n    gbval := math.Inf(1)\n    return &state{iter, gbpos, gbval, min, max, params,\n        pos, vel, bpos, bval, nParticles, nDims}\n}\n\nfunc pso(fn ff, y *state) *state {\n    p := y.params\n    v := make([]float64, y.nParticles)\n    bpos := make([][]float64, y.nParticles)\n    bval := make([]float64, y.nParticles)\n    gbpos := make([]float64, y.nDims)\n    gbval := math.Inf(1)\n    for j := 0; j < y.nParticles; j++ {\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j] {\n            bpos[j] = y.pos[j]\n            bval[j] = v[j]\n        } else {\n            bpos[j] = y.bpos[j]\n            bval[j] = y.bval[j]\n        }\n        if bval[j] < gbval {\n            gbval = bval[j]\n            gbpos = bpos[j]\n        }\n    }\n    rg := rand.Float64()\n    pos := make([][]float64, y.nParticles)\n    vel := make([][]float64, y.nParticles)\n    for j := 0; j < y.nParticles; j++ {\n        pos[j] = make([]float64, y.nDims)\n        vel[j] = make([]float64, y.nDims)\n        \n        rp := rand.Float64()\n        ok := true\n        for z := 0; z < y.nDims; z++ {\n            pos[j][z] = 0\n            vel[j][z] = 0\n        }\n        for k := 0; k < y.nDims; k++ {\n            vel[j][k] = p.omega*y.vel[j][k] +\n                p.phip*rp*(bpos[j][k]-y.pos[j][k]) +\n                p.phig*rg*(gbpos[k]-y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]\n        }\n        if !ok {\n            for k := 0; k < y.nDims; k++ {\n                pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64()\n            }\n        }\n    }\n    iter := 1 + y.iter\n    return &state{iter, gbpos, gbval, y.min, y.max, y.params,\n        pos, vel, bpos, bval, y.nParticles, y.nDims}\n}\n\nfunc iterate(fn ff, n int, y *state) *state {\n    r := y\n    for i := 0; i < n; i++ {\n        r = pso(fn, r)\n    }\n    return r\n}\n\nfunc mccormick(x []float64) float64 {\n    a, b := x[0], x[1]\n    return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a\n}\n\nfunc michalewicz(x []float64) float64 {\n    m := 10.0\n    sum := 0.0\n    for i := 1; i <= len(x); i++ {\n        j := x[i-1]\n        k := math.Sin(float64(i) * j * j / math.Pi)\n        sum += math.Sin(j) * math.Pow(k, 2*m)\n    }\n    return -sum\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    st := psoInit(\n        []float64{-1.5, -3.0},\n        []float64{4.0, 4.0},\n        parameters{0.0, 0.6, 0.3},\n        100,\n    )\n    st = iterate(mccormick, 40, st)\n    st.report(\"McCormick\")\n    fmt.Println(\"f(-.54719, -1.54719) :\", mccormick([]float64{-.54719, -1.54719}))\n    fmt.Println()\n    st = psoInit(\n        []float64{0.0, 0.0},\n        []float64{math.Pi, math.Pi},\n        parameters{0.3, 0.3, 0.3},\n        1000,\n    )\n    st = iterate(michalewicz, 30, st)\n    st.report(\"Michalewicz (2D)\")\n    fmt.Println(\"f(2.20, 1.57)        :\", michalewicz([]float64{2.2, 1.57}))\n"}
{"id": 58475, "name": "Interactive programming (repl)", "Python": "python\nPython 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(string1, string2, separator):\n\treturn separator.join([string1, '', string2])\n\n>>> f('Rosetta', 'Code', ':')\n'Rosetta::Code'\n>>>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc f(s1, s2, sep string) string {\n\treturn s1 + sep + sep + s2\n}\n\nfunc main() {\n\tfmt.Println(f(\"Rosetta\", \"Code\", \":\"))\n}\n"}
{"id": 58476, "name": "Interactive programming (repl)", "Python": "python\nPython 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(string1, string2, separator):\n\treturn separator.join([string1, '', string2])\n\n>>> f('Rosetta', 'Code', ':')\n'Rosetta::Code'\n>>>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc f(s1, s2, sep string) string {\n\treturn s1 + sep + sep + s2\n}\n\nfunc main() {\n\tfmt.Println(f(\"Rosetta\", \"Code\", \":\"))\n}\n"}
{"id": 58477, "name": "Index finite lists of positive integers", "Python": "def rank(x): return int('a'.join(map(str, [1] + x)), 11)\n\ndef unrank(n):\n\ts = ''\n\twhile n: s,n = \"0123456789a\"[n%11] + s, n//11\n\treturn map(int, s.split('a'))[1:]\n\nl = [1, 2, 3, 10, 100, 987654321]\nprint l\nn = rank(l)\nprint n\nl = unrank(n)\nprint l\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc rank(l []uint) (r big.Int) {\n    for _, n := range l {\n        r.Lsh(&r, n+1)\n        r.SetBit(&r, int(n), 1)\n    }\n    return\n}\n\nfunc unrank(n big.Int) (l []uint) {\n    m := new(big.Int).Set(&n)\n    for a := m.BitLen(); a > 0; {\n        m.SetBit(m, a-1, 0)\n        b := m.BitLen()\n        l = append(l, uint(a-b-1))\n        a = b\n    }\n    return\n}\n\nfunc main() {\n    var b big.Int\n    for i := 0; i <= 10; i++ {\n        b.SetInt64(int64(i))\n        u := unrank(b)\n        r := rank(u)\n        fmt.Println(i, u, &r)\n    }\n    b.SetString(\"12345678901234567890\", 10)\n    u := unrank(b)\n    r := rank(u)\n    fmt.Printf(\"\\n%v\\n%d\\n%d\\n\", &b, u, &r)\n}\n"}
{"id": 58478, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58479, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58480, "name": "Make a backup file", "Python": "import os\ntargetfile = \"pycon-china\"\nos.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+\".bak\")\nf = open(os.path.realpath(targetfile), \"w\")\nf.write(\"this task was solved during a talk about rosettacode at the PyCon China in 2011\")\nf.close()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58481, "name": "Reverse the gender of a string", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n"}
{"id": 58482, "name": "Reverse the gender of a string", "Python": "\n\n \nimport re\nmale2female=u\n \nre_nl=re.compile(r\",[ \\n]*\")\nm2f=[ tok.split(\" \") for tok in re_nl.split(male2female) ]\n \nswitch={}\nwords=[]\n \n \nre_plural=re.compile(\"E*S$\")\nre_ES=re.compile(\"ES$\")\n \ndef gen_pluralize(m,f):\n\n  yield re_plural.sub(\"\",m),re_plural.sub(\"\",f)\n  yield re_ES.sub(\"es\",m),re_ES.sub(\"es\",f)\n  yield re_plural.sub(\"s\",m),re_plural.sub(\"s\",f)\n \ndef gen_capitalize_pluralize(m,f):\n  for m,f in gen_pluralize(m,f):\n    yield m.capitalize(), f.capitalize()\n    yield m,f\n \ndef gen_switch_role_capitalize_pluralize(m,f):\n  for m,f in gen_capitalize_pluralize(m,f):\n    yield m,f\n    yield f,m\n \nfor m,f in m2f:\n  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):\n    if xy not in switch: \n      switch[xy]=xx\n      words.append(xy)\n \nwords=\"|\".join(words)\n \nre_word=re.compile(ur\"\\b(\"+words+ur\")\\b\")\n \ntext=u\n \n \ndef rev_gender(text):\n  text=re_word.split(text)\n  return \"\".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]\n \nprint rev_gender(text)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n"}
{"id": 58483, "name": "Audio alarm", "Python": "import time\nimport os\n\nseconds = input(\"Enter a number of seconds: \")\nsound = input(\"Enter an mp3 filename: \")\n\ntime.sleep(float(seconds))\nos.startfile(sound + \".mp3\")\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    number := 0\n    for number < 1 {\n        fmt.Print(\"Enter number of seconds delay > 0 : \")\n        scanner.Scan()\n        input := scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n        number, _ = strconv.Atoi(input)\n    }\n\n    filename := \"\"\n    for filename == \"\" {\n        fmt.Print(\"Enter name of .mp3 file to play (without extension) : \")\n        scanner.Scan()\n        filename = scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n    }\n\n    cls := \"\\033[2J\\033[0;0H\" \n    fmt.Printf(\"%sAlarm will sound in %d seconds...\", cls, number)\n    time.Sleep(time.Duration(number) * time.Second)\n    fmt.Printf(cls)\n    cmd := exec.Command(\"play\", filename+\".mp3\")\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58484, "name": "Decimal floating point number to binary", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n"}
{"id": 58485, "name": "Decimal floating point number to binary", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n"}
{"id": 58486, "name": "Decimal floating point number to binary", "Python": "hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))\nbin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))\n\ndef float_dec2bin(d):\n    neg = False\n    if d < 0:\n        d = -d\n        neg = True\n    hx = float(d).hex()\n    p = hx.index('p')\n    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])\n    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]\n            + bin(int(hx[p+2:]))[2:])\n\ndef float_bin2dec(bn):\n    neg = False\n    if bn[0] == '-':\n        bn = bn[1:]\n        neg = True\n    dp = bn.index('.')\n    extra0 = '0' * (4 - (dp % 4))\n    bn2 = extra0 + bn\n    dp = bn2.index('.')\n    p = bn2.index('p')\n    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])\n                 for i in range(0, dp+1, 4))\n    bn3 = bn2[dp+1:p]\n    extra0 = '0' * (4 - (len(bn3) % 4))\n    bn4 = bn3 + extra0\n    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))\n                  for i in range(0, len(bn4), 4))\n    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]\n          + str(int('0b' + bn2[p+2:], 2)))\n    return float.fromhex(hx)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n"}
{"id": 58487, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 58488, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n"}
{"id": 58489, "name": "Check Machin-like formulas", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n"}
{"id": 58490, "name": "Check Machin-like formulas", "Python": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = \n\ndef parse_eqn(equationtext=equationtext):\n    eqn_re = re.compile(r)\n\n    found = eqn_re.findall(equationtext)\n    machins, part = [], []\n    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n        if lhs and part:\n            machins.append(part)\n            part = []\n        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n                       Fraction(int(numer), (int(denom) if denom else 1)) ) )\n    machins.append(part)\n    return machins\n\n\ndef tans(xs):\n    xslen = len(xs)\n    if xslen == 1:\n        return tanEval(*xs[0])\n    aa, bb = xs[:xslen//2], xs[xslen//2:]\n    a, b = tans(aa), tans(bb)\n    return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n    if coef == 1:\n        return f\n    if coef < 0:\n        return -tanEval(-coef, f)\n    ca = coef // 2\n    cb = coef - ca\n    a, b = tanEval(ca, f), tanEval(cb, f)\n    return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n    machins = parse_eqn()\n    \n    for machin, eqn in zip(machins, equationtext.split('\\n')):\n        ans = tans(machin)\n        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n"}
{"id": 58491, "name": "MD5_Implementation", "Python": "import math\n\nrotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\nconstants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]\n\ninit_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]\n\nfunctions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \\\n            16*[lambda b, c, d: (d & b) | (~d & c)] + \\\n            16*[lambda b, c, d: b ^ c ^ d] + \\\n            16*[lambda b, c, d: c ^ (b | ~d)]\n\nindex_functions = 16*[lambda i: i] + \\\n                  16*[lambda i: (5*i + 1)%16] + \\\n                  16*[lambda i: (3*i + 5)%16] + \\\n                  16*[lambda i: (7*i)%16]\n\ndef left_rotate(x, amount):\n    x &= 0xFFFFFFFF\n    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF\n\ndef md5(message):\n\n    message = bytearray(message) \n    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff\n    message.append(0x80)\n    while len(message)%64 != 56:\n        message.append(0)\n    message += orig_len_in_bits.to_bytes(8, byteorder='little')\n\n    hash_pieces = init_values[:]\n\n    for chunk_ofst in range(0, len(message), 64):\n        a, b, c, d = hash_pieces\n        chunk = message[chunk_ofst:chunk_ofst+64]\n        for i in range(64):\n            f = functions[i](b, c, d)\n            g = index_functions[i](i)\n            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')\n            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF\n            a, b, c, d = d, new_b, b, c\n        for i, val in enumerate([a, b, c, d]):\n            hash_pieces[i] += val\n            hash_pieces[i] &= 0xFFFFFFFF\n    \n    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))\n        \ndef md5_to_hex(digest):\n    raw = digest.to_bytes(16, byteorder='little')\n    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))\n\nif __name__=='__main__':\n    demo = [b\"\", b\"a\", b\"abc\", b\"message digest\", b\"abcdefghijklmnopqrstuvwxyz\",\n            b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n            b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"]\n    for message in demo:\n        print(md5_to_hex(md5(message)),' <= \"',message.decode('ascii'),'\"', sep='')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"bytes\"\n    \"encoding/binary\"\n)\n\ntype testCase struct {\n    hashCode string\n    string\n}\n\nvar testCases = []testCase{\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\nfunc main() {\n    for _, tc := range testCases {\n        fmt.Printf(\"%s\\n%x\\n\\n\", tc.hashCode, md5(tc.string))\n    }\n}\n\nvar shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}\nvar table [64]uint32\n\nfunc init() {\n    for i := range table {\n        table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))\n    }\n}\n\nfunc md5(s string) (r [16]byte) {\n    padded := bytes.NewBuffer([]byte(s))\n    padded.WriteByte(0x80)\n    for padded.Len() % 64 != 56 {\n        padded.WriteByte(0)\n    }\n    messageLenBits := uint64(len(s)) * 8\n    binary.Write(padded, binary.LittleEndian, messageLenBits)\n\n    var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476\n    var buffer [16]uint32\n    for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { \n        a1, b1, c1, d1 := a, b, c, d\n        for j := 0; j < 64; j++ {\n            var f uint32\n            bufferIndex := j\n            round := j >> 4\n            switch round {\n            case 0:\n                f = (b1 & c1) | (^b1 & d1)\n            case 1:\n                f = (b1 & d1) | (c1 & ^d1)\n                bufferIndex = (bufferIndex*5 + 1) & 0x0F\n            case 2:\n                f = b1 ^ c1 ^ d1\n                bufferIndex = (bufferIndex*3 + 5) & 0x0F\n            case 3:\n                f = c1 ^ (b1 | ^d1)\n                bufferIndex = (bufferIndex * 7) & 0x0F\n            }\n            sa := shift[(round<<2)|(j&3)]\n            a1 += f + buffer[bufferIndex] + table[j]\n            a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1\n        }\n        a, b, c, d = a+a1, b+b1, c+c1, d+d1\n    }\n\n    binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})\n    return\n}\n"}
{"id": 58492, "name": "K-means++ clustering", "Python": "from math import pi, sin, cos\nfrom collections import namedtuple\nfrom random import random, choice\nfrom copy import copy\n\ntry:\n    import psyco\n    psyco.full()\nexcept ImportError:\n    pass\n\n\nFLOAT_MAX = 1e100\n\n\nclass Point:\n    __slots__ = [\"x\", \"y\", \"group\"]\n    def __init__(self, x=0.0, y=0.0, group=0):\n        self.x, self.y, self.group = x, y, group\n\n\ndef generate_points(npoints, radius):\n    points = [Point() for _ in xrange(npoints)]\n\n    \n    for p in points:\n        r = random() * radius\n        ang = random() * 2 * pi\n        p.x = r * cos(ang)\n        p.y = r * sin(ang)\n\n    return points\n\n\ndef nearest_cluster_center(point, cluster_centers):\n    \n    def sqr_distance_2D(a, b):\n        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2\n\n    min_index = point.group\n    min_dist = FLOAT_MAX\n\n    for i, cc in enumerate(cluster_centers):\n        d = sqr_distance_2D(cc, point)\n        if min_dist > d:\n            min_dist = d\n            min_index = i\n\n    return (min_index, min_dist)\n\n\ndef kpp(points, cluster_centers):\n    cluster_centers[0] = copy(choice(points))\n    d = [0.0 for _ in xrange(len(points))]\n\n    for i in xrange(1, len(cluster_centers)):\n        sum = 0\n        for j, p in enumerate(points):\n            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]\n            sum += d[j]\n\n        sum *= random()\n\n        for j, di in enumerate(d):\n            sum -= di\n            if sum > 0:\n                continue\n            cluster_centers[i] = copy(points[j])\n            break\n\n    for p in points:\n        p.group = nearest_cluster_center(p, cluster_centers)[0]\n\n\ndef lloyd(points, nclusters):\n    cluster_centers = [Point() for _ in xrange(nclusters)]\n\n    \n    kpp(points, cluster_centers)\n\n    lenpts10 = len(points) >> 10\n\n    changed = 0\n    while True:\n        \n        for cc in cluster_centers:\n            cc.x = 0\n            cc.y = 0\n            cc.group = 0\n\n        for p in points:\n            cluster_centers[p.group].group += 1\n            cluster_centers[p.group].x += p.x\n            cluster_centers[p.group].y += p.y\n\n        for cc in cluster_centers:\n            cc.x /= cc.group\n            cc.y /= cc.group\n\n        \n        changed = 0\n        for p in points:\n            min_i = nearest_cluster_center(p, cluster_centers)[0]\n            if min_i != p.group:\n                changed += 1\n                p.group = min_i\n\n        \n        if changed <= lenpts10:\n            break\n\n    for i, cc in enumerate(cluster_centers):\n        cc.group = i\n\n    return cluster_centers\n\n\ndef print_eps(points, cluster_centers, W=400, H=400):\n    Color = namedtuple(\"Color\", \"r g b\");\n\n    colors = []\n    for i in xrange(len(cluster_centers)):\n        colors.append(Color((3 * (i + 1) % 11) / 11.0,\n                            (7 * i % 11) / 11.0,\n                            (9 * i % 11) / 11.0))\n\n    max_x = max_y = -FLOAT_MAX\n    min_x = min_y = FLOAT_MAX\n\n    for p in points:\n        if max_x < p.x: max_x = p.x\n        if min_x > p.x: min_x = p.x\n        if max_y < p.y: max_y = p.y\n        if min_y > p.y: min_y = p.y\n\n    scale = min(W / (max_x - min_x),\n                H / (max_y - min_y))\n    cx = (max_x + min_x) / 2\n    cy = (max_y + min_y) / 2\n\n    print \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: -5 -5 %d %d\" % (W + 10, H + 10)\n\n    print (\"/l {rlineto} def /m {rmoveto} def\\n\" +\n           \"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\\n\" +\n           \"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath \" +\n           \"   gsave 1 setgray fill grestore gsave 3 setlinewidth\" +\n           \" 1 setgray stroke grestore 0 setgray stroke }def\")\n\n    for i, cc in enumerate(cluster_centers):\n        print (\"%g %g %g setrgbcolor\" %\n               (colors[i].r, colors[i].g, colors[i].b))\n\n        for p in points:\n            if p.group != i:\n                continue\n            print (\"%.3f %.3f c\" % ((p.x - cx) * scale + W / 2,\n                                    (p.y - cy) * scale + H / 2))\n\n        print (\"\\n0 setgray %g %g s\" % ((cc.x - cx) * scale + W / 2,\n                                        (cc.y - cy) * scale + H / 2))\n\n    print \"\\n%%%%EOF\"\n\n\ndef main():\n    npoints = 30000\n    k = 7 \n\n    points = generate_points(npoints, 10)\n    cluster_centers = lloyd(points, k)\n    print_eps(points, cluster_centers)\n\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype r2 struct {\n    x, y float64\n}\n\ntype r2c struct {\n    r2\n    c int \n}\n\n\nfunc kmpp(k int, data []r2c) {\n    kMeans(data, kmppSeeds(k, data))\n}\n\n\n\nfunc kmppSeeds(k int, data []r2c) []r2 {\n    s := make([]r2, k)\n    s[0] = data[rand.Intn(len(data))].r2\n    d2 := make([]float64, len(data))\n    for i := 1; i < k; i++ {\n        var sum float64\n        for j, p := range data {\n            _, dMin := nearest(p, s[:i])\n            d2[j] = dMin * dMin\n            sum += d2[j]\n        }\n        target := rand.Float64() * sum\n        j := 0\n        for sum = d2[0]; sum < target; sum += d2[j] {\n            j++\n        }\n        s[i] = data[j].r2\n    }\n    return s\n}\n\n\n\n\nfunc nearest(p r2c, mean []r2) (int, float64) {\n    iMin := 0\n    dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y)\n    for i := 1; i < len(mean); i++ {\n        d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y)\n        if d < dMin {\n            dMin = d\n            iMin = i\n        }\n    }\n    return iMin, dMin\n}\n\n\nfunc kMeans(data []r2c, mean []r2) {\n    \n    for i, p := range data {\n        cMin, _ := nearest(p, mean)\n        data[i].c = cMin\n    }\n    mLen := make([]int, len(mean))\n    for {\n        \n        for i := range mean {\n            mean[i] = r2{}\n            mLen[i] = 0\n        }\n        for _, p := range data {\n            mean[p.c].x += p.x\n            mean[p.c].y += p.y\n            mLen[p.c]++\n        }\n        for i := range mean {\n            inv := 1 / float64(mLen[i])\n            mean[i].x *= inv\n            mean[i].y *= inv\n        }\n        \n        var changes int\n        for i, p := range data {\n            if cMin, _ := nearest(p, mean); cMin != p.c {\n                changes++\n                data[i].c = cMin\n            }\n        }\n        if changes == 0 {\n            return\n        }\n    }\n}\n\n\ntype ecParam struct {\n    k          int\n    nPoints    int\n    xBox, yBox int\n    stdv       int\n}\n\n\nfunc main() {\n    ec := &ecParam{6, 30000, 300, 200, 30}\n    \n    origin, data := genECData(ec)\n    vis(ec, data, \"origin\")\n    fmt.Println(\"Data set origins:\")\n    fmt.Println(\"    x      y\")\n    for _, o := range origin {\n        fmt.Printf(\"%5.1f  %5.1f\\n\", o.x, o.y)\n    }\n\n    kmpp(ec.k, data)\n    \n    fmt.Println(\n        \"\\nCluster centroids, mean distance from centroid, number of points:\")\n    fmt.Println(\"    x      y  distance  points\")\n    cent := make([]r2, ec.k)\n    cLen := make([]int, ec.k)\n    inv := make([]float64, ec.k)\n    for _, p := range data {\n        cent[p.c].x += p.x \n        cent[p.c].y += p.y \n        cLen[p.c]++\n    }\n    for i, iLen := range cLen {\n        inv[i] = 1 / float64(iLen)\n        cent[i].x *= inv[i]\n        cent[i].y *= inv[i]\n    }\n    dist := make([]float64, ec.k)\n    for _, p := range data {\n        dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y)\n    }\n    for i, iLen := range cLen {\n        fmt.Printf(\"%5.1f  %5.1f  %8.1f  %6d\\n\",\n            cent[i].x, cent[i].y, dist[i]*inv[i], iLen)\n    }\n    vis(ec, data, \"clusters\")\n}\n\n\n\n\n\n\n\nfunc genECData(ec *ecParam) (orig []r2, data []r2c) {\n    rand.Seed(time.Now().UnixNano())\n    orig = make([]r2, ec.k)\n    data = make([]r2c, ec.nPoints)\n    for i, n := 0, 0; i < ec.k; i++ {\n        x := rand.Float64() * float64(ec.xBox)\n        y := rand.Float64() * float64(ec.yBox)\n        orig[i] = r2{x, y}\n        for j := ec.nPoints / ec.k; j > 0; j-- {\n            data[n].x = rand.NormFloat64()*float64(ec.stdv) + x\n            data[n].y = rand.NormFloat64()*float64(ec.stdv) + y\n            data[n].c = i\n            n++\n        }\n    }\n    return\n}\n\n\nfunc vis(ec *ecParam, data []r2c, fn string) {\n    colors := make([]color.NRGBA, ec.k)\n    for i := range colors {\n        i3 := i * 3\n        third := i3 / ec.k\n        frac := uint8((i3 % ec.k) * 255 / ec.k)\n        switch third {\n        case 0:\n            colors[i] = color.NRGBA{frac, 255 - frac, 0, 255}\n        case 1:\n            colors[i] = color.NRGBA{0, frac, 255 - frac, 255}\n        case 2:\n            colors[i] = color.NRGBA{255 - frac, 0, frac, 255}\n        }\n    }\n    bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv)\n    im := image.NewNRGBA(bounds)\n    draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    fMinX := float64(bounds.Min.X)\n    fMaxX := float64(bounds.Max.X)\n    fMinY := float64(bounds.Min.Y)\n    fMaxY := float64(bounds.Max.Y)\n    for _, p := range data {\n        imx := math.Floor(p.x)\n        imy := math.Floor(float64(ec.yBox) - p.y)\n        if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY {\n            im.SetNRGBA(int(imx), int(imy), colors[p.c])\n        }\n    }\n    f, err := os.Create(fn + \".png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = png.Encode(f, im)\n    if err != nil {\n        fmt.Println(err)\n    }\n    err = f.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 58493, "name": "Maze solving", "Python": "\n\ndef Dijkstra(Graph, source):\n    \n    \n    infinity = float('infinity')\n    n = len(graph)\n    dist = [infinity]*n   \n    previous = [infinity]*n \n    dist[source] = 0        \n    Q = list(range(n)) \n    while Q:           \n        u = min(Q, key=lambda n:dist[n])                 \n        Q.remove(u)\n        if dist[u] == infinity:\n            break \n        for v in range(n):               \n            if Graph[u][v] and (v in Q): \n                alt = dist[u] + Graph[u][v]\n                if alt < dist[v]:       \n                    dist[v] = alt\n                    previous[v] = u\n    return dist,previous\n\ndef display_solution(predecessor):\n    cell = len(predecessor)-1\n    while cell:\n        print(cell,end='<')\n        cell = predecessor[cell]\n    print(0)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\" \n    \"math/rand\"\n    \"time\"\n)\n\ntype maze struct { \n    c2 [][]byte \n    h2 [][]byte \n    v2 [][]byte \n}\n\nfunc newMaze(rows, cols int) *maze {\n    c := make([]byte, rows*cols)              \n    h := bytes.Repeat([]byte{'-'}, rows*cols) \n    v := bytes.Repeat([]byte{'|'}, rows*cols) \n    c2 := make([][]byte, rows)                \n    h2 := make([][]byte, rows)                \n    v2 := make([][]byte, rows)                \n    for i := range h2 {\n        c2[i] = c[i*cols : (i+1)*cols]\n        h2[i] = h[i*cols : (i+1)*cols]\n        v2[i] = v[i*cols : (i+1)*cols]\n    }\n    return &maze{c2, h2, v2}\n}   \n    \nfunc (m *maze) String() string {\n    hWall := []byte(\"+---\")\n    hOpen := []byte(\"+   \")\n    vWall := []byte(\"|   \")\n    vOpen := []byte(\"    \")\n    rightCorner := []byte(\"+\\n\")\n    rightWall := []byte(\"|\\n\")\n    var b []byte\n    for r, hw := range m.h2 {\n        for _, h := range hw {\n            if h == '-' || r == 0 {\n                b = append(b, hWall...)\n            } else {\n                b = append(b, hOpen...)\n                if h != '-' && h != 0 {\n                    b[len(b)-2] = h\n                }\n            }\n        }\n        b = append(b, rightCorner...)\n        for c, vw := range m.v2[r] {\n            if vw == '|' || c == 0 {\n                b = append(b, vWall...)\n            } else {\n                b = append(b, vOpen...)\n                if vw != '|' && vw != 0 {\n                    b[len(b)-4] = vw\n                }\n            }\n            if m.c2[r][c] != 0 {\n                b[len(b)-2] = m.c2[r][c]\n            }\n        }\n        b = append(b, rightWall...)\n    }\n    for _ = range m.h2[0] {\n        b = append(b, hWall...)\n    }\n    b = append(b, rightCorner...)\n    return string(b)\n}\n\nfunc (m *maze) gen() {\n    m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))\n}\n\nconst (\n    up = iota\n    dn\n    rt\n    lf\n)\n\nfunc (m *maze) g2(r, c int) {\n    m.c2[r][c] = ' '\n    for _, dir := range rand.Perm(4) {\n        switch dir {\n        case up:\n            if r > 0 && m.c2[r-1][c] == 0 {\n                m.h2[r][c] = 0\n                m.g2(r-1, c)\n            }\n        case lf:\n            if c > 0 && m.c2[r][c-1] == 0 {\n                m.v2[r][c] = 0\n                m.g2(r, c-1)\n            }\n        case dn:\n            if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {\n                m.h2[r+1][c] = 0\n                m.g2(r+1, c)\n            }\n        case rt:\n            if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {\n                m.v2[r][c+1] = 0\n                m.g2(r, c+1)\n            } \n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const height = 4\n    const width = 7\n    m := newMaze(height, width)\n    m.gen() \n    m.solve(\n        rand.Intn(height), rand.Intn(width),\n        rand.Intn(height), rand.Intn(width))\n    fmt.Print(m)\n}   \n    \nfunc (m *maze) solve(ra, ca, rz, cz int) {\n    var rSolve func(ra, ca, dir int) bool\n    rSolve = func(r, c, dir int) bool {\n        if r == rz && c == cz {\n            m.c2[r][c] = 'F'\n            return true\n        }\n        if dir != dn && m.h2[r][c] == 0 {\n            if rSolve(r-1, c, up) {\n                m.c2[r][c] = '^'\n                m.h2[r][c] = '^'\n                return true\n            }\n        }\n        if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 {\n            if rSolve(r+1, c, dn) {\n                m.c2[r][c] = 'v'\n                m.h2[r+1][c] = 'v'\n                return true\n            }\n        }\n        if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 {\n            if rSolve(r, c+1, rt) {\n                m.c2[r][c] = '>'\n                m.v2[r][c+1] = '>'\n                return true\n            }\n        }\n        if dir != rt && m.v2[r][c] == 0 {\n            if rSolve(r, c-1, lf) {\n                m.c2[r][c] = '<'\n                m.v2[r][c] = '<'\n                return true\n            }\n        }\n        return false\n    }\n    rSolve(ra, ca, -1)\n    m.c2[ra][ca] = 'S'\n}\n"}
{"id": 58494, "name": "Generate random numbers without repeating a value", "Python": "import random\n\nprint(random.sample(range(1, 21), 20))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\nfunc generate(from, to int64) {\n    if to < from || from < 0 {\n        log.Fatal(\"Invalid range.\")\n    }\n    span := to - from + 1\n    generated := make([]bool, span) \n    count := span\n    for count > 0 {\n        n := from + rand.Int63n(span) \n        if !generated[n-from] {\n            generated[n-from] = true\n            fmt.Printf(\"%2d \", n)\n            count--\n        }\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    \n    for i := 1; i <= 5; i++ {\n        generate(1, 20)\n    }\n}\n"}
{"id": 58495, "name": "Solve triangle solitare puzzle", "Python": "\n\n\ndef DrawBoard(board):\n  peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n  for n in xrange(1,16):\n    peg[n] = '.'\n    if n in board:\n      peg[n] = \"%X\" % n\n  print \"     %s\" % peg[1]\n  print \"    %s %s\" % (peg[2],peg[3])\n  print \"   %s %s %s\" % (peg[4],peg[5],peg[6])\n  print \"  %s %s %s %s\" % (peg[7],peg[8],peg[9],peg[10])\n  print \" %s %s %s %s %s\" % (peg[11],peg[12],peg[13],peg[14],peg[15])\n\n\n\ndef RemovePeg(board,n):\n  board.remove(n)\n\n\ndef AddPeg(board,n):\n  board.append(n)\n\n\ndef IsPeg(board,n):\n  return n in board\n\n\n\nJumpMoves = { 1: [ (2,4),(3,6) ],  \n              2: [ (4,7),(5,9)  ],\n              3: [ (5,8),(6,10) ],\n              4: [ (2,1),(5,6),(7,11),(8,13) ],\n              5: [ (8,12),(9,14) ],\n              6: [ (3,1),(5,4),(9,13),(10,15) ],\n              7: [ (4,2),(8,9)  ],\n              8: [ (5,3),(9,10) ],\n              9: [ (5,2),(8,7)  ],\n             10: [ (9,8) ],\n             11: [ (12,13) ],\n             12: [ (8,5),(13,14) ],\n             13: [ (8,4),(9,6),(12,11),(14,15) ],\n             14: [ (9,5),(13,12)  ],\n             15: [ (10,6),(14,13) ]\n            }\n\nSolution = []\n\n\n\ndef Solve(board):\n  \n  if len(board) == 1:\n    return board \n  \n  for peg in xrange(1,16): \n    if IsPeg(board,peg):\n      movelist = JumpMoves[peg]\n      for over,land in movelist:\n        if IsPeg(board,over) and not IsPeg(board,land):\n          saveboard = board[:] \n          RemovePeg(board,peg)\n          RemovePeg(board,over)\n          AddPeg(board,land) \n\n          Solution.append((peg,over,land))\n\n          board = Solve(board)\n          if len(board) == 1:\n            return board\n        \n          board = saveboard[:] \n          del Solution[-1] \n  return board\n\n\n\n\ndef InitSolve(empty):\n  board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n  RemovePeg(board,empty_start)\n  Solve(board)\n\n\nempty_start = 1\nInitSolve(empty_start)\n\nboard = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nRemovePeg(board,empty_start)\nfor peg,over,land in Solution:\n  RemovePeg(board,peg)\n  RemovePeg(board,over)\n  AddPeg(board,land) \n  DrawBoard(board)\n  print \"Peg %X jumped over %X to land on %X\\n\" % (peg,over,land)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype solution struct{ peg, over, land int }\n\ntype move struct{ from, to int }\n\nvar emptyStart = 1\n\nvar board [16]bool\n\nvar jumpMoves = [16][]move{\n    {},\n    {{2, 4}, {3, 6}},\n    {{4, 7}, {5, 9}},\n    {{5, 8}, {6, 10}},\n    {{2, 1}, {5, 6}, {7, 11}, {8, 13}},\n    {{8, 12}, {9, 14}},\n    {{3, 1}, {5, 4}, {9, 13}, {10, 15}},\n    {{4, 2}, {8, 9}},\n    {{5, 3}, {9, 10}},\n    {{5, 2}, {8, 7}},\n    {{9, 8}},\n    {{12, 13}},\n    {{8, 5}, {13, 14}},\n    {{8, 4}, {9, 6}, {12, 11}, {14, 15}},\n    {{9, 5}, {13, 12}},\n    {{10, 6}, {14, 13}},\n}\n\nvar solutions []solution\n\nfunc initBoard() {\n    for i := 1; i < 16; i++ {\n        board[i] = true\n    }\n    board[emptyStart] = false\n}\n\nfunc (sol solution) split() (int, int, int) {\n    return sol.peg, sol.over, sol.land\n}\n\nfunc (mv move) split() (int, int) {\n    return mv.from, mv.to\n}\n\nfunc drawBoard() {\n    var pegs [16]byte\n    for i := 1; i < 16; i++ {\n        if board[i] {\n            pegs[i] = fmt.Sprintf(\"%X\", i)[0]\n        } else {\n            pegs[i] = '-'\n        }\n    }\n    fmt.Printf(\"       %c\\n\", pegs[1])\n    fmt.Printf(\"      %c %c\\n\", pegs[2], pegs[3])\n    fmt.Printf(\"     %c %c %c\\n\", pegs[4], pegs[5], pegs[6])\n    fmt.Printf(\"    %c %c %c %c\\n\", pegs[7], pegs[8], pegs[9], pegs[10])\n    fmt.Printf(\"   %c %c %c %c %c\\n\", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n}\n\nfunc solved() bool {\n    count := 0\n    for _, b := range board {\n        if b {\n            count++\n        }\n    }\n    return count == 1 \n}\n\nfunc solve() {\n    if solved() {\n        return\n    }\n    for peg := 1; peg < 16; peg++ {\n        if board[peg] {\n            for _, mv := range jumpMoves[peg] {\n                over, land := mv.split()\n                if board[over] && !board[land] {\n                    saveBoard := board\n                    board[peg] = false\n                    board[over] = false\n                    board[land] = true\n                    solutions = append(solutions, solution{peg, over, land})\n                    solve()\n                    if solved() {\n                        return \n                    }\n                    board = saveBoard\n                    solutions = solutions[:len(solutions)-1]\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    initBoard()\n    solve()\n    initBoard()\n    drawBoard()\n    fmt.Printf(\"Starting with peg %X removed\\n\\n\", emptyStart)\n    for _, solution := range solutions {\n        peg, over, land := solution.split()\n        board[peg] = false\n        board[over] = false\n        board[land] = true\n        drawBoard()\n        fmt.Printf(\"Peg %X jumped over %X to land on %X\\n\\n\", peg, over, land)\n    }\n}\n"}
{"id": 58496, "name": "Non-transitive dice", "Python": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n    dice = list(cmbr(faces, n))\n \n    succ = [set(j for j, b in enumerate(dice)\n                    if sum((x>y) - (x<y) for x in a for y in b) > 0)\n                for a in dice]\n \n    def loops(seq):\n        s = succ[seq[-1]]\n\n        if len(seq) == m:\n            if seq[0] in s: yield seq\n            return\n\n        for d in (x for x in s if x > seq[0] and not x in seq):\n            yield from loops(seq + (d,))\n \n    yield from (tuple(''.join(dice[s]) for s in x)\n                    for i, v in enumerate(succ)\n                    for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n    print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n    t, t0 = time(), t\n    print(f'\\ttime: {t - t0:.4f} seconds\\n')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n    found := make([]bool, 256)\n    for i := 1; i <= 4; i++ {\n        for j := 1; j <= 4; j++ {\n            for k := 1; k <= 4; k++ {\n                for l := 1; l <= 4; l++ {\n                    c := [4]int{i, j, k, l}\n                    sort.Ints(c[:])\n                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n                    if !found[key] {\n                        found[key] = true\n                        res = append(res, c)\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc cmp(x, y [4]int) int {\n    xw := 0\n    yw := 0\n    for i := 0; i < 4; i++ {\n        for j := 0; j < 4; j++ {\n            if x[i] > y[j] {\n                xw++\n            } else if y[j] > x[i] {\n                yw++\n            }\n        }\n    }\n    if xw < yw {\n        return -1\n    } else if xw > yw {\n        return 1\n    }\n    return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n    var c = len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                first := cmp(cs[i], cs[j])\n                if first == -1 {\n                    second := cmp(cs[j], cs[k])\n                    if second == -1 {\n                        third := cmp(cs[i], cs[k])\n                        if third == 1 {\n                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n    c := len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                for l := 0; l < c; l++ {\n                    first := cmp(cs[i], cs[j])\n                    if first == -1 {\n                        second := cmp(cs[j], cs[k])\n                        if second == -1 {\n                            third := cmp(cs[k], cs[l])\n                            if third == -1 {\n                                fourth := cmp(cs[i], cs[l])\n                                if fourth == 1 {\n                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc main() {\n    combs := fourFaceCombs()\n    fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n    it3 := findIntransitive3(combs)\n    fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n    for _, a := range it3 {\n        fmt.Println(a)\n    }\n    it4 := findIntransitive4(combs)\n    fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n    for _, a := range it4 {\n        fmt.Println(a)\n    }\n}\n"}
{"id": 58497, "name": "Non-transitive dice", "Python": "from itertools import combinations_with_replacement as cmbr\nfrom time import time\n \ndef dice_gen(n, faces, m):\n    dice = list(cmbr(faces, n))\n \n    succ = [set(j for j, b in enumerate(dice)\n                    if sum((x>y) - (x<y) for x in a for y in b) > 0)\n                for a in dice]\n \n    def loops(seq):\n        s = succ[seq[-1]]\n\n        if len(seq) == m:\n            if seq[0] in s: yield seq\n            return\n\n        for d in (x for x in s if x > seq[0] and not x in seq):\n            yield from loops(seq + (d,))\n \n    yield from (tuple(''.join(dice[s]) for s in x)\n                    for i, v in enumerate(succ)\n                    for x in loops((i,)))\n \nt = time()\nfor n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:\n    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass\n \n    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')\n    print(f'\\t{i + 1}*{loop_len} solutions, e.g. {\" > \".join(x)} > [loop]')\n    t, t0 = time(), t\n    print(f'\\ttime: {t - t0:.4f} seconds\\n')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n    found := make([]bool, 256)\n    for i := 1; i <= 4; i++ {\n        for j := 1; j <= 4; j++ {\n            for k := 1; k <= 4; k++ {\n                for l := 1; l <= 4; l++ {\n                    c := [4]int{i, j, k, l}\n                    sort.Ints(c[:])\n                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n                    if !found[key] {\n                        found[key] = true\n                        res = append(res, c)\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc cmp(x, y [4]int) int {\n    xw := 0\n    yw := 0\n    for i := 0; i < 4; i++ {\n        for j := 0; j < 4; j++ {\n            if x[i] > y[j] {\n                xw++\n            } else if y[j] > x[i] {\n                yw++\n            }\n        }\n    }\n    if xw < yw {\n        return -1\n    } else if xw > yw {\n        return 1\n    }\n    return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n    var c = len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                first := cmp(cs[i], cs[j])\n                if first == -1 {\n                    second := cmp(cs[j], cs[k])\n                    if second == -1 {\n                        third := cmp(cs[i], cs[k])\n                        if third == 1 {\n                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n    c := len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                for l := 0; l < c; l++ {\n                    first := cmp(cs[i], cs[j])\n                    if first == -1 {\n                        second := cmp(cs[j], cs[k])\n                        if second == -1 {\n                            third := cmp(cs[k], cs[l])\n                            if third == -1 {\n                                fourth := cmp(cs[i], cs[l])\n                                if fourth == 1 {\n                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc main() {\n    combs := fourFaceCombs()\n    fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n    it3 := findIntransitive3(combs)\n    fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n    for _, a := range it3 {\n        fmt.Println(a)\n    }\n    it4 := findIntransitive4(combs)\n    fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n    for _, a := range it4 {\n        fmt.Println(a)\n    }\n}\n"}
{"id": 58498, "name": "History variables", "Python": "import sys\n\nHIST = {}\n\ndef trace(frame, event, arg):\n    for name,val in frame.f_locals.items():\n        if name not in HIST:\n            HIST[name] = []\n        else:\n            if HIST[name][-1] is val:\n                continue\n        HIST[name].append(val)\n    return trace\n\ndef undo(name):\n    HIST[name].pop(-1)\n    return HIST[name][-1]\n\ndef main():\n    a = 10\n    a = 20\n\n    for i in range(5):\n        c = i\n\n    print \"c:\", c, \"-> undo x3 ->\",\n    c = undo('c')\n    c = undo('c')\n    c = undo('c')\n    print c\n    print 'HIST:', HIST\n\nsys.settrace(trace)\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"sync\"\n    \"time\"\n)\n\n\ntype history struct {\n    timestamp tsFunc\n    hs        []hset\n}\n\n\ntype tsFunc func() time.Time\n\n\ntype hset struct {\n    int           \n    t   time.Time \n}\n\n\nfunc newHistory(ts tsFunc) history {\n    return history{ts, []hset{{t: ts()}}}\n}   \n    \n\nfunc (h history) int() int {\n    return h.hs[len(h.hs)-1].int\n}\n    \n\nfunc (h *history) set(x int) time.Time {\n    t := h.timestamp()\n    h.hs = append(h.hs, hset{x, t})\n    return t\n}\n\n\nfunc (h history) dump() {\n    for _, hs := range h.hs {\n        fmt.Println(hs.t.Format(time.StampNano), hs.int)\n    }\n}   \n    \n\n\nfunc (h history) recall(t time.Time) (int,  bool) {\n    i := sort.Search(len(h.hs), func(i int) bool {\n        return h.hs[i].t.After(t)\n    })\n    if i > 0 {\n        return h.hs[i-1].int, true\n    }\n    return 0, false\n}\n\n\n\n\n\nfunc newTimestamper() tsFunc {\n    var last time.Time\n    return func() time.Time {\n        if t := time.Now(); t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n        }\n        return last\n    }\n}\n\n\n\nfunc newProtectedTimestamper() tsFunc {\n    var last time.Time\n    var m sync.Mutex\n    return func() (t time.Time) {\n        t = time.Now()\n        m.Lock() \n        if t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n            t = last\n        }\n        m.Unlock()\n        return\n    }\n}\n\nfunc main() {\n    \n    ts := newTimestamper()\n    \n    h := newHistory(ts)\n    \n    ref := []time.Time{h.set(3), h.set(1), h.set(4)}\n    \n    fmt.Println(\"History of variable h:\")\n    h.dump() \n    \n    \n    fmt.Println(\"Recalling values:\")\n    for _, t := range ref {\n        rv, _ := h.recall(t)\n        fmt.Println(rv)\n    }\n}\n"}
{"id": 58499, "name": "Perceptron", "Python": "import random\n\nTRAINING_LENGTH = 2000\n\nclass Perceptron:\n    \n    def __init__(self,n):\n        self.c = .01\n        self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)]\n\n    def feed_forward(self, inputs):\n        vars = []\n        for i in range(len(inputs)):\n            vars.append(inputs[i] * self.weights[i])\n        return self.activate(sum(vars))\n\n    def activate(self, value):\n        return 1 if value > 0 else -1\n\n    def train(self, inputs, desired):\n        guess = self.feed_forward(inputs)\n        error = desired - guess\n        for i in range(len(inputs)):\n            self.weights[i] += self.c * error * inputs[i]\n        \nclass Trainer():\n    \n    def __init__(self, x, y, a):\n        self.inputs = [x, y, 1]\n        self.answer = a\n\ndef F(x):\n    return 2 * x + 1\n\nif __name__ == \"__main__\":\n    ptron = Perceptron(3)\n    training = []\n    for i in range(TRAINING_LENGTH):\n        x = random.uniform(-10,10)\n        y = random.uniform(-10,10)\n        answer = 1\n        if y < F(x): answer = -1\n        training.append(Trainer(x,y,answer))\n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Untrained')\n    for row in result:\n        print(''.join(v for v in row))\n\n    for t in training:\n        ptron.train(t.inputs, t.answer)\n    \n    result = []\n    for y in range(-10,10):\n        temp = []\n        for x in range(-10,10):\n            if ptron.feed_forward([x,y,1]) == 1:\n                temp.append('^')\n            else:\n                temp.append('.')\n        result.append(temp)\n    \n    print('Trained')\n    for row in result:\n        print(''.join(v for v in row))\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst c = 0.00001\n\nfunc linear(x float64) float64 {\n    return x*0.7 + 40\n}\n\ntype trainer struct {\n    inputs []float64\n    answer int\n}\n\nfunc newTrainer(x, y float64, a int) *trainer {\n    return &trainer{[]float64{x, y, 1}, a}\n}\n\ntype perceptron struct {\n    weights  []float64\n    training []*trainer\n}\n\nfunc newPerceptron(n, w, h int) *perceptron {\n    weights := make([]float64, n)\n    for i := 0; i < n; i++ {\n        weights[i] = rand.Float64()*2 - 1\n    }\n\n    training := make([]*trainer, 2000)\n    for i := 0; i < 2000; i++ {\n        x := rand.Float64() * float64(w)\n        y := rand.Float64() * float64(h)\n        answer := 1\n        if y < linear(x) {\n            answer = -1\n        }\n        training[i] = newTrainer(x, y, answer)\n    }\n    return &perceptron{weights, training}\n}\n\nfunc (p *perceptron) feedForward(inputs []float64) int {\n    if len(inputs) != len(p.weights) {\n        panic(\"weights and input length mismatch, program terminated\")\n    }\n    sum := 0.0\n    for i, w := range p.weights {\n        sum += inputs[i] * w\n    }\n    if sum > 0 {\n        return 1\n    }\n    return -1\n}\n\nfunc (p *perceptron) train(inputs []float64, desired int) {\n    guess := p.feedForward(inputs)\n    err := float64(desired - guess)\n    for i := range p.weights {\n        p.weights[i] += c * err * inputs[i]\n    }\n}\n\nfunc (p *perceptron) draw(dc *gg.Context, iterations int) {\n    le := len(p.training)\n    for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le {\n        p.train(p.training[count].inputs, p.training[count].answer)\n    }\n    x := float64(dc.Width())\n    y := linear(x)\n    dc.SetLineWidth(2)\n    dc.SetRGB255(0, 0, 0) \n    dc.DrawLine(0, linear(0), x, y)\n    dc.Stroke()\n    dc.SetLineWidth(1)\n    for i := 0; i < le; i++ {\n        guess := p.feedForward(p.training[i].inputs)\n        x := p.training[i].inputs[0] - 4\n        y := p.training[i].inputs[1] - 4\n        if guess > 0 {\n            dc.SetRGB(0, 0, 1) \n        } else {\n            dc.SetRGB(1, 0, 0) \n        }\n        dc.DrawCircle(x, y, 8)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    w, h := 640, 360\n    perc := newPerceptron(3, w, h)\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    perc.draw(dc, 2000)\n    dc.SavePNG(\"perceptron.png\")\n}\n"}
{"id": 58500, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 58501, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n"}
{"id": 58502, "name": "Pisano period", "Python": "from sympy import isprime, lcm, factorint, primerange\nfrom functools import reduce\n\n\ndef pisano1(m):\n    \"Simple definition\"\n    if m < 2:\n        return 1\n    lastn, n = 0, 1\n    for i in range(m ** 2):\n        lastn, n = n, (lastn + n) % m\n        if lastn == 0 and n == 1:\n            return i + 1\n    return 1\n\ndef pisanoprime(p, k):\n    \"Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1\"\n    assert isprime(p) and k > 0\n    return p ** (k - 1) * pisano1(p)\n\ndef pisano_mult(m, n):\n    \"pisano(m*n) where m and n assumed coprime integers\"\n    return lcm(pisano1(m), pisano1(n))\n\ndef pisano2(m):\n    \"Uses prime factorization of m\"\n    return reduce(lcm, (pisanoprime(prime, mult)\n                        for prime, mult in factorint(m).items()), 1)\n\n\nif __name__ == '__main__':\n    for n in range(1, 181):\n        assert pisano1(n) == pisano2(n), \"Wall-Sun-Sun prime exists??!!\"\n    print(\"\\nPisano period (p, 2) for primes less than 50\\n \",\n          [pisanoprime(prime, 2) for prime in primerange(1, 50)])\n    print(\"\\nPisano period (p, 1) for primes less than 180\\n \",\n          [pisanoprime(prime, 1) for prime in primerange(1, 180)])\n    print(\"\\nPisano period (p) for integers 1 to 180\")\n    for i in range(1, 181):\n        print(\" %3d\" % pisano2(i), end=\"\" if i % 10 else \"\\n\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(a, b uint) uint {\n    if b == 0 {\n        return a\n    }\n    return gcd(b, a%b)\n}\n\nfunc lcm(a, b uint) uint {\n    return a / gcd(a, b) * b\n}\n\nfunc ipow(x, p uint) uint {\n    prod := uint(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\n\nfunc getPrimes(n uint) []uint {\n    var primes []uint\n    for i := uint(2); i <= n; i++ {\n        div := n / i\n        mod := n % i\n        for mod == 0 {\n            primes = append(primes, i)\n            n = div\n            div = n / i\n            mod = n % i\n        }\n    }\n    return primes\n}\n\n\nfunc isPrime(n uint) 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 := uint(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\n\nfunc pisanoPeriod(m uint) uint {\n    var p, c uint = 0, 1\n    for i := uint(0); i < m*m; i++ {\n        p, c = c, (p+c)%m\n        if p == 0 && c == 1 {\n            return i + 1\n        }\n    }\n    return 1\n}\n\n\nfunc pisanoPrime(p uint, k uint) uint {\n    if !isPrime(p) || k == 0 {\n        return 0 \n    }\n    return ipow(p, k-1) * pisanoPeriod(p)\n}\n\n\nfunc pisano(m uint) uint {\n    primes := getPrimes(m)\n    primePowers := make(map[uint]uint)\n    for _, p := range primes {\n        primePowers[p]++\n    }\n    var pps []uint\n    for k, v := range primePowers {\n        pps = append(pps, pisanoPrime(k, v))\n    }\n    if len(pps) == 0 {\n        return 1\n    }\n    if len(pps) == 1 {\n        return pps[0]\n    }    \n    f := pps[0]\n    for i := 1; i < len(pps); i++ {\n        f = lcm(f, pps[i])\n    }\n    return f\n}\n\nfunc main() {\n    for p := uint(2); p < 15; p++ {\n        pp := pisanoPrime(p, 2)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%2d: 2) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    for p := uint(2); p < 180; p++ {\n        pp := pisanoPrime(p, 1)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%3d: 1) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    fmt.Println(\"pisano(n) for integers 'n' from 1 to 180 are:\")\n    for n := uint(1); n <= 180; n++ {\n        fmt.Printf(\"%3d \", pisano(n))\n        if n != 1 && n%15 == 0 {\n            fmt.Println()\n        }\n    }    \n    fmt.Println()\n}\n"}
{"id": 58503, "name": "Railway circuit", "Python": "from itertools import count, islice\nimport numpy as np\nfrom numpy import sin, cos, pi\n\n\nANGDIV = 12\nANG = 2*pi/ANGDIV\n\ndef draw_all(sols):\n    import matplotlib.pyplot as plt\n\n    def draw_track(ax, s):\n        turn, xend, yend = 0, [0], [0]\n\n        for d in s:\n            x0, y0 = xend[-1], yend[-1]\n            a = turn*ANG\n            cs, sn = cos(a), sin(a)\n            ang = a + d*pi/2\n            cx, cy = x0 + cos(ang), y0 + sin(ang)\n\n            da = np.linspace(ang, ang + d*ANG, 10)\n            xs = cx - cos(da)\n            ys = cy - sin(da)\n            ax.plot(xs, ys, 'green' if d == -1 else 'orange')\n\n            xend.append(xs[-1])\n            yend.append(ys[-1])\n            turn += d\n\n        ax.plot(xend, yend, 'k.', markersize=1)\n        ax.set_aspect(1)\n\n    ls = len(sols)\n    if ls == 0: return\n\n    w, h = min((abs(w*2 - h*3) + w*h - ls, w, h)\n        for w, h in ((w, (ls + w - 1)//w)\n            for w in range(1, ls + 1)))[1:]\n\n    fig, ax = plt.subplots(h, w, squeeze=False)\n    for a in ax.ravel(): a.set_axis_off()\n\n    for i, s in enumerate(sols):\n        draw_track(ax[i//w, i%w], s)\n\n    plt.show()\n\n\ndef match_up(this, that, equal_lr, seen):\n    if not this or not that: return\n\n    n = len(this[0][-1])\n    n2 = n*2\n\n    l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0\n\n    def record(m):\n        for _ in range(n2):\n            seen[m] = True\n            m = (m&1) << (n2 - 1) | (m >> 1)\n\n        if equal_lr:\n            m ^= (1<<n2) - 1\n            for _ in range(n2):\n                seen[m] = True\n                m = (m&1) << (n2 - 1) | (m >> 1)\n\n    l_n, r_n = len(this), len(that)\n    tol = 1e-3\n\n    while l_lo < l_n:\n        while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol:\n            l_hi += 1\n\n        while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol:\n            r_lo += 1\n\n        r_hi = r_lo\n        while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol:\n            r_hi += 1\n\n        for a in this[l_lo:l_hi]:\n            m_left = a[-2]<<n\n            for b in that[r_lo:r_hi]:\n                if (m := m_left | b[-2]) not in seen:\n                    if np.abs(a[1] + b[2]) < tol:\n                        record(m)\n                        record(int(f'{m:b}'[::-1], base=2))\n                        yield(a[-1] + b[-1])\n\n        l_lo, r_lo = l_hi, r_hi\n\ndef track_combo(left, right):\n    n = (left + right)//2\n    n1 = left + right - n\n\n    alphas = np.exp(1j*ANG*np.arange(ANGDIV))\n    def half_track(m, n):\n        turns = tuple(1 - 2*(m>>i & 1) for i in range(n))\n        rcnt = np.cumsum(turns)%ANGDIV\n        asum = np.sum(alphas[rcnt])\n        want = asum/alphas[rcnt[-1]]\n        return np.abs(asum), asum, want, m, turns\n\n    res = [[] for _ in range(right + 1)]\n    for i in range(1<<n):\n        b = i.bit_count()\n        if b <= right:\n            res[b].append(half_track(i, n))\n\n    for v in res: v.sort()\n    if n1 == n:\n        return res, res\n\n    res1 = [[] for _ in range(right + 1)]\n    for i in range(1<<n1):\n        b = i.bit_count()\n        if b <= right:\n            res1[b].append(half_track(i, n1))\n\n    for v in res: v.sort()\n    return res, res1\n\ndef railway(n):\n    seen = {}\n\n    for l in range(n//2, n + 1):\n        r = n - l\n        if not l >= r: continue\n\n        if (l - r)%ANGDIV == 0:\n            res_l, res_r = track_combo(l, r)\n\n            for i, this in enumerate(res_l):\n                if 2*i < r: continue\n                that = res_r[r - i]\n                for s in match_up(this, that, l == r, seen):\n                    yield s\n\nsols = []\nfor i, s in enumerate(railway(30)):\n    \n    print(i + 1, s)\n    sols.append(s)\n\ndraw_all(sols[:40])\n", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    right    = 1\n    left     = -1\n    straight = 0\n)\n\nfunc normalize(tracks []int) string {\n    size := len(tracks)\n    a := make([]byte, size)\n    for i := 0; i < size; i++ {\n        a[i] = \"abc\"[tracks[i]+1]\n    }\n\n    \n\n    norm := string(a)\n    for i := 0; i < size; i++ {\n        s := string(a)\n        if s < norm {\n            norm = s\n        }\n        tmp := a[0]\n        copy(a, a[1:])\n        a[size-1] = tmp\n    }\n    return norm\n}\n\nfunc fullCircleStraight(tracks []int, nStraight int) bool {\n    if nStraight == 0 {\n        return true\n    }\n\n    \n    count := 0\n    for _, track := range tracks {\n        if track == straight {\n            count++\n        }\n    }\n    if count != nStraight {\n        return false\n    }\n\n    \n    var straightTracks [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == straight {\n            straightTracks[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if straightTracks[i] != straightTracks[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if straightTracks[i] != straightTracks[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc fullCircleRight(tracks []int) bool {\n    \n    sum := 0\n    for _, track := range tracks {\n        sum += track * 30\n    }\n    if sum%360 != 0 {\n        return false\n    }\n\n    \n    var rTurns [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == right {\n            rTurns[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if rTurns[i] != rTurns[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if rTurns[i] != rTurns[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc circuits(nCurved, nStraight int) {\n    solutions := make(map[string][]int)\n    gen := getPermutationsGen(nCurved, nStraight)\n    for gen.hasNext() {\n        tracks := gen.next()\n        if !fullCircleStraight(tracks, nStraight) {\n            continue\n        }\n        if !fullCircleRight(tracks) {\n            continue\n        }\n        tracks2 := make([]int, len(tracks))\n        copy(tracks2, tracks)\n        solutions[normalize(tracks)] = tracks2\n    }\n    report(solutions, nCurved, nStraight)\n}\n\nfunc getPermutationsGen(nCurved, nStraight int) PermutationsGen {\n    if (nCurved+nStraight-12)%4 != 0 {\n        panic(\"input must be 12 + k * 4\")\n    }\n    var trackTypes []int\n    switch nStraight {\n    case 0:\n        trackTypes = []int{right, left}\n    case 12:\n        trackTypes = []int{right, straight}\n    default:\n        trackTypes = []int{right, left, straight}\n    }\n    return NewPermutationsGen(nCurved+nStraight, trackTypes)\n}\n\nfunc report(sol map[string][]int, numC, numS int) {\n    size := len(sol)\n    fmt.Printf(\"\\n%d solution(s) for C%d,%d \\n\", size, numC, numS)\n    if numC <= 20 {\n        for _, tracks := range sol {\n            for _, track := range tracks {\n                fmt.Printf(\"%2d \", track)\n            }\n            fmt.Println()\n        }\n    }\n}\n\n\ntype PermutationsGen struct {\n    NumPositions int\n    choices      []int\n    indices      []int\n    sequence     []int\n    carry        int\n}\n\nfunc NewPermutationsGen(numPositions int, choices []int) PermutationsGen {\n    indices := make([]int, numPositions)\n    sequence := make([]int, numPositions)\n    carry := 0\n    return PermutationsGen{numPositions, choices, indices, sequence, carry}\n}\n\nfunc (p *PermutationsGen) next() []int {\n    p.carry = 1\n\n    \n    for i := 1; i < len(p.indices) && p.carry > 0; i++ {\n        p.indices[i] += p.carry\n        p.carry = 0\n        if p.indices[i] == len(p.choices) {\n            p.carry = 1\n            p.indices[i] = 0\n        }\n    }\n    for j := 0; j < len(p.indices); j++ {\n        p.sequence[j] = p.choices[p.indices[j]]\n    }\n    return p.sequence\n}\n\nfunc (p *PermutationsGen) hasNext() bool {\n    return p.carry != 1\n}\n\nfunc main() {\n    for n := 12; n <= 28; n += 4 {\n        circuits(n, 0)\n    }\n    circuits(12, 4)\n}\n"}
{"id": 58504, "name": "Free polyominoes enumeration", "Python": "from itertools import imap, imap, groupby, chain, imap\nfrom operator import itemgetter\nfrom sys import argv\nfrom array import array\n\ndef concat_map(func, it):\n    return list(chain.from_iterable(imap(func, it)))\n\ndef minima(poly):\n    \n    return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))\n\ndef translate_to_origin(poly):\n    (minx, miny) = minima(poly)\n    return [(x - minx, y - miny) for (x, y) in poly]\n\nrotate90   = lambda (x, y): ( y, -x)\nrotate180  = lambda (x, y): (-x, -y)\nrotate270  = lambda (x, y): (-y,  x)\nreflect    = lambda (x, y): (-x,  y)\n\ndef rotations_and_reflections(poly):\n    \n    return (poly,\n            map(rotate90, poly),\n            map(rotate180, poly),\n            map(rotate270, poly),\n            map(reflect, poly),\n            [reflect(rotate90(pt)) for pt in poly],\n            [reflect(rotate180(pt)) for pt in poly],\n            [reflect(rotate270(pt)) for pt in poly])\n\ndef canonical(poly):\n    return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly))\n\ndef unique(lst):\n    lst.sort()\n    return map(next, imap(itemgetter(1), groupby(lst)))\n\n\ncontiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]\n\ndef new_points(poly):\n    \n    return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly])\n\ndef new_polys(poly):\n    return unique([canonical(poly + [pt]) for pt in new_points(poly)])\n\nmonomino = [(0, 0)]\nmonominoes = [monomino]\n\ndef rank(n):\n    \n    assert n >= 0\n    if n == 0: return []\n    if n == 1: return monominoes\n    return unique(concat_map(new_polys, rank(n - 1)))\n\ndef text_representation(poly):\n    \n    min_pt = minima(poly)\n    max_pt = (max(p[0] for p in poly), max(p[1] for p in poly))\n    table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1)\n             for _ in xrange(max_pt[0] - min_pt[0] + 1)]\n    for pt in poly:\n        table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = '\n    return \"\\n\".join(row.tostring() for row in table)\n\ndef main():\n    print [len(rank(n)) for n in xrange(1, 11)]\n\n    n = int(argv[1]) if (len(argv) == 2) else 5\n    print \"\\nAll free polyominoes of rank %d:\" % n\n\n    for poly in rank(n):\n        print text_representation(poly), \"\\n\"\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype point struct{ x, y int }\ntype polyomino []point\ntype pointset map[point]bool\n\nfunc (p point) rotate90() point  { return point{p.y, -p.x} }\nfunc (p point) rotate180() point { return point{-p.x, -p.y} }\nfunc (p point) rotate270() point { return point{-p.y, p.x} }\nfunc (p point) reflect() point   { return point{-p.x, p.y} }\n\nfunc (p point) String() string { return fmt.Sprintf(\"(%d, %d)\", p.x, p.y) }\n\n\nfunc (p point) contiguous() polyomino {\n    return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y},\n        point{p.x, p.y - 1}, point{p.x, p.y + 1}}\n}\n\n\nfunc (po polyomino) minima() (int, int) {\n    minx := po[0].x\n    miny := po[0].y\n    for i := 1; i < len(po); i++ {\n        if po[i].x < minx {\n            minx = po[i].x\n        }\n        if po[i].y < miny {\n            miny = po[i].y\n        }\n    }\n    return minx, miny\n}\n\nfunc (po polyomino) translateToOrigin() polyomino {\n    minx, miny := po.minima()\n    res := make(polyomino, len(po))\n    for i, p := range po {\n        res[i] = point{p.x - minx, p.y - miny}\n    }\n    sort.Slice(res, func(i, j int) bool {\n        return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y)\n    })\n    return res\n}\n\n\nfunc (po polyomino) rotationsAndReflections() []polyomino {\n    rr := make([]polyomino, 8)\n    for i := 0; i < 8; i++ {\n        rr[i] = make(polyomino, len(po))\n    }\n    copy(rr[0], po)\n    for j := 0; j < len(po); j++ {\n        rr[1][j] = po[j].rotate90()\n        rr[2][j] = po[j].rotate180()\n        rr[3][j] = po[j].rotate270()\n        rr[4][j] = po[j].reflect()\n        rr[5][j] = po[j].rotate90().reflect()\n        rr[6][j] = po[j].rotate180().reflect()\n        rr[7][j] = po[j].rotate270().reflect()\n    }\n    return rr\n}\n\nfunc (po polyomino) canonical() polyomino {\n    rr := po.rotationsAndReflections()\n    minr := rr[0].translateToOrigin()\n    mins := minr.String()\n    for i := 1; i < 8; i++ {\n        r := rr[i].translateToOrigin()\n        s := r.String()\n        if s < mins {\n            minr = r\n            mins = s\n        }\n    }\n    return minr\n}\n\nfunc (po polyomino) String() string {\n    return fmt.Sprintf(\"%v\", []point(po))\n}\n\nfunc (po polyomino) toPointset() pointset {\n    pset := make(pointset, len(po))\n    for _, p := range po {\n        pset[p] = true\n    }\n    return pset\n}\n\n\nfunc (po polyomino) newPoints() polyomino {\n    pset := po.toPointset()\n    m := make(pointset) \n    for _, p := range po {\n        pts := p.contiguous()\n        for _, pt := range pts {\n            if !pset[pt] {\n                m[pt] = true \n            }\n        }\n    }\n    poly := make(polyomino, 0, len(m))\n    for k := range m {\n        poly = append(poly, k)\n    }\n    return poly\n}\n\nfunc (po polyomino) newPolys() []polyomino {\n    pts := po.newPoints()\n    res := make([]polyomino, len(pts))\n    for i, pt := range pts {\n        poly := make(polyomino, len(po))\n        copy(poly, po)\n        poly = append(poly, pt)\n        res[i] = poly.canonical()\n    }\n    return res\n}\n\nvar monomino = polyomino{point{0, 0}}\nvar monominoes = []polyomino{monomino}\n\n\nfunc rank(n int) []polyomino {\n    switch {\n    case n < 0:\n        panic(\"n cannot be negative. Program terminated.\")\n    case n == 0:\n        return []polyomino{}\n    case n == 1:\n        return monominoes\n    default:\n        r := rank(n - 1)\n        m := make(map[string]bool)\n        var polys []polyomino\n        for _, po := range r {\n            for _, po2 := range po.newPolys() {\n                if s := po2.String(); !m[s] {\n                    polys = append(polys, po2)\n                    m[s] = true\n                }\n            }\n        }\n        sort.Slice(polys, func(i, j int) bool {\n            return polys[i].String() < polys[j].String()\n        })\n        return polys\n    }\n}\n\nfunc main() {\n    const n = 5\n    fmt.Printf(\"All free polyominoes of rank %d:\\n\\n\", n)\n    for _, poly := range rank(n) {\n        for _, pt := range poly {\n            fmt.Printf(\"%s \", pt)\n        }\n        fmt.Println()\n    }\n    const k = 10\n    fmt.Printf(\"\\nNumber of free polyominoes of ranks 1 to %d:\\n\", k)\n    for i := 1; i <= k; i++ {\n        fmt.Printf(\"%d \", len(rank(i)))\n    }\n    fmt.Println()\n}\n"}
{"id": 58505, "name": "Use a REST API", "Python": "\nimport requests\nimport json\n\ncity = None\ntopic = None\n\ndef getEvent(url_path, key) :\n    responseString = \"\"\n    \n    params = {'city':city, 'key':key,'topic':topic}\n    r = requests.get(url_path, params = params)    \n    print(r.url)    \n    responseString = r.text\n    return responseString\n\n\ndef getApiKey(key_path):\n    key = \"\"\n    f = open(key_path, 'r')\n    key = f.read()\n    return key\n\n\ndef submitEvent(url_path,params):\n    r = requests.post(url_path, data=json.dumps(params))        \n    print(r.text+\" : Event Submitted\")\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar key string\n\nfunc init() {\n\t\n\t\n\tconst keyFile = \"api_key.txt\"\n\tf, err := os.Open(keyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkeydata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkey = strings.TrimSpace(string(keydata))\n}\n\ntype EventResponse struct {\n\tResults []Result\n\t\n}\n\ntype Result struct {\n\tID          string\n\tStatus      string\n\tName        string\n\tEventURL    string `json:\"event_url\"`\n\tDescription string\n\tTime        EventTime\n\t\n}\n\n\n\ntype EventTime struct{ time.Time }\n\nfunc (et *EventTime) UnmarshalJSON(data []byte) error {\n\tvar msec int64\n\tif err := json.Unmarshal(data, &msec); err != nil {\n\t\treturn err\n\t}\n\tet.Time = time.Unix(0, msec*int64(time.Millisecond))\n\treturn nil\n}\n\nfunc (et EventTime) MarshalJSON() ([]byte, error) {\n\tmsec := et.UnixNano() / int64(time.Millisecond)\n\treturn json.Marshal(msec)\n}\n\n\nfunc (r *Result) String() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintln(&b, \"ID:\", r.ID)\n\tfmt.Fprintln(&b, \"URL:\", r.EventURL)\n\tfmt.Fprintln(&b, \"Time:\", r.Time.Format(time.UnixDate))\n\td := r.Description\n\tconst limit = 65\n\tif len(d) > limit {\n\t\td = d[:limit-1] + \"…\"\n\t}\n\tfmt.Fprintln(&b, \"Description:\", d)\n\treturn b.String()\n}\n\nfunc main() {\n\tv := url.Values{\n\t\t\n\t\t\n\t\t\"topic\": []string{\"photo\"},\n\t\t\"time\":  []string{\",1w\"},\n\t\t\"key\":   []string{key},\n\t}\n\tu := url.URL{\n\t\tScheme:   \"http\",\n\t\tHost:     \"api.meetup.com\",\n\t\tPath:     \"2/open_events.json\",\n\t\tRawQuery: v.Encode(),\n\t}\n\t\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Println(\"HTTP Status:\", resp.Status)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\n\tvar buf bytes.Buffer\n\tif err = json.Indent(&buf, body, \"\", \"  \"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\n\n\tvar evresp EventResponse\n\tjson.Unmarshal(body, &evresp)\n\t\n\n\tfmt.Println(\"Got\", len(evresp.Results), \"events\")\n\tif len(evresp.Results) > 0 {\n\t\tfmt.Println(\"First event:\\n\", &evresp.Results[0])\n\t}\n}\n"}
{"id": 58506, "name": "Twelve statements", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 58507, "name": "Twelve statements", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n"}
{"id": 58508, "name": "Deming's funnel", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n"}
{"id": 58509, "name": "Deming's funnel", "Python": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n       0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n    x, rxs = 0, []\n    for dx in dxs:\n        rxs.append(x + dx)\n        x = rule(x, dx)\n    return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n    m = mean(xs)\n    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n    rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n    print label\n    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))\n    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n    print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n"}
{"id": 58510, "name": "Rosetta Code_Fix code tags", "Python": "\n\nfrom re import sub\n\ntesttexts = [\n,\n    ,\n    ]\n\nfor txt in testtexts:\n    text2 = sub(r'<lang\\s+\\\"?([\\w\\d\\s]+)\\\"?\\s?>', r'<syntaxhighlight lang=\\1>', txt)\n    text2 = sub(r'<lang\\s*>', r'<syntaxhighlight lang=text>', text2)\n    text2 = sub(r'</lang\\s*>', r'\n", "Go": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"log\"\nimport \"os\"\nimport \"regexp\"\nimport \"strings\"\n\nfunc main() {\n\terr := fix()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc fix() (err error) {\n\tbuf, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, err := Lang(string(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(out)\n\treturn nil\n}\n\nfunc Lang(in string) (out string, err error) {\n\treg := regexp.MustCompile(\"<[^>]+>\")\n\tout = reg.ReplaceAllStringFunc(in, repl)\n\treturn out, nil\n}\n\nfunc repl(in string) (out string) {\n\tif in == \"</code>\" {\n\t\t\n\t\treturn \"</\"+\"lang>\"\n\t}\n\n\t\n\tmid := in[1 : len(in)-1]\n\n\t\n\tvar langs = []string{\n\t\t\"abap\", \"actionscript\", \"actionscript3\", \"ada\", \"apache\", \"applescript\",\n\t\t\"apt_sources\", \"asm\", \"asp\", \"autoit\", \"avisynth\", \"bash\", \"basic4gl\",\n\t\t\"bf\", \"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\", \"cfm\",\n\t\t\"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\", \"d\", \"delphi\",\n\t\t\"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\", \"fortran\", \"freebasic\",\n\t\t\"genero\", \"gettext\", \"glsl\", \"gml\", \"gnuplot\", \"go\", \"groovy\", \"haskell\",\n\t\t\"hq9plus\", \"html4strict\", \"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\",\n\t\t\"java5\", \"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\", \"m68k\",\n\t\t\"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\", \"mysql\", \"nsis\",\n\t\t\"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\", \"oracle11\", \"oracle8\", \"pascal\",\n\t\t\"per\", \"perl\", \"php\", \"php-brief\", \"pic16\", \"pixelbender\", \"plsql\",\n\t\t\"povray\", \"powershell\", \"progress\", \"prolog\", \"providex\", \"python\",\n\t\t\"qbasic\", \"rails\", \"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\",\n\t\t\"scilab\", \"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\", \"verilog\",\n\t\t\"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\", \"whitespace\", \"winbatch\",\n\t\t\"xml\", \"xorg_conf\", \"xpp\", \"z80\",\n\t}\n\tfor _, lang := range langs {\n\t\tif mid == lang {\n\t\t\t\n\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"/\") {\n\t\t\tif mid[len(\"/\"):] == lang {\n\t\t\t\t\n\t\t\t\treturn \"</\"+\"lang>\"\n\t\t\t}\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"code \") {\n\t\t\tif mid[len(\"code \"):] == lang {\n\t\t\t\t\n\t\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn in\n}\n"}
{"id": 58511, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 58512, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n"}
{"id": 58513, "name": "OpenWebNet password", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n    start := true\n    num1 := uint32(0)\n    num2 := num1\n    i, _ := strconv.Atoi(password)\n    pwd := uint32(i)\n    for _, c := range nonce {\n        if c != '0' {\n            if start {\n                num2 = pwd\n            }\n            start = false\n        }\n        switch c {\n        case '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        case '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        case '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        case '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        case '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        case '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        case '7':\n            num3 := num2 & 0x0000FF00\n            num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n            num1 = num3 | num4\n            num2 = (num2 & 0xFF000000) >> 8\n        case '8':\n            num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n            num2 = (num2 & 0x00FF0000) >> 8\n        case '9':\n            num1 = ^num2\n        default:\n            num1 = num2\n        }\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if c != '0' && c != '9' {\n            num1 |= num2\n        }\n        num2 = num1\n    }\n    return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n    res := ownCalcPass(password, nonce)\n    m := fmt.Sprintf(\"%s  %s  %-10d  %-10d\", password, nonce, res, expected)\n    if res == expected {\n        fmt.Println(\"PASS\", m)\n    } else {\n        fmt.Println(\"FAIL\", m)\n    }\n}\n\nfunc main() {\n    testPasswordCalc(\"12345\", \"603356072\", 25280520)\n    testPasswordCalc(\"12345\", \"410501656\", 119537670)\n    testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}\n"}
{"id": 58514, "name": "ADFGVX cipher", "Python": "\n\nfrom random import shuffle, choice\nfrom itertools import product, accumulate\nfrom numpy import floor, sqrt\n\nclass ADFGVX:\n    \n    def __init__(self, spoly, k, alph='ADFGVX'):\n        self.polybius = list(spoly.upper())\n        self.pdim = int(floor(sqrt(len(self.polybius))))\n        self.key = list(k.upper())\n        self.keylen = len(self.key)\n        self.alphabet = list(alph)\n        pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)]\n        self.encode = dict(zip(self.polybius, pairs))\n        self.decode = dict((v, k) for (k, v) in self.encode.items())\n\n    def encrypt(self, msg):\n        \n        chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius]))\n        colvecs = [(lett, chars[i:len(chars):self.keylen]) \\\n            for (i, lett) in enumerate(self.key)]\n        colvecs.sort(key=lambda x: x[0])\n        return ''.join([''.join(a[1]) for a in colvecs])\n\n    def decrypt(self, cod):\n        \n        chars = [c for c in cod if c in self.alphabet]\n        sortedkey = sorted(self.key)\n        order = [self.key.index(ch) for ch in sortedkey]\n        originalorder = [sortedkey.index(ch) for ch in self.key]\n        base, extra = divmod(len(chars), self.keylen)\n        strides = [base + (1 if extra > i else 0) for i in order]    \n        starts = list(accumulate(strides[:-1], lambda x, y: x + y))  \n        starts = [0] + starts                                        \n        ends = [starts[i] + strides[i] for i in range(self.keylen)]  \n        cols = [chars[starts[i]:ends[i]] for i in originalorder]     \n        pairs = []                                                   \n        for i in range((len(chars) - 1) // self.keylen + 1):\n            for j in range(self.keylen):\n                if i * self.keylen + j < len(chars):\n                    pairs.append(cols[j][i])\n\n        return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)])\n\n\nif __name__ == '__main__':\n    PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')\n    shuffle(PCHARS)\n    POLYBIUS = ''.join(PCHARS)\n    with open('unixdict.txt') as fh:\n        WORDS = [w for w in (fh.read()).split() \\\n            if len(w) == 9 and len(w) == len(set(list(w)))]\n        KEY = choice(WORDS)\n\n    SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM'\n    print(f'Polybius: {POLYBIUS}, key: {KEY}')\n    print('Message: ', MESSAGE)\n    ENCODED = SECRET.encrypt(MESSAGE)\n    DECODED = SECRET.decrypt(ENCODED)\n    print('Encoded: ', ENCODED)\n    print('Decoded: ', DECODED)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n)\n\nvar adfgvx = \"ADFGVX\"\nvar alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\nfunc distinct(bs []byte) []byte {\n    var u []byte\n    for _, b := range bs {\n        if !bytes.Contains(u, []byte{b}) {\n            u = append(u, b)\n        }\n    }\n    return u\n}\n\nfunc allAsciiAlphaNum(word []byte) bool {\n    for _, b := range word {\n        if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc orderKey(key string) []int {\n    temp := make([][2]byte, len(key))\n    for i := 0; i < len(key); i++ {\n        temp[i] = [2]byte{key[i], byte(i)}\n    }\n    sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] })\n    res := make([]int, len(key))\n    for i := 0; i < len(key); i++ {\n        res[i] = int(temp[i][1])\n    }\n    return res\n}\n\nfunc createPolybius() []string {\n    temp := []byte(alphabet)\n    rand.Shuffle(36, func(i, j int) {\n        temp[i], temp[j] = temp[j], temp[i]\n    })\n    alphabet = string(temp)\n    fmt.Println(\"6 x 6 Polybius square:\\n\")\n    fmt.Println(\"  | A D F G V X\")\n    fmt.Println(\"---------------\")\n    p := make([]string, 6)\n    for i := 0; i < 6; i++ {\n        fmt.Printf(\"%c | \", adfgvx[i])\n        p[i] = alphabet[6*i : 6*(i+1)]\n        for _, c := range p[i] {\n            fmt.Printf(\"%c \", c)\n        }\n        fmt.Println()\n    }\n    return p\n}\n\nfunc createKey(n int) string {\n    if n < 7 || n > 12 {\n        log.Fatal(\"Key should be within 7 and 12 letters long.\")\n    }\n    bs, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Split(bs, []byte{'\\n'})\n    var candidates [][]byte\n    for _, word := range words {\n        if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) {\n            candidates = append(candidates, word)\n        }\n    }\n    k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))]))\n    fmt.Println(\"\\nThe key is\", k)\n    return k\n}\n\nfunc encrypt(polybius []string, key, plainText string) string {\n    temp := \"\"\nouter:\n    for _, ch := range []byte(plainText) {\n        for r := 0; r <= 5; r++ {\n            for c := 0; c <= 5; c++ {\n                if polybius[r][c] == ch {\n                    temp += fmt.Sprintf(\"%c%c\", adfgvx[r], adfgvx[c])\n                    continue outer\n                }\n            }\n        }\n    }\n    colLen := len(temp) / len(key)\n    \n    if len(temp)%len(key) > 0 {\n        colLen++\n    }\n    table := make([][]string, colLen)\n    for i := 0; i < colLen; i++ {\n        table[i] = make([]string, len(key))\n    }\n    for i := 0; i < len(temp); i++ {\n        table[i/len(key)][i%len(key)] = string(temp[i])\n    }\n    order := orderKey(key)\n    cols := make([][]string, len(key))\n    for i := 0; i < len(key); i++ {\n        cols[i] = make([]string, colLen)\n        for j := 0; j < colLen; j++ {\n            cols[i][j] = table[j][order[i]]\n        }\n    }\n    res := make([]string, len(cols))\n    for i := 0; i < len(cols); i++ {\n        res[i] = strings.Join(cols[i], \"\")\n    }\n    return strings.Join(res, \" \")\n}\n\nfunc decrypt(polybius []string, key, cipherText string) string {\n    colStrs := strings.Split(cipherText, \" \")\n    \n    maxColLen := 0\n    for _, s := range colStrs {\n        if len(s) > maxColLen {\n            maxColLen = len(s)\n        }\n    }\n    cols := make([][]string, len(colStrs))\n    for i, s := range colStrs {\n        var ls []string\n        for _, c := range s {\n            ls = append(ls, string(c))\n        }\n        if len(s) < maxColLen {\n            cols[i] = make([]string, maxColLen)\n            copy(cols[i], ls)\n        } else {\n            cols[i] = ls\n        }\n    }\n    table := make([][]string, maxColLen)\n    order := orderKey(key)\n    for i := 0; i < maxColLen; i++ {\n        table[i] = make([]string, len(key))\n        for j := 0; j < len(key); j++ {\n            table[i][order[j]] = cols[j][i]\n        }\n    }\n    temp := \"\"\n    for i := 0; i < len(table); i++ {\n        temp += strings.Join(table[i], \"\")\n    }\n    plainText := \"\"\n    for i := 0; i < len(temp); i += 2 {\n        r := strings.IndexByte(adfgvx, temp[i])\n        c := strings.IndexByte(adfgvx, temp[i+1])\n        plainText = plainText + string(polybius[r][c])\n    }\n    return plainText\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    plainText := \"ATTACKAT1200AM\"\n    polybius := createPolybius()\n    key := createKey(9)\n    fmt.Println(\"\\nPlaintext :\", plainText)\n    cipherText := encrypt(polybius, key, plainText)\n    fmt.Println(\"\\nEncrypted :\", cipherText)\n    plainText2 := decrypt(polybius, key, cipherText)\n    fmt.Println(\"\\nDecrypted :\", plainText2)\n}\n"}
{"id": 58515, "name": "ADFGVX cipher", "Python": "\n\nfrom random import shuffle, choice\nfrom itertools import product, accumulate\nfrom numpy import floor, sqrt\n\nclass ADFGVX:\n    \n    def __init__(self, spoly, k, alph='ADFGVX'):\n        self.polybius = list(spoly.upper())\n        self.pdim = int(floor(sqrt(len(self.polybius))))\n        self.key = list(k.upper())\n        self.keylen = len(self.key)\n        self.alphabet = list(alph)\n        pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)]\n        self.encode = dict(zip(self.polybius, pairs))\n        self.decode = dict((v, k) for (k, v) in self.encode.items())\n\n    def encrypt(self, msg):\n        \n        chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius]))\n        colvecs = [(lett, chars[i:len(chars):self.keylen]) \\\n            for (i, lett) in enumerate(self.key)]\n        colvecs.sort(key=lambda x: x[0])\n        return ''.join([''.join(a[1]) for a in colvecs])\n\n    def decrypt(self, cod):\n        \n        chars = [c for c in cod if c in self.alphabet]\n        sortedkey = sorted(self.key)\n        order = [self.key.index(ch) for ch in sortedkey]\n        originalorder = [sortedkey.index(ch) for ch in self.key]\n        base, extra = divmod(len(chars), self.keylen)\n        strides = [base + (1 if extra > i else 0) for i in order]    \n        starts = list(accumulate(strides[:-1], lambda x, y: x + y))  \n        starts = [0] + starts                                        \n        ends = [starts[i] + strides[i] for i in range(self.keylen)]  \n        cols = [chars[starts[i]:ends[i]] for i in originalorder]     \n        pairs = []                                                   \n        for i in range((len(chars) - 1) // self.keylen + 1):\n            for j in range(self.keylen):\n                if i * self.keylen + j < len(chars):\n                    pairs.append(cols[j][i])\n\n        return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)])\n\n\nif __name__ == '__main__':\n    PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')\n    shuffle(PCHARS)\n    POLYBIUS = ''.join(PCHARS)\n    with open('unixdict.txt') as fh:\n        WORDS = [w for w in (fh.read()).split() \\\n            if len(w) == 9 and len(w) == len(set(list(w)))]\n        KEY = choice(WORDS)\n\n    SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM'\n    print(f'Polybius: {POLYBIUS}, key: {KEY}')\n    print('Message: ', MESSAGE)\n    ENCODED = SECRET.encrypt(MESSAGE)\n    DECODED = SECRET.decrypt(ENCODED)\n    print('Encoded: ', ENCODED)\n    print('Decoded: ', DECODED)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n)\n\nvar adfgvx = \"ADFGVX\"\nvar alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\nfunc distinct(bs []byte) []byte {\n    var u []byte\n    for _, b := range bs {\n        if !bytes.Contains(u, []byte{b}) {\n            u = append(u, b)\n        }\n    }\n    return u\n}\n\nfunc allAsciiAlphaNum(word []byte) bool {\n    for _, b := range word {\n        if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc orderKey(key string) []int {\n    temp := make([][2]byte, len(key))\n    for i := 0; i < len(key); i++ {\n        temp[i] = [2]byte{key[i], byte(i)}\n    }\n    sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] })\n    res := make([]int, len(key))\n    for i := 0; i < len(key); i++ {\n        res[i] = int(temp[i][1])\n    }\n    return res\n}\n\nfunc createPolybius() []string {\n    temp := []byte(alphabet)\n    rand.Shuffle(36, func(i, j int) {\n        temp[i], temp[j] = temp[j], temp[i]\n    })\n    alphabet = string(temp)\n    fmt.Println(\"6 x 6 Polybius square:\\n\")\n    fmt.Println(\"  | A D F G V X\")\n    fmt.Println(\"---------------\")\n    p := make([]string, 6)\n    for i := 0; i < 6; i++ {\n        fmt.Printf(\"%c | \", adfgvx[i])\n        p[i] = alphabet[6*i : 6*(i+1)]\n        for _, c := range p[i] {\n            fmt.Printf(\"%c \", c)\n        }\n        fmt.Println()\n    }\n    return p\n}\n\nfunc createKey(n int) string {\n    if n < 7 || n > 12 {\n        log.Fatal(\"Key should be within 7 and 12 letters long.\")\n    }\n    bs, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Split(bs, []byte{'\\n'})\n    var candidates [][]byte\n    for _, word := range words {\n        if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) {\n            candidates = append(candidates, word)\n        }\n    }\n    k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))]))\n    fmt.Println(\"\\nThe key is\", k)\n    return k\n}\n\nfunc encrypt(polybius []string, key, plainText string) string {\n    temp := \"\"\nouter:\n    for _, ch := range []byte(plainText) {\n        for r := 0; r <= 5; r++ {\n            for c := 0; c <= 5; c++ {\n                if polybius[r][c] == ch {\n                    temp += fmt.Sprintf(\"%c%c\", adfgvx[r], adfgvx[c])\n                    continue outer\n                }\n            }\n        }\n    }\n    colLen := len(temp) / len(key)\n    \n    if len(temp)%len(key) > 0 {\n        colLen++\n    }\n    table := make([][]string, colLen)\n    for i := 0; i < colLen; i++ {\n        table[i] = make([]string, len(key))\n    }\n    for i := 0; i < len(temp); i++ {\n        table[i/len(key)][i%len(key)] = string(temp[i])\n    }\n    order := orderKey(key)\n    cols := make([][]string, len(key))\n    for i := 0; i < len(key); i++ {\n        cols[i] = make([]string, colLen)\n        for j := 0; j < colLen; j++ {\n            cols[i][j] = table[j][order[i]]\n        }\n    }\n    res := make([]string, len(cols))\n    for i := 0; i < len(cols); i++ {\n        res[i] = strings.Join(cols[i], \"\")\n    }\n    return strings.Join(res, \" \")\n}\n\nfunc decrypt(polybius []string, key, cipherText string) string {\n    colStrs := strings.Split(cipherText, \" \")\n    \n    maxColLen := 0\n    for _, s := range colStrs {\n        if len(s) > maxColLen {\n            maxColLen = len(s)\n        }\n    }\n    cols := make([][]string, len(colStrs))\n    for i, s := range colStrs {\n        var ls []string\n        for _, c := range s {\n            ls = append(ls, string(c))\n        }\n        if len(s) < maxColLen {\n            cols[i] = make([]string, maxColLen)\n            copy(cols[i], ls)\n        } else {\n            cols[i] = ls\n        }\n    }\n    table := make([][]string, maxColLen)\n    order := orderKey(key)\n    for i := 0; i < maxColLen; i++ {\n        table[i] = make([]string, len(key))\n        for j := 0; j < len(key); j++ {\n            table[i][order[j]] = cols[j][i]\n        }\n    }\n    temp := \"\"\n    for i := 0; i < len(table); i++ {\n        temp += strings.Join(table[i], \"\")\n    }\n    plainText := \"\"\n    for i := 0; i < len(temp); i += 2 {\n        r := strings.IndexByte(adfgvx, temp[i])\n        c := strings.IndexByte(adfgvx, temp[i+1])\n        plainText = plainText + string(polybius[r][c])\n    }\n    return plainText\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    plainText := \"ATTACKAT1200AM\"\n    polybius := createPolybius()\n    key := createKey(9)\n    fmt.Println(\"\\nPlaintext :\", plainText)\n    cipherText := encrypt(polybius, key, plainText)\n    fmt.Println(\"\\nEncrypted :\", cipherText)\n    plainText2 := decrypt(polybius, key, cipherText)\n    fmt.Println(\"\\nDecrypted :\", plainText2)\n}\n"}
{"id": 58516, "name": "Exponentiation with infix operators in (or operating on) the base", "Python": "from itertools import product\n\nxx = '-5 +5'.split()\npp = '2 3'.split()\ntexts = '-x**p -(x)**p (-x)**p -(x**p)'.split()\n\nprint('Integer variable exponentiation')\nfor x, p in product(xx, pp):\n    print(f'  x,p = {x:2},{p}; ', end=' ')\n    x, p = int(x), int(p)\n    print('; '.join(f\"{t} =={eval(t):4}\" for t in texts))\n\nprint('\\nBonus integer literal exponentiation')\nX, P = 'xp'\nxx.insert(0, ' 5')\ntexts.insert(0, 'x**p')\nfor x, p in product(xx, pp):\n    texts2 = [t.replace(X, x).replace(P, p) for t in texts]\n    print(' ', '; '.join(f\"{t2} =={eval(t2):4}\" for t2 in texts2))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype float float64\n\nfunc (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }\n\nfunc main() {\n    ops := []string{\"-x.p(e)\", \"-(x).p(e)\", \"(-x).p(e)\", \"-(x.p(e))\"}\n    for _, x := range []float{float(-5), float(5)} {\n        for _, e := range []float{float(2), float(3)} {\n            fmt.Printf(\"x = %2.0f e = %0.0f | \", x, e)\n            fmt.Printf(\"%s = %4.0f | \", ops[0], -x.p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[1], -(x).p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[2], (-x).p(e))\n            fmt.Printf(\"%s = %4.0f\\n\", ops[3], -(x.p(e)))\n        }\n    }\n}\n"}
{"id": 58517, "name": "Exponentiation with infix operators in (or operating on) the base", "Python": "from itertools import product\n\nxx = '-5 +5'.split()\npp = '2 3'.split()\ntexts = '-x**p -(x)**p (-x)**p -(x**p)'.split()\n\nprint('Integer variable exponentiation')\nfor x, p in product(xx, pp):\n    print(f'  x,p = {x:2},{p}; ', end=' ')\n    x, p = int(x), int(p)\n    print('; '.join(f\"{t} =={eval(t):4}\" for t in texts))\n\nprint('\\nBonus integer literal exponentiation')\nX, P = 'xp'\nxx.insert(0, ' 5')\ntexts.insert(0, 'x**p')\nfor x, p in product(xx, pp):\n    texts2 = [t.replace(X, x).replace(P, p) for t in texts]\n    print(' ', '; '.join(f\"{t2} =={eval(t2):4}\" for t2 in texts2))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype float float64\n\nfunc (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }\n\nfunc main() {\n    ops := []string{\"-x.p(e)\", \"-(x).p(e)\", \"(-x).p(e)\", \"-(x.p(e))\"}\n    for _, x := range []float{float(-5), float(5)} {\n        for _, e := range []float{float(2), float(3)} {\n            fmt.Printf(\"x = %2.0f e = %0.0f | \", x, e)\n            fmt.Printf(\"%s = %4.0f | \", ops[0], -x.p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[1], -(x).p(e))\n            fmt.Printf(\"%s = %4.0f | \", ops[2], (-x).p(e))\n            fmt.Printf(\"%s = %4.0f\\n\", ops[3], -(x.p(e)))\n        }\n    }\n}\n"}
{"id": 58518, "name": "Separate the house number from the street name", "Python": "Plataanstraat 5           split as (Plataanstraat, 5)\nStraat 12                 split as (Straat, 12)\nStraat 12 II              split as (Straat, 12 II)\nDr. J. Straat   12        split as (Dr. J. Straat  , 12)\nDr. J. Straat 12 a        split as (Dr. J. Straat, 12 a)\nDr. J. Straat 12-14       split as (Dr. J. Straat, 12-14)\nLaan 1940 – 1945 37       split as (Laan 1940 – 1945, 37)\nPlein 1940 2              split as (Plein 1940, 2)\n1213-laan 11              split as (1213-laan, 11)\n16 april 1944 Pad 1       split as (16 april 1944 Pad, 1)\n1e Kruisweg 36            split as (1e Kruisweg, 36)\nLaan 1940-’45 66          split as (Laan 1940-’45, 66)\nLaan ’40-’45              split as (Laan ’40-’45,)\nLangeloërduinen 3 46      split as (Langeloërduinen, 3 46)\nMarienwaerdt 2e Dreef 2   split as (Marienwaerdt 2e Dreef, 2)\nProvincialeweg N205 1     split as (Provincialeweg N205, 1)\nRivium 2e Straat 59.      split as (Rivium 2e Straat, 59.)\nNieuwe gracht 20rd        split as (Nieuwe gracht, 20rd)\nNieuwe gracht 20rd 2      split as (Nieuwe gracht, 20rd 2)\nNieuwe gracht 20zw /2     split as (Nieuwe gracht, 20zw /2)\nNieuwe gracht 20zw/3      split as (Nieuwe gracht, 20zw/3)\nNieuwe gracht 20 zw/4     split as (Nieuwe gracht, 20 zw/4)\nBahnhofstr. 4             split as (Bahnhofstr., 4)\nWertstr. 10               split as (Wertstr., 10)\nLindenhof 1               split as (Lindenhof, 1)\nNordesch 20               split as (Nordesch, 20)\nWeilstr. 6                split as (Weilstr., 6)\nHarthauer Weg 2           split as (Harthauer Weg, 2)\nMainaustr. 49             split as (Mainaustr., 49)\nAugust-Horch-Str. 3       split as (August-Horch-Str., 3)\nMarktplatz 31             split as (Marktplatz, 31)\nSchmidener Weg 3          split as (Schmidener Weg, 3)\nKarl-Weysser-Str. 6       split as (Karl-Weysser-Str., 6)''')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc isDigit(b byte) bool {\n    return '0' <= b && b <= '9'\n}\n\nfunc separateHouseNumber(address string) (street string, house string) {\n    length := len(address)\n    fields := strings.Fields(address)\n    size := len(fields)\n    last := fields[size-1]\n    penult := fields[size-2]\n    if isDigit(last[0]) {\n        isdig := isDigit(penult[0])\n        if size > 2 && isdig && !strings.HasPrefix(penult, \"194\") {\n            house = fmt.Sprintf(\"%s %s\", penult, last)\n        } else {\n            house = last\n        }\n    } else if size > 2 {\n        house = fmt.Sprintf(\"%s %s\", penult, last)\n    }\n    street = strings.TrimRight(address[:length-len(house)], \" \")\n    return\n}\n\nfunc main() {\n    addresses := [...]string{\n        \"Plataanstraat 5\",\n        \"Straat 12\",\n        \"Straat 12 II\",\n        \"Dr. J. Straat   12\",\n        \"Dr. J. Straat 12 a\",\n        \"Dr. J. Straat 12-14\",\n        \"Laan 1940 - 1945 37\",\n        \"Plein 1940 2\",\n        \"1213-laan 11\",\n        \"16 april 1944 Pad 1\",\n        \"1e Kruisweg 36\",\n        \"Laan 1940-'45 66\",\n        \"Laan '40-'45\",\n        \"Langeloërduinen 3 46\",\n        \"Marienwaerdt 2e Dreef 2\",\n        \"Provincialeweg N205 1\",\n        \"Rivium 2e Straat 59.\",\n        \"Nieuwe gracht 20rd\",\n        \"Nieuwe gracht 20rd 2\",\n        \"Nieuwe gracht 20zw /2\",\n        \"Nieuwe gracht 20zw/3\",\n        \"Nieuwe gracht 20 zw/4\",\n        \"Bahnhofstr. 4\",\n        \"Wertstr. 10\",\n        \"Lindenhof 1\",\n        \"Nordesch 20\",\n        \"Weilstr. 6\",\n        \"Harthauer Weg 2\",\n        \"Mainaustr. 49\",\n        \"August-Horch-Str. 3\",\n        \"Marktplatz 31\",\n        \"Schmidener Weg 3\",\n        \"Karl-Weysser-Str. 6\",\n    }\n    fmt.Println(\"Street                   House Number\")\n    fmt.Println(\"---------------------    ------------\")\n    for _, address := range addresses {\n        street, house := separateHouseNumber(address)\n        if house == \"\" {\n            house = \"(none)\"\n        }\n        fmt.Printf(\"%-22s   %s\\n\", street, house)\n    }\n}\n"}
{"id": 58519, "name": "Display an outline as a nested table", "Python": "\n\nimport itertools\nimport re\nimport sys\n\nfrom collections import deque\nfrom typing import NamedTuple\n\n\nRE_OUTLINE = re.compile(r\"^((?: |\\t)*)(.+)$\", re.M)\n\nCOLORS = itertools.cycle(\n    [\n        \"\n        \"\n        \"\n        \"\n        \"\n    ]\n)\n\n\nclass Node:\n    def __init__(self, indent, value, parent, children=None):\n        self.indent = indent\n        self.value = value\n        self.parent = parent\n        self.children = children or []\n\n        self.color = None\n\n    def depth(self):\n        if self.parent:\n            return self.parent.depth() + 1\n        return -1\n\n    def height(self):\n        \n        if not self.children:\n            return 0\n        return max(child.height() for child in self.children) + 1\n\n    def colspan(self):\n        if self.leaf:\n            return 1\n        return sum(child.colspan() for child in self.children)\n\n    @property\n    def leaf(self):\n        return not bool(self.children)\n\n    def __iter__(self):\n        \n        q = deque()\n        q.append(self)\n        while q:\n            node = q.popleft()\n            yield node\n            q.extend(node.children)\n\n\nclass Token(NamedTuple):\n    indent: int\n    value: str\n\n\ndef tokenize(outline):\n    \n    for match in RE_OUTLINE.finditer(outline):\n        indent, value = match.groups()\n        yield Token(len(indent), value)\n\n\ndef parse(outline):\n    \n    \n    tokens = list(tokenize(outline))\n\n    \n    temp_root = Node(-1, \"\", None)\n    _parse(tokens, 0, temp_root)\n\n    \n    root = temp_root.children[0]\n    pad_tree(root, root.height())\n\n    return root\n\n\ndef _parse(tokens, index, node):\n    \n    \n    if index >= len(tokens):\n        return\n\n    token = tokens[index]\n\n    if token.indent == node.indent:\n        \n        current = Node(token.indent, token.value, node.parent)\n        node.parent.children.append(current)\n        _parse(tokens, index + 1, current)\n\n    elif token.indent > node.indent:\n        \n        current = Node(token.indent, token.value, node)\n        node.children.append(current)\n        _parse(tokens, index + 1, current)\n\n    elif token.indent < node.indent:\n        \n        _parse(tokens, index, node.parent)\n\n\ndef pad_tree(node, height):\n    \n    if node.leaf and node.depth() < height:\n        pad_node = Node(node.indent + 1, \"\", node)\n        node.children.append(pad_node)\n\n    for child in node.children:\n        pad_tree(child, height)\n\n\ndef color_tree(node):\n    \n    if not node.value:\n        node.color = \"\n    elif node.depth() <= 1:\n        node.color = next(COLORS)\n    else:\n        node.color = node.parent.color\n\n    for child in node.children:\n        color_tree(child)\n\n\ndef table_data(node):\n    \n    indent = \"    \"\n\n    if node.colspan() > 1:\n        colspan = f'colspan=\"{node.colspan()}\"'\n    else:\n        colspan = \"\"\n\n    if node.color:\n        style = f'style=\"background-color: {node.color};\"'\n    else:\n        style = \"\"\n\n    attrs = \" \".join([colspan, style])\n    return f\"{indent}<td{attrs}>{node.value}</td>\"\n\n\ndef html_table(tree):\n    \n    \n    table_cols = tree.colspan()\n\n    \n    row_cols = 0\n\n    \n    buf = [\"<table style='text-align: center;'>\"]\n\n    \n    for node in tree:\n        if row_cols == 0:\n            buf.append(\"  <tr>\")\n\n        buf.append(table_data(node))\n        row_cols += node.colspan()\n\n        if row_cols == table_cols:\n            buf.append(\"  </tr>\")\n            row_cols = 0\n\n    buf.append(\"</table>\")\n    return \"\\n\".join(buf)\n\n\ndef wiki_table_data(node):\n    \n    if not node.value:\n        return \"|  |\"\n\n    if node.colspan() > 1:\n        colspan = f\"colspan={node.colspan()}\"\n    else:\n        colspan = \"\"\n\n    if node.color:\n        style = f'style=\"background: {node.color};\"'\n    else:\n        style = \"\"\n\n    attrs = \" \".join([colspan, style])\n    return f\"| {attrs} | {node.value}\"\n\n\ndef wiki_table(tree):\n    \n    \n    table_cols = tree.colspan()\n\n    \n    row_cols = 0\n\n    \n    buf = ['{| class=\"wikitable\" style=\"text-align: center;\"']\n\n    for node in tree:\n        if row_cols == 0:\n            buf.append(\"|-\")\n\n        buf.append(wiki_table_data(node))\n        row_cols += node.colspan()\n\n        if row_cols == table_cols:\n            row_cols = 0\n\n    buf.append(\"|}\")\n    return \"\\n\".join(buf)\n\n\ndef example(table_format=\"wiki\"):\n    \n\n    outline = (\n        \"Display an outline as a nested table.\\n\"\n        \"    Parse the outline to a tree,\\n\"\n        \"        measuring the indent of each line,\\n\"\n        \"        translating the indentation to a nested structure,\\n\"\n        \"        and padding the tree to even depth.\\n\"\n        \"    count the leaves descending from each node,\\n\"\n        \"        defining the width of a leaf as 1,\\n\"\n        \"        and the width of a parent node as a sum.\\n\"\n        \"            (The sum of the widths of its children)\\n\"\n        \"    and write out a table with 'colspan' values\\n\"\n        \"        either as a wiki table,\\n\"\n        \"        or as HTML.\"\n    )\n\n    tree = parse(outline)\n    color_tree(tree)\n\n    if table_format == \"wiki\":\n        print(wiki_table(tree))\n    else:\n        print(html_table(tree))\n\n\nif __name__ == \"__main__\":\n    args = sys.argv[1:]\n\n    if len(args) == 1:\n        table_format = args[0]\n    else:\n        table_format = \"wiki\"\n\n    example(table_format)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype nNode struct {\n    name     string\n    children []nNode\n}\n\ntype iNode struct {\n    level int\n    name  string\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n    if level == 0 {\n        n.name = iNodes[0].name\n    }\n    for i := start + 1; i < len(iNodes); i++ {\n        if iNodes[i].level == level+1 {\n            c := nNode{iNodes[i].name, nil}\n            toNest(iNodes, i, level+1, &c)\n            n.children = append(n.children, c)\n        } else if iNodes[i].level <= level {\n            return\n        }\n    }\n}\n\nfunc makeIndent(outline string, tab int) []iNode {\n    lines := strings.Split(outline, \"\\n\")\n    iNodes := make([]iNode, len(lines))\n    for i, line := range lines {\n        line2 := strings.TrimLeft(line, \" \")\n        le, le2 := len(line), len(line2)\n        level := (le - le2) / tab\n        iNodes[i] = iNode{level, line2}\n    }\n    return iNodes\n}\n\nfunc toMarkup(n nNode, cols []string, depth int) string {\n    var span int\n\n    var colSpan func(nn nNode)\n    colSpan = func(nn nNode) {\n        for i, c := range nn.children {\n            if i > 0 {\n                span++\n            }\n            colSpan(c)\n        }\n    }\n\n    for _, c := range n.children {\n        span = 1\n        colSpan(c)\n    }\n    var lines []string\n    lines = append(lines, `{| class=\"wikitable\" style=\"text-align: center;\"`)\n    const l1, l2 = \"|-\", \"|  |\"\n    lines = append(lines, l1)\n    span = 1\n    colSpan(n)\n    s := fmt.Sprintf(`| style=\"background: %s \" colSpan=%d | %s`, cols[0], span, n.name)\n    lines = append(lines, s, l1)\n\n    var nestedFor func(nn nNode, level, maxLevel, col int)\n    nestedFor = func(nn nNode, level, maxLevel, col int) {\n        if level == 1 && maxLevel > level {\n            for i, c := range nn.children {\n                nestedFor(c, 2, maxLevel, i)\n            }\n        } else if level < maxLevel {\n            for _, c := range nn.children {\n                nestedFor(c, level+1, maxLevel, col)\n            }\n        } else {\n            if len(nn.children) > 0 {\n                for i, c := range nn.children {\n                    span = 1\n                    colSpan(c)\n                    cn := col + 1\n                    if maxLevel == 1 {\n                        cn = i + 1\n                    }\n                    s := fmt.Sprintf(`| style=\"background: %s \" colspan=%d | %s`, cols[cn], span, c.name)\n                    lines = append(lines, s)\n                }\n            } else {\n                lines = append(lines, l2)\n            }\n        }\n    }\n    for maxLevel := 1; maxLevel < depth; maxLevel++ {\n        nestedFor(n, 1, maxLevel, 0)\n        if maxLevel < depth-1 {\n            lines = append(lines, l1)\n        }\n    }\n    lines = append(lines, \"|}\")\n    return strings.Join(lines, \"\\n\")\n}\n\nfunc main() {\n    const outline = `Display an outline as a nested table.\n    Parse the outline to a tree,\n        measuring the indent of each line,\n        translating the indentation to a nested structure,\n        and padding the tree to even depth.\n    count the leaves descending from each node,\n        defining the width of a leaf as 1,\n        and the width of a parent node as a sum.\n            (The sum of the widths of its children) \n    and write out a table with 'colspan' values\n        either as a wiki table,\n        or as HTML.`\n    const (\n        yellow = \"#ffffe6;\"\n        orange = \"#ffebd2;\"\n        green  = \"#f0fff0;\"\n        blue   = \"#e6ffff;\"\n        pink   = \"#ffeeff;\"\n    )\n    cols := []string{yellow, orange, green, blue, pink}\n    iNodes := makeIndent(outline, 4)\n    var n nNode\n    toNest(iNodes, 0, 0, &n)\n    fmt.Println(toMarkup(n, cols, 4))\n\n    fmt.Println(\"\\n\")\n    const outline2 = `Display an outline as a nested table.\n    Parse the outline to a tree,\n        measuring the indent of each line,\n        translating the indentation to a nested structure,\n        and padding the tree to even depth.\n    count the leaves descending from each node,\n        defining the width of a leaf as 1,\n        and the width of a parent node as a sum.\n            (The sum of the widths of its children)\n            Propagating the sums upward as necessary. \n    and write out a table with 'colspan' values\n        either as a wiki table,\n        or as HTML.\n    Optionally add color to the nodes.`\n    cols2 := []string{blue, yellow, orange, green, pink}\n    var n2 nNode\n    iNodes2 := makeIndent(outline2, 4)\n    toNest(iNodes2, 0, 0, &n2)\n    fmt.Println(toMarkup(n2, cols2, 4))\n}\n"}
{"id": 58520, "name": "Common list elements", "Python": "\n\ndef common_list_elements(*lists):\n    return list(set.intersection(*(set(list_) for list_ in lists)))\n\n\nif __name__ == \"__main__\":\n    test_cases = [\n        ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),\n        ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),\n    ]\n\n    for case in test_cases:\n        result = common_list_elements(*case)\n        print(f\"Intersection of {case} is {result}\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc indexOf(l []int, n int) int {\n    for i := 0; i < len(l); i++ {\n        if l[i] == n {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc common2(l1, l2 []int) []int {\n    \n    c1, c2 := len(l1), len(l2)\n    shortest, longest := l1, l2\n    if c1 > c2 {\n        shortest, longest = l2, l1\n    }\n    longest2 := make([]int, len(longest))\n    copy(longest2, longest) \n    var res []int\n    for _, e := range shortest {\n        ix := indexOf(longest2, e)\n        if ix >= 0 {\n            res = append(res, e)\n            longest2 = append(longest2[:ix], longest2[ix+1:]...)\n        }\n    }\n    return res\n}\n\nfunc commonN(ll [][]int) []int {\n    n := len(ll)\n    if n == 0 {\n        return []int{}\n    }\n    if n == 1 {\n        return ll[0]\n    }\n    res := common2(ll[0], ll[1])\n    if n == 2 {\n        return res\n    }\n    for _, l := range ll[2:] {\n        res = common2(res, l)\n    }\n    return res\n}\n\nfunc main() {\n    lls := [][][]int{\n        {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}},\n        {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}},\n    }\n    for _, ll := range lls {\n        fmt.Println(\"Intersection of\", ll, \"is:\")\n        fmt.Println(commonN(ll))\n        fmt.Println()\n    }\n}\n"}
{"id": 58521, "name": "Common list elements", "Python": "\n\ndef common_list_elements(*lists):\n    return list(set.intersection(*(set(list_) for list_ in lists)))\n\n\nif __name__ == \"__main__\":\n    test_cases = [\n        ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),\n        ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),\n    ]\n\n    for case in test_cases:\n        result = common_list_elements(*case)\n        print(f\"Intersection of {case} is {result}\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc indexOf(l []int, n int) int {\n    for i := 0; i < len(l); i++ {\n        if l[i] == n {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc common2(l1, l2 []int) []int {\n    \n    c1, c2 := len(l1), len(l2)\n    shortest, longest := l1, l2\n    if c1 > c2 {\n        shortest, longest = l2, l1\n    }\n    longest2 := make([]int, len(longest))\n    copy(longest2, longest) \n    var res []int\n    for _, e := range shortest {\n        ix := indexOf(longest2, e)\n        if ix >= 0 {\n            res = append(res, e)\n            longest2 = append(longest2[:ix], longest2[ix+1:]...)\n        }\n    }\n    return res\n}\n\nfunc commonN(ll [][]int) []int {\n    n := len(ll)\n    if n == 0 {\n        return []int{}\n    }\n    if n == 1 {\n        return ll[0]\n    }\n    res := common2(ll[0], ll[1])\n    if n == 2 {\n        return res\n    }\n    for _, l := range ll[2:] {\n        res = common2(res, l)\n    }\n    return res\n}\n\nfunc main() {\n    lls := [][][]int{\n        {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}},\n        {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}},\n    }\n    for _, ll := range lls {\n        fmt.Println(\"Intersection of\", ll, \"is:\")\n        fmt.Println(commonN(ll))\n        fmt.Println()\n    }\n}\n"}
{"id": 58522, "name": "Monads_Writer monad", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype mwriter struct {\n    value float64\n    log   string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n    n := f(m.value)\n    n.log = m.log + n.log\n    return n\n}\n\nfunc unit(v float64, s string) mwriter {\n    return mwriter{v, fmt.Sprintf(\"  %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n    return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n    return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n    return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n    mw1 := unit(5, \"Initial value\")\n    mw2 := mw1.bind(root).bind(addOne).bind(half)\n    fmt.Println(\"The Golden Ratio is\", mw2.value)\n    fmt.Println(\"\\nThis was derived as follows:-\")\n    fmt.Println(mw2.log)\n}\n"}
{"id": 58523, "name": "N-queens minimum and knights and bishops", "Python": "\n\nfrom mip import Model, BINARY, xsum, minimize\n\ndef n_queens_min(N):\n    \n    if N < 4:\n        brd = [[0 for i in range(N)] for j in range(N)]\n        brd[0 if N < 2 else 1][0 if N < 2 else 1] = 1\n        return 1, brd\n\n    model = Model()\n    board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)]\n    for k in range(N):\n        model += xsum(board[k][j] for j in range(N)) <= 1\n        model += xsum(board[i][k] for i in range(N)) <= 1\n\n    for k in range(1, 2 * N - 2):\n        model += xsum(board[k - j][j] for j in range(max(0, k - N + 1), min(k + 1, N))) <= 1\n\n    for k in range(2 - N, N - 1):\n        model += xsum(board[k + j][j] for j in range(max(0, -k), min(N - k, N))) <= 1\n\n    for i in range(N):\n        for j in range(N):\n            model += xsum([xsum(board[i][k] for k in range(N)),\n               xsum(board[k][j] for k in range(N)),\n               xsum(board[i + k][j + k] for k in range(-N, N)\n                  if 0 <= i + k < N and 0 <= j + k < N),\n               xsum(board[i - k][j + k] for k in range(-N, N)\n                  if 0 <= i - k < N and 0 <= j + k < N)]) >= 1\n\n    model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N)))\n    model.optimize()\n    return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)]\n\n\ndef n_bishops_min(N):\n    \n    model = Model()\n    board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)]\n\n    for i in range(N):\n        for j in range(N):\n            model += xsum([\n               xsum(board[i + k][j + k] for k in range(-N, N)\n                  if 0 <= i + k < N and 0 <= j + k < N),\n               xsum(board[i - k][j + k] for k in range(-N, N)\n                  if 0 <= i - k < N and 0 <= j + k < N)]) >= 1\n\n    model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N)))\n    model.optimize()\n    return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)]\n\ndef n_knights_min(N):\n    \n    if N < 2:\n        return 1, \"N\"\n\n    knightdeltas = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n    model = Model()\n    \n    board = [[model.add_var(var_type=BINARY) for j in range(N + 4)] for i in range(N + 4)]\n    for i in range(N + 4):\n        model += xsum(board[i][j] for j in [0, 1, N + 2, N + 3]) == 0\n    for j in range(N + 4):\n        model += xsum(board[i][j] for i in [0, 1, N + 2, N + 3]) == 0\n\n    for i in range(2, N + 2):\n        for j in range(2, N + 2):\n            model += xsum([board[i][j]] + [board[i + d[0]][j + d[1]]\n               for d in knightdeltas]) >= 1\n            model += xsum([board[i + d[0]][j + d[1]]\n               for d in knightdeltas] + [100 * board[i][j]]) <= 100\n\n    model.objective = minimize(xsum(board[i][j] for i in range(2, N + 2) for j in range(2, N + 2)))\n    model.optimize()\n    minresult = model.objective_value\n    return minresult, [[board[i][j].x for i in range(2, N + 2)] for j in range(2, N + 2)]\n\n\nif __name__ == '__main__':\n    examples, pieces, chars = [[], [], []], [\"Queens\", \"Bishops\", \"Knights\"], ['Q', 'B', 'N']\n    print(\"   Squares    Queens   Bishops   Knights\")\n    for nrows in range(1, 11):\n        print(str(nrows * nrows).rjust(10), end='')\n        minval, examples[0] = n_queens_min(nrows)\n        print(str(int(minval)).rjust(10), end='')\n        minval, examples[1] = n_bishops_min(nrows)\n        print(str(int(minval)).rjust(10), end='')\n        minval, examples[2] = n_knights_min(nrows)\n        print(str(int(minval)).rjust(10))\n        if nrows == 10:\n            print(\"\\nExamples for N = 10:\")\n            for idx, piece in enumerate(chars):\n                print(f\"\\n{pieces[idx]}:\")\n                for row in examples[idx]:\n                    for sqr in row:\n                        print(chars[idx] if sqr == 1 else '.', '', end = '')\n                    print()\n                print()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n    \"time\"\n)\n\nvar board [][]bool\nvar diag1, diag2 [][]int\nvar diag1Lookup, diag2Lookup []bool\nvar n, minCount int\nvar layout string\n\nfunc isAttacked(piece string, row, col int) bool {\n    if piece == \"Q\" {\n        for i := 0; i < n; i++ {\n            if board[i][col] || board[row][i] {\n                return true\n            }\n        }\n        if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] {\n            return true\n        }\n    } else if piece == \"B\" {\n        if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] {\n            return true\n        }\n    } else { \n        if board[row][col] {\n            return true\n        }\n        if row+2 < n && col-1 >= 0 && board[row+2][col-1] {\n            return true\n        }\n        if row-2 >= 0 && col-1 >= 0 && board[row-2][col-1] {\n            return true\n        }\n        if row+2 < n && col+1 < n && board[row+2][col+1] {\n            return true\n        }\n        if row-2 >= 0 && col+1 < n && board[row-2][col+1] {\n            return true\n        }\n        if row+1 < n && col+2 < n && board[row+1][col+2] {\n            return true\n        }\n        if row-1 >= 0 && col+2 < n && board[row-1][col+2] {\n            return true\n        }\n        if row+1 < n && col-2 >= 0 && board[row+1][col-2] {\n            return true\n        }\n        if row-1 >= 0 && col-2 >= 0 && board[row-1][col-2] {\n            return true\n        }\n    }\n    return false\n}\n\nfunc abs(i int) int {\n    if i < 0 {\n        i = -i\n    }\n    return i\n}\n\nfunc attacks(piece string, row, col, trow, tcol int) bool {\n    if piece == \"Q\" {\n        return row == trow || col == tcol || abs(row-trow) == abs(col-tcol)\n    } else if piece == \"B\" {\n        return abs(row-trow) == abs(col-tcol)\n    } else { \n        rd := abs(trow - row)\n        cd := abs(tcol - col)\n        return (rd == 1 && cd == 2) || (rd == 2 && cd == 1)\n    }\n}\n\nfunc storeLayout(piece string) {\n    var sb strings.Builder\n    for _, row := range board {\n        for _, cell := range row {\n            if cell {\n                sb.WriteString(piece + \" \")\n            } else {\n                sb.WriteString(\". \")\n            }\n        }\n        sb.WriteString(\"\\n\")\n    }\n    layout = sb.String()\n}\n\nfunc placePiece(piece string, countSoFar, maxCount int) {\n    if countSoFar >= minCount {\n        return\n    }\n    allAttacked := true\n    ti := 0\n    tj := 0\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            if !isAttacked(piece, i, j) {\n                allAttacked = false\n                ti = i\n                tj = j\n                break\n            }\n        }\n        if !allAttacked {\n            break\n        }\n    }\n    if allAttacked {\n        minCount = countSoFar\n        storeLayout(piece)\n        return\n    }\n    if countSoFar <= maxCount {\n        si := ti\n        sj := tj\n        if piece == \"K\" {\n            si = si - 2\n            sj = sj - 2\n            if si < 0 {\n                si = 0\n            }\n            if sj < 0 {\n                sj = 0\n            } \n        }\n        for i := si; i < n; i++ {\n            for j := sj; j < n; j++ {\n                if !isAttacked(piece, i, j) {\n                    if (i == ti && j == tj) || attacks(piece, i, j, ti, tj) {\n                        board[i][j] = true\n                        if piece != \"K\" {\n                            diag1Lookup[diag1[i][j]] = true\n                            diag2Lookup[diag2[i][j]] = true\n                        }\n                        placePiece(piece, countSoFar+1, maxCount)\n                        board[i][j] = false\n                        if piece != \"K\" {\n                            diag1Lookup[diag1[i][j]] = false\n                            diag2Lookup[diag2[i][j]] = false\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    start := time.Now()\n    pieces := []string{\"Q\", \"B\", \"K\"}\n    limits := map[string]int{\"Q\": 10, \"B\": 10, \"K\": 10}\n    names := map[string]string{\"Q\": \"Queens\", \"B\": \"Bishops\", \"K\": \"Knights\"}\n    for _, piece := range pieces {\n        fmt.Println(names[piece])\n        fmt.Println(\"=======\\n\")\n\n        for n = 1; ; n++ {\n            board = make([][]bool, n)\n            for i := 0; i < n; i++ {\n                board[i] = make([]bool, n)\n            }\n            if piece != \"K\" {\n                diag1 = make([][]int, n)\n                for i := 0; i < n; i++ {\n                    diag1[i] = make([]int, n)\n                    for j := 0; j < n; j++ {\n                        diag1[i][j] = i + j\n                    }\n                }\n                diag2 = make([][]int, n)\n                for i := 0; i < n; i++ {\n                    diag2[i] = make([]int, n)\n                    for j := 0; j < n; j++ {\n                        diag2[i][j] = i - j + n - 1\n                    }\n                }\n                diag1Lookup = make([]bool, 2*n-1)\n                diag2Lookup = make([]bool, 2*n-1)\n            }\n            minCount = math.MaxInt32\n            layout = \"\"\n            for maxCount := 1; maxCount <= n*n; maxCount++ {\n                placePiece(piece, 0, maxCount)\n                if minCount <= n*n {\n                    break\n                }\n            }\n            fmt.Printf(\"%2d x %-2d : %d\\n\", n, n, minCount)\n            if n == limits[piece] {\n                fmt.Printf(\"\\n%s on a %d x %d board:\\n\", names[piece], n, n)\n                fmt.Println(\"\\n\" + layout)\n                break\n            }\n        }\n    }\n    elapsed := time.Now().Sub(start)\n    fmt.Printf(\"Took %s\\n\", elapsed)\n}\n"}
{"id": 58524, "name": "Wordle comparison", "Python": "\n\nfrom functools import reduce\nfrom operator import add\n\n\n\ndef wordleScore(target, guess):\n    \n    return mapAccumL(amber)(\n        *first(charCounts)(\n            mapAccumL(green)(\n                [], zip(target, guess)\n            )\n        )\n    )[1]\n\n\n\ndef green(residue, tg):\n    \n    t, g = tg\n    return (residue, (g, 2)) if t == g else (\n        [t] + residue, (g, 0)\n    )\n\n\n\ndef amber(tally, cn):\n    \n    c, n = cn\n    return (tally, 2) if 2 == n else (\n        adjust(\n            lambda x: x - 1,\n            c, tally\n        ),\n        1\n    ) if 0 < tally.get(c, 0) else (tally, 0)\n\n\n\n\ndef main():\n    \n    print(' -> '.join(['Target', 'Guess', 'Scores']))\n    print()\n    print(\n        '\\n'.join([\n            wordleReport(*tg) for tg in [\n                (\"ALLOW\", \"LOLLY\"),\n                (\"CHANT\", \"LATTE\"),\n                (\"ROBIN\", \"ALERT\"),\n                (\"ROBIN\", \"SONIC\"),\n                (\"ROBIN\", \"ROBIN\"),\n                (\"BULLY\", \"LOLLY\"),\n                (\"ADAPT\", \"SÅLÅD\"),\n                (\"Ukraine\", \"Ukraíne\"),\n                (\"BBAAB\", \"BBBBBAA\"),\n                (\"BBAABBB\", \"AABBBAA\")\n            ]\n        ])\n    )\n\n\n\ndef wordleReport(target, guess):\n    \n    scoreName = {2: 'green', 1: 'amber', 0: 'gray'}\n\n    if 5 != len(target):\n        return f'{target}: Expected 5 character target.'\n    elif 5 != len(guess):\n        return f'{guess}: Expected 5 character guess.'\n    else:\n        scores = wordleScore(target, guess)\n        return ' -> '.join([\n            target, guess, repr(scores),\n            ' '.join([\n                scoreName[n] for n in scores\n            ])\n        ])\n\n\n\n\n\ndef adjust(f, k, dct):\n    \n    return dict(\n        dct,\n        **{k: f(dct[k]) if k in dct else None}\n    )\n\n\n\ndef charCounts(s):\n    \n    return reduce(\n        lambda a, c: insertWith(add)(c)(1)(a),\n        list(s),\n        {}\n    )\n\n\n\ndef first(f):\n    \n    return lambda xy: (f(xy[0]), xy[1])\n\n\n\n\ndef insertWith(f):\n    \n    return lambda k: lambda x: lambda dct: dict(\n        dct,\n        **{k: f(dct[k], x) if k in dct else x}\n    )\n\n\n\n\ndef mapAccumL(f):\n    \n    def nxt(a, x):\n        return second(lambda v: a[1] + [v])(\n            f(a[0], x)\n        )\n    return lambda acc, xs: reduce(\n        nxt, xs, (acc, [])\n    )\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc wordle(answer, guess string) []int {\n    n := len(guess)\n    if n != len(answer) {\n        log.Fatal(\"The words must be of the same length.\")\n    }\n    answerBytes := []byte(answer)\n    result := make([]int, n) \n    for i := 0; i < n; i++ {\n        if guess[i] == answerBytes[i] {\n            answerBytes[i] = '\\000'\n            result[i] = 2\n        }\n    }\n    for i := 0; i < n; i++ {\n        ix := bytes.IndexByte(answerBytes, guess[i])\n        if ix >= 0 {\n            answerBytes[ix] = '\\000'\n            result[i] = 1\n        }\n    }\n    return result\n}\n\nfunc main() {\n    colors := []string{\"grey\", \"yellow\", \"green\"}\n    pairs := [][]string{\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"},\n    }\n    for _, pair := range pairs {\n        res := wordle(pair[0], pair[1])\n        res2 := make([]string, len(res))\n        for i := 0; i < len(res); i++ {\n            res2[i] = colors[res[i]]\n        }\n        fmt.Printf(\"%s v %s => %v => %v\\n\", pair[0], pair[1], res, res2)\n    }\n}\n"}
{"id": 58525, "name": "Largest product in a grid", "Python": "\n\nfrom math import prod\n\ndef maxproduct(mat, length):\n    \n    nrow, ncol = len(mat), len(mat[0])\n    maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0]\n    for row in range(nrow):\n        for col in range(ncol):\n            row2, col2 = row + length, col + length\n            if row < nrow - length:\n                array = [r[col] for r in mat[row:row2]]\n                pro = prod(array)\n                if pro > maxprod:\n                    maxprod, maxrow, maxcol, arr = pro, [row, row2], col, array\n            if col < ncol - length:\n                pro = prod(mat[row][col:col2])\n                if pro > maxprod:\n                    maxprod, maxrow, maxcol, arr = pro, row, [col, col2], mat[row][col:col2]\n\n    print(f\"The max {length}-product is {maxprod}, product of {arr} at row {maxrow}, col {maxcol}.\")\n\nMATRIX = [\n    [ 8,  2, 22, 97, 38, 15,  0, 40,  0, 75,  4,  5,  7, 78, 52, 12, 50, 77, 91,  8],\n    [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48,  4, 56, 62,  0],\n    [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30,  3, 49, 13, 36, 65],\n    [52, 70, 95, 23,  4, 60, 11, 42, 69, 24, 68, 56,  1, 32, 56, 71, 37,  2, 36, 91],\n    [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],\n    [24, 47, 32, 60, 99,  3, 45,  2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],\n    [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],\n    [67, 26, 20, 68,  2, 62, 12, 20, 95, 63, 94, 39, 63,  8, 40, 91, 66, 49, 94, 21],\n    [24, 55, 58,  5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],\n    [21, 36, 23,  9, 75,  0, 76, 44, 20, 45, 35, 14,  0, 61, 33, 97, 34, 31, 33, 95],\n    [78, 17, 53, 28, 22, 75, 31, 67, 15, 94,  3, 80,  4, 62, 16, 14,  9, 53, 56, 92],\n    [16, 39,  5, 42, 96, 35, 31, 47, 55, 58, 88, 24,  0, 17, 54, 24, 36, 29, 85, 57],\n    [86, 56,  0, 48, 35, 71, 89,  7,  5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],\n    [19, 80, 81, 68,  5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77,  4, 89, 55, 40],\n    [ 4, 52,  8, 83, 97, 35, 99, 16,  7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],\n    [88, 36, 68, 87, 57, 62, 20, 72,  3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],\n    [ 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18,  8, 46, 29, 32, 40, 62, 76, 36],\n    [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74,  4, 36, 16],\n    [20, 73, 35, 29, 78, 31, 90,  1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57,  5, 54],\n    [ 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52,  1, 89, 19, 67, 48]\n]\n\nfor n in range(2, 6):\n    maxproduct(MATRIX, n)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strings\"\n)\n\nvar grid = [][]int {\n    { 8,  2, 22, 97, 38, 15,  0, 40,  0, 75,  4,  5,  7, 78, 52, 12, 50, 77, 91,  8},\n    {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48,  4, 56, 62,  0},\n    {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30,  3, 49, 13, 36, 65},\n    {52, 70, 95, 23,  4, 60, 11, 42, 69, 24, 68, 56,  1, 32, 56, 71, 37,  2, 36, 91},\n    {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},\n    {24, 47, 32, 60, 99,  3, 45,  2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},\n    {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},\n    {67, 26, 20, 68,  2, 62, 12, 20, 95, 63, 94, 39, 63,  8, 40, 91, 66, 49, 94, 21},\n    {24, 55, 58,  5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},\n    {21, 36, 23,  9, 75,  0, 76, 44, 20, 45, 35, 14,  0, 61, 33, 97, 34, 31, 33, 95},\n    {78, 17, 53, 28, 22, 75, 31, 67, 15, 94,  3, 80,  4, 62, 16, 14,  9, 53, 56, 92},\n    {16, 39,  5, 42, 96, 35, 31, 47, 55, 58, 88, 24,  0, 17, 54, 24, 36, 29, 85, 57},\n    {86, 56,  0, 48, 35, 71, 89,  7,  5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},\n    {19, 80, 81, 68,  5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77,  4, 89, 55, 40},\n    { 4, 52,  8, 83, 97, 35, 99, 16,  7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},\n    {88, 36, 68, 87, 57, 62, 20, 72,  3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},\n    { 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18,  8, 46, 29, 32, 40, 62, 76, 36},\n    {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74,  4, 36, 16},\n    {20, 73, 35, 29, 78, 31, 90,  1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57,  5, 54},\n    { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52,  1, 89, 19, 67, 48},\n}\n\nfunc main() {\n    maxProd, maxR1, maxR2, maxC1, maxC2 := 0, 0, 0, 0, 0\n    var maxNums [4]int\n    h, w := len(grid), len(grid[0])\n\n    \n    for r := 0; r < h; r++ {\n        for c := 0; c < w-4; c++ {\n            prod := 1\n            for i := c; i < c+4; i++ {\n                prod *= grid[r][i]\n            }\n            if prod > maxProd {\n                maxProd = prod\n                for n := 0; n < 4; n++ {\n                    maxNums[n] = grid[r][c+n]\n                }\n                maxR1, maxR2 = r, r\n                maxC1, maxC2 = c, c+3\n            }\n        }\n    }\n\n    \n    for c := 0; c < w; c++ {\n        for r := 0; r < h-4; r++ {\n            prod := 1\n            for i := r; i < r+4; i++ {\n                prod *= grid[i][c]\n            }\n            if prod > maxProd {\n                maxProd = prod\n                for n := 0; n < 4; n++ {\n                    maxNums[n] = grid[r+n][c]\n                }\n                maxR1, maxR2 = r, r+3\n                maxC1, maxC2 = c, c\n            }\n        }\n    }\n\n    fmt.Println(\"The greatest product of four adjacent numbers in the same direction (down or right) in the grid is:\")\n    var maxNumStrs [4]string\n    for i := 0; i < 4; i++ {\n        maxNumStrs[i] = fmt.Sprintf(\"%d\", maxNums[i])\n    }\n    fmt.Printf(\"  %s = %s\\n\", strings.Join(maxNumStrs[:], \" x \"), rcu.Commatize(maxProd))\n    fmt.Print(\"  at indices (one based): \")\n    for r := maxR1; r <= maxR2; r++ {\n        for c := maxC1; c <= maxC2; c++ {\n            fmt.Printf(\"(%d, %d) \", r+1, c+1)\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58526, "name": "Neighbour primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    print(\"p        q       pq+2\")\n    print(\"-----------------------\")\n    for p in range(2, 499):\n        if not isPrime(p):\n            continue\n        q = p + 1\n        while not isPrime(q):\n            q += 1\n        if not isPrime(2 + p*q):\n            continue \n        print(p, \"\\t\", q, \"\\t\", 2+p*q)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(504)\n    var nprimes []int\n    fmt.Println(\"Neighbour primes < 500:\")\n    for i := 0; i < len(primes)-1; i++ {\n        p := primes[i]*primes[i+1] + 2\n        if rcu.IsPrime(p) {\n            nprimes = append(nprimes, primes[i])\n        }\n    }\n    rcu.PrintTable(nprimes, 10, 3, false)\n    fmt.Println(\"\\nFound\", len(nprimes), \"such primes.\")\n}\n"}
{"id": 58527, "name": "Neighbour primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    print(\"p        q       pq+2\")\n    print(\"-----------------------\")\n    for p in range(2, 499):\n        if not isPrime(p):\n            continue\n        q = p + 1\n        while not isPrime(q):\n            q += 1\n        if not isPrime(2 + p*q):\n            continue \n        print(p, \"\\t\", q, \"\\t\", 2+p*q)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(504)\n    var nprimes []int\n    fmt.Println(\"Neighbour primes < 500:\")\n    for i := 0; i < len(primes)-1; i++ {\n        p := primes[i]*primes[i+1] + 2\n        if rcu.IsPrime(p) {\n            nprimes = append(nprimes, primes[i])\n        }\n    }\n    rcu.PrintTable(nprimes, 10, 3, false)\n    fmt.Println(\"\\nFound\", len(nprimes), \"such primes.\")\n}\n"}
{"id": 58528, "name": "Resistance calculator", "Python": "import strutils, strformat\n\ntype\n  Node = ref object\n    kind: char  \n    resistance: float\n    voltage: float\n    a: Node\n    b: Node\n\nproc res(node: Node): float =\n  if node.kind == '+': return node.a.res + node.b.res\n  if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res)\n  node.resistance\n\nproc current(node: Node): float = node.voltage / node.res\nproc effect (node: Node): float = node.current * node.voltage\n\nproc report(node: Node, level: string = \"\") =\n  echo fmt\"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f}  {level}{node.kind}\"\n  if node.kind in \"+*\":\n    node.a.report level & \"| \"\n    node.b.report level & \"| \"\n\nproc setVoltage(node: Node, voltage: float) =\n  node.voltage = voltage\n  if node.kind == '+':\n    let ra = node.a.res\n    let rb = node.b.res\n    node.a.setVoltage ra / (ra+rb) * voltage\n    node.b.setVoltage rb / (ra+rb) * voltage\n  if node.kind == '*':\n    node.a.setVoltage voltage\n    node.b.setVoltage voltage\n\nproc build(tokens: seq[string]): Node =\n  var stack: seq[Node]\n  for token in tokens:\n    stack.add if token == \"+\": Node(kind: '+', a: stack.pop, b: stack.pop)\n              elif token == \"*\": Node(kind: '*', a: stack.pop, b: stack.pop)\n              else: Node(kind: 'r', resistance: parseFloat(token))\n  stack.pop\n\nproc calculate(voltage: float, tokens: seq[string]): Node =\n  echo \"\"\n  echo \"     Ohm     Volt   Ampere     Watt  Network tree\"\n  let node = build tokens\n  node.setVoltage voltage\n  node.report\n  node\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Resistor struct {\n    symbol              rune\n    resistance, voltage float64\n    a, b                *Resistor\n}\n\nfunc (r *Resistor) res() float64 {\n    switch r.symbol {\n    case '+':\n        return r.a.res() + r.b.res()\n    case '*':\n        return 1 / (1/r.a.res() + 1/r.b.res())\n    default:\n        return r.resistance\n    }\n}\n\nfunc (r *Resistor) setVoltage(voltage float64) {\n    switch r.symbol {\n    case '+':\n        ra := r.a.res()\n        rb := r.b.res()\n        r.a.setVoltage(ra / (ra + rb) * voltage)\n        r.b.setVoltage(rb / (ra + rb) * voltage)\n    case '*':\n        r.a.setVoltage(voltage)\n        r.b.setVoltage(voltage)\n    }\n    r.voltage = voltage\n}\n\nfunc (r *Resistor) current() float64 {\n    return r.voltage / r.res()\n}\n\nfunc (r *Resistor) effect() float64 {\n    return r.current() * r.voltage\n}\n\nfunc (r *Resistor) report(level string) {\n    fmt.Printf(\"%8.3f %8.3f %8.3f %8.3f  %s%c\\n\", r.res(), r.voltage, r.current(), r.effect(), level, r.symbol)\n    if r.a != nil {\n        r.a.report(level + \"| \")\n    }\n    if r.b != nil {\n        r.b.report(level + \"| \")\n    }\n}\n\nfunc (r *Resistor) add(other *Resistor) *Resistor {\n    return &Resistor{'+', 0, 0, r, other}\n}\n\nfunc (r *Resistor) mul(other *Resistor) *Resistor {\n    return &Resistor{'*', 0, 0, r, other}\n}\n\nfunc main() {\n    var r [10]*Resistor\n    resistances := []float64{6, 8, 4, 8, 4, 6, 8, 10, 6, 2}\n    for i := 0; i < 10; i++ {\n        r[i] = &Resistor{'r', resistances[i], 0, nil, nil}\n    }\n    node := r[7].add(r[9]).mul(r[8]).add(r[6]).mul(r[5]).add(r[4]).mul(r[3]).add(r[2]).mul(r[1]).add(r[0])\n    node.setVoltage(18)\n    fmt.Println(\"     Ohm     Volt   Ampere     Watt  Network tree\")\n    node.report(\"\")\n}\n"}
{"id": 58529, "name": "Upside-down numbers", "Python": "\n\n\ndef gen_upside_down_number():\n    \n    wrappings = [[1, 9], [2, 8], [3, 7], [4, 6],\n                 [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]]\n    evens = [19, 28, 37, 46, 55, 64, 73, 82, 91]\n    odds = [5]\n    odd_index, even_index = 0, 0\n    ndigits = 1\n    while True:\n        if ndigits % 2 == 1:\n            if len(odds) > odd_index:\n                yield odds[odd_index]\n                odd_index += 1\n            else:\n                \n                odds = sorted([hi * 10**(ndigits + 1) + 10 *\n                              i + lo for i in odds for hi, lo in wrappings])\n                ndigits += 1\n                odd_index = 0\n        else:\n            if len(evens) > even_index:\n                yield evens[even_index]\n                even_index += 1\n            else:\n                \n                evens = sorted([hi * 10**(ndigits + 1) + 10 *\n                               i + lo for i in evens for hi, lo in wrappings])\n                ndigits += 1\n                even_index = 0\n\n\nprint('First fifty upside-downs:')\nfor (udcount, udnumber) in enumerate(gen_upside_down_number()):\n    if udcount < 50:\n        print(f'{udnumber : 5}', end='\\n' if (udcount + 1) % 10 == 0 else '')\n    elif udcount == 499:\n        print(f'\\nFive hundredth: {udnumber: ,}')\n    elif udcount == 4999:\n        print(f'\\nFive thousandth: {udnumber: ,}')\n    elif udcount == 49_999:\n        print(f'\\nFifty thousandth: {udnumber: ,}')\n    elif udcount == 499_999:\n        print(f'\\nFive hundred thousandth: {udnumber: ,}')\n    elif udcount == 4_999_999:\n        print(f'\\nFive millionth: {udnumber: ,}')\n        break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc genUpsideDown(limit int) chan int {\n    ch := make(chan int)\n    wrappings := [][2]int{\n        {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5},\n        {6, 4}, {7, 3}, {8, 2}, {9, 1},\n    }\n    evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91}\n    odds := []int{5}\n    oddIndex := 0\n    evenIndex := 0\n    ndigits := 1\n    pow := 100\n    count := 0\n    go func() {\n        for count < limit {\n            if ndigits%2 == 1 {\n                if len(odds) > oddIndex {\n                    ch <- odds[oddIndex]\n                    count++\n                    oddIndex++\n                } else {\n                    \n                    var nextOdds []int\n                    for _, w := range wrappings {\n                        for _, i := range odds {\n                            nextOdds = append(nextOdds, w[0]*pow+i*10+w[1])\n                        }\n                    }\n                    odds = nextOdds\n                    ndigits++\n                    pow *= 10\n                    oddIndex = 0\n                }\n            } else {\n                if len(evens) > evenIndex {\n                    ch <- evens[evenIndex]\n                    count++\n                    evenIndex++\n                } else {\n                    \n                    var nextEvens []int\n                    for _, w := range wrappings {\n                        for _, i := range evens {\n                            nextEvens = append(nextEvens, w[0]*pow+i*10+w[1])\n                        }\n                    }\n                    evens = nextEvens\n                    ndigits++\n                    pow *= 10\n                    evenIndex = 0\n                }\n            }\n        }\n        close(ch)\n    }()\n    return ch\n}\n\nfunc main() {\n    const limit = 50_000_000\n    count := 0\n    var ud50s []int\n    pow := 50\n    for n := range genUpsideDown(limit) {\n        count++\n        if count < 50 {\n            ud50s = append(ud50s, n)\n        } else if count == 50 {\n            ud50s = append(ud50s, n)\n            fmt.Println(\"First 50 upside down numbers:\")\n            rcu.PrintTable(ud50s, 10, 5, true)\n            fmt.Println()\n            pow = 500\n        } else if count == pow {\n            fmt.Printf(\"%sth : %s\\n\", rcu.Commatize(pow), rcu.Commatize(n))\n            pow *= 10\n        }\n    }\n}\n"}
{"id": 58530, "name": "Minkowski question-mark function", "Python": "    print(\n        \"{:19.16f} {:19.16f}\".format(\n            minkowski(minkowski_inv(4.04145188432738056)),\n            minkowski_inv(minkowski(4.04145188432738056)),\n        )\n    )\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst MAXITER = 151\n\nfunc minkowski(x float64) float64 {\n    if x > 1 || x < 0 {\n        return math.Floor(x) + minkowski(x-math.Floor(x))\n    }\n    p := uint64(x)\n    q := uint64(1)\n    r := p + 1\n    s := uint64(1)\n    d := 1.0\n    y := float64(p)\n    for {\n        d = d / 2\n        if y+d == y {\n            break\n        }\n        m := p + r\n        if m < 0 || p < 0 {\n            break\n        }\n        n := q + s\n        if n < 0 {\n            break\n        }\n        if x < float64(m)/float64(n) {\n            r = m\n            s = n\n        } else {\n            y = y + d\n            p = m\n            q = n\n        }\n    }\n    return y + d\n}\n\nfunc minkowskiInv(x float64) float64 {\n    if x > 1 || x < 0 {\n        return math.Floor(x) + minkowskiInv(x-math.Floor(x))\n    }\n    if x == 1 || x == 0 {\n        return x\n    }\n    contFrac := []uint32{0}\n    curr := uint32(0)\n    count := uint32(1)\n    i := 0\n    for {\n        x *= 2\n        if curr == 0 {\n            if x < 1 {\n                count++\n            } else {\n                i++\n                t := contFrac\n                contFrac = make([]uint32, i+1)\n                copy(contFrac, t)\n                contFrac[i-1] = count\n                count = 1\n                curr = 1\n                x--\n            }\n        } else {\n            if x > 1 {\n                count++\n                x--\n            } else {\n                i++\n                t := contFrac\n                contFrac = make([]uint32, i+1)\n                copy(contFrac, t)\n                contFrac[i-1] = count\n                count = 1\n                curr = 0\n            }\n        }\n        if x == math.Floor(x) {\n            contFrac[i] = count\n            break\n        }\n        if i == MAXITER {\n            break\n        }\n    }\n    ret := 1.0 / float64(contFrac[i])\n    for j := i - 1; j >= 0; j-- {\n        ret = float64(contFrac[j]) + 1.0/ret\n    }\n    return 1.0 / ret\n}\n\nfunc main() {\n    fmt.Printf(\"%19.16f %19.16f\\n\", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0)\n    fmt.Printf(\"%19.16f %19.16f\\n\", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6)\n    fmt.Printf(\"%19.16f %19.16f\\n\", minkowski(minkowskiInv(0.718281828)),\n        minkowskiInv(minkowski(0.1213141516171819)))\n}\n"}
{"id": 58531, "name": "Canny edge detector", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n", "Go": "package main\n\nimport (\n    ed \"github.com/Ernyoke/Imger/edgedetection\"\n    \"github.com/Ernyoke/Imger/imgio\"\n    \"log\"\n)\n\nfunc main() {\n    img, err := imgio.ImreadRGBA(\"Valve_original_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not read image\", err)\n    }\n\n    cny, err := ed.CannyRGBA(img, 15, 45, 5)\n    if err != nil {\n        log.Fatal(\"Could not perform Canny Edge detection\")\n    }\n\n    err = imgio.Imwrite(cny, \"Valve_canny_(1).png\")\n    if err != nil {\n        log.Fatal(\"Could not write Canny image to disk\")\n    }\n}\n"}
{"id": 58532, "name": "War card game", "Python": "\n\nfrom numpy.random import shuffle\n\nSUITS = ['♣', '♦', '♥', '♠']\nFACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nDECK = [f + s for f in FACES for s in SUITS]\nCARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))\n\n\nclass WarCardGame:\n    \n    def __init__(self):\n        deck = DECK.copy()\n        shuffle(deck)\n        self.deck1, self.deck2 = deck[:26], deck[26:]\n        self.pending = []\n\n    def turn(self):\n        \n        if len(self.deck1) == 0 or len(self.deck2) == 0:\n            return self.gameover()\n\n        card1, card2 = self.deck1.pop(0), self.deck2.pop(0)\n        rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]\n        print(\"{:10}{:10}\".format(card1, card2), end='')\n        if rank1 > rank2:\n            print('Player 1 takes the cards.')\n            self.deck1.extend([card1, card2])\n            self.deck1.extend(self.pending)\n            self.pending = []\n        elif rank1 < rank2:\n            print('Player 2 takes the cards.')\n            self.deck2.extend([card2, card1])\n            self.deck2.extend(self.pending)\n            self.pending = []\n        else:  \n            print('Tie!')\n            if len(self.deck1) == 0 or len(self.deck2) == 0:\n                return self.gameover()\n\n            card3, card4 = self.deck1.pop(0), self.deck2.pop(0)\n            self.pending.extend([card1, card2, card3, card4])\n            print(\"{:10}{:10}\".format(\"?\", \"?\"), 'Cards are face down.', sep='')\n            return self.turn()\n\n        return True\n\n    def gameover(self):\n        \n        if len(self.deck2) == 0:\n            if len(self.deck1) == 0:\n                print('\\nGame ends as a tie.')\n            else:\n                print('\\nPlayer 1 wins the game.')\n        else:\n            print('\\nPlayer 2 wins the game.')\n\n        return False\n\n\nif __name__ == '__main__':\n    WG = WarCardGame()\n    while WG.turn():\n        continue\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar suits = []string{\"♣\", \"♦\", \"♥\", \"♠\"}\nvar faces = []string{\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"}\nvar cards = make([]string, 52)\nvar ranks = make([]int, 52)\n\nfunc init() {\n    for i := 0; i < 52; i++ {\n        cards[i] = fmt.Sprintf(\"%s%s\", faces[i%13], suits[i/13])\n        ranks[i] = i % 13\n    }\n}\n\nfunc war() {\n    deck := make([]int, 52)\n    for i := 0; i < 52; i++ {\n        deck[i] = i\n    }\n    rand.Shuffle(52, func(i, j int) {\n        deck[i], deck[j] = deck[j], deck[i]\n    })\n    hand1 := make([]int, 26, 52)\n    hand2 := make([]int, 26, 52)\n    for i := 0; i < 26; i++ {\n        hand1[25-i] = deck[2*i]\n        hand2[25-i] = deck[2*i+1]\n    }\n    for len(hand1) > 0 && len(hand2) > 0 {\n        card1 := hand1[0]\n        copy(hand1[0:], hand1[1:])\n        hand1[len(hand1)-1] = 0\n        hand1 = hand1[0 : len(hand1)-1]\n        card2 := hand2[0]\n        copy(hand2[0:], hand2[1:])\n        hand2[len(hand2)-1] = 0\n        hand2 = hand2[0 : len(hand2)-1]\n        played1 := []int{card1}\n        played2 := []int{card2}\n        numPlayed := 2\n        for {\n            fmt.Printf(\"%s\\t%s\\t\", cards[card1], cards[card2])\n            if ranks[card1] > ranks[card2] {\n                hand1 = append(hand1, played1...)\n                hand1 = append(hand1, played2...)\n                fmt.Printf(\"Player 1 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand1))\n                break\n            } else if ranks[card1] < ranks[card2] {\n                hand2 = append(hand2, played2...)\n                hand2 = append(hand2, played1...)\n                fmt.Printf(\"Player 2 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand2))\n                break\n            } else {\n                fmt.Println(\"War!\")\n                if len(hand1) < 2 {\n                    fmt.Println(\"Player 1 has insufficient cards left.\")\n                    hand2 = append(hand2, played2...)\n                    hand2 = append(hand2, played1...)\n                    hand2 = append(hand2, hand1...)\n                    hand1 = hand1[0:0]\n                    break\n                }\n                if len(hand2) < 2 {\n                    fmt.Println(\"Player 2 has insufficient cards left.\")\n                    hand1 = append(hand1, played1...)\n                    hand1 = append(hand1, played2...)\n                    hand1 = append(hand1, hand2...)\n                    hand2 = hand2[0:0]\n                    break\n                }\n                fdCard1 := hand1[0] \n                card1 = hand1[1]    \n                copy(hand1[0:], hand1[2:])\n                hand1[len(hand1)-1] = 0\n                hand1[len(hand1)-2] = 0\n                hand1 = hand1[0 : len(hand1)-2]\n                played1 = append(played1, fdCard1, card1)\n                fdCard2 := hand2[0] \n                card2 = hand2[1]    \n                copy(hand2[0:], hand2[2:])\n                hand2[len(hand2)-1] = 0\n                hand2[len(hand2)-2] = 0\n                hand2 = hand2[0 : len(hand2)-2]\n                played2 = append(played2, fdCard2, card2)\n                numPlayed += 4\n                fmt.Println(\"? \\t? \\tFace down cards.\")\n            }\n        }\n    }\n    if len(hand1) == 52 {\n        fmt.Println(\"Player 1 wins the game!\")\n    } else {\n        fmt.Println(\"Player 2 wins the game!\")\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    war()\n}\n"}
{"id": 58533, "name": "War card game", "Python": "\n\nfrom numpy.random import shuffle\n\nSUITS = ['♣', '♦', '♥', '♠']\nFACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nDECK = [f + s for f in FACES for s in SUITS]\nCARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))\n\n\nclass WarCardGame:\n    \n    def __init__(self):\n        deck = DECK.copy()\n        shuffle(deck)\n        self.deck1, self.deck2 = deck[:26], deck[26:]\n        self.pending = []\n\n    def turn(self):\n        \n        if len(self.deck1) == 0 or len(self.deck2) == 0:\n            return self.gameover()\n\n        card1, card2 = self.deck1.pop(0), self.deck2.pop(0)\n        rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]\n        print(\"{:10}{:10}\".format(card1, card2), end='')\n        if rank1 > rank2:\n            print('Player 1 takes the cards.')\n            self.deck1.extend([card1, card2])\n            self.deck1.extend(self.pending)\n            self.pending = []\n        elif rank1 < rank2:\n            print('Player 2 takes the cards.')\n            self.deck2.extend([card2, card1])\n            self.deck2.extend(self.pending)\n            self.pending = []\n        else:  \n            print('Tie!')\n            if len(self.deck1) == 0 or len(self.deck2) == 0:\n                return self.gameover()\n\n            card3, card4 = self.deck1.pop(0), self.deck2.pop(0)\n            self.pending.extend([card1, card2, card3, card4])\n            print(\"{:10}{:10}\".format(\"?\", \"?\"), 'Cards are face down.', sep='')\n            return self.turn()\n\n        return True\n\n    def gameover(self):\n        \n        if len(self.deck2) == 0:\n            if len(self.deck1) == 0:\n                print('\\nGame ends as a tie.')\n            else:\n                print('\\nPlayer 1 wins the game.')\n        else:\n            print('\\nPlayer 2 wins the game.')\n\n        return False\n\n\nif __name__ == '__main__':\n    WG = WarCardGame()\n    while WG.turn():\n        continue\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar suits = []string{\"♣\", \"♦\", \"♥\", \"♠\"}\nvar faces = []string{\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"}\nvar cards = make([]string, 52)\nvar ranks = make([]int, 52)\n\nfunc init() {\n    for i := 0; i < 52; i++ {\n        cards[i] = fmt.Sprintf(\"%s%s\", faces[i%13], suits[i/13])\n        ranks[i] = i % 13\n    }\n}\n\nfunc war() {\n    deck := make([]int, 52)\n    for i := 0; i < 52; i++ {\n        deck[i] = i\n    }\n    rand.Shuffle(52, func(i, j int) {\n        deck[i], deck[j] = deck[j], deck[i]\n    })\n    hand1 := make([]int, 26, 52)\n    hand2 := make([]int, 26, 52)\n    for i := 0; i < 26; i++ {\n        hand1[25-i] = deck[2*i]\n        hand2[25-i] = deck[2*i+1]\n    }\n    for len(hand1) > 0 && len(hand2) > 0 {\n        card1 := hand1[0]\n        copy(hand1[0:], hand1[1:])\n        hand1[len(hand1)-1] = 0\n        hand1 = hand1[0 : len(hand1)-1]\n        card2 := hand2[0]\n        copy(hand2[0:], hand2[1:])\n        hand2[len(hand2)-1] = 0\n        hand2 = hand2[0 : len(hand2)-1]\n        played1 := []int{card1}\n        played2 := []int{card2}\n        numPlayed := 2\n        for {\n            fmt.Printf(\"%s\\t%s\\t\", cards[card1], cards[card2])\n            if ranks[card1] > ranks[card2] {\n                hand1 = append(hand1, played1...)\n                hand1 = append(hand1, played2...)\n                fmt.Printf(\"Player 1 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand1))\n                break\n            } else if ranks[card1] < ranks[card2] {\n                hand2 = append(hand2, played2...)\n                hand2 = append(hand2, played1...)\n                fmt.Printf(\"Player 2 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand2))\n                break\n            } else {\n                fmt.Println(\"War!\")\n                if len(hand1) < 2 {\n                    fmt.Println(\"Player 1 has insufficient cards left.\")\n                    hand2 = append(hand2, played2...)\n                    hand2 = append(hand2, played1...)\n                    hand2 = append(hand2, hand1...)\n                    hand1 = hand1[0:0]\n                    break\n                }\n                if len(hand2) < 2 {\n                    fmt.Println(\"Player 2 has insufficient cards left.\")\n                    hand1 = append(hand1, played1...)\n                    hand1 = append(hand1, played2...)\n                    hand1 = append(hand1, hand2...)\n                    hand2 = hand2[0:0]\n                    break\n                }\n                fdCard1 := hand1[0] \n                card1 = hand1[1]    \n                copy(hand1[0:], hand1[2:])\n                hand1[len(hand1)-1] = 0\n                hand1[len(hand1)-2] = 0\n                hand1 = hand1[0 : len(hand1)-2]\n                played1 = append(played1, fdCard1, card1)\n                fdCard2 := hand2[0] \n                card2 = hand2[1]    \n                copy(hand2[0:], hand2[2:])\n                hand2[len(hand2)-1] = 0\n                hand2[len(hand2)-2] = 0\n                hand2 = hand2[0 : len(hand2)-2]\n                played2 = append(played2, fdCard2, card2)\n                numPlayed += 4\n                fmt.Println(\"? \\t? \\tFace down cards.\")\n            }\n        }\n    }\n    if len(hand1) == 52 {\n        fmt.Println(\"Player 1 wins the game!\")\n    } else {\n        fmt.Println(\"Player 2 wins the game!\")\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    war()\n}\n"}
{"id": 58534, "name": "Color quantization", "Python": "from PIL import Image\n\nif __name__==\"__main__\":\n\tim = Image.open(\"frog.png\")\n\tim2 = im.quantize(16)\n\tim2.show()\n", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    f, err := os.Open(\"Quantum_frog.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    img, err := png.Decode(f)\n    if ec := f.Close(); err != nil {\n        log.Fatal(err)\n    } else if ec != nil {\n        log.Fatal(ec)\n    }\n    fq, err := os.Create(\"frog16.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = png.Encode(fq, quant(img, 16)); err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc quant(img image.Image, nq int) image.Image {\n    qz := newQuantizer(img, nq) \n    qz.cluster()                \n    return qz.Paletted()        \n}\n\n\ntype quantizer struct {\n    img image.Image \n    cs  []cluster   \n    px  []point     \n    ch  chValues    \n    eq  []point     \n}\n\ntype cluster struct {\n    px       []point \n    widestCh int     \n    chRange  uint32  \n}\n\ntype point struct{ x, y int }\ntype chValues []uint32\ntype queue []*cluster\n\nconst (\n    rx = iota\n    gx\n    bx\n)\n\nfunc newQuantizer(img image.Image, nq int) *quantizer {\n    b := img.Bounds()\n    npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)\n    \n    qz := &quantizer{\n        img: img,\n        ch:  make(chValues, npx),\n        cs:  make([]cluster, nq),\n    }\n    \n    c := &qz.cs[0]\n    px := make([]point, npx)\n    c.px = px\n    i := 0\n    for y := b.Min.Y; y < b.Max.Y; y++ {\n        for x := b.Min.X; x < b.Max.X; x++ {\n            px[i].x = x\n            px[i].y = y\n            i++\n        }\n    }\n    return qz\n}\n\nfunc (qz *quantizer) cluster() {\n    \n    \n    \n    \n    \n    pq := new(queue)\n    \n    c := &qz.cs[0]\n    for i := 1; ; {\n        qz.setColorRange(c)\n        \n        \n        if c.chRange > 0 {\n            heap.Push(pq, c) \n        }\n        \n        \n        if len(*pq) == 0 {\n            qz.cs = qz.cs[:i]\n            break\n        }\n        s := heap.Pop(pq).(*cluster) \n        c = &qz.cs[i]                \n        i++\n        m := qz.Median(s)\n        qz.Split(s, c, m) \n        \n        if i == len(qz.cs) {\n            break\n        }\n        qz.setColorRange(s)\n        if s.chRange > 0 {\n            heap.Push(pq, s) \n        }\n    }\n}\n    \nfunc (q *quantizer) setColorRange(c *cluster) {\n    \n    var maxR, maxG, maxB uint32\n    minR := uint32(math.MaxUint32)\n    minG := uint32(math.MaxUint32)\n    minB := uint32(math.MaxUint32) \n    for _, p := range c.px {\n        r, g, b, _ := q.img.At(p.x, p.y).RGBA()\n        if r < minR { \n            minR = r\n        }\n        if r > maxR {\n            maxR = r\n        }\n        if g < minG {\n            minG = g \n        }\n        if g > maxG {\n            maxG = g\n        }\n        if b < minB {\n            minB = b\n        }\n        if b > maxB {\n            maxB = b\n        }\n    }\n    \n    s := gx\n    min := minG\n    max := maxG\n    if maxR-minR > max-min {\n        s = rx\n        min = minR\n        max = maxR\n    }\n    if maxB-minB > max-min {\n        s = bx\n        min = minB\n        max = maxB\n    }\n    c.widestCh = s\n    c.chRange = max - min \n}\n\nfunc (q *quantizer) Median(c *cluster) uint32 {\n    px := c.px\n    ch := q.ch[:len(px)]\n    \n    switch c.widestCh {\n    case rx:\n        for i, p := range c.px {\n            ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case gx:\n        for i, p := range c.px {\n            _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case bx:\n        for i, p := range c.px {\n            _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA()\n        }\n    }\n    \n    sort.Sort(ch)\n    half := len(ch) / 2\n    m := ch[half]\n    if len(ch)%2 == 0 {\n        m = (m + ch[half-1]) / 2\n    }\n    return m\n}\n\nfunc (q *quantizer) Split(s, c *cluster, m uint32) {\n    px := s.px\n    var v uint32\n    i := 0\n    lt := 0\n    gt := len(px) - 1\n    eq := q.eq[:0] \n    for i <= gt {\n        \n        r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA()\n        switch s.widestCh {\n        case rx:\n            v = r\n        case gx:\n            v = g\n        case bx:\n            v = b\n        } \n        \n        switch {\n        case v < m:\n            px[lt] = px[i]\n            lt++\n            i++\n        case v > m:\n            px[gt], px[i] = px[i], px[gt]\n            gt--\n        default:\n            eq = append(eq, px[i])\n            i++\n        }\n    }\n    \n    if len(eq) > 0 {\n        copy(px[lt:], eq) \n        \n        \n        \n        if len(px)-i < lt {\n            i = lt\n        }\n        q.eq = eq \n    }\n    \n    s.px = px[:i]\n    c.px = px[i:]\n}   \n    \nfunc (qz *quantizer) Paletted() *image.Paletted {\n    cp := make(color.Palette, len(qz.cs))\n    pi := image.NewPaletted(qz.img.Bounds(), cp)\n    for i := range qz.cs {\n        px := qz.cs[i].px\n        \n        var rsum, gsum, bsum int64\n        for _, p := range px {\n            r, g, b, _ := qz.img.At(p.x, p.y).RGBA()\n            rsum += int64(r)\n            gsum += int64(g)\n            bsum += int64(b)\n        } \n        n64 := int64(len(px))\n        cp[i] = color.NRGBA64{\n            uint16(rsum / n64),\n            uint16(gsum / n64),\n            uint16(bsum / n64),\n            0xffff,\n        }\n        \n        for _, p := range px {\n            pi.SetColorIndex(p.x, p.y, uint8(i))\n        }\n    }\n    return pi\n}\n\n\nfunc (c chValues) Len() int           { return len(c) }\nfunc (c chValues) Less(i, j int) bool { return c[i] < c[j] }\nfunc (c chValues) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\n\n\nfunc (q queue) Len() int { return len(q) }\n\n\nfunc (q queue) Less(i, j int) bool {\n    return len(q[j].px) < len(q[i].px)\n}\n\nfunc (q queue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n}\nfunc (pq *queue) Push(x interface{}) {\n    c := x.(*cluster)\n    *pq = append(*pq, c)\n}\nfunc (pq *queue) Pop() interface{} {\n    q := *pq\n    n := len(q) - 1\n    c := q[n]\n    *pq = q[:n]\n    return c\n}\n"}
{"id": 58535, "name": "Modified random distribution", "Python": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n    \n    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n                                 n: int) -> List[float]:\n    \n    d: List[float] = []\n    while len(d) < n:\n        r1 = prob = random.random()\n        if random.random() < modifier(prob):\n            d.append(r1)\n    return d\n\n\nif __name__ == '__main__':\n    from collections import Counter\n\n    data = modified_random_distribution(modifier, 50_000)\n    bins = 15\n    counts = Counter(d // (1 / bins) for d in data)\n    \n    mx = max(counts.values())\n    print(\"   BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n    last: Optional[float] = None\n    for b, count in sorted(counts.items()):\n        delta = 'N/A' if last is None else str(count - last)\n        print(f\"  {b / bins:5.2f},  {count:4},  {delta:>4}: \"\n              f\"{'\n        last = count\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n    for {\n        r1 := rand.Float64()\n        r2 := rand.Float64()\n        if r2 < modifier(r1) {\n            return r1\n        }\n    }\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    rand.Seed(time.Now().UnixNano())\n    modifier := func(x float64) float64 {\n        if x < 0.5 {\n            return 2 * (0.5 - x)\n        }\n        return 2 * (x - 0.5)\n    }\n    const (\n        N              = 100000\n        NUM_BINS       = 20\n        HIST_CHAR      = \"■\"\n        HIST_CHAR_SIZE = 125\n    )\n    bins := make([]int, NUM_BINS) \n    binSize := 1.0 / NUM_BINS\n    for i := 0; i < N; i++ {\n        rn := rng(modifier)\n        bn := int(math.Floor(rn / binSize))\n        bins[bn]++\n    }\n\n    fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n    fmt.Println(\"    Range           Number of samples within that range\")\n    for i := 0; i < NUM_BINS; i++ {\n        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n        fi := float64(i)\n        fmt.Printf(\"%4.2f ..< %4.2f  %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n    }\n}\n"}
{"id": 58536, "name": "Modified random distribution", "Python": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n    \n    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n                                 n: int) -> List[float]:\n    \n    d: List[float] = []\n    while len(d) < n:\n        r1 = prob = random.random()\n        if random.random() < modifier(prob):\n            d.append(r1)\n    return d\n\n\nif __name__ == '__main__':\n    from collections import Counter\n\n    data = modified_random_distribution(modifier, 50_000)\n    bins = 15\n    counts = Counter(d // (1 / bins) for d in data)\n    \n    mx = max(counts.values())\n    print(\"   BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n    last: Optional[float] = None\n    for b, count in sorted(counts.items()):\n        delta = 'N/A' if last is None else str(count - last)\n        print(f\"  {b / bins:5.2f},  {count:4},  {delta:>4}: \"\n              f\"{'\n        last = count\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n    for {\n        r1 := rand.Float64()\n        r2 := rand.Float64()\n        if r2 < modifier(r1) {\n            return r1\n        }\n    }\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    rand.Seed(time.Now().UnixNano())\n    modifier := func(x float64) float64 {\n        if x < 0.5 {\n            return 2 * (0.5 - x)\n        }\n        return 2 * (x - 0.5)\n    }\n    const (\n        N              = 100000\n        NUM_BINS       = 20\n        HIST_CHAR      = \"■\"\n        HIST_CHAR_SIZE = 125\n    )\n    bins := make([]int, NUM_BINS) \n    binSize := 1.0 / NUM_BINS\n    for i := 0; i < N; i++ {\n        rn := rng(modifier)\n        bn := int(math.Floor(rn / binSize))\n        bins[bn]++\n    }\n\n    fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n    fmt.Println(\"    Range           Number of samples within that range\")\n    for i := 0; i < NUM_BINS; i++ {\n        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n        fi := float64(i)\n        fmt.Printf(\"%4.2f ..< %4.2f  %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n    }\n}\n"}
{"id": 58537, "name": "Modified random distribution", "Python": "import random\nfrom typing import List, Callable, Optional\n\n\ndef modifier(x: float) -> float:\n    \n    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)\n\n\ndef modified_random_distribution(modifier: Callable[[float], float],\n                                 n: int) -> List[float]:\n    \n    d: List[float] = []\n    while len(d) < n:\n        r1 = prob = random.random()\n        if random.random() < modifier(prob):\n            d.append(r1)\n    return d\n\n\nif __name__ == '__main__':\n    from collections import Counter\n\n    data = modified_random_distribution(modifier, 50_000)\n    bins = 15\n    counts = Counter(d // (1 / bins) for d in data)\n    \n    mx = max(counts.values())\n    print(\"   BIN, COUNTS, DELTA: HISTOGRAM\\n\")\n    last: Optional[float] = None\n    for b, count in sorted(counts.items()):\n        delta = 'N/A' if last is None else str(count - last)\n        print(f\"  {b / bins:5.2f},  {count:4},  {delta:>4}: \"\n              f\"{'\n        last = count\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n    for {\n        r1 := rand.Float64()\n        r2 := rand.Float64()\n        if r2 < modifier(r1) {\n            return r1\n        }\n    }\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    rand.Seed(time.Now().UnixNano())\n    modifier := func(x float64) float64 {\n        if x < 0.5 {\n            return 2 * (0.5 - x)\n        }\n        return 2 * (x - 0.5)\n    }\n    const (\n        N              = 100000\n        NUM_BINS       = 20\n        HIST_CHAR      = \"■\"\n        HIST_CHAR_SIZE = 125\n    )\n    bins := make([]int, NUM_BINS) \n    binSize := 1.0 / NUM_BINS\n    for i := 0; i < N; i++ {\n        rn := rng(modifier)\n        bn := int(math.Floor(rn / binSize))\n        bins[bn]++\n    }\n\n    fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n    fmt.Println(\"    Range           Number of samples within that range\")\n    for i := 0; i < NUM_BINS; i++ {\n        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n        fi := float64(i)\n        fmt.Printf(\"%4.2f ..< %4.2f  %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n    }\n}\n"}
{"id": 58538, "name": "Collect and sort square numbers in ascending order from three lists", "Python": "import math\n\nprint(\"working...\")\nlist = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)]\nSquares = []\n\ndef issquare(x):\n\tfor p in range(x):\n\t\tif x == p*p:\n\t\t\treturn 1\nfor n in range(3):\n\tfor m in range(len(list[n])):\n\t\tif issquare(list[n][m]):\n\t\t\tSquares.append(list[n][m])\n\nSquares.sort()\nprint(Squares)\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc main() {\n    lists := [][]int{\n        {3, 4, 34, 25, 9, 12, 36, 56, 36},\n        {2, 8, 81, 169, 34, 55, 76, 49, 7},\n        {75, 121, 75, 144, 35, 16, 46, 35},\n    }\n    var squares []int\n    for _, list := range lists {\n        for _, e := range list {\n            if isSquare(e) {\n                squares = append(squares, e)\n            }\n        }\n    }\n    sort.Ints(squares)\n    fmt.Println(squares)\n}\n"}
{"id": 58539, "name": "Collect and sort square numbers in ascending order from three lists", "Python": "import math\n\nprint(\"working...\")\nlist = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)]\nSquares = []\n\ndef issquare(x):\n\tfor p in range(x):\n\t\tif x == p*p:\n\t\t\treturn 1\nfor n in range(3):\n\tfor m in range(len(list[n])):\n\t\tif issquare(list[n][m]):\n\t\t\tSquares.append(list[n][m])\n\nSquares.sort()\nprint(Squares)\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nfunc isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc main() {\n    lists := [][]int{\n        {3, 4, 34, 25, 9, 12, 36, 56, 36},\n        {2, 8, 81, 169, 34, 55, 76, 49, 7},\n        {75, 121, 75, 144, 35, 16, 46, 35},\n    }\n    var squares []int\n    for _, list := range lists {\n        for _, e := range list {\n            if isSquare(e) {\n                squares = append(squares, e)\n            }\n        }\n    }\n    sort.Ints(squares)\n    fmt.Println(squares)\n}\n"}
{"id": 58540, "name": "Suffixation of decimal numbers", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n"}
{"id": 58541, "name": "Suffixation of decimal numbers", "Python": "import math\nimport os\n\n\ndef suffize(num, digits=None, base=10):\n    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']\n\n    exponent_distance = 10 if base == 2 else 3\n    num = num.strip().replace(',', '')\n    num_sign = num[0] if num[0] in '+-' else ''\n\n    num = abs(float(num))\n\n    if base == 10 and num >= 1e100:\n        suffix_index = 13\n        num /= 1e100\n    elif num > 1:\n        magnitude = math.floor(math.log(num, base))\n        suffix_index = min(math.floor(magnitude / exponent_distance), 12)\n        num /= base ** (exponent_distance * suffix_index)\n    else:\n        suffix_index = 0\n\n    if digits is not None:\n        num_str = f'{num:.{digits}f}'\n    else:\n        num_str = f'{num:.3f}'.strip('0').strip('.')\n\n    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')\n\n\ntests = [('87,654,321',),\n         ('-998,877,665,544,332,211,000', 3),\n         ('+112,233', 0),\n         ('16,777,216', 1),\n         ('456,789,100,000,000', 2),\n         ('456,789,100,000,000', 2, 10),\n         ('456,789,100,000,000', 5, 2),\n         ('456,789,100,000.000e+00', 0, 10),\n         ('+16777216', None, 2),\n         ('1.2e101',)]\n\nfor test in tests:\n    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc suffize(arg string) {\n    fields := strings.Fields(arg)\n    a := fields[0]\n    if a == \"\" {\n        a = \"0\"\n    }\n    var places, base int\n    var frac, radix string\n    switch len(fields) {\n    case 1:\n        places = -1\n        base = 10\n    case 2:\n        places, _ = strconv.Atoi(fields[1])\n        base = 10\n        frac = strconv.Itoa(places)\n    case 3:\n        if fields[1] == \",\" {\n            places = 0\n            frac = \",\"\n        } else {\n            places, _ = strconv.Atoi(fields[1])\n            frac = strconv.Itoa(places)\n        }\n        base, _ = strconv.Atoi(fields[2])\n        if base != 2 && base != 10 {\n            base = 10\n        }\n        radix = strconv.Itoa(base)\n    }\n    a = strings.Replace(a, \",\", \"\", -1) \n    sign := \"\"\n    if a[0] == '+' || a[0] == '-' {\n        sign = string(a[0])\n        a = a[1:] \n    }\n    b := new(big.Float).SetPrec(500)\n    d := new(big.Float).SetPrec(500)\n    b.SetString(a)\n    g := false\n    if b.Cmp(ggl) >= 0 {\n        g = true\n    }\n    if !g && base == 2 {\n        d.SetUint64(1024)\n    } else if !g && base == 10 {\n        d.SetUint64(1000)\n    } else {\n        d.Set(ggl)\n    }\n    c := 0\n    for b.Cmp(d) >= 0 && c < 12 { \n        b.Quo(b, d)\n        c++\n    }\n    var suffix string\n    if !g {\n        suffix = string(suffixes[c])\n    } else {\n        suffix = \"googol\"\n    }\n    if base == 2 {\n        suffix += \"i\"\n    }\n    fmt.Println(\"   input number =\", fields[0])\n    fmt.Println(\"  fraction digs =\", frac)\n    fmt.Println(\"specified radix =\", radix)\n    fmt.Print(\"     new number = \")\n    if places >= 0 {\n        fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n    } else {\n        fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    tests := []string{\n        \"87,654,321\",\n        \"-998,877,665,544,332,211,000      3\",\n        \"+112,233                          0\",\n        \"16,777,216                        1\",\n        \"456,789,100,000,000\",\n        \"456,789,100,000,000               2      10\",\n        \"456,789,100,000,000               5       2\",\n        \"456,789,100,000.000e+00           0      10\",\n        \"+16777216                         ,       2\",\n        \"1.2e101\",\n        \"446,835,273,728                   1\",\n        \"1e36\",\n        \"1e39\", \n    }\n    for _, test := range tests {\n        suffize(test)\n    }\n}\n"}
{"id": 58542, "name": "Longest palindromic substrings", "Python": "\n\n\n\ndef longestPalindromes(s):\n    \n    k = s.lower()\n    palindromes = [\n        palExpansion(k)(ab) for ab\n        in palindromicNuclei(k)\n    ]\n    maxLength = max([\n        len(x) for x in palindromes\n    ]) if palindromes else 1\n    return (\n        [\n            x for x in palindromes if maxLength == len(x)\n        ] if palindromes else list(s),\n        maxLength\n    ) if s else ([], 0)\n\n\n\ndef palindromicNuclei(s):\n    \n    cs = list(s)\n    return [\n        \n        (i, 1 + i) for (i, (a, b))\n        in enumerate(zip(cs, cs[1:]))\n        if a == b\n    ] + [\n        \n        (i, 2 + i) for (i, (a, b, c))\n        in enumerate(zip(cs, cs[1:], cs[2:]))\n        if a == c\n    ]\n\n\n\ndef palExpansion(s):\n    \n    iEnd = len(s) - 1\n\n    def limit(ij):\n        i, j = ij\n        return 0 == i or iEnd == j or s[i-1] != s[j+1]\n\n    def expansion(ij):\n        i, j = ij\n        return (i - 1, 1 + j)\n\n    def go(ij):\n        ab = until(limit)(expansion)(ij)\n        return s[ab[0]:ab[1] + 1]\n    return go\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(repr)(\n            longestPalindromes\n        )([\n            'three old rotators',\n            'never reverse',\n            'stable was I ere I saw elbatrosses',\n            'abracadabra',\n            'drome',\n            'the abbatial palace',\n            ''\n        ])\n    )\n\n\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\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\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc reverse(s string) string {\n    var r = []rune(s)\n    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc longestPalSubstring(s string) []string {\n    var le = len(s)\n    if le <= 1 {\n        return []string{s}\n    }\n    targetLen := le\n    var longest []string\n    i := 0\n    for {\n        j := i + targetLen - 1\n        if j < le {\n            ss := s[i : j+1]\n            if reverse(ss) == ss {\n                longest = append(longest, ss)\n            }\n            i++\n        } else {\n            if len(longest) > 0 {\n                return longest\n            }\n            i = 0\n            targetLen--\n        }\n    }\n    return longest\n}\n\nfunc distinct(sa []string) []string {\n    sort.Strings(sa)\n    duplicated := make([]bool, len(sa))\n    for i := 1; i < len(sa); i++ {\n        if sa[i] == sa[i-1] {\n            duplicated[i] = true\n        }\n    }\n    var res []string\n    for i := 0; i < len(sa); i++ {\n        if !duplicated[i] {\n            res = append(res, sa[i])\n        }\n    }\n    return res\n}\n\nfunc main() {\n    strings := []string{\"babaccd\", \"rotator\", \"reverse\", \"forever\", \"several\", \"palindrome\", \"abaracadaraba\"}\n    fmt.Println(\"The palindromic substrings having the longest length are:\")\n    for _, s := range strings {\n        longest := distinct(longestPalSubstring(s))\n        fmt.Printf(\"  %-13s Length %d -> %v\\n\", s, len(longest[0]), longest)\n    }\n}\n"}
{"id": 58543, "name": "Hunt the Wumpus", "Python": "import random\n\nclass WumpusGame(object):\n\n\n\tdef __init__(self, edges=[]):\n\t\t\n\t\t\n\t\tif edges:\n\t\t\tcave = {}\n\t\t\tN = max([edges[i][0] for i in range(len(edges))])\n\t\t\tfor i in range(N):\n\t\t\t\texits = [edge[1] for edge in edges if edge[0] == i]\n\t\t\t\tcave[i] = exits\n\n\t\t\n\t\telse:\n\t\t\tcave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1,9,10], 5:[2,9,11],\n\t\t\t\t6: [2,7,12], 7: [3,6,13], 8: [3,10,14], 9: [4,5,15], 10: [4,8,16], \n\t\t\t\t11: [5,12,17], 12: [6,11,18], 13: [7,14,18], 14: [8,13,19], \n\t\t\t\t15: [9,16,17], 16: [10,15,19], 17: [11,20,15], 18: [12,13,20], \n\t\t\t\t19: [14,16,20], 20: [17,18,19]}\n\n\t\tself.cave = cave\n\n\t\tself.threats = {}\n\n\t\tself.arrows = 5\n\n\t\tself.arrow_travel_distance = 5\t\t\n\t\t\t\t\t\t\t\t\t\t\t\n\t\tself.player_pos = -1\n\n\n\t\n\n\n\tdef get_safe_rooms(self):\n\t\t\n\t\treturn list(set(self.cave.keys()).difference(self.threats.keys()))\n\n\n\tdef populate_cave(self):\n\t\t\n\t\tfor threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']:\n\t\t\tpos = random.choice(self.get_safe_rooms())\n\t\t\tself.threats[pos] = threat\n\t\tself.player_pos = random.choice(self.get_safe_rooms())\n\n\n\tdef breadth_first_search(self, source, target, max_depth=5):\n\t\t\n\t\t\n\t\tgraph = self.cave\n\t\tdepth = 0\n\n\t\tdef search(stack, visited, target, depth):\n\t\t\tif stack == []:\t\t\t\t\t\n\t\t\t\treturn False, -1\n\t\t\tif target in stack:\n\t\t\t\treturn True, depth\n\t\t\tvisited = visited + stack\n\t\t\tstack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited))\n\t\t\tdepth += 1\n\t\t\tif depth > max_depth:\t\t\t\n\t\t\t\treturn False, depth\n\t\t\telse:\t\t\t\t\t\t\t\n\t\t\t\treturn search(stack, visited, target, depth)\n\n\t\treturn search([source], [], target, depth)\n\n\n\t\n\n\n\tdef print_warning(self, threat):\n\t\t\n\t\tif threat == 'bat':\n\t\t\tprint(\"You hear a rustling.\")\n\t\telif threat == 'pit':\n\t\t\tprint(\"You feel a cold wind blowing from a nearby cavern.\")\n\t\telif threat == 'wumpus':\n\t\t\tprint(\"You smell something terrible nearby.\")\n\n\n\tdef get_players_input(self):\n\t\t\n\t\twhile 1:\t\t\t\t\t\t\t\t\n\n\t\t\tinpt = input(\"Shoot or move (S-M)? \")\n\t\t\ttry:\t\t\t\t\t\t\t\t\n\t\t\t\tmode = str(inpt).lower()\n\t\t\t\tassert mode in ['s', 'm', 'q']\n\t\t\t\tbreak\n\t\t\texcept (ValueError, AssertionError):\n\t\t\t\tprint(\"This is not a valid action: pick 'S' to shoot and 'M' to move.\")\n\n\t\tif mode == 'q':\t\t\t\t\t\t\t\n\t\t\treturn 'q', 0\n\n\t\twhile 1:\t\t\t\t\t\t\t\t\n\n\t\t\tinpt = input(\"Where to? \")\n\t\t\ttry:\t\t\t\t\t\t\t\t\n\t\t\t\ttarget = int(inpt)\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"This is not even a real number.\")\n\t\t\t\tcontinue\t\t\t\t\t\t\n\n\t\t\tif mode == 'm':\n\t\t\t\ttry:\t\t\t\t\t\t\t\n\t\t\t\t\tassert target in self.cave[self.player_pos]\n\t\t\t\t\tbreak\n\t\t\t\texcept AssertionError:\n\t\t\t\t\tprint(\"You cannot walk that far. Please use one of the tunnels.\")\n\n\t\t\telif mode == 's':\n\t\t\t\ttry:\t\t\t\t\t\t\t\n\t\t\t\t\tbfs = self.breadth_first_search(self.player_pos, target)\n\t\t\t\t\tassert bfs[0] == True\n\t\t\t\t\tbreak\n\t\t\t\texcept AssertionError:\n\t\t\t\t\tif bfs[1] == -1: \t\t\t\n\t\t\t\t\t\tprint(\"There is no room with this number in the cave. Your arrow travels randomly.\")\n\t\t\t\t\t\ttarget = random.choice(self.cave.keys())\n\t\t\t\t\tif bfs[1] > self.arrow_travel_distance:\t\t\t\t\n\t\t\t\t\t\tprint(\"Arrows aren't that croocked.\")\n\n\t\treturn mode, target\n\n\n\t\n\n\n\tdef enter_room(self, room_number):\n\t\t\t\n\t\tprint(\"Entering room {}...\".format(room_number))\n\t\t\n\t\tif self.threats.get(room_number) == 'bat':\n\t\t\t\n\t\t\tprint(\"You encounter a bat, it transports you to a random empty room.\")\n\t\t\tnew_pos = random.choice(self.get_safe_rooms())\n\t\t\treturn self.enter_room(new_pos)\n\t\telif self.threats.get(room_number) == 'wumpus':\n\t\t\tprint(\"Wumpus eats you.\")\n\t\t\treturn -1\n\t\telif self.threats.get(room_number) == 'pit':\n\t\t\tprint(\"You fall into a pit.\")\n\t\t\treturn -1\n\n\t\t\n\t\tfor i in self.cave[room_number]:\n\t\t\tself.print_warning(self.threats.get(i))\n\n\t\t\n\t\treturn room_number\n\n\n\tdef shoot_room(self, room_number):\n\t\t\n\t\tprint(\"Shooting an arrow into room {}...\".format(room_number))\n\t\t\n\t\tself.arrows -= 1\n\t\tthreat = self.threats.get(room_number)\n\t\tif threat in ['bat', 'wumpus']:\n\t\t\tdel self.threats[room_number]\t\t\n\t\t\tif threat == 'wumpus':\n\t\t\t\tprint(\"Hurra, you killed the wumpus!\")\n\t\t\t\treturn -1\n\t\t\telif threat == 'bat':\n\t\t\t\tprint(\"You killed a bat.\")\n\t\telif threat in ['pit', None]:\n\t\t\tprint(\"This arrow is lost.\")\n\t\t\n\t\t\n\t\tif self.arrows < 1:\t\t\n\t\t\tprint(\"Your quiver is empty.\")\n\t\t\treturn -1\n\n\t\t\n\t\tif random.random() < 0.75:\n\t\t\t\n\t\t\tfor room_number, threat in self.threats.items():\n\t\t\t\tif threat == 'wumpus':\n\t\t\t\t\twumpus_pos = room_number\t\t\t\t\t\n\t\t\tnew_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys())))\n\t\t\tdel self.threats[room_number]\n\t\t\tself.threats[new_pos] = 'wumpus'\t\t\t\n\t\t\tif new_pos == self.player_pos: \n\t\t\t\tprint(\"Wumpus enters your room and eats you!\")\n\t\t\t\treturn -1\n\n\t\treturn self.player_pos\n\n\t\t\n\tdef gameloop(self):\n\n\t\tprint(\"HUNT THE WUMPUS\")\n\t\tprint(\"===============\")\n\t\tprint()\n\t\tself.populate_cave()\n\t\tself.enter_room(self.player_pos)\n\n\t\twhile 1:\n\n\t\t\t\n\t\t\t\n\t\t\t\n\n\t\t\tprint(\"You are in room {}.\".format(self.player_pos), end=\" \")\n\t\t\tprint(\"Tunnels lead to:  {0}  {1}  {2}\".format(*self.cave[self.player_pos]))\n\t\t\t\n\t\t\t\n\t\t\tinpt = self.get_players_input()\t\t\n\t\t\tprint()\t\t\t\t\t\t\t\t\n\t\t\tif inpt[0] == 'm':\t\t\t\t\t\n\t\t\t\ttarget = inpt[1] \n\t\t\t\tself.player_pos = self.enter_room(target)\n\t\t\telif inpt[0] == 's':\t\t\t\t\n\t\t\t\ttarget = inpt[1]\n\t\t\t\tself.player_pos = self.shoot_room(target)\n\t\t\telif inpt[0] == 'q':\t\t\t\t\n\t\t\t\tself.player_pos = -1\n\n\t\t\tif self.player_pos == -1:\t\t\t\n\t\t\t\tbreak\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\tprint()\n\t\tprint(\"Game over!\")\t\n\t\t\n\nif __name__ == '__main__':\t\t\t\t\t\t\n\t\n\t\n\t\n\t\n\n\t\n\n\tWG = WumpusGame()\n\tWG.gameloop()\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar cave = map[int][3]int{\n    1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11},\n    6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16},\n    11: {5, 12, 17}, 12: {6, 11, 18}, 13: {7, 14, 18}, 14: {8, 13, 19},\n    15: {9, 16, 17}, 16: {10, 15, 19}, 17: {11, 20, 15}, 18: {12, 13, 20},\n    19: {14, 16, 20}, 20: {17, 18, 19},\n}\n\nvar player, wumpus, bat1, bat2, pit1, pit2 int\n\nvar arrows = 5\n\nfunc isEmpty(r int) bool {\n    if r != player && r != wumpus && r != bat1 && r != bat2 && r != pit1 && r != pit2 {\n        return true\n    }\n    return false\n}\n\nfunc sense(adj [3]int) {\n    bat := false\n    pit := false\n    for _, ar := range adj {\n        if ar == wumpus {\n            fmt.Println(\"You smell something terrible nearby.\")\n        }\n        switch ar {\n        case bat1, bat2:\n            if !bat {\n                fmt.Println(\"You hear a rustling.\")\n                bat = true\n            }\n        case pit1, pit2:\n            if !pit {\n                fmt.Println(\"You feel a cold wind blowing from a nearby cavern.\")\n                pit = true\n            }\n        }\n    }\n    fmt.Println()\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc plural(n int) string {\n    if n != 1 {\n        return \"s\"\n    }\n    return \"\"\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    player = 1\n    wumpus = rand.Intn(19) + 2 \n    bat1 = rand.Intn(19) + 2\n    for {\n        bat2 = rand.Intn(19) + 2\n        if bat2 != bat1 {\n            break\n        }\n    }\n    for {\n        pit1 = rand.Intn(19) + 2\n        if pit1 != bat1 && pit1 != bat2 {\n            break\n        }\n    }\n    for {\n        pit2 = rand.Intn(19) + 2\n        if pit2 != bat1 && pit2 != bat2 && pit2 != pit1 {\n            break\n        }\n    }\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        fmt.Printf(\"\\nYou are in room %d with %d arrow%s left\\n\", player, arrows, plural(arrows))\n        adj := cave[player]\n        fmt.Printf(\"The adjacent rooms are %v\\n\", adj)\n        sense(adj)\n        var room int\n        for {\n            fmt.Print(\"Choose an adjacent room : \")\n            scanner.Scan()\n            room, _ = strconv.Atoi(scanner.Text())\n            if room != adj[0] && room != adj[1] && room != adj[2] {\n                fmt.Println(\"Invalid response, try again\")\n            } else {\n                break\n            }\n        }\n        check(scanner.Err())\n        var action byte\n        for {\n            fmt.Print(\"Walk or shoot w/s : \")\n            scanner.Scan()\n            reply := strings.ToLower(scanner.Text())\n            if len(reply) != 1 || (len(reply) == 1 && reply[0] != 'w' && reply[0] != 's') {\n                fmt.Println(\"Invalid response, try again\")\n            } else {\n                action = reply[0]\n                break\n            }\n        }\n        check(scanner.Err())\n        if action == 'w' {\n            player = room\n            switch player {\n            case wumpus:\n                fmt.Println(\"You have been eaten by the Wumpus and lost the game!\")\n                return\n            case pit1, pit2:\n                fmt.Println(\"You have fallen down a bottomless pit and lost the game!\")\n                return\n            case bat1, bat2:\n                for {\n                    room = rand.Intn(19) + 2\n                    if isEmpty(room) {\n                        fmt.Println(\"A bat has transported you to a random empty room\")\n                        player = room\n                        break\n                    }\n                }\n            }\n        } else {\n            if room == wumpus {\n                fmt.Println(\"You have killed the Wumpus and won the game!!\")\n                return\n            } else {\n                chance := rand.Intn(4) \n                if chance > 0 {        \n                    wumpus = cave[wumpus][rand.Intn(3)]\n                    if player == wumpus {\n                        fmt.Println(\"You have been eaten by the Wumpus and lost the game!\")\n                        return\n                    }\n                }\n            }\n            arrows--\n            if arrows == 0 {\n                fmt.Println(\"You have run out of arrows and lost the game!\")\n                return\n            }\n        }\n    }\n}\n"}
{"id": 58544, "name": "Reverse the order of lines in a text file while preserving the contents of each line", "Python": "\n\nimport sys\n\nif len(sys.argv)!=2:\n    print(\"Usage : python \" + sys.argv[0] + \" <filename>\")\n    exit()\n\ndataFile = open(sys.argv[1],\"r\")\n\nfileData = dataFile.read().split('\\n')\n\ndataFile.close()\n\n[print(i) for i in fileData[::-1]]\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"runtime\"\n)\n\nfunc main() {\n    fileName1 := \"rodgers.txt\"\n    fileName2 := \"rodgers_reversed.txt\"\n    lineBreak := \"\\n\"\n    if runtime.GOOS == \"windows\" {\n        lineBreak = \"\\r\\n\"\n    }\n    \n    b, err := ioutil.ReadFile(fileName1)\n    if err != nil {\n        log.Fatal(err)\n    }\n    lines := bytes.Split(b, []byte(lineBreak))\n    \n    if len(lines[len(lines)-1]) == 0 {\n        lines = lines[:len(lines)-1]\n    }\n\n    \n    for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {\n        lines[i], lines[j] = lines[j], lines[i]\n    }\n    b = bytes.Join(lines, []byte(lineBreak))\n    if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil {\n        log.Fatal(err)\n    }\n    \n    b, err = ioutil.ReadFile(fileName2)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(b))\n}\n"}
{"id": 58545, "name": "Hourglass puzzle", "Python": "def hourglass_puzzle():\n    t4 = 0\n    while t4 < 10_000:\n        t7_left = 7 - t4 % 7\n        if t7_left == 9 - 4:\n            break\n        t4 += 4\n    else:\n        print('Not found')\n        return \n    print(f)\n \nhourglass_puzzle()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc minimum(a []int) int {\n    min := a[0]\n    for i := 1; i < len(a); i++ {\n        if a[i] < min {\n            min = a[i]\n        }\n    }\n    return min\n}\n\nfunc sum(a []int) int {\n    s := 0\n    for _, i := range a {\n        s = s + i\n    }\n    return s\n}\n\nfunc hourglassFlipper(hourglasses []int, target int) (int, []int) {\n    flippers := make([]int, len(hourglasses))\n    copy(flippers, hourglasses)\n    var series []int\n    for iter := 0; iter < 10000; iter++ {\n        n := minimum(flippers)\n        series = append(series, n)\n        for i := 0; i < len(flippers); i++ {\n            flippers[i] -= n\n        }\n        for i, flipper := range flippers {\n            if flipper == 0 {\n                flippers[i] = hourglasses[i]\n            }\n        }\n        for start := len(series) - 1; start >= 0; start-- {\n            if sum(series[start:]) == target {\n                return start, series\n            }\n        }\n    }\n    log.Fatal(\"Unable to find an answer within 10,000 iterations.\")\n    return 0, nil\n}\n\nfunc main() {\n    fmt.Print(\"Flip an hourglass every time it runs out of grains, \")\n    fmt.Println(\"and note the interval in time.\")\n    hgs := [][]int{{4, 7}, {5, 7, 31}}\n    ts := []int{9, 36}\n    for i := 0; i < len(hgs); i++ {\n        start, series := hourglassFlipper(hgs[i], ts[i])\n        end := len(series) - 1\n        fmt.Println(\"\\nSeries:\", series)\n        fmt.Printf(\"Use hourglasses from indices %d to %d (inclusive) to sum \", start, end)\n        fmt.Println(ts[i], \"using\", hgs[i])\n    }\n}\n"}
{"id": 58546, "name": "Hourglass puzzle", "Python": "def hourglass_puzzle():\n    t4 = 0\n    while t4 < 10_000:\n        t7_left = 7 - t4 % 7\n        if t7_left == 9 - 4:\n            break\n        t4 += 4\n    else:\n        print('Not found')\n        return \n    print(f)\n \nhourglass_puzzle()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc minimum(a []int) int {\n    min := a[0]\n    for i := 1; i < len(a); i++ {\n        if a[i] < min {\n            min = a[i]\n        }\n    }\n    return min\n}\n\nfunc sum(a []int) int {\n    s := 0\n    for _, i := range a {\n        s = s + i\n    }\n    return s\n}\n\nfunc hourglassFlipper(hourglasses []int, target int) (int, []int) {\n    flippers := make([]int, len(hourglasses))\n    copy(flippers, hourglasses)\n    var series []int\n    for iter := 0; iter < 10000; iter++ {\n        n := minimum(flippers)\n        series = append(series, n)\n        for i := 0; i < len(flippers); i++ {\n            flippers[i] -= n\n        }\n        for i, flipper := range flippers {\n            if flipper == 0 {\n                flippers[i] = hourglasses[i]\n            }\n        }\n        for start := len(series) - 1; start >= 0; start-- {\n            if sum(series[start:]) == target {\n                return start, series\n            }\n        }\n    }\n    log.Fatal(\"Unable to find an answer within 10,000 iterations.\")\n    return 0, nil\n}\n\nfunc main() {\n    fmt.Print(\"Flip an hourglass every time it runs out of grains, \")\n    fmt.Println(\"and note the interval in time.\")\n    hgs := [][]int{{4, 7}, {5, 7, 31}}\n    ts := []int{9, 36}\n    for i := 0; i < len(hgs); i++ {\n        start, series := hourglassFlipper(hgs[i], ts[i])\n        end := len(series) - 1\n        fmt.Println(\"\\nSeries:\", series)\n        fmt.Printf(\"Use hourglasses from indices %d to %d (inclusive) to sum \", start, end)\n        fmt.Println(ts[i], \"using\", hgs[i])\n    }\n}\n"}
{"id": 58547, "name": "Unique characters in each string", "Python": "LIST = [\"1a3c52debeffd\", \"2b6178c97a938stf\", \"3ycxdb1fgxa2yz\"]\n\nprint(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    strings := []string{\"1a3c52debeffd\", \"2b6178c97a938stf\", \"3ycxdb1fgxa2yz\"}\n    u := make(map[rune]int)\n    for _, s := range strings {\n        m := make(map[rune]int)\n        for _, c := range s {\n            m[c]++\n        }\n        for k, v := range m {\n            if v == 1 {\n                u[k]++\n            }\n        }\n    }\n    var chars []rune\n    for k, v := range u {\n        if v == 3 {\n            chars = append(chars, k)\n        }\n    }\n    sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] })\n    fmt.Println(string(chars))\n}\n"}
{"id": 58548, "name": "Fibonacci heap", "Python": "class FibonacciHeap:\n    \n    \n    class Node:\n        def __init__(self, data):\n            self.data = data\n            self.parent = self.child = self.left = self.right = None\n            self.degree = 0\n            self.mark = False\n            \n    \n    def iterate(self, head):\n        node = stop = head\n        flag = False\n        while True:\n            if node == stop and flag is True:\n                break\n            elif node == stop:\n                flag = True\n            yield node\n            node = node.right\n    \n    \n    root_list, min_node = None, None\n    \n    \n    total_nodes = 0\n    \n    \n    def find_min(self):\n        return self.min_node\n         \n    \n    \n    def extract_min(self):\n        z = self.min_node\n        if z is not None:\n            if z.child is not None:\n                \n                children = [x for x in self.iterate(z.child)]\n                for i in xrange(0, len(children)):\n                    self.merge_with_root_list(children[i])\n                    children[i].parent = None\n            self.remove_from_root_list(z)\n            \n            if z == z.right:\n                self.min_node = self.root_list = None\n            else:\n                self.min_node = z.right\n                self.consolidate()\n            self.total_nodes -= 1\n        return z\n                    \n    \n    def insert(self, data):\n        n = self.Node(data)\n        n.left = n.right = n\n        self.merge_with_root_list(n)\n        if self.min_node is None or n.data < self.min_node.data:\n            self.min_node = n\n        self.total_nodes += 1\n        \n    \n    def decrease_key(self, x, k):\n        if k > x.data:\n            return None\n        x.data = k\n        y = x.parent\n        if y is not None and x.data < y.data:\n            self.cut(x, y)\n            self.cascading_cut(y)\n        if x.data < self.min_node.data:\n            self.min_node = x\n            \n    \n    \n    \n    def merge(self, h2):\n        H = FibonacciHeap()\n        H.root_list, H.min_node = self.root_list, self.min_node\n        \n        last = h2.root_list.left\n        h2.root_list.left = H.root_list.left\n        H.root_list.left.right = h2.root_list\n        H.root_list.left = last\n        H.root_list.left.right = H.root_list\n        \n        if h2.min_node.data < H.min_node.data:\n            H.min_node = h2.min_node\n        \n        H.total_nodes = self.total_nodes + h2.total_nodes\n        return H\n        \n    \n    \n    def cut(self, x, y):\n        self.remove_from_child_list(y, x)\n        y.degree -= 1\n        self.merge_with_root_list(x)\n        x.parent = None\n        x.mark = False\n    \n    \n    def cascading_cut(self, y):\n        z = y.parent\n        if z is not None:\n            if y.mark is False:\n                y.mark = True\n            else:\n                self.cut(y, z)\n                self.cascading_cut(z)\n    \n    \n    \n    def consolidate(self):\n        A = [None] * self.total_nodes\n        nodes = [w for w in self.iterate(self.root_list)]\n        for w in xrange(0, len(nodes)):\n            x = nodes[w]\n            d = x.degree\n            while A[d] != None:\n                y = A[d] \n                if x.data > y.data:\n                    temp = x\n                    x, y = y, temp\n                self.heap_link(y, x)\n                A[d] = None\n                d += 1\n            A[d] = x\n        \n        \n        \n        for i in xrange(0, len(A)):\n            if A[i] is not None:\n                if A[i].data < self.min_node.data:\n                    self.min_node = A[i]\n        \n    \n    \n    def heap_link(self, y, x):\n        self.remove_from_root_list(y)\n        y.left = y.right = y\n        self.merge_with_child_list(x, y)\n        x.degree += 1\n        y.parent = x\n        y.mark = False\n        \n    \n    def merge_with_root_list(self, node):\n        if self.root_list is None:\n            self.root_list = node\n        else:\n            node.right = self.root_list.right\n            node.left = self.root_list\n            self.root_list.right.left = node\n            self.root_list.right = node\n            \n    \n    def merge_with_child_list(self, parent, node):\n        if parent.child is None:\n            parent.child = node\n        else:\n            node.right = parent.child.right\n            node.left = parent.child\n            parent.child.right.left = node\n            parent.child.right = node\n            \n    \n    def remove_from_root_list(self, node):\n        if node == self.root_list:\n            self.root_list = node.right\n        node.left.right = node.right\n        node.right.left = node.left\n        \n    \n    def remove_from_child_list(self, parent, node):\n        if parent.child == parent.child.right:\n            parent.child = None\n        elif parent.child == node:\n            parent.child = node.right\n            node.right.parent = parent\n        node.left.right = node.right\n        node.right.left = node.left\n", "Go": "package fib\n\nimport \"fmt\"\n\ntype Value interface {\n    LT(Value) bool\n}\n\ntype Node struct {\n    value      Value\n    parent     *Node\n    child      *Node\n    prev, next *Node\n    rank       int\n    mark       bool\n}\n\nfunc (n Node) Value() Value { return n.value }\n\ntype Heap struct{ *Node }\n\n\nfunc MakeHeap() *Heap { return &Heap{} }\n\n\nfunc (h *Heap) Insert(v Value) *Node {\n    x := &Node{value: v}\n    if h.Node == nil {\n        x.next = x\n        x.prev = x\n        h.Node = x\n    } else {\n        meld1(h.Node, x)\n        if x.value.LT(h.value) {\n            h.Node = x\n        }\n    }\n    return x\n}\n\nfunc meld1(list, single *Node) {\n    list.prev.next = single\n    single.prev = list.prev\n    single.next = list\n    list.prev = single\n}\n\n\nfunc (h *Heap) Union(h2 *Heap) {\n    switch {\n    case h.Node == nil:\n        *h = *h2\n    case h2.Node != nil:\n        meld2(h.Node, h2.Node)\n        if h2.value.LT(h.value) {\n            *h = *h2\n        }\n    }\n    h2.Node = nil\n}\n\nfunc meld2(a, b *Node) {\n    a.prev.next = b\n    b.prev.next = a\n    a.prev, b.prev = b.prev, a.prev\n}\n\n\nfunc (h Heap) Minimum() (min Value, ok bool) {\n    if h.Node == nil {\n        return\n    }\n    return h.value, true\n}\n\n\nfunc (h *Heap) ExtractMin() (min Value, ok bool) {\n    if h.Node == nil {\n        return\n    }\n    min = h.value\n    roots := map[int]*Node{}\n    add := func(r *Node) {\n        r.prev = r\n        r.next = r\n        for {\n            x, ok := roots[r.rank]\n            if !ok {\n               break\n            }\n            delete(roots, r.rank)\n            if x.value.LT(r.value) {\n                r, x = x, r\n            }\n            x.parent = r\n            x.mark = false\n            if r.child == nil {\n                x.next = x\n                x.prev = x\n                r.child = x\n            } else {\n                meld1(r.child, x)\n            }\n            r.rank++\n        }\n        roots[r.rank] = r\n    }\n    for r := h.next; r != h.Node; {\n        n := r.next\n        add(r)\n        r = n\n    }\n    if c := h.child; c != nil {\n        c.parent = nil\n        r := c.next\n        add(c)\n        for r != c {\n            n := r.next\n            r.parent = nil\n            add(r)\n            r = n\n        }\n    }\n    if len(roots) == 0 {\n        h.Node = nil\n        return min, true\n    }\n    var mv *Node\n    var d int\n    for d, mv = range roots {\n        break\n    }\n    delete(roots, d)\n    mv.next = mv\n    mv.prev = mv\n    for _, r := range roots {\n        r.prev = mv\n        r.next = mv.next\n        mv.next.prev = r\n        mv.next = r\n        if r.value.LT(mv.value) {\n            mv = r\n        }\n    }\n    h.Node = mv\n    return min, true\n}\n\n\nfunc (h *Heap) DecreaseKey(n *Node, v Value) error {\n    if n.value.LT(v) {\n        return fmt.Errorf(\"DecreaseKey new value greater than existing value\")\n    }\n    n.value = v\n    if n == h.Node {\n        return nil\n    }\n    p := n.parent\n    if p == nil {\n        if v.LT(h.value) {\n            h.Node = n\n        }\n        return nil\n    }\n    h.cutAndMeld(n)\n    return nil\n}\n\nfunc (h Heap) cut(x *Node) {\n    p := x.parent\n    p.rank--\n    if p.rank == 0 {\n        p.child = nil\n    } else {\n        p.child = x.next\n        x.prev.next = x.next\n        x.next.prev = x.prev\n    }\n    if p.parent == nil {\n        return\n    }\n    if !p.mark {\n        p.mark = true\n        return\n    }\n    h.cutAndMeld(p)\n}\n\nfunc (h Heap) cutAndMeld(x *Node) {\n    h.cut(x)\n    x.parent = nil\n    meld1(h.Node, x)\n}\n\n\nfunc (h *Heap) Delete(n *Node) {\n    p := n.parent\n    if p == nil {\n        if n == h.Node {\n            h.ExtractMin()\n            return\n        }\n        n.prev.next = n.next\n        n.next.prev = n.prev\n    } else {\n        h.cut(n)\n    }\n    c := n.child\n    if c == nil {\n        return\n    }\n    for {\n        c.parent = nil\n        c = c.next\n        if c == n.child {\n            break\n        }\n    }\n    meld2(h.Node, c)\n}\n\n\nfunc (h Heap) Vis() {\n    if h.Node == nil {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(*Node, string)\n    f = func(n *Node, pre string) {\n        pc := \"│ \"\n        for x := n; ; x = x.next {\n            if x.next != n {\n                fmt.Print(pre, \"├─\")\n            } else {\n                fmt.Print(pre, \"└─\")\n                pc = \"  \"\n            }\n            if x.child == nil {\n                fmt.Println(\"╴\", x.value)\n            } else {\n                fmt.Println(\"┐\", x.value)\n                f(x.child, pre+pc)\n            }\n            if x.next == n {\n                break\n            }\n        }\n    }\n    f(h.Node, \"\")\n}\n"}
{"id": 58549, "name": "Mayan calendar", "Python": "import datetime\n\n\ndef g2m(date, gtm_correlation=True):\n    \n\n    \n\n    correlation = 584283 if gtm_correlation else 584285\n\n    long_count_days = [144000, 7200, 360, 20, 1]\n\n    tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen',\n                      'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw']  \n\n    haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak',\n                   'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’']  \n\n    gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal()\n    julian_days = gregorian_days + 1721425\n\n    \n\n    long_date = list()\n    remainder = julian_days - correlation\n\n    for days in long_count_days:\n\n        result, remainder = divmod(remainder, days)\n        long_date.append(int(result))\n\n    long_date = '.'.join(['{:02d}'.format(d) for d in long_date])\n\n    \n\n    tzolkin_month = (julian_days + 16) % 20\n    tzolkin_day = ((julian_days + 5) % 13) + 1\n\n    haab_month = int(((julian_days + 65) % 365) / 20)\n    haab_day = ((julian_days + 65) % 365) % 20\n    haab_day = haab_day if haab_day else 'Chum'\n\n    lord_number = (julian_days - correlation) % 9\n    lord_number = lord_number if lord_number else 9\n\n    round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}'\n\n    return long_date, round_date\n\nif __name__ == '__main__':\n\n    dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01']\n\n    for date in dates:\n\n        long, round = g2m(date)\n        print(date, long, round)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar sacred = strings.Fields(\"Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw\")\n\nvar civil = strings.Fields(\"Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’\")\n\nvar (\n    date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC)\n    date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC)\n)\n\nfunc tzolkin(date time.Time) (int, string) {\n    diff := int(date.Sub(date1).Hours()) / 24\n    rem := diff % 13\n    if rem < 0 {\n        rem = 13 + rem\n    }\n    var num int\n    if rem <= 9 {\n        num = rem + 4\n    } else {\n        num = rem - 9\n    }\n    rem = diff % 20\n    if rem <= 0 {\n        rem = 20 + rem\n    }\n    return num, sacred[rem-1]\n}\n\nfunc haab(date time.Time) (string, string) {\n    diff := int(date.Sub(date2).Hours()) / 24\n    rem := diff % 365\n    if rem < 0 {\n        rem = 365 + rem\n    }\n    month := civil[(rem+1)/20]\n    last := 20\n    if month == \"Wayeb’\" {\n        last = 5\n    }\n    d := rem%20 + 1\n    if d < last {\n        return strconv.Itoa(d), month\n    }\n    return \"Chum\", month\n}\n\nfunc longCount(date time.Time) string {\n    diff := int(date.Sub(date1).Hours()) / 24\n    diff += 13 * 400 * 360\n    baktun := diff / (400 * 360)\n    diff %= 400 * 360\n    katun := diff / (20 * 360)\n    diff %= 20 * 360\n    tun := diff / 360\n    diff %= 360\n    winal := diff / 20\n    kin := diff % 20\n    return fmt.Sprintf(\"%d.%d.%d.%d.%d\", baktun, katun, tun, winal, kin)    \n}\n\nfunc lord(date time.Time) string {\n    diff := int(date.Sub(date1).Hours()) / 24\n    rem := diff % 9\n    if rem <= 0 {\n        rem = 9 + rem\n    }\n    return fmt.Sprintf(\"G%d\", rem)\n}\n\nfunc main() {\n    const shortForm = \"2006-01-02\"\n    dates := []string{\n        \"2004-06-19\",\n        \"2012-12-18\",\n        \"2012-12-21\",\n        \"2019-01-19\",\n        \"2019-03-27\",\n        \"2020-02-29\",\n        \"2020-03-01\",\n        \"2071-05-16\",\n    }\n    fmt.Println(\" Gregorian   Tzolk’in        Haab’              Long           Lord of\")\n    fmt.Println(\"   Date       # Name       Day Month            Count         the Night\")\n    fmt.Println(\"----------   --------    -------------        --------------  ---------\")\n    for _, dt := range dates {\n        date, _ := time.Parse(shortForm, dt)\n        n, s := tzolkin(date)\n        d, m := haab(date)\n        lc := longCount(date)\n        l := lord(date)\n        fmt.Printf(\"%s   %2d %-8s %4s %-9s       %-14s     %s\\n\", dt, n, s, d, m, lc, l)\n    }\n}\n"}
{"id": 58550, "name": "Smallest numbers", "Python": "\n\nimport sys\n\nif len(sys.argv)!=2:\n    print(\"Usage : python \" + sys.argv[0] + \" <whole number>\")\n    exit()\n\nnumLimit = int(sys.argv[1])\n\nresultSet = {}\n\nbase = 1\n\nwhile len(resultSet)!=numLimit:\n    result = base**base\n\n    for i in range(0,numLimit):\n        if str(i) in str(result) and i not in resultSet:\n            resultSet[i] = base\n\n    base+=1\n\n[print(resultSet[i], end=' ') for i in sorted(resultSet)]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    var res []int64\n    for n := 0; n <= 50; n++ {\n        ns := strconv.Itoa(n)\n        k := int64(1)\n        for {\n            bk := big.NewInt(k)\n            s := bk.Exp(bk, bk, nil).String()\n            if strings.Contains(s, ns) {\n                res = append(res, k)\n                break\n            }\n            k++\n        }\n    }\n    fmt.Println(\"The smallest positive integers K where K ^ K contains N (0..50) are:\")\n    for i, n := range res {\n        fmt.Printf(\"%2d \", n)\n        if (i+1)%17 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 58551, "name": "Safe and Sophie Germain primes", "Python": "print(\"working...\")\nrow = 0\nlimit = 1500\nSophie = []\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\nfor n in range(2,limit):\n\tp = 2*n + 1\n\tif isPrime(n) and isPrime(p):\n\t\tSophie.append(n)\n\nprint(\"Found \",end = \"\")\nprint(len(Sophie),end = \"\")\nprint(\" Safe and Sophie primes.\")\n\nprint(Sophie)\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var sgp []int\n    p := 2\n    count := 0\n    for count < 50 {\n        if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) {\n            sgp = append(sgp, p)\n            count++\n        }\n        if p != 2 {\n            p = p + 2\n        } else {\n            p = 3\n        }\n    }\n    fmt.Println(\"The first 50 Sophie Germain primes are:\")\n    for i := 0; i < len(sgp); i++ {\n        fmt.Printf(\"%5s \", rcu.Commatize(sgp[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 58552, "name": "Safe and Sophie Germain primes", "Python": "print(\"working...\")\nrow = 0\nlimit = 1500\nSophie = []\n\ndef isPrime(n):\n    for i in range(2,int(n**0.5)+1):\n        if n%i==0:\n            return False\n    return True\n\nfor n in range(2,limit):\n\tp = 2*n + 1\n\tif isPrime(n) and isPrime(p):\n\t\tSophie.append(n)\n\nprint(\"Found \",end = \"\")\nprint(len(Sophie),end = \"\")\nprint(\" Safe and Sophie primes.\")\n\nprint(Sophie)\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var sgp []int\n    p := 2\n    count := 0\n    for count < 50 {\n        if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) {\n            sgp = append(sgp, p)\n            count++\n        }\n        if p != 2 {\n            p = p + 2\n        } else {\n            p = 3\n        }\n    }\n    fmt.Println(\"The first 50 Sophie Germain primes are:\")\n    for i := 0; i < len(sgp); i++ {\n        fmt.Printf(\"%5s \", rcu.Commatize(sgp[i]))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 58553, "name": "Checksumcolor", "Python": "\n\n\nfrom __future__ import unicode_literals\n\nimport argparse\nimport fileinput\nimport os\nimport sys\n\nfrom functools import partial\nfrom itertools import count\nfrom itertools import takewhile\n\n\nANSI_RESET = \"\\u001b[0m\"\n\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nYELLOW = (255, 255, 0)\nBLUE = (0, 0, 255)\nMAGENTA = (255, 0, 255)\nCYAN = (0, 255, 255)\n\nANSI_PALETTE = {\n    RED: \"\\u001b[31m\",\n    GREEN: \"\\u001b[32m\",\n    YELLOW: \"\\u001b[33m\",\n    BLUE: \"\\u001b[34m\",\n    MAGENTA: \"\\u001b[35m\",\n    CYAN: \"\\u001b[36m\",\n}\n\n\n\n_8BIT_PALETTE = {\n    (0xAF, 0x00, 0x00): \"\\u001b[38;5;124m\",\n    (0xAF, 0x00, 0x5F): \"\\u001b[38;5;125m\",\n    (0xAF, 0x00, 0x87): \"\\u001b[38;5;126m\",\n    (0xAF, 0x00, 0xAF): \"\\u001b[38;5;127m\",\n    (0xAF, 0x00, 0xD7): \"\\u001b[38;5;128m\",\n    (0xAF, 0x00, 0xFF): \"\\u001b[38;5;129m\",\n    (0xAF, 0x5F, 0x00): \"\\u001b[38;5;130m\",\n    (0xAF, 0x5F, 0x5F): \"\\u001b[38;5;131m\",\n    (0xAF, 0x5F, 0x87): \"\\u001b[38;5;132m\",\n    (0xAF, 0x5F, 0xAF): \"\\u001b[38;5;133m\",\n    (0xAF, 0x5F, 0xD7): \"\\u001b[38;5;134m\",\n    (0xAF, 0x5F, 0xFF): \"\\u001b[38;5;135m\",\n    (0xAF, 0x87, 0x00): \"\\u001b[38;5;136m\",\n    (0xAF, 0x87, 0x5F): \"\\u001b[38;5;137m\",\n    (0xAF, 0x87, 0x87): \"\\u001b[38;5;138m\",\n    (0xAF, 0x87, 0xAF): \"\\u001b[38;5;139m\",\n    (0xAF, 0x87, 0xD7): \"\\u001b[38;5;140m\",\n    (0xAF, 0x87, 0xFF): \"\\u001b[38;5;141m\",\n    (0xAF, 0xAF, 0x00): \"\\u001b[38;5;142m\",\n    (0xAF, 0xAF, 0x5F): \"\\u001b[38;5;143m\",\n    (0xAF, 0xAF, 0x87): \"\\u001b[38;5;144m\",\n    (0xAF, 0xAF, 0xAF): \"\\u001b[38;5;145m\",\n    (0xAF, 0xAF, 0xD7): \"\\u001b[38;5;146m\",\n    (0xAF, 0xAF, 0xFF): \"\\u001b[38;5;147m\",\n    (0xAF, 0xD7, 0x00): \"\\u001b[38;5;148m\",\n    (0xAF, 0xD7, 0x5F): \"\\u001b[38;5;149m\",\n    (0xAF, 0xD7, 0x87): \"\\u001b[38;5;150m\",\n    (0xAF, 0xD7, 0xAF): \"\\u001b[38;5;151m\",\n    (0xAF, 0xD7, 0xD7): \"\\u001b[38;5;152m\",\n    (0xAF, 0xD7, 0xFF): \"\\u001b[38;5;153m\",\n    (0xAF, 0xFF, 0x00): \"\\u001b[38;5;154m\",\n    (0xAF, 0xFF, 0x5F): \"\\u001b[38;5;155m\",\n    (0xAF, 0xFF, 0x87): \"\\u001b[38;5;156m\",\n    (0xAF, 0xFF, 0xAF): \"\\u001b[38;5;157m\",\n    (0xAF, 0xFF, 0xD7): \"\\u001b[38;5;158m\",\n    (0xAF, 0xFF, 0xFF): \"\\u001b[38;5;159m\",\n}\n\n\ndef error(msg):\n    \n    sys.stderr.write(msg)\n    sys.stderr.write(os.linesep)\n    sys.exit(1)\n\n\ndef rgb(group):\n    \n    nibbles_per_channel = len(group) // 3\n    max_val = 16 ** nibbles_per_channel - 1\n    nibbles = chunked(group, nibbles_per_channel)\n\n    \n    return tuple((int(n, 16) * 255) // max_val for n in nibbles)\n\n\ndef distance(color, other):\n    \n    return sum((o - s) ** 2 for s, o in zip(color, other))\n\n\ndef chunked(seq, n):\n    \n    return takewhile(len, (seq[i : i + n] for i in count(0, n)))\n\n\ndef escape(group, palette):\n    \n    key = partial(distance, other=rgb(group.ljust(3, \"0\")))\n    ansi_color = min(palette, key=key)\n    return \"\".join([palette[ansi_color], group, ANSI_RESET])\n\n\ndef colorize(line, group_size=3, palette=ANSI_PALETTE):\n    \n    checksum, filename = line.split(None, 1)\n    escaped = [escape(group, palette) for group in chunked(checksum, group_size)]\n    sys.stdout.write(\"  \".join([\"\".join(escaped), filename]))\n\n\ndef html_colorize(checksum, group_size=3, palette=ANSI_PALETTE):\n    \n\n    def span(group):\n        key = partial(distance, other=rgb(group.ljust(3, \"0\")))\n        ansi_color = min(palette, key=key)\n        int_val = int.from_bytes(ansi_color, byteorder=\"big\")\n        hex_val = hex(int_val)[2:].rjust(6, \"0\")\n        return '<span style=\"color:\n\n    checksum, filename = line.split(None, 1)\n    escaped = [span(group) for group in chunked(checksum, group_size)]\n    sys.stdout.write(\"  \".join([\"\".join(escaped), filename]))\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description=\"Color checksum.\")\n\n    parser.add_argument(\n        \"-n\",\n        type=int,\n        default=3,\n        help=\"Color the checksum in groups of size N. Defaults to 3.\",\n    )\n\n    parser.add_argument(\n        \"-e\",\n        \"--extended-palette\",\n        action=\"store_true\",\n        help=\"Use the extended 8-bit palette. Defaults to False.\",\n    )\n\n    parser.add_argument(\n        \"--html\",\n        action=\"store_true\",\n        help=\"Output checksum groups wrapped with 'span' tags instead of ANSI escape sequences.\",\n    )\n\n    parser.add_argument(\"files\", nargs=\"*\", default=\"-\", metavar=\"FILE\")\n\n    args = parser.parse_args()\n\n    if sys.stdout.isatty():\n\n        palette = ANSI_PALETTE\n        if args.extended_palette:\n            palette = _8BIT_PALETTE\n\n        colorize_func = colorize\n        if args.html:\n            colorize_func = html_colorize\n\n        for line in fileinput.input(files=args.files):\n            colorize_func(line, group_size=args.n, palette=palette)\n    else:\n        \n        for line in fileinput.input(files=args.files):\n            sys.stdout.write(line)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"log\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n)\n\ntype Color struct{ r, g, b int }\n\ntype ColorEx struct {\n    color Color\n    code  string\n}\n\nvar colors = []ColorEx{\n    {Color{15, 0, 0}, \"31\"},\n    {Color{0, 15, 0}, \"32\"},\n    {Color{15, 15, 0}, \"33\"},\n    {Color{0, 0, 15}, \"34\"},\n    {Color{15, 0, 15}, \"35\"},\n    {Color{0, 15, 15}, \"36\"},\n}\n\nfunc squareDist(c1, c2 Color) int {\n    xd := c2.r - c1.r\n    yd := c2.g - c1.g\n    zd := c2.b - c1.b\n    return xd*xd + yd*yd + zd*zd\n}\n\nfunc printColor(s string) {\n    n := len(s)\n    k := 0\n    for i := 0; i < n/3; i++ {\n        j := i * 3\n        c1 := s[j]\n        c2 := s[j+1]\n        c3 := s[j+2]\n        k = j + 3\n        r, err := strconv.ParseInt(fmt.Sprintf(\"0x%c\", c1), 0, 64)\n        check(err)\n        g, err := strconv.ParseInt(fmt.Sprintf(\"0x%c\", c2), 0, 64)\n        check(err)\n        b, err := strconv.ParseInt(fmt.Sprintf(\"0x%c\", c3), 0, 64)\n        check(err)\n        rgb := Color{int(r), int(g), int(b)}\n        m := 676\n        colorCode := \"\"\n        for _, cex := range colors {\n            sqd := squareDist(cex.color, rgb)\n            if sqd < m {\n                colorCode = cex.code\n                m = sqd\n            }\n        }\n        fmt.Printf(\"\\033[%s;1m%c%c%c\\033[00m\", colorCode, c1, c2, c3)\n    }\n    for j := k; j < n; j++ {\n        c := s[j]\n        fmt.Printf(\"\\033[0;1m%c\\033[00m\", c)\n    }\n}\n\nvar (\n    r       = regexp.MustCompile(\"^([A-Fa-f0-9]+)([ \\t]+.+)$\")\n    scanner = bufio.NewScanner(os.Stdin)\n    err     error\n)\n\nfunc colorChecksum() {\n    for scanner.Scan() {\n        line := scanner.Text()\n        if r.MatchString(line) {\n            submatches := r.FindStringSubmatch(line)\n            s1 := submatches[1]\n            s2 := submatches[2]\n            printColor(s1)\n            fmt.Println(s2)\n        } else {\n            fmt.Println(line)\n        }\n    }\n    check(scanner.Err())\n}\n\nfunc cat() {\n    for scanner.Scan() {\n        line := scanner.Text()\n        fmt.Println(line)\n    }\n    check(scanner.Err())\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdout.Fd())) {\n        colorChecksum()\n    } else {\n        cat()\n    }\n}\n"}
{"id": 58554, "name": "URL shortener", "Python": "\n\nimport sqlite3\nimport string\nimport random\n\nfrom http import HTTPStatus\n\nfrom flask import Flask\nfrom flask import Blueprint\nfrom flask import abort\nfrom flask import current_app\nfrom flask import g\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import request\nfrom flask import url_for\n\n\nCHARS = frozenset(string.ascii_letters + string.digits)\nMIN_URL_SIZE = 8\nRANDOM_ATTEMPTS = 3\n\n\ndef create_app(*, db=None, server_name=None) -> Flask:\n    app = Flask(__name__)\n    app.config.from_mapping(\n        DATABASE=db or \"shorten.sqlite\",\n        SERVER_NAME=server_name,\n    )\n\n    with app.app_context():\n        init_db()\n\n    app.teardown_appcontext(close_db)\n    app.register_blueprint(shortener)\n\n    return app\n\n\ndef get_db():\n    if \"db\" not in g:\n        g.db = sqlite3.connect(current_app.config[\"DATABASE\"])\n        g.db.row_factory = sqlite3.Row\n\n    return g.db\n\n\ndef close_db(_):\n    db = g.pop(\"db\", None)\n\n    if db is not None:\n        db.close()\n\n\ndef init_db():\n    db = get_db()\n\n    with db:\n        db.execute(\n            \"CREATE TABLE IF NOT EXISTS shorten (\"\n            \"url TEXT PRIMARY KEY, \"\n            \"short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)\"\n        )\n\n\nshortener = Blueprint(\"shorten\", \"short\")\n\n\ndef random_short(size=MIN_URL_SIZE):\n    \n    return \"\".join(random.sample(CHARS, size))\n\n\n@shortener.errorhandler(HTTPStatus.NOT_FOUND)\ndef short_url_not_found(_):\n    return \"short url not found\", HTTPStatus.NOT_FOUND\n\n\n@shortener.route(\"/<path:key>\", methods=(\"GET\",))\ndef short(key):\n    db = get_db()\n\n    cursor = db.execute(\"SELECT url FROM shorten WHERE short = ?\", (key,))\n    row = cursor.fetchone()\n\n    if row is None:\n        abort(HTTPStatus.NOT_FOUND)\n\n    \n    return redirect(row[\"url\"], code=HTTPStatus.FOUND)\n\n\nclass URLExistsError(Exception):\n    \n\n\nclass ShortCollisionError(Exception):\n    \n\n\ndef _insert_short(long_url, short):\n    \n    db = get_db()\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE url = ?\", (long_url,)).fetchone()\n        is not None\n    ):\n        raise URLExistsError(long_url)\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE short = ?\", (short,)).fetchone()\n        is not None\n    ):\n        raise ShortCollisionError(short)\n\n    with db:\n        db.execute(\"INSERT INTO shorten VALUES (?, ?)\", (long_url, short))\n\n\ndef make_short(long_url):\n    \n    size = MIN_URL_SIZE\n    attempts = 1\n    short = random_short(size=size)\n\n    while True:\n        try:\n            _insert_short(long_url, short)\n        except ShortCollisionError:\n            \n            if not attempts % RANDOM_ATTEMPTS:\n                size += 1\n\n            attempts += 1\n            short = random_short(size=size)\n        else:\n            break\n\n    return short\n\n\n@shortener.route(\"/\", methods=(\"POST\",))\ndef shorten():\n    data = request.get_json()\n\n    if data is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    long_url = data.get(\"long\")\n\n    if long_url is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    db = get_db()\n\n    \n    cursor = db.execute(\"SELECT short FROM shorten WHERE url = ?\", (long_url,))\n    row = cursor.fetchone()\n\n    if row is not None:\n        short_url = url_for(\"shorten.short\", _external=True, key=row[\"short\"])\n        status_code = HTTPStatus.OK\n    else:\n        short_url = url_for(\"shorten.short\", _external=True, key=make_short(long_url))\n        status_code = HTTPStatus.CREATED\n\n    mimetype = request.accept_mimetypes.best_match(\n        matches=[\"text/plain\", \"application/json\"], default=\"text/plain\"\n    )\n\n    if mimetype == \"application/json\":\n        return jsonify(long=long_url, short=short_url), status_code\n    else:\n        return short_url, status_code\n\n\nif __name__ == \"__main__\":\n    \n    app = create_app()\n    app.env = \"development\"\n    app.run(debug=True)\n", "Go": "\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"net/http\"\n    \"time\"\n)\n\nconst (\n    chars = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    host  = \"localhost:8000\"\n)\n\ntype database map[string]string\n\ntype shortener struct {\n    Long string `json:\"long\"`\n}\n\nfunc (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n    switch req.Method {\n    case http.MethodPost: \n        body, err := ioutil.ReadAll(req.Body)\n        if err != nil {\n            w.WriteHeader(http.StatusBadRequest) \n            return\n        }\n        var sh shortener\n        err = json.Unmarshal(body, &sh)\n        if err != nil {\n            w.WriteHeader(http.StatusUnprocessableEntity) \n            return\n        }\n        short := generateKey(8)\n        db[short] = sh.Long\n        fmt.Fprintf(w, \"The shortened URL: http:\n    case http.MethodGet: \n        path := req.URL.Path[1:]\n        if v, ok := db[path]; ok {\n            http.Redirect(w, req, v, http.StatusFound) \n        } else {\n            w.WriteHeader(http.StatusNotFound) \n            fmt.Fprintf(w, \"No such shortened url: http:\n        }\n    default:\n        w.WriteHeader(http.StatusNotFound) \n        fmt.Fprintf(w, \"Unsupprted method: %s\\n\", req.Method)\n    }\n}\n\nfunc generateKey(size int) string {\n    key := make([]byte, size)\n    le := len(chars)\n    for i := 0; i < size; i++ {\n        key[i] = chars[rand.Intn(le)]\n    }\n    return string(key)\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    db := make(database)\n    log.Fatal(http.ListenAndServe(host, db))\n}\n"}
{"id": 58555, "name": "URL shortener", "Python": "\n\nimport sqlite3\nimport string\nimport random\n\nfrom http import HTTPStatus\n\nfrom flask import Flask\nfrom flask import Blueprint\nfrom flask import abort\nfrom flask import current_app\nfrom flask import g\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import request\nfrom flask import url_for\n\n\nCHARS = frozenset(string.ascii_letters + string.digits)\nMIN_URL_SIZE = 8\nRANDOM_ATTEMPTS = 3\n\n\ndef create_app(*, db=None, server_name=None) -> Flask:\n    app = Flask(__name__)\n    app.config.from_mapping(\n        DATABASE=db or \"shorten.sqlite\",\n        SERVER_NAME=server_name,\n    )\n\n    with app.app_context():\n        init_db()\n\n    app.teardown_appcontext(close_db)\n    app.register_blueprint(shortener)\n\n    return app\n\n\ndef get_db():\n    if \"db\" not in g:\n        g.db = sqlite3.connect(current_app.config[\"DATABASE\"])\n        g.db.row_factory = sqlite3.Row\n\n    return g.db\n\n\ndef close_db(_):\n    db = g.pop(\"db\", None)\n\n    if db is not None:\n        db.close()\n\n\ndef init_db():\n    db = get_db()\n\n    with db:\n        db.execute(\n            \"CREATE TABLE IF NOT EXISTS shorten (\"\n            \"url TEXT PRIMARY KEY, \"\n            \"short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)\"\n        )\n\n\nshortener = Blueprint(\"shorten\", \"short\")\n\n\ndef random_short(size=MIN_URL_SIZE):\n    \n    return \"\".join(random.sample(CHARS, size))\n\n\n@shortener.errorhandler(HTTPStatus.NOT_FOUND)\ndef short_url_not_found(_):\n    return \"short url not found\", HTTPStatus.NOT_FOUND\n\n\n@shortener.route(\"/<path:key>\", methods=(\"GET\",))\ndef short(key):\n    db = get_db()\n\n    cursor = db.execute(\"SELECT url FROM shorten WHERE short = ?\", (key,))\n    row = cursor.fetchone()\n\n    if row is None:\n        abort(HTTPStatus.NOT_FOUND)\n\n    \n    return redirect(row[\"url\"], code=HTTPStatus.FOUND)\n\n\nclass URLExistsError(Exception):\n    \n\n\nclass ShortCollisionError(Exception):\n    \n\n\ndef _insert_short(long_url, short):\n    \n    db = get_db()\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE url = ?\", (long_url,)).fetchone()\n        is not None\n    ):\n        raise URLExistsError(long_url)\n\n    if (\n        db.execute(\"SELECT * FROM shorten WHERE short = ?\", (short,)).fetchone()\n        is not None\n    ):\n        raise ShortCollisionError(short)\n\n    with db:\n        db.execute(\"INSERT INTO shorten VALUES (?, ?)\", (long_url, short))\n\n\ndef make_short(long_url):\n    \n    size = MIN_URL_SIZE\n    attempts = 1\n    short = random_short(size=size)\n\n    while True:\n        try:\n            _insert_short(long_url, short)\n        except ShortCollisionError:\n            \n            if not attempts % RANDOM_ATTEMPTS:\n                size += 1\n\n            attempts += 1\n            short = random_short(size=size)\n        else:\n            break\n\n    return short\n\n\n@shortener.route(\"/\", methods=(\"POST\",))\ndef shorten():\n    data = request.get_json()\n\n    if data is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    long_url = data.get(\"long\")\n\n    if long_url is None:\n        abort(HTTPStatus.BAD_REQUEST)\n\n    db = get_db()\n\n    \n    cursor = db.execute(\"SELECT short FROM shorten WHERE url = ?\", (long_url,))\n    row = cursor.fetchone()\n\n    if row is not None:\n        short_url = url_for(\"shorten.short\", _external=True, key=row[\"short\"])\n        status_code = HTTPStatus.OK\n    else:\n        short_url = url_for(\"shorten.short\", _external=True, key=make_short(long_url))\n        status_code = HTTPStatus.CREATED\n\n    mimetype = request.accept_mimetypes.best_match(\n        matches=[\"text/plain\", \"application/json\"], default=\"text/plain\"\n    )\n\n    if mimetype == \"application/json\":\n        return jsonify(long=long_url, short=short_url), status_code\n    else:\n        return short_url, status_code\n\n\nif __name__ == \"__main__\":\n    \n    app = create_app()\n    app.env = \"development\"\n    app.run(debug=True)\n", "Go": "\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math/rand\"\n    \"net/http\"\n    \"time\"\n)\n\nconst (\n    chars = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    host  = \"localhost:8000\"\n)\n\ntype database map[string]string\n\ntype shortener struct {\n    Long string `json:\"long\"`\n}\n\nfunc (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n    switch req.Method {\n    case http.MethodPost: \n        body, err := ioutil.ReadAll(req.Body)\n        if err != nil {\n            w.WriteHeader(http.StatusBadRequest) \n            return\n        }\n        var sh shortener\n        err = json.Unmarshal(body, &sh)\n        if err != nil {\n            w.WriteHeader(http.StatusUnprocessableEntity) \n            return\n        }\n        short := generateKey(8)\n        db[short] = sh.Long\n        fmt.Fprintf(w, \"The shortened URL: http:\n    case http.MethodGet: \n        path := req.URL.Path[1:]\n        if v, ok := db[path]; ok {\n            http.Redirect(w, req, v, http.StatusFound) \n        } else {\n            w.WriteHeader(http.StatusNotFound) \n            fmt.Fprintf(w, \"No such shortened url: http:\n        }\n    default:\n        w.WriteHeader(http.StatusNotFound) \n        fmt.Fprintf(w, \"Unsupprted method: %s\\n\", req.Method)\n    }\n}\n\nfunc generateKey(size int) string {\n    key := make([]byte, size)\n    le := len(chars)\n    for i := 0; i < size; i++ {\n        key[i] = chars[rand.Intn(le)]\n    }\n    return string(key)\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    db := make(database)\n    log.Fatal(http.ListenAndServe(host, db))\n}\n"}
{"id": 58556, "name": "Hexapawn", "Python": "\nimport sys\n\nblack_pawn = \" \\u265f  \"\nwhite_pawn = \" \\u2659  \"\nempty_square = \"    \"\n\n\ndef draw_board(board_data):\n    \n    bg_black = \"\\u001b[48;5;237m\"\n    \n    bg_white = \"\\u001b[48;5;245m\"\n\n    clear_to_eol = \"\\u001b[0m\\u001b[K\\n\"\n\n    board = [\"1 \", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol,\n             \"2 \", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol,\n             \"3 \", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol,\n             \"   A   B   C\\n\"];\n\n    sys.stdout.write(\"\".join(board))\n\ndef get_movement_direction(colour):\n    direction = -1\n    if colour == black_pawn:\n        direction = 1\n    elif colour == white_pawn:\n        direction = -1\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\n    return direction\n\ndef get_other_colour(colour):\n    if colour == black_pawn:\n        return white_pawn\n    elif colour == white_pawn:\n        return black_pawn\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\ndef get_allowed_moves(board_data, row, col):\n    if board_data[row][col] == empty_square:\n        return set()\n\n    colour = board_data[row][col]\n    other_colour = get_other_colour(colour)\n    direction = get_movement_direction(colour)\n\n    if (row + direction < 0 or row + direction > 2):\n        return set()\n\n    allowed_moves = set()\n    if board_data[row + direction][col] == empty_square:\n        allowed_moves.add('f')\n    if col > 0 and board_data[row + direction][col - 1] == other_colour:\n        allowed_moves.add('dl')\n    if col < 2 and board_data[row + direction][col + 1] == other_colour:\n        allowed_moves.add('dr')\n\n    return allowed_moves\n\ndef get_human_move(board_data, colour):\n    \n    direction = get_movement_direction(colour)\n\n    while True:\n        piece_posn = input(f'What {colour} do you want to move? ')\n        valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2),\n                        'a2': (1,0), 'b2': (1,1), 'c2': (1,2),\n                        'a3': (2,0), 'b3': (2,1), 'c3': (2,2)}\n        if piece_posn not in valid_inputs:\n            print(\"LOL that's not a valid position! Try again.\")\n            continue\n\n        (row, col) = valid_inputs[piece_posn]\n        piece = board_data[row][col]\n        if piece == empty_square:\n            print(\"What are you trying to pull, there's no piece in that space!\")\n            continue\n\n        if piece != colour:\n            print(\"LOL that's not your piece, try again!\")\n            continue\n\n        allowed_moves = get_allowed_moves(board_data, row, col)\n\n        if len(allowed_moves) == 0:\n            print('LOL nice try. That piece has no valid moves.')\n            continue\n\n        move = list(allowed_moves)[0]\n        if len(allowed_moves) > 1:\n            move = input(f'What move do you want to make ({\",\".join(list(allowed_moves))})? ')\n            if move not in allowed_moves:\n                print('LOL that move is not allowed. Try again.')\n                continue\n\n        if move == 'f':\n            board_data[row + direction][col] = board_data[row][col]\n        elif move == 'dl':\n            board_data[row + direction][col - 1] = board_data[row][col]\n        elif move == 'dr':\n            board_data[row + direction][col + 1] = board_data[row][col]\n\n        board_data[row][col] = empty_square\n        return board_data\n\n\ndef is_game_over(board_data):\n    if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn:\n        return white_pawn\n\n    if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn:\n        return black_pawn\n\n    white_count = 0\n    black_count = 0\n    black_allowed_moves = []\n    white_allowed_moves = []\n    for i in range(3):\n        for j in range(3):\n            moves = get_allowed_moves(board_data, i, j)\n\n            if board_data[i][j] == white_pawn:\n                white_count += 1\n                if len(moves) > 0:\n                    white_allowed_moves.append((i,j,moves))\n            if board_data[i][j] == black_pawn:\n                black_count += 1\n                if len(moves) > 0:\n                    black_allowed_moves.append((i,j,moves))\n\n    if white_count == 0 or len(white_allowed_moves) == 0:\n        return black_pawn\n    if black_count == 0 or len(black_allowed_moves) == 0:\n        return white_pawn\n\n    return \"LOL NOPE\"\n\ndef play_game(black_move, white_move):\n\n    board_data = [[black_pawn, black_pawn, black_pawn],\n                  [empty_square, empty_square, empty_square],\n                  [white_pawn, white_pawn, white_pawn]]\n\n    last_player = black_pawn\n    next_player = white_pawn\n    while is_game_over(board_data) == \"LOL NOPE\":\n        draw_board(board_data)\n\n        if (next_player == black_pawn):\n            board_data = black_move(board_data, next_player)\n        else:\n            board_data = white_move(board_data, next_player)\n\n        temp = last_player\n        last_player = next_player\n        next_player = temp\n\n    winner = is_game_over(board_data)\n    print(f'Congratulations {winner}!')\n\nplay_game(get_human_move, get_human_move)\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\nconst (\n\tRows = 3\n\tCols = 3\n)\n\nvar vlog *log.Logger\n\nfunc main() {\n\tverbose := flag.Bool(\"v\", false, \"verbose\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tlogOutput := ioutil.Discard\n\tif *verbose {\n\t\tlogOutput = os.Stderr\n\t}\n\tvlog = log.New(logOutput, \"hexapawn: \", 0)\n\n\trand.Seed(time.Now().UnixNano())\n\twins := make(map[spot]int, 2)\n\tfor {\n\t\th := New()\n\t\tvar s herGameState\n\t\tfor c := false; h[stateIdx] == empty; c = !c {\n\t\t\tif c {\n\t\t\t\th = s.Move(h)\n\t\t\t} else {\n\t\t\t\th = h.HumanMove()\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Board:\\n%v is a win for %v\\n\", h, h[stateIdx])\n\t\ts.Result(h[stateIdx])\n\t\twins[h[stateIdx]]++\n\t\tfmt.Printf(\"Wins: Black=%d, White=%d\\n\", wins[black], wins[white])\n\t\tfmt.Println()\n\t}\n}\n\nfunc (h Hexapawn) HumanMove() Hexapawn {\n\tfmt.Print(\"Board:\\n\", h, \"\\n\")\n\tvar from, to int\n\tfor {\n\t\tfmt.Print(\"Your move: \")\n\t\t_, err := fmt.Scanln(&from, &to)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err == io.EOF {\n\t\t\t\tos.Exit(0) \n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err := h.doMove(white, from-1, to-1); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\treturn h\n\t}\n}\n\nvar herNextMove = make(map[Hexapawn][]move)\n\ntype herGameState struct {\n\t\n\th Hexapawn\n\ti int\n}\n\nfunc (s *herGameState) Move(h Hexapawn) Hexapawn {\n\tknown := false\n\tmoves := herNextMove[h]\n\tif moves == nil { \n\t\tmoves = possibleMoves(black, h)\n\t\therNextMove[h] = moves\n\t} else if len(moves) == 0 {\n\t\t\n\t\tvlog.Println(\"no good moves left to black, picking a random looser\")\n\t\tknown = true\n\t\tmoves = possibleMoves(black, h)\n\t}\n\tvlog.Println(\"considering\", moves)\n\ti := rand.Intn(len(moves))\n\tif !known {\n\t\ts.h = h\n\t\ts.i = i\n\t}\n\tfmt.Println(\"Computer moves\", moves[i])\n\tif err := h.doMove(black, moves[i].from, moves[i].to); err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}\n\nfunc (s herGameState) Result(winner spot) {\n\tif winner == black {\n\t\treturn \n\t}\n\t\n\tmoves := herNextMove[s.h]\n\tvlog.Printf(\"Training:\\n%v will no longer do %v\\n\", s.h, moves[s.i])\n\therNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...)\n\tvlog.Println(\"will instead do one of:\", herNextMove[s.h])\n}\n\ntype move struct{ from, to int }\n\nfunc (m move) String() string { return fmt.Sprintf(\"%d→%d\", m.from+1, m.to+1) }\n\nvar cachedMoves = []map[Hexapawn][]move{\n\tblack: make(map[Hexapawn][]move),\n\twhite: make(map[Hexapawn][]move),\n}\n\nfunc possibleMoves(s spot, h Hexapawn) []move {\n\tm := cachedMoves[s][h]\n\tif m != nil {\n\t\treturn m\n\t}\n\t\n\t\n\t\n\tm = make([]move, 0)\n\tfor from := 0; from < Rows*Cols; from++ {\n\t\tfor to := 0; to < Rows*Cols; to++ {\n\t\t\tif err := h.checkMove(s, from, to); err == nil {\n\t\t\t\tm = append(m, move{from, to})\n\t\t\t}\n\t\t}\n\t}\n\tcachedMoves[s][h] = m\n\tvlog.Printf(\"caclulated possible moves for %v\\n%v as %v\\n\", s, h, m)\n\treturn m\n}\n\nfunc (h *Hexapawn) doMove(p spot, from, to int) error {\n\tif err := h.checkMove(p, from, to); err != nil {\n\t\treturn err\n\t}\n\th[from] = empty\n\th[to] = p\n\tif (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) {\n\t\th[stateIdx] = p\n\t} else if len(possibleMoves(p.Other(), *h)) == 0 {\n\t\th[stateIdx] = p\n\t}\n\treturn nil\n}\n\nfunc (h *Hexapawn) checkMove(p spot, from, to int) error {\n\tif h[from] != p {\n\t\treturn fmt.Errorf(\"No %v located at spot %v\", p, from+1)\n\t}\n\tif h[to] == p {\n\t\treturn fmt.Errorf(\"%v already occupies spot %v\", p, to+1)\n\t}\n\tΔr := from/Rows - to/Rows\n\tif (p == white && Δr != -1) || (p == black && Δr != 1) {\n\t\treturn errors.New(\"must move forward one row\")\n\t}\n\tΔc := from%Rows - to%Rows\n\tcapture := h[to] != empty\n\tif (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) {\n\t\treturn errors.New(\"ilegal move\")\n\t}\n\treturn nil\n}\n\ntype Hexapawn [Rows*Cols + 1]spot\n\nfunc New() Hexapawn {\n\t\n\treturn Hexapawn{\n\t\twhite, white, white,\n\t\tempty, empty, empty,\n\t\tblack, black, black,\n\t}\n}\n\nfunc idx(r, c int) int { return r*Cols + c }\n\n\nconst stateIdx = Rows * Cols\n\nfunc (h Hexapawn) String() string {\n\tvar b bytes.Buffer\n\tfor r := Rows - 1; r >= 0; r-- {\n\t\tfor c := 0; c < Cols; c++ {\n\t\t\tb.WriteByte(h[idx(r, c)].Byte())\n\t\t}\n\t\tb.WriteByte('\\n')\n\t}\n\t\n\treturn string(b.Next(Rows*(Cols+1) - 1))\n}\n\ntype spot uint8\n\nconst (\n\tempty spot = iota\n\tblack\n\twhite\n)\n\nfunc (s spot) String() string {\n\tswitch s {\n\tcase black:\n\t\treturn \"Black\"\n\tcase white:\n\t\treturn \"White\"\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Byte() byte {\n\tswitch s {\n\tcase empty:\n\t\treturn '.'\n\tcase black:\n\t\treturn 'B'\n\tcase white:\n\t\treturn 'W'\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Other() spot {\n\tif s == black {\n\t\treturn white\n\t}\n\treturn black\n}\n"}
{"id": 58557, "name": "Hexapawn", "Python": "\nimport sys\n\nblack_pawn = \" \\u265f  \"\nwhite_pawn = \" \\u2659  \"\nempty_square = \"    \"\n\n\ndef draw_board(board_data):\n    \n    bg_black = \"\\u001b[48;5;237m\"\n    \n    bg_white = \"\\u001b[48;5;245m\"\n\n    clear_to_eol = \"\\u001b[0m\\u001b[K\\n\"\n\n    board = [\"1 \", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol,\n             \"2 \", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol,\n             \"3 \", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol,\n             \"   A   B   C\\n\"];\n\n    sys.stdout.write(\"\".join(board))\n\ndef get_movement_direction(colour):\n    direction = -1\n    if colour == black_pawn:\n        direction = 1\n    elif colour == white_pawn:\n        direction = -1\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\n    return direction\n\ndef get_other_colour(colour):\n    if colour == black_pawn:\n        return white_pawn\n    elif colour == white_pawn:\n        return black_pawn\n    else:\n        raise ValueError(\"Invalid piece colour\")\n\ndef get_allowed_moves(board_data, row, col):\n    if board_data[row][col] == empty_square:\n        return set()\n\n    colour = board_data[row][col]\n    other_colour = get_other_colour(colour)\n    direction = get_movement_direction(colour)\n\n    if (row + direction < 0 or row + direction > 2):\n        return set()\n\n    allowed_moves = set()\n    if board_data[row + direction][col] == empty_square:\n        allowed_moves.add('f')\n    if col > 0 and board_data[row + direction][col - 1] == other_colour:\n        allowed_moves.add('dl')\n    if col < 2 and board_data[row + direction][col + 1] == other_colour:\n        allowed_moves.add('dr')\n\n    return allowed_moves\n\ndef get_human_move(board_data, colour):\n    \n    direction = get_movement_direction(colour)\n\n    while True:\n        piece_posn = input(f'What {colour} do you want to move? ')\n        valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2),\n                        'a2': (1,0), 'b2': (1,1), 'c2': (1,2),\n                        'a3': (2,0), 'b3': (2,1), 'c3': (2,2)}\n        if piece_posn not in valid_inputs:\n            print(\"LOL that's not a valid position! Try again.\")\n            continue\n\n        (row, col) = valid_inputs[piece_posn]\n        piece = board_data[row][col]\n        if piece == empty_square:\n            print(\"What are you trying to pull, there's no piece in that space!\")\n            continue\n\n        if piece != colour:\n            print(\"LOL that's not your piece, try again!\")\n            continue\n\n        allowed_moves = get_allowed_moves(board_data, row, col)\n\n        if len(allowed_moves) == 0:\n            print('LOL nice try. That piece has no valid moves.')\n            continue\n\n        move = list(allowed_moves)[0]\n        if len(allowed_moves) > 1:\n            move = input(f'What move do you want to make ({\",\".join(list(allowed_moves))})? ')\n            if move not in allowed_moves:\n                print('LOL that move is not allowed. Try again.')\n                continue\n\n        if move == 'f':\n            board_data[row + direction][col] = board_data[row][col]\n        elif move == 'dl':\n            board_data[row + direction][col - 1] = board_data[row][col]\n        elif move == 'dr':\n            board_data[row + direction][col + 1] = board_data[row][col]\n\n        board_data[row][col] = empty_square\n        return board_data\n\n\ndef is_game_over(board_data):\n    if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn:\n        return white_pawn\n\n    if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn:\n        return black_pawn\n\n    white_count = 0\n    black_count = 0\n    black_allowed_moves = []\n    white_allowed_moves = []\n    for i in range(3):\n        for j in range(3):\n            moves = get_allowed_moves(board_data, i, j)\n\n            if board_data[i][j] == white_pawn:\n                white_count += 1\n                if len(moves) > 0:\n                    white_allowed_moves.append((i,j,moves))\n            if board_data[i][j] == black_pawn:\n                black_count += 1\n                if len(moves) > 0:\n                    black_allowed_moves.append((i,j,moves))\n\n    if white_count == 0 or len(white_allowed_moves) == 0:\n        return black_pawn\n    if black_count == 0 or len(black_allowed_moves) == 0:\n        return white_pawn\n\n    return \"LOL NOPE\"\n\ndef play_game(black_move, white_move):\n\n    board_data = [[black_pawn, black_pawn, black_pawn],\n                  [empty_square, empty_square, empty_square],\n                  [white_pawn, white_pawn, white_pawn]]\n\n    last_player = black_pawn\n    next_player = white_pawn\n    while is_game_over(board_data) == \"LOL NOPE\":\n        draw_board(board_data)\n\n        if (next_player == black_pawn):\n            board_data = black_move(board_data, next_player)\n        else:\n            board_data = white_move(board_data, next_player)\n\n        temp = last_player\n        last_player = next_player\n        next_player = temp\n\n    winner = is_game_over(board_data)\n    print(f'Congratulations {winner}!')\n\nplay_game(get_human_move, get_human_move)\n", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\nconst (\n\tRows = 3\n\tCols = 3\n)\n\nvar vlog *log.Logger\n\nfunc main() {\n\tverbose := flag.Bool(\"v\", false, \"verbose\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tlogOutput := ioutil.Discard\n\tif *verbose {\n\t\tlogOutput = os.Stderr\n\t}\n\tvlog = log.New(logOutput, \"hexapawn: \", 0)\n\n\trand.Seed(time.Now().UnixNano())\n\twins := make(map[spot]int, 2)\n\tfor {\n\t\th := New()\n\t\tvar s herGameState\n\t\tfor c := false; h[stateIdx] == empty; c = !c {\n\t\t\tif c {\n\t\t\t\th = s.Move(h)\n\t\t\t} else {\n\t\t\t\th = h.HumanMove()\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Board:\\n%v is a win for %v\\n\", h, h[stateIdx])\n\t\ts.Result(h[stateIdx])\n\t\twins[h[stateIdx]]++\n\t\tfmt.Printf(\"Wins: Black=%d, White=%d\\n\", wins[black], wins[white])\n\t\tfmt.Println()\n\t}\n}\n\nfunc (h Hexapawn) HumanMove() Hexapawn {\n\tfmt.Print(\"Board:\\n\", h, \"\\n\")\n\tvar from, to int\n\tfor {\n\t\tfmt.Print(\"Your move: \")\n\t\t_, err := fmt.Scanln(&from, &to)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err == io.EOF {\n\t\t\t\tos.Exit(0) \n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err := h.doMove(white, from-1, to-1); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\treturn h\n\t}\n}\n\nvar herNextMove = make(map[Hexapawn][]move)\n\ntype herGameState struct {\n\t\n\th Hexapawn\n\ti int\n}\n\nfunc (s *herGameState) Move(h Hexapawn) Hexapawn {\n\tknown := false\n\tmoves := herNextMove[h]\n\tif moves == nil { \n\t\tmoves = possibleMoves(black, h)\n\t\therNextMove[h] = moves\n\t} else if len(moves) == 0 {\n\t\t\n\t\tvlog.Println(\"no good moves left to black, picking a random looser\")\n\t\tknown = true\n\t\tmoves = possibleMoves(black, h)\n\t}\n\tvlog.Println(\"considering\", moves)\n\ti := rand.Intn(len(moves))\n\tif !known {\n\t\ts.h = h\n\t\ts.i = i\n\t}\n\tfmt.Println(\"Computer moves\", moves[i])\n\tif err := h.doMove(black, moves[i].from, moves[i].to); err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}\n\nfunc (s herGameState) Result(winner spot) {\n\tif winner == black {\n\t\treturn \n\t}\n\t\n\tmoves := herNextMove[s.h]\n\tvlog.Printf(\"Training:\\n%v will no longer do %v\\n\", s.h, moves[s.i])\n\therNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...)\n\tvlog.Println(\"will instead do one of:\", herNextMove[s.h])\n}\n\ntype move struct{ from, to int }\n\nfunc (m move) String() string { return fmt.Sprintf(\"%d→%d\", m.from+1, m.to+1) }\n\nvar cachedMoves = []map[Hexapawn][]move{\n\tblack: make(map[Hexapawn][]move),\n\twhite: make(map[Hexapawn][]move),\n}\n\nfunc possibleMoves(s spot, h Hexapawn) []move {\n\tm := cachedMoves[s][h]\n\tif m != nil {\n\t\treturn m\n\t}\n\t\n\t\n\t\n\tm = make([]move, 0)\n\tfor from := 0; from < Rows*Cols; from++ {\n\t\tfor to := 0; to < Rows*Cols; to++ {\n\t\t\tif err := h.checkMove(s, from, to); err == nil {\n\t\t\t\tm = append(m, move{from, to})\n\t\t\t}\n\t\t}\n\t}\n\tcachedMoves[s][h] = m\n\tvlog.Printf(\"caclulated possible moves for %v\\n%v as %v\\n\", s, h, m)\n\treturn m\n}\n\nfunc (h *Hexapawn) doMove(p spot, from, to int) error {\n\tif err := h.checkMove(p, from, to); err != nil {\n\t\treturn err\n\t}\n\th[from] = empty\n\th[to] = p\n\tif (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) {\n\t\th[stateIdx] = p\n\t} else if len(possibleMoves(p.Other(), *h)) == 0 {\n\t\th[stateIdx] = p\n\t}\n\treturn nil\n}\n\nfunc (h *Hexapawn) checkMove(p spot, from, to int) error {\n\tif h[from] != p {\n\t\treturn fmt.Errorf(\"No %v located at spot %v\", p, from+1)\n\t}\n\tif h[to] == p {\n\t\treturn fmt.Errorf(\"%v already occupies spot %v\", p, to+1)\n\t}\n\tΔr := from/Rows - to/Rows\n\tif (p == white && Δr != -1) || (p == black && Δr != 1) {\n\t\treturn errors.New(\"must move forward one row\")\n\t}\n\tΔc := from%Rows - to%Rows\n\tcapture := h[to] != empty\n\tif (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) {\n\t\treturn errors.New(\"ilegal move\")\n\t}\n\treturn nil\n}\n\ntype Hexapawn [Rows*Cols + 1]spot\n\nfunc New() Hexapawn {\n\t\n\treturn Hexapawn{\n\t\twhite, white, white,\n\t\tempty, empty, empty,\n\t\tblack, black, black,\n\t}\n}\n\nfunc idx(r, c int) int { return r*Cols + c }\n\n\nconst stateIdx = Rows * Cols\n\nfunc (h Hexapawn) String() string {\n\tvar b bytes.Buffer\n\tfor r := Rows - 1; r >= 0; r-- {\n\t\tfor c := 0; c < Cols; c++ {\n\t\t\tb.WriteByte(h[idx(r, c)].Byte())\n\t\t}\n\t\tb.WriteByte('\\n')\n\t}\n\t\n\treturn string(b.Next(Rows*(Cols+1) - 1))\n}\n\ntype spot uint8\n\nconst (\n\tempty spot = iota\n\tblack\n\twhite\n)\n\nfunc (s spot) String() string {\n\tswitch s {\n\tcase black:\n\t\treturn \"Black\"\n\tcase white:\n\t\treturn \"White\"\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Byte() byte {\n\tswitch s {\n\tcase empty:\n\t\treturn '.'\n\tcase black:\n\t\treturn 'B'\n\tcase white:\n\t\treturn 'W'\n\t}\n\tpanic(s)\n}\n\nfunc (s spot) Other() spot {\n\tif s == black {\n\t\treturn white\n\t}\n\treturn black\n}\n"}
{"id": 58558, "name": "Graph colouring", "Python": "import re\nfrom collections import defaultdict\nfrom itertools import count\n\n\nconnection_re = r\n\nclass Graph:\n\n    def __init__(self, name, connections):\n        self.name = name\n        self.connections = connections\n        g = self.graph = defaultdict(list)  \n\n        matches = re.finditer(connection_re, connections,\n                              re.MULTILINE | re.VERBOSE)\n        for match in matches:\n            n1, n2, n = match.groups()\n            if n:\n                g[n] += []\n            else:\n                g[n1].append(n2)    \n                g[n2].append(n1)\n\n    def greedy_colour(self, order=None):\n        \"Greedy colourisation algo.\"\n        if order is None:\n            order = self.graph      \n        colour = self.colour = {}\n        neighbours = self.graph\n        for node in order:\n            used_neighbour_colours = (colour[nbr] for nbr in neighbours[node]\n                                      if nbr in colour)\n            colour[node] = first_avail_int(used_neighbour_colours)\n        self.pp_colours()\n        return colour\n\n    def pp_colours(self):\n        print(f\"\\n{self.name}\")\n        c = self.colour\n        e = canonical_edges = set()\n        for n1, neighbours in sorted(self.graph.items()):\n            if neighbours:\n                for n2 in neighbours:\n                    edge = tuple(sorted([n1, n2]))\n                    if edge not in canonical_edges:\n                        print(f\"       {n1}-{n2}: Colour: {c[n1]}, {c[n2]}\")\n                        canonical_edges.add(edge)\n            else:\n                print(f\"         {n1}: Colour: {c[n1]}\")\n        lc = len(set(c.values()))\n        print(f\"    \n\n\ndef first_avail_int(data):\n    \"return lowest int 0... not in data\"\n    d = set(data)\n    for i in count():\n        if i not in d:\n            return i\n\n\nif __name__ == '__main__':\n    for name, connections in [\n            ('Ex1', \"0-1 1-2 2-0 3\"),\n            ('Ex2', \"1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\"),\n            ('Ex3', \"1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\"),\n            ('Ex4', \"1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\"),\n            ]:\n        g = Graph(name, connections)\n        g.greedy_colour()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype graph struct {\n    nn  int     \n    st  int     \n    nbr [][]int \n}\n\ntype nodeval struct {\n    n int \n    v int \n}\n\nfunc contains(s []int, n int) bool {\n    for _, e := range s {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc newGraph(nn, st int) graph {\n    nbr := make([][]int, nn)\n    return graph{nn, st, nbr}\n}\n\n\nfunc (g graph) addEdge(n1, n2 int) {\n    n1, n2 = n1-g.st, n2-g.st \n    g.nbr[n1] = append(g.nbr[n1], n2)\n    if n1 != n2 {\n        g.nbr[n2] = append(g.nbr[n2], n1)\n    }\n}\n\n\nfunc (g graph) greedyColoring() []int {\n    \n    cols := make([]int, g.nn) \n    for i := 1; i < g.nn; i++ {\n        cols[i] = -1 \n    }\n    \n    available := make([]bool, g.nn) \n    \n    for i := 1; i < g.nn; i++ {\n        \n        for _, j := range g.nbr[i] {\n            if cols[j] != -1 {\n                available[cols[j]] = true\n            }\n        }\n        \n        c := 0\n        for ; c < g.nn; c++ {\n            if !available[c] {\n                break\n            }\n        }\n        cols[i] = c \n        \n        \n        for _, j := range g.nbr[i] {\n            if cols[j] != -1 {\n                available[cols[j]] = false\n            }\n        }\n    }\n    return cols\n}\n\n\nfunc (g graph) wpColoring() []int {\n    \n    nvs := make([]nodeval, g.nn)\n    for i := 0; i < g.nn; i++ {\n        v := len(g.nbr[i])\n        if v == 1 && g.nbr[i][0] == i { \n            v = 0\n        }\n        nvs[i] = nodeval{i, v}\n    }\n    \n    sort.Slice(nvs, func(i, j int) bool {\n        return nvs[i].v > nvs[j].v\n    })\n    \n    cols := make([]int, g.nn)\n    for i := range cols {\n        cols[i] = -1 \n    }\n    currCol := 0 \n    for f := 0; f < g.nn-1; f++ {\n        h := nvs[f].n\n        if cols[h] != -1 { \n            continue\n        }\n        cols[h] = currCol\n        \n        \n    outer:\n        for i := f + 1; i < g.nn; i++ {\n            j := nvs[i].n\n            if cols[j] != -1 { \n                continue\n            }\n            for k := f; k < i; k++ {\n                l := nvs[k].n\n                if cols[l] == -1 { \n                    continue\n                }\n                if contains(g.nbr[j], l) {\n                    continue outer \n                }\n            }\n            cols[j] = currCol\n        }\n        currCol++\n    }\n    return cols\n}\n\nfunc main() {\n    fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring}\n    titles := []string{\"'Greedy'\", \"Welsh-Powell\"}\n    nns := []int{4, 8, 8, 8}\n    starts := []int{0, 1, 1, 1}\n    edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}}\n    edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8},\n        {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}}\n    edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8},\n        {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}}\n    edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8},\n        {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}}\n    for j, fn := range fns {\n        fmt.Println(\"Using the\", titles[j], \"algorithm:\\n\")\n        for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} {\n            fmt.Println(\"  Example\", i+1)\n            g := newGraph(nns[i], starts[i])\n            for _, e := range edges {\n                g.addEdge(e[0], e[1])\n            }\n            cols := fn(g)\n            ecount := 0 \n            for _, e := range edges {\n                if e[0] != e[1] {\n                    fmt.Printf(\"    Edge  %d-%d -> Color %d, %d\\n\", e[0], e[1],\n                        cols[e[0]-g.st], cols[e[1]-g.st])\n                    ecount++\n                } else {\n                    fmt.Printf(\"    Node  %d   -> Color %d\\n\", e[0], cols[e[0]-g.st])\n                }\n            }\n            maxCol := 0 \n            for _, col := range cols {\n                if col > maxCol {\n                    maxCol = col\n                }\n            }\n            fmt.Println(\"    Number of nodes  :\", nns[i])\n            fmt.Println(\"    Number of edges  :\", ecount)\n            fmt.Println(\"    Number of colors :\", maxCol+1)\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 58559, "name": "Sort primes from list to a list", "Python": "print(\"working...\")\nprint(\"Primes are:\")\n\ndef isprime(m):\n    for i in range(2,int(m**0.5)+1):\n        if m%i==0:\n            return False\n    return True\n\nPrimes = [2,43,81,122,63,13,7,95,103]\nTemp = []\n\nfor n in range(len(Primes)):\n\tif isprime(Primes[n]):\n\t\tTemp.append(Primes[n])\n\nTemp.sort()\nprint(Temp)\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103}\n    var primes []int\n    for _, e := range list {\n        if rcu.IsPrime(e) {\n            primes = append(primes, e)\n        }\n    }\n    sort.Ints(primes)\n    fmt.Println(primes)\n}\n"}
{"id": 58560, "name": "Count the coins_0-1", "Python": "from itertools import product, compress\n\nfact = lambda n: n and n*fact(n - 1) or 1\ncombo_count = lambda total, coins, perm:\\\n                    sum(perm and fact(len(x)) or 1\n                        for x in (list(compress(coins, c))\n                                  for c in product(*([(0, 1)]*len(coins))))\n                        if sum(x) == total)\n\ncases = [(6,  [1, 2, 3, 4, 5]),\n         (6,  [1, 1, 2, 3, 3, 4, 5]),\n         (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])]\n\nfor perm in [False, True]:\n    print(f'Order matters: {perm}')\n    for s, c in cases:\n        print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}')\n    print()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar cnt = 0  \nvar cnt2 = 0 \nvar wdth = 0 \n\nfunc factorial(n int) int {\n    prod := 1\n    for i := 2; i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc count(want int, used []int, sum int, have, uindices, rindices []int) {\n    if sum == want {\n        cnt++\n        cnt2 += factorial(len(used))\n        if cnt < 11 {\n            uindicesStr := fmt.Sprintf(\"%v\", uindices)\n            fmt.Printf(\"  indices %*s => used %v\\n\", wdth, uindicesStr, used)\n        }\n    } else if sum < want && len(have) != 0 {\n        thisCoin := have[0]\n        index := rindices[0]\n        rest := have[1:]\n        rindices := rindices[1:]\n        count(want, append(used, thisCoin), sum+thisCoin, rest,\n            append(uindices, index), rindices)\n        count(want, used, sum, rest, uindices, rindices)\n    }\n}\n\nfunc countCoins(want int, coins []int, width int) {\n    fmt.Printf(\"Sum %d from coins %v\\n\", want, coins)\n    cnt = 0\n    cnt2 = 0\n    wdth = -width\n    rindices := make([]int, len(coins))\n    for i := range rindices {\n        rindices[i] = i\n    }\n    count(want, []int{}, 0, coins, []int{}, rindices)\n    if cnt > 10 {\n        fmt.Println(\"  .......\")\n        fmt.Println(\"  (only the first 10 ways generated are shown)\")\n    }\n    fmt.Println(\"Number of ways - order unimportant :\", cnt, \"(as above)\")\n    fmt.Println(\"Number of ways - order important   :\", cnt2, \"(all perms of above indices)\\n\")\n}\n\nfunc main() {\n    countCoins(6, []int{1, 2, 3, 4, 5}, 7)\n    countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9)\n    countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20)\n}\n"}
{"id": 58561, "name": "Count the coins_0-1", "Python": "from itertools import product, compress\n\nfact = lambda n: n and n*fact(n - 1) or 1\ncombo_count = lambda total, coins, perm:\\\n                    sum(perm and fact(len(x)) or 1\n                        for x in (list(compress(coins, c))\n                                  for c in product(*([(0, 1)]*len(coins))))\n                        if sum(x) == total)\n\ncases = [(6,  [1, 2, 3, 4, 5]),\n         (6,  [1, 1, 2, 3, 3, 4, 5]),\n         (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])]\n\nfor perm in [False, True]:\n    print(f'Order matters: {perm}')\n    for s, c in cases:\n        print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}')\n    print()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar cnt = 0  \nvar cnt2 = 0 \nvar wdth = 0 \n\nfunc factorial(n int) int {\n    prod := 1\n    for i := 2; i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc count(want int, used []int, sum int, have, uindices, rindices []int) {\n    if sum == want {\n        cnt++\n        cnt2 += factorial(len(used))\n        if cnt < 11 {\n            uindicesStr := fmt.Sprintf(\"%v\", uindices)\n            fmt.Printf(\"  indices %*s => used %v\\n\", wdth, uindicesStr, used)\n        }\n    } else if sum < want && len(have) != 0 {\n        thisCoin := have[0]\n        index := rindices[0]\n        rest := have[1:]\n        rindices := rindices[1:]\n        count(want, append(used, thisCoin), sum+thisCoin, rest,\n            append(uindices, index), rindices)\n        count(want, used, sum, rest, uindices, rindices)\n    }\n}\n\nfunc countCoins(want int, coins []int, width int) {\n    fmt.Printf(\"Sum %d from coins %v\\n\", want, coins)\n    cnt = 0\n    cnt2 = 0\n    wdth = -width\n    rindices := make([]int, len(coins))\n    for i := range rindices {\n        rindices[i] = i\n    }\n    count(want, []int{}, 0, coins, []int{}, rindices)\n    if cnt > 10 {\n        fmt.Println(\"  .......\")\n        fmt.Println(\"  (only the first 10 ways generated are shown)\")\n    }\n    fmt.Println(\"Number of ways - order unimportant :\", cnt, \"(as above)\")\n    fmt.Println(\"Number of ways - order important   :\", cnt2, \"(all perms of above indices)\\n\")\n}\n\nfunc main() {\n    countCoins(6, []int{1, 2, 3, 4, 5}, 7)\n    countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9)\n    countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20)\n}\n"}
{"id": 58562, "name": "Numerical and alphabetical suffixes", "Python": "from functools import reduce\nfrom operator import mul\nfrom decimal import *\n\ngetcontext().prec = MAX_PREC\n\ndef expand(num):\n    suffixes = [\n        \n        ('greatgross', 7, 12, 3),\n        ('gross', 2, 12, 2),\n        ('dozens', 3, 12, 1),\n        ('pairs', 4, 2, 1),\n        ('scores', 3, 20, 1),\n        ('googols', 6, 10, 100),\n        ('ki', 2, 2, 10),\n        ('mi', 2, 2, 20),\n        ('gi', 2, 2, 30),\n        ('ti', 2, 2, 40),\n        ('pi', 2, 2, 50),\n        ('ei', 2, 2, 60),\n        ('zi', 2, 2, 70),\n        ('yi', 2, 2, 80),\n        ('xi', 2, 2, 90),\n        ('wi', 2, 2, 100),\n        ('vi', 2, 2, 110),\n        ('ui', 2, 2, 120),\n        ('k', 1, 10, 3),\n        ('m', 1, 10, 6),\n        ('g', 1, 10, 9),\n        ('t', 1, 10, 12),\n        ('p', 1, 10, 15),\n        ('e', 1, 10, 18),\n        ('z', 1, 10, 21),\n        ('y', 1, 10, 24),\n        ('x', 1, 10, 27),\n        ('w', 1, 10, 30)\n    ]\n\n    num = num.replace(',', '').strip().lower()\n\n    if num[-1].isdigit():\n        return float(num)\n\n    for i, char in enumerate(reversed(num)):\n        if char.isdigit():\n            input_suffix = num[-i:]\n            num = Decimal(num[:-i])\n            break\n\n    if input_suffix[0] == '!':\n        return reduce(mul, range(int(num), 0, -len(input_suffix)))\n\n    while len(input_suffix) > 0:\n        for suffix, min_abbrev, base, power in suffixes:\n            if input_suffix[:min_abbrev] == suffix[:min_abbrev]:\n                for i in range(min_abbrev, len(input_suffix) + 1):\n                    if input_suffix[:i+1] != suffix[:i+1]:\n                        num *= base ** power\n                        input_suffix = input_suffix[i:]\n                        break\n                break\n\n    return num\n\n\ntest = \"2greatGRo   24Gros  288Doz  1,728pairs  172.8SCOre\\n\\\n        1,567      +1.567k    0.1567e-2m\\n\\\n        25.123kK    25.123m   2.5123e-00002G\\n\\\n        25.123kiKI  25.123Mi  2.5123e-00002Gi  +.25123E-7Ei\\n\\\n        -.25123e-34Vikki      2e-77gooGols\\n\\\n        9!   9!!   9!!!   9!!!!   9!!!!!   9!!!!!!   9!!!!!!!   9!!!!!!!!   9!!!!!!!!!\"\n\nfor test_line in test.split(\"\\n\"):\n    test_cases = test_line.split()\n    print(\"Input:\", ' '.join(test_cases))\n    print(\"Output:\", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype minmult struct {\n    min  int\n    mult float64\n}\n\nvar abbrevs = map[string]minmult{\n    \"PAIRs\": {4, 2}, \"SCOres\": {3, 20}, \"DOZens\": {3, 12},\n    \"GRoss\": {2, 144}, \"GREATGRoss\": {7, 1728}, \"GOOGOLs\": {6, 1e100},\n}\n\nvar metric = map[string]float64{\n    \"K\": 1e3, \"M\": 1e6, \"G\": 1e9, \"T\": 1e12, \"P\": 1e15, \"E\": 1e18,\n    \"Z\": 1e21, \"Y\": 1e24, \"X\": 1e27, \"W\": 1e30, \"V\": 1e33, \"U\": 1e36,\n}\n\nvar binary = map[string]float64{\n    \"Ki\": b(10), \"Mi\": b(20), \"Gi\": b(30), \"Ti\": b(40), \"Pi\": b(50), \"Ei\": b(60),\n    \"Zi\": b(70), \"Yi\": b(80), \"Xi\": b(90), \"Wi\": b(100), \"Vi\": b(110), \"Ui\": b(120),\n}\n\nfunc b(e float64) float64 {\n    return math.Pow(2, e)\n}\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc fact(num string, d int) int {\n    prod := 1\n    n, _ := strconv.Atoi(num)\n    for i := n; i > 0; i -= d {\n        prod *= i\n    }\n    return prod\n}\n\nfunc parse(number string) *big.Float {\n    bf := new(big.Float).SetPrec(500)\n    t1 := new(big.Float).SetPrec(500)\n    t2 := new(big.Float).SetPrec(500)\n    \n    var i int\n    for i = len(number) - 1; i >= 0; i-- {\n        if '0' <= number[i] && number[i] <= '9' {\n            break\n        }\n    }\n    num := number[:i+1]\n    num = strings.Replace(num, \",\", \"\", -1) \n    suf := strings.ToUpper(number[i+1:])\n    if suf == \"\" {\n        bf.SetString(num)\n        return bf\n    }\n    if suf[0] == '!' {\n        prod := fact(num, len(suf))\n        bf.SetInt64(int64(prod))\n        return bf\n    }\n    for k, v := range abbrevs {\n        kk := strings.ToUpper(k)\n        if strings.HasPrefix(kk, suf) && len(suf) >= v.min {\n            t1.SetString(num)\n            if k != \"GOOGOLs\" {\n                t2.SetFloat64(v.mult)\n            } else {\n                t2 = googol() \n            }\n            bf.Mul(t1, t2)\n            return bf\n        }\n    }\n    bf.SetString(num)\n    for k, v := range metric {\n        for j := 0; j < len(suf); j++ {\n            if k == suf[j:j+1] {\n                if j < len(suf)-1 && suf[j+1] == 'I' {\n                    t1.SetFloat64(binary[k+\"i\"])\n                    bf.Mul(bf, t1)\n                    j++\n                } else {\n                    t1.SetFloat64(v)\n                    bf.Mul(bf, t1)\n                }\n            }\n        }\n    }\n    return bf\n}\n\nfunc commatize(s string) string {\n    if len(s) == 0 {\n        return \"\"\n    }\n    neg := s[0] == '-'\n    if neg {\n        s = s[1:]\n    }\n    frac := \"\"\n    if ix := strings.Index(s, \".\"); ix >= 0 {\n        frac = s[ix:]\n        s = s[:ix]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if !neg {\n        return s + frac\n    }\n    return \"-\" + s + frac\n}\n\nfunc process(numbers []string) {\n    fmt.Print(\"numbers =  \")\n    for _, number := range numbers {\n        fmt.Printf(\"%s  \", number)\n    }\n    fmt.Print(\"\\nresults =  \")\n    for _, number := range numbers {\n        res := parse(number)\n        t := res.Text('g', 50)\n        fmt.Printf(\"%s  \", commatize(t))\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    numbers := []string{\"2greatGRo\", \"24Gros\", \"288Doz\", \"1,728pairs\", \"172.8SCOre\"}\n    process(numbers)\n\n    numbers = []string{\"1,567\", \"+1.567k\", \"0.1567e-2m\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kK\", \"25.123m\", \"2.5123e-00002G\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kiKI\", \"25.123Mi\", \"2.5123e-00002Gi\", \"+.25123E-7Ei\"}\n    process(numbers)\n\n    numbers = []string{\"-.25123e-34Vikki\", \"2e-77gooGols\"}\n    process(numbers)\n\n    numbers = []string{\"9!\", \"9!!\", \"9!!!\", \"9!!!!\", \"9!!!!!\", \"9!!!!!!\",\n        \"9!!!!!!!\", \"9!!!!!!!!\", \"9!!!!!!!!!\"}\n    process(numbers)\n}\n"}
{"id": 58563, "name": "Numerical and alphabetical suffixes", "Python": "from functools import reduce\nfrom operator import mul\nfrom decimal import *\n\ngetcontext().prec = MAX_PREC\n\ndef expand(num):\n    suffixes = [\n        \n        ('greatgross', 7, 12, 3),\n        ('gross', 2, 12, 2),\n        ('dozens', 3, 12, 1),\n        ('pairs', 4, 2, 1),\n        ('scores', 3, 20, 1),\n        ('googols', 6, 10, 100),\n        ('ki', 2, 2, 10),\n        ('mi', 2, 2, 20),\n        ('gi', 2, 2, 30),\n        ('ti', 2, 2, 40),\n        ('pi', 2, 2, 50),\n        ('ei', 2, 2, 60),\n        ('zi', 2, 2, 70),\n        ('yi', 2, 2, 80),\n        ('xi', 2, 2, 90),\n        ('wi', 2, 2, 100),\n        ('vi', 2, 2, 110),\n        ('ui', 2, 2, 120),\n        ('k', 1, 10, 3),\n        ('m', 1, 10, 6),\n        ('g', 1, 10, 9),\n        ('t', 1, 10, 12),\n        ('p', 1, 10, 15),\n        ('e', 1, 10, 18),\n        ('z', 1, 10, 21),\n        ('y', 1, 10, 24),\n        ('x', 1, 10, 27),\n        ('w', 1, 10, 30)\n    ]\n\n    num = num.replace(',', '').strip().lower()\n\n    if num[-1].isdigit():\n        return float(num)\n\n    for i, char in enumerate(reversed(num)):\n        if char.isdigit():\n            input_suffix = num[-i:]\n            num = Decimal(num[:-i])\n            break\n\n    if input_suffix[0] == '!':\n        return reduce(mul, range(int(num), 0, -len(input_suffix)))\n\n    while len(input_suffix) > 0:\n        for suffix, min_abbrev, base, power in suffixes:\n            if input_suffix[:min_abbrev] == suffix[:min_abbrev]:\n                for i in range(min_abbrev, len(input_suffix) + 1):\n                    if input_suffix[:i+1] != suffix[:i+1]:\n                        num *= base ** power\n                        input_suffix = input_suffix[i:]\n                        break\n                break\n\n    return num\n\n\ntest = \"2greatGRo   24Gros  288Doz  1,728pairs  172.8SCOre\\n\\\n        1,567      +1.567k    0.1567e-2m\\n\\\n        25.123kK    25.123m   2.5123e-00002G\\n\\\n        25.123kiKI  25.123Mi  2.5123e-00002Gi  +.25123E-7Ei\\n\\\n        -.25123e-34Vikki      2e-77gooGols\\n\\\n        9!   9!!   9!!!   9!!!!   9!!!!!   9!!!!!!   9!!!!!!!   9!!!!!!!!   9!!!!!!!!!\"\n\nfor test_line in test.split(\"\\n\"):\n    test_cases = test_line.split()\n    print(\"Input:\", ' '.join(test_cases))\n    print(\"Output:\", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype minmult struct {\n    min  int\n    mult float64\n}\n\nvar abbrevs = map[string]minmult{\n    \"PAIRs\": {4, 2}, \"SCOres\": {3, 20}, \"DOZens\": {3, 12},\n    \"GRoss\": {2, 144}, \"GREATGRoss\": {7, 1728}, \"GOOGOLs\": {6, 1e100},\n}\n\nvar metric = map[string]float64{\n    \"K\": 1e3, \"M\": 1e6, \"G\": 1e9, \"T\": 1e12, \"P\": 1e15, \"E\": 1e18,\n    \"Z\": 1e21, \"Y\": 1e24, \"X\": 1e27, \"W\": 1e30, \"V\": 1e33, \"U\": 1e36,\n}\n\nvar binary = map[string]float64{\n    \"Ki\": b(10), \"Mi\": b(20), \"Gi\": b(30), \"Ti\": b(40), \"Pi\": b(50), \"Ei\": b(60),\n    \"Zi\": b(70), \"Yi\": b(80), \"Xi\": b(90), \"Wi\": b(100), \"Vi\": b(110), \"Ui\": b(120),\n}\n\nfunc b(e float64) float64 {\n    return math.Pow(2, e)\n}\n\nfunc googol() *big.Float {\n    g1 := new(big.Float).SetPrec(500)\n    g1.SetInt64(10000000000)\n    g := new(big.Float)\n    g.Set(g1)\n    for i := 2; i <= 10; i++ {\n        g.Mul(g, g1)\n    }\n    return g\n}\n\nfunc fact(num string, d int) int {\n    prod := 1\n    n, _ := strconv.Atoi(num)\n    for i := n; i > 0; i -= d {\n        prod *= i\n    }\n    return prod\n}\n\nfunc parse(number string) *big.Float {\n    bf := new(big.Float).SetPrec(500)\n    t1 := new(big.Float).SetPrec(500)\n    t2 := new(big.Float).SetPrec(500)\n    \n    var i int\n    for i = len(number) - 1; i >= 0; i-- {\n        if '0' <= number[i] && number[i] <= '9' {\n            break\n        }\n    }\n    num := number[:i+1]\n    num = strings.Replace(num, \",\", \"\", -1) \n    suf := strings.ToUpper(number[i+1:])\n    if suf == \"\" {\n        bf.SetString(num)\n        return bf\n    }\n    if suf[0] == '!' {\n        prod := fact(num, len(suf))\n        bf.SetInt64(int64(prod))\n        return bf\n    }\n    for k, v := range abbrevs {\n        kk := strings.ToUpper(k)\n        if strings.HasPrefix(kk, suf) && len(suf) >= v.min {\n            t1.SetString(num)\n            if k != \"GOOGOLs\" {\n                t2.SetFloat64(v.mult)\n            } else {\n                t2 = googol() \n            }\n            bf.Mul(t1, t2)\n            return bf\n        }\n    }\n    bf.SetString(num)\n    for k, v := range metric {\n        for j := 0; j < len(suf); j++ {\n            if k == suf[j:j+1] {\n                if j < len(suf)-1 && suf[j+1] == 'I' {\n                    t1.SetFloat64(binary[k+\"i\"])\n                    bf.Mul(bf, t1)\n                    j++\n                } else {\n                    t1.SetFloat64(v)\n                    bf.Mul(bf, t1)\n                }\n            }\n        }\n    }\n    return bf\n}\n\nfunc commatize(s string) string {\n    if len(s) == 0 {\n        return \"\"\n    }\n    neg := s[0] == '-'\n    if neg {\n        s = s[1:]\n    }\n    frac := \"\"\n    if ix := strings.Index(s, \".\"); ix >= 0 {\n        frac = s[ix:]\n        s = s[:ix]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if !neg {\n        return s + frac\n    }\n    return \"-\" + s + frac\n}\n\nfunc process(numbers []string) {\n    fmt.Print(\"numbers =  \")\n    for _, number := range numbers {\n        fmt.Printf(\"%s  \", number)\n    }\n    fmt.Print(\"\\nresults =  \")\n    for _, number := range numbers {\n        res := parse(number)\n        t := res.Text('g', 50)\n        fmt.Printf(\"%s  \", commatize(t))\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    numbers := []string{\"2greatGRo\", \"24Gros\", \"288Doz\", \"1,728pairs\", \"172.8SCOre\"}\n    process(numbers)\n\n    numbers = []string{\"1,567\", \"+1.567k\", \"0.1567e-2m\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kK\", \"25.123m\", \"2.5123e-00002G\"}\n    process(numbers)\n\n    numbers = []string{\"25.123kiKI\", \"25.123Mi\", \"2.5123e-00002Gi\", \"+.25123E-7Ei\"}\n    process(numbers)\n\n    numbers = []string{\"-.25123e-34Vikki\", \"2e-77gooGols\"}\n    process(numbers)\n\n    numbers = []string{\"9!\", \"9!!\", \"9!!!\", \"9!!!!\", \"9!!!!!\", \"9!!!!!!\",\n        \"9!!!!!!!\", \"9!!!!!!!!\", \"9!!!!!!!!!\"}\n    process(numbers)\n}\n"}
{"id": 58564, "name": "Factorial base numbers indexing permutations of a collection", "Python": "\n\nimport math\n\ndef apply_perm(omega,fbn):\n    \n    for m in range(len(fbn)):\n        g = fbn[m]\n        if g > 0:\n            \n            \n            new_first = omega[m+g]\n            \n            omega[m+1:m+g+1] = omega[m:m+g]\n            \n            omega[m] = new_first\n            \n    return omega\n    \ndef int_to_fbn(i):\n    \n    current = i\n    divisor = 2\n    new_fbn = []\n    while current > 0:\n        remainder = current % divisor\n        current = current // divisor\n        new_fbn.append(remainder)\n        divisor += 1\n    \n    return list(reversed(new_fbn))\n    \ndef leading_zeros(l,n):\n   \n   if len(l) < n:\n       return(([0] * (n - len(l))) + l)\n   else:\n       return l\n\ndef get_fbn(n):\n    \n    max = math.factorial(n)\n    \n    for i in range(max):\n        \n        current = i\n        divisor = 1\n        new_fbn = int_to_fbn(i)\n        yield leading_zeros(new_fbn,n-1)\n        \ndef print_write(f, line):\n    \n    print(line)\n    f.write(str(line)+'\\n')     \n    \ndef dot_format(l):\n    \n    \n    if len(l) < 1:\n        return \"\"\n    \n    dot_string = str(l[0])\n    \n    for e in l[1:]:\n        dot_string += \".\"+str(e)\n        \n    return dot_string\n    \ndef str_format(l):\n    \n    if len(l) < 1:\n        return \"\"\n        \n    new_string = \"\"\n        \n    for e in l:\n        new_string += str(e)\n    \n    return new_string \n    \nwith open(\"output.html\", \"w\", encoding=\"utf-8\") as f:\n    f.write(\"<pre>\\n\")\n    \n    \n        \n    omega=[0,1,2,3]\n    \n    four_list = get_fbn(4)\n    \n    for l in four_list:\n        print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l)))\n        \n    print_write(f,\" \")\n    \n    \n    \n    \n    \n    \n        \n    num_permutations = 0\n    \n    for p in get_fbn(11):\n        num_permutations += 1\n        if num_permutations % 1000000 == 0:\n            print_write(f,\"permutations so far = \"+str(num_permutations))\n    \n    print_write(f,\" \")\n    print_write(f,\"Permutations generated = \"+str(num_permutations))\n    print_write(f,\"compared to 11! which  = \"+str(math.factorial(11)))\n    \n    print_write(f,\" \")\n    \n       \n    \n    \n    \n    shoe = []\n    \n    for suit in [u\"\\u2660\",u\"\\u2665\",u\"\\u2666\",u\"\\u2663\"]:\n        for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']:\n            shoe.append(value+suit)\n                    \n    print_write(f,str_format(shoe))\n    \n    p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0]\n    \n    p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1]\n    \n    print_write(f,\" \")\n    print_write(f,dot_format(p1))\n    print_write(f,\" \")\n    print_write(f,str_format(apply_perm(shoe[:],p1)))\n    \n    print_write(f,\" \")\n    print_write(f,dot_format(p2))\n    print_write(f,\" \")\n    print_write(f,str_format(apply_perm(shoe[:],p2)))\n\n    \n    \n    import random\n    \n    max = math.factorial(52)\n    \n    random_int = random.randint(0, max-1)\n\n    myperm = leading_zeros(int_to_fbn(random_int),51)\n    \n    print(len(myperm))\n    \n    print_write(f,\" \")\n    print_write(f,dot_format(myperm))\n    print_write(f,\" \")\n    print_write(f,str_format(apply_perm(shoe[:],myperm)))\n\n    f.write(\"</pre>\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\nfunc genFactBaseNums(size int, countOnly bool) ([][]int, int) {\n    var results [][]int\n    count := 0\n    for n := 0; ; n++ {\n        radix := 2\n        var res []int = nil\n        if !countOnly { \n            res = make([]int, size)\n        }\n        k := n\n        for k > 0 {\n            div := k / radix\n            rem := k % radix\n            if !countOnly {\n                if radix <= size+1 {\n                    res[size-radix+1] = rem\n                }\n            }\n            k = div\n            radix++\n        }\n        if radix > size+2 {\n            break\n        }\n        count++\n        if !countOnly {\n            results = append(results, res)\n        }\n    }\n    return results, count\n}\n\nfunc mapToPerms(factNums [][]int) [][]int {\n    var perms [][]int\n    psize := len(factNums[0]) + 1\n    start := make([]int, psize)\n    for i := 0; i < psize; i++ {\n        start[i] = i\n    }\n    for _, fn := range factNums {\n        perm := make([]int, psize)\n        copy(perm, start)\n        for m := 0; m < len(fn); m++ {\n            g := fn[m]\n            if g == 0 {\n                continue\n            }\n            first := m\n            last := m + g\n            for i := 1; i <= g; i++ {\n                temp := perm[first]\n                for j := first + 1; j <= last; j++ {\n                    perm[j-1] = perm[j]\n                }\n                perm[last] = temp\n            }\n        }\n        perms = append(perms, perm)\n    }\n    return perms\n}\n\nfunc join(is []int, sep string) string {\n    ss := make([]string, len(is))\n    for i := 0; i < len(is); i++ {\n        ss[i] = strconv.Itoa(is[i])\n    }\n    return strings.Join(ss, sep)\n}\n\nfunc undot(s string) []int {\n    ss := strings.Split(s, \".\")\n    is := make([]int, len(ss))\n    for i := 0; i < len(ss); i++ {\n        is[i], _ = strconv.Atoi(ss[i])\n    }\n    return is\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    \n    factNums, _ := genFactBaseNums(3, false)\n    perms := mapToPerms(factNums)\n    for i, fn := range factNums {\n        fmt.Printf(\"%v -> %v\\n\", join(fn, \".\"), join(perms[i], \"\"))\n    }\n\n    \n    _, count := genFactBaseNums(10, true)\n    fmt.Println(\"\\nPermutations generated =\", count)\n    fmt.Println(\"compared to 11! which  =\", factorial(11))\n    fmt.Println()\n\n    \n    fbn51s := []string{\n        \"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\",\n        \"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\",\n    }\n    factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])}\n    perms = mapToPerms(factNums)\n    shoe := []rune(\"A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣\")\n    cards := make([]string, 52)\n    for i := 0; i < 52; i++ {\n        cards[i] = string(shoe[2*i : 2*i+2])\n        if cards[i][0] == 'T' {\n            cards[i] = \"10\" + cards[i][1:]\n        }\n    }\n    for i, fbn51 := range fbn51s {\n        fmt.Println(fbn51)\n        for _, d := range perms[i] {\n            fmt.Print(cards[d])\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    fbn51 := make([]int, 51)\n    for i := 0; i < 51; i++ {\n        fbn51[i] = rand.Intn(52 - i)\n    }\n    fmt.Println(join(fbn51, \".\"))\n    perms = mapToPerms([][]int{fbn51})\n    for _, d := range perms[0] {\n        fmt.Print(cards[d])\n    }\n    fmt.Println()\n}\n"}
{"id": 58565, "name": "Discrete Fourier transform", "Python": "\nimport cmath\n\n\ndef dft( x ):\n    \n    N                           = len( x )\n    result                      = []\n    for k in range( N ):\n        r                       = 0\n        for n in range( N ):\n            t                   = -2j * cmath.pi * k * n / N\n            r                  += x[n] * cmath.exp( t )\n        result.append( r )\n    return result\n\n\ndef idft( y ):\n    \n    N                           = len( y )\n    result                      = []\n    for n in range( N ):\n        r                       = 0\n        for k in range( N ):\n            t                   = 2j * cmath.pi * k * n / N\n            r                  += y[k] * cmath.exp( t )\n        r                      /= N+0j\n        result.append( r )\n    return result\n\n\nif __name__ == \"__main__\":\n    x                           = [ 2, 3, 5, 7, 11 ]\n    print( \"vals:   \" + ' '.join( f\"{f:11.2f}\" for f in x ))\n    y                           = dft( x )\n    print( \"DFT:    \" + ' '.join( f\"{f:11.2f}\" for f in y ))\n    z                           = idft( y )\n    print( \"inverse:\" + ' '.join( f\"{f:11.2f}\" for f in z ))\n    print( \" - real:\" + ' '.join( f\"{f.real:11.2f}\" for f in z ))\n\n    N                           = 8\n    print( f\"Complex signals, 1-4 cycles in {N} samples; energy into successive DFT bins\" )\n    for rot in (0, 1, 2, 3, -4, -3, -2, -1):    \n        if rot > N/2:\n            print( \"Signal change frequency exceeds sample rate and will result in artifacts\")\n        sig                     = [\n            \n            cmath.rect(\n                1, cmath.pi*2*rot/N*i\n            )\n            for i in range( N )\n        ]\n        print( f\"{rot:2} cycle\" + ' '.join( f\"{f:11.2f}\" for f in sig ))\n        dft_sig                 = dft( sig )\n        print( f\"  DFT:  \" + ' '.join( f\"{f:11.2f}\" for f in dft_sig ))\n        print( f\"   ABS: \" + ' '.join( f\"{abs(f):11.2f}\" for f in dft_sig ))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\nfunc dft(x []complex128) []complex128 {\n    N := len(x)\n    y := make([]complex128, N)\n    for k := 0; k < N; k++ {\n        for n := 0; n < N; n++ {\n            t := -1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0)\n            y[k] += x[n] * cmplx.Exp(t)\n        }\n    }\n    return y\n}\n\nfunc idft(y []complex128) []float64 {\n    N := len(y)\n    x := make([]complex128, N)\n    for n := 0; n < N; n++ {\n        for k := 0; k < N; k++ {\n            t := 1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0)\n            x[n] += y[k] * cmplx.Exp(t)\n        }\n        x[n] /= complex(float64(N), 0)\n        \n        if math.Abs(imag(x[n])) < 1e-14 {\n            x[n] = complex(real(x[n]), 0)\n        }\n    }\n    z := make([]float64, N)\n    for i, c := range x {\n        z[i] = float64(real(c))\n    }\n    return z\n}\n\nfunc main() {\n    z := []float64{2, 3, 5, 7, 11}\n    x := make([]complex128, len(z))\n    fmt.Println(\"Original sequence:\", z)\n    for i, n := range z {\n        x[i] = complex(n, 0)\n    }\n    y := dft(x)\n    fmt.Println(\"\\nAfter applying the Discrete Fourier Transform:\")\n    fmt.Printf(\"%0.14g\", y)\n    fmt.Println(\"\\n\\nAfter applying the Inverse Discrete Fourier Transform to the above transform:\")\n    z = idft(y)\n    fmt.Printf(\"%0.14g\", z)\n    fmt.Println()\n}\n"}
{"id": 58566, "name": "Find first missing positive", "Python": "\n\nfrom itertools import count\n\n\n\ndef firstGap(xs):\n    \n    return next(x for x in count(1) if x not in xs)\n\n\n\n\ndef main():\n    \n    print('\\n'.join([\n        f'{repr(xs)} -> {firstGap(xs)}' for xs in [\n            [1, 2, 0],\n            [3, 4, -1, 1],\n            [7, 8, 9, 11, 12]\n        ]\n    ]))\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc firstMissingPositive(a []int) int {\n    var b []int\n    for _, e := range a {\n        if e > 0 {\n            b = append(b, e)\n        }\n    }\n    sort.Ints(b)\n    le := len(b)\n    if le == 0 || b[0] > 1 {\n        return 1\n    }\n    for i := 1; i < le; i++ {\n        if b[i]-b[i-1] > 1 {\n            return b[i-1] + 1\n        }\n    }\n    return b[le-1] + 1\n}\n\nfunc main() {\n    fmt.Println(\"The first missing positive integers for the following arrays are:\\n\")\n    aa := [][]int{\n        {1, 2, 0}, {3, 4, -1, 1}, {7, 8, 9, 11, 12}, {1, 2, 3, 4, 5},\n        {-6, -5, -2, -1}, {5, -5}, {-2}, {1}, {}}\n    for _, a := range aa {\n        fmt.Println(a, \"->\", firstMissingPositive(a))\n    }\n}\n"}
{"id": 58567, "name": "Names to numbers", "Python": "from spell_integer import spell_integer, SMALL, TENS, HUGE\n\ndef int_from_words(num):\n    words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split()\n    if words[0] == 'minus':\n        negmult = -1\n        words.pop(0)\n    else:\n        negmult = 1\n    small, total = 0, 0\n    for word in words:\n        if word in SMALL:\n            small += SMALL.index(word)\n        elif word in TENS:\n            small += TENS.index(word) * 10\n        elif word == 'hundred':\n            small *= 100\n        elif word == 'thousand':\n            total += small * 1000\n            small = 0\n        elif word in HUGE:\n            total += small * 1000 ** HUGE.index(word)\n            small = 0\n        else:\n            raise ValueError(\"Don't understand %r part of %r\" % (word, num))\n    return negmult * (total + small)\n\n\nif __name__ == '__main__':\n    \n    for n in range(-10000, 10000, 17):\n        assert n == int_from_words(spell_integer(n))\n\n    for n in range(20):\n        assert 13**n == int_from_words(spell_integer(13**n))\n    \n    print('\\n\n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        txt = spell_integer(n)\n        num = int_from_words(txt)\n        print('%+4i <%s> %s' % (n, '==' if n == num else '??', txt))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        txt = spell_integer(n)\n        num = int_from_words(txt)\n        print('%12i <%s> %s' % (n, '==' if n == num else '??', txt))\n        n //= -10\n    txt = spell_integer(n)\n    num = int_from_words(txt)\n    print('%12i <%s> %s' % (n, '==' if n == num else '??', txt))\n    print('')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar names = map[string]int64{\n    \"one\":         1,\n    \"two\":         2,\n    \"three\":       3,\n    \"four\":        4,\n    \"five\":        5,\n    \"six\":         6,\n    \"seven\":       7,\n    \"eight\":       8,\n    \"nine\":        9,\n    \"ten\":         10,\n    \"eleven\":      11,\n    \"twelve\":      12,\n    \"thirteen\":    13,\n    \"fourteen\":    14,\n    \"fifteen\":     15,\n    \"sixteen\":     16,\n    \"seventeen\":   17,\n    \"eighteen\":    18,\n    \"nineteen\":    19,\n    \"twenty\":      20,\n    \"thirty\":      30,\n    \"forty\":       40,\n    \"fifty\":       50,\n    \"sixty\":       60,\n    \"seventy\":     70,\n    \"eighty\":      80,\n    \"ninety\":      90,\n    \"hundred\":     100,\n    \"thousand\":    1000,\n    \"million\":     1000000,\n    \"billion\":     1000000000,\n    \"trillion\":    1000000000000,\n    \"quadrillion\": 1000000000000000,\n    \"quintillion\": 1000000000000000000,\n}\n\nvar seps = regexp.MustCompile(`,|-| and | `)\nvar zeros = regexp.MustCompile(`^(zero|nought|nil|none|nothing)$`)\n\nfunc nameToNum(name string) (int64, error) {\n    text := strings.ToLower(strings.TrimSpace(name))\n    isNegative := strings.HasPrefix(text, \"minus \")\n    if isNegative {\n        text = text[6:]\n    }\n    if strings.HasPrefix(text, \"a \") {\n        text = \"one\" + text[1:]\n    }\n    words := seps.Split(text, -1)\n    for i := len(words) - 1; i >= 0; i-- {\n        if words[i] == \"\" {\n            if i < len(words)-1 {\n                copy(words[i:], words[i+1:])\n            }\n            words = words[:len(words)-1]\n        }\n    }\n    size := len(words)\n    if size == 1 && zeros.MatchString(words[0]) {\n        return 0, nil\n    }\n    var multiplier, lastNum, sum int64 = 1, 0, 0\n    for i := size - 1; i >= 0; i-- {\n        num, ok := names[words[i]]\n        if !ok {\n            return 0, fmt.Errorf(\"'%s' is not a valid number\", words[i])\n        } else {\n            switch {\n            case num == lastNum, num >= 1000 && lastNum >= 100:\n                return 0, fmt.Errorf(\"'%s' is not a well formed numeric string\", name)\n            case num >= 1000:\n                multiplier = num\n                if i == 0 {\n                    sum += multiplier\n                }\n            case num >= 100:\n                multiplier *= 100\n                if i == 0 {\n                    sum += multiplier\n                }\n            case num >= 20 && lastNum >= 10 && lastNum <= 90:\n                return 0, fmt.Errorf(\"'%s' is not a well formed numeric string\", name)\n            case num >= 20:\n                sum += num * multiplier\n            case lastNum >= 1 && lastNum <= 90:\n                return 0, fmt.Errorf(\"'%s' is not a well formed numeric string\", name)\n            default:\n                sum += num * multiplier\n            }\n        }\n        lastNum = num\n    }\n\n    if isNegative && sum == -sum {\n        return math.MinInt64, nil\n    }\n    if sum < 0 {\n        return 0, fmt.Errorf(\"'%s' is outside the range of an int64\", name)\n    }\n    if isNegative {\n        return -sum, nil\n    } else {\n        return sum, nil\n    }\n}\n\nfunc main() {\n    names := [...]string{\n        \"none\",\n        \"one\",\n        \"twenty-five\",\n        \"minus one hundred and seventeen\",\n        \"hundred and fifty-six\",\n        \"minus two thousand two\",\n        \"nine thousand, seven hundred, one\",\n        \"minus six hundred and twenty six thousand, eight hundred and fourteen\",\n        \"four million, seven hundred thousand, three hundred and eighty-six\",\n        \"fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four\",\n        \"two hundred and one billion, twenty-one million, two thousand and one\",\n        \"minus three hundred trillion, nine million, four hundred and one thousand and thirty-one\",\n        \"seventeen quadrillion, one hundred thirty-seven\",\n        \"a quintillion, eight trillion and five\",\n        \"minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight\",\n    }\n    for _, name := range names {\n        num, err := nameToNum(name)\n        if err != nil {\n            fmt.Println(err)\n        } else {\n            fmt.Printf(\"%20d = %s\\n\", num, name)\n        }\n    }\n}\n"}
{"id": 58568, "name": "Magic constant", "Python": "\n\ndef a(n):\n    n += 2\n    return n*(n**2 + 1)/2\n \ndef inv_a(x):\n    k = 0\n    while k*(k**2+1)/2+2 < x:\n        k+=1\n    return k\n\n \nif __name__ == '__main__':\n    print(\"The first 20 magic constants are:\");\n    for n in range(1, 20):\n        print(int(a(n)), end = \" \");\n    print(\"\\nThe 1,000th magic constant is:\",int(a(1000)));\n     \n    for e in range(1, 20):\n        print(f'10^{e}: {inv_a(10**e)}');\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc magicConstant(n int) int {\n    return (n*n + 1) * n / 2\n}\n\nvar ss = []string{\n    \"\\u2070\", \"\\u00b9\", \"\\u00b2\", \"\\u00b3\", \"\\u2074\",\n    \"\\u2075\", \"\\u2076\", \"\\u2077\", \"\\u2078\", \"\\u2079\",\n}\n\nfunc superscript(n int) string {\n    if n < 10 {\n        return ss[n]\n    }\n    if n < 20 {\n        return ss[1] + ss[n-10]\n    }\n    return ss[2] + ss[0]\n}\n\nfunc main() {\n    fmt.Println(\"First 20 magic constants:\")\n    for n := 3; n <= 22; n++ {\n        fmt.Printf(\"%5d \", magicConstant(n))\n        if (n-2)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\n1,000th magic constant:\", rcu.Commatize(magicConstant(1002)))\n\n    fmt.Println(\"\\nSmallest order magic square with a constant greater than:\")\n    for i := 1; i <= 20; i++ {\n        goal := math.Pow(10, float64(i))\n        order := int(math.Cbrt(goal*2)) + 1\n        fmt.Printf(\"10%-2s : %9s\\n\", superscript(i), rcu.Commatize(order))\n    }\n}\n"}
{"id": 58569, "name": "Find minimum number of coins that make a given value", "Python": "def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988):\n    print(f\"Available denominations: {denominations}. Total is to be: {total}.\")\n    coins, remaining = sorted(denominations, reverse=True), total\n    for n in range(len(coins)):\n        coinsused, remaining = divmod(remaining, coins[n])\n        if coinsused > 0:\n            print(\"   \", coinsused, \"*\", coins[n])\n\nmakechange()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    denoms := []int{200, 100, 50, 20, 10, 5, 2, 1}\n    coins := 0\n    amount := 988\n    remaining := 988\n    fmt.Println(\"The minimum number of coins needed to make a value of\", amount, \"is as follows:\")\n    for _, denom := range denoms {\n        n := remaining / denom\n        if n > 0 {\n            coins += n\n            fmt.Printf(\"  %3d x %d\\n\", denom, n)\n            remaining %= denom\n            if remaining == 0 {\n                break\n            }\n        }\n    }\n    fmt.Println(\"\\nA total of\", coins, \"coins in all.\")\n}\n"}
{"id": 58570, "name": "Prime numbers which contain 123", "Python": "\n\ndef prime(limite, mostrar):\n    global columna\n    columna = 0\n    \n    for n in range(limite):\n        strn = str(n)\n        if isPrime(n) and ('123' in str(n)):\n            columna += 1                \n            if mostrar == True:\n                print(n, end=\"  \");\n                if columna % 8 == 0:\n                    print('')\n    return columna\n\n\nif __name__ == \"__main__\":\n    print(\"Números primos que contienen 123:\")\n    limite = 100000\n    prime(limite, True)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n    limite = 1000000\n    prime(limite, False)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 100_000\n    primes := rcu.Primes(limit * 10)\n    var results []int\n    for _, p := range primes {\n        if p < 1000 || p > 99999 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            results = append(results, p)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Primes under %s which contain '123' when expressed in decimal:\\n\", climit)\n    for i, p := range results {\n        fmt.Printf(\"%7s \", rcu.Commatize(p))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such primes under\", climit, \"\\b.\")\n\n    limit = 1_000_000\n    climit = rcu.Commatize(limit)\n    count := len(results)\n    for _, p := range primes {\n        if p < 100_000 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            count++\n        }\n    }\n    fmt.Println(\"\\nFound\", count, \"such primes under\", climit, \"\\b.\")\n}\n"}
{"id": 58571, "name": "Prime numbers which contain 123", "Python": "\n\ndef prime(limite, mostrar):\n    global columna\n    columna = 0\n    \n    for n in range(limite):\n        strn = str(n)\n        if isPrime(n) and ('123' in str(n)):\n            columna += 1                \n            if mostrar == True:\n                print(n, end=\"  \");\n                if columna % 8 == 0:\n                    print('')\n    return columna\n\n\nif __name__ == \"__main__\":\n    print(\"Números primos que contienen 123:\")\n    limite = 100000\n    prime(limite, True)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n    limite = 1000000\n    prime(limite, False)\n    print(\"\\n\\nEncontrados \", columna, \" números primos por debajo de\", limite)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strings\"\n)\n\nfunc main() {\n    limit := 100_000\n    primes := rcu.Primes(limit * 10)\n    var results []int\n    for _, p := range primes {\n        if p < 1000 || p > 99999 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            results = append(results, p)\n        }\n    }\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"Primes under %s which contain '123' when expressed in decimal:\\n\", climit)\n    for i, p := range results {\n        fmt.Printf(\"%7s \", rcu.Commatize(p))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such primes under\", climit, \"\\b.\")\n\n    limit = 1_000_000\n    climit = rcu.Commatize(limit)\n    count := len(results)\n    for _, p := range primes {\n        if p < 100_000 {\n            continue\n        }\n        ps := fmt.Sprintf(\"%s\", p)\n        if strings.Contains(ps, \"123\") {\n            count++\n        }\n    }\n    fmt.Println(\"\\nFound\", count, \"such primes under\", climit, \"\\b.\")\n}\n"}
{"id": 58572, "name": "Function frequency", "Python": "import ast\n\nclass CallCountingVisitor(ast.NodeVisitor):\n\n    def __init__(self):\n        self.calls = {}\n\n    def visit_Call(self, node):\n        if isinstance(node.func, ast.Name):\n            fun_name = node.func.id\n            call_count = self.calls.get(fun_name, 0)\n            self.calls[fun_name] = call_count + 1\n        self.generic_visit(node)\n\nfilename = input('Enter a filename to parse: ')\nwith open(filename, encoding='utf-8') as f:\n    contents = f.read()\nroot = ast.parse(contents, filename=filename) \nvisitor = CallCountingVisitor()\nvisitor.visit(root)\ntop10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10]\nfor name, count in top10:\n    print(name,'called',count,'times')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"go/token\"\n    \"io/ioutil\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    if len(os.Args) != 2 {\n        fmt.Println(\"usage ff <go source filename>\")\n        return\n    }\n    src, err := ioutil.ReadFile(os.Args[1])\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fs := token.NewFileSet()\n    a, err := parser.ParseFile(fs, os.Args[1], src, 0)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f := fs.File(a.Pos())\n    m := make(map[string]int)\n    ast.Inspect(a, func(n ast.Node) bool {\n        if ce, ok := n.(*ast.CallExpr); ok {\n            start := f.Offset(ce.Pos())\n            end := f.Offset(ce.Lparen)\n            m[string(src[start:end])]++\n        }\n        return true\n    })\n    cs := make(calls, 0, len(m))\n    for k, v := range m {\n        cs = append(cs, &call{k, v})\n    }\n    sort.Sort(cs)\n    for i, c := range cs {\n        fmt.Printf(\"%-20s %4d\\n\", c.expr, c.count)\n        if i == 9 {\n            break\n        }\n    }\n}\n\ntype call struct {\n    expr  string\n    count int\n}\ntype calls []*call\n\nfunc (c calls) Len() int           { return len(c) }\nfunc (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c calls) Less(i, j int) bool { return c[i].count > c[j].count }\n"}
{"id": 58573, "name": "Price list behind API", "Python": "import random\n\n\nprice_list_size = random.choice(range(99_000, 101_000))\nprice_list = random.choices(range(100_000), k=price_list_size)\n\ndelta_price = 1     \n\n\ndef get_prange_count(startp, endp):\n    return len([r for r in price_list if startp <= r <= endp])\n\ndef get_max_price():\n    return max(price_list)\n\n\ndef get_5k(mn=0, mx=get_max_price(), num=5_000):\n    \"Binary search for num items between mn and mx, adjusting mx\"\n    count = get_prange_count(mn, mx)\n    delta_mx = (mx - mn) / 2\n    while count != num and delta_mx >= delta_price / 2:\n        mx += -delta_mx if count > num else +delta_mx\n        mx = mx // 1    \n        count, delta_mx = get_prange_count(mn, mx), delta_mx / 2\n    return mx, count\n\ndef get_all_5k(mn=0, mx=get_max_price(), num=5_000):\n    \"Get all non-overlapping ranges\"\n    partmax, partcount = get_5k(mn, mx, num)\n    result = [(mn, partmax, partcount)]\n    while partmax < mx:\n        partmin = partmax + delta_price \n        partmax, partcount = get_5k(partmin, mx, num)\n        assert partcount > 0, \\\n            f\"price_list from {partmin} with too many of the same price\"\n        result.append((partmin, partmax, partcount))\n    return result\n\nif __name__ == '__main__':\n    print(f\"Using {price_list_size} random prices from 0 to {get_max_price()}\")\n    result = get_all_5k()\n    print(f\"Splits into {len(result)} bins of approx 5000 elements\")\n    for mn, mx, count in result:\n        print(f\"  From {mn:8.1f} ... {mx:8.1f} with {count} items.\")\n\n    if len(price_list) != sum(count for mn, mx, count in result):\n        print(\"\\nWhoops! Some items missing:\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar minDelta = 1.0\n\nfunc getMaxPrice(prices []float64) float64 {\n    max := prices[0]\n    for i := 1; i < len(prices); i++ {\n        if prices[i] > max {\n            max = prices[i]\n        }\n    }\n    return max\n}\n\nfunc getPRangeCount(prices []float64, min, max float64) int {\n    count := 0\n    for _, price := range prices {\n        if price >= min && price <= max {\n            count++\n        }\n    }\n    return count\n}\n\nfunc get5000(prices []float64, min, max float64, n int) (float64, int) {\n    count := getPRangeCount(prices, min, max)\n    delta := (max - min) / 2\n    for count != n && delta >= minDelta/2 {\n        if count > n {\n            max -= delta\n        } else {\n            max += delta\n        }\n        max = math.Floor(max)\n        count = getPRangeCount(prices, min, max)\n        delta /= 2\n    }\n    return max, count\n}\n\nfunc getAll5000(prices []float64, min, max float64, n int) [][3]float64 {\n    pmax, pcount := get5000(prices, min, max, n)\n    res := [][3]float64{{min, pmax, float64(pcount)}}\n    for pmax < max {\n        pmin := pmax + 1\n        pmax, pcount = get5000(prices, pmin, max, n)\n        if pcount == 0 {\n            log.Fatal(\"Price list from\", pmin, \"has too many with same price.\")\n        }\n        res = append(res, [3]float64{pmin, pmax, float64(pcount)})\n    }\n    return res\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    numPrices := 99000 + rand.Intn(2001)\n    maxPrice := 1e5\n    prices := make([]float64, numPrices) \n    for i := 0; i < numPrices; i++ {\n        prices[i] = float64(rand.Intn(int(maxPrice) + 1))\n    }\n    actualMax := getMaxPrice(prices)\n    fmt.Println(\"Using\", numPrices, \"items with prices from 0 to\", actualMax, \"\\b:\")\n    res := getAll5000(prices, 0, actualMax, 5000)\n    fmt.Println(\"Split into\", len(res), \"bins of approx 5000 elements:\")\n    total := 0\n    for _, r := range res {\n        min := int(r[0])\n        tmx := r[1]\n        if tmx > actualMax {\n            tmx = actualMax\n        }\n        max := int(tmx)\n        cnt := int(r[2])\n        total += cnt\n        fmt.Printf(\"   From %6d to %6d with %4d items\\n\", min, max, cnt)\n    }\n    if total != numPrices {\n        fmt.Println(\"Something went wrong - grand total of\", total, \"doesn't equal\", numPrices, \"\\b!\")\n    }\n}\n"}
{"id": 58574, "name": "Cullen and Woodall numbers", "Python": "print(\"working...\")\nprint(\"First 20 Cullen numbers:\")\n\nfor n in range(1,21):\n    num = n*pow(2,n)+1\n    print(str(num),end= \" \")\n\nprint()\nprint(\"First 20 Woodall numbers:\")\n\nfor n in range(1,21):\n    num = n*pow(2,n)-1\n    print(str(num),end=\" \")\n\nprint()\nprint(\"done...\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n)\n\nfunc cullen(n uint) *big.Int {\n    one := big.NewInt(1)\n    bn := big.NewInt(int64(n))\n    res := new(big.Int).Lsh(one, n)\n    res.Mul(res, bn)\n    return res.Add(res, one)\n}\n\nfunc woodall(n uint) *big.Int {\n    res := cullen(n)\n    return res.Sub(res, big.NewInt(2))\n}\n\nfunc main() {\n    fmt.Println(\"First 20 Cullen numbers (n * 2^n + 1):\")\n    for n := uint(1); n <= 20; n++ {\n        fmt.Printf(\"%d \", cullen(n))\n    }\n\n    fmt.Println(\"\\n\\nFirst 20 Woodall numbers (n * 2^n - 1):\")\n    for n := uint(1); n <= 20; n++ {\n        fmt.Printf(\"%d \", woodall(n))\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 Cullen primes (in terms of n):\")\n    count := 0\n    for n := uint(1); count < 5; n++ {\n        cn := cullen(n)\n        if cn.ProbablyPrime(15) {\n            fmt.Printf(\"%d \", n)\n            count++\n        }\n    }\n\n    fmt.Println(\"\\n\\nFirst 12 Woodall primes (in terms of n):\")\n    count = 0\n    for n := uint(1); count < 12; n++ {\n        cn := woodall(n)\n        if cn.ProbablyPrime(15) {\n            fmt.Printf(\"%d \", n)\n            count++\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58575, "name": "Cyclops numbers", "Python": "from sympy import isprime\n\n\ndef print50(a, width=8):\n    for i, n in enumerate(a):\n        print(f'{n: {width},}', end='\\n' if (i + 1) % 10 == 0 else '')\n\n\ndef generate_cyclops(maxdig=9):\n    yield 0\n    for d in range((maxdig + 1) // 2):\n        arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))]\n        for left in arr:\n            for right in arr:\n                yield int(left + '0' + right)\n\n\ndef generate_prime_cyclops():\n    for c in generate_cyclops():\n        if isprime(c):\n            yield c\n\n\ndef generate_blind_prime_cyclops():\n    for c in generate_prime_cyclops():\n        cstr = str(c)\n        mid = len(cstr) // 2\n        if isprime(int(cstr[:mid] + cstr[mid+1:])):\n            yield c\n\n\ndef generate_palindromic_cyclops(maxdig=9):\n    for d in range((maxdig + 1) // 2):\n        arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))]\n        for s in arr:\n            yield int(s + '0' + s[::-1])\n\n\ndef generate_palindromic_prime_cyclops():\n    for c in generate_palindromic_cyclops():\n        if isprime(c):\n            yield c\n\n\nprint('The first 50 cyclops numbers are:')\ngen = generate_cyclops()\nprint50([next(gen) for _ in range(50)])\nfor i, c in enumerate(generate_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next cyclops number after 10,000,000 is {c} at position {i:,}.')\n        break\n\nprint('\\nThe first 50 prime cyclops numbers are:')\ngen = generate_prime_cyclops()\nprint50([next(gen) for _ in range(50)])\nfor i, c in enumerate(generate_prime_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next prime cyclops number after 10,000,000 is {c} at position {i:,}.')\n        break\n\nprint('\\nThe first 50 blind prime cyclops numbers are:')\ngen = generate_blind_prime_cyclops()\nprint50([next(gen) for _ in range(50)])\nfor i, c in enumerate(generate_blind_prime_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next blind prime cyclops number after 10,000,000 is {c} at position {i:,}.')\n        break\n\nprint('\\nThe first 50 palindromic prime cyclops numbers are:')\ngen = generate_palindromic_prime_cyclops()\nprint50([next(gen) for _ in range(50)], 11)\nfor i, c in enumerate(generate_palindromic_prime_cyclops()):\n    if c > 10000000:\n        print(\n            f'\\nThe next palindromic prime cyclops number after 10,000,000 is {c} at position {i}.')\n        break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc findFirst(list []int) (int, int) {\n    for i, n := range list {\n        if n > 1e7 {\n            return n, i\n        }\n    }\n    return -1, -1\n}\n\nfunc reverse(s string) string {\n    chars := []rune(s)\n    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n        chars[i], chars[j] = chars[j], chars[i]\n    }\n    return string(chars)\n}\n\nfunc main() {\n    ranges := [][2]int{\n        {0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111},\n    }\n    var cyclops []int\n    for _, r := range ranges {\n        numDigits := len(fmt.Sprint(r[0]))\n        center := numDigits / 2\n        for i := r[0]; i <= r[1]; i++ {\n            digits := rcu.Digits(i, 10)\n            if digits[center] == 0 {\n                count := 0\n                for _, d := range digits {\n                    if d == 0 {\n                        count++\n                    }\n                }\n                if count == 1 {\n                    cyclops = append(cyclops, i)\n                }\n            }\n        }\n    }\n    fmt.Println(\"The first 50 cyclops numbers are:\")\n    for i, n := range cyclops[0:50] {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i := findFirst(cyclops)\n    ns, is := rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n\n    var primes []int\n    for _, n := range cyclops {\n        if rcu.IsPrime(n) {\n            primes = append(primes, n)\n        }\n    }\n    fmt.Println(\"\\n\\nThe first 50 prime cyclops numbers are:\")\n    for i, n := range primes[0:50] {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i = findFirst(primes)\n    ns, is = rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n\n    var bpcyclops []int\n    var ppcyclops []int\n    for _, p := range primes {\n        ps := fmt.Sprint(p)\n        split := strings.Split(ps, \"0\")\n        noMiddle, _ := strconv.Atoi(split[0] + split[1])\n        if rcu.IsPrime(noMiddle) {\n            bpcyclops = append(bpcyclops, p)\n        }\n        if ps == reverse(ps) {\n            ppcyclops = append(ppcyclops, p)\n        }\n    }\n\n    fmt.Println(\"\\n\\nThe first 50 blind prime cyclops numbers are:\")\n    for i, n := range bpcyclops[0:50] {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i = findFirst(bpcyclops)\n    ns, is = rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n\n    fmt.Println(\"\\n\\nThe first 50 palindromic prime cyclops numbers are:\\n\")\n    for i, n := range ppcyclops[0:50] {\n        fmt.Printf(\"%9s \", rcu.Commatize(n))\n        if (i+1)%8 == 0 {\n            fmt.Println()\n        }\n    }\n    n, i = findFirst(ppcyclops)\n    ns, is = rcu.Commatize(n), rcu.Commatize(i)\n    fmt.Printf(\"\\n\\nFirst such number > 10 million is %s at zero-based index %s\\n\", ns, is)\n}\n"}
{"id": 58576, "name": "Prime triplets", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    for p in range(3, 5499, 2):\n        if not isPrime(p+6):\n            continue\n        if not isPrime(p+2):\n            continue\n        if not isPrime(p):\n            continue\n        print(f'[{p} {p+2} {p+6}]')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    c := rcu.PrimeSieve(5505, false)\n    var triples [][3]int\n    fmt.Println(\"Prime triplets: p, p + 2, p + 6 where p < 5,500:\")\n    for i := 3; i < 5500; i += 2 {\n        if !c[i] && !c[i+2] && !c[i+6] {\n            triples = append(triples, [3]int{i, i + 2, i + 6})\n        }\n    }\n    for _, triple := range triples {\n        var t [3]string\n        for i := 0; i < 3; i++ {\n            t[i] = rcu.Commatize(triple[i])\n        }\n        fmt.Printf(\"%5s  %5s  %5s\\n\", t[0], t[1], t[2])\n    }\n    fmt.Println(\"\\nFound\", len(triples), \"such prime triplets.\")\n}\n"}
{"id": 58577, "name": "Prime triplets", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    for p in range(3, 5499, 2):\n        if not isPrime(p+6):\n            continue\n        if not isPrime(p+2):\n            continue\n        if not isPrime(p):\n            continue\n        print(f'[{p} {p+2} {p+6}]')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    c := rcu.PrimeSieve(5505, false)\n    var triples [][3]int\n    fmt.Println(\"Prime triplets: p, p + 2, p + 6 where p < 5,500:\")\n    for i := 3; i < 5500; i += 2 {\n        if !c[i] && !c[i+2] && !c[i+6] {\n            triples = append(triples, [3]int{i, i + 2, i + 6})\n        }\n    }\n    for _, triple := range triples {\n        var t [3]string\n        for i := 0; i < 3; i++ {\n            t[i] = rcu.Commatize(triple[i])\n        }\n        fmt.Printf(\"%5s  %5s  %5s\\n\", t[0], t[1], t[2])\n    }\n    fmt.Println(\"\\nFound\", len(triples), \"such prime triplets.\")\n}\n"}
{"id": 58578, "name": "Find Chess960 starting position identifier", "Python": "\ndef validate_position(candidate: str):\n    assert (\n        len(candidate) == 8\n    ), f\"candidate position has invalide len = {len(candidate)}\"\n\n    valid_pieces = {\"R\": 2, \"N\": 2, \"B\": 2, \"Q\": 1, \"K\": 1}\n    assert {\n        piece for piece in candidate\n    } == valid_pieces.keys(), f\"candidate position contains invalid pieces\"\n    for piece_type in valid_pieces.keys():\n        assert (\n            candidate.count(piece_type) == valid_pieces[piece_type]\n        ), f\"piece type '{piece_type}' has invalid count\"\n\n    bishops_pos = [index for index, \n                   value in enumerate(candidate) if value == \"B\"]\n    assert (\n        bishops_pos[0] % 2 != bishops_pos[1] % 2\n    ), f\"candidate position has both bishops in the same color\"\n\n    assert [piece for piece in candidate if piece in \"RK\"] == [\n        \"R\",\n        \"K\",\n        \"R\",\n    ], \"candidate position has K outside of RR\"\n\n\ndef calc_position(start_pos: str):\n    try:\n        validate_position(start_pos)\n    except AssertionError:\n        raise AssertionError\n    \n    subset_step1 = [piece for piece in start_pos if piece not in \"QB\"]\n    nights_positions = [\n        index for index, value in enumerate(subset_step1) if value == \"N\"\n    ]\n    nights_table = {\n        (0, 1): 0,\n        (0, 2): 1,\n        (0, 3): 2,\n        (0, 4): 3,\n        (1, 2): 4,\n        (1, 3): 5,\n        (1, 4): 6,\n        (2, 3): 7,\n        (2, 4): 8,\n        (3, 4): 9,\n    }\n    N = nights_table.get(tuple(nights_positions))\n\n    \n    subset_step2 = [piece for piece in start_pos if piece != \"B\"]\n    Q = subset_step2.index(\"Q\")\n\n    \n    dark_squares = [\n        piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2)\n    ]\n    light_squares = [\n        piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2)\n    ]\n    D = dark_squares.index(\"B\")\n    L = light_squares.index(\"B\")\n\n    return 4 * (4 * (6*N + Q) + D) + L\n\nif __name__ == '__main__':\n    for example in [\"QNRBBNKR\", \"RNBQKBNR\", \"RQNBBKRN\", \"RNQBBKRN\"]:\n        print(f'Position: {example}; Chess960 PID= {calc_position(example)}')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar glyphs = []rune(\"♜♞♝♛♚♖♘♗♕♔\")\nvar names = map[rune]string{'R': \"rook\", 'N': \"knight\", 'B': \"bishop\", 'Q': \"queen\", 'K': \"king\"}\nvar g2lMap = map[rune]string{\n    '♜': \"R\", '♞': \"N\", '♝': \"B\", '♛': \"Q\", '♚': \"K\",\n    '♖': \"R\", '♘': \"N\", '♗': \"B\", '♕': \"Q\", '♔': \"K\",\n}\n\nvar ntable = map[string]int{\"01\": 0, \"02\": 1, \"03\": 2, \"04\": 3, \"12\": 4, \"13\": 5, \"14\": 6, \"23\": 7, \"24\": 8, \"34\": 9}\n\nfunc g2l(pieces string) string {\n    lets := \"\"\n    for _, p := range pieces {\n        lets += g2lMap[p]\n    }\n    return lets\n}\n\nfunc spid(pieces string) int {\n    pieces = g2l(pieces) \n\n    \n    if len(pieces) != 8 {\n        log.Fatal(\"There must be exactly 8 pieces.\")\n    }\n    for _, one := range \"KQ\" {\n        count := 0\n        for _, p := range pieces {\n            if p == one {\n                count++\n            }\n        }\n        if count != 1 {\n            log.Fatalf(\"There must be one %s.\", names[one])\n        }\n    }\n    for _, two := range \"RNB\" {\n        count := 0\n        for _, p := range pieces {\n            if p == two {\n                count++\n            }\n        }\n        if count != 2 {\n            log.Fatalf(\"There must be two %s.\", names[two])\n        }\n    }\n    r1 := strings.Index(pieces, \"R\")\n    r2 := strings.Index(pieces[r1+1:], \"R\") + r1 + 1\n    k := strings.Index(pieces, \"K\")\n    if k < r1 || k > r2 {\n        log.Fatal(\"The king must be between the rooks.\")\n    }\n    b1 := strings.Index(pieces, \"B\")\n    b2 := strings.Index(pieces[b1+1:], \"B\") + b1 + 1\n    if (b2-b1)%2 == 0 {\n        log.Fatal(\"The bishops must be on opposite color squares.\")\n    }\n\n    \n    piecesN := strings.ReplaceAll(pieces, \"Q\", \"\")\n    piecesN = strings.ReplaceAll(piecesN, \"B\", \"\")\n    n1 := strings.Index(piecesN, \"N\")\n    n2 := strings.Index(piecesN[n1+1:], \"N\") + n1 + 1\n    np := fmt.Sprintf(\"%d%d\", n1, n2)\n    N := ntable[np]\n\n    piecesQ := strings.ReplaceAll(pieces, \"B\", \"\")\n    Q := strings.Index(piecesQ, \"Q\")\n\n    D := strings.Index(\"0246\", fmt.Sprintf(\"%d\", b1))\n    L := strings.Index(\"1357\", fmt.Sprintf(\"%d\", b2))\n    if D == -1 {\n        D = strings.Index(\"0246\", fmt.Sprintf(\"%d\", b2))\n        L = strings.Index(\"1357\", fmt.Sprintf(\"%d\", b1))\n    }\n\n    return 96*N + 16*Q + 4*D + L\n}\n\nfunc main() {\n    for _, pieces := range []string{\"♕♘♖♗♗♘♔♖\", \"♖♘♗♕♔♗♘♖\", \"♖♕♘♗♗♔♖♘\", \"♖♘♕♗♗♔♖♘\"} {\n        fmt.Printf(\"%s or %s has SP-ID of %d\\n\", pieces, g2l(pieces), spid(pieces))\n    }\n}\n"}
{"id": 58579, "name": "Conjugate a Latin verb", "Python": "\n\n \ndef conjugate(infinitive): \n    if not infinitive[-3:] == \"are\":\n        print(\"'\", infinitive, \"' non prima coniugatio verbi.\\n\", sep='')\n        return False\n    \n    stem = infinitive[0:-3]\n    if len(stem) == 0:\n        print(\"\\'\", infinitive, \"\\' non satis diu conjugatus\\n\", sep='')\n        return False\n\n    print(\"Praesens indicativi temporis of '\", infinitive, \"':\", sep='') \n    for ending in (\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"):\n        print(\"     \", stem, ending, sep='')\n    print()\n \n \nif __name__ == '__main__':\n    for infinitive in (\"amare\", \"dare\", \"qwerty\", \"are\"):\n        conjugate(infinitive)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nvar endings = [][]string{\n    {\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"},\n    {\"eo\", \"es\", \"et\", \"emus\", \"etis\", \"ent\"},\n    {\"o\", \"is\", \"it\", \"imus\", \"itis\", \"unt\"},\n    {\"io\", \"is\", \"it\", \"imus\", \"itis\", \"iunt\"},\n}\n\nvar infinEndings = []string{\"are\", \"ēre\", \"ere\", \"ire\"}\n\nvar pronouns = []string{\"I\", \"you (singular)\", \"he, she or it\", \"we\", \"you (plural)\", \"they\"}\n\nvar englishEndings = []string{\"\", \"\", \"s\", \"\", \"\", \"\"}\n\nfunc conjugate(infinitive, english string) {\n    letters := []rune(infinitive)\n    le := len(letters)\n    if le < 4 {\n        log.Fatal(\"Infinitive is too short for a regular verb.\")\n    }\n    infinEnding := string(letters[le-3:])\n    conj := -1\n    for i, s := range infinEndings {\n        if s == infinEnding {\n            conj = i\n            break\n        }\n    }\n    if conj == -1 {\n        log.Fatalf(\"Infinitive ending -%s not recognized.\", infinEnding)\n    }\n    stem := string(letters[:le-3])\n    fmt.Printf(\"Present indicative tense, active voice, of '%s' to '%s':\\n\", infinitive, english)\n    for i, ending := range endings[conj] {\n        fmt.Printf(\"    %s%-4s  %s %s%s\\n\", stem, ending, pronouns[i], english, englishEndings[i])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    pairs := [][2]string{{\"amare\", \"love\"}, {\"vidēre\", \"see\"}, {\"ducere\", \"lead\"}, {\"audire\", \"hear\"}}\n    for _, pair := range pairs {\n        conjugate(pair[0], pair[1])\n    }\n}\n"}
{"id": 58580, "name": "Conjugate a Latin verb", "Python": "\n\n \ndef conjugate(infinitive): \n    if not infinitive[-3:] == \"are\":\n        print(\"'\", infinitive, \"' non prima coniugatio verbi.\\n\", sep='')\n        return False\n    \n    stem = infinitive[0:-3]\n    if len(stem) == 0:\n        print(\"\\'\", infinitive, \"\\' non satis diu conjugatus\\n\", sep='')\n        return False\n\n    print(\"Praesens indicativi temporis of '\", infinitive, \"':\", sep='') \n    for ending in (\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"):\n        print(\"     \", stem, ending, sep='')\n    print()\n \n \nif __name__ == '__main__':\n    for infinitive in (\"amare\", \"dare\", \"qwerty\", \"are\"):\n        conjugate(infinitive)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nvar endings = [][]string{\n    {\"o\", \"as\", \"at\", \"amus\", \"atis\", \"ant\"},\n    {\"eo\", \"es\", \"et\", \"emus\", \"etis\", \"ent\"},\n    {\"o\", \"is\", \"it\", \"imus\", \"itis\", \"unt\"},\n    {\"io\", \"is\", \"it\", \"imus\", \"itis\", \"iunt\"},\n}\n\nvar infinEndings = []string{\"are\", \"ēre\", \"ere\", \"ire\"}\n\nvar pronouns = []string{\"I\", \"you (singular)\", \"he, she or it\", \"we\", \"you (plural)\", \"they\"}\n\nvar englishEndings = []string{\"\", \"\", \"s\", \"\", \"\", \"\"}\n\nfunc conjugate(infinitive, english string) {\n    letters := []rune(infinitive)\n    le := len(letters)\n    if le < 4 {\n        log.Fatal(\"Infinitive is too short for a regular verb.\")\n    }\n    infinEnding := string(letters[le-3:])\n    conj := -1\n    for i, s := range infinEndings {\n        if s == infinEnding {\n            conj = i\n            break\n        }\n    }\n    if conj == -1 {\n        log.Fatalf(\"Infinitive ending -%s not recognized.\", infinEnding)\n    }\n    stem := string(letters[:le-3])\n    fmt.Printf(\"Present indicative tense, active voice, of '%s' to '%s':\\n\", infinitive, english)\n    for i, ending := range endings[conj] {\n        fmt.Printf(\"    %s%-4s  %s %s%s\\n\", stem, ending, pronouns[i], english, englishEndings[i])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    pairs := [][2]string{{\"amare\", \"love\"}, {\"vidēre\", \"see\"}, {\"ducere\", \"lead\"}, {\"audire\", \"hear\"}}\n    for _, pair := range pairs {\n        conjugate(pair[0], pair[1])\n    }\n}\n"}
{"id": 58581, "name": "Fortunate numbers", "Python": "from sympy.ntheory.generate import primorial\nfrom sympy.ntheory import isprime\n\ndef fortunate_number(n):\n    \n    \n    \n    i = 3\n    primorial_ = primorial(n)\n    while True:\n        if isprime(primorial_ + i):\n            return i\n        i += 2\n\nfortunate_numbers = set()\nfor i in range(1, 76):\n    fortunate_numbers.add(fortunate_number(i))\n\n\nfirst50 = sorted(list(fortunate_numbers))[:50]\n\nprint('The first 50 fortunate numbers:')\nprint(('{:<3} ' * 10).format(*(first50[:10])))\nprint(('{:<3} ' * 10).format(*(first50[10:20])))\nprint(('{:<3} ' * 10).format(*(first50[20:30])))\nprint(('{:<3} ' * 10).format(*(first50[30:40])))\nprint(('{:<3} ' * 10).format(*(first50[40:])))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    primes := rcu.Primes(379)\n    primorial := big.NewInt(1)\n    var fortunates []int\n    bPrime := new(big.Int)\n    for _, prime := range primes {\n        bPrime.SetUint64(uint64(prime))\n        primorial.Mul(primorial, bPrime)\n        for j := 3; ; j += 2 {\n            jj := big.NewInt(int64(j))\n            bPrime.Add(primorial, jj)\n            if bPrime.ProbablyPrime(5) {\n                fortunates = append(fortunates, j)\n                break\n            }\n        }\n    }\n    m := make(map[int]bool)\n    for _, f := range fortunates {\n        m[f] = true\n    }\n    fortunates = fortunates[:0]\n    for k := range m {\n        fortunates = append(fortunates, k)\n    }\n    sort.Ints(fortunates)\n    fmt.Println(\"After sorting, the first 50 distinct fortunate numbers are:\")\n    for i, f := range fortunates[0:50] {\n        fmt.Printf(\"%3d \", f)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n"}
{"id": 58582, "name": "Sort an outline at every level", "Python": "\n\n\nfrom itertools import chain, product, takewhile, tee\nfrom functools import cmp_to_key, reduce\n\n\n\n\n\n\n\ndef sortedOutline(cmp):\n    \n    def go(outlineText):\n        indentTuples = indentTextPairs(\n            outlineText.splitlines()\n        )\n        return bindLR(\n            minimumIndent(enumerate(indentTuples))\n        )(lambda unitIndent: Right(\n            outlineFromForest(\n                unitIndent,\n                nest(foldTree(\n                    lambda x: lambda xs: Node(x)(\n                        sorted(xs, key=cmp_to_key(cmp))\n                    )\n                )(Node('')(\n                    forestFromIndentLevels(\n                        indentLevelsFromLines(\n                            unitIndent\n                        )(indentTuples)\n                    )\n                )))\n            )\n        ))\n    return go\n\n\n\n\ndef main():\n    \n\n    ascending = comparing(root)\n    descending = flip(ascending)\n\n    spacedOutline = \n\n    tabbedOutline = \n\n    confusedOutline = \n\n    raggedOutline = \n\n    def displaySort(kcmp):\n        \n        k, cmp = kcmp\n        return [\n            tested(cmp, k, label)(\n                outline\n            ) for (label, outline) in [\n                ('4-space indented', spacedOutline),\n                ('tab indented', tabbedOutline),\n                ('Unknown 1', confusedOutline),\n                ('Unknown 2', raggedOutline)\n            ]\n        ]\n\n    def tested(cmp, cmpName, outlineName):\n        \n        def go(outline):\n            print('\\n' + outlineName, cmpName + ':')\n            either(print)(print)(\n                sortedOutline(cmp)(outline)\n            )\n        return go\n\n    \n    ap([\n        displaySort\n    ])([\n        (\"(A -> Z)\", ascending),\n        (\"(Z -> A)\", descending)\n    ])\n\n\n\n\n\ndef forestFromIndentLevels(tuples):\n    \n    def go(xs):\n        if xs:\n            intIndent, v = xs[0]\n            firstTreeLines, rest = span(\n                lambda x: intIndent < x[0]\n            )(xs[1:])\n            return [Node(v)(go(firstTreeLines))] + go(rest)\n        else:\n            return []\n    return go(tuples)\n\n\n\n\ndef indentLevelsFromLines(indentUnit):\n    \n    def go(xs):\n        w = len(indentUnit)\n        return [\n            (len(x[0]) // w, x[1])\n            for x in xs\n        ]\n    return go\n\n\n\ndef indentTextPairs(xs):\n    \n    def indentAndText(s):\n        pfx = list(takewhile(lambda c: c.isspace(), s))\n        return (pfx, s[len(pfx):])\n    return [indentAndText(x) for x in xs]\n\n\n\ndef outlineFromForest(tabString, forest):\n    \n    def go(indent):\n        def serial(node):\n            return [indent + root(node)] + list(\n                concatMap(\n                    go(tabString + indent)\n                )(nest(node))\n            )\n        return serial\n    return '\\n'.join(\n        concatMap(go(''))(forest)\n    )\n\n\n\n\n\n\ndef minimumIndent(indexedPrefixes):\n    \n    (xs, ts) = tee(indexedPrefixes)\n    (ys, zs) = tee(ts)\n\n    def mindentLR(charSet):\n        if list(charSet):\n            def w(x):\n                return len(x[1][0])\n\n            unit = min(filter(w, ys), key=w)[1][0]\n            unitWidth = len(unit)\n\n            def widthCheck(a, ix):\n                \n                wx = len(ix[1][0])\n                return a if (a or 0 == wx) else (\n                    ix[0] if 0 != wx % unitWidth else a\n                )\n            oddLine = reduce(widthCheck, zs, None)\n            return Left(\n                'Inconsistent indentation width at line ' + (\n                    str(1 + oddLine)\n                )\n            ) if oddLine else Right(''.join(unit))\n        else:\n            return Right('')\n\n    def tabSpaceCheck(a, ics):\n        \n        charSet = a[0].union(set(ics[1][0]))\n        return a if a[1] else (\n            charSet, ics[0] if 1 < len(charSet) else None\n        )\n\n    indentCharSet, mbAnomalyLine = reduce(\n        tabSpaceCheck, xs, (set([]), None)\n    )\n    return bindLR(\n        Left(\n            'Mixed indent characters found in line ' + str(\n                1 + mbAnomalyLine\n            )\n        ) if mbAnomalyLine else Right(list(indentCharSet))\n    )(mindentLR)\n\n\n\n\n\ndef Left(x):\n    \n    return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n\ndef Right(x):\n    \n    return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n\ndef Node(v):\n    \n    return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}\n\n\n\ndef ap(fs):\n    \n    def go(xs):\n        return [\n            f(x) for (f, x)\n            in product(fs, xs)\n        ]\n    return go\n\n\n\ndef bindLR(m):\n    \n    def go(mf):\n        return (\n            mf(m.get('Right')) if None is m.get('Left') else m\n        )\n    return go\n\n\n\ndef comparing(f):\n    \n    def go(x, y):\n        fx = f(x)\n        fy = f(y)\n        return -1 if fx < fy else (1 if fx > fy else 0)\n    return go\n\n\n\ndef concatMap(f):\n    \n    def go(xs):\n        return chain.from_iterable(map(f, xs))\n    return go\n\n\n\ndef either(fl):\n    \n    return lambda fr: lambda e: fl(e['Left']) if (\n        None is e['Right']\n    ) else fr(e['Right'])\n\n\n\ndef flip(f):\n    \n    return lambda a, b: f(b, a)\n\n\n\ndef foldTree(f):\n    \n    def go(node):\n        return f(root(node))([\n            go(x) for x in nest(node)\n        ])\n    return go\n\n\n\ndef nest(t):\n    \n    return t.get('nest')\n\n\n\ndef root(t):\n    \n    return t.get('root')\n\n\n\ndef span(p):\n    \n    def match(ab):\n        b = ab[1]\n        return not b or not p(b[0])\n\n    def f(ab):\n        a, b = ab\n        return a + [b[0]], b[1:]\n\n    def go(xs):\n        return until(match)(f)(([], xs))\n    return go\n\n\n\ndef until(p):\n    \n    def go(f):\n        def g(x):\n            v = x\n            while not p(v):\n                v = f(v)\n            return v\n        return g\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc sortedOutline(originalOutline []string, ascending bool) {\n    outline := make([]string, len(originalOutline))\n    copy(outline, originalOutline) \n    indent := \"\"\n    del := \"\\x7f\"\n    sep := \"\\x00\"\n    var messages []string\n    if strings.TrimLeft(outline[0], \" \\t\") != outline[0] {\n        fmt.Println(\"    outline structure is unclear\")\n        return\n    }\n    for i := 1; i < len(outline); i++ {\n        line := outline[i]\n        lc := len(line)\n        if strings.HasPrefix(line, \"  \") || strings.HasPrefix(line, \" \\t\") || line[0] == '\\t' {\n            lc2 := len(strings.TrimLeft(line, \" \\t\"))\n            currIndent := line[0 : lc-lc2]\n            if indent == \"\" {\n                indent = currIndent\n            } else {\n                correctionNeeded := false\n                if (strings.ContainsRune(currIndent, '\\t') && !strings.ContainsRune(indent, '\\t')) ||\n                    (!strings.ContainsRune(currIndent, '\\t') && strings.ContainsRune(indent, '\\t')) {\n                    m := fmt.Sprintf(\"corrected inconsistent whitespace use at line %q\", line)\n                    messages = append(messages, indent+m)\n                    correctionNeeded = true\n                } else if len(currIndent)%len(indent) != 0 {\n                    m := fmt.Sprintf(\"corrected inconsistent indent width at line %q\", line)\n                    messages = append(messages, indent+m)\n                    correctionNeeded = true\n                }\n                if correctionNeeded {\n                    mult := int(math.Round(float64(len(currIndent)) / float64(len(indent))))\n                    outline[i] = strings.Repeat(indent, mult) + line[lc-lc2:]\n                }\n            }\n        }\n    }\n    levels := make([]int, len(outline))\n    levels[0] = 1\n    margin := \"\"\n    for level := 1; ; level++ {\n        allPos := true\n        for i := 1; i < len(levels); i++ {\n            if levels[i] == 0 {\n                allPos = false\n                break\n            }\n        }\n        if allPos {\n            break\n        }\n        mc := len(margin)\n        for i := 1; i < len(outline); i++ {\n            if levels[i] == 0 {\n                line := outline[i]\n                if strings.HasPrefix(line, margin) && line[mc] != ' ' && line[mc] != '\\t' {\n                    levels[i] = level\n                }\n            }\n        }\n        margin += indent\n    }\n    lines := make([]string, len(outline))\n    lines[0] = outline[0]\n    var nodes []string\n    for i := 1; i < len(outline); i++ {\n        if levels[i] > levels[i-1] {\n            if len(nodes) == 0 {\n                nodes = append(nodes, outline[i-1])\n            } else {\n                nodes = append(nodes, sep+outline[i-1])\n            }\n        } else if levels[i] < levels[i-1] {\n            j := levels[i-1] - levels[i]\n            nodes = nodes[0 : len(nodes)-j]\n        }\n        if len(nodes) > 0 {\n            lines[i] = strings.Join(nodes, \"\") + sep + outline[i]\n        } else {\n            lines[i] = outline[i]\n        }\n    }\n    if ascending {\n        sort.Strings(lines)\n    } else {\n        maxLen := len(lines[0])\n        for i := 1; i < len(lines); i++ {\n            if len(lines[i]) > maxLen {\n                maxLen = len(lines[i])\n            }\n        }\n        for i := 0; i < len(lines); i++ {\n            lines[i] = lines[i] + strings.Repeat(del, maxLen-len(lines[i]))\n        }\n        sort.Sort(sort.Reverse(sort.StringSlice(lines)))\n    }\n    for i := 0; i < len(lines); i++ {\n        s := strings.Split(lines[i], sep)\n        lines[i] = s[len(s)-1]\n        if !ascending {\n            lines[i] = strings.TrimRight(lines[i], del)\n        }\n    }\n    if len(messages) > 0 {\n        fmt.Println(strings.Join(messages, \"\\n\"))\n        fmt.Println()\n    }\n    fmt.Println(strings.Join(lines, \"\\n\"))\n}\n\nfunc main() {\n    outline := []string{\n        \"zeta\",\n        \"    beta\",\n        \"    gamma\",\n        \"        lambda\",\n        \"        kappa\",\n        \"        mu\",\n        \"    delta\",\n        \"alpha\",\n        \"    theta\",\n        \"    iota\",\n        \"    epsilon\",\n    }\n\n    outline2 := make([]string, len(outline))\n    for i := 0; i < len(outline); i++ {\n        outline2[i] = strings.ReplaceAll(outline[i], \"    \", \"\\t\")\n    }\n\n    outline3 := []string{\n        \"alpha\",\n        \"    epsilon\",\n        \"        iota\",\n        \"    theta\",\n        \"zeta\",\n        \"    beta\",\n        \"    delta\",\n        \"    gamma\",\n        \"    \\t   kappa\", \n        \"        lambda\",\n        \"        mu\",\n    }\n\n    outline4 := []string{\n        \"zeta\",\n        \"    beta\",\n        \"   gamma\",\n        \"        lambda\",\n        \"         kappa\",\n        \"        mu\",\n        \"    delta\",\n        \"alpha\",\n        \"    theta\",\n        \"    iota\",\n        \"    epsilon\",\n    }\n\n    fmt.Println(\"Four space indented outline, ascending sort:\")\n    sortedOutline(outline, true)\n\n    fmt.Println(\"\\nFour space indented outline, descending sort:\")\n    sortedOutline(outline, false)\n\n    fmt.Println(\"\\nTab indented outline, ascending sort:\")\n    sortedOutline(outline2, true)\n\n    fmt.Println(\"\\nTab indented outline, descending sort:\")\n    sortedOutline(outline2, false)\n\n    fmt.Println(\"\\nFirst unspecified outline, ascending sort:\")\n    sortedOutline(outline3, true)\n\n    fmt.Println(\"\\nFirst unspecified outline, descending sort:\")\n    sortedOutline(outline3, false)\n\n    fmt.Println(\"\\nSecond unspecified outline, ascending sort:\")\n    sortedOutline(outline4, true)\n\n    fmt.Println(\"\\nSecond unspecified outline, descending sort:\")\n    sortedOutline(outline4, false)\n}\n"}
{"id": 58583, "name": "Smallest multiple", "Python": "\n\nfrom math import gcd\nfrom functools import reduce\n\n\ndef lcm(a, b):\n    \n    return 0 if 0 == a or 0 == b else (\n        abs(a * b) // gcd(a, b)\n    )\n\n\nfor i in [10, 20, 200, 2000]:\n    print(str(i) + ':', reduce(lcm, range(1, i + 1)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n)\n\nfunc lcm(n int) *big.Int {\n    lcm := big.NewInt(1)\n    t := new(big.Int)\n    for _, p := range rcu.Primes(n) {\n        f := p\n        for f*p <= n {\n            f *= p\n        }\n        lcm.Mul(lcm, t.SetUint64(uint64(f)))\n    }\n    return lcm\n}\n\nfunc main() {\n    fmt.Println(\"The LCMs of the numbers 1 to N inclusive is:\")\n    for _, i := range []int{10, 20, 200, 2000} {\n        fmt.Printf(\"%4d: %s\\n\", i, lcm(i))\n    }\n}\n"}
{"id": 58584, "name": "Meissel–Mertens constant", "Python": "\n\nfrom math import log\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    Euler = 0.57721566490153286\n    m = 0\n    for x in range(2, 10_000_000):\n        if isPrime(x):\n            m += log(1-(1/x)) + (1/x)\n\n    print(\"MM =\", Euler + m)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc contains(a []int, f int) bool {\n    for _, e := range a {\n        if e == f {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const euler = 0.57721566490153286\n    primes := rcu.Primes(1 << 31)\n    pc := len(primes)\n    sum := 0.0\n    fmt.Println(\"Primes added         M\")\n    fmt.Println(\"------------  --------------\")\n    for i, p := range primes {\n        rp := 1.0 / float64(p)\n        sum += math.Log(1.0-rp) + rp\n        c := i + 1\n        if (c%1e7) == 0 || c == pc {\n            fmt.Printf(\"%11s   %0.12f\\n\", rcu.Commatize(c), sum+euler)\n        }\n    }\n}\n"}
{"id": 58585, "name": "Unicode strings", "Python": "\n\n\nu = 'abcdé'\nprint(ord(u[-1]))\n", "Go": "    var i int\n    var u rune\n    for i, u = range \"voilà\" {\n        fmt.Println(i, u)\n    }\n"}
{"id": 58586, "name": "Quadrat special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 2\n    j = 1\n    print(2, end = \" \");\n    while True:\n        while True:\n            if isPrime(p + j*j):\n                break\n            j += 1\n        p += j*j\n        if p > 16000:\n            break\n        print(p, end = \" \");\n        j = 1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc commas(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(15999)\n    fmt.Println(\"Quadrat special primes under 16,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Sqrt\")\n    lastQuadSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 16000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastQuadSpecial\n        if isSquare(gap) {\n            sqrt := int(math.Sqrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastQuadSpecial), commas(i), commas(gap), sqrt)\n            lastQuadSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n"}
{"id": 58587, "name": "Quadrat special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    p = 2\n    j = 1\n    print(2, end = \" \");\n    while True:\n        while True:\n            if isPrime(p + j*j):\n                break\n            j += 1\n        p += j*j\n        if p > 16000:\n            break\n        print(p, end = \" \");\n        j = 1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isSquare(n int) bool {\n    s := int(math.Sqrt(float64(n)))\n    return s*s == n\n}\n\nfunc commas(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(15999)\n    fmt.Println(\"Quadrat special primes under 16,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Sqrt\")\n    lastQuadSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 16000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastQuadSpecial\n        if isSquare(gap) {\n            sqrt := int(math.Sqrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastQuadSpecial), commas(i), commas(gap), sqrt)\n            lastQuadSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n"}
{"id": 58588, "name": "Bioinformatics_Global alignment", "Python": "import os\n\nfrom collections import Counter\nfrom functools import reduce\nfrom itertools import permutations\n\nBASES = (\"A\", \"C\", \"G\", \"T\")\n\n\ndef deduplicate(sequences):\n    \n    sequences = set(sequences)\n    duplicates = set()\n\n    for s, t in permutations(sequences, 2):\n        if s != t and s in t:\n            duplicates.add(s)\n\n    return sequences - duplicates\n\n\ndef smash(s, t):\n    \n    for i in range(len(s)):\n        if t.startswith(s[i:]):\n            return s[:i] + t\n    return s + t\n\n\ndef shortest_superstring(sequences):\n    \n    sequences = deduplicate(sequences)\n    shortest = \"\".join(sequences)\n\n    for perm in permutations(sequences):\n        superstring = reduce(smash, perm)\n        if len(superstring) < len(shortest):\n            shortest = superstring\n\n    return shortest\n\n\ndef shortest_superstrings(sequences):\n    \n    sequences = deduplicate(sequences)\n\n    shortest = set([\"\".join(sequences)])\n    shortest_length = sum(len(s) for s in sequences)\n\n    for perm in permutations(sequences):\n        superstring = reduce(smash, perm)\n        superstring_length = len(superstring)\n        if superstring_length < shortest_length:\n            shortest.clear()\n            shortest.add(superstring)\n            shortest_length = superstring_length\n        elif superstring_length == shortest_length:\n            shortest.add(superstring)\n\n    return shortest\n\n\ndef print_report(sequence):\n    \n    buf = [f\"Nucleotide counts for {sequence}:\\n\"]\n\n    counts = Counter(sequence)\n    for base in BASES:\n        buf.append(f\"{base:>10}{counts.get(base, 0):>12}\")\n\n    other = sum(v for k, v in counts.items() if k not in BASES)\n    buf.append(f\"{'Other':>10}{other:>12}\")\n\n    buf.append(\" \" * 5 + \"_\" * 17)\n    buf.append(f\"{'Total length':>17}{sum(counts.values()):>5}\")\n\n    print(os.linesep.join(buf), \"\\n\")\n\n\nif __name__ == \"__main__\":\n    test_cases = [\n        (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"),\n        (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"),\n        (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"),\n        (\n            \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n            \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n            \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n            \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n            \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n            \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n        ),\n    ]\n\n    for case in test_cases:\n        for superstring in shortest_superstrings(case):\n            print_report(superstring)\n\n    \n    \n    \n    \n    \n    \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\n\nfunc factorial(n int) int {\n    fact := 1\n    for i := 2; i <= n; i++ {\n        fact *= i\n    }\n    return fact\n}\n\n\nfunc getPerms(input []string) [][]string {\n    perms := [][]string{input}\n    le := len(input)\n    a := make([]string, le)\n    copy(a, input)\n    n := le - 1\n    fact := factorial(n + 1)\n\n    for c := 1; c < fact; c++ {\n        i := n - 1\n        j := n\n        for i >= 0 && a[i] > a[i+1] {\n            i--\n        }\n        if i == -1 {\n            i = n\n        }\n        for a[j] < a[i] {\n            j--\n        }\n        a[i], a[j] = a[j], a[i]\n        j = n\n        i++\n        if i == n+1 {\n            i = 0\n        }\n        for i < j {\n            a[i], a[j] = a[j], a[i]\n            i++\n            j--\n        }\n        b := make([]string, le)\n        copy(b, a)\n        perms = append(perms, b)\n    }\n    return perms\n}\n\n\nfunc distinct(slist []string) []string {\n    distinctSet := make(map[string]int, len(slist))\n    i := 0\n    for _, s := range slist {\n        if _, ok := distinctSet[s]; !ok {\n            distinctSet[s] = i\n            i++\n        }\n    }\n    result := make([]string, len(distinctSet))\n    for s, i := range distinctSet {\n        result[i] = s\n    }\n    return result\n}\n\n\nfunc printCounts(seq string) {\n    bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}}\n    for _, c := range seq {\n        for _, base := range bases {\n            if c == base[0] {\n                base[1]++\n            }\n        }\n    }\n    sum := 0\n    fmt.Println(\"\\nNucleotide counts for\", seq, \"\\b:\\n\")\n    for _, base := range bases {\n        fmt.Printf(\"%10c%12d\\n\", base[0], base[1])\n        sum += int(base[1])\n    }\n    le := len(seq)\n    fmt.Printf(\"%10s%12d\\n\", \"Other\", le-sum)\n    fmt.Printf(\"  ____________________\\n%14s%8d\\n\", \"Total length\", le)\n}\n\n\nfunc headTailOverlap(s1, s2 string) int {\n    for start := 0; ; start++ {\n        ix := strings.IndexByte(s1[start:], s2[0])\n        if ix == -1 {\n            return 0\n        } else {\n            start += ix\n        }\n        if strings.HasPrefix(s2, s1[start:]) {\n            return len(s1) - start\n        }\n    }\n}\n\n\nfunc deduplicate(slist []string) []string {\n    var filtered []string\n    arr := distinct(slist)\n    for i, s1 := range arr {\n        withinLarger := false\n        for j, s2 := range arr {\n            if j != i && strings.Contains(s2, s1) {\n                withinLarger = true\n                break\n            }\n        }\n        if !withinLarger {\n            filtered = append(filtered, s1)\n        }\n    }\n    return filtered\n}\n\n\nfunc shortestCommonSuperstring(slist []string) string {\n    ss := deduplicate(slist)\n    shortestSuper := strings.Join(ss, \"\")\n    for _, perm := range getPerms(ss) {\n        sup := perm[0]\n        for i := 0; i < len(ss)-1; i++ {\n            overlapPos := headTailOverlap(perm[i], perm[i+1])\n            sup += perm[i+1][overlapPos:]\n        }\n        if len(sup) < len(shortestSuper) {\n            shortestSuper = sup\n        }\n    }\n    return shortestSuper\n}\n\nfunc main() {\n    testSequences := [][]string{\n        {\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"},\n        {\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"},\n        {\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"},\n        {\n            \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n            \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n            \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n            \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n            \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n            \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n            \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n            \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n            \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n        },\n    }\n\n    for _, test := range testSequences {\n        scs := shortestCommonSuperstring(test)\n        printCounts(scs)\n    }\n}\n"}
{"id": 58589, "name": "Strassen's algorithm", "Python": "\n\nfrom __future__ import annotations\nfrom itertools import chain\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\n\n\nclass Shape(NamedTuple):\n    rows: int\n    cols: int\n\n\nclass Matrix(List):\n    \n\n    @classmethod\n    def block(cls, blocks) -> Matrix:\n        \n        m = Matrix()\n        for hblock in blocks:\n            for row in zip(*hblock):\n                m.append(list(chain.from_iterable(row)))\n\n        return m\n\n    def dot(self, b: Matrix) -> Matrix:\n        \n        assert self.shape.cols == b.shape.rows\n        m = Matrix()\n        for row in self:\n            new_row = []\n            for c in range(len(b[0])):\n                col = [b[r][c] for r in range(len(b))]\n                new_row.append(sum(x * y for x, y in zip(row, col)))\n            m.append(new_row)\n        return m\n\n    def __matmul__(self, b: Matrix) -> Matrix:\n        return self.dot(b)\n\n    def __add__(self, b: Matrix) -> Matrix:\n        \n        assert self.shape == b.shape\n        rows, cols = self.shape\n        return Matrix(\n            [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]\n        )\n\n    def __sub__(self, b: Matrix) -> Matrix:\n        \n        assert self.shape == b.shape\n        rows, cols = self.shape\n        return Matrix(\n            [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)]\n        )\n\n    def strassen(self, b: Matrix) -> Matrix:\n        \n        rows, cols = self.shape\n\n        assert rows == cols, \"matrices must be square\"\n        assert self.shape == b.shape, \"matrices must be the same shape\"\n        assert rows and (rows & rows - 1) == 0, \"shape must be a power of 2\"\n\n        if rows == 1:\n            return self.dot(b)\n\n        p = rows // 2  \n\n        a11 = Matrix([n[:p] for n in self[:p]])\n        a12 = Matrix([n[p:] for n in self[:p]])\n        a21 = Matrix([n[:p] for n in self[p:]])\n        a22 = Matrix([n[p:] for n in self[p:]])\n\n        b11 = Matrix([n[:p] for n in b[:p]])\n        b12 = Matrix([n[p:] for n in b[:p]])\n        b21 = Matrix([n[:p] for n in b[p:]])\n        b22 = Matrix([n[p:] for n in b[p:]])\n\n        m1 = (a11 + a22).strassen(b11 + b22)\n        m2 = (a21 + a22).strassen(b11)\n        m3 = a11.strassen(b12 - b22)\n        m4 = a22.strassen(b21 - b11)\n        m5 = (a11 + a12).strassen(b22)\n        m6 = (a21 - a11).strassen(b11 + b12)\n        m7 = (a12 - a22).strassen(b21 + b22)\n\n        c11 = m1 + m4 - m5 + m7\n        c12 = m3 + m5\n        c21 = m2 + m4\n        c22 = m1 - m2 + m3 + m6\n\n        return Matrix.block([[c11, c12], [c21, c22]])\n\n    def round(self, ndigits: Optional[int] = None) -> Matrix:\n        return Matrix([[round(i, ndigits) for i in row] for row in self])\n\n    @property\n    def shape(self) -> Shape:\n        cols = len(self[0]) if self else 0\n        return Shape(len(self), cols)\n\n\ndef examples():\n    a = Matrix(\n        [\n            [1, 2],\n            [3, 4],\n        ]\n    )\n    b = Matrix(\n        [\n            [5, 6],\n            [7, 8],\n        ]\n    )\n    c = Matrix(\n        [\n            [1, 1, 1, 1],\n            [2, 4, 8, 16],\n            [3, 9, 27, 81],\n            [4, 16, 64, 256],\n        ]\n    )\n    d = Matrix(\n        [\n            [4, -3, 4 / 3, -1 / 4],\n            [-13 / 3, 19 / 4, -7 / 3, 11 / 24],\n            [3 / 2, -2, 7 / 6, -1 / 4],\n            [-1 / 6, 1 / 4, -1 / 6, 1 / 24],\n        ]\n    )\n    e = Matrix(\n        [\n            [1, 2, 3, 4],\n            [5, 6, 7, 8],\n            [9, 10, 11, 12],\n            [13, 14, 15, 16],\n        ]\n    )\n    f = Matrix(\n        [\n            [1, 0, 0, 0],\n            [0, 1, 0, 0],\n            [0, 0, 1, 0],\n            [0, 0, 0, 1],\n        ]\n    )\n\n    print(\"Naive matrix multiplication:\")\n    print(f\"  a * b = {a @ b}\")\n    print(f\"  c * d = {(c @ d).round()}\")\n    print(f\"  e * f = {e @ f}\")\n\n    print(\"Strassen's matrix multiplication:\")\n    print(f\"  a * b = {a.strassen(b)}\")\n    print(f\"  c * d = {c.strassen(d).round()}\")\n    print(f\"  e * f = {e.strassen(f)}\")\n\n\nif __name__ == \"__main__\":\n    examples()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\ntype Matrix [][]float64\n\nfunc (m Matrix) rows() int { return len(m) }\nfunc (m Matrix) cols() int { return len(m[0]) }\n\nfunc (m Matrix) add(m2 Matrix) Matrix {\n    if m.rows() != m2.rows() || m.cols() != m2.cols() {\n        log.Fatal(\"Matrices must have the same dimensions.\")\n    }\n    c := make(Matrix, m.rows())\n    for i := 0; i < m.rows(); i++ {\n        c[i] = make([]float64, m.cols())\n        for j := 0; j < m.cols(); j++ {\n            c[i][j] = m[i][j] + m2[i][j]\n        }\n    }\n    return c\n}\n\nfunc (m Matrix) sub(m2 Matrix) Matrix {\n    if m.rows() != m2.rows() || m.cols() != m2.cols() {\n        log.Fatal(\"Matrices must have the same dimensions.\")\n    }\n    c := make(Matrix, m.rows())\n    for i := 0; i < m.rows(); i++ {\n        c[i] = make([]float64, m.cols())\n        for j := 0; j < m.cols(); j++ {\n            c[i][j] = m[i][j] - m2[i][j]\n        }\n    }\n    return c\n}\n\nfunc (m Matrix) mul(m2 Matrix) Matrix {\n    if m.cols() != m2.rows() {\n        log.Fatal(\"Cannot multiply these matrices.\")\n    }\n    c := make(Matrix, m.rows())\n    for i := 0; i < m.rows(); i++ {\n        c[i] = make([]float64, m2.cols())\n        for j := 0; j < m2.cols(); j++ {\n            for k := 0; k < m2.rows(); k++ {\n                c[i][j] += m[i][k] * m2[k][j]\n            }\n        }\n    }\n    return c\n}\n\nfunc (m Matrix) toString(p int) string {\n    s := make([]string, m.rows())\n    pow := math.Pow(10, float64(p))\n    for i := 0; i < m.rows(); i++ {\n        t := make([]string, m.cols())\n        for j := 0; j < m.cols(); j++ {\n            r := math.Round(m[i][j]*pow) / pow\n            t[j] = fmt.Sprintf(\"%g\", r)\n            if t[j] == \"-0\" {\n                t[j] = \"0\"\n            }\n        }\n        s[i] = fmt.Sprintf(\"%v\", t)\n    }\n    return fmt.Sprintf(\"%v\", s)\n}\n\nfunc params(r, c int) [4][6]int {\n    return [4][6]int{\n        {0, r, 0, c, 0, 0},\n        {0, r, c, 2 * c, 0, c},\n        {r, 2 * r, 0, c, r, 0},\n        {r, 2 * r, c, 2 * c, r, c},\n    }\n}\n\nfunc toQuarters(m Matrix) [4]Matrix {\n    r := m.rows() / 2\n    c := m.cols() / 2\n    p := params(r, c)\n    var quarters [4]Matrix\n    for k := 0; k < 4; k++ {\n        q := make(Matrix, r)\n        for i := p[k][0]; i < p[k][1]; i++ {\n            q[i-p[k][4]] = make([]float64, c)\n            for j := p[k][2]; j < p[k][3]; j++ {\n                q[i-p[k][4]][j-p[k][5]] = m[i][j]\n            }\n        }\n        quarters[k] = q\n    }\n    return quarters\n}\n\nfunc fromQuarters(q [4]Matrix) Matrix {\n    r := q[0].rows()\n    c := q[0].cols()\n    p := params(r, c)\n    r *= 2\n    c *= 2\n    m := make(Matrix, r)\n    for i := 0; i < c; i++ {\n        m[i] = make([]float64, c)\n    }\n    for k := 0; k < 4; k++ {\n        for i := p[k][0]; i < p[k][1]; i++ {\n            for j := p[k][2]; j < p[k][3]; j++ {\n                m[i][j] = q[k][i-p[k][4]][j-p[k][5]]\n            }\n        }\n    }\n    return m\n}\n\nfunc strassen(a, b Matrix) Matrix {\n    if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() {\n        log.Fatal(\"Matrices must be square and of equal size.\")\n    }\n    if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 {\n        log.Fatal(\"Size of matrices must be a power of two.\")\n    }\n    if a.rows() == 1 {\n        return a.mul(b)\n    }\n    qa := toQuarters(a)\n    qb := toQuarters(b)\n    p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3]))\n    p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3]))\n    p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1]))\n    p4 := strassen(qa[0].add(qa[1]), qb[3])\n    p5 := strassen(qa[0], qb[1].sub(qb[3]))\n    p6 := strassen(qa[3], qb[2].sub(qb[0]))\n    p7 := strassen(qa[2].add(qa[3]), qb[0])\n    var q [4]Matrix\n    q[0] = p1.add(p2).sub(p4).add(p6)\n    q[1] = p4.add(p5)\n    q[2] = p6.add(p7)\n    q[3] = p2.sub(p3).add(p5).sub(p7)\n    return fromQuarters(q)\n}\n\nfunc main() {\n    a := Matrix{{1, 2}, {3, 4}}\n    b := Matrix{{5, 6}, {7, 8}}\n    c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}}\n    d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24},\n        {3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}}\n    e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}\n    f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}\n    fmt.Println(\"Using 'normal' matrix multiplication:\")\n    fmt.Printf(\"  a * b = %v\\n\", a.mul(b))\n    fmt.Printf(\"  c * d = %v\\n\", c.mul(d).toString(6))\n    fmt.Printf(\"  e * f = %v\\n\", e.mul(f))\n    fmt.Println(\"\\nUsing 'Strassen' matrix multiplication:\")\n    fmt.Printf(\"  a * b = %v\\n\", strassen(a, b))\n    fmt.Printf(\"  c * d = %v\\n\", strassen(c, d).toString(6))\n    fmt.Printf(\"  e * f = %v\\n\", strassen(e, f))\n}\n"}
{"id": 58590, "name": "Topic variable", "Python": ">>> 3\n3\n>>> _*_, _**0.5\n(9, 1.7320508075688772)\n>>>\n", "Go": "package main\n\nimport (\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"text/template\"\n)\n\nfunc sqr(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(f*f, 'f', -1, 64)\n}\n\nfunc sqrt(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)\n}\n\nfunc main() {\n    f := template.FuncMap{\"sqr\": sqr, \"sqrt\": sqrt}\n    t := template.Must(template.New(\"\").Funcs(f).Parse(`. = {{.}}\nsquare: {{sqr .}}\nsquare root: {{sqrt .}}\n`))\n    t.Execute(os.Stdout, \"3\")\n}\n"}
{"id": 58591, "name": "Topic variable", "Python": ">>> 3\n3\n>>> _*_, _**0.5\n(9, 1.7320508075688772)\n>>>\n", "Go": "package main\n\nimport (\n    \"math\"\n    \"os\"\n    \"strconv\"\n    \"text/template\"\n)\n\nfunc sqr(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(f*f, 'f', -1, 64)\n}\n\nfunc sqrt(x string) string {\n    f, err := strconv.ParseFloat(x, 64)\n    if err != nil {\n        return \"NA\"\n    }\n    return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)\n}\n\nfunc main() {\n    f := template.FuncMap{\"sqr\": sqr, \"sqrt\": sqrt}\n    t := template.Must(template.New(\"\").Funcs(f).Parse(`. = {{.}}\nsquare: {{sqr .}}\nsquare root: {{sqrt .}}\n`))\n    t.Execute(os.Stdout, \"3\")\n}\n"}
{"id": 58592, "name": "Add a variable to a class instance at runtime", "Python": "class empty(object):\n    pass\ne = empty()\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n)\n\ntype SomeStruct struct {\n    runtimeFields map[string]string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    ss := SomeStruct{make(map[string]string)}\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Println(\"Create two fields at runtime: \")\n    for i := 1; i <= 2; i++ {\n        fmt.Printf(\"  Field #%d:\\n\", i)\n        fmt.Print(\"       Enter name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        fmt.Print(\"       Enter value : \")\n        scanner.Scan()\n        value := scanner.Text()\n        check(scanner.Err())\n        ss.runtimeFields[name] = value\n        fmt.Println()\n    }\n    for {\n        fmt.Print(\"Which field do you want to inspect ? \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        value, ok := ss.runtimeFields[name]\n        if !ok {\n            fmt.Println(\"There is no field of that name, try again\")\n        } else {\n            fmt.Printf(\"Its value is '%s'\\n\", value)\n            return\n        }\n    }\n}\n"}
{"id": 58593, "name": "Faces from a mesh", "Python": "def perim_equal(p1, p2):\n    \n    if len(p1) != len(p2) or set(p1) != set(p2):\n        return False\n    if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):\n        return True\n    p2 = p2[::-1] \n    return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))\n\ndef edge_to_periphery(e):\n    edges = sorted(e)\n    p = list(edges.pop(0)) if edges else []\n    last = p[-1] if p else None\n    while edges:\n        for n, (i, j) in enumerate(edges):\n            if i == last:\n                p.append(j)\n                last = j\n                edges.pop(n)\n                break\n            elif j == last:\n                p.append(i)\n                last = i\n                edges.pop(n)\n                break\n        else:\n            \n            return \">>>Error! Invalid edge format<<<\"\n    return p[:-1]\n\nif __name__ == '__main__':\n    print('Perimeter format equality checks:')\n    for eq_check in [\n            { 'Q': (8, 1, 3),\n              'R': (1, 3, 8)},\n            { 'U': (18, 8, 14, 10, 12, 17, 19),\n              'V': (8, 14, 10, 12, 17, 19, 18)} ]:\n        (n1, p1), (n2, p2) = eq_check.items()\n        eq = '==' if perim_equal(p1, p2) else '!='\n        print(' ', n1, eq, n2)\n\n    print('\\nEdge to perimeter format translations:')\n    edge_d = {\n     'E': {(1, 11), (7, 11), (1, 7)},\n     'F': {(11, 23), (1, 17), (17, 23), (1, 11)},\n     'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)},\n     'H': {(1, 3), (9, 11), (3, 11), (1, 11)}\n            }\n    for name, edges in edge_d.items():\n        print(f\"  {name}: {edges}\\n     -> {edge_to_periphery(edges)}\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\n\nfunc contains(s []int, f int) bool {\n    for _, e := range s {\n        if e == f {\n            return true\n        }\n    }\n    return false\n}\n\n\nfunc sliceEqual(s1, s2 []int) bool {\n    for i := 0; i < len(s1); i++ {\n        if s1[i] != s2[i] {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\n\nfunc perimEqual(p1, p2 []int) bool {\n    le := len(p1)\n    if le != len(p2) {\n        return false\n    }\n    for _, p := range p1 {\n        if !contains(p2, p) {\n            return false\n        }\n    }\n    \n    c := make([]int, le)\n    copy(c, p1)\n    for r := 0; r < 2; r++ {\n        for i := 0; i < le; i++ {\n            if sliceEqual(c, p2) {\n                return true\n            }\n            \n            t := c[le-1]\n            copy(c[1:], c[0:le-1])\n            c[0] = t\n        }\n        \n        reverse(c)\n    }\n    return false\n}\n\ntype edge [2]int\n\n\nfunc faceToPerim(face []edge) []int {\n    \n    le := len(face)\n    if le == 0 {\n        return nil\n    }\n    edges := make([]edge, le)\n    for i := 0; i < le; i++ {\n        \n        if face[i][1] <= face[i][0] {\n            return nil\n        }\n        edges[i] = face[i]\n    }\n    \n    sort.Slice(edges, func(i, j int) bool {\n        if edges[i][0] != edges[j][0] {\n            return edges[i][0] < edges[j][0]\n        }\n        return edges[i][1] < edges[j][1]\n    })\n    var perim []int\n    first, last := edges[0][0], edges[0][1]\n    perim = append(perim, first, last)\n    \n    copy(edges, edges[1:])\n    edges = edges[0 : le-1]\n    le--\nouter:\n    for le > 0 {\n        for i, e := range edges {\n            found := false\n            if e[0] == last {\n                perim = append(perim, e[1])\n                last, found = e[1], true\n            } else if e[1] == last {\n                perim = append(perim, e[0])\n                last, found = e[0], true\n            }\n            if found {\n                \n                copy(edges[i:], edges[i+1:])\n                edges = edges[0 : le-1]\n                le--\n                if last == first {\n                    if le == 0 {\n                        break outer\n                    } else {\n                        return nil\n                    }\n                }\n                continue outer\n            }\n        }\n    }\n    return perim[0 : len(perim)-1]\n}\n\nfunc main() {\n    fmt.Println(\"Perimeter format equality checks:\")\n    areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8})\n    fmt.Printf(\"  Q == R is %t\\n\", areEqual)\n    areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18})\n    fmt.Printf(\"  U == V is %t\\n\", areEqual)\n    e := []edge{{7, 11}, {1, 11}, {1, 7}}\n    f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}}\n    g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}}\n    h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}}\n    fmt.Println(\"\\nEdge to perimeter format translations:\")\n    for i, face := range [][]edge{e, f, g, h} {\n        perim := faceToPerim(face)\n        if perim == nil {\n            fmt.Printf(\"  %c => Invalid edge format\\n\", i + 'E')\n        } else {\n            fmt.Printf(\"  %c => %v\\n\", i + 'E', perim)\n        }\n    }\n}\n"}
{"id": 58594, "name": "Resistance network calculator", "Python": "from fractions import Fraction\n\ndef gauss(m):\n\tn, p = len(m), len(m[0])\n\tfor i in range(n):\n\t\tk = max(range(i, n), key = lambda x: abs(m[x][i]))\n\t\tm[i], m[k] = m[k], m[i]\n\t\tt = 1 / m[i][i]\n\t\tfor j in range(i + 1, p): m[i][j] *= t\n\t\tfor j in range(i + 1, n):\n\t\t\tt = m[j][i]\n\t\t\tfor k in range(i + 1, p): m[j][k] -= t * m[i][k]\n\tfor i in range(n - 1, -1, -1):\n\t\tfor j in range(i): m[j][-1] -= m[j][i] * m[i][-1]\n\treturn [row[-1] for row in m]\n\ndef network(n,k0,k1,s):\n\tm = [[0] * (n+1) for i in range(n)]\n\tresistors = s.split('|')\n\tfor resistor in resistors:\n\t\ta,b,r = resistor.split(' ')\n\t\ta,b,r = int(a), int(b), Fraction(1,int(r))\n\t\tm[a][a] += r\n\t\tm[b][b] += r\n\t\tif a > 0: m[a][b] -= r\n\t\tif b > 0: m[b][a] -= r\n\tm[k0][k0] = Fraction(1, 1)\n\tm[k1][-1] = Fraction(1, 1)\n\treturn gauss(m)[k1]\n\nassert 10             == network(7,0,1,\"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8\")\nassert 3/2            == network(3*3,0,3*3-1,\"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1\")\nassert Fraction(13,7) == network(4*4,0,4*4-1,\"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1\")\nassert 180            == network(4,0,3,\"0 1 150|0 2 50|1 3 300|2 3 250\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc argmax(m [][]float64, i int) int {\n    col := make([]float64, len(m))\n    max, maxx := -1.0, -1\n    for x := 0; x < len(m); x++ {\n        col[x] = math.Abs(m[x][i])\n        if col[x] > max {\n            max = col[x]\n            maxx = x\n        }\n    }\n    return maxx\n}\n\nfunc gauss(m [][]float64) []float64 {\n    n, p := len(m), len(m[0])\n    for i := 0; i < n; i++ {\n        k := i + argmax(m[i:n], i)\n        m[i], m[k] = m[k], m[i]\n        t := 1 / m[i][i]\n        for j := i + 1; j < p; j++ {\n            m[i][j] *= t\n        }\n        for j := i + 1; j < n; j++ {\n            t = m[j][i]\n            for l := i + 1; l < p; l++ {\n                m[j][l] -= t * m[i][l]\n            }\n        }\n    }\n    for i := n - 1; i >= 0; i-- {\n        for j := 0; j < i; j++ {\n            m[j][p-1] -= m[j][i] * m[i][p-1]\n        }\n    }\n    col := make([]float64, len(m))\n    for x := 0; x < len(m); x++ {\n        col[x] = m[x][p-1]\n    }\n    return col\n}\n\nfunc network(n, k0, k1 int, s string) float64 {\n    m := make([][]float64, n)\n    for i := 0; i < n; i++ {\n        m[i] = make([]float64, n+1)\n    }\n    for _, resistor := range strings.Split(s, \"|\") {\n        rarr := strings.Fields(resistor)\n        a, _ := strconv.Atoi(rarr[0])\n        b, _ := strconv.Atoi(rarr[1])\n        ri, _ := strconv.Atoi(rarr[2])\n        r := 1.0 / float64(ri)\n        m[a][a] += r\n        m[b][b] += r\n        if a > 0 {\n            m[a][b] -= r\n        }\n        if b > 0 {\n            m[b][a] -= r\n        }\n    }\n    m[k0][k0] = 1\n    m[k1][n] = 1\n    return gauss(m)[k1]\n}\n\nfunc main() {\n    var fa [4]float64\n    fa[0] = network(7, 0, 1, \"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8\")\n    fa[1] = network(9, 0, 8, \"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1\")\n    fa[2] = network(16, 0, 15, \"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1\")\n    fa[3] = network(4, 0, 3, \"0 1 150|0 2 50|1 3 300|2 3 250\")\n    for _, f := range fa {\n        fmt.Printf(\"%.6g\\n\", f)\n    }\n}\n"}
{"id": 58595, "name": "Bioinformatics_Subsequence", "Python": " \nfrom random import choice\nimport regex as re \nimport time\n\ndef generate_sequence(n: int ) -> str:\n    return \"\".join([ choice(['A','C','G','T']) for _ in range(n) ])\n\ndef dna_findall(needle: str, haystack: str) -> None:\n\n    if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0:\n        print(\"No matches found\")\n    else:\n        print(f\"Found {needle} at the following indices: \")\n        for match in re.finditer(needle, haystack, overlapped=True):\n            print(f\"{match.start()}:{match.end()} \")\n\ndna_seq = generate_sequence(200)\nsample_seq = generate_sequence(4)\n\nc = 1\nfor i in dna_seq:\n    print(i, end=\"\") if c % 20 != 0 else print(f\"{i}\")\n    c += 1\nprint(f\"\\nSearch Sample: {sample_seq}\")\n\ndna_findall(sample_seq, dna_seq)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"regexp\"\n    \"time\"\n)\n\nconst base = \"ACGT\"\n\nfunc findDnaSubsequence(dnaSize, chunkSize int) {\n    dnaSeq := make([]byte, dnaSize)\n    for i := 0; i < dnaSize; i++ {\n        dnaSeq[i] = base[rand.Intn(4)]\n    }\n    dnaStr := string(dnaSeq)\n    dnaSubseq := make([]byte, 4)\n    for i := 0; i < 4; i++ {\n        dnaSubseq[i] = base[rand.Intn(4)]\n    }\n    dnaSubstr := string(dnaSubseq)\n    fmt.Println(\"DNA sequnence:\")\n    for i := chunkSize; i <= len(dnaStr); i += chunkSize {\n        start := i - chunkSize\n        fmt.Printf(\"%3d..%3d: %s\\n\", start+1, i, dnaStr[start:i])\n    }\n    fmt.Println(\"\\nSubsequence to locate:\", dnaSubstr)\n    var r = regexp.MustCompile(dnaSubstr)\n    var matches = r.FindAllStringIndex(dnaStr, -1)\n    if len(matches) == 0 {\n        fmt.Println(\"No matches found.\")\n    } else {\n        fmt.Println(\"Matches found at the following indices:\")\n        for _, m := range matches {\n            fmt.Printf(\"%3d..%-3d\\n\", m[0]+1, m[1])\n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    findDnaSubsequence(200, 20)\n    fmt.Println()\n    findDnaSubsequence(600, 40)\n}\n"}
{"id": 58596, "name": "Nested templated data", "Python": "from pprint import pprint as pp\n\nclass Template():\n    def __init__(self, structure):\n        self.structure = structure\n        self.used_payloads, self.missed_payloads = [], []\n    \n    def inject_payload(self, id2data):\n        \n        def _inject_payload(substruct, i2d, used, missed):\n            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)\n            missed.extend(f'??\n                          for x in substruct if type(x) is not tuple and x not in i2d)\n            return tuple(_inject_payload(x, i2d, used, missed) \n                           if type(x) is tuple \n                           else i2d.get(x, f'??\n                         for x in substruct)\n                           \n        ans = _inject_payload(self.structure, id2data, \n                              self.used_payloads, self.missed_payloads)\n        self.unused_payloads = sorted(set(id2data.values()) \n                                      - set(self.used_payloads))\n        self.missed_payloads = sorted(set(self.missed_payloads))\n        return ans\n\nif __name__ == '__main__':\n    index2data = {p: f'Payload\n    print(\"\n    print('\\n  '.join(list(index2data.values())))\n    for structure in [\n     (((1, 2),\n       (3, 4, 1),\n       5),),\n    \n     (((1, 2),\n       (10, 4, 1),\n       5),)]:\n        print(\"\\n\\n\n        pp(structure, width=13)\n        print(\"\\n TEMPLATE WITH PAYLOADS:\")\n        t = Template(structure)\n        out = t.inject_payload(index2data)\n        pp(out)\n        print(\"\\n UNUSED PAYLOADS:\\n  \", end='')\n        unused = t.unused_payloads\n        print('\\n  '.join(unused) if unused else '-')\n        print(\" MISSING PAYLOADS:\\n  \", end='')\n        missed = t.missed_payloads\n        print('\\n  '.join(missed) if missed else '-')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"text/template\"\n)\n\nfunc main() {\n    const t = `[[[{{index .P 1}}, {{index .P 2}}],\n  [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n  {{index .P 5}}]]\n`\n    type S struct {\n        P map[int]string\n    }\n\n    var s S\n    s.P = map[int]string{\n        0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n        4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n    }\n    tmpl := template.Must(template.New(\"\").Parse(t))\n    tmpl.Execute(os.Stdout, s)\n\n    var unused []int\n    for k, _ := range s.P {\n        if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n            unused = append(unused, k)\n        }\n    }\n    sort.Ints(unused)\n    fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}\n"}
{"id": 58597, "name": "Bitmap_Read an image through a pipe", "Python": "\n\nfrom PIL import Image\n\n\n\nim = Image.open(\"boxes_1.jpg\")\nim.save(\"boxes_1v2.ppm\")\n", "Go": "package main\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    c := exec.Command(\"convert\", \"Unfilledcirc.png\", \"-depth\", \"1\", \"ppm:-\")\n    pipe, err := c.StdoutPipe()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = c.Start(); err != nil {\n        log.Fatal(err)\n    }\n    b, err := raster.ReadPpmFrom(pipe)\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = b.WritePpmFile(\"Unfilledcirc.ppm\"); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58598, "name": "Bitmap_Read an image through a pipe", "Python": "\n\nfrom PIL import Image\n\n\n\nim = Image.open(\"boxes_1.jpg\")\nim.save(\"boxes_1v2.ppm\")\n", "Go": "package main\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    c := exec.Command(\"convert\", \"Unfilledcirc.png\", \"-depth\", \"1\", \"ppm:-\")\n    pipe, err := c.StdoutPipe()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = c.Start(); err != nil {\n        log.Fatal(err)\n    }\n    b, err := raster.ReadPpmFrom(pipe)\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = b.WritePpmFile(\"Unfilledcirc.ppm\"); err != nil {\n        log.Fatal(err)\n    }\n}\n"}
{"id": 58599, "name": "Memory layout of a data structure", "Python": "from ctypes import Structure, c_int\n\nrs232_9pin  = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg\"\n                \"_11 SCD SCS STD TC  SRD RC\"\n                \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]\n", "Go": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9  rs232p9 = 1 << iota \n\tRD9                      \n\tTD9                      \n\tDTR9                     \n\tSG9                      \n\tDSR9                     \n\tRTS9                     \n\tCTS9                     \n\tRI9                      \n)\n\nfunc main() {\n\t\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}\n"}
{"id": 58600, "name": "Memory layout of a data structure", "Python": "from ctypes import Structure, c_int\n\nrs232_9pin  = \"_0 CD RD TD DTR SG DSR RTS CTS RI\".split()\nrs232_25pin = ( \"_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg\"\n                \"_11 SCD SCS STD TC  SRD RC\"\n                \"_18 SRS DTR SQD RI DRS XTC\" ).split()\n\nclass RS232_9pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]\n\n\t\nclass RS232_25pin(Structure):\n    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]\n", "Go": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9  rs232p9 = 1 << iota \n\tRD9                      \n\tTD9                      \n\tDTR9                     \n\tSG9                      \n\tDSR9                     \n\tRTS9                     \n\tCTS9                     \n\tRI9                      \n)\n\nfunc main() {\n\t\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}\n"}
{"id": 58601, "name": "Sum of two adjacent numbers are primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == \"__main__\":\n    n = 0\n    num = 0\n\n    print('The first 20 pairs of numbers whose sum is prime:') \n    while True:\n        n += 1\n        suma = 2*n+1\n        if isPrime(suma):\n            num += 1\n            if num < 21:\n                print('{:2}'.format(n), \"+\", '{:2}'.format(n+1), \"=\", '{:2}'.format(suma))\n            else:\n                break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(math.Log(1e7) * 1e7 * 1.2) \n    primes := rcu.Primes(limit)\n    fmt.Println(\"The first 20 pairs of natural numbers whose sum is prime are:\")\n    for i := 1; i <= 20; i++ {\n        p := primes[i]\n        hp := p / 2\n        fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n    }\n    fmt.Println(\"\\nThe 10 millionth such pair is:\")\n    p := primes[1e7]\n    hp := p / 2\n    fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n}\n"}
{"id": 58602, "name": "Mastermind", "Python": "import random\n\n\ndef encode(correct, guess):\n    output_arr = [''] * len(correct)\n\n    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):\n        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'\n\n    return ''.join(output_arr)\n\n\ndef safe_int_input(prompt, min_val, max_val):\n    while True:\n        user_input = input(prompt)\n\n        try:\n            user_input = int(user_input)\n        except ValueError:\n            continue\n\n        if min_val <= user_input <= max_val:\n            return user_input\n\n\ndef play_game():\n    print(\"Welcome to Mastermind.\")\n    print(\"You will need to guess a random code.\")\n    print(\"For each guess, you will receive a hint.\")\n    print(\"In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.\")\n    print()\n\n    number_of_letters = safe_int_input(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n    code_length = safe_int_input(\"Select a length for the code (4-10): \", 4, 10)\n\n    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]\n    code = ''.join(random.choices(letters, k=code_length))\n    guesses = []\n\n    while True:\n        print()\n        guess = input(f\"Enter a guess of length {code_length} ({letters}): \").upper().strip()\n\n        if len(guess) != code_length or any([char not in letters for char in guess]):\n            continue\n        elif guess == code:\n            print(f\"\\nYour guess {guess} was correct!\")\n            break\n        else:\n            guesses.append(f\"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}\")\n\n        for i_guess in guesses:\n            print(\"------------------------------------\")\n            print(i_guess)\n        print(\"------------------------------------\")\n\n\nif __name__ == '__main__':\n    play_game()\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n"}
{"id": 58603, "name": "Mastermind", "Python": "import random\n\n\ndef encode(correct, guess):\n    output_arr = [''] * len(correct)\n\n    for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):\n        output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'\n\n    return ''.join(output_arr)\n\n\ndef safe_int_input(prompt, min_val, max_val):\n    while True:\n        user_input = input(prompt)\n\n        try:\n            user_input = int(user_input)\n        except ValueError:\n            continue\n\n        if min_val <= user_input <= max_val:\n            return user_input\n\n\ndef play_game():\n    print(\"Welcome to Mastermind.\")\n    print(\"You will need to guess a random code.\")\n    print(\"For each guess, you will receive a hint.\")\n    print(\"In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.\")\n    print()\n\n    number_of_letters = safe_int_input(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n    code_length = safe_int_input(\"Select a length for the code (4-10): \", 4, 10)\n\n    letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]\n    code = ''.join(random.choices(letters, k=code_length))\n    guesses = []\n\n    while True:\n        print()\n        guess = input(f\"Enter a guess of length {code_length} ({letters}): \").upper().strip()\n\n        if len(guess) != code_length or any([char not in letters for char in guess]):\n            continue\n        elif guess == code:\n            print(f\"\\nYour guess {guess} was correct!\")\n            break\n        else:\n            guesses.append(f\"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}\")\n\n        for i_guess in guesses:\n            print(\"------------------------------------\")\n            print(i_guess)\n        print(\"------------------------------------\")\n\n\nif __name__ == '__main__':\n    play_game()\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"mastermind: \")\n\tlog.SetFlags(0)\n\tcolours := flag.Int(\"colours\", 6, \"number of colours to use (2-20)\")\n\tflag.IntVar(colours, \"colors\", 6, \"alias for colours\")\n\tholes := flag.Int(\"holes\", 4, \"number of holes (the code length, 4-10)\")\n\tguesses := flag.Int(\"guesses\", 12, \"number of guesses allowed (7-20)\")\n\tunique := flag.Bool(\"unique\", false, \"disallow duplicate colours in the code\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\tm, err := NewMastermind(*colours, *holes, *guesses, *unique)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = m.Play()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype mastermind struct {\n\tcolours int\n\tholes   int\n\tguesses int\n\tunique  bool\n\n\tcode   string\n\tpast   []string \n\tscores []string \n}\n\nfunc NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {\n\tif colours < 2 || colours > 20 {\n\t\treturn nil, errors.New(\"colours must be between 2 and 20 inclusive\")\n\t}\n\tif holes < 4 || holes > 10 {\n\t\treturn nil, errors.New(\"holes must be between 4 and 10 inclusive\")\n\t}\n\tif guesses < 7 || guesses > 20 {\n\t\treturn nil, errors.New(\"guesses must be between 7 and 20 inclusive\")\n\t}\n\tif unique && holes > colours {\n\t\treturn nil, errors.New(\"holes must be > colours when using unique\")\n\t}\n\n\treturn &mastermind{\n\t\tcolours: colours,\n\t\tholes:   holes,\n\t\tguesses: guesses,\n\t\tunique:  unique,\n\t\tpast:    make([]string, 0, guesses),\n\t\tscores:  make([]string, 0, guesses),\n\t}, nil\n}\n\nfunc (m *mastermind) Play() error {\n\tm.generateCode()\n\tfmt.Printf(\"A set of %s has been selected as the code.\\n\", m.describeCode(m.unique))\n\tfmt.Printf(\"You have %d guesses.\\n\", m.guesses)\n\tfor len(m.past) < m.guesses {\n\t\tguess, err := m.inputGuess()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println()\n\t\tm.past = append(m.past, guess)\n\t\tstr, won := m.scoreString(m.score(guess))\n\t\tif won {\n\t\t\tplural := \"es\"\n\t\t\tif len(m.past) == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"You found the code in %d guess%s.\\n\", len(m.past), plural)\n\t\t\treturn nil\n\t\t}\n\t\tm.scores = append(m.scores, str)\n\t\tm.printHistory()\n\t\tfmt.Println()\n\t}\n\tfmt.Printf(\"You are out of guesses. The code was %s.\\n\", m.code)\n\treturn nil\n}\n\nconst charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst blacks = \"XXXXXXXXXX\"\nconst whites = \"OOOOOOOOOO\"\nconst nones = \"----------\"\n\nfunc (m *mastermind) describeCode(unique bool) string {\n\tustr := \"\"\n\tif unique {\n\t\tustr = \" unique\"\n\t}\n\treturn fmt.Sprintf(\"%d%s letters (from 'A' to %q)\",\n\t\tm.holes, ustr, charset[m.colours-1],\n\t)\n}\n\nfunc (m *mastermind) printHistory() {\n\tfor i, g := range m.past {\n\t\tfmt.Printf(\"-----%s---%[1]s--\\n\", nones[:m.holes])\n\t\tfmt.Printf(\"%2d:  %s : %s\\n\", i+1, g, m.scores[i])\n\t}\n}\n\nfunc (m *mastermind) generateCode() {\n\tcode := make([]byte, m.holes)\n\tif m.unique {\n\t\tp := rand.Perm(m.colours)\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[p[i]]\n\t\t}\n\t} else {\n\t\tfor i := range code {\n\t\t\tcode[i] = charset[rand.Intn(m.colours)]\n\t\t}\n\t}\n\tm.code = string(code)\n\t\n}\n\nfunc (m *mastermind) inputGuess() (string, error) {\n\tvar input string\n\tfor {\n\t\tfmt.Printf(\"Enter guess #%d: \", len(m.past)+1)\n\t\tif _, err := fmt.Scanln(&input); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinput = strings.ToUpper(strings.TrimSpace(input))\n\t\tif m.validGuess(input) {\n\t\t\treturn input, nil\n\t\t}\n\t\tfmt.Printf(\"A guess must consist of %s.\\n\", m.describeCode(false))\n\t}\n}\n\nfunc (m *mastermind) validGuess(input string) bool {\n\tif len(input) != m.holes {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(input); i++ {\n\t\tc := input[i]\n\t\tif c < 'A' || c > charset[m.colours-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *mastermind) score(guess string) (black, white int) {\n\tscored := make([]bool, m.holes)\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tblack++\n\t\t\tscored[i] = true\n\t\t}\n\t}\n\tfor i := 0; i < len(guess); i++ {\n\t\tif guess[i] == m.code[i] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < len(m.code); j++ {\n\t\t\tif i != j && !scored[j] && guess[i] == m.code[j] {\n\t\t\t\twhite++\n\t\t\t\tscored[j] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (m *mastermind) scoreString(black, white int) (string, bool) {\n\tnone := m.holes - black - white\n\treturn blacks[:black] + whites[:white] + nones[:none], black == m.holes\n}\n"}
{"id": 58604, "name": "Maximum difference between adjacent elements of list", "Python": "\n\n\n\ndef maxDeltas(ns):\n    \n    pairs = [\n        (abs(a - b), (a, b)) for a, b\n        in zip(ns, ns[1:])\n    ]\n    delta = max(pairs, key=lambda ab: ab[0])[0]\n\n    return [\n        ab for ab in pairs\n        if delta == ab[0]\n    ]\n\n\n\n\ndef main():\n    \n\n    maxPairs = maxDeltas([\n        1, 8, 2, -3, 0, 1, 1, -2.3, 0,\n        5.5, 8, 6, 2, 9, 11, 10, 3\n    ])\n\n    for ab in maxPairs:\n        print(ab)\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3}\n    maxDiff := -1.0\n    var maxPairs [][2]float64\n    for i := 1; i < len(list); i++ {\n        diff := math.Abs(list[i-1] - list[i])\n        if diff > maxDiff {\n            maxDiff = diff\n            maxPairs = [][2]float64{{list[i-1], list[i]}}\n        } else if diff == maxDiff {\n            maxPairs = append(maxPairs, [2]float64{list[i-1], list[i]})\n        }\n    }\n    fmt.Println(\"The maximum difference between adjacent pairs of the list is:\", maxDiff)\n    fmt.Println(\"The pairs with this difference are:\", maxPairs)\n}\n"}
{"id": 58605, "name": "Composite numbers k with no single digit factors whose factors are all substrings of k", "Python": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n    if n < 10 or isprime(n):\n        return False\n    strn = str(n)\n    pfacs = factorint(n).keys()\n    return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n    if contains_its_prime_factors_all_over_7(n):\n        found += 1\n        print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n        if found == 20:\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    count := 0\n    k := 11 * 11\n    var res []int\n    for count < 20 {\n        if k%3 == 0 || k%5 == 0 || k%7 == 0 {\n            k += 2\n            continue\n        }\n        factors := rcu.PrimeFactors(k)\n        if len(factors) > 1 {\n            s := strconv.Itoa(k)\n            includesAll := true\n            prev := -1\n            for _, f := range factors {\n                if f == prev {\n                    continue\n                }\n                fs := strconv.Itoa(f)\n                if strings.Index(s, fs) == -1 {\n                    includesAll = false\n                    break\n                }\n            }\n            if includesAll {\n                res = append(res, k)\n                count++\n            }\n        }\n        k += 2\n    }\n    for _, e := range res[0:10] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n    for _, e := range res[10:20] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n}\n"}
{"id": 58606, "name": "Composite numbers k with no single digit factors whose factors are all substrings of k", "Python": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n    if n < 10 or isprime(n):\n        return False\n    strn = str(n)\n    pfacs = factorint(n).keys()\n    return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n    if contains_its_prime_factors_all_over_7(n):\n        found += 1\n        print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n        if found == 20:\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    count := 0\n    k := 11 * 11\n    var res []int\n    for count < 20 {\n        if k%3 == 0 || k%5 == 0 || k%7 == 0 {\n            k += 2\n            continue\n        }\n        factors := rcu.PrimeFactors(k)\n        if len(factors) > 1 {\n            s := strconv.Itoa(k)\n            includesAll := true\n            prev := -1\n            for _, f := range factors {\n                if f == prev {\n                    continue\n                }\n                fs := strconv.Itoa(f)\n                if strings.Index(s, fs) == -1 {\n                    includesAll = false\n                    break\n                }\n            }\n            if includesAll {\n                res = append(res, k)\n                count++\n            }\n        }\n        k += 2\n    }\n    for _, e := range res[0:10] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n    for _, e := range res[10:20] {\n        fmt.Printf(\"%10s \", rcu.Commatize(e))\n    }\n    fmt.Println()\n}\n"}
{"id": 58607, "name": "Functional coverage tree", "Python": "from itertools import zip_longest\n\n\nfc2 = \n\nNAME, WT, COV = 0, 1, 2\n\ndef right_type(txt):\n    try:\n        return float(txt)\n    except ValueError:\n        return txt\n\ndef commas_to_list(the_list, lines, start_indent=0):\n    \n    for n, line in lines:\n        indent = 0\n        while line.startswith(' ' * (4 * indent)):\n            indent += 1\n        indent -= 1\n        fields = [right_type(f) for f in line.strip().split(',')]\n        if indent == start_indent:\n            the_list.append(fields)\n        elif indent > start_indent:\n            lst = [fields]\n            sub = commas_to_list(lst, lines, indent)\n            the_list[-1] = (the_list[-1], lst)\n            if sub not in (None, ['']) :\n                the_list.append(sub)\n        else:\n            return fields if fields else None\n    return None\n\n\ndef pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']):\n    \n    lhs = ' ' * (4 * indent)\n    for item in lst:\n        if type(item) != tuple:\n            name, *rest = item\n            print(widths[0] % (lhs + name), end='|')\n            for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):\n                if type(item) == str:\n                    width = width[:-1] + 's'\n                print(width % item, end='|')\n            print()\n        else:\n            item, children = item\n            name, *rest = item\n            print(widths[0] % (lhs + name), end='|')\n            for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):\n                if type(item) == str:\n                    width = width[:-1] + 's'\n                print(width % item, end='|')\n            print()\n            pptreefields(children, indent+1)\n\n\ndef default_field(node_list):\n    node_list[WT] = node_list[WT] if node_list[WT] else 1.0\n    node_list[COV] = node_list[COV] if node_list[COV] else 0.0\n\ndef depth_first(tree, visitor=default_field):\n    for item in tree:\n        if type(item) == tuple:\n            item, children = item\n            depth_first(children, visitor)\n        visitor(item)\n            \n\ndef covercalc(tree):\n    \n    sum_covwt, sum_wt = 0, 0\n    for item in tree:\n        if type(item) == tuple:\n            item, children = item\n            item[COV] = covercalc(children)\n        sum_wt  += item[WT]\n        sum_covwt += item[COV] * item[WT]\n    cov = sum_covwt / sum_wt\n    return cov\n\nif __name__ == '__main__':        \n    lstc = []\n    commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\\n'))))\n    \n    \n    \n    depth_first(lstc)\n    \n    \n    print('\\n\\nTOP COVERAGE = %f\\n' % covercalc(lstc))\n    depth_first(lstc)\n    pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype FCNode struct {\n    name     string\n    weight   int\n    coverage float64\n    children []*FCNode\n    parent   *FCNode\n}\n\nfunc newFCN(name string, weight int, coverage float64) *FCNode {\n    return &FCNode{name, weight, coverage, nil, nil}\n}\n\nfunc (n *FCNode) addChildren(nodes []*FCNode) {\n    for _, node := range nodes {\n        node.parent = n\n        n.children = append(n.children, node)\n    }\n    n.updateCoverage()\n}\n\nfunc (n *FCNode) setCoverage(value float64) {\n    if n.coverage != value {\n        n.coverage = value\n        \n        if n.parent != nil {\n            n.parent.updateCoverage()\n        }\n    }\n}\n\nfunc (n *FCNode) updateCoverage() {\n    v1 := 0.0\n    v2 := 0\n    for _, node := range n.children {\n        v1 += float64(node.weight) * node.coverage\n        v2 += node.weight\n    }\n    n.setCoverage(v1 / float64(v2))\n}\n\nfunc (n *FCNode) show(level int) {\n    indent := level * 4\n    nl := len(n.name) + indent\n    fmt.Printf(\"%*s%*s  %3d   | %8.6f |\\n\", nl, n.name, 32-nl, \"|\", n.weight, n.coverage)\n    if len(n.children) == 0 {\n        return\n    }\n    for _, child := range n.children {\n        child.show(level + 1)\n    }\n}\n\nvar houses = []*FCNode{\n    newFCN(\"house1\", 40, 0),\n    newFCN(\"house2\", 60, 0),\n}\n\nvar house1 = []*FCNode{\n    newFCN(\"bedrooms\", 1, 0.25),\n    newFCN(\"bathrooms\", 1, 0),\n    newFCN(\"attic\", 1, 0.75),\n    newFCN(\"kitchen\", 1, 0.1),\n    newFCN(\"living_rooms\", 1, 0),\n    newFCN(\"basement\", 1, 0),\n    newFCN(\"garage\", 1, 0),\n    newFCN(\"garden\", 1, 0.8),\n}\n\nvar house2 = []*FCNode{\n    newFCN(\"upstairs\", 1, 0),\n    newFCN(\"groundfloor\", 1, 0),\n    newFCN(\"basement\", 1, 0),\n}\n\nvar h1Bathrooms = []*FCNode{\n    newFCN(\"bathroom1\", 1, 0.5),\n    newFCN(\"bathroom2\", 1, 0),\n    newFCN(\"outside_lavatory\", 1, 1),\n}\n\nvar h1LivingRooms = []*FCNode{\n    newFCN(\"lounge\", 1, 0),\n    newFCN(\"dining_room\", 1, 0),\n    newFCN(\"conservatory\", 1, 0),\n    newFCN(\"playroom\", 1, 1),\n}\n\nvar h2Upstairs = []*FCNode{\n    newFCN(\"bedrooms\", 1, 0),\n    newFCN(\"bathroom\", 1, 0),\n    newFCN(\"toilet\", 1, 0),\n    newFCN(\"attics\", 1, 0.6),\n}\n\nvar h2Groundfloor = []*FCNode{\n    newFCN(\"kitchen\", 1, 0),\n    newFCN(\"living_rooms\", 1, 0),\n    newFCN(\"wet_room_&_toilet\", 1, 0),\n    newFCN(\"garage\", 1, 0),\n    newFCN(\"garden\", 1, 0.9),\n    newFCN(\"hot_tub_suite\", 1, 1),\n}\n\nvar h2Basement = []*FCNode{\n    newFCN(\"cellars\", 1, 1),\n    newFCN(\"wine_cellar\", 1, 1),\n    newFCN(\"cinema\", 1, 0.75),\n}\n\nvar h2UpstairsBedrooms = []*FCNode{\n    newFCN(\"suite_1\", 1, 0),\n    newFCN(\"suite_2\", 1, 0),\n    newFCN(\"bedroom_3\", 1, 0),\n    newFCN(\"bedroom_4\", 1, 0),\n}\n\nvar h2GroundfloorLivingRooms = []*FCNode{\n    newFCN(\"lounge\", 1, 0),\n    newFCN(\"dining_room\", 1, 0),\n    newFCN(\"conservatory\", 1, 0),\n    newFCN(\"playroom\", 1, 0),\n}\n\nfunc main() {\n    cleaning := newFCN(\"cleaning\", 1, 0)\n\n    house1[1].addChildren(h1Bathrooms)\n    house1[4].addChildren(h1LivingRooms)\n    houses[0].addChildren(house1)\n\n    h2Upstairs[0].addChildren(h2UpstairsBedrooms)\n    house2[0].addChildren(h2Upstairs)\n    h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)\n    house2[1].addChildren(h2Groundfloor)\n    house2[2].addChildren(h2Basement)\n    houses[1].addChildren(house2)\n\n    cleaning.addChildren(houses)\n    topCoverage := cleaning.coverage\n    fmt.Printf(\"TOP COVERAGE = %8.6f\\n\\n\", topCoverage)\n    fmt.Println(\"NAME HIERARCHY                 | WEIGHT | COVERAGE |\")\n    cleaning.show(0)\n\n    h2Basement[2].setCoverage(1) \n    diff := cleaning.coverage - topCoverage\n    fmt.Println(\"\\nIf the coverage of the Cinema node were increased from 0.75 to 1\")\n    fmt.Print(\"the top level coverage would increase by \")\n    fmt.Printf(\"%8.6f to %8.6f\\n\", diff, topCoverage+diff)\n    h2Basement[2].setCoverage(0.75) \n}\n"}
{"id": 58608, "name": "Smallest enclosing circle problem", "Python": "import numpy as np\n\nclass ProjectorStack:\n    \n    def __init__(self, vec):\n        self.vs = np.array(vec)\n        \n    def push(self, v):\n        if len(self.vs) == 0:\n            self.vs = np.array([v])\n        else:\n            self.vs = np.append(self.vs, [v], axis=0)\n        return self\n    \n    def pop(self):\n        if len(self.vs) > 0:\n            ret, self.vs = self.vs[-1], self.vs[:-1]\n            return ret\n    \n    def __mul__(self, v):\n        s = np.zeros(len(v))\n        for vi in self.vs:\n            s = s + vi * np.dot(vi, v)\n        return s\n    \nclass GaertnerBoundary:\n    \n    def __init__(self, pts):\n        self.projector = ProjectorStack([])\n        self.centers, self.square_radii = np.array([]), np.array([])\n        self.empty_center = np.array([np.NaN for _ in pts[0]])\n\n\ndef push_if_stable(bound, pt):\n    if len(bound.centers) == 0:\n        bound.square_radii = np.append(bound.square_radii, 0.0)\n        bound.centers = np.array([pt])\n        return True\n    q0, center = bound.centers[0], bound.centers[-1]\n    C, r2  = center - q0, bound.square_radii[-1]\n    Qm, M = pt - q0, bound.projector\n    Qm_bar = M * Qm\n    residue, e = Qm - Qm_bar, sqdist(Qm, C) - r2\n    z, tol = 2 * sqnorm(residue), np.finfo(float).eps * max(r2, 1.0)\n    isstable = np.abs(z) > tol\n    if isstable:\n        center_new  = center + (e / z) * residue\n        r2new = r2 + (e * e) / (2 * z)\n        bound.projector.push(residue / np.linalg.norm(residue))\n        bound.centers = np.append(bound.centers, np.array([center_new]), axis=0)\n        bound.square_radii = np.append(bound.square_radii, r2new)\n    return isstable\n\ndef pop(bound):\n    n = len(bound.centers)\n    bound.centers = bound.centers[:-1]\n    bound.square_radii = bound.square_radii[:-1]\n    if n >= 2:\n        bound.projector.pop()\n    return bound\n\n\nclass NSphere:\n    def __init__(self, c, sqr):\n        self.center = np.array(c)\n        self.sqradius = sqr\n\ndef isinside(pt, nsphere, atol=1e-6, rtol=0.0):\n    r2, R2 = sqdist(pt, nsphere.center), nsphere.sqradius\n    return r2 <= R2 or np.isclose(r2, R2, atol=atol**2,rtol=rtol**2)\n\ndef allinside(pts, nsphere, atol=1e-6, rtol=0.0):\n    for p in pts:\n        if not isinside(p, nsphere, atol, rtol):\n            return False\n    return True\n\ndef move_to_front(pts, i):\n    pt = pts[i]\n    for j in range(len(pts)):\n        pts[j], pt = pt, np.array(pts[j])\n        if j == i:\n            break\n    return pts\n\ndef dist(p1, p2):\n    return np.linalg.norm(p1 - p2)\n\ndef sqdist(p1, p2):\n    return sqnorm(p1 - p2)\n\ndef sqnorm(p):\n    return np.sum(np.array([x * x for x in p]))\n\ndef ismaxlength(bound):\n    len(bound.centers) == len(bound.empty_center) + 1\n\ndef makeNSphere(bound):\n    if len(bound.centers) == 0: \n        return NSphere(bound.empty_center, 0.0)\n    return NSphere(bound.centers[-1], bound.square_radii[-1])\n\ndef _welzl(pts, pos, bdry):\n    support_count, nsphere = 0, makeNSphere(bdry)\n    if ismaxlength(bdry):\n        return nsphere, 0\n    for i in range(pos):\n        if not isinside(pts[i], nsphere):\n            isstable = push_if_stable(bdry, pts[i])\n            if isstable:\n                nsphere, s = _welzl(pts, i, bdry)\n                pop(bdry)\n                move_to_front(pts, i)\n                support_count = s + 1\n    return nsphere, support_count\n\ndef find_max_excess(nsphere, pts, k1):\n    err_max, k_max = -np.Inf, k1 - 1\n    for (k, pt) in enumerate(pts[k_max:]):\n        err = sqdist(pt, nsphere.center) - nsphere.sqradius\n        if  err > err_max:\n            err_max, k_max = err, k + k1\n    return err_max, k_max - 1\n\ndef welzl(points, maxiterations=2000):\n    pts, eps = np.array(points, copy=True), np.finfo(float).eps\n    bdry, t = GaertnerBoundary(pts), 1\n    nsphere, s = _welzl(pts, t, bdry)\n    for i in range(maxiterations):\n        e, k = find_max_excess(nsphere, pts, t + 1)\n        if e <= eps:\n            break\n        pt = pts[k]\n        push_if_stable(bdry, pt)\n        nsphere_new, s_new = _welzl(pts, s, bdry)\n        pop(bdry)\n        move_to_front(pts, k)\n        nsphere = nsphere_new\n        t, s = s + 1, s_new + 1\n    return nsphere\n\nif __name__ == '__main__':\n    TESTDATA =[\n        np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]]),\n        np.array([[5.0, -2.0], [-3.0, -2.0], [-2.0, 5.0], [1.0, 6.0], [0.0, 2.0]]),\n        np.array([[2.0, 4.0, -1.0], [1.0, 5.0, -3.0], [8.0, -4.0, 1.0], [3.0, 9.0, -5.0]]),\n        np.random.normal(size=(8, 5))\n    ]\n    for test in TESTDATA:\n        nsphere = welzl(test)\n        print(\"For points: \", test)\n        print(\"    Center is at: \", nsphere.center)\n        print(\"    Radius is: \", np.sqrt(nsphere.sqradius), \"\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype Point struct{ x, y float64 }\n\ntype Circle struct {\n    c Point\n    r float64\n}\n\n\nfunc (p Point) String() string { return fmt.Sprintf(\"(%f, %f)\", p.x, p.y) }\n\n\nfunc distSq(a, b Point) float64 {\n    return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)\n}\n\n\nfunc getCircleCenter(bx, by, cx, cy float64) Point {\n    b := bx*bx + by*by\n    c := cx*cx + cy*cy\n    d := bx*cy - by*cx\n    return Point{(cy*b - by*c) / (2 * d), (bx*c - cx*b) / (2 * d)}\n}\n\n\nfunc (ci Circle) contains(p Point) bool {\n    return distSq(ci.c, p) <= ci.r*ci.r\n}\n\n\nfunc (ci Circle) encloses(ps []Point) bool {\n    for _, p := range ps {\n        if !ci.contains(p) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (ci Circle) String() string { return fmt.Sprintf(\"{%v, %f}\", ci.c, ci.r) }\n\n\nfunc circleFrom3(a, b, c Point) Circle {\n    i := getCircleCenter(b.x-a.x, b.y-a.y, c.x-a.x, c.y-a.y)\n    i.x += a.x\n    i.y += a.y\n    return Circle{i, math.Sqrt(distSq(i, a))}\n}\n\n\nfunc circleFrom2(a, b Point) Circle {\n    c := Point{(a.x + b.x) / 2, (a.y + b.y) / 2}\n    return Circle{c, math.Sqrt(distSq(a, b)) / 2}\n}\n\n\nfunc secTrivial(rs []Point) Circle {\n    size := len(rs)\n    if size > 3 {\n        log.Fatal(\"There shouldn't be more than 3 points.\")\n    }\n    if size == 0 {\n        return Circle{Point{0, 0}, 0}\n    }\n    if size == 1 {\n        return Circle{rs[0], 0}\n    }\n    if size == 2 {\n        return circleFrom2(rs[0], rs[1])\n    }\n    for i := 0; i < 2; i++ {\n        for j := i + 1; j < 3; j++ {\n            c := circleFrom2(rs[i], rs[j])\n            if c.encloses(rs) {\n                return c\n            }\n        }\n    }\n    return circleFrom3(rs[0], rs[1], rs[2])\n}\n\n\nfunc welzlHelper(ps, rs []Point, n int) Circle {\n    rc := make([]Point, len(rs))\n    copy(rc, rs) \n    if n == 0 || len(rc) == 3 {\n        return secTrivial(rc)\n    }\n    idx := rand.Intn(n)\n    p := ps[idx]\n    ps[idx], ps[n-1] = ps[n-1], p\n    d := welzlHelper(ps, rc, n-1)\n    if d.contains(p) {\n        return d\n    }\n    rc = append(rc, p)\n    return welzlHelper(ps, rc, n-1)\n}\n\n\nfunc welzl(ps []Point) Circle {\n    var pc = make([]Point, len(ps))\n    copy(pc, ps)\n    rand.Shuffle(len(pc), func(i, j int) {\n        pc[i], pc[j] = pc[j], pc[i]\n    })\n    return welzlHelper(pc, []Point{}, len(pc))\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := [][]Point{\n        {Point{0, 0}, Point{0, 1}, Point{1, 0}},\n        {Point{5, -2}, Point{-3, -2}, Point{-2, 5}, Point{1, 6}, Point{0, 2}},\n    }\n    for _, test := range tests {\n        fmt.Println(welzl(test))\n    }\n}\n"}
{"id": 58609, "name": "Brace expansion using ranges", "Python": "\n\nfrom __future__ import annotations\n\nimport itertools\nimport re\n\nfrom abc import ABC\nfrom abc import abstractmethod\n\nfrom typing import Iterable\nfrom typing import Optional\n\n\nRE_SPEC = [\n    (\n        \"INT_RANGE\",\n        r\"\\{(?P<int_start>[0-9]+)..(?P<int_stop>[0-9]+)(?:(?:..)?(?P<int_step>-?[0-9]+))?}\",\n    ),\n    (\n        \"ORD_RANGE\",\n        r\"\\{(?P<ord_start>[^0-9])..(?P<ord_stop>[^0-9])(?:(?:..)?(?P<ord_step>-?[0-9]+))?}\",\n    ),\n    (\n        \"LITERAL\",\n        r\".+?(?=\\{|$)\",\n    ),\n]\n\n\nRE_EXPRESSION = re.compile(\n    \"|\".join(rf\"(?P<{name}>{pattern})\" for name, pattern in RE_SPEC)\n)\n\n\nclass Expression(ABC):\n    \n\n    @abstractmethod\n    def expand(self, prefix: str) -> Iterable[str]:\n        pass\n\n\nclass Literal(Expression):\n    \n\n    def __init__(self, value: str):\n        self.value = value\n\n    def expand(self, prefix: str) -> Iterable[str]:\n        return [f\"{prefix}{self.value}\"]\n\n\nclass IntRange(Expression):\n    \n\n    def __init__(\n        self, start: int, stop: int, step: Optional[int] = None, zfill: int = 0\n    ):\n        self.start, self.stop, self.step = fix_range(start, stop, step)\n        self.zfill = zfill\n\n    def expand(self, prefix: str) -> Iterable[str]:\n        return (\n            f\"{prefix}{str(i).zfill(self.zfill)}\"\n            for i in range(self.start, self.stop, self.step)\n        )\n\n\nclass OrdRange(Expression):\n    \n\n    def __init__(self, start: str, stop: str, step: Optional[int] = None):\n        self.start, self.stop, self.step = fix_range(ord(start), ord(stop), step)\n\n    def expand(self, prefix: str) -> Iterable[str]:\n        return (f\"{prefix}{chr(i)}\" for i in range(self.start, self.stop, self.step))\n\n\ndef expand(expressions: Iterable[Expression]) -> Iterable[str]:\n    \n    expanded = [\"\"]\n\n    for expression in expressions:\n        expanded = itertools.chain.from_iterable(\n            [expression.expand(prefix) for prefix in expanded]\n        )\n\n    return expanded\n\n\ndef zero_fill(start, stop) -> int:\n    \n\n    def _zfill(s):\n        if len(s) <= 1 or not s.startswith(\"0\"):\n            return 0\n        return len(s)\n\n    return max(_zfill(start), _zfill(stop))\n\n\ndef fix_range(start, stop, step):\n    \n    if not step:\n        \n        if start <= stop:\n            \n            step = 1\n        else:\n            \n            step = -1\n\n    elif step < 0:\n        \n        start, stop = stop, start\n\n        if start < stop:\n            step = abs(step)\n        else:\n            start -= 1\n            stop -= 1\n\n    elif start > stop:\n        \n        step = -step\n\n    \n    if (start - stop) % step == 0:\n        stop += step\n\n    return start, stop, step\n\n\ndef parse(expression: str) -> Iterable[Expression]:\n    \n    for match in RE_EXPRESSION.finditer(expression):\n        kind = match.lastgroup\n\n        if kind == \"INT_RANGE\":\n            start = match.group(\"int_start\")\n            stop = match.group(\"int_stop\")\n            step = match.group(\"int_step\")\n            zfill = zero_fill(start, stop)\n\n            if step is not None:\n                step = int(step)\n\n            yield IntRange(int(start), int(stop), step, zfill=zfill)\n\n        elif kind == \"ORD_RANGE\":\n            start = match.group(\"ord_start\")\n            stop = match.group(\"ord_stop\")\n            step = match.group(\"ord_step\")\n\n            if step is not None:\n                step = int(step)\n\n            yield OrdRange(start, stop, step)\n\n        elif kind == \"LITERAL\":\n            yield Literal(match.group())\n\n\ndef examples():\n    cases = [\n        r\"simpleNumberRising{1..3}.txt\",\n        r\"simpleAlphaDescending-{Z..X}.txt\",\n        r\"steppedDownAndPadded-{10..00..5}.txt\",\n        r\"minusSignFlipsSequence {030..20..-5}.txt\",\n        r\"reverseSteppedNumberRising{1..6..-2}.txt\",\n        r\"combined-{Q..P}{2..1}.txt\",\n        r\"emoji{🌵..🌶}{🌽..🌾}etc\",\n        r\"li{teral\",\n        r\"rangeless{}empty\",\n        r\"rangeless{random}string\",\n        \n        r\"steppedNumberRising{1..6..2}.txt\",\n        r\"steppedNumberDescending{20..9..2}.txt\",\n        r\"steppedAlphaDescending-{Z..M..2}.txt\",\n        r\"reverseSteppedAlphaRising{A..F..-2}.txt\",\n        r\"reversedSteppedAlphaDescending-{Z..M..-2}.txt\",\n    ]\n\n    for case in cases:\n        print(f\"{case} ->\")\n        expressions = parse(case)\n\n        for itm in expand(expressions):\n            print(f\"{' '*4}{itm}\")\n\n        print(\"\")  \n\n\nif __name__ == \"__main__\":\n    examples()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc sign(n int) int {\n    switch {\n    case n < 0:\n        return -1\n    case n > 0:\n        return 1\n    }\n    return 0\n}\n\nfunc abs(n int) int {\n    if n < 0 {\n        return -n\n    }\n    return n\n}\n\nfunc parseRange(r string) []string {\n    if r == \"\" {\n        return []string{\"{}\"} \n    }\n    sp := strings.Split(r, \"..\")\n    if len(sp) == 1 {\n        return []string{\"{\" + r + \"}\"} \n    }\n    sta := sp[0]\n    end := sp[1]\n    inc := \"1\"\n    if len(sp) > 2 {\n        inc = sp[2]\n    }\n    n1, ok1 := strconv.Atoi(sta)\n    n2, ok2 := strconv.Atoi(end)\n    n3, ok3 := strconv.Atoi(inc)\n    if ok3 != nil {\n        return []string{\"{\" + r + \"}\"} \n    }\n    numeric := (ok1 == nil) && (ok2 == nil)\n    if !numeric {\n        if (ok1 == nil && ok2 != nil) || (ok1 != nil && ok2 == nil) {\n            return []string{\"{\" + r + \"}\"} \n        }\n        if utf8.RuneCountInString(sta) != 1 || utf8.RuneCountInString(end) != 1 {\n            return []string{\"{\" + r + \"}\"} \n        }\n        n1 = int(([]rune(sta))[0])\n        n2 = int(([]rune(end))[0])\n    }\n    width := 1\n    if numeric {\n        if len(sta) < len(end) {\n            width = len(end)\n        } else {\n            width = len(sta)\n        }\n    }\n    if n3 == 0 { \n        if numeric {\n            return []string{fmt.Sprintf(\"%0*d\", width, n1)}\n        } else {\n            return []string{sta}\n        }\n    }\n    var res []string\n    asc := n1 < n2\n    if n3 < 0 {\n        asc = !asc\n        t := n1\n        d := abs(n1-n2) % (-n3)\n        n1 = n2 - d*sign(n2-n1)\n        n2 = t\n        n3 = -n3\n    }\n    i := n1\n    if asc {\n        for ; i <= n2; i += n3 {\n            if numeric {\n                res = append(res, fmt.Sprintf(\"%0*d\", width, i))\n            } else {\n                res = append(res, string(rune(i)))\n            }\n        }\n    } else {\n        for ; i >= n2; i -= n3 {\n            if numeric {\n                res = append(res, fmt.Sprintf(\"%0*d\", width, i))\n            } else {\n                res = append(res, string(rune(i)))\n            }\n        }\n    }\n    return res\n}\n\nfunc rangeExpand(s string) []string {\n    res := []string{\"\"}\n    rng := \"\"\n    inRng := false\n    for _, c := range s {\n        if c == '{' && !inRng {\n            inRng = true\n            rng = \"\"\n        } else if c == '}' && inRng {\n            rngRes := parseRange(rng)\n            rngLen := len(rngRes)\n            var res2 []string\n            for i := 0; i < len(res); i++ {\n                for j := 0; j < rngLen; j++ {\n                    res2 = append(res2, res[i]+rngRes[j])\n                }\n            }\n            res = res2\n            inRng = false\n        } else if inRng {\n            rng += string(c)\n        } else {\n            for i := 0; i < len(res); i++ {\n                res[i] += string(c)\n            }\n        }\n    }\n    if inRng {\n        for i := 0; i < len(res); i++ {\n            res[i] += \"{\" + rng \n        }\n    }\n    return res\n}\n\nfunc main() {\n    examples := []string{\n        \"simpleNumberRising{1..3}.txt\",\n        \"simpleAlphaDescending-{Z..X}.txt\",\n        \"steppedDownAndPadded-{10..00..5}.txt\",\n        \"minusSignFlipsSequence {030..20..-5}.txt\",\n        \"reverseSteppedNumberRising{1..6..-2}.txt\",\n        \"combined-{Q..P}{2..1}.txt\",\n        \"emoji{🌵..🌶}{🌽..🌾}etc\",\n        \"li{teral\",\n        \"rangeless{}empty\",\n        \"rangeless{random}string\",\n        \"mixedNumberAlpha{5..k}\",\n        \"steppedAlphaRising{P..Z..2}.txt\",\n        \"stops after endpoint-{02..10..3}.txt\",\n        \"steppedNumberRising{1..6..2}.txt\",\n        \"steppedNumberDescending{20..9..2}\",\n        \"steppedAlphaDescending-{Z..M..2}.txt\",\n        \"reversedSteppedAlphaDescending-{Z..M..-2}.txt\",\n    }\n    for _, s := range examples {\n        fmt.Print(s, \"->\\n    \")\n        res := rangeExpand(s)\n        fmt.Println(strings.Join(res, \"\\n    \"))\n        fmt.Println()\n    }\n}\n"}
{"id": 58610, "name": "Colour pinstripe_Printer", "Python": "from turtle import *\nfrom PIL import Image\nimport time\nimport subprocess\n\n\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\nscreen = getscreen()\n\n\n\n\ninch_width = 11.0\ninch_height = 8.5\n\npixels_per_inch = 100\n\npix_width = int(inch_width*pixels_per_inch)\npix_height = int(inch_height*pixels_per_inch)\n\nscreen.setup (width=pix_width, height=pix_height, startx=0, starty=0)\n\nscreen.screensize(pix_width,pix_height)\n\n\n\n\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nbottom_edge = -screen.window_height()//2\n\ntop_edge = screen.window_height()//2\n\n\n\nscreen.delay(0)\nscreen.tracer(5)\n\nfor inch in range(int(inch_width)-1):\n    line_width = inch + 1\n    pensize(line_width)\n    colornum = 0\n\n    min_x = left_edge + (inch * pixels_per_inch)\n    max_x = left_edge + ((inch+1) * pixels_per_inch)\n    \n    for y in range(bottom_edge,top_edge,line_width):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(min_x,y)\n        pendown()\n        setposition(max_x,y)\n         \nscreen.getcanvas().postscript(file=\"striped.eps\")\n\n\n\n\nim = Image.open(\"striped.eps\")\nim.save(\"striped.jpg\")\n\n\n    \nsubprocess.run([\"mspaint\", \"/pt\", \"striped.jpg\"])\n", "Go": "package main\n \nimport (\n    \"github.com/fogleman/gg\"\n    \"log\"\n    \"os/exec\"\n    \"runtime\"\n)\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() / 7\n    for b := 1; b <= 11; 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(842, 595)\n    pinstripe(dc)\n    fileName := \"color_pinstripe.png\"\n    dc.SavePNG(fileName)\n    var cmd *exec.Cmd\n    if runtime.GOOS == \"windows\" {\n        cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n    } else {\n        cmd = exec.Command(\"lp\", fileName)\n    }\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }   \n}\n"}
{"id": 58611, "name": "Determine sentence type", "Python": "import re\n\ntxt = \n\ndef haspunctotype(s):\n    return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N'\n\ntxt = re.sub('\\n', '', txt)\npars = [s.strip() for s in re.split(\"(?:(?:(?<=[\\?\\!\\.])(?:))|(?:(?:)(?=[\\?\\!\\.])))\", txt)]\nif len(pars) % 2:\n    pars.append('')  \nfor i in range(0, len(pars)-1, 2):\n    print((pars[i] + pars[i + 1]).ljust(54), \"==>\", haspunctotype(pars[i + 1]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc sentenceType(s string) string {\n    if len(s) == 0 {\n        return \"\"\n    }\n    var types []string\n    for _, c := range s {\n        if c == '?' {\n            types = append(types, \"Q\")\n        } else if c == '!' {\n            types = append(types, \"E\")\n        } else if c == '.' {\n            types = append(types, \"S\")\n        }\n    }\n    if strings.IndexByte(\"?!.\", s[len(s)-1]) == -1 {\n        types = append(types, \"N\")\n    }\n    return strings.Join(types, \"|\")\n}\n\nfunc main() {\n    s := \"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it\"\n    fmt.Println(sentenceType(s))\n}\n"}
{"id": 58612, "name": "Long literals, with continuations", "Python": "\n\nrevision = \"October 13th 2020\"\n\n\n\n\nelements = (\n    \"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine \"\n    \"neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon \"\n    \"potassium calcium scandium titanium vanadium chromium manganese iron \"\n    \"cobalt nickel copper zinc gallium germanium arsenic selenium bromine \"\n    \"krypton rubidium strontium yttrium zirconium niobium molybdenum \"\n    \"technetium ruthenium rhodium palladium silver cadmium indium tin \"\n    \"antimony tellurium iodine xenon cesium barium lanthanum cerium \"\n    \"praseodymium neodymium promethium samarium europium gadolinium terbium \"\n    \"dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum \"\n    \"tungsten rhenium osmium iridium platinum gold mercury thallium lead \"\n    \"bismuth polonium astatine radon francium radium actinium thorium \"\n    \"protactinium uranium neptunium plutonium americium curium berkelium \"\n    \"californium einsteinium fermium mendelevium nobelium lawrencium \"\n    \"rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium \"\n    \"roentgenium copernicium nihonium flerovium moscovium livermorium \"\n    \"tennessine oganesson\"\n)\n\n\ndef report():\n    \n    items = elements.split()\n\n    print(f\"Last revision date: {revision}\")\n    print(f\"Number of elements: {len(items)}\")\n    print(f\"Last element      : {items[-1]}\")\n\n\nif __name__ == \"__main__\":\n    report()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\n\n\n\nvar elements = `\n    hydrogen     helium        lithium      beryllium\n    boron        carbon        nitrogen     oxygen\n    fluorine     neon          sodium       magnesium\n    aluminum     silicon       phosphorous  sulfur\n    chlorine     argon         potassium    calcium\n    scandium     titanium      vanadium     chromium\n    manganese    iron          cobalt       nickel\n    copper       zinc          gallium      germanium\n    arsenic      selenium      bromine      krypton\n    rubidium     strontium     yttrium      zirconium\n    niobium      molybdenum    technetium   ruthenium\n    rhodium      palladium     silver       cadmium\n    indium       tin           antimony     tellurium\n    iodine       xenon         cesium       barium\n    lanthanum    cerium        praseodymium neodymium\n    promethium   samarium      europium     gadolinium\n    terbium      dysprosium    holmium      erbium\n    thulium      ytterbium     lutetium     hafnium\n    tantalum     tungsten      rhenium      osmium\n    iridium      platinum      gold         mercury\n    thallium     lead          bismuth      polonium\n    astatine     radon         francium     radium\n    actinium     thorium       protactinium uranium\n    neptunium    plutonium     americium    curium\n    berkelium    californium   einsteinium  fermium\n    mendelevium  nobelium      lawrencium   rutherfordium\n    dubnium      seaborgium    bohrium      hassium\n    meitnerium   darmstadtium  roentgenium  copernicium\n    nihonium     flerovium     moscovium    livermorium\n    tennessine   oganesson\n`\n\nfunc main() {\n    lastRevDate := \"March 24th, 2020\"\n    re := regexp.MustCompile(`\\s+`) \n    els := re.Split(strings.TrimSpace(elements), -1)\n    numEls := len(els)\n    \n    elements2 := strings.Join(els, \" \")\n    \n    fmt.Println(\"Last revision Date: \", lastRevDate)\n    fmt.Println(\"Number of elements: \", numEls)\n    \n    \n    lix := strings.LastIndex(elements2, \" \") \n    fmt.Println(\"Last element      : \", elements2[lix+1:])\n}\n"}
{"id": 58613, "name": "Set right-adjacent bits", "Python": "from operator import or_\nfrom functools import reduce\n\ndef set_right_adjacent_bits(n: int, b: int) -> int:\n    return reduce(or_, (b >> x for x in range(n+1)), 0)\n\n\nif __name__ == \"__main__\":\n    print(\"SAME n & Width.\\n\")\n    n = 2  \n    bits = \"1000 0100 0010 0000\"\n    first = True\n    for b_str in bits.split():\n        b = int(b_str, 2)\n        e = len(b_str)\n        if first:\n            first = False\n            print(f\"n = {n}; Width e = {e}:\\n\")\n        result = set_right_adjacent_bits(n, b)\n        print(f\"     Input b: {b:0{e}b}\")\n        print(f\"      Result: {result:0{e}b}\\n\")\n        \n    print(\"SAME Input & Width.\\n\")\n    \n    bits = '01' + '1'.join('0'*x for x in range(10, 0, -1))\n    for n in range(4):\n        first = True\n        for b_str in bits.split():\n            b = int(b_str, 2)\n            e = len(b_str)\n            if first:\n                first = False\n                print(f\"n = {n}; Width e = {e}:\\n\")\n            result = set_right_adjacent_bits(n, b)\n            print(f\"     Input b: {b:0{e}b}\")\n            print(f\"      Result: {result:0{e}b}\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype test struct {\n    bs string\n    n  int\n}\n\nfunc setRightBits(bits []byte, e, n int) []byte {\n    if e == 0 || n <= 0 {\n        return bits\n    }\n    bits2 := make([]byte, len(bits))\n    copy(bits2, bits)\n    for i := 0; i < e-1; i++ {\n        c := bits[i]\n        if c == 1 {\n            j := i + 1\n            for j <= i+n && j < e {\n                bits2[j] = 1\n                j++\n            }\n        }\n    }\n    return bits2\n}\n\nfunc main() {\n    b := \"010000000000100000000010000000010000000100000010000010000100010010\"\n    tests := []test{\n        test{\"1000\", 2}, test{\"0100\", 2}, test{\"0010\", 2}, test{\"0000\", 2},\n        test{b, 0}, test{b, 1}, test{b, 2}, test{b, 3},\n    }\n    for _, test := range tests {\n        bs := test.bs\n        e := len(bs)\n        n := test.n\n        fmt.Println(\"n =\", n, \"\\b; Width e =\", e, \"\\b:\")\n        fmt.Println(\"    Input b:\", bs)\n        bits := []byte(bs)\n        for i := 0; i < len(bits); i++ {\n            bits[i] = bits[i] - '0'\n        }\n        bits = setRightBits(bits, e, n)\n        var sb strings.Builder\n        for i := 0; i < len(bits); i++ {\n            sb.WriteByte(bits[i] + '0')\n        }\n        fmt.Println(\"    Result :\", sb.String())\n    }\n}\n"}
{"id": 58614, "name": "Cubic special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n"}
{"id": 58615, "name": "Cubic special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n"}
{"id": 58616, "name": "Cubic special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n"}
{"id": 58617, "name": "Cubic special primes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\nif __name__ == '__main__':\n    p = 2\n    n = 1\n\n    print(\"2\",end = \" \")\n    while True:\n        if isPrime(p + n**3):\n            p += n**3\n            n = 1\n            print(p,end = \" \")\n        else:\n            n += 1\n        if p + n**3 >= 15000:\n            break\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\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 isCube(n int) bool {\n    s := int(math.Cbrt(float64(n)))\n    return s*s*s == n\n}\n\nfunc commas(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(14999)\n    fmt.Println(\"Cubic special primes under 15,000:\")\n    fmt.Println(\" Prime1  Prime2    Gap  Cbrt\")\n    lastCubicSpecial := 3\n    gap := 1\n    count := 1\n    fmt.Printf(\"%7d %7d %6d %4d\\n\", 2, 3, 1, 1)\n    for i := 5; i < 15000; i += 2 {\n        if c[i] {\n            continue\n        }\n        gap = i - lastCubicSpecial\n        if isCube(gap) {\n            cbrt := int(math.Cbrt(float64(gap)))\n            fmt.Printf(\"%7s %7s %6s %4d\\n\", commas(lastCubicSpecial), commas(i), commas(gap), cbrt)\n            lastCubicSpecial = i\n            count++\n        }\n    }\n    fmt.Println(\"\\n\", count+1, \"such primes found.\")\n}\n"}
{"id": 58618, "name": "Geohash", "Python": "ch32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\nbool2ch = {f\"{i:05b}\": ch for i, ch in enumerate(ch32)}\nch2bool = {v : k for k, v in bool2ch.items()}\n\ndef bisect(val, mn, mx, bits):\n    mid = (mn + mx) / 2\n    if val < mid:\n        bits <<= 1                        \n        mx = mid                          \n    else:\n        bits = bits << 1 | 1              \n        mn = mid                          \n\n    return mn, mx, bits\n\ndef encoder(lat, lng, pre):\n    latmin, latmax = -90, 90\n    lngmin, lngmax = -180, 180\n    bits = 0\n    for i in range(pre * 5):\n        if i % 2:\n            \n            latmin, latmax, bits = bisect(lat, latmin, latmax, bits)\n        else:\n            \n            lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits)\n    \n    b = f\"{bits:0{pre * 5}b}\"\n    geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre))\n\n    return ''.join(geo)\n\ndef decoder(geo):\n    minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True\n    for c in geo:\n        for bit in ch2bool[c]:\n            minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2\n            latlong = not latlong\n\n    return minmaxes\n\nif __name__ == '__main__':\n    for (lat, lng), pre in [([51.433718, -0.214126],  2),\n                            ([51.433718, -0.214126],  9),\n                            ([57.64911,  10.40744] , 11),\n                            ([57.64911,  10.40744] , 22)]:\n        print(\"encoder(lat=%f, lng=%f, pre=%i) = %r\"\n              % (lat, lng, pre, encoder(lat, lng, pre)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype Location struct{ lat, lng float64 }\n\nfunc (loc Location) String() string { return fmt.Sprintf(\"[%f, %f]\", loc.lat, loc.lng) }\n\ntype Range struct{ lower, upper float64 }\n\nvar gBase32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\n\nfunc encodeGeohash(loc Location, prec int) string {\n    latRange := Range{-90, 90}\n    lngRange := Range{-180, 180}\n    var hash strings.Builder\n    hashVal := 0\n    bits := 0\n    even := true\n    for hash.Len() < prec {\n        val := loc.lat\n        rng := latRange\n        if even {\n            val = loc.lng\n            rng = lngRange\n        }\n        mid := (rng.lower + rng.upper) / 2\n        if val > mid {\n            hashVal = (hashVal << 1) + 1\n            rng = Range{mid, rng.upper}\n            if even {\n                lngRange = Range{mid, lngRange.upper}\n            } else {\n                latRange = Range{mid, latRange.upper}\n            }\n        } else {\n            hashVal <<= 1\n            if even {\n                lngRange = Range{lngRange.lower, mid}\n            } else {\n                latRange = Range{latRange.lower, mid}\n            }\n        }\n        even = !even\n        if bits < 4 {\n            bits++\n        } else {\n            bits = 0\n            hash.WriteByte(gBase32[hashVal])\n            hashVal = 0\n        }\n    }\n    return hash.String()\n}\n\nfunc main() {\n    locs := []Location{\n        {51.433718, -0.214126},\n        {51.433718, -0.214126},\n        {57.64911, 10.40744},\n    }\n    precs := []int{2, 9, 11}\n\n    for i, loc := range locs {\n        geohash := encodeGeohash(loc, precs[i])\n        fmt.Printf(\"geohash for %v, precision %-2d = %s\\n\", loc, precs[i], geohash)\n    }\n}\n"}
{"id": 58619, "name": "Geohash", "Python": "ch32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\nbool2ch = {f\"{i:05b}\": ch for i, ch in enumerate(ch32)}\nch2bool = {v : k for k, v in bool2ch.items()}\n\ndef bisect(val, mn, mx, bits):\n    mid = (mn + mx) / 2\n    if val < mid:\n        bits <<= 1                        \n        mx = mid                          \n    else:\n        bits = bits << 1 | 1              \n        mn = mid                          \n\n    return mn, mx, bits\n\ndef encoder(lat, lng, pre):\n    latmin, latmax = -90, 90\n    lngmin, lngmax = -180, 180\n    bits = 0\n    for i in range(pre * 5):\n        if i % 2:\n            \n            latmin, latmax, bits = bisect(lat, latmin, latmax, bits)\n        else:\n            \n            lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits)\n    \n    b = f\"{bits:0{pre * 5}b}\"\n    geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre))\n\n    return ''.join(geo)\n\ndef decoder(geo):\n    minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True\n    for c in geo:\n        for bit in ch2bool[c]:\n            minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2\n            latlong = not latlong\n\n    return minmaxes\n\nif __name__ == '__main__':\n    for (lat, lng), pre in [([51.433718, -0.214126],  2),\n                            ([51.433718, -0.214126],  9),\n                            ([57.64911,  10.40744] , 11),\n                            ([57.64911,  10.40744] , 22)]:\n        print(\"encoder(lat=%f, lng=%f, pre=%i) = %r\"\n              % (lat, lng, pre, encoder(lat, lng, pre)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype Location struct{ lat, lng float64 }\n\nfunc (loc Location) String() string { return fmt.Sprintf(\"[%f, %f]\", loc.lat, loc.lng) }\n\ntype Range struct{ lower, upper float64 }\n\nvar gBase32 = \"0123456789bcdefghjkmnpqrstuvwxyz\"\n\nfunc encodeGeohash(loc Location, prec int) string {\n    latRange := Range{-90, 90}\n    lngRange := Range{-180, 180}\n    var hash strings.Builder\n    hashVal := 0\n    bits := 0\n    even := true\n    for hash.Len() < prec {\n        val := loc.lat\n        rng := latRange\n        if even {\n            val = loc.lng\n            rng = lngRange\n        }\n        mid := (rng.lower + rng.upper) / 2\n        if val > mid {\n            hashVal = (hashVal << 1) + 1\n            rng = Range{mid, rng.upper}\n            if even {\n                lngRange = Range{mid, lngRange.upper}\n            } else {\n                latRange = Range{mid, latRange.upper}\n            }\n        } else {\n            hashVal <<= 1\n            if even {\n                lngRange = Range{lngRange.lower, mid}\n            } else {\n                latRange = Range{latRange.lower, mid}\n            }\n        }\n        even = !even\n        if bits < 4 {\n            bits++\n        } else {\n            bits = 0\n            hash.WriteByte(gBase32[hashVal])\n            hashVal = 0\n        }\n    }\n    return hash.String()\n}\n\nfunc main() {\n    locs := []Location{\n        {51.433718, -0.214126},\n        {51.433718, -0.214126},\n        {57.64911, 10.40744},\n    }\n    precs := []int{2, 9, 11}\n\n    for i, loc := range locs {\n        geohash := encodeGeohash(loc, precs[i])\n        fmt.Printf(\"geohash for %v, precision %-2d = %s\\n\", loc, precs[i], geohash)\n    }\n}\n"}
{"id": 58620, "name": "Natural sorting", "Python": "\n\n\n\nfrom itertools import groupby\nfrom unicodedata import decomposition, name\nfrom pprint import pprint as pp\n\ncommonleaders = ['the'] \nreplacements = {u'ß': 'ss',  \n                u'ſ': 's',\n                u'ʒ': 's',\n                }\n\nhexdigits = set('0123456789abcdef')\ndecdigits = set('0123456789')   \n\ndef splitchar(c):\n    ' De-ligature. De-accent a char'\n    de = decomposition(c)\n    if de:\n        \n        de = [d for d in de.split()\n                  if all(c.lower()\n                         in hexdigits for c in d)]\n        n = name(c, c).upper()\n        \n        if len(de)> 1 and 'PRECEDE' in n:\n            \n            de[1], de[0] = de[0], de[1]\n        tmp = [ unichr(int(k, 16)) for k in de]\n        base, others = tmp[0], tmp[1:]\n        if 'LIGATURE' in n:\n            \n            base += others.pop(0)\n    else:\n        base = c\n    return base\n    \n\ndef sortkeygen(s):\n    \n    \n    s = unicode(s).strip()\n    \n    s = ' '.join(s.split())\n    \n    s = s.lower()\n    \n    words = s.split()\n    if len(words) > 1 and words[0] in commonleaders:\n        s = ' '.join( words[1:])\n    \n    s = ''.join(splitchar(c) for c in s)\n    \n    s = ''.join( replacements.get(ch, ch) for ch in s )\n    \n    s = [ int(\"\".join(g)) if isinteger else \"\".join(g)\n          for isinteger,g in groupby(s, lambda x: x in decdigits)]\n\n    return s\n\ndef naturalsort(items):\n    \n    return sorted(items, key=sortkeygen)\n\nif __name__ == '__main__':\n    import string\n    \n    ns = naturalsort\n\n    print '\\n\n    txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3)\n           for i,ch in enumerate(reversed(string.whitespace))]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    s = 'CASE INDEPENENT'\n    txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt',\n           'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['The Wind in the Willows','The 40th step more',\n                         'The 39 steps', 'Wanda']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv. %s accents: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(u'\\xfd\\xddyY')]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = [u'\\462 ligatured ij', 'no ligature',]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n    \n    print '\\n\n    s = u'ʒſßs' \n    txt = ['Start with an %s: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(s)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; print '\\n'.join(sorted(txt))\n    print 'Naturally sorted:'; print '\\n'.join(ns(txt))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar tests = []struct {\n    descr string\n    list  []string\n}{\n    {\"Ignoring leading spaces\", []string{\n        \"ignore leading spaces: 2-2\",\n        \" ignore leading spaces: 2-1\",\n        \"  ignore leading spaces: 2+0\",\n        \"   ignore leading spaces: 2+1\",\n    }},\n    {\"Ignoring multiple adjacent spaces\", []string{\n        \"ignore m.a.s spaces: 2-2\",\n        \"ignore m.a.s  spaces: 2-1\",\n        \"ignore m.a.s   spaces: 2+0\",\n        \"ignore m.a.s    spaces: 2+1\",\n    }},\n    {\"Equivalent whitespace characters\", []string{\n        \"Equiv. spaces: 3-3\",\n        \"Equiv.\\rspaces: 3-2\",\n        \"Equiv.\\fspaces: 3-1\",\n        \"Equiv.\\bspaces: 3+0\",\n        \"Equiv.\\nspaces: 3+1\",\n        \"Equiv.\\tspaces: 3+2\",\n    }},\n    {\"Case Indepenent sort\", []string{\n        \"cASE INDEPENENT: 3-2\",\n        \"caSE INDEPENENT: 3-1\",\n        \"casE INDEPENENT: 3+0\",\n        \"case INDEPENENT: 3+1\",\n    }},\n    {\"Numeric fields as numerics\", []string{\n        \"foo100bar99baz0.txt\",\n        \"foo100bar10baz0.txt\",\n        \"foo1000bar99baz10.txt\",\n        \"foo1000bar99baz9.txt\",\n    }},\n}\n\nfunc main() {\n    for _, test := range tests {\n        fmt.Println(test.descr)\n        fmt.Println(\"Input order:\")\n        for _, s := range test.list {\n            fmt.Printf(\"   %q\\n\", s)\n        }\n        fmt.Println(\"Natural order:\")\n        l := make(list, len(test.list))\n        for i, s := range test.list {\n            l[i] = newNatStr(s)\n        }\n        sort.Sort(l)\n        for _, s := range l {\n            fmt.Printf(\"   %q\\n\", s.s)\n        }\n        fmt.Println()\n    }\n}\n\n\ntype natStr struct {\n    s string \n    t []tok  \n}\n\nfunc newNatStr(s string) (t natStr) {\n    t.s = s\n    s = strings.ToLower(strings.Join(strings.Fields(s), \" \"))\n    x := dx.FindAllString(s, -1)\n    t.t = make([]tok, len(x))\n    for i, s := range x {\n        if n, err := strconv.Atoi(s); err == nil {\n            t.t[i].n = n\n        } else {\n            t.t[i].s = s\n        }\n    }\n    return t\n}\n\nvar dx = regexp.MustCompile(`\\d+|\\D+`)\n\n\ntype tok struct {\n    s string\n    n int\n}\n\n\nfunc (f1 tok) Cmp(f2 tok) int {\n    switch {\n    case f1.s == \"\":\n        switch {\n        case f2.s > \"\" || f1.n < f2.n:\n            return -1\n        case f1.n > f2.n:\n            return 1\n        }\n    case f2.s == \"\" || f1.s > f2.s:\n        return 1\n    case f1.s < f2.s:\n        return -1\n    }\n    return 0\n}\n\ntype list []natStr\n\nfunc (l list) Len() int      { return len(l) }\nfunc (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] }\nfunc (l list) Less(i, j int) bool {\n    ti := l[i].t\n    for k, t := range l[j].t {\n        if k == len(ti) {\n            return true\n        }\n        switch ti[k].Cmp(t) {\n        case -1:\n            return true\n        case 1:\n            return false\n        }\n    }\n    return false\n}\n"}
{"id": 58621, "name": "Natural sorting", "Python": "\n\n\n\nfrom itertools import groupby\nfrom unicodedata import decomposition, name\nfrom pprint import pprint as pp\n\ncommonleaders = ['the'] \nreplacements = {u'ß': 'ss',  \n                u'ſ': 's',\n                u'ʒ': 's',\n                }\n\nhexdigits = set('0123456789abcdef')\ndecdigits = set('0123456789')   \n\ndef splitchar(c):\n    ' De-ligature. De-accent a char'\n    de = decomposition(c)\n    if de:\n        \n        de = [d for d in de.split()\n                  if all(c.lower()\n                         in hexdigits for c in d)]\n        n = name(c, c).upper()\n        \n        if len(de)> 1 and 'PRECEDE' in n:\n            \n            de[1], de[0] = de[0], de[1]\n        tmp = [ unichr(int(k, 16)) for k in de]\n        base, others = tmp[0], tmp[1:]\n        if 'LIGATURE' in n:\n            \n            base += others.pop(0)\n    else:\n        base = c\n    return base\n    \n\ndef sortkeygen(s):\n    \n    \n    s = unicode(s).strip()\n    \n    s = ' '.join(s.split())\n    \n    s = s.lower()\n    \n    words = s.split()\n    if len(words) > 1 and words[0] in commonleaders:\n        s = ' '.join( words[1:])\n    \n    s = ''.join(splitchar(c) for c in s)\n    \n    s = ''.join( replacements.get(ch, ch) for ch in s )\n    \n    s = [ int(\"\".join(g)) if isinteger else \"\".join(g)\n          for isinteger,g in groupby(s, lambda x: x in decdigits)]\n\n    return s\n\ndef naturalsort(items):\n    \n    return sorted(items, key=sortkeygen)\n\nif __name__ == '__main__':\n    import string\n    \n    ns = naturalsort\n\n    print '\\n\n    txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3)\n           for i,ch in enumerate(reversed(string.whitespace))]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    s = 'CASE INDEPENENT'\n    txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt',\n           'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['The Wind in the Willows','The 40th step more',\n                         'The 39 steps', 'Wanda']\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = ['Equiv. %s accents: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(u'\\xfd\\xddyY')]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n\n    print '\\n\n    txt = [u'\\462 ligatured ij', 'no ligature',]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; pp(sorted(txt))\n    print 'Naturally sorted:'; pp(ns(txt))\n    \n    print '\\n\n    s = u'ʒſßs' \n    txt = ['Start with an %s: 2%+i' % (ch, i-2)\n           for i,ch in enumerate(s)]\n    print 'Text strings:'; pp(txt)\n    print 'Normally sorted :'; print '\\n'.join(sorted(txt))\n    print 'Naturally sorted:'; print '\\n'.join(ns(txt))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar tests = []struct {\n    descr string\n    list  []string\n}{\n    {\"Ignoring leading spaces\", []string{\n        \"ignore leading spaces: 2-2\",\n        \" ignore leading spaces: 2-1\",\n        \"  ignore leading spaces: 2+0\",\n        \"   ignore leading spaces: 2+1\",\n    }},\n    {\"Ignoring multiple adjacent spaces\", []string{\n        \"ignore m.a.s spaces: 2-2\",\n        \"ignore m.a.s  spaces: 2-1\",\n        \"ignore m.a.s   spaces: 2+0\",\n        \"ignore m.a.s    spaces: 2+1\",\n    }},\n    {\"Equivalent whitespace characters\", []string{\n        \"Equiv. spaces: 3-3\",\n        \"Equiv.\\rspaces: 3-2\",\n        \"Equiv.\\fspaces: 3-1\",\n        \"Equiv.\\bspaces: 3+0\",\n        \"Equiv.\\nspaces: 3+1\",\n        \"Equiv.\\tspaces: 3+2\",\n    }},\n    {\"Case Indepenent sort\", []string{\n        \"cASE INDEPENENT: 3-2\",\n        \"caSE INDEPENENT: 3-1\",\n        \"casE INDEPENENT: 3+0\",\n        \"case INDEPENENT: 3+1\",\n    }},\n    {\"Numeric fields as numerics\", []string{\n        \"foo100bar99baz0.txt\",\n        \"foo100bar10baz0.txt\",\n        \"foo1000bar99baz10.txt\",\n        \"foo1000bar99baz9.txt\",\n    }},\n}\n\nfunc main() {\n    for _, test := range tests {\n        fmt.Println(test.descr)\n        fmt.Println(\"Input order:\")\n        for _, s := range test.list {\n            fmt.Printf(\"   %q\\n\", s)\n        }\n        fmt.Println(\"Natural order:\")\n        l := make(list, len(test.list))\n        for i, s := range test.list {\n            l[i] = newNatStr(s)\n        }\n        sort.Sort(l)\n        for _, s := range l {\n            fmt.Printf(\"   %q\\n\", s.s)\n        }\n        fmt.Println()\n    }\n}\n\n\ntype natStr struct {\n    s string \n    t []tok  \n}\n\nfunc newNatStr(s string) (t natStr) {\n    t.s = s\n    s = strings.ToLower(strings.Join(strings.Fields(s), \" \"))\n    x := dx.FindAllString(s, -1)\n    t.t = make([]tok, len(x))\n    for i, s := range x {\n        if n, err := strconv.Atoi(s); err == nil {\n            t.t[i].n = n\n        } else {\n            t.t[i].s = s\n        }\n    }\n    return t\n}\n\nvar dx = regexp.MustCompile(`\\d+|\\D+`)\n\n\ntype tok struct {\n    s string\n    n int\n}\n\n\nfunc (f1 tok) Cmp(f2 tok) int {\n    switch {\n    case f1.s == \"\":\n        switch {\n        case f2.s > \"\" || f1.n < f2.n:\n            return -1\n        case f1.n > f2.n:\n            return 1\n        }\n    case f2.s == \"\" || f1.s > f2.s:\n        return 1\n    case f1.s < f2.s:\n        return -1\n    }\n    return 0\n}\n\ntype list []natStr\n\nfunc (l list) Len() int      { return len(l) }\nfunc (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] }\nfunc (l list) Less(i, j int) bool {\n    ti := l[i].t\n    for k, t := range l[j].t {\n        if k == len(ti) {\n            return true\n        }\n        switch ti[k].Cmp(t) {\n        case -1:\n            return true\n        case 1:\n            return false\n        }\n    }\n    return false\n}\n"}
{"id": 58622, "name": "Positive decimal integers with the digit 1 occurring exactly twice", "Python": "\n\nfrom itertools import permutations\n\nfor i in range(0,10):\n    if i!=1:\n        baseList = [1,1]\n        baseList.append(i)\n        [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Decimal numbers under 1,000 whose digits include two 1's:\")\n    var results []int\n    for i := 11; i <= 911; i++ {\n        digits := rcu.Digits(i, 10)\n        count := 0\n        for _, d := range digits {\n            if d == 1 {\n                count++\n            }\n        }\n        if count == 2 {\n            results = append(results, i)\n        }\n    }\n    for i, n := range results {\n        fmt.Printf(\"%5d\", n)\n        if (i+1)%7 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such numbers.\")\n}\n"}
{"id": 58623, "name": "Positive decimal integers with the digit 1 occurring exactly twice", "Python": "\n\nfrom itertools import permutations\n\nfor i in range(0,10):\n    if i!=1:\n        baseList = [1,1]\n        baseList.append(i)\n        [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Decimal numbers under 1,000 whose digits include two 1's:\")\n    var results []int\n    for i := 11; i <= 911; i++ {\n        digits := rcu.Digits(i, 10)\n        count := 0\n        for _, d := range digits {\n            if d == 1 {\n                count++\n            }\n        }\n        if count == 2 {\n            results = append(results, i)\n        }\n    }\n    for i, n := range results {\n        fmt.Printf(\"%5d\", n)\n        if (i+1)%7 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(results), \"such numbers.\")\n}\n"}
{"id": 58624, "name": "Odd and square numbers", "Python": "import math\nszamok=[]\nlimit = 1000\n\nfor i in range(1,int(math.ceil(math.sqrt(limit))),2):\n    num = i*i\n    if (num < 1000 and num > 99):\n        szamok.append(num)\n\nprint(szamok)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    pow := 1\n    for p := 0; p < 5; p++ {\n        low := int(math.Ceil(math.Sqrt(float64(pow))))\n        if low%2 == 0 {\n            low++\n        }\n        pow *= 10\n        high := int(math.Sqrt(float64(pow)))\n        var oddSq []int\n        for i := low; i <= high; i += 2 {\n            oddSq = append(oddSq, i*i)\n        }\n        fmt.Println(len(oddSq), \"odd squares from\", pow/10, \"to\", pow, \"\\b:\")\n        for i := 0; i < len(oddSq); i++ {\n            fmt.Printf(\"%d \", oddSq[i])\n            if (i+1)%10 == 0 {\n                fmt.Println()\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 58625, "name": "Odd and square numbers", "Python": "import math\nszamok=[]\nlimit = 1000\n\nfor i in range(1,int(math.ceil(math.sqrt(limit))),2):\n    num = i*i\n    if (num < 1000 and num > 99):\n        szamok.append(num)\n\nprint(szamok)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    pow := 1\n    for p := 0; p < 5; p++ {\n        low := int(math.Ceil(math.Sqrt(float64(pow))))\n        if low%2 == 0 {\n            low++\n        }\n        pow *= 10\n        high := int(math.Sqrt(float64(pow)))\n        var oddSq []int\n        for i := low; i <= high; i += 2 {\n            oddSq = append(oddSq, i*i)\n        }\n        fmt.Println(len(oddSq), \"odd squares from\", pow/10, \"to\", pow, \"\\b:\")\n        for i := 0; i < len(oddSq); i++ {\n            fmt.Printf(\"%d \", oddSq[i])\n            if (i+1)%10 == 0 {\n                fmt.Println()\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 58626, "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++": "#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": 58627, "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++": "#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": 58628, "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++": "#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": 58629, "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++": "#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": 58630, "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++": "#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": 58631, "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++": "#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": 58632, "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++": "#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": 58633, "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", "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": 58634, "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", "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": 58635, "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", "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": 58636, "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", "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": 58637, "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", "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": 58638, "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++": "#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": 58639, "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++": "#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": 58640, "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++": "#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": 58641, "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++": "#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": 58642, "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++": "#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": 58643, "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", "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": 58644, "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", "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": 58645, "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", "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": 58646, "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", "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": 58647, "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", "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": 58648, "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++": "#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": 58649, "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++": "#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": 58650, "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", "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": 58651, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 58652, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 58653, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 58654, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\n", "C++": "#include <Rcpp.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nusing namespace Rcpp ;\n\n\nCharacterVector getNameInfo(std::string fqdn) {\n\n  struct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n  memset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;\n\thints.ai_socktype = SOCK_DGRAM;\n\n\terror = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);\n\tif (error) { return(NA_STRING);\t}\n\n  int i = 0 ;\n\tfor (res = res0; res; res = res->ai_next) {\n  \terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { i++ ; }\n\t}\n\n  CharacterVector results(i) ;\n\n  i = 0;\n\n  for (res = res0; res; res = res->ai_next) {\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\t\tif (!error) { results[i++] = host ; }\n\t}\n\n  freeaddrinfo(res0);\n\n  return(results) ;\n\n}\n"}
{"id": 58655, "name": "Peano curve", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\n", "C++": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass peano_curve {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid peano_curve::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = length;\n    y_ = length;\n    angle_ = 90;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"L\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string peano_curve::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        switch (c) {\n        case 'L':\n            t += \"LFRFL-F-RFLFR+F+LFRFL\";\n            break;\n        case 'R':\n            t += \"RFLFR+F+LFRFL-F-RFLFR\";\n            break;\n        default:\n            t += c;\n            break;\n        }\n    }\n    return t;\n}\n\nvoid peano_curve::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid peano_curve::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"peano_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    peano_curve pc;\n    pc.write(out, 656, 8, 4);\n    return 0;\n}\n"}
{"id": 58656, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\n", "C++": "template<typename F> class fivetoseven\n{\npublic:\n  fivetoseven(F f): d5(f), rem(0), max(1) {}\n  int operator()();\nprivate:\n  F d5;\n  int rem, max;\n};\n\ntemplate<typename F>\n int fivetoseven<F>::operator()()\n{\n  while (rem/7 == max/7)\n  {\n    while (max < 7)\n    {\n      int rand5 = d5()-1;\n      max *= 5;\n      rem = 5*rem + rand5;\n    }\n\n    int groups = max / 7;\n    if (rem >= 7*groups)\n    {\n      rem -= 7*groups;\n      max -= 7*groups;\n    }\n  }\n\n  int result = rem % 7;\n  rem /= 7;\n  max /= 7;\n  return result+1;\n}\n\nint d5()\n{\n  return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;\n}\n\nfivetoseven<int(*)()> d7(d5);\n\nint main()\n{\n  srand(time(0));\n  test_distribution(d5, 1000000, 0.001);\n  test_distribution(d7, 1000000, 0.001);\n}\n"}
{"id": 58657, "name": "Magnanimous numbers", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\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\nbool is_magnanimous(unsigned int n) {\n    for (unsigned int p = 10; n >= p; p *= 10) {\n        if (!is_prime(n % p + n / p))\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    unsigned int count = 0, n = 0;\n    std::cout << \"First 45 magnanimous numbers:\\n\";\n    for (; count < 45; ++n) {\n        if (is_magnanimous(n)) {\n            if (count > 0)\n                std::cout << (count % 15 == 0 ? \"\\n\" : \", \");\n            std::cout << std::setw(3) << n;\n            ++count;\n        }\n    }\n    std::cout << \"\\n\\n241st through 250th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 250; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 240) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << \"\\n\\n391st through 400th magnanimous numbers:\\n\";\n    for (unsigned int i = 0; count < 400; ++n) {\n        if (is_magnanimous(n)) {\n            if (count++ >= 390) {\n                if (i++ > 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 58658, "name": "Extensible prime generator", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\n", "C++": "#include <iostream>\n#include <cstdint>\n#include <queue>\n#include <utility>\n#include <vector>\n#include <limits>\n\ntemplate<typename integer>\nclass prime_generator {\npublic:\n    integer next_prime();\n    integer count() const {\n        return count_;\n    }\nprivate:\n    struct queue_item {\n        queue_item(integer prime, integer multiple, unsigned int wheel_index) :\n            prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}\n        integer prime_;\n        integer multiple_;\n        unsigned int wheel_index_;\n    };\n    struct cmp {\n        bool operator()(const queue_item& a, const queue_item& b) const {\n            return a.multiple_ > b.multiple_;\n        }\n    };\n    static integer wheel_next(unsigned int& index) {\n        integer offset = wheel_[index];\n        ++index;\n        if (index == std::size(wheel_))\n            index = 0;\n        return offset;\n    }\n    typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;\n    integer next_ = 11;\n    integer count_ = 0;\n    queue queue_;\n    unsigned int wheel_index_ = 0;\n    static const unsigned int wheel_[];\n    static const integer primes_[];\n};\n\ntemplate<typename integer>\nconst unsigned int prime_generator<integer>::wheel_[] = {\n    2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,\n    6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,\n    2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10\n};\n\ntemplate<typename integer>\nconst integer prime_generator<integer>::primes_[] = {\n    2, 3, 5, 7\n};\n\ntemplate<typename integer>\ninteger prime_generator<integer>::next_prime() {\n    if (count_ < std::size(primes_))\n        return primes_[count_++];\n    integer n = next_;\n    integer prev = 0;\n    while (!queue_.empty()) {\n        queue_item item = queue_.top();\n        if (prev != 0 && prev != item.multiple_)\n            n += wheel_next(wheel_index_);\n        if (item.multiple_ > n)\n            break;\n        else if (item.multiple_ == n) {\n            queue_.pop();\n            queue_item new_item(item);\n            new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);\n            queue_.push(new_item);\n        }\n        else\n            throw std::overflow_error(\"prime_generator: overflow!\");\n        prev = item.multiple_;\n    }\n    if (std::numeric_limits<integer>::max()/n > n)\n        queue_.emplace(n, n * n, wheel_index_);\n    next_ = n + wheel_next(wheel_index_);\n    ++count_;\n    return n;\n}\n\nint main() {\n    typedef uint32_t integer;\n    prime_generator<integer> pgen;\n    std::cout << \"First 20 primes:\\n\";\n    for (int i = 0; i < 20; ++i) {\n        integer p = pgen.next_prime();\n        if (i != 0)\n            std::cout << \", \";\n        std::cout << p;\n    }\n    std::cout << \"\\nPrimes between 100 and 150:\\n\";\n    for (int n = 0; ; ) {\n        integer p = pgen.next_prime();\n        if (p > 150)\n            break;\n        if (p >= 100) {\n            if (n != 0)\n                std::cout << \", \";\n            std::cout << p;\n            ++n;\n        }\n    }\n    int count = 0;\n    for (;;) {\n        integer p = pgen.next_prime();\n        if (p > 8000)\n            break;\n        if (p >= 7700)\n            ++count;\n    }\n    std::cout << \"\\nNumber of primes between 7700 and 8000: \" << count << '\\n';\n\n    for (integer n = 10000; n <= 10000000; n *= 10) {\n        integer prime;\n        while (pgen.count() != n)\n            prime = pgen.next_prime();\n        std::cout << n << \"th prime: \" << prime << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 58659, "name": "Create a two-dimensional array at runtime", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\n", "C++": "#include <iostream>\n\nint main()\n{\n  \n  int dim1, dim2;\n  std::cin >> dim1 >> dim2;\n\n  \n  double* array_data = new double[dim1*dim2];\n  double** array = new double*[dim1];\n  for (int i = 0; i < dim1; ++i)\n    array[i] = array_data + dim2*i;\n\n  \n  array[0][0] = 3.5;\n\n  \n  std::cout << array[0][0] << std::endl;\n\n  \n  delete[] array;\n  delete[] array_data;\n\n  return 0;\n}\n"}
{"id": 58660, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 58661, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\n", "C++": "\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <execution>\n\ntemplate<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector<int> n = { 3, 5, 7 };\n\tvector<int> a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}\n"}
{"id": 58662, "name": "Pi", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\n", "C++": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n    cpp_int q, r, t, i, n;\n\npublic:    \n\n    \n    Gospers() : q{1}, r{0}, t{1}, i{1}\n    {\n        ++*this; \n    }\n\n    \n    Gospers& operator++()\n    {\n        n = (q*(27*i-12)+5*r) / (5*t);\n\n        while(n != (q*(675*i-216)+125*r)/(125*t))\n        {\n            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n            q = i*(2*i-1)*q;\n            t = 3*(3*i+1)*(3*i+2)*t;\n            i++;\n\n            n = (q*(27*i-12)+5*r) / (5*t);\n        }\n\n        q = 10*q;\n        r = 10*r-10*n*t;\n\n        return *this;\n    }\n\n    \n    int operator*()\n    {\n        return (int)n;\n    }\n};\n\nint main()\n{\n    Gospers g;\n\n    std::cout << *g << \".\";  \n\n    for(;;) \n    {\n        std::cout << *++g;  \n    }\n}\n"}
{"id": 58663, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 58664, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\n", "C++": "#include <iostream>\n \nint main() {\n   const int size = 100000;\n   int hofstadters[size] = { 1, 1 };  \n   for (int i = 3 ; i < size; i++) \n      hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n                             hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n   std::cout << \"The first 10 numbers are: \";\n   for (int i = 0; i < 10; i++) \n      std::cout << hofstadters[ i ] << ' ';\n   std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n   int less_than_preceding = 0;\n   for (int i = 0; i < size - 1; i++)\n      if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t     less_than_preceding++;\n   std::cout << \"In array of size: \" << size << \", \";\n   std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n   return 0;\n}\n"}
{"id": 58665, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n", "C++": "#include <iostream>\n#include <functional>\n\ntemplate <typename F>\nstruct RecursiveFunc {\n\tstd::function<F(RecursiveFunc)> o;\n};\n\ntemplate <typename A, typename B>\nstd::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {\n\tRecursiveFunc<std::function<B(A)>> r = {\n\t\tstd::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {\n\t\t\treturn f(std::function<B(A)>([w](A x) {\n\t\t\t\treturn w.o(w)(x);\n\t\t\t}));\n\t\t})\n\t};\n\treturn r.o(r);\n}\n\ntypedef std::function<int(int)> Func;\ntypedef std::function<Func(Func)> FuncFunc;\nFuncFunc almost_fac = [](Func f) {\n\treturn Func([f](int n) {\n\t\tif (n <= 1) return 1;\n\t\treturn n * f(n - 1);\n\t});\n};\n\nFuncFunc almost_fib = [](Func f) {\n\treturn Func([f](int n) {\n\t \tif (n <= 2) return 1;\n\t\treturn  f(n - 1) + f(n - 2);\n\t});\n};\n\nint main() {\n\tauto fib = Y(almost_fib);\n\tauto fac = Y(almost_fac);\n\tstd::cout << \"fib(10) = \" << fib(10) << std::endl;\n\tstd::cout << \"fac(10) = \" << fac(10) << std::endl;\n\treturn 0;\n}\n"}
{"id": 58666, "name": "Return multiple values", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<int, int> minmax(const int * numbers, const std::size_t num) {\n   const auto maximum = std::max_element(numbers, numbers + num);\n   const auto minimum = std::min_element(numbers, numbers + num);\n   return std::make_tuple(*minimum, *maximum) ;\n}\n\nint main( ) {\n   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};\n   int min{};\n   int max{};\n   std::tie(min, max) = minmax(numbers.data(), numbers.size());\n   std::cout << \"The smallest number is \" << min << \", the biggest \" << max << \"!\\n\" ;\n}\n"}
{"id": 58667, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 58668, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\n", "C++": "#include <iostream>\n#include <map>\n\nclass van_eck_generator {\npublic:\n    int next() {\n        int result = last_term;\n        auto iter = last_pos.find(last_term);\n        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n        last_pos[last_term] = index;\n        last_term = next_term;\n        ++index;\n        return result;\n    }\nprivate:\n    int index = 0;\n    int last_term = 0;\n    std::map<int, int> last_pos;\n};\n\nint main() {\n    van_eck_generator gen;\n    int i = 0;\n    std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n    for (; i < 10; ++i)\n        std::cout << gen.next() << ' ';\n    for (; i < 990; ++i)\n        gen.next();\n    std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n    for (; i < 1000; ++i)\n        std::cout << gen.next() << ' ';\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 58669, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 58670, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n", "C++": "#include <random>\n#include <iostream>\n#include <stack>\n#include <set>\n#include <string>\n#include <functional>\nusing namespace std;\n\nclass RPNParse\n{\npublic:\n  stack<double> stk;\n  multiset<int> digits;\n\n  void op(function<double(double,double)> f)\n  {\n    if(stk.size() < 2)\n      throw \"Improperly written expression\";\n    int b = stk.top(); stk.pop();\n    int a = stk.top(); stk.pop();\n    stk.push(f(a, b));\n  }\n\n  void parse(char c)\n  {\n    if(c >= '0' && c <= '9')\n    {\n      stk.push(c - '0');\n      digits.insert(c - '0');\n    }\n    else if(c == '+')\n      op([](double a, double b) {return a+b;});\n    else if(c == '-')\n      op([](double a, double b) {return a-b;});\n    else if(c == '*')\n      op([](double a, double b) {return a*b;});\n    else if(c == '/')\n      op([](double a, double b) {return a/b;});\n  }\n\n  void parse(string s)\n  {\n    for(int i = 0; i < s.size(); ++i)\n      parse(s[i]);\n  }\n\n  double getResult()\n  {\n    if(stk.size() != 1)\n      throw \"Improperly written expression\";\n    return stk.top();\n  }\n};\n\nint main()\n{\n  random_device seed;\n  mt19937 engine(seed());\n  uniform_int_distribution<> distribution(1, 9);\n  auto rnd = bind(distribution, engine);\n\n  multiset<int> digits;\n  cout << \"Make 24 with the digits: \";\n  for(int i = 0; i < 4; ++i)\n  {\n    int n = rnd();\n    cout << \" \" << n;\n    digits.insert(n);\n  }\n  cout << endl;\n\n  RPNParse parser;\n\n  try\n  {\n    string input;\n    getline(cin, input);\n    parser.parse(input);\n\n    if(digits != parser.digits)\n      cout << \"Error: Not using the given digits\" << endl;\n    else\n    {\n      double r = parser.getResult();\n      cout << \"Result: \" << r << endl;\n\n      if(r > 23.999 && r < 24.001)\n        cout << \"Good job!\" << endl;\n      else\n        cout << \"Try again.\" << endl;\n    }\n  }\n  catch(char* e)\n  {\n    cout << \"Error: \" << e << endl;\n  }\n  return 0;\n}\n"}
{"id": 58671, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n", "C++": "for(int i = 1;i <= 10; i++){\n   cout << i;\n   if(i % 5 == 0){\n      cout << endl;\n      continue;\n   }\n   cout << \", \";\n}\n"}
{"id": 58672, "name": "LU decomposition", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C++": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\ntemplate <typename scalar_type> class matrix {\npublic:\n    matrix(size_t rows, size_t columns)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n    matrix(size_t rows, size_t columns, scalar_type value)\n        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n    matrix(size_t rows, size_t columns,\n        const std::initializer_list<std::initializer_list<scalar_type>>& values)\n        : rows_(rows), columns_(columns), elements_(rows * columns) {\n        assert(values.size() <= rows_);\n        size_t i = 0;\n        for (const auto& row : values) {\n            assert(row.size() <= columns_);\n            std::copy(begin(row), end(row), &elements_[i]);\n            i += columns_;\n        }\n    }\n\n    size_t rows() const { return rows_; }\n    size_t columns() const { return columns_; }\n\n    const scalar_type& operator()(size_t row, size_t column) const {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\n    scalar_type& operator()(size_t row, size_t column) {\n        assert(row < rows_);\n        assert(column < columns_);\n        return elements_[row * columns_ + column];\n    }\nprivate:\n    size_t rows_;\n    size_t columns_;\n    std::vector<scalar_type> elements_;\n};\n\ntemplate <typename scalar_type>\nvoid print(std::wostream& out, const matrix<scalar_type>& a) {\n    const wchar_t* box_top_left = L\"\\x23a1\";\n    const wchar_t* box_top_right = L\"\\x23a4\";\n    const wchar_t* box_left = L\"\\x23a2\";\n    const wchar_t* box_right = L\"\\x23a5\";\n    const wchar_t* box_bottom_left = L\"\\x23a3\";\n    const wchar_t* box_bottom_right = L\"\\x23a6\";\n\n    const int precision = 5;\n    size_t rows = a.rows(), columns = a.columns();\n    std::vector<size_t> width(columns);\n    for (size_t column = 0; column < columns; ++column) {\n        size_t max_width = 0;\n        for (size_t row = 0; row < rows; ++row) {\n            std::ostringstream str;\n            str << std::fixed << std::setprecision(precision) << a(row, column);\n            max_width = std::max(max_width, str.str().length());\n        }\n        width[column] = max_width;\n    }\n    out << std::fixed << std::setprecision(precision);\n    for (size_t row = 0; row < rows; ++row) {\n        const bool top(row == 0), bottom(row + 1 == rows);\n        out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));\n        for (size_t column = 0; column < columns; ++column) {\n            if (column > 0)\n                out << L' ';\n            out << std::setw(width[column]) << a(row, column);\n        }\n        out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));\n        out << L'\\n';\n    }\n}\n\n\ntemplate <typename scalar_type>\nauto lu_decompose(const matrix<scalar_type>& input) {\n    assert(input.rows() == input.columns());\n    size_t n = input.rows();\n    std::vector<size_t> perm(n);\n    std::iota(perm.begin(), perm.end(), 0);\n    matrix<scalar_type> lower(n, n);\n    matrix<scalar_type> upper(n, n);\n    matrix<scalar_type> input1(input);\n    for (size_t j = 0; j < n; ++j) {\n        size_t max_index = j;\n        scalar_type max_value = 0;\n        for (size_t i = j; i < n; ++i) {\n            scalar_type value = std::abs(input1(perm[i], j));\n            if (value > max_value) {\n                max_index = i;\n                max_value = value;\n            }\n        }\n        if (max_value <= std::numeric_limits<scalar_type>::epsilon())\n            throw std::runtime_error(\"matrix is singular\");\n        if (j != max_index)\n            std::swap(perm[j], perm[max_index]);\n        size_t jj = perm[j];\n        for (size_t i = j + 1; i < n; ++i) {\n            size_t ii = perm[i];\n            input1(ii, j) /= input1(jj, j);\n            for (size_t k = j + 1; k < n; ++k)\n                input1(ii, k) -= input1(ii, j) * input1(jj, k);\n        }\n    }\n    \n    for (size_t j = 0; j < n; ++j) {\n        lower(j, j) = 1;\n        for (size_t i = j + 1; i < n; ++i)\n            lower(i, j) = input1(perm[i], j);\n        for (size_t i = 0; i <= j; ++i)\n            upper(i, j) = input1(perm[i], j);\n    }\n    \n    matrix<scalar_type> pivot(n, n);\n    for (size_t i = 0; i < n; ++i)\n        pivot(i, perm[i]) = 1;\n\n    return std::make_tuple(lower, upper, pivot);\n}\n\ntemplate <typename scalar_type>\nvoid show_lu_decomposition(const matrix<scalar_type>& input) {\n    try {\n        std::wcout << L\"A\\n\";\n        print(std::wcout, input);\n        auto result(lu_decompose(input));\n        std::wcout << L\"\\nL\\n\";\n        print(std::wcout, std::get<0>(result));\n        std::wcout << L\"\\nU\\n\";\n        print(std::wcout, std::get<1>(result));\n        std::wcout << L\"\\nP\\n\";\n        print(std::wcout, std::get<2>(result));\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n    }\n}\n\nint main() {\n    std::wcout.imbue(std::locale(\"\"));\n    std::wcout << L\"Example 1:\\n\";\n    matrix<double> matrix1(3, 3,\n       {{1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}});\n    show_lu_decomposition(matrix1);\n    std::wcout << '\\n';\n\n    std::wcout << L\"Example 2:\\n\";\n    matrix<double> matrix2(4, 4,\n      {{11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}});\n    show_lu_decomposition(matrix2);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 3:\\n\";\n    matrix<double> matrix3(3, 3,\n      {{-5, -6, -3},\n       {-1,  0, -2},\n       {-3, -4, -7}});\n    show_lu_decomposition(matrix3);\n    std::wcout << '\\n';\n    \n    std::wcout << L\"Example 4:\\n\";\n    matrix<double> matrix4(3, 3,\n      {{1, 2, 3},\n       {4, 5, 6},\n       {7, 8, 9}});\n    show_lu_decomposition(matrix4);\n\n    return 0;\n}\n"}
{"id": 58673, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n\nclass pair  {\npublic:\n    pair( int s, std::string z )            { p = std::make_pair( s, z ); }\n    bool operator < ( const pair& o ) const { return i() < o.i(); }\n    int i() const                           { return p.first; }\n    std::string s() const                   { return p.second; }\nprivate:\n    std::pair<int, std::string> p;\n};\nvoid gFizzBuzz( int c, std::vector<pair>& v ) {\n    bool output;\n    for( int x = 1; x <= c; x++ ) {\n        output = false;\n        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {\n            if( !( x % ( *i ).i() ) ) {\n                std::cout << ( *i ).s();\n                output = true;\n            }\n        }\n        if( !output ) std::cout << x;\n        std::cout << \"\\n\";\n    }\n}\nint main( int argc, char* argv[] ) {\n    std::vector<pair> v;\n    v.push_back( pair( 7, \"Baxx\" ) );\n    v.push_back( pair( 3, \"Fizz\" ) );\n    v.push_back( pair( 5, \"Buzz\" ) );\n    std::sort( v.begin(), v.end() );\n    gFizzBuzz( 20, v );\n    return 0;\n}\n"}
{"id": 58674, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 58675, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "C++": "#include <string>\n#include <fstream>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"Which file do you want to look at ?\\n\" ;\n   std::string input ;\n   std::getline( std::cin , input ) ;\n   std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n   std::string file( input ) ;\n   std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n   std::getline( std::cin , input ) ;\n   int linenumber = std::stoi( input ) ;\n   int lines_read = 0 ;\n   std::string line ;\n   if ( infile.is_open( ) ) {\n      while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t    std::cout << line << std::endl ;\n\t    break ; \n\t }\n      }\n      infile.close( ) ;\n      if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n      return 0 ;\n   }\n   else {\n      std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n      return 1 ;\n   }\n}\n"}
{"id": 58676, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << \"[ \";\n    if (it != end) {\n        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;\n        it = std::next(it);\n    }\n    return os << \" ]\";\n}\n\nstd::vector<uint8_t> to_seq(uint64_t x) {\n    int i;\n    for (i = 9; i > 0; i--) {\n        if (x & 127ULL << i * 7) {\n            break;\n        }\n    }\n\n    std::vector<uint8_t> out;\n    for (int j = 0; j <= i; j++) {\n        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);\n    }\n    out[i] ^= 128;\n    return out;\n}\n\nuint64_t from_seq(const std::vector<uint8_t> &seq) {\n    uint64_t r = 0;\n\n    for (auto b : seq) {\n        r = (r << 7) | (b & 127);\n    }\n\n    return r;\n}\n\nint main() {\n    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };\n\n    for (auto x : src) {\n        auto s = to_seq(x);\n        std::cout << std::hex;\n        std::cout << \"seq from \" << x << ' ' << s << \" back: \" << from_seq(s) << '\\n';\n        std::cout << std::dec;\n    }\n\n    return 0;\n}\n"}
{"id": 58677, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\n\nvoid str_toupper(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::toupper);\n}\n\n\n\nvoid str_tolower(std::string &str) {\n  std::transform(str.begin(), \n                 str.end(), \n                 str.begin(),\n                 (int(*)(int)) std::tolower);\n}\n"}
{"id": 58678, "name": "Text processing_1", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing std::cout;\nusing std::endl;\nconst int NumFlags = 24;\n\nint main()\n{\n    std::fstream file(\"readings.txt\");\n\n    int badCount = 0;\n    std::string badDate;\n    int badCountMax = 0;\n    while(true)\n    {\n        std::string line;\n        getline(file, line);\n        if(!file.good())\n            break;\n\n        std::vector<std::string> tokens;\n        boost::algorithm::split(tokens, line, boost::is_space());\n\n        if(tokens.size() != NumFlags * 2 + 1)\n        {\n            cout << \"Bad input file.\" << endl;\n            return 0;\n        }\n\n        double total = 0.0;\n        int accepted = 0;\n        for(size_t i = 1; i < tokens.size(); i += 2)\n        {\n            double val = boost::lexical_cast<double>(tokens[i]);\n            int flag = boost::lexical_cast<int>(tokens[i+1]);\n            if(flag > 0)\n            {\n                total += val;\n                ++accepted;\n                badCount = 0;\n            }\n            else\n            {\n                ++badCount;\n                if(badCount > badCountMax)\n                {\n                    badCountMax = badCount;\n                    badDate = tokens[0];\n                }\n            }\n        }\n\n        cout << tokens[0];\n        cout << \"  Reject: \" << std::setw(2) << (NumFlags - accepted);\n        cout << \"  Accept: \" << std::setw(2) << accepted;\n        cout << \"  Average: \" << std::setprecision(5) << total / accepted << endl;\n    }\n    cout << endl;\n    cout << \"Maximum number of consecutive bad readings is \" << badCountMax << endl;\n    cout << \"Ends on date \" << badDate << endl;\n}\n"}
{"id": 58679, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n", "C++": "#include <string>\n#include <iostream>\n#include \"Poco/MD5Engine.h\"\n#include \"Poco/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest :\\n\" << DigestEngine::digestToHex( digest ) \n      << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 58680, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 58681, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\n\ninteger divisor_sum(integer n) {\n    integer total = 1, power = 2;\n    \n    for (; n % 2 == 0; power *= 2, n /= 2)\n        total += power;\n    \n    for (integer p = 3; p * p <= n; p += 2) {\n        integer 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\n\nvoid classify_aliquot_sequence(integer n) {\n    constexpr int limit = 16;\n    integer terms[limit];\n    terms[0] = n;\n    std::string classification(\"non-terminating\");\n    int length = 1;\n    for (int i = 1; i < limit; ++i) {\n        ++length;\n        terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n        if (terms[i] == n) {\n            classification =\n                (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n            break;\n        }\n        int j = 1;\n        for (; j < i; ++j) {\n            if (terms[i] == terms[i - j])\n                break;\n        }\n        if (j < i) {\n            classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n            break;\n        }\n        if (terms[i] == 0) {\n            classification = \"terminating\";\n            break;\n        }\n    }\n    std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n    for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n        std::cout << ' ' << terms[i];\n    std::cout << '\\n';\n}\n\nint main() {\n    for (integer i = 1; i <= 10; ++i)\n        classify_aliquot_sequence(i);\n    for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n                      1064, 1488})\n        classify_aliquot_sequence(i);\n    classify_aliquot_sequence(15355717786080);\n    classify_aliquot_sequence(153557177860800);\n    return 0;\n}\n"}
{"id": 58682, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n", "C++": "#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n  std::vector<std::thread> threads;\n\n  for (int i = 1; i < argc; ++i) {\n    threads.emplace_back([i, &argv]() {\n      int arg = std::stoi(argv[i]);\n      std::this_thread::sleep_for(std::chrono::seconds(arg));\n      std::cout << argv[i] << std::endl;\n    });\n  }\n\n  for (auto& thread : threads) {\n    thread.join();\n  }\n}\n"}
{"id": 58683, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C++": "#include<cstdlib>\n#include<ctime>\n#include<iostream>\n\nusing namespace std;\nint main()\n{\n    int arr[10][10];\n    srand(time(NULL));\n    for(auto& row: arr)\n        for(auto& col: row)\n            col = rand() % 20 + 1;\n\n    ([&](){\n       for(auto& row : arr)\n           for(auto& col: row)\n           {\n               cout << col << endl;\n               if(col == 20)return;\n           }\n    })();\n    return 0;\n}\n"}
{"id": 58684, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 58685, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "C++": "#include <cmath>\n#include <iostream>\n#include <numeric>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n    unsigned long long totalCount = 0;\n    unsigned long long primitveCount = 0;\n    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n    for(unsigned long long m = 2; m < max_M; ++m)\n    {\n        for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n        {\n            if(gcd(m,n) != 1)\n            {\n                continue;\n            }\n            \n            \n            \n            \n            \n            \n            auto a = m * m - n * n;\n            auto b = 2 * m * n;\n            auto c = m * m + n * n;\n            auto perimeter = a + b + c;\n            if(perimeter <= maxPerimeter)\n            {\n                primitveCount++;\n                totalCount+= maxPerimeter / perimeter;\n            }\n        }\n    }\n    \n    return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,\n        1000'000, 10'000'000, 100'000'000, 1000'000'000,\n        10'000'000'000};  \n    for(auto maxPerimeter : inputs)\n    {\n        auto [total, primitive] = CountTriplets(maxPerimeter);\n        cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n    }\n}\n"}
{"id": 58686, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 58687, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "C++": "#include <set>\n#include <iostream>\nusing namespace std;\n\nint main() {\n    typedef set<int> TySet;\n    int data[] = {1, 2, 3, 2, 3, 4};\n\n    TySet unique_set(data, data + 6);\n\n    cout << \"Set items:\" << endl;\n    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n          cout << *iter << \" \";\n    cout << endl;\n}\n"}
{"id": 58688, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n", "C++": "#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string lookandsay(const std::string& s)\n{\n    std::ostringstream r;\n\n    for (std::size_t i = 0; i != s.length();) {\n        auto new_i = s.find_first_not_of(s[i], i + 1);\n\n        if (new_i == std::string::npos)\n            new_i = s.length();\n\n        r << new_i - i << s[i];\n        i = new_i;\n    }\n    return r.str();\n}\n\nint main()\n{\n    std::string laf = \"1\";\n\n    std::cout << laf << '\\n';\n    for (int i = 0; i < 10; ++i) {\n        laf = lookandsay(laf);\n        std::cout << laf << '\\n';\n    }\n}\n"}
{"id": 58689, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "C++": "#include <stack>\n"}
{"id": 58690, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n", "C++": "#include <cassert>\n#include <iomanip>\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\nint count_primes(const totient_calculator& tc, int min, int max) {\n    int count = 0;\n    for (int i = min; i <= max; ++i) {\n        if (tc.is_prime(i))\n            ++count;\n    }\n    return count;\n}\n\nint main() {\n    const int max = 10000000;\n    totient_calculator tc(max);\n    std::cout << \" n  totient  prime?\\n\";\n    for (int i = 1; i <= 25; ++i) {\n        std::cout << std::setw(2) << i\n            << std::setw(9) << tc.totient(i)\n            << std::setw(8) << (tc.is_prime(i) ? \"yes\" : \"no\") << '\\n';\n    }\n    for (int n = 100; n <= max; n *= 10) {\n        std::cout << \"Count of primes up to \" << n << \": \"\n            << count_primes(tc, 1, n) << '\\n';\n    }\n    return 0;\n}\n"}
{"id": 58691, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "C++": "template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>\n{\n  typedef ThenType type;\n};\n\ntemplate<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>\n{\n  typedef ElseType type;\n};\n\n\nifthenelse<INT_MAX == 32767, \n           long int,         \n           int>              \n  ::type myvar;              \n"}
{"id": 58692, "name": "Fractran", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nclass fractran\n{\npublic:\n    void run( std::string p, int s, int l  )\n    {\n        start = s; limit = l;\n        istringstream iss( p ); vector<string> tmp;\n        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );\n\n        string item; vector< pair<float, float> > v;\n\tpair<float, float> a;\n\tfor( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )\n\t{\n\t    string::size_type pos = ( *i ).find( '/', 0 );\n\t    if( pos != std::string::npos )\n\t    {\n\t\ta = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );\n\t\tv.push_back( a );\n\t    }\n\t}\n\t\t\n\texec( &v );\n    }\n\nprivate:\n    void exec( vector< pair<float, float> >* v )\n    {\n\tint cnt = 0;\n\twhile( cnt < limit )\n\t{\n\t    cout << cnt << \" : \" << start << \"\\n\";\n\t    cnt++;\n\t    vector< pair<float, float> >::iterator it = v->begin();\n\t    bool found = false; float r;\n\t    while( it != v->end() )\n\t    {\n\t\tr  = start * ( ( *it ).first / ( *it ).second );\n\t\tif( r == floor( r ) )\n\t\t{\n\t\t    found = true;\n\t\t    break;\n\t\t}\n\t\t++it;\n\t    }\n\n\t    if( found ) start = ( int )r;\n\t    else break;\n\t}\n    }\n    int start, limit;\n};\nint main( int argc, char* argv[] )\n{\n    fractran f; f.run( \"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2, 15 );\n    cin.get();\n    return 0;\n}\n"}
{"id": 58693, "name": "Read a configuration file", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n", "C++": "#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\nstatic const char_separator<char> sep(\" \",\"#;,\");\n\n\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector<string> otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector<string> tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.fullname += tokens[i] + \" \";\n\t\tconf.fullname.erase(conf.fullname.size() -1, 1);\n\t}\n\tif (tokens[0] == \"favouritefruit\") \n\t\tfor (unsigned int i=1; i<tokens.size(); i++)\n\t\t\tconf.favoritefruit += tokens[i];\n\tif (tokens[0] == \"otherfamily\"){\n\t\tunsigned int i=1;\n\t\tstring tmp;\n\t\twhile (i<=tokens.size()){\t\t\n\t\t\tif ( i == tokens.size() || tokens[i] ==\",\"){\n\t\t\t\ttmp.erase(tmp.size()-1, 1);\n\t\t\t\tconf.otherfamily.push_back(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttmp += tokens[i];\n\t\t\t\ttmp += \" \";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint _tmain(int argc, TCHAR* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\twstring tmp = argv[0];\n\t\twcout << L\"Usage: \" << tmp << L\" <configfile.ini>\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n"}
{"id": 58694, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n", "C++": "#include <algorithm>\n#include <string>\n#include <cctype>\n\n\nstruct icompare_char {\n  bool operator()(char c1, char c2) {\n    return std::toupper(c1) < std::toupper(c2);\n  }\n};\n\n\nstruct compare {\n  bool operator()(std::string const& s1, std::string const& s2) {\n    if (s1.length() > s2.length())\n      return true;\n    if (s1.length() < s2.length())\n      return false;\n    return std::lexicographical_compare(s1.begin(), s1.end(),\n                                        s2.begin(), s2.end(),\n                                        icompare_char());\n  }\n};\n\nint main() {\n  std::string strings[8] = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n  std::sort(strings, strings+8, compare());\n  return 0;\n}\n"}
{"id": 58695, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n", "C++": "#include \"animationwidget.h\"\n\n#include <QLabel>\n#include <QTimer>\n#include <QVBoxLayout>\n\n#include <algorithm>\n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n    setWindowTitle(tr(\"Animation\"));\n    QFont font(\"Courier\", 24);\n    QLabel* label = new QLabel(\"Hello World! \");\n    label->setFont(font);\n    QVBoxLayout* layout = new QVBoxLayout(this);\n    layout->addWidget(label);\n    QTimer* timer = new QTimer(this);\n    connect(timer, &QTimer::timeout, this, [label,this]() {\n        QString text = label->text();\n        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n        label->setText(text);\n    });\n    timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n    right_ = !right_;\n}\n"}
{"id": 58696, "name": "List comprehensions", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n", "C++": "#include <vector>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n\nvoid list_comprehension( std::vector<int> & , int ) ;\n\nint main( ) {\n   std::vector<int> triangles ;\n   list_comprehension( triangles , 20 ) ;\n   std::copy( triangles.begin( ) , triangles.end( ) ,\n\t std::ostream_iterator<int>( std::cout , \" \" ) ) ;\n   std::cout << std::endl ;\n   return 0 ;\n}\n\nvoid list_comprehension( std::vector<int> & numbers , int upper_border ) {\n   for ( int a = 1 ; a < upper_border ; a++ ) {\n      for ( int b = a + 1 ; b < upper_border ; b++ ) {\n\t double c = pow( a * a + b * b , 0.5 ) ; \n\t if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {\n\t    if ( c == floor( c ) ) {\n\t       numbers.push_back( a ) ;\n\t       numbers.push_back( b ) ;\t      \n\t       numbers.push_back( static_cast<int>( c ) ) ;\n\t    }\n\t }\n      }\n   }\n}\n"}
{"id": 58697, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename ForwardIterator> void selection_sort(ForwardIterator begin,\n                                                       ForwardIterator end) {\n  for(auto i = begin; i != end; ++i) {\n    std::iter_swap(i, std::min_element(i, end));\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  selection_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": 58698, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n", "C++": "#include <iostream> \n#include <algorithm> \n\n\nvoid print_square(int i) {\n  std::cout << i*i << \" \";\n}\n\nint main() {\n  \n  int ary[]={1,2,3,4,5};\n  \n  std::for_each(ary,ary+5,print_square);\n  return 0;\n}\n\n"}
{"id": 58699, "name": "Case-sensitivity of identifiers", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n    string dog = \"Benjamin\", Dog = \"Samba\", DOG = \"Bernie\";\n    \n    cout << \"The three dogs are named \" << dog << \", \" << Dog << \", and \" << DOG << endl;\n}\n"}
{"id": 58700, "name": "Loops_Downward for", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n", "C++": "for(int i = 10; i >= 0; --i)\n  std::cout << i << \"\\n\";\n"}
{"id": 58701, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "C++": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n    ofstream file(\"new.txt\");\n    file << \"this is a string\";\n    file.close();\n    return 0;\n}\n"}
{"id": 58702, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "C++": "for(int i = 0; i < 5; ++i) {\n  for(int j = 0; j < i; ++j)\n    std::cout.put('*');\n\n  std::cout.put('\\n');\n}\n"}
{"id": 58703, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 58704, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 58705, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "C++": "#include <windows.h>\n#include <string>\n#include <iostream>\n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap() {\n        DeleteObject( pen ); DeleteObject( brush );\n        DeleteDC( hdc ); DeleteObject( bmp );\n    }\n    bool create( int w, int h ) {\n        BITMAPINFO bi;\n        ZeroMemory( &bi, sizeof( bi ) );\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        HDC dc = GetDC( GetConsoleWindow() );\n        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n        if( !bmp ) return false;\n        hdc = CreateCompatibleDC( dc );\n        SelectObject( hdc, bmp );\n        ReleaseDC( GetConsoleWindow(), dc );\n        width = w; height = h;\n        return true;\n    }\n    void clear( BYTE clr = 0 ) {\n        memset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n    void setBrushColor( DWORD bClr ) {\n        if( brush ) DeleteObject( brush );\n        brush = CreateSolidBrush( bClr );\n        SelectObject( hdc, brush );\n    }\n    void setPenColor( DWORD c ) {\n        clr = c; createPen();\n    }\n    void setPenWidth( int w ) {\n        wid = w; createPen();\n    }\n    void saveBitmap( std::string path ) {\n        BITMAPFILEHEADER fileheader;\n        BITMAPINFO       infoheader;\n        BITMAP           bitmap;\n        DWORD            wb;\n        GetObject( bmp, sizeof( bitmap ), &bitmap );\n        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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        fileheader.bfType    = 0x4D42;\n        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n                                  FILE_ATTRIBUTE_NORMAL, NULL );\n        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n        CloseHandle( file );\n        delete [] dwpBits;\n    }\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\nprivate:\n    void createPen() {\n        if( pen ) DeleteObject( pen );\n        pen = CreatePen( PS_SOLID, wid, clr );\n        SelectObject( hdc, pen );\n    }\n    HBITMAP bmp; HDC    hdc;\n    HPEN    pen; HBRUSH brush;\n    void    *pBits; int    width, height, wid;\n    DWORD    clr;\n};\nclass sierpinski {\npublic:\n    void draw( int o ) {\n        colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n        colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n        bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n        drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n        bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n        LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n        LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n    }\nprivate:\n    void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n        float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n        if( i ) {\n            drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n            drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n            drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n        }\n        bmp.setPenColor( colors[i % 6] );\n        MoveToEx( dc, ( int )( l + ww ),          ( int )( t + hh ), NULL );\n        LineTo  ( dc, ( int )( l + ww * 3.f ),    ( int )( t + hh ) );\n        LineTo  ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n        LineTo  ( dc, ( int )( l + ww ),          ( int )( t + hh ) );\n    }\n    myBitmap bmp;\n    DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n    sierpinski s; s.draw( 12 );\n    return 0;\n}\n"}
{"id": 58706, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 58707, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n", "C++": "\nclass N{\n  uint n,i,g,e,l;\npublic:\n  N(uint n): n(n-1),i{},g{},e(1),l(n-1){}\n  bool hasNext(){\n    g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;\n    if (l==2)             {l=--n; e=1; return true;}\n    if (e<((1<<(l-1))-1)) {++e;        return true;}\n                           e=1; --l;   return (l>0);\n  }\n  uint next() {return g;}\n};\n"}
{"id": 58708, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <primesieve.hpp>\n\nvoid print_twin_prime_count(long long limit) {\n    std::cout << \"Number of twin prime pairs less than \" << limit\n        << \" is \" << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\\n';\n}\n\nint main(int argc, char** argv) {\n    std::cout.imbue(std::locale(\"\"));\n    if (argc > 1) {\n        \n        \n        for (int i = 1; i < argc; ++i) {\n            try {\n                print_twin_prime_count(std::stoll(argv[i]));\n            } catch (const std::exception& ex) {\n                std::cerr << \"Cannot parse limit from '\" << argv[i] << \"'\\n\";\n            }\n        }\n    } else {\n        \n        \n        uint64_t limit = 10;\n        for (int power = 1; power < 12; ++power, limit *= 10)\n            print_twin_prime_count(limit);\n    }\n    return 0;\n}\n"}
{"id": 58709, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 58710, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n", "C++": "#include <complex>\n#include <cmath>\n#include <iostream>\n\ndouble const pi = 4 * std::atan(1);\n\nint main()\n{\n  for (int n = 2; n <= 10; ++n)\n  {\n    std::cout << n << \": \";\n    for (int k = 0; k < n; ++k)\n      std::cout << std::polar(1, 2*pi*k/n) << \" \";\n    std::cout << std::endl;\n  }\n}\n"}
{"id": 58711, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <sstream>\n\ntypedef long long bigInt;\n\nusing namespace std;\n\nclass number\n{\npublic:\n    number()                                { s = \"0\"; neg = false; }\n    number( bigInt a )                      { set( a ); }\n    number( string a )                      { set( a ); }\n    void set( bigInt a )                    { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }\n    void set( string a )                    { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }\n    number operator *  ( const number& b )  { return this->mul( b ); }\n    number& operator *= ( const number& b ) { *this = *this * b; return *this; }\n    number& operator = ( const number& b )  { s = b.s; return *this; }\n    friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << \"-\"; out << a.s; return out; }\n    friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }\n\nprivate:\n    number mul( const number& b )\n    {\n\tnumber a; bool neg = false;\n\tstring r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );\n\tint xx, ss, rr, t, c, stp = 0;\n\tstring::reverse_iterator xi = bs.rbegin(), si, ri;\n\tfor( ; xi != bs.rend(); xi++ )\n\t{\n\t    c = 0; ri = r.rbegin() + stp;\n\t    for( si = s.rbegin(); si != s.rend(); si++ )\n\t    {\n\t\txx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;\n\t\tss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;\n\t\t( *ri++ ) = t + 48;\n\t    }\n\t    if( c > 0 ) ( *ri ) = c + 48;\n\t    stp++;\n\t}\n\ttrimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;\n\tif( t & 1 ) a.s = \"-\" + r;\n\telse a.s = r;\n\treturn a;\n    }\n\n    void trimLeft( string& r )\n    {\n\tif( r.length() < 2 ) return;\n\tfor( string::iterator x = r.begin(); x != ( r.end() - 1 ); )\n\t{\n\t    if( ( *x ) != '0' ) return;\n\t    x = r.erase( x );\n\t}\n    }\n\n    void clearStr()\n    {\n\tfor( string::iterator x = s.begin(); x != s.end(); )\n\t{\n\t    if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );\n\t    else x++;\n\t}\n    }\n    string s;\n    bool neg;\n};\n\nint main( int argc, char* argv[] )\n{\n    number a, b;\n    a.set( \"18446744073709551616\" ); b.set( \"18446744073709551616\" );\n    cout << a * b << endl << endl;\n\n    cout << \"Factor 1 = \"; cin >> a;\n    cout << \"Factor 2 = \"; cin >> b;\n    cout << \"Product: = \" << a * b << endl << endl;\n    return system( \"pause\" );\n}\n\n"}
{"id": 58712, "name": "Pell's equation", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <tuple>\n\nstd::tuple<uint64_t, uint64_t> solvePell(int n) {\n    int x = (int)sqrt(n);\n\n    if (x * x == n) {\n        \n        return std::make_pair(1, 0);\n    }\n\n    \n    int y = x;\n    int z = 1;\n    int r = 2 * x;\n    std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);\n    std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);\n    uint64_t a = 0;\n    uint64_t b = 0;\n\n    while (true) {\n        y = r * z - y;\n        z = (n - y * y) / z;\n        r = (x + y) / z;\n        e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));\n        f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));\n        a = std::get<1>(e) + x * std::get<1>(f);\n        b = std::get<1>(f);\n        if (a * a - n * b * b == 1) {\n            break;\n        }\n    }\n\n    return std::make_pair(a, b);\n}\n\nvoid test(int n) {\n    auto r = solvePell(n);\n    std::cout << \"x^2 - \" << std::setw(3) << n << \" * y^2 = 1 for x = \" << std::setw(21) << std::get<0>(r) << \" and y = \" << std::setw(21) << std::get<1>(r) << '\\n';\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 58713, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n", "C++": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cstdlib>\n\nbool contains_duplicates(std::string s)\n{\n  std::sort(s.begin(), s.end());\n  return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n  typedef std::string::size_type index;\n\n  std::string symbols = \"0123456789\";\n  unsigned int const selection_length = 4;\n\n  std::random_shuffle(symbols.begin(), symbols.end());\n  std::string selection = symbols.substr(0, selection_length);\n  std::string guess;\n  while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n  {\n    if (guess.length() != selection_length\n        || guess.find_first_not_of(symbols) != std::string::npos\n        || contains_duplicates(guess))\n    {\n      std::cout << guess << \" is not a valid guess!\";\n      continue;\n    }\n\n    unsigned int bulls = 0;\n    unsigned int cows = 0;\n    for (index i = 0; i != selection_length; ++i)\n    {\n      index pos = selection.find(guess[i]);\n      if (pos == i)\n        ++bulls;\n      else if (pos != std::string::npos)\n        ++cows;\n    }\n    std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n    if (bulls == selection_length)\n    {\n      std::cout << \"Congratulations! You have won!\\n\";\n      return;\n    }\n  }\n  std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n  std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n  std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n  std::string answer;\n  while (true)\n  {\n    while (true)\n    {\n      if (!std::getline(std::cin, answer))\n      {\n        std::cout << \"I can't get an answer. Exiting.\\n\";\n        return EXIT_FAILURE;\n      }\n      if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n        break;\n      if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n      {\n        std::cout << \"Ok. Goodbye.\\n\";\n        return EXIT_SUCCESS;\n      }\n      std::cout << \"Please answer yes or no: \";\n    }\n    game(); \n    std::cout << \"Another game? \";\n  }\n}\n"}
{"id": 58714, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n\ntemplate <typename RandomAccessIterator>\nvoid bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bool swapped = true;\n  while (begin != end-- && swapped) {\n    swapped = false;\n    for (auto i = begin; i != end; ++i) {\n      if (*(i + 1) < *i) {\n        std::iter_swap(i, i + 1);\n        swapped = true;\n      }\n    }\n  }\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bubble_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": 58715, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "C++": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    string line;\n    ifstream input ( \"input.txt\" );\n    ofstream output (\"output.txt\");\n    \n    if (output.is_open()) {\n        if (input.is_open()){\n            while (getline (input,line)) {\n                output << line << endl;\n            }\n            input.close(); \n        }\n        else {\n            cout << \"input.txt cannot be opened!\\n\";\n        }\n        output.close(); \n    }\n    else {\n        cout << \"output.txt cannot be written to!\\n\";\n    }\n    return 0;\n}\n"}
{"id": 58716, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n", "C++": "#include <iostream>\n\nint main()\n{\n  int a, b;\n  std::cin >> a >> b;\n  std::cout << \"a+b = \" << a+b << \"\\n\";\n  std::cout << \"a-b = \" << a-b << \"\\n\";\n  std::cout << \"a*b = \" << a*b << \"\\n\";\n  std::cout << \"a/b = \" << a/b << \", remainder \" << a%b << \"\\n\";\n  return 0;\n}\n"}
{"id": 58717, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n", "C++": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n"}
{"id": 58718, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n", "C++": "#include <iostream>\n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n"}
{"id": 58719, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 58720, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "C++": "#include <iostream>\n \nvoid recurse(unsigned int i)\n{\n  std::cout<<i<<\"\\n\";\n  recurse(i+1);\n}\n \nint main()\n{\n  recurse(0);\n}\n"}
{"id": 58721, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n"}
{"id": 58722, "name": "Arithmetic numbers", "VB": "\n\n\nfunction isarit_compo(i)\n     cnt=0\n     sum=0\n     for j=1 to sqr(i)\n       if (i mod j)=0 then \n          k=i\\j \n             \n         if k=j then \n            cnt=cnt+1:sum=sum+j \n         else  \n            cnt=cnt+2:sum=sum+j+k \n         end if\n       end if\n     next\n   avg= sum/cnt\n   isarit_compo= array((fix(avg)=avg),-(cnt>2))\nend function\n\nfunction rpad(a,n) rpad=right(space(n)&a,n) :end function\n\ndim s1\nsub print(s) \n  s1=s1& rpad(s,4)\n  if len(s1)=40 then wscript.stdout.writeline s1:s1=\"\"\nend sub\n\n\ncntr=0\ncntcompo=0\ni=1\nwscript.stdout.writeline \"the first 100 arithmetic numbers are:\"\ndo\n  a=isarit_compo(i)\n  if a(0) then  \n    cntcompo=cntcompo+a(1)\n    cntr=cntr+1\n    if cntr<=100 then print i\n    if cntr=1000 then wscript.stdout.writeline vbcrlf&\"1000th   : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=10000 then wscript.stdout.writeline vbcrlf& \"10000th  : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6)\n    if cntr=100000 then wscript.stdout.writeline vbcrlf &\"100000th : \"&rpad(i,6) & \" nr composites \" &rpad(cntcompo,6):exit do\n  end if \n  i=i+1\nloop\n", "C++": "#include <cstdio>\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t   unsigned int& divisor_count,\n\t\t\t   unsigned int& divisor_sum)\n{\n  divisor_count = 0;\n  divisor_sum = 0;\n  for (unsigned int i = 1;; i++)\n  {\n    unsigned int j = n / i;\n    if (j < i)\n      break;\n    if (i * j != n)\n      continue;\n    divisor_sum += i;\n    divisor_count += 1;\n    if (i != j)\n    {\n      divisor_sum += j;\n      divisor_count += 1;\n    }\n  }\n}\n\nint main()\n{\n  unsigned int arithmetic_count = 0;\n  unsigned int composite_count = 0;\n\n  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n  {\n    unsigned int divisor_count;\n    unsigned int divisor_sum;\n    divisor_count_and_sum(n, divisor_count, divisor_sum);\n    unsigned int mean = divisor_sum / divisor_count;\n    if (mean * divisor_count != divisor_sum)\n      continue;\n    arithmetic_count++;\n    if (divisor_count > 2)\n      composite_count++;\n    if (arithmetic_count <= 100)\n    {\n      \n      std::printf(\"%3u \", n);\n      if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n    }\n    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n    {\n      std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n      std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n    }\n  }\n  return 0;\n}\n"}
{"id": 58723, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "C++": "#include <windows.h>\n#include <sstream>\n#include <tchar.h>\n\nusing namespace std;\n\n\nconst unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;\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\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\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    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\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\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\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\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    void* getBits( void ) const { return pBits; }\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 bmpNoise\n{\npublic:\n    bmpNoise()\n    {\n\tQueryPerformanceFrequency( &_frequency );\n\t_bmp.create( BMP_WID, BMP_HEI );\n\t_frameTime = _fps = 0; _start = getTime(); _frames = 0;\n    }\n\n    void mainLoop()\n    {\n\tfloat now = getTime();\n\tif( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }\n\tHDC wdc, dc = _bmp.getDC();\n\tunsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );\n\n\tfor( int y = 0; y < BMP_HEI; y++ )\n\t{\n\t    for( int x = 0; x < BMP_WID; x++ )\n\t    {\n\t\tif( rand() % 10 < 5 ) memset( bits, 255, 3 );\n\t\telse memset( bits, 0, 3 );\n\t\tbits++;\n\t    }\n\t}\n\tostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );\n\n\twdc = GetDC( _hwnd );\n\tBitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, wdc );\n\t_frames++; _frameTime = getTime() - now;\n\tif( _frameTime > 1.0f ) _frameTime = 1.0f;\n    }\n\t\n    void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n    float getTime()\n    {\n\tLARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );\n\treturn liTime.QuadPart  / ( float )_frequency.QuadPart;\n    }\n    myBitmap      _bmp;\n    HWND          _hwnd;\n    float         _start, _fps, _frameTime;\n    unsigned int  _frames;\n    LARGE_INTEGER _frequency;\n};\n\nclass wnd\n{\npublic:\n    wnd() { _inst = this; }\n    int wnd::Run( HINSTANCE hInst )\n    {\n\t_hInst = hInst; _hwnd = InitAll();\n        _noise.setHWND( _hwnd );\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t    {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t    }\n\t    else\n\t    {\n\t\t_noise.mainLoop();\n\t    }\n\t}\n\treturn UnregisterClass( \"_MY_NOISE_\", _hInst );\n    }\nprivate:\n    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n    {\n\tswitch( msg )\n\t{\n\t    case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t    default:\n\t        return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n    }\n\n    HWND InitAll()\n    {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize           = sizeof( WNDCLASSEX );\n\twcex.style           = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc   = ( WNDPROC )WndProc;\n\twcex.hInstance     = _hInst;\n\twcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_NOISE_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_WID, BMP_HEI };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_NOISE_\", \".: Noise image -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n    }\n\n    static wnd* _inst;\n    HINSTANCE   _hInst;\n    HWND        _hwnd;\n    bmpNoise    _noise;\n};\nwnd* wnd::_inst = 0;\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() ); wnd myWnd;\n    return myWnd.Run( hInstance );\n}\n\n"}
{"id": 58724, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 58725, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 58726, "name": "Keyboard input_Obtain a Y or N response", "VB": "\n\n\n\nGraphicsWindow.DrawText(10, 10, \"Hit any key to dump.\")\nGraphicsWindow.KeyDown = OnKeyDown\nSub OnKeyDown\n  TextWindow.WriteLine(GraphicsWindow.LastKey)\nEndSub\n", "C++": "#include <conio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 58727, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 58728, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "C++": "#include <iostream>\nusing namespace std ;\n\nint divisor_sum( int number ) { \n   int sum = 0 ; \n   for ( int i = 1 ; i < number ; i++ ) \n      if ( number % i == 0 ) \n         sum += i ; \n   return sum; \n}\n\nint main( ) { \n   cout << \"Perfect numbers from 1 to 33550337:\\n\" ;\n   for ( int num = 1 ; num < 33550337 ; num++ ) { \n      if (divisor_sum(num) == num) \n         cout << num << '\\n' ;\n   }   \n   return 0 ; \n}\n"}
{"id": 58729, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "C++": "\n\n\n\n#include <iostream>\n#include <vector>\n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector<int> &List) {\n\t\n    if (dist > List.size() )\n        List.resize(dist); \n\n    for (int i=0; i < dist; i++)\n        List[i]++;\n}\n\nvector<int> beadSort(int *myints, int n) {\n    vector<int> list, list2, fifth (myints, myints + n);\n\n    cout << \"#1 Beads falling down: \";\n    for (int i=0; i < fifth.size(); i++)\n        distribute (fifth[i], list);\n    cout << '\\n';\n\n    cout << \"\\nBeads on their sides: \";\n    for (int i=0; i < list.size(); i++)\n        cout << \" \" << list[i];\n    cout << '\\n';\n\n    \n\n    cout << \"#2 Beads right side up: \";\n    for (int i=0; i < list.size(); i++)\n        distribute (list[i], list2);\n    cout << '\\n';\n\n    return list2;\n}\n\nint main() {\n    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};\n\tvector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i<sorted.size(); i++)\n\t\tcout << sorted[i] << ' ';\n}\n"}
{"id": 58730, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n#include <string>\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const *argv[])\n{\n    \n    \n    \n    \n    uint64_t tmpres = mp::pow(mp::mpz_int(4)\n                            , mp::pow(mp::mpz_int(3)\n                                    , 2).convert_to<uint64_t>()\n                                      ).convert_to<uint64_t>();\n    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);\n    std::string s = res.str();\n    std::cout << s.substr(0, 20) \n              << \"...\"\n              << s.substr(s.length() - 20, 20) << std::endl;\n    return 0;\n}\n"}
{"id": 58731, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 58732, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "C++": "\n\n#include <QImage>\n#include <QPainter>\n\nint main() {\n    const QColor black(0, 0, 0);\n    const QColor white(255, 255, 255);\n\n    const int size = 300;\n    const double diameter = 0.6 * size;\n\n    QImage image(size, size, QImage::Format_RGB32);\n    QPainter painter(&image);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    QLinearGradient linearGradient(0, 0, 0, size);\n    linearGradient.setColorAt(0, white);\n    linearGradient.setColorAt(1, black);\n\n    QBrush brush(linearGradient);\n    painter.fillRect(QRect(0, 0, size, size), brush);\n\n    QPointF point1(0.4 * size, 0.4 * size);\n    QPointF point2(0.45 * size, 0.4 * size);\n    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n    radialGradient.setColorAt(0, white);\n    radialGradient.setColorAt(1, black);\n\n    QBrush brush2(radialGradient);\n    painter.setPen(Qt::NoPen);\n    painter.setBrush(brush2);\n    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));\n\n    image.save(\"sphere.png\");\n    return 0;\n}\n"}
{"id": 58733, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 58734, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "C++": "#include <boost/math/common_factor.hpp>\n#include <iostream>\n\nint main( ) {\n   std::cout << \"The least common multiple of 12 and 18 is \" << \n      boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n      << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \" !\" << std::endl ;\n   return 0 ;\n}\n"}
{"id": 58735, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "C++": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(){\n\tsrand(time(NULL)); \n\twhile(true){\n\t\tconst int a = rand() % 20; \n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n"}
{"id": 58736, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n  auto water = 0;\n  const auto rows = *std::max_element(std::begin(b), std::end(b));\n  const auto cols = std::size(b);\n  std::vector<std::vector<int>> g(rows);\n  for (auto& r : g) {\n    for (auto i = 0; i < cols; ++i) {\n      r.push_back(EMPTY);\n    }\n  }\n  for (auto c = 0; c < cols; ++c) {\n    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n      g[r][c] = WALL;\n    }\n  }\n  for (auto c = 0; c < cols - 1; ++c) {\n    auto start_row = rows - b[c];\n    while (start_row < rows) {\n      if (g[start_row][c] == EMPTY) break;\n      auto c2 = c + 1;\n      bool hitWall = false;\n      while (c2 < cols) {\n        if (g[start_row][c2] == WALL) {\n          hitWall = true;\n          break;\n        }\n        ++c2;\n      }\n      if (hitWall) {\n        for (auto i = c + 1; i < c2; ++i) {\n          g[start_row][i] = WATER;\n          ++water;\n        }\n      }\n      ++start_row;\n    }\n  }\n  return water;\n}\n\nint main() {\n  std::vector<std::vector<int>> b = {\n    { 1, 5, 3, 7, 2 },\n    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n    { 5, 5, 5, 5 },\n    { 5, 6, 7, 8 },\n    { 8, 7, 7, 6 },\n    { 6, 7, 10, 7, 6 }\n  };\n  for (const auto v : b) {\n    auto water = fill(v);\n    std::cout << water << \" water drops.\" << std::endl;\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 58737, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <string>\n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n    if (n % 4 == 0)\n        return false;\n    for (integer p = 3; p * p <= n; p += 2) {\n        integer count = 0;\n        for (; n % p == 0; n /= p) {\n            if (++count > 1)\n                return false;\n        }\n    }\n    return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n    std::cout << \"Square-free numbers between \" << from\n        << \" and \" << to << \":\\n\";\n    std::string line;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i)) {\n            if (!line.empty())\n                line += ' ';\n            line += std::to_string(i);\n            if (line.size() >= 80) {\n                std::cout << line << '\\n';\n                line.clear();\n            }\n        }\n    }\n    if (!line.empty())\n        std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n    integer count = 0;\n    for (integer i = from; i <= to; ++i) {\n        if (square_free(i))\n            ++count;\n    }\n    std::cout << \"Number of square-free numbers between \"\n        << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n    print_square_free_numbers(1, 145);\n    print_square_free_numbers(1000000000000LL, 1000000000145LL);\n    print_square_free_count(1, 100);\n    print_square_free_count(1, 1000);\n    print_square_free_count(1, 10000);\n    print_square_free_count(1, 100000);\n    print_square_free_count(1, 1000000);\n    return 0;\n}\n"}
{"id": 58738, "name": "Jaro similarity", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\ndouble jaro(const std::string s1, const std::string s2) {\n    const uint l1 = s1.length(), l2 = s2.length();\n    if (l1 == 0)\n        return l2 == 0 ? 1.0 : 0.0;\n    const uint match_distance = std::max(l1, l2) / 2 - 1;\n    bool s1_matches[l1];\n    bool s2_matches[l2];\n    std::fill(s1_matches, s1_matches + l1, false);\n    std::fill(s2_matches, s2_matches + l2, false);\n    uint matches = 0;\n    for (uint i = 0; i < l1; i++)\n    {\n        const int end = std::min(i + match_distance + 1, l2);\n        for (int k = std::max(0u, i - match_distance); k < end; k++)\n            if (!s2_matches[k] && s1[i] == s2[k])\n            {\n                s1_matches[i] = true;\n                s2_matches[k] = true;\n                matches++;\n                break;\n            }\n    }\n    if (matches == 0)\n        return 0.0;\n    double t = 0.0;\n    uint k = 0;\n    for (uint i = 0; i < l1; i++)\n        if (s1_matches[i])\n        {\n            while (!s2_matches[k]) k++;\n            if (s1[i] != s2[k]) t += 0.5;\n            k++;\n        }\n\n    const double m = matches;\n    return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n    using namespace std;\n    cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n    cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n    cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n    return 0;\n}\n"}
{"id": 58739, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <vector>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    printf(\"Base %2d:\", base);\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    std::vector<int> cnt(base, 0);\n\n    for (int i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    int minTurn = INT_MAX;\n    int maxTurn = INT_MIN;\n    int portion = 0;\n    for (int i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 58740, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "C++": "#include <ciso646>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\n\n\n\n#include <exception>\n#include <stdexcept>\ntemplate <typename...Args> std::runtime_error error( Args...args )\n{\n  return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n\n\n\n\n\n\n\n\n\ntemplate <typename T> struct stack : public std::vector <T>\n{\n  using base_type = std::vector <T> ;\n  T        push ( const T& x ) { base_type::push_back( x ); return x; }\n  const T& top  ()             { return base_type::back(); }\n  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }\n  bool     empty()             { return base_type::empty(); }\n};\n\n\nusing Number = double;\n\n\n\n\n\n\nusing Operator_Name = string;\nusing Precedence    = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map <Operator_Name, Operator_Info>  Operators =\n{\n  { \"^\", { 4, Associates::right_to_left } },\n  { \"*\", { 3, Associates::left_to_right } },\n  { \"/\", { 3, Associates::left_to_right } },\n  { \"+\", { 2, Associates::left_to_right } },\n  { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n\nusing Token = string;\n\nbool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator         ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n\n\n\n\n\n\ntemplate <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )\n{\n  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? \" \" : \"\") << x;  return outs;\n}\n\n\n\n\n\n\n\n\n#include <iomanip>\n\nstruct Progressive_Display\n{\n  string token_name;\n  string token_type;\n\n  Progressive_Display()  \n  {\n    std::cout << \"\\n\"\n      \"  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\\n\"\n      \"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\\n\";\n  }\n\n  Progressive_Display& operator () ( const Token& token )  \n  {\n    token_name = token;\n    token_type = is_operator   ( token ) ? \"op\"\n               : is_parenthesis( token ) ? \"()\"\n               : is_number     ( token ) ? \"num\"\n               : \"\";\n    return *this;\n  }\n\n  Progressive_Display& operator () (  \n    const string         & description,\n    const stack  <Token> & stack,\n    const vector <Token> & output )\n  {\n    std::cout                                                              << std::right\n      << std::setw(  7 ) << token_name                            << \" │ \" << std::left\n      << std::setw(  4 ) << token_type                            << \" │ \"\n      << std::setw( 16 ) << description                           << \" │ \"\n      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" │ \"\n      <<                    output                                << \"\\n\";\n    return operator () ( \"\" );  \n  }\n};\n\n\nvector <Token> parse( const vector <Token> & tokens )\n\n{\n  vector <Token> output;\n  stack  <Token> stack;\n\n  Progressive_Display display;\n\n  for (auto token : tokens)  \n\n    \n    if (is_number( token ))\n    {\n      output.push_back( token );\n      display( token )( \"num --> output\", stack, output );\n    }\n\n    \n    else if (is_operator( token ) or is_parenthesis( token ))\n    {\n      display( token );\n\n      if (!is_open_parenthesis( token ))\n      {\n        \n        \n        \n        \n        while (!stack.empty()\n          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n               or (precedence( stack.top() ) > precedence( token ))\n               or (    (precedence( stack.top() ) == precedence( token ))\n                   and (associativity( token ) == Associates::left_to_right))))\n        {\n          output.push_back( stack.pop() );\n          display( \"pop --> output\", stack, output );\n        }\n\n        \n        if (is_close_parenthesis( token ))\n        {\n          stack.pop();\n          display( \"pop\", stack, output );\n        }\n      }\n\n      \n      if (!is_close_parenthesis( token ))\n      {\n        stack.push( token );\n        display( \"push op\", stack, output );\n      }\n    }\n\n    \n    else throw error( \"unexpected token: \", token );\n\n  \n\n  display( \"END\" );\n  while (!stack.empty())\n  {\n    output.push_back( stack.pop() );\n    display( \"pop --> output\", stack, output );\n  }\n\n  return output;\n}\n\n\nint main( int argc, char** argv )\n\ntry\n{\n  auto tokens   = vector <Token> ( argv+1, argv+argc );\n  auto rpn_expr = parse( tokens );\n  std::cout\n    << \"\\nInfix = \" << tokens\n    << \"\\nRPN   = \" << rpn_expr\n    << \"\\n\";\n}\ncatch (std::exception e)\n{\n  std::cerr << \"error: \" << e.what() << \"\\n\";\n  return 1;\n}\n"}
{"id": 58741, "name": "Prime triangle", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n", "C++": "#include <cassert>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nbool is_prime(unsigned int n) {\n    assert(n > 0 && n < 64);\n    return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate <typename Iterator>\nbool prime_triangle_row(Iterator begin, Iterator end) {\n    if (std::distance(begin, end) == 2)\n        return is_prime(*begin + *(begin + 1));\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            if (prime_triangle_row(begin + 1, end))\n                return true;\n            std::iter_swap(i, begin + 1);\n        }\n    }\n    return false;\n}\n\ntemplate <typename Iterator>\nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n    if (std::distance(begin, end) == 2) {\n        if (is_prime(*begin + *(begin + 1)))\n            ++count;\n        return;\n    }\n    for (auto i = begin + 1; i + 1 != end; ++i) {\n        if (is_prime(*begin + *i)) {\n            std::iter_swap(i, begin + 1);\n            prime_triangle_count(begin + 1, end, count);\n            std::iter_swap(i, begin + 1);\n        }\n    }\n}\n\ntemplate <typename Iterator>\nvoid print(Iterator begin, Iterator end) {\n    if (begin == end)\n        return;\n    auto i = begin;\n    std::cout << std::setw(2) << *i++;\n    for (; i != end; ++i)\n        std::cout << ' ' << std::setw(2) << *i;\n    std::cout << '\\n';\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        if (prime_triangle_row(v.begin(), v.end()))\n            print(v.begin(), v.end());\n    }\n    std::cout << '\\n';\n    for (unsigned int n = 2; n < 21; ++n) {\n        std::vector<unsigned int> v(n);\n        std::iota(v.begin(), v.end(), 1);\n        int count = 0;\n        prime_triangle_count(v.begin(), v.end(), count);\n        if (n > 2)\n            std::cout << ' ';\n        std::cout << count;\n    }\n    std::cout << '\\n';\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> duration(end - start);\n    std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}\n"}
{"id": 58742, "name": "Trabb Pardo–Knuth algorithm", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n", "C++": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nint main( ) {\n   std::vector<double> input( 11 ) , results( 11 ) ;\n   std::cout << \"Please enter 11 numbers!\\n\" ;\n   for ( int i = 0 ; i < input.size( ) ; i++ ) \n      std::cin >> input[i];\n      \n   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n   for ( int i = 10 ; i > -1 ; i-- ) {\n      std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n      if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n      else \n\t std::cout << results[ i ] << \" !\" ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 58743, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "C++": "#include <iostream>\n\nstd::string middleThreeDigits(int n)\n{\n    auto number = std::to_string(std::abs(n));\n    auto length = number.size();\n\n    if (length < 3) {\n        return \"less than three digits\";\n    } else if (length % 2 == 0) {\n        return \"even number of digits\";\n    } else {\n        return number.substr(length / 2 - 1, 3);\n    }\n}\n\nint main()\n{\n    auto values {123, 12345, 1234567, 987654321, 10001,\n                 -10001, -123, -100, 100, -12345,\n                 1, 2, -1, -10, 2002, -2002, 0};\n\n    for (auto&& v : values) {\n        std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n                     middleThreeDigits(v) << \"\\n\";\n    }\n}\n"}
{"id": 58744, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "C++": "#include <iostream>\n#include <cctype>\n#include <functional>\n\nusing namespace std;\n\nbool odd()\n{\n  function<void ()> prev = []{};\n  while(true) {\n    int c = cin.get();\n    if (!isalpha(c)) {\n      prev();\n      cout.put(c);\n      return c != '.';\n    }\n    prev = [=] { cout.put(c); prev();  };\n  }\n}\n\nbool even() \n{\n  while(true) {\n    int c;\n    cout.put(c = cin.get());\n    if (!isalpha(c)) return c != '.';\n  }\n}\n\n\nint main()\n{\n  bool e = false;\n  while( e ? odd() : even() ) e = !e;\n  return 0;\n}\n"}
{"id": 58745, "name": "Stern-Brocot sequence", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\nunsigned gcd( unsigned i, unsigned j ) {\n    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector<unsigned>& seq, int c ) {\n    if( 1500 == seq.size() ) return;\n    unsigned t = seq.at( c ) + seq.at( c + 1 );\n    seq.push_back( t );\n    seq.push_back( seq.at( c + 1 ) );\n    createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n    std::vector<unsigned> seq( 2, 1 );\n    createSequence( seq, 0 );\n\n    std::cout << \"First fifteen members of the sequence:\\n    \";\n    for( unsigned x = 0; x < 15; x++ ) {\n        std::cout << seq[x] << \" \";    \n    }\n\n    std::cout << \"\\n\\n\";    \n    for( unsigned x = 1; x < 11; x++ ) {\n        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );\n        if( i != seq.end() ) {\n            std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n        }\n    }\n\n    std::cout << \"\\n\";\n    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );\n    if( i != seq.end() ) {\n        std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n    unsigned g;\n    bool f = false;\n    for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n        g =  gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n        std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n                  << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n    }\n    std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n    return 0;\n}\n"}
{"id": 58746, "name": "Sierpinski pentagon", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n", "C++": "#include <iomanip>\n#include <iostream>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nconstexpr double degrees(double deg) {\n    const double tau = 2.0 * M_PI;\n    return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n\nstruct Point {\n    double x, y;\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n    auto f(std::cout.flags());\n    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n    std::cout.flags(f);\n    return os;\n}\n\n\nstruct Turtle {\nprivate:\n    Point pos;\n    double theta;\n    bool tracing;\n\npublic:\n    Turtle() : theta(0.0), tracing(false) {\n        pos.x = 0.0;\n        pos.y = 0.0;\n    }\n\n    Turtle(double x, double y) : theta(0.0), tracing(false) {\n        pos.x = x;\n        pos.y = y;\n    }\n\n    Point position() {\n        return pos;\n    }\n    void position(const Point& p) {\n        pos = p;\n    }\n\n    double heading() {\n        return theta;\n    }\n    void heading(double angle) {\n        theta = angle;\n    }\n\n    \n    void forward(double dist) {\n        auto dx = dist * cos(theta);\n        auto dy = dist * sin(theta);\n\n        pos.x += dx;\n        pos.y += dy;\n\n        if (tracing) {\n            std::cout << pos;\n        }\n    }\n\n    \n    void right(double angle) {\n        theta -= angle;\n    }\n\n    \n    void begin_fill() {\n        if (!tracing) {\n            std::cout << \"<polygon points=\\\"\";\n            tracing = true;\n        }\n    }\n    void end_fill() {\n        if (tracing) {\n            std::cout << \"\\\"/>\\n\";\n            tracing = false;\n        }\n    }\n};\n\n\nvoid pentagon(Turtle& turtle, double size) {\n    turtle.right(degrees(36));\n    turtle.begin_fill();\n    for (size_t i = 0; i < 5; i++) {\n        turtle.forward(size);\n        turtle.right(degrees(72));\n    }\n    turtle.end_fill();\n}\n\n\nvoid sierpinski(int order, Turtle& turtle, double size) {\n    turtle.heading(0.0);\n    auto new_size = size * side_ratio;\n\n    if (order-- > 1) {\n        \n        for (size_t j = 0; j < 4; j++) {\n            turtle.right(degrees(36));\n\n            double small = size * side_ratio / part_ratio;\n            auto distList = { small, size, size, small };\n            auto dist = *(distList.begin() + j);\n\n            Turtle spawn{ turtle.position().x, turtle.position().y };\n            spawn.heading(turtle.heading());\n            spawn.forward(dist);\n\n            \n            sierpinski(order, spawn, new_size);\n        }\n\n        \n        sierpinski(order, turtle, new_size);\n    } else {\n        \n        pentagon(turtle, size);\n    }\n    if (order > 0) {\n        std::cout << '\\n';\n    }\n}\n\n\nint main() {\n    const int order = 5;\n    double size = 500;\n\n    Turtle turtle{ size / 2.0, size };\n\n    std::cout << \"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\"?>\\n\";\n    std::cout << \"<!DOCTYPE svg PUBLIC \\\" -\n    std::cout << \"    \\\"http:\n    std::cout << \"<svg height=\\\"\" << size << \"\\\" width=\\\"\" << size << \"\\\" style=\\\"fill:blue\\\" transform=\\\"translate(\" << size / 2 << \", \" << size / 2 << \") rotate(-36)\\\"\\n\";\n    std::cout << \"    version=\\\"1.1\\\" xmlns=\\\"http:\n\n    size *= part_ratio;\n    sierpinski(order, turtle, size);\n\n    std::cout << \"</svg>\";\n}\n"}
{"id": 58747, "name": "Rep-string", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n", "C++": "#include <string>\n#include <vector>\n#include <boost/regex.hpp>\n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n   std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n   boost::regex e ( regex ) ;\n   boost::smatch what ;\n   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n      std::string firstbracket( what[1 ] ) ;\n      std::string secondbracket( what[ 2 ] ) ;\n      if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t    firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket  ;\n      }\n   }\n   return !repunit.empty( ) ;\n}\n\nint main( ) {\n   std::vector<std::string> teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n      \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n   std::string theRep ;\n   for ( std::string myString : teststrings ) {\n      if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n      }\n      else {\n\t std::cout << myString << \" is no rep string!\" ;\n      }\n      theRep.clear( ) ;\n      std::cout << std::endl ;\n   }\n   return 0 ;\n}\n"}
{"id": 58748, "name": "Literals_String", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n", "C++": "auto strA = R\"(this is\na newline-separated\nraw string)\";\n"}
{"id": 58749, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "C++": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 58750, "name": "Parse an IP Address", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n", "C++": "#include <boost/asio/ip/address.hpp>\n#include <cstdint>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <string>\n\nusing boost::asio::ip::address;\nusing boost::asio::ip::address_v4;\nusing boost::asio::ip::address_v6;\nusing boost::asio::ip::make_address;\nusing boost::asio::ip::make_address_v4;\nusing boost::asio::ip::make_address_v6;\n\ntemplate<typename uint>\nbool parse_int(const std::string& str, int base, uint& n) {\n    try {\n        size_t pos = 0;\n        unsigned long u = stoul(str, &pos, base);\n        if (pos != str.length() || u > std::numeric_limits<uint>::max())\n            return false;\n        n = static_cast<uint>(u);\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {\n    size_t pos = input.rfind(':');\n    if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()\n        && parse_int(input.substr(pos + 1), 10, port) && port > 0) {\n        if (input[0] == '[' && input[pos - 1] == ']') {\n            \n            addr = make_address_v6(input.substr(1, pos - 2));\n            return;\n        } else {\n            try {\n                \n                addr = make_address_v4(input.substr(0, pos));\n                return;\n            } catch (const std::exception& ex) {\n                \n            }\n        }\n    }\n    port = 0;\n    addr = make_address(input);\n}\n\nvoid print_address_and_port(const address& addr, uint16_t port) {\n    std::cout << std::hex << std::uppercase << std::setfill('0');\n    if (addr.is_v4()) {\n        address_v4 addr4 = addr.to_v4();\n        std::cout << \"address family: IPv4\\n\";\n        std::cout << \"address number: \" << std::setw(8) << addr4.to_uint() << '\\n';\n    } else if (addr.is_v6()) {\n        address_v6 addr6 = addr.to_v6();\n        address_v6::bytes_type bytes(addr6.to_bytes());\n        std::cout << \"address family: IPv6\\n\";\n        std::cout << \"address number: \";\n        for (unsigned char byte : bytes)\n            std::cout << std::setw(2) << static_cast<unsigned int>(byte);\n        std::cout << '\\n';\n    }\n    if (port != 0)\n        std::cout << \"port: \" << std::dec << port << '\\n';\n    else\n        std::cout << \"port not specified\\n\";\n}\n\nvoid test(const std::string& input) {\n    std::cout << \"input: \" << input << '\\n';\n    try {\n        address addr;\n        uint16_t port = 0;\n        parse_ip_address_and_port(input, addr, port);\n        print_address_and_port(addr, port);\n    } catch (const std::exception& ex) {\n        std::cout << \"parsing failed\\n\";\n    }\n    std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n    test(\"127.0.0.1\");\n    test(\"127.0.0.1:80\");\n    test(\"::ffff:127.0.0.1\");\n    test(\"::1\");\n    test(\"[::1]:80\");\n    test(\"1::80\");\n    test(\"2605:2700:0:3::4713:93e3\");\n    test(\"[2605:2700:0:3::4713:93e3]:80\");\n    return 0;\n}\n"}
{"id": 58751, "name": "Textonyms", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n", "C++": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nstruct Textonym_Checker {\nprivate:\n    int total;\n    int elements;\n    int textonyms;\n    int max_found;\n    std::vector<std::string> max_strings;\n    std::unordered_map<std::string, std::vector<std::string>> values;\n\n    int get_mapping(std::string &result, const std::string &input)\n    {\n        static std::unordered_map<char, char> mapping = {\n            {'A', '2'}, {'B', '2'}, {'C', '2'},\n            {'D', '3'}, {'E', '3'}, {'F', '3'},\n            {'G', '4'}, {'H', '4'}, {'I', '4'},\n            {'J', '5'}, {'K', '5'}, {'L', '5'},\n            {'M', '6'}, {'N', '6'}, {'O', '6'},\n            {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n            {'T', '8'}, {'U', '8'}, {'V', '8'},\n            {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n        };\n\n        result = input;\n        for (char &c : result) {\n            if (!isalnum(c)) return 0;\n            if (isalpha(c)) c = mapping[toupper(c)];\n        }\n\n        return 1;\n    }\n\npublic:\n    Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n    ~Textonym_Checker() { }\n\n    void add(const std::string &str) {\n        std::string mapping;\n        total++;\n\n        if (!get_mapping(mapping, str)) return;\n\n        const int num_strings = values[mapping].size();\n\n        if (num_strings == 1) textonyms++;\n        elements++;\n\n        if (num_strings > max_found) {\n            max_strings.clear();\n            max_strings.push_back(mapping);\n            max_found = num_strings;\n        }\n        else if (num_strings == max_found)\n            max_strings.push_back(mapping);\n\n        values[mapping].push_back(str);\n    }\n\n    void results(const std::string &filename) {\n        std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n        std::cout << \"There are \" << elements << \" words in \" << filename;\n        std::cout << \" which can be represented by the digit key mapping.\\n\";\n        std::cout << \"They require \" << values.size() <<\n                     \" digit combinations to represent them.\\n\";\n        std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n        std::cout << \"The numbers mapping to the most words map to \";\n        std::cout << max_found + 1 << \" words each:\\n\";\n\n        for (auto it1 : max_strings) {\n            std::cout << '\\t' << it1 << \" maps to: \";\n            for (auto it2 : values[it1])\n                std::cout << it2 << \" \";\n            std::cout << '\\n';\n        }\n        std::cout << '\\n';\n    }\n\n    void match(const std::string &str) {\n        auto match = values.find(str);\n\n        if (match == values.end()) {\n            std::cout << \"Key '\" << str << \"' not found\\n\";\n        }\n        else {\n            std::cout << \"Key '\" << str << \"' matches: \";\n            for (auto it : values[str])\n                std::cout << it << \" \";\n            std::cout << '\\n';\n        }\n    }\n};\n\nint main()\n{\n    auto filename = \"unixdict.txt\";\n    std::ifstream input(filename);\n    Textonym_Checker tc;\n\n    if (input.is_open()) {\n        std::string line;\n        while (getline(input, line))\n            tc.add(line);\n    }\n\n    input.close();\n\n    tc.results(filename);\n    tc.match(\"001\");\n    tc.match(\"228\");\n    tc.match(\"27484247\");\n    tc.match(\"7244967473642\");\n}\n"}
{"id": 58752, "name": "Range extraction", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n", "C++": "#include <iostream>\n#include <iterator>\n#include <cstddef>\n\ntemplate<typename InIter>\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n  if (begin == end)\n    return;\n\n  int current = *begin++;\n  os << current;\n  int count = 1;\n\n  while (begin != end)\n  {\n    int next = *begin++;\n    if (next == current+1)\n      ++count;\n    else\n    {\n      if (count > 2)\n        os << '-';\n      else\n        os << ',';\n      if (count > 1)\n        os << current << ',';\n      os << next;\n      count = 1;\n    }\n    current = next;\n  }\n\n  if (count > 1)\n    os << (count > 2? '-' : ',') << current;\n}\n\ntemplate<typename T, std::size_t n>\n T* end(T (&array)[n])\n{\n  return array+n;\n}\n\nint main()\n{\n  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n                 37, 38, 39 };\n\n  extract_ranges(data, end(data), std::cout);\n  std::cout << std::endl;\n}\n"}
{"id": 58753, "name": "Type detection", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n", "C++": "#include <iostream>\n\ntemplate <typename T>\nauto typeString(const T&) {\n    return typeid(T).name();\n}\n\nclass C {};\nstruct S {};\n\nint main() {\n    std::cout << typeString(1) << '\\n';\n    std::cout << typeString(1L) << '\\n';\n    std::cout << typeString(1.0f) << '\\n';\n    std::cout << typeString(1.0) << '\\n';\n    std::cout << typeString('c') << '\\n';\n    std::cout << typeString(\"string\") << '\\n';\n    std::cout << typeString(C{}) << '\\n';\n    std::cout << typeString(S{}) << '\\n';\n    std::cout << typeString(nullptr) << '\\n';\n}\n"}
{"id": 58754, "name": "Maximum triangle path sum", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n", "C++": "\n#include <iostream>\n\nint main( int argc, char* argv[] )\n{\n    int triangle[] = \n    {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n    };\n\n    const int size = sizeof( triangle ) / sizeof( int );\n    const int tn = static_cast<int>(sqrt(2.0 * size));\n    assert(tn * (tn + 1) == 2 * size);    \n\n    \n    for (int n = tn - 1; n > 0; --n)   \n        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) \n            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n    std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"}
{"id": 58755, "name": "Zhang-Suen thinning algorithm", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <valarray>\nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n    friend class ZhangSuen;\n    using pixel_t = char;\n    static const pixel_t BLACK_PIX;\n    static const pixel_t WHITE_PIX;\n\n    Image(unsigned width = 1, unsigned height = 1) \n    : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n    {}\n    Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n    {}\n    Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n    {}\n    ~Image() = default;\n    Image& operator=(const Image& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = i.data_;\n        }\n        return *this;\n    }\n    Image& operator=(Image&& i) {\n        if (this != &i) {\n            width_ = i.width_;\n            height_ = i.height_;\n            data_ = std::move(i.data_);\n        }\n        return *this;\n    }\n    size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n    bool operator()(unsigned x, unsigned y) {\n        return data_[idx(x, y)];\n    }\n    friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n        o << i.width_ << \" x \" << i.height_ << std::endl;\n        size_t px = 0;\n        for(const auto& e : i.data_) {\n            o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n            if (++px % i.width_ == 0)\n                o << std::endl;\n        }\n        return o << std::endl;\n    }\n    friend std::istream& operator>>(std::istream& in, Image& img) {\n        auto it = std::begin(img.data_);\n        const auto end = std::end(img.data_);\n        Image::pixel_t tmp;\n        while(in && it != end) {\n            in >> tmp;\n            if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n                throw \"Bad character found in image\";\n            *it = (tmp == Image::BLACK_PIX)?1:0;\n            ++it;\n        }\n        return in;\n    }\n    unsigned width() const noexcept { return width_; }\n    unsigned height() const noexcept { return height_; }\n    struct Neighbours {\n        \n        \n        \n        Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n        : img_{img}\n        , p1_{img.idx(p1_x, p1_y)}\n        , p2_{p1_ - img.width()}\n        , p3_{p2_ + 1}\n        , p4_{p1_ + 1}\n        , p5_{p4_ + img.width()}\n        , p6_{p5_ - 1}\n        , p7_{p6_ - 1}\n        , p8_{p1_ - 1}\n        , p9_{p2_ - 1} \n        {}\n        const Image& img_;\n        const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n        const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n        const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n        const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n        const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n        const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n        const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n        const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n        const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n        const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n    };\n    Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n    unsigned height_ { 0 };\n    unsigned width_ { 0 };\n    std::valarray<pixel_t> data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n    \n    unsigned transitions_white_black(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += (a.p9() == 0) && a.p2();\n        sum += (a.p2() == 0) && a.p3();\n        sum += (a.p3() == 0) && a.p4();\n        sum += (a.p8() == 0) && a.p9();\n        sum += (a.p4() == 0) && a.p5();\n        sum += (a.p7() == 0) && a.p8();\n        sum += (a.p6() == 0) && a.p7();\n        sum += (a.p5() == 0) && a.p6();\n        return sum;\n    }\n\n    \n    unsigned black_pixels(const Image::Neighbours& a) const {\n        unsigned sum = 0;\n        sum += a.p9();\n        sum += a.p2();\n        sum += a.p3();\n        sum += a.p8();\n        sum += a.p4();\n        sum += a.p7();\n        sum += a.p6();\n        sum += a.p5();\n        return sum;\n    }\n    const Image& operator()(const Image& img) {\n        tmp_a_ = img;\n        size_t changed_pixels = 0;\n        do {\n            changed_pixels = 0;\n            \n            tmp_b_ = tmp_a_;\n            for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n                    if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n                        auto n = tmp_a_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p6() == 0)\n                                && (n.p4() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_b_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n            \n            tmp_a_ = tmp_b_;\n            for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n                for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n                    if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n                        auto n = tmp_b_.neighbours(x, y);\n                        auto bp = black_pixels(n);\n                        if (bp >= 2 && bp <= 6) {\n                            auto tr = transitions_white_black(n);\n                            if (    tr == 1 \n                                && (n.p2() * n.p4() * n.p8() == 0)\n                                && (n.p2() * n.p6() * n.p8() == 0)\n                                ) {\n                                tmp_a_.data_[n.p1_] = 0;\n                                ++changed_pixels;\n                            }\n                        }\n                    } \n                }\n            }\n        } while(changed_pixels > 0);\n        return tmp_a_;\n    }\nprivate:\n    Image tmp_a_;\n    Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n    using namespace std;\n    Image img(32, 10);\n    istringstream iss{input};\n    iss >> img;\n    cout << img;\n    cout << \"ZhangSuen\" << endl;\n    ZhangSuen zs;\n    Image res = std::move(zs(img));\n    cout << res << endl;\n\n    Image img2(58,18);\n    istringstream iss2{input2};\n    iss2 >> img2;\n    cout << img2;\n    cout << \"ZhangSuen with big image\" << endl;\n    Image res2 = std::move(zs(img2));\n    cout << res2 << endl;\n    return 0;\n}\n"}
{"id": 58756, "name": "Variable declaration reset", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n", "C++": "#include <array>\n#include <iostream>\n\nint main()\n{\n  constexpr std::array s {1,2,2,3,4,4,5};\n\n  if(!s.empty())\n  {\n    int previousValue = s[0];\n\n    for(size_t i = 1; i < s.size(); ++i)\n    {\n      \n      const int currentValue = s[i];\n\n      if(i > 0 && previousValue == currentValue)\n      {\n        std::cout << i << \"\\n\";\n      }\n\n      previousValue = currentValue;\n    }\n  }\n}\n"}
{"id": 58757, "name": "Koch 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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n", "C++": "\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nconstexpr double sqrt3_2 = 0.86602540378444; \n\nstruct point {\n    double x;\n    double y;\n};\n\nstd::vector<point> koch_next(const std::vector<point>& points) {\n    size_t size = points.size();\n    std::vector<point> output(4*(size - 1) + 1);\n    double x0, y0, x1, y1;\n    size_t j = 0;\n    for (size_t i = 0; i + 1 < size; ++i) {\n        x0 = points[i].x;\n        y0 = points[i].y;\n        x1 = points[i + 1].x;\n        y1 = points[i + 1].y;\n        double dy = y1 - y0;\n        double dx = x1 - x0;\n        output[j++] = {x0, y0};\n        output[j++] = {x0 + dx/3, y0 + dy/3};\n        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n    }\n    output[j] = {x1, y1};\n    return output;\n}\n\nstd::vector<point> koch_points(int size, int iterations) {\n    double length = size * sqrt3_2 * 0.95;\n    double x = (size - length)/2;\n    double y = size/2 - length * sqrt3_2/3;\n    std::vector<point> points{\n        {x, y},\n        {x + length/2, y + length * sqrt3_2},\n        {x + length, y},\n        {x, y}\n    };\n    for (int i = 0; i < iterations; ++i)\n        points = koch_next(points);\n    return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='black'/>\\n\";\n    out << \"<path stroke-width='1' stroke='white' fill='none' d='\";\n    auto points(koch_points(size, iterations));\n    for (size_t i = 0, n = points.size(); i < n; ++i)\n        out << (i == 0 ? \"M\" : \"L\") << points[i].x << ',' << points[i].y << '\\n';\n    out << \"z'/>\\n</svg>\\n\";\n}\n\nint main() {\n    std::ofstream out(\"koch_curve.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return EXIT_FAILURE;\n    }\n    koch_curve_svg(out, 600, 5);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 58758, "name": "Words from neighbour ones", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char** argv) {\n    const int min_length = 9;\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string line;\n    std::vector<std::string> words;\n    while (getline(in, line)) {\n        if (line.size() >= min_length)\n            words.push_back(line);\n    }\n    std::sort(words.begin(), words.end());\n    std::string previous_word;\n    int count = 0;\n    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {\n        std::string word;\n        word.reserve(min_length);\n        for (size_t j = 0; j < min_length; ++j)\n            word += words[i + j][j];\n        if (previous_word == word)\n            continue;\n        auto w = std::lower_bound(words.begin(), words.end(), word);\n        if (w != words.end() && *w == word)\n            std::cout << std::setw(2) << ++count << \". \" << word << '\\n';\n        previous_word = word;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 58759, "name": "Magic squares of doubly even order", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\nusing namespace std;\n\nclass magicSqr\n{\npublic: \n    magicSqr( int d ) {\n        while( d % 4 > 0 ) { d++; }\n        sz = d;\n        sqr = new int[sz * sz];\n        fillSqr();\n    }\n    ~magicSqr() { delete [] sqr; }\n\n    void display() const {\n        cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr; cvr << sz * sz;\n        int l = cvr.str().size();\n \n        for( int y = 0; y < sz; y++ ) {\n            int yy = y * sz;\n            for( int x = 0; x < sz; x++ ) {\n                cout << setw( l + 2 ) << sqr[yy + x];\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\\n\";\n    }\nprivate:\n    void fillSqr() {\n        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n        int i = 0;\n        for( int curRow = 0; curRow < sz; curRow++ ) {\n            for( int curCol = 0; curCol < sz; curCol++ ) {\n                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n                i++;\n            }\n        }\n    }\n    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    int* sqr;\n    int sz;\n};\n \nint main( int argc, char* argv[] ) {\n    magicSqr s( 8 );\n    s.display();\n    return 0;\n}\n"}
{"id": 58760, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "C++": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\nclass MTF\n{\npublic:\n    string encode( string str )\n    {\n\tfillSymbolTable();\n\tvector<int> output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t    for( int i = 0; i < 26; i++ )\n\t    {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t    output.push_back( i );\n\t\t    moveToFront( i );\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    ostringstream ss;\n\t    ss << *it;\n\t    r += ss.str() + \" \";\n\t}\n\treturn r;\n    }\n\n    string decode( string str )\n    {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector<int> output;\n\tcopy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );\n\tstring r;\n\tfor( vector<int>::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t    r.append( 1, symbolTable[*it] );\n\t    moveToFront( *it );\n\t}\n\treturn r;\n    }\n\nprivate:\n    void moveToFront( int i )\n    {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t    symbolTable[z + 1] = symbolTable[z];\n\n        symbolTable[0] = t;\n    }\n\n    void fillSymbolTable()\n    {\n        for( int x = 0; x < 26; x++ )\n\t    symbolTable[x] = x + 'a';\n    }\n\n    char symbolTable[26];\n};\n\nint main()\n{\n    MTF mtf;\n    string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n    for( int x = 0; x < 3; x++ )\n    {\n        a = str[x];\n        cout << a << \" -> encoded = \";\n        a = mtf.encode( a );\n        cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n    }\n    return 0;\n}\n"}
{"id": 58761, "name": "Longest increasing subsequence", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n", "C++": "#include <vector>\n#include <list>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename T>\nstruct Node {\n    T value;\n    Node* prev_node;\n};\n\ntemplate <typename Container>\nContainer lis(const Container& values) {\n    using E = typename Container::value_type;\n    using NodePtr = Node<E>*;\n    using ConstNodePtr = const NodePtr;\n\n    std::vector<NodePtr> pileTops;\n    std::vector<Node<E>> nodes(values.size());\n\n    \n    auto cur_node = std::begin(nodes);\n    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)\n    {\n        auto node = &*cur_node;\n        node->value = *cur_value;\n\n        \n        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,\n            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });\n\n        if (lb != pileTops.begin())\n            node->prev_node = *std::prev(lb);\n\n        if (lb == pileTops.end())\n            pileTops.push_back(node);\n        else\n            *lb = node;\n    }\n\n    \n    \n    Container result(pileTops.size());\n    auto r = std::rbegin(result);\n\n    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)\n        *r = node->value;\n\n    return result;\n}\n\ntemplate <typename Container>\nvoid show_lis(const Container& values)\n{\n    auto&& result = lis(values);\n    for (auto& r : result) {\n        std::cout << r << ' ';\n    }\n    std::cout << std::endl;\n}\n\nint main() \n{\n    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });\n    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });\n}\n"}
{"id": 58762, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace detail {\n\ntemplate <typename ForwardIterator>\nclass tokenizer\n{\n\t\n\tForwardIterator _tbegin, _tend, _end;\n\t\npublic:\n\t\n\ttokenizer(ForwardIterator begin, ForwardIterator end)\n\t\t: _tbegin(begin), _tend(begin), _end(end)\n\t{ }\n\t\n\ttemplate <typename Lambda>\n\tbool next(Lambda istoken)\n\t{\n\t\tif (_tbegin == _end) {\n\t\t\treturn false;\n\t\t}\n\t\t_tbegin = _tend;\n\t\tfor (; _tend != _end && !istoken(*_tend); ++_tend) {\n\t\t\tif (*_tend == '\\\\' && std::next(_tend) != _end) {\n\t\t\t\t++_tend;\n\t\t\t}\n\t\t}\n\t\tif (_tend == _tbegin) {\n\t\t\t_tend++;\n\t\t}\n\t\treturn _tbegin != _end;\n\t}\n\t\n\tForwardIterator begin() const { return _tbegin; }\n\tForwardIterator end()   const { return _tend; }\n\tbool operator==(char c) { return *_tbegin == c; }\n\t\n};\n\ntemplate <typename List>\nvoid append_all(List & lista, const List & listb)\n{\n\tif (listb.size() == 1) {\n\t\tfor (auto & a : lista) {\n\t\t\ta += listb.back();\n\t\t}\n\t} else {\n\t\tList tmp;\n\t\tfor (auto & a : lista) {\n\t\t\tfor (auto & b : listb) {\n\t\t\t\ttmp.push_back(a + b);\n\t\t\t}\n\t\t}\n\t\tlista = std::move(tmp);\n\t}\n}\n\ntemplate <typename String, typename List, typename Tokenizer>\nList expand(Tokenizer & token)\n{\n\t\n\tstd::vector<List> alts{ { String() } };\n\t\n\twhile (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {\n\t\t\n\t\tif (token == '{') {\n\t\t\tappend_all(alts.back(), expand<String, List>(token));\n\t\t} else if (token == ',') {\n\t\t\talts.push_back({ String() });\n\t\t} else if (token == '}') {\n\t\t\tif (alts.size() == 1) {\n\t\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\t\ta = '{' + a + '}';\n\t\t\t\t}\n\t\t\t\treturn alts.back();\n\t\t\t} else {\n\t\t\t\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\t\t\t\talts.front().insert(alts.front().end(),\n\t\t\t\t\t\tstd::make_move_iterator(std::begin(alts[i])),\n\t\t\t\t\t\tstd::make_move_iterator(std::end(alts[i])));\n\t\t\t\t}\n\t\t\t\treturn std::move(alts.front());\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto & a : alts.back()) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tList result{ String{ '{' } };\n\tappend_all(result, alts.front());\n\tfor (std::size_t i = 1; i < alts.size(); i++) {\n\t\tfor (auto & a : result) {\n\t\t\ta += ',';\n\t\t}\n\t\tappend_all(result, alts[i]);\n\t}\n\treturn result;\n}\n\n} \n\ntemplate <\n\ttypename ForwardIterator,\n\ttypename String = std::basic_string<\n\t\ttypename std::iterator_traits<ForwardIterator>::value_type\n\t>,\n\ttypename List = std::vector<String>\n>\nList expand(ForwardIterator begin, ForwardIterator end)\n{\n\tdetail::tokenizer<ForwardIterator> token(begin, end);\n\tList list{ String() };\n\twhile (token.next([](char c) { return c == '{'; })) {\n\t\tif (token == '{') {\n\t\t\tdetail::append_all(list, detail::expand<String, List>(token));\n\t\t} else {\n\t\t\tfor (auto & a : list) {\n\t\t\t\ta.append(token.begin(), token.end());\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\ntemplate <\n\ttypename Range,\n\ttypename String = std::basic_string<typename Range::value_type>,\n\ttypename List = std::vector<String>\n>\nList expand(const Range & range)\n{\n\tusing Iterator = typename Range::const_iterator;\n\treturn expand<Iterator, String, List>(std::begin(range), std::end(range));\n}\n\nint main()\n{\n\t\n\tfor (std::string string : {\n\t\tR\"(~/{Downloads,Pictures}/*.{jpg,gif,png})\",\n\t\tR\"(It{{em,alic}iz,erat}e{d,}, please.)\",\n\t\tR\"({,{,gotta have{ ,\\, again\\, }}more }cowbell!)\",\n\t\tR\"({}} some {\\\\{edge,edgy} }{ cases, here\\\\\\})\",\n\t\tR\"(a{b{1,2}c)\",\n\t\tR\"(a{1,2}b}c)\",\n\t\tR\"(a{1,{2},3}b)\",\n\t\tR\"(a{b{1,2}c{}})\",\n\t\tR\"(more{ darn{ cowbell,},})\",\n\t\tR\"(ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr)\",\n\t\tR\"({a,{\\,b}c)\",\n\t\tR\"(a{b,{{c}})\",\n\t\tR\"({a{\\}b,c}d)\",\n\t\tR\"({a,b{{1,2}e}f)\",\n\t\tR\"({}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\})\",\n\t\tR\"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)\",\n\t}) {\n\t\tstd::cout << string << '\\n';\n\t\tfor (auto expansion : expand(string)) {\n\t\t\tstd::cout << \"    \" << expansion << '\\n';\n\t\t}\n\t\tstd::cout << '\\n';\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 58763, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n"}
{"id": 58764, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n", "C++": "#ifndef INTERACTION_H\n#define INTERACTION_H\n#include <QWidget>\n\nclass QPushButton ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass MyWidget : public QWidget {\n   Q_OBJECT \n\npublic :\n   MyWidget( QWidget *parent = 0 ) ;\nprivate :\n   QLineEdit *entryField ;\n   QPushButton *increaseButton ;\n   QPushButton *randomButton ;\n   QVBoxLayout *myLayout ;\nprivate slots :\n   void doIncrement( ) ;\n   void findRandomNumber( ) ;\n} ;\n#endif\n"}
{"id": 58765, "name": "One of n lines in a file", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n", "C++": "#include <random>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nmt19937 engine; \n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution<unsigned int> distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); \n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator<unsigned int> out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"}
{"id": 58766, "name": "Spelling of ordinal numbers", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n#include <cstdint>\n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n    const char* cardinal;\n    const char* ordinal;\n};\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n};\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n    return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n    constexpr size_t names_len = std::size(named_numbers);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return named_numbers[i];\n    }\n    return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n    std::string result;\n    if (n < 20)\n        result = get_name(small[n], ordinal);\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            result = get_name(tens[n/10 - 2], ordinal);\n        } else {\n            result = get_name(tens[n/10 - 2], false);\n            result += \"-\";\n            result += get_name(small[n % 10], ordinal);\n        }\n    } else {\n        const named_number& num = get_named_number(n);\n        integer p = num.number;\n        result = number_name(n/p, false);\n        result += \" \";\n        if (n % p == 0) {\n            result += get_name(num, ordinal);\n        } else {\n            result += get_name(num, false);\n            result += \" \";\n            result += number_name(n % p, ordinal);\n        }\n    }\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 58767, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "C++": "#include <iostream>\n \n\ntypedef unsigned long long bigint;\n \n\nusing namespace std;\n \n\nclass sdn\n{\npublic:\n    bool check( bigint n )\n    {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n    }\n \n    void displayAll( bigint s )\n    {\n\tfor( bigint y = 1; y < s; y++ )\n\t    if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n    }\n \nprivate:\n    bool compare( bigint n, int cc )\n    {\n\tbigint a;\n\twhile( cc )\n\t{\n\t    cc--; a = n % 10;\n\t    if( dig[cc] != a ) return false;\n\t    n -= a; n /= 10;\n\t}\n\treturn true;\n    }\n \n    int digitsCount( bigint n )\n    {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t    a = n % 10; dig[a]++;\n\t    cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n    }\n \n    int dig[10];\n};\n\nint main( int argc, char* argv[] )\n{\n    sdn s;\n    s. displayAll( 1000000000000 );\n    cout << endl << endl; system( \"pause\" );\n \n    bigint n;\n    while( true )\n    {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n    }\n \n    return 0;\n}\n"}
{"id": 58768, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <tuple>\n#include <vector>\n\nstd::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);\n\nstd::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (pos > minLen || seq[0] > n) return { minLen, 0 };\n    else if (seq[0] == n)           return { pos, 1 };\n    else if (pos < minLen)          return tryPerm(0, pos, seq, n, minLen);\n    else                            return { minLen, 0 };\n}\n\nstd::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {\n    if (i > pos) return { minLen, 0 };\n\n    std::vector<int> seq2{ seq[0] + seq[i] };\n    seq2.insert(seq2.end(), seq.cbegin(), seq.cend());\n    auto res1 = checkSeq(pos + 1, seq2, n, minLen);\n    auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);\n\n    if (res2.first < res1.first)       return res2;\n    else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };\n    else                               throw std::runtime_error(\"tryPerm exception\");\n}\n\nstd::pair<int, int> initTryPerm(int x) {\n    return tryPerm(0, 0, { 1 }, x, 12);\n}\n\nvoid findBrauer(int num) {\n    auto res = initTryPerm(num);\n    std::cout << '\\n';\n    std::cout << \"N = \" << num << '\\n';\n    std::cout << \"Minimum length of chains: L(n)= \" << res.first << '\\n';\n    std::cout << \"Number of minimum length Brauer chains: \" << res.second << '\\n';\n}\n\nint main() {\n    std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n    for (int i : nums) {\n        findBrauer(i);\n    }\n\n    return 0;\n}\n"}
{"id": 58769, "name": "Repeat", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n", "C++": "template <typename Function>\nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0<i; i--)\n  f();\n}\n"}
{"id": 58770, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n"}
{"id": 58771, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "C++": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <locale>\n\nclass Sparkline {\n    public:\n        Sparkline(std::wstring &cs) : charset( cs ){\n        }\n        virtual ~Sparkline(){\n        }\n\n        void print(std::string spark){\n            const char *delim = \", \";\n            std::vector<float> data;\n            \n            std::string::size_type last = spark.find_first_not_of(delim, 0);\n            \n            std::string::size_type pos = spark.find_first_of(delim, last);\n\n            while( pos != std::string::npos || last != std::string::npos ){\n                std::string tok = spark.substr(last, pos-last);\n                \n                std::stringstream ss(tok);\n                float entry;\n                ss >> entry;\n\n                data.push_back( entry );\n\n                last = spark.find_first_not_of(delim, pos);\n                pos = spark.find_first_of(delim, last);\n            }\n\n            \n            float min = *std::min_element( data.begin(), data.end() );\n            float max = *std::max_element( data.begin(), data.end() );\n\n            float skip = (charset.length()-1) / (max - min);\n\n            std::wcout<<L\"Min: \"<<min<<L\"; Max: \"<<max<<L\"; Range: \"<<(max-min)<<std::endl;\n            \n            std::vector<float>::const_iterator it;\n            for(it = data.begin(); it != data.end(); it++){\n                float v = ( (*it) - min ) * skip; \n                std::wcout<<charset[ (int)floor( v ) ];\n            }\n            std::wcout<<std::endl;\n            \n        }\n    private:\n        std::wstring &charset;\n};\n\nint main( int argc, char **argv ){\n    std::wstring charset = L\"\\u2581\\u2582\\u2583\\u2584\\u2585\\u2586\\u2587\\u2588\";\n\n    \n    std::locale::global(std::locale(\"en_US.utf8\"));\n\n    Sparkline sl(charset);\n\n    sl.print(\"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\");\n    sl.print(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\");\n\n    return 0;\n}\n"}
{"id": 58772, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "C++": "#include <iostream>\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 main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}\n"}
{"id": 58773, "name": "Chemical calculator", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nstd::map<std::string, double> atomicMass = {\n    {\"H\", 1.008},\n    {\"He\",    4.002602},\n    {\"Li\",    6.94},\n    {\"Be\",    9.0121831},\n    {\"B\",    10.81},\n    {\"C\",    12.011},\n    {\"N\",    14.007},\n    {\"O\",    15.999},\n    {\"F\",    18.998403163},\n    {\"Ne\",   20.1797},\n    {\"Na\",   22.98976928},\n    {\"Mg\",   24.305},\n    {\"Al\",   26.9815385},\n    {\"Si\",   28.085},\n    {\"P\",    30.973761998},\n    {\"S\",    32.06},\n    {\"Cl\",   35.45},\n    {\"Ar\",   39.948},\n    {\"K\",    39.0983},\n    {\"Ca\",   40.078},\n    {\"Sc\",   44.955908},\n    {\"Ti\",   47.867},\n    {\"V\",    50.9415},\n    {\"Cr\",   51.9961},\n    {\"Mn\",   54.938044},\n    {\"Fe\",   55.845},\n    {\"Co\",   58.933194},\n    {\"Ni\",   58.6934},\n    {\"Cu\",   63.546},\n    {\"Zn\",   65.38},\n    {\"Ga\",   69.723},\n    {\"Ge\",   72.630},\n    {\"As\",   74.921595},\n    {\"Se\",   78.971},\n    {\"Br\",   79.904},\n    {\"Kr\",   83.798},\n    {\"Rb\",   85.4678},\n    {\"Sr\",   87.62},\n    {\"Y\",    88.90584},\n    {\"Zr\",   91.224},\n    {\"Nb\",   92.90637},\n    {\"Mo\",   95.95},\n    {\"Ru\",  101.07},\n    {\"Rh\",  102.90550},\n    {\"Pd\",  106.42},\n    {\"Ag\",  107.8682},\n    {\"Cd\",  112.414},\n    {\"In\",  114.818},\n    {\"Sn\",  118.710},\n    {\"Sb\",  121.760},\n    {\"Te\",  127.60},\n    {\"I\",   126.90447},\n    {\"Xe\",  131.293},\n    {\"Cs\",  132.90545196},\n    {\"Ba\",  137.327},\n    {\"La\",  138.90547},\n    {\"Ce\",  140.116},\n    {\"Pr\",  140.90766},\n    {\"Nd\",  144.242},\n    {\"Pm\",  145},\n    {\"Sm\",  150.36},\n    {\"Eu\",  151.964},\n    {\"Gd\",  157.25},\n    {\"Tb\",  158.92535},\n    {\"Dy\",  162.500},\n    {\"Ho\",  164.93033},\n    {\"Er\",  167.259},\n    {\"Tm\",  168.93422},\n    {\"Yb\",  173.054},\n    {\"Lu\",  174.9668},\n    {\"Hf\",  178.49},\n    {\"Ta\",  180.94788},\n    {\"W\",   183.84},\n    {\"Re\",  186.207},\n    {\"Os\",  190.23},\n    {\"Ir\",  192.217},\n    {\"Pt\",  195.084},\n    {\"Au\",  196.966569},\n    {\"Hg\",  200.592},\n    {\"Tl\",  204.38},\n    {\"Pb\",  207.2},\n    {\"Bi\",  208.98040},\n    {\"Po\",  209},\n    {\"At\",  210},\n    {\"Rn\",  222},\n    {\"Fr\",  223},\n    {\"Ra\",  226},\n    {\"Ac\",  227},\n    {\"Th\",  232.0377},\n    {\"Pa\",  231.03588},\n    {\"U\",   238.02891},\n    {\"Np\",  237},\n    {\"Pu\",  244},\n    {\"Am\",  243},\n    {\"Cm\",  247},\n    {\"Bk\",  247},\n    {\"Cf\",  251},\n    {\"Es\",  252},\n    {\"Fm\",  257},\n    {\"Uue\", 315},\n    {\"Ubn\", 299},\n};\n\ndouble evaluate(std::string s) {\n    s += '[';\n\n    double sum = 0.0;\n    std::string symbol;\n    std::string number;\n\n    for (auto c : s) {\n        if ('@' <= c && c <= '[') {\n            \n            int n = 1;\n            if (number != \"\") {\n                n = stoi(number);\n            }\n            if (symbol != \"\") {\n                sum += atomicMass[symbol] * n;\n            }\n            if (c == '[') {\n                break;\n            }\n            symbol = c;\n            number = \"\";\n        } else if ('a' <= c && c <= 'z') {\n            symbol += c;\n        } else if ('0' <= c && c <= '9') {\n            number += c;\n        } else {\n            std::string msg = \"Unexpected symbol \";\n            msg += c;\n            msg += \" in molecule\";\n            throw std::runtime_error(msg);\n        }\n    }\n\n    return sum;\n}\n\nstd::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {\n    auto pos = text.find(search);\n    if (pos == std::string::npos) {\n        return text;\n    }\n\n    auto beg = text.substr(0, pos);\n    auto end = text.substr(pos + search.length());\n    return beg + replace + end;\n}\n\nstd::string replaceParens(std::string s) {\n    char letter = 'a';\n    while (true) {\n        auto start = s.find(\"(\");\n        if (start == std::string::npos) {\n            break;\n        }\n\n        for (size_t i = start + 1; i < s.length(); i++) {\n            if (s[i] == ')') {\n                auto expr = s.substr(start + 1, i - start - 1);\n                std::string symbol = \"@\";\n                symbol += letter;\n                auto search = s.substr(start, i + 1 - start);\n                s = replaceFirst(s, search, symbol);\n                atomicMass[symbol] = evaluate(expr);\n                letter++;\n                break;\n            }\n            if (s[i] == '(') {\n                start = i;\n                continue;\n            }\n        }\n    }\n    return s;\n}\n\nint main() {\n    std::vector<std::string> molecules = {\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n        \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n    };\n    for (auto molecule : molecules) {\n        auto mass = evaluate(replaceParens(molecule));\n        std::cout << std::setw(17) << molecule << \" -> \" << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 58774, "name": "Pythagorean quadruples", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n", "C++": "#include <iostream>\n#include <vector>\n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n    using namespace std;\n\n    vector<bool> found(N + 1);\n    vector<bool> aabb(N2 + 1);\n\n    int s = 3;\n\n    for (int a = 1; a < N; ++a) {\n        int aa = a * a;\n        for (int b = 1; b < N; ++b) {\n            aabb[aa + b * b] = true;\n        }\n    }\n\n    for (int c = 1; c <= N; ++c) {\n        int s1 = s;\n        s += 2;\n        int s2 = s;\n        for (int d = c + 1; d <= N; ++d) {\n            if (aabb[s1]) {\n                found[d] = true;\n            }\n            s1 += s2;\n            s2 += 2;\n        }\n    }\n\n    cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n    for (int d = 1; d <= N; ++d) {\n        if (!found[d]) {\n            cout << d << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}\n"}
{"id": 58775, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 58776, "name": "Pseudo-random numbers_Middle-square method", "VB": "Option Explicit\nDim seed As Long\nSub Main()\n    Dim i As Integer\n    seed = 675248\n    For i = 1 To 5\n        Debug.Print Rand\n    Next i\nEnd Sub\nFunction Rand() As Variant\n    Dim s As String\n    s = CStr(seed ^ 2)\n    Do While Len(s) <> 12\n        s = \"0\" + s\n    Loop\n    seed = Val(Mid(s, 4, 6))\n    Rand = seed\nEnd Function\n", "C++": "#include <exception>\n#include <iostream>\n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n    ulong state;\n    ulong div, mod;\npublic:\n    MiddleSquare() = delete;\n    MiddleSquare(ulong start, ulong length) {\n        if (length % 2) throw std::invalid_argument(\"length must be even\");\n        div = mod = 1;\n        for (ulong i=0; i<length/2; i++) div *= 10;\n        for (ulong i=0; i<length; i++) mod *= 10;\n        state = start % mod;\n    }\n    \n    ulong next() { \n        return state = state * state / div % mod;\n    }\n};\n\nint main() {\n    MiddleSquare msq(675248, 6);\n    for (int i=0; i<5; i++)\n        std::cout << msq.next() << std::endl;\n    return 0;\n}\n"}
{"id": 58777, "name": "Zebra puzzle", "VB": "Option Base 1\nPublic Enum attr\n    Colour = 1\n    Nationality\n    Beverage\n    Smoke\n    Pet\nEnd Enum\nPublic Enum Drinks_\n    Beer = 1\n    Coffee\n    Milk\n    Tea\n    Water\nEnd Enum\nPublic Enum nations\n    Danish = 1\n    English\n    German\n    Norwegian\n    Swedish\nEnd Enum\nPublic Enum colors\n    Blue = 1\n    Green\n    Red\n    White\n    Yellow\nEnd Enum\nPublic Enum tobaccos\n    Blend = 1\n    BlueMaster\n    Dunhill\n    PallMall\n    Prince\nEnd Enum\nPublic Enum animals\n    Bird = 1\n    Cat\n    Dog\n    Horse\n    Zebra\nEnd Enum\nPublic permutation As New Collection\nPublic perm(5) As Variant\nConst factorial5 = 120\nPublic Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant\n\nPrivate Sub generate(n As Integer, A As Variant)\n    If n = 1 Then\n        permutation.Add A\n    Else\n        For i = 1 To n\n            generate n - 1, A\n            If n Mod 2 = 0 Then\n                tmp = A(i)\n                A(i) = A(n)\n                A(n) = tmp\n            Else\n                tmp = A(1)\n                A(1) = A(n)\n                A(n) = tmp\n            End If\n        Next i\n    End If\nEnd Sub\n\nFunction house(i As Integer, name As Variant) As Integer\n    Dim x As Integer\n    For x = 1 To 5\n        If perm(i)(x) = name Then\n            house = x\n            Exit For\n        End If\n    Next x\nEnd Function\n \nFunction left_of(h1 As Integer, h2 As Integer) As Boolean\n    left_of = (h1 - h2) = -1\nEnd Function\n \nFunction next_to(h1 As Integer, h2 As Integer) As Boolean\n    next_to = Abs(h1 - h2) = 1\nEnd Function\n \nPrivate Sub print_house(i As Integer)\n    Debug.Print i & \": \"; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _\n        Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))\nEnd Sub\nPublic Sub Zebra_puzzle()\n    Colours = [{\"blue\",\"green\",\"red\",\"white\",\"yellow\"}]\n    Nationalities = [{\"Dane\",\"English\",\"German\",\"Norwegian\",\"Swede\"}]\n    Drinks = [{\"beer\",\"coffee\",\"milk\",\"tea\",\"water\"}]\n    Smokes = [{\"Blend\",\"Blue Master\",\"Dunhill\",\"Pall Mall\",\"Prince\"}]\n    Pets = [{\"birds\",\"cats\",\"dog\",\"horse\",\"zebra\"}]\n    Dim solperms As New Collection\n    Dim solutions As Integer\n    Dim b(5) As Integer, i As Integer\n    For i = 1 To 5: b(i) = i: Next i\n    \n    generate 5, b\n    For c = 1 To factorial5\n        perm(Colour) = permutation(c)\n        \n        If left_of(house(Colour, Green), house(Colour, White)) Then\n            For n = 1 To factorial5\n                perm(Nationality) = permutation(n)\n                \n                \n                \n                If house(Nationality, Norwegian) = 1 _\n                    And house(Nationality, English) = house(Colour, Red) _\n                    And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then\n                    For d = 1 To factorial5\n                        perm(Beverage) = permutation(d)\n                        \n                        \n                        \n                        If house(Nationality, Danish) = house(Beverage, Tea) _\n                            And house(Beverage, Coffee) = house(Colour, Green) _\n                            And house(Beverage, Milk) = 3 Then\n                            For s = 1 To factorial5\n                                perm(Smoke) = permutation(s)\n                                \n                                \n                                \n                                \n                                If house(Colour, Yellow) = house(Smoke, Dunhill) _\n                                    And house(Nationality, German) = house(Smoke, Prince) _\n                                    And house(Smoke, BlueMaster) = house(Beverage, Beer) _\n                                    And next_to(house(Beverage, Water), house(Smoke, Blend)) Then\n                                    For p = 1 To factorial5\n                                        perm(Pet) = permutation(p)\n                                        \n                                        \n                                        \n                                        \n                                        If house(Nationality, Swedish) = house(Pet, Dog) _\n                                            And house(Smoke, PallMall) = house(Pet, Bird) _\n                                            And next_to(house(Smoke, Blend), house(Pet, Cat)) _\n                                            And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then\n                                            For i = 1 To 5\n                                                print_house i\n                                            Next i\n                                            Debug.Print\n                                            solutions = solutions + 1\n                                            solperms.Add perm\n                                        End If\n                                    Next p\n                                End If\n                            Next s\n                        End If\n                    Next d\n                End If\n            Next n\n        End If\n    Next c\n    Debug.Print Format(solutions, \"@\"); \" solution\" & IIf(solutions > 1, \"s\", \"\") & \" found\"\n    For i = 1 To solperms.Count\n        For j = 1 To 5\n            perm(j) = solperms(i)(j)\n        Next j\n        Debug.Print \"The \" & Nationalities(perm(Nationality)(house(Pet, Zebra))) & \" owns the Zebra\"\n    Next i\nEnd Sub\n", "C++": "#include <stdio.h>\n#include <string.h>\n\n#define defenum(name, val0, val1, val2, val3, val4) \\\n    enum name { val0, val1, val2, val3, val4 }; \\\n    const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }\n\ndefenum( Attrib,    Color, Man, Drink, Animal, Smoke );\ndefenum( Colors,    Red, Green, White, Yellow, Blue );\ndefenum( Mans,      English, Swede, Dane, German, Norwegian );\ndefenum( Drinks,    Tea, Coffee, Milk, Beer, Water );\ndefenum( Animals,   Dog, Birds, Cats, Horse, Zebra );\ndefenum( Smokes,    PallMall, Dunhill, Blend, BlueMaster, Prince );\n\nvoid printHouses(int ha[5][5]) {\n    const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};\n\n    printf(\"%-10s\", \"House\");\n    for (const char *name : Attrib_str) printf(\"%-10s\", name);\n    printf(\"\\n\");\n\n    for (int i = 0; i < 5; i++) {\n        printf(\"%-10d\", i);\n        for (int j = 0; j < 5; j++) printf(\"%-10s\", attr_names[j][ha[i][j]]);\n        printf(\"\\n\");\n    }\n}\n\nstruct HouseNoRule {\n    int houseno;\n    Attrib a; int v;\n} housenos[] = {\n    {2, Drink, Milk},     \n    {0, Man, Norwegian}   \n};\n\nstruct AttrPairRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&\n               ((ha[i][a1] == v1 && ha[i][a2] != v2) ||\n                (ha[i][a1] != v1 && ha[i][a2] == v2));\n    }\n} pairs[] = {\n    {Man, English,      Color, Red},     \n    {Man, Swede,        Animal, Dog},    \n    {Man, Dane,         Drink, Tea},     \n    {Color, Green,      Drink, Coffee},  \n    {Smoke, PallMall,   Animal, Birds},  \n    {Smoke, Dunhill,    Color, Yellow},  \n    {Smoke, BlueMaster, Drink, Beer},    \n    {Man, German,       Smoke, Prince}    \n};\n\nstruct NextToRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5], int i) {\n        return (ha[i][a1] == v1) &&\n               ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||\n                (i == 4 && ha[i - 1][a2] != v2) ||\n                (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));\n    }\n} nexttos[] = {\n    {Smoke, Blend,      Animal, Cats},    \n    {Smoke, Dunhill,    Animal, Horse},   \n    {Man, Norwegian,    Color, Blue},     \n    {Smoke, Blend,      Drink, Water}     \n};\n\nstruct LeftOfRule {\n    Attrib a1; int v1;\n    Attrib a2; int v2;\n\n    bool invalid(int ha[5][5]) {\n        return (ha[0][a2] == v2) || (ha[4][a1] == v1);\n    }\n\n    bool invalid(int ha[5][5], int i) {\n        return ((i > 0 && ha[i][a1] >= 0) &&\n                ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||\n                 (ha[i - 1][a1] != v1 && ha[i][a2] == v2)));\n    }\n} leftofs[] = {\n    {Color, Green,  Color, White}     \n};\n\nbool invalid(int ha[5][5]) {\n    for (auto &rule : leftofs) if (rule.invalid(ha)) return true;\n\n    for (int i = 0; i < 5; i++) {\n#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;\n        eval_rules(pairs);\n        eval_rules(nexttos);\n        eval_rules(leftofs);\n    }\n    return false;\n}\n\nvoid search(bool used[5][5], int ha[5][5], const int hno, const int attr) {\n    int nexthno, nextattr;\n    if (attr < 4) {\n        nextattr = attr + 1;\n        nexthno = hno;\n    } else {\n        nextattr = 0;\n        nexthno = hno + 1;\n    }\n\n    if (ha[hno][attr] != -1) {\n        search(used, ha, nexthno, nextattr);\n    } else {\n        for (int i = 0; i < 5; i++) {\n            if (used[attr][i]) continue;\n            used[attr][i] = true;\n            ha[hno][attr] = i;\n\n            if (!invalid(ha)) {\n                if ((hno == 4) && (attr == 4)) {\n                    printHouses(ha);\n                } else {\n                    search(used, ha, nexthno, nextattr);\n                }\n            }\n\n            used[attr][i] = false;\n        }\n        ha[hno][attr] = -1;\n    }\n}\n\nint main() {\n    bool used[5][5] = {};\n    int ha[5][5]; memset(ha, -1, sizeof(ha));\n\n    for (auto &rule : housenos) {\n        ha[rule.houseno][rule.a] = rule.v;\n        used[rule.a][rule.v] = true;\n    }\n\n    search(used, ha, 0, 0);\n\n    return 0;\n}\n"}
{"id": 58778, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 58779, "name": "Almkvist-Giullera formula for pi", "VB": "Imports System, BI = System.Numerics.BigInteger, System.Console\n\nModule Module1\n\n    Function isqrt(ByVal x As BI) As BI\n        Dim t As BI, q As BI = 1, r As BI = 0\n        While q <= x : q <<= 2 : End While\n        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1\n            If t >= 0 Then x = t : r += q\n        End While : Return r\n    End Function\n\n    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String\n        digs += 1\n        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb\n        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1\n        For n As BI = 0 To dg - 1\n            If n > 0 Then t3 = t3 * BI.Pow(n, 6)\n            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6\n            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)\n            If show AndAlso n < 10 Then WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t)\n            su += te : If te < 10 Then\n                digs -= 1\n                If show Then WriteLine(vbLf & \"{0} iterations required for {1} digits \" & _\n                    \"after the decimal point.\" & vbLf, n, digs)\n                Exit For\n            End If\n            For j As BI = n * 6 + 1 To n * 6 + 6\n                t1 = t1 * j : Next\n            d += 2 : t2 += 126 + 532 * d\n        Next\n        Dim s As String = String.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) _\n            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))\n        Return s(0) & \".\" & s.Substring(1, digs)\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(dump(70, true))\n    End Sub\n\nEnd Module\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace mp = boost::multiprecision;\nusing big_int = mp::mpz_int;\nusing big_float = mp::cpp_dec_float_100;\nusing rational = mp::mpq_rational;\n\nbig_int factorial(int n) {\n    big_int result = 1;\n    for (int i = 2; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nbig_int almkvist_giullera(int n) {\n    return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /\n           (pow(factorial(n), 6) * 3);\n}\n\nint main() {\n    std::cout << \"n |                  Integer portion of nth term\\n\"\n              << \"------------------------------------------------\\n\";\n    for (int n = 0; n < 10; ++n)\n        std::cout << n << \" | \" << std::setw(44) << almkvist_giullera(n)\n                  << '\\n';\n\n    big_float epsilon(pow(big_float(10), -70));\n    big_float prev = 0, pi = 0;\n    rational sum = 0;\n    for (int n = 0;; ++n) {\n        rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));\n        sum += term;\n        pi = sqrt(big_float(1 / sum));\n        if (abs(pi - prev) < epsilon)\n            break;\n        prev = pi;\n    }\n    std::cout << \"\\nPi to 70 decimal places is:\\n\"\n              << std::fixed << std::setprecision(70) << pi << '\\n';\n}\n"}
{"id": 58780, "name": "Practical numbers", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n\n\ntemplate <typename iterator>\nbool sum_of_any_subset(int n, iterator begin, iterator end) {\n    if (begin == end)\n        return false;\n    if (std::find(begin, end, n) != end)\n        return true;\n    int total = std::accumulate(begin, end, 0);\n    if (n == total)\n        return true;\n    if (n > total)\n        return false;\n    --end;\n    int d = n - *end;\n    return (d > 0 && sum_of_any_subset(d, begin, end)) ||\n           sum_of_any_subset(n, begin, end);\n}\n\n\nstd::vector<int> factors(int n) {\n    std::vector<int> f{1};\n    for (int i = 2; i * i <= n; ++i) {\n        if (n % i == 0) {\n            f.push_back(i);\n            if (i * i != n)\n                f.push_back(n / i);\n        }\n    }\n    std::sort(f.begin(), f.end());\n    return f;\n}\n\nbool is_practical(int n) {\n    std::vector<int> f = factors(n);\n    for (int i = 1; i < n; ++i) {\n        if (!sum_of_any_subset(i, f.begin(), f.end()))\n            return false;\n    }\n    return true;\n}\n\nstd::string shorten(const std::vector<int>& v, size_t n) {\n    std::ostringstream out;\n    size_t size = v.size(), i = 0;\n    if (n > 0 && size > 0)\n        out << v[i++];\n    for (; i < n && i < size; ++i)\n        out << \", \" << v[i];\n    if (size > i + n) {\n        out << \", ...\";\n        i = size - n;\n    }\n    for (; i < size; ++i)\n        out << \", \" << v[i];\n    return out.str();\n}\n\nint main() {\n    std::vector<int> practical;\n    for (int n = 1; n <= 333; ++n) {\n        if (is_practical(n))\n            practical.push_back(n);\n    }\n    std::cout << \"Found \" << practical.size() << \" practical numbers:\\n\"\n              << shorten(practical, 10) << '\\n';\n    for (int n : {666, 6666, 66666, 672, 720, 222222})\n        std::cout << n << \" is \" << (is_practical(n) ? \"\" : \"not \")\n                  << \"a practical number.\\n\";\n    return 0;\n}\n"}
{"id": 58781, "name": "Literals_Floating point", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n", "C++": "#include <iostream>\n\nint main()\n{\n  \n  auto double1 = 2.5;\n\n  \n  auto float1 = 2.5f;\n\n  \n  auto longdouble1 = 2.5l;\n\n  \n  auto double2 = 2.5e-3;\n  auto float2 = 2.5e3f;\n\n  \n  auto double3 = 0x1p4;\n  auto float3 = 0xbeefp-8f;\n\n  std::cout << \"\\ndouble1: \" << double1;\n  std::cout << \"\\nfloat1: \" << float1;\n  std::cout << \"\\nlongdouble1: \" << longdouble1;\n  std::cout << \"\\ndouble2: \" << double2;\n  std::cout << \"\\nfloat2: \" << float2;\n  std::cout << \"\\ndouble3: \" << double3;\n  std::cout << \"\\nfloat3: \" << float3;\n  std::cout << \"\\n\";\n}\n"}
{"id": 58782, "name": "Word search", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n    Cell() : val( 0 ), cntOverlap( 0 ) {}\n    char val; int cntOverlap;\n};\nclass Word {\npublic:\n    Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n      word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n    bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n    std::string word;\n    int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n    void create( std::string& file ) {\n        std::ifstream f( file.c_str(), std::ios_base::in );\n        std::string word;\n        while( f >> word ) {\n            if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n            if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n            dictionary.push_back( word );\n        }\n        f.close();\n        std::random_shuffle( dictionary.begin(), dictionary.end() );\n        buildPuzzle();\n    }\n\n    void printOut() {\n        std::cout << \"\\t\";\n        for( int x = 0; x < WID; x++ ) std::cout << x << \"  \";\n        std::cout << \"\\n\\n\";\n        for( int y = 0; y < HEI; y++ ) {\n            std::cout << y << \"\\t\";\n            for( int x = 0; x < WID; x++ )\n                std::cout << puzzle[x][y].val << \"  \";\n            std::cout << \"\\n\";\n        }\n        size_t wid1 = 0, wid2 = 0;\n        for( size_t x = 0; x < used.size(); x++ ) {\n            if( x & 1 ) {\n                if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n            } else {\n                if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n            }\n        }\n        std::cout << \"\\n\";\n        std::vector<Word>::iterator w = used.begin();\n        while( w != used.end() ) {\n            std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n            w++;\n            if( w == used.end() ) break;\n            std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n                      << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n            w++;\n        }\n        std::cout << \"\\n\\n\";\n    }\nprivate:\n    void addMsg() {\n        std::string msg = \"ROSETTACODE\";\n        int stp = 9, p = rand() % stp;\n        for( size_t x = 0; x < msg.length(); x++ ) {\n            puzzle[p % WID][p / HEI].val = msg.at( x );\n            p += rand() % stp + 4;\n        }\n    }\n    int getEmptySpaces() {\n        int es = 0;\n        for( int y = 0; y < HEI; y++ ) {\n            for( int x = 0; x < WID; x++ ) {\n                if( !puzzle[x][y].val ) es++;\n            }\n        }\n        return es;\n    }\n    bool check( std::string word, int c, int r, int dc, int dr ) {\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n            if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n            c += dc; r += dr;\n        }\n        return true;\n    }\n    bool setWord( std::string word, int c, int r, int dc, int dr ) {\n        if( !check( word, c, r, dc, dr ) ) return false;\n        int sx = c, sy = r;\n        for( size_t a = 0; a < word.length(); a++ ) {\n            if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n            else puzzle[c][r].cntOverlap++;\n            c += dc; r += dr;\n        }\n        used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n        return true;\n    }\n    bool add2Puzzle( std::string word ) {\n        int x = rand() % WID, y = rand() % HEI,\n            z = rand() % 8;\n        for( int d = z; d < z + 8; d++ ) {\n            switch( d % 8 ) {\n                case 0: if( setWord( word, x, y,  1,  0 ) ) return true; break;\n                case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n                case 2: if( setWord( word, x, y,  0,  1 ) ) return true; break;\n                case 3: if( setWord( word, x, y,  1, -1 ) ) return true; break;\n                case 4: if( setWord( word, x, y, -1,  0 ) ) return true; break;\n                case 5: if( setWord( word, x, y, -1,  1 ) ) return true; break;\n                case 6: if( setWord( word, x, y,  0, -1 ) ) return true; break;\n                case 7: if( setWord( word, x, y,  1,  1 ) ) return true; break;\n            }\n        }\n        return false;\n    }\n    void clearWord() {\n        if( used.size() ) {\n            Word lastW = used.back();\n            used.pop_back();\n\n            for( size_t a = 0; a < lastW.word.length(); a++ ) {\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n                    puzzle[lastW.cols][lastW.rows].val = 0;\n                }\n                if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n                    puzzle[lastW.cols][lastW.rows].cntOverlap--;\n                }\n                lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n            }\n        }\n    }\n    void buildPuzzle() {\n        addMsg();\n        int es = 0, cnt = 0;\n        size_t idx = 0;\n        do {\n            for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n                if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n            \n                if( add2Puzzle( *w ) ) {\n                    es = getEmptySpaces();\n                    if( !es && used.size() >= MIN_WORD_CNT ) \n                        return;\n                }\n            }\n            clearWord();\n            std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n        } while( ++cnt < 100 );\n    }\n    std::vector<Word> used;\n    std::vector<std::string> dictionary;\n    Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n    unsigned s = unsigned( time( 0 ) );\n    srand( s );\n    words w; w.create( std::string( \"unixdict.txt\" ) );\n    w.printOut();\n    return 0;\n}\n"}
{"id": 58783, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 58784, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 58785, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "C++": "#include <iostream>\n\nclass CWidget; \n\nclass CFactory\n{\n  friend class CWidget;\nprivate:\n  unsigned int m_uiCount;\npublic:\n  CFactory();\n  ~CFactory();\n  CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n  CFactory& m_parent;\n\nprivate:\n  CWidget(); \n  CWidget(const CWidget&); \n  CWidget& operator=(const CWidget&); \npublic:\n  CWidget(CFactory& parent);\n  ~CWidget();\n};\n\n\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n\nCWidget* CFactory::GetWidget()\n{\n  \n  return new CWidget(*this);\n}\n\n\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n  ++m_parent.m_uiCount;\n\n  std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n  --m_parent.m_uiCount;\n\n  std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n  CFactory factory;\n\n  CWidget* pWidget1 = factory.GetWidget();\n  CWidget* pWidget2 = factory.GetWidget();\n  delete pWidget1;\n\n  CWidget* pWidget3 = factory.GetWidget();\n  delete pWidget3;\n  delete pWidget2;\n}\n"}
{"id": 58786, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 58787, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <functional>\n#include <map>\n#include <vector>\n\nstruct Node {\n    int length;\n    std::map<char, int> edges;\n    int suffix;\n\n    Node(int l) : length(l), suffix(0) {\n        \n    }\n\n    Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {\n        \n    }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector<Node> eertree(const std::string& s) {\n    std::vector<Node> tree = {\n        Node(0, {}, oddRoot),\n        Node(-1, {}, oddRoot)\n    };\n    int suffix = oddRoot;\n    int n, k;\n\n    for (size_t i = 0; i < s.length(); ++i) {\n        char c = s[i];\n        for (n = suffix; ; n = tree[n].suffix) {\n            k = tree[n].length;\n            int b = i - k - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n\n        auto it = tree[n].edges.find(c);\n        auto end = tree[n].edges.end();\n        if (it != end) {\n            suffix = it->second;\n            continue;\n        }\n        suffix = tree.size();\n        tree.push_back(Node(k + 2));\n        tree[n].edges[c] = suffix;\n        if (tree[suffix].length == 1) {\n            tree[suffix].suffix = 0;\n            continue;\n        }\n        while (true) {\n            n = tree[n].suffix;\n            int b = i - tree[n].length - 1;\n            if (b >= 0 && s[b] == c) {\n                break;\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c];\n    }\n\n    return tree;\n}\n\nstd::vector<std::string> subPalindromes(const std::vector<Node>& tree) {\n    std::vector<std::string> s;\n\n    std::function<void(int, std::string)> children;\n    children = [&children, &tree, &s](int n, std::string p) {\n        auto it = tree[n].edges.cbegin();\n        auto end = tree[n].edges.cend();\n        for (; it != end; it = std::next(it)) {\n            auto c = it->first;\n            auto m = it->second;\n\n            std::string pl = c + p + c;\n            s.push_back(pl);\n            children(m, pl);\n        }\n    };\n    children(0, \"\");\n\n    auto it = tree[1].edges.cbegin();\n    auto end = tree[1].edges.cend();\n    for (; it != end; it = std::next(it)) {\n        auto c = it->first;\n        auto n = it->second;\n\n        std::string ct(1, c);\n        s.push_back(ct);\n\n        children(n, ct);\n    }\n\n    return s;\n}\n\nint main() {\n    using namespace std;\n\n    auto tree = eertree(\"eertree\");\n    auto pal = subPalindromes(tree);\n\n    auto it = pal.cbegin();\n    auto end = pal.cend();\n\n    cout << \"[\";\n    if (it != end) {\n        cout << it->c_str();\n        it++;\n    }\n    while (it != end) {\n        cout << \", \" << it->c_str();\n        it++;\n    }\n    cout << \"]\" << endl;\n\n    return 0;\n}\n"}
{"id": 58788, "name": "Long year", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n", "C++": "#include <stdio.h>\n#include <math.h>\n\n\n\nint p(int year) {\n\treturn (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;\n}\n\nint is_long_year(int year) {\n\treturn p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n\tfor (int year = from; year <= to; ++year) {\n\t\tif (is_long_year(year)) {\n\t\t\tprintf(\"%d \", year);\n\t\t}\n\t}\n}\n\nint main() {\n\n\tprintf(\"Long (53 week) years between 1800 and 2100\\n\\n\");\n\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n"}
{"id": 58789, "name": "Zumkeller numbers", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n", "C++": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n\nconst uint* binary(uint n, uint length);\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n    for (uint i = 0; i < zumz.size(); i++) {\n        if (i % 10 == 0)\n            os << endl;\n        os << setw(10) << zumz[i] << ' ';\n    }\n    return os;\n}\n\nint main() {\n    cout << \"First 220 Zumkeller numbers:\" << endl;\n    vector<uint> zumz;\n    for (uint n = 2; zumz.size() < 220; n++)\n        if (isZum(n))\n            zumz.push_back(n);\n    cout << zumz << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers:\" << endl;\n    vector<uint> zumz2;\n    for (uint n = 2; zumz2.size() < 40; n++)\n        if (n % 2 && isZum(n))\n            zumz2.push_back(n);\n    cout << zumz2 << endl << endl;\n\n    cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n    vector<uint> zumz3;\n    for (uint n = 2; zumz3.size() < 40; n++)\n        if (n % 2 && (n % 10) !=  5 && isZum(n))\n            zumz3.push_back(n);\n    cout << zumz3 << endl << endl;\n\n    return 0;\n}\n\n\nconst uint* binary(uint n, uint length) {\n    uint* bin = new uint[length];\t    \n    fill(bin, bin + length, 0);         \n    \n    for (uint i = 0; n > 0; i++) {\n        uint rem = n % 2;\n        n /= 2;\n        if (rem)\n            bin[length - 1 - i] = 1;\n    }\n\n    return bin;\n}\n\n\n\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n    vector<uint> subset;\n    \n    const uint* bits = binary(r, d.size() - 1);\n\n    \n    for (uint i = 0; i < d.size() - 1; i++)\n        if (bits[i])\n            subset.push_back(d[i]);\n\n    delete[] bits;\n\n    return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n    vector<uint> result;\n    \n    for (uint i = 1; i * i <= x; i++) {\n        \n        if (x % i == 0) {\n            result.push_back(i);\n\n            if (x / i != i)\n                result.push_back(x / i);\n        }\n    }\n\n    \n    sort(result.begin(), result.end());\n    return result;\n}\n\nbool isPrime(uint number) {\n    if (number < 2) return false;\n    if (number == 2) return true;\n    if (number % 2 == 0) return false;\n    for (uint i = 3; i * i <= number; i += 2)\n        if (number % i == 0) return false;\n\n    return true;\n}\n\nbool isZum(uint n) {\n    \n    if (isPrime(n))\n        return false;\n\n    \n    const auto d = factors(n);\n    uint s = accumulate(d.begin(), d.end(), 0u);\n\n    \n    if (s % 2 || s < 2 * n)\n        return false;\n\n    \n    \n    \n    if (n % 2 || d.size() >= 24)\n        return true;\n\n    if (!(s % 2) && d[d.size() - 1] <= s / 2)\n        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) \n            if (sum_subset_unrank_bin(d, x) == s / 2)\n                return true; \n\n    \n    return false;\n}\n"}
{"id": 58790, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 58791, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n#include <map>\n\ntemplate<typename map_type>\nmap_type merge(const map_type& original, const map_type& update) {\n    map_type result(update);\n    result.insert(original.begin(), original.end());\n    return result;\n}\n\nint main() {\n    typedef std::map<std::string, std::string> map;\n    map original{\n        {\"name\", \"Rocket Skates\"},\n        {\"price\", \"12.75\"},\n        {\"color\", \"yellow\"}\n    };\n    map update{\n        {\"price\", \"15.25\"},\n        {\"color\", \"red\"},\n        {\"year\", \"1974\"}\n    };\n    map merged(merge(original, update));\n    for (auto&& i : merged)\n        std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n    return 0;\n}\n"}
{"id": 58792, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 58793, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 58794, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "C++": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n\nconst char* names[] = { \"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\" };\n\ntemplate<const uint N>\nvoid lucas(ulong b) {\n    std::cout << \"Lucas sequence for \" << names[b] << \" ratio, where b = \" << b << \":\\nFirst \" << N << \" elements: \";\n    auto x0 = 1L, x1 = 1L;\n    std::cout << x0 << \", \" << x1;\n    for (auto i = 1u; i <= N - 1 - 1; i++) {\n        auto x2 = b * x1 + x0;\n        std::cout << \", \" << x2;\n        x0 = x1;\n        x1 = x2;\n    }\n    std::cout << std::endl;\n}\n\ntemplate<const ushort P>\nvoid metallic(ulong b) {\n    using namespace boost::multiprecision;\n    using bfloat = number<cpp_dec_float<P+1>>;\n    bfloat x0(1), x1(1);\n    auto prev = bfloat(1).str(P+1);\n    for (auto i = 0u;;) {\n        i++;\n        bfloat x2(b * x1 + x0);\n        auto thiz = bfloat(x2 / x1).str(P+1);\n        if (prev == thiz) {\n            std::cout << \"Value after \" << i << \" iteration\" << (i == 1 ? \": \" : \"s: \") << thiz << std::endl << std::endl;\n            break;\n        }\n        prev = thiz;\n        x0 = x1;\n        x1 = x2;\n    }\n}\n\nint main() {\n    for (auto b = 0L; b < 10L; b++) {\n        lucas<15>(b);\n        metallic<32>(b);\n    }\n    std::cout << \"Golden ratio, where b = 1:\" << std::endl;\n    metallic<256>(1);\n\n    return 0;\n}\n"}
{"id": 58795, "name": "Dijkstra's algorithm", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n", "C++": "#include <iostream>\n#include <vector>\n#include <string>\n#include <list>\n\n#include <limits> \n\n#include <set>\n#include <utility> \n#include <algorithm>\n#include <iterator>\n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits<double>::infinity();\n\nstruct neighbor {\n    vertex_t target;\n    weight_t weight;\n    neighbor(vertex_t arg_target, weight_t arg_weight)\n        : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector<std::vector<neighbor> > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n                          const adjacency_list_t &adjacency_list,\n                          std::vector<weight_t> &min_distance,\n                          std::vector<vertex_t> &previous)\n{\n    int n = adjacency_list.size();\n    min_distance.clear();\n    min_distance.resize(n, max_weight);\n    min_distance[source] = 0;\n    previous.clear();\n    previous.resize(n, -1);\n    std::set<std::pair<weight_t, vertex_t> > vertex_queue;\n    vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n    while (!vertex_queue.empty()) \n    {\n        weight_t dist = vertex_queue.begin()->first;\n        vertex_t u = vertex_queue.begin()->second;\n        vertex_queue.erase(vertex_queue.begin());\n\n        \n\tconst std::vector<neighbor> &neighbors = adjacency_list[u];\n        for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();\n             neighbor_iter != neighbors.end();\n             neighbor_iter++)\n        {\n            vertex_t v = neighbor_iter->target;\n            weight_t weight = neighbor_iter->weight;\n            weight_t distance_through_u = dist + weight;\n\t    if (distance_through_u < min_distance[v]) {\n\t        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t        min_distance[v] = distance_through_u;\n\t        previous[v] = u;\n\t        vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t    }\n\n        }\n    }\n}\n\n\nstd::list<vertex_t> DijkstraGetShortestPathTo(\n    vertex_t vertex, const std::vector<vertex_t> &previous)\n{\n    std::list<vertex_t> path;\n    for ( ; vertex != -1; vertex = previous[vertex])\n        path.push_front(vertex);\n    return path;\n}\n\n\nint main()\n{\n    \n    adjacency_list_t adjacency_list(6);\n    \n    adjacency_list[0].push_back(neighbor(1, 7));\n    adjacency_list[0].push_back(neighbor(2, 9));\n    adjacency_list[0].push_back(neighbor(5, 14));\n    \n    adjacency_list[1].push_back(neighbor(0, 7));\n    adjacency_list[1].push_back(neighbor(2, 10));\n    adjacency_list[1].push_back(neighbor(3, 15));\n    \n    adjacency_list[2].push_back(neighbor(0, 9));\n    adjacency_list[2].push_back(neighbor(1, 10));\n    adjacency_list[2].push_back(neighbor(3, 11));\n    adjacency_list[2].push_back(neighbor(5, 2));\n    \n    adjacency_list[3].push_back(neighbor(1, 15));\n    adjacency_list[3].push_back(neighbor(2, 11));\n    adjacency_list[3].push_back(neighbor(4, 6));\n    \n    adjacency_list[4].push_back(neighbor(3, 6));\n    adjacency_list[4].push_back(neighbor(5, 9));\n    \n    adjacency_list[5].push_back(neighbor(0, 14));\n    adjacency_list[5].push_back(neighbor(2, 2));\n    adjacency_list[5].push_back(neighbor(4, 9));\n\n    std::vector<weight_t> min_distance;\n    std::vector<vertex_t> previous;\n    DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n    std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n    std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);\n    std::cout << \"Path : \";\n    std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, \" \"));\n    std::cout << std::endl;\n\n    return 0;\n}\n"}
{"id": 58796, "name": "Geometric algebra", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\ndouble uniform01() {\n    static std::default_random_engine generator;\n    static std::uniform_real_distribution<double> distribution(0.0, 1.0);\n    return distribution(generator);\n}\n\nint bitCount(int i) {\n    i -= ((i >> 1) & 0x55555555);\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n    i = (i + (i >> 4)) & 0x0F0F0F0F;\n    i += (i >> 8);\n    i += (i >> 16);\n    return i & 0x0000003F;\n}\n\ndouble reorderingSign(int i, int j) {\n    int k = i >> 1;\n    int sum = 0;\n    while (k != 0) {\n        sum += bitCount(k & j);\n        k = k >> 1;\n    }\n    return ((sum & 1) == 0) ? 1.0 : -1.0;\n}\n\nstruct MyVector {\npublic:\n    MyVector(const std::vector<double> &da) : dims(da) {\n        \n    }\n\n    double &operator[](size_t i) {\n        return dims[i];\n    }\n\n    const double &operator[](size_t i) const {\n        return dims[i];\n    }\n\n    MyVector operator+(const MyVector &rhs) const {\n        std::vector<double> temp(dims);\n        for (size_t i = 0; i < rhs.dims.size(); ++i) {\n            temp[i] += rhs[i];\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(const MyVector &rhs) const {\n        std::vector<double> temp(dims.size(), 0.0);\n        for (size_t i = 0; i < dims.size(); i++) {\n            if (dims[i] != 0.0) {\n                for (size_t j = 0; j < dims.size(); j++) {\n                    if (rhs[j] != 0.0) {\n                        auto s = reorderingSign(i, j) * dims[i] * rhs[j];\n                        auto k = i ^ j;\n                        temp[k] += s;\n                    }\n                }\n            }\n        }\n        return MyVector(temp);\n    }\n\n    MyVector operator*(double scale) const {\n        std::vector<double> temp(dims);\n        std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });\n        return MyVector(temp);\n    }\n\n    MyVector operator-() const {\n        return *this * -1.0;\n    }\n\n    MyVector dot(const MyVector &rhs) const {\n        return (*this * rhs + rhs * *this) * 0.5;\n    }\n\n    friend std::ostream &operator<<(std::ostream &, const MyVector &);\n\nprivate:\n    std::vector<double> dims;\n};\n\nstd::ostream &operator<<(std::ostream &os, const MyVector &v) {\n    auto it = v.dims.cbegin();\n    auto end = v.dims.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\nMyVector e(int n) {\n    if (n > 4) {\n        throw new std::runtime_error(\"n must be less than 5\");\n    }\n\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    result[1 << n] = 1.0;\n    return result;\n}\n\nMyVector randomVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 5; i++) {\n        result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);\n    }\n    return result;\n}\n\nMyVector randomMultiVector() {\n    auto result = MyVector(std::vector<double>(32, 0.0));\n    for (int i = 0; i < 32; i++) {\n        result[i] = uniform01();\n    }\n    return result;\n}\n\nint main() {\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i < j) {\n                if (e(i).dot(e(j))[0] != 0.0) {\n                    std::cout << \"Unexpected non-null scalar product.\";\n                    return 1;\n                } else if (i == j) {\n                    if (e(i).dot(e(j))[0] == 0.0) {\n                        std::cout << \"Unexpected null scalar product.\";\n                    }\n                }\n            }\n        }\n    }\n\n    auto a = randomMultiVector();\n    auto b = randomMultiVector();\n    auto c = randomMultiVector();\n    auto x = randomVector();\n\n    \n    std::cout << ((a * b) * c) << '\\n';\n    std::cout << (a * (b * c)) << \"\\n\\n\";\n\n    \n    std::cout << (a * (b + c)) << '\\n';\n    std::cout << (a * b + a * c) << \"\\n\\n\";\n\n    \n    std::cout << ((a + b) * c) << '\\n';\n    std::cout << (a * c + b * c) << \"\\n\\n\";\n\n    \n    std::cout << (x * x) << '\\n';\n\n    return 0;\n}\n"}
{"id": 58797, "name": "Associative array_Iteration", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n", "C++": "#include <iostream>\n#include <map>\n#include <string>\n\nint main() {\n  std::map<std::string, int> dict {\n    {\"One\", 1},\n    {\"Two\", 2},\n    {\"Three\", 7}\n  };\n\n  dict[\"Three\"] = 3;\n\n  std::cout << \"One: \" << dict[\"One\"] << std::endl;\n  std::cout << \"Key/Value pairs: \" << std::endl;\n  for(auto& kv: dict) {\n    std::cout << \"  \" << kv.first << \": \" << kv.second << std::endl;\n  }\n\n  return 0;\n}\n"}
{"id": 58798, "name": "Define a primitive data type", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n", "C++": "#include <stdexcept>\n\nclass tiny_int\n{\npublic:\n  tiny_int(int i):\n    value(i)\n  {\n    if (value < 1)\n      throw std::out_of_range(\"tiny_int: value smaller than 1\");\n    if (value > 10)\n      throw std::out_of_range(\"tiny_int: value larger than 10\");\n  }\n  operator int() const\n  {\n    return value;\n  }\n  tiny_int& operator+=(int i)\n  {\n    \n    \n    *this = value + i;\n    return *this;\n  }\n  tiny_int& operator-=(int i)\n  {\n    *this = value - i;\n    return *this;\n  }\n  tiny_int& operator*=(int i)\n  {\n    *this = value * i;\n    return *this;\n  }\n  tiny_int& operator/=(int i)\n  {\n    *this = value / i;\n    return *this;\n  }\n  tiny_int& operator<<=(int i)\n  {\n    *this = value << i;\n    return *this;\n  }\n  tiny_int& operator>>=(int i)\n  {\n    *this = value >> i;\n    return *this;\n  }\n  tiny_int& operator&=(int i)\n  {\n    *this = value & i;\n    return *this;\n  }\n  tiny_int& operator|=(int i)\n  {\n    *this = value | i;\n    return *this;\n  }\nprivate:\n  unsigned char value; \n};\n"}
{"id": 58799, "name": "Hash join", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing tab_t = std::vector<std::vector<std::string>>;\ntab_t tab1 {\n\n  {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n\n  {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n  for(size_t i = 0; i < t.size(); ++i) {\n    o << i << \":\";\n    for(const auto& e : t[i]) \n      o << '\\t' << e;\n    o << std::endl;\n  }\n  return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n  std::unordered_multimap<std::string, size_t> hashmap;\n  \n  for(size_t i = 0; i < a.size(); ++i) {\n    hashmap.insert(std::make_pair(a[i][columna], i));\n  }\n  \n  tab_t result;\n  for(size_t i = 0; i < b.size(); ++i) {\n    auto range = hashmap.equal_range(b[i][columnb]);\n    for(auto it = range.first; it != range.second; ++it) {\n      tab_t::value_type row;\n      row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n      row.insert(row.end() , b[i].begin()          , b[i].end());\n      result.push_back(std::move(row));\n    }\n  }\n  return result;\n}\n\nint main(int argc, char const *argv[])\n{\n  using namespace std;\n  int ret = 0;\n  cout << \"Table A: \"       << endl << tab1 << endl;\n  cout << \"Table B: \"       << endl << tab2 << endl;\n  auto tab3 = Join(tab1, 1, tab2, 0);\n  cout << \"Joined tables: \" << endl << tab3 << endl;\n  return ret;\n}\n"}
{"id": 58800, "name": "Sierpinski square 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n", "C++": "\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass sierpinski_square {\npublic:\n    void write(std::ostream& out, int size, int length, int order);\nprivate:\n    static std::string rewrite(const std::string& s);\n    void line(std::ostream& out);\n    void execute(std::ostream& out, const std::string& s);\n    double x_;\n    double y_;\n    int angle_;\n    int length_;\n};\n\nvoid sierpinski_square::write(std::ostream& out, int size, int length, int order) {\n    length_ = length;\n    x_ = (size - length)/2;\n    y_ = length;\n    angle_ = 0;\n    out << \"<svg xmlns='http:\n        << size << \"' height='\" << size << \"'>\\n\";\n    out << \"<rect width='100%' height='100%' fill='white'/>\\n\";\n    out << \"<path stroke-width='1' stroke='black' fill='none' d='\";\n    std::string s = \"F+XF+F+XF\";\n    for (int i = 0; i < order; ++i)\n        s = rewrite(s);\n    execute(out, s);\n    out << \"'/>\\n</svg>\\n\";\n}\n\nstd::string sierpinski_square::rewrite(const std::string& s) {\n    std::string t;\n    for (char c : s) {\n        if (c == 'X')\n            t += \"XF-F+F-XF+F+XF-F+F-X\";\n        else\n            t += c;\n    }\n    return t;\n}\n\nvoid sierpinski_square::line(std::ostream& out) {\n    double theta = (3.14159265359 * angle_)/180.0;\n    x_ += length_ * std::cos(theta);\n    y_ += length_ * std::sin(theta);\n    out << \" L\" << x_ << ',' << y_;\n}\n\nvoid sierpinski_square::execute(std::ostream& out, const std::string& s) {\n    out << 'M' << x_ << ',' << y_;\n    for (char c : s) {\n        switch (c) {\n        case 'F':\n            line(out);\n            break;\n        case '+':\n            angle_ = (angle_ + 90) % 360;\n            break;\n        case '-':\n            angle_ = (angle_ - 90) % 360;\n            break;\n        }\n    }\n}\n\nint main() {\n    std::ofstream out(\"sierpinski_square.svg\");\n    if (!out) {\n        std::cerr << \"Cannot open output file\\n\";\n        return 1;\n    }\n    sierpinski_square s;\n    s.write(out, 635, 5, 5);\n    return 0;\n}\n"}
{"id": 58801, "name": "Find words whose first and last three letters are equal", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\nset d= createobject(\"Scripting.Dictionary\")\nfor each aa in a\n  x=trim(aa)\n  l=len(x)\n  if l>5 then\n   d.removeall\n   for i=1 to 3\n     m=mid(x,i,1)\n     if not d.exists(m) then d.add m,null\n   next\n   res=true\n   for i=l-2 to l\n     m=mid(x,i,1)\n     if not d.exists(m) then \n       res=false:exit for \n      else\n        d.remove(m)\n      end if        \n   next \n   if res then \n     wscript.stdout.write left(x & space(15),15)\n     if left(x,3)=right(x,3) then  wscript.stdout.write \"*\"\n     wscript.stdout.writeline\n    end if \n  end if\nnext\n", "C++": "#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    int n = 0;\n    while (getline(in, word)) {\n        const size_t len = word.size();\n        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)\n            std::cout << ++n << \": \" << word << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 58802, "name": "Word break problem", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <optional>\n#include <set>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstruct string_comparator {\n    using is_transparent = void;\n    bool operator()(const std::string& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string& lhs, const std::string_view& rhs) const {\n        return lhs < rhs;\n    }\n    bool operator()(const std::string_view& lhs, const std::string& rhs) const {\n        return lhs < rhs;\n    }\n};\n\nusing dictionary = std::set<std::string, string_comparator>;\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\nauto create_string(const std::string_view& s,\n                   const std::vector<std::optional<size_t>>& v) {\n    auto idx = s.size();\n    std::vector<std::string_view> sv;\n    while (v[idx].has_value()) {\n        size_t prev = v[idx].value();\n        sv.push_back(s.substr(prev, idx - prev));\n        idx = prev;\n    }\n    std::reverse(sv.begin(), sv.end());\n    return join(sv.begin(), sv.end(), ' ');\n}\n\nstd::optional<std::string> word_break(const std::string_view& str,\n                                      const dictionary& dict) {\n    auto size = str.size() + 1;\n    std::vector<std::optional<size_t>> possible(size);\n    auto check_word = [&dict, &str](size_t i, size_t j)\n            -> std::optional<size_t> {\n        if (dict.find(str.substr(i, j - i)) != dict.end())\n            return i;\n        return std::nullopt;\n    };\n    for (size_t i = 1; i < size; ++i) {\n        if (!possible[i].has_value())\n            possible[i] = check_word(0, i);\n        if (possible[i].has_value()) {\n            for (size_t j = i + 1; j < size; ++j) {\n                if (!possible[j].has_value())\n                    possible[j] = check_word(i, j);\n            }\n            if (possible[str.size()].has_value())\n                return create_string(str, possible);\n        }\n    }\n    return std::nullopt;\n}\n\nint main(int argc, char** argv) {\n    dictionary dict;\n    dict.insert(\"a\");\n    dict.insert(\"bc\");\n    dict.insert(\"abc\");\n    dict.insert(\"cd\");\n    dict.insert(\"b\");\n    auto result = word_break(\"abcd\", dict);\n    if (result.has_value())\n        std::cout << result.value() << '\\n';\n    return 0;\n}\n"}
{"id": 58803, "name": "Latin Squares in reduced form", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntypedef std::vector<std::vector<int>> matrix;\n\nmatrix dList(int n, int start) {\n    start--; \n\n    std::vector<int> a(n);\n    std::iota(a.begin(), a.end(), 0);\n    a[start] = a[0];\n    a[0] = start;\n    std::sort(a.begin() + 1, a.end());\n    auto first = a[1];\n    \n    matrix r;\n    std::function<void(int)> recurse;\n    recurse = [&](int last) {\n        if (last == first) {\n            \n            \n            for (size_t j = 1; j < a.size(); j++) {\n                auto v = a[j];\n                if (j == v) {\n                    return; \n                }\n            }\n            \n            std::vector<int> b;\n            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n            r.push_back(b);\n            return;\n        }\n        for (int i = last; i >= 1; i--) {\n            std::swap(a[i], a[last]);\n            recurse(last - 1);\n            std::swap(a[i], a[last]);\n        }\n    };\n    recurse(n - 1);\n    return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n    for (auto &row : latin) {\n        auto it = row.cbegin();\n        auto end = row.cend();\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    std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n    if (n <= 0) {\n        if (echo) {\n            std::cout << \"[]\\n\";\n        }\n        return 0;\n    } else if (n == 1) {\n        if (echo) {\n            std::cout << \"[1]\\n\";\n        }\n        return 1;\n    }\n\n    matrix rlatin;\n    for (int i = 0; i < n; i++) {\n        rlatin.push_back({});\n        for (int j = 0; j < n; j++) {\n            rlatin[i].push_back(j);\n        }\n    }\n    \n    for (int j = 0; j < n; j++) {\n        rlatin[0][j] = j + 1;\n    }\n\n    unsigned long count = 0;\n    std::function<void(int)> recurse;\n    recurse = [&](int i) {\n        auto rows = dList(n, i);\n\n        for (size_t r = 0; r < rows.size(); r++) {\n            rlatin[i - 1] = rows[r];\n            for (int k = 0; k < i - 1; k++) {\n                for (int j = 1; j < n; j++) {\n                    if (rlatin[k][j] == rlatin[i - 1][j]) {\n                        if (r < rows.size() - 1) {\n                            goto outer;\n                        }\n                        if (i > 2) {\n                            return;\n                        }\n                    }\n                }\n            }\n            if (i < n) {\n                recurse(i + 1);\n            } else {\n                count++;\n                if (echo) {\n                    printSquare(rlatin, n);\n                }\n            }\n        outer: {}\n        }\n    };\n\n    \n    recurse(2);\n    return count;\n}\n\nunsigned long factorial(unsigned long n) {\n    if (n <= 0) return 1;\n    unsigned long prod = 1;\n    for (unsigned long i = 2; i <= n; i++) {\n        prod *= i;\n    }\n    return prod;\n}\n\nint main() {\n    std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n    reducedLatinSquares(4, true);\n\n    std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n    std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n    for (int n = 1; n < 7; n++) {\n        auto size = reducedLatinSquares(n, false);\n        auto f = factorial(n - 1);\n        f *= f * n * size;\n        std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n    }\n\n    return 0;\n}\n"}
{"id": 58804, "name": "UPC", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n", "C++": "#include <iostream>\n#include <locale>\n#include <map>\n#include <vector>\n\nstd::string trim(const std::string &str) {\n    auto s = str;\n\n    \n    auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(it1.base(), s.end());\n\n    \n    auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });\n    s.erase(s.begin(), it2);\n\n    return s;\n}\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\nconst std::map<std::string, int> LEFT_DIGITS = {\n    {\"   ## #\", 0},\n    {\"  ##  #\", 1},\n    {\"  #  ##\", 2},\n    {\" #### #\", 3},\n    {\" #   ##\", 4},\n    {\" ##   #\", 5},\n    {\" # ####\", 6},\n    {\" ### ##\", 7},\n    {\" ## ###\", 8},\n    {\"   # ##\", 9}\n};\n\nconst std::map<std::string, int> RIGHT_DIGITS = {\n    {\"###  # \", 0},\n    {\"##  ## \", 1},\n    {\"## ##  \", 2},\n    {\"#    # \", 3},\n    {\"# ###  \", 4},\n    {\"#  ### \", 5},\n    {\"# #    \", 6},\n    {\"#   #  \", 7},\n    {\"#  #   \", 8},\n    {\"### #  \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n    auto decode = [](const std::string &candidate) {\n        using OT = std::vector<int>;\n        OT output;\n        size_t pos = 0;\n\n        auto part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = LEFT_DIGITS.find(part);\n            if (e != LEFT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, MID_SENTINEL.length());\n        if (part == MID_SENTINEL) {\n            pos += MID_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        for (size_t i = 0; i < 6; i++) {\n            part = candidate.substr(pos, 7);\n            pos += 7;\n\n            auto e = RIGHT_DIGITS.find(part);\n            if (e != RIGHT_DIGITS.end()) {\n                output.push_back(e->second);\n            } else {\n                return std::make_pair(false, output);\n            }\n        }\n\n        part = candidate.substr(pos, END_SENTINEL.length());\n        if (part == END_SENTINEL) {\n            pos += END_SENTINEL.length();\n        } else {\n            return std::make_pair(false, OT{});\n        }\n\n        int sum = 0;\n        for (size_t i = 0; i < output.size(); i++) {\n            if (i % 2 == 0) {\n                sum += 3 * output[i];\n            } else {\n                sum += output[i];\n            }\n        }\n        return std::make_pair(sum % 10 == 0, output);\n    };\n\n    auto candidate = trim(input);\n\n    auto out = decode(candidate);\n    if (out.first) {\n        std::cout << out.second << '\\n';\n    } else {\n        std::reverse(candidate.begin(), candidate.end());\n        out = decode(candidate);\n        if (out.first) {\n            std::cout << out.second << \" Upside down\\n\";\n        } else if (out.second.size()) {\n            std::cout << \"Invalid checksum\\n\";\n        } else {\n            std::cout << \"Invalid digit(s)\\n\";\n        }\n    }\n}\n\nint main() {\n    std::vector<std::string> barcodes = {\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    };\n    for (auto &barcode : barcodes) {\n        decodeUPC(barcode);\n    }\n    return 0;\n}\n"}
{"id": 58805, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 58806, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 58807, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "C++": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass playfair\n{\npublic:\n    void doIt( string k, string t, bool ij, bool e )\n    {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n    }\n\nprivate:\n    void doIt( int dir )\n    {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t    if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n    }\n\n    void display()\n    {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t    cout << *si; si++; cout << *si << \" \"; si++;\n\t    if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n    }\n\n    char getChar( int a, int b )\n    {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n    }\n\n    bool getCharPos( char l, int &a, int &b )\n    {\n\tfor( int y = 0; y < 5; y++ )\n\t    for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n    }\n\n    void getTextReady( string t, bool ij, bool e )\n    {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( *si == 'J' && ij ) *si = 'I';\n\t    else if( *si == 'Q' && !ij ) continue;\n\t    _txt += *si;\n\t}\n\tif( e )\n\t{\n\t    string ntxt = \"\"; size_t len = _txt.length();\n\t    for( size_t x = 0; x < len; x += 2 )\n\t    {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t    ntxt += _txt[x + 1];\n\t\t}\n\t    }\n\t    _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n    }\n\n    void createGrid( string k, bool ij )\n    {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t    if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n    }\n\n    string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n    string key, i, txt; bool ij, e;\n    cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n    cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n    cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n    cout << \"Enter the text: \"; getline( cin, txt ); \n    playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n"}
{"id": 58808, "name": "Closest-pair problem", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n", "C++": "\n\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <iterator>\n\ntypedef std::pair<double, double> point_t;\ntypedef std::pair<point_t, point_t> points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,\n\tconst std::vector<point_t>& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector<point_t>();\n\tauto xR = std::vector<point_t>();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) / 2).first;\n\tauto yL = std::vector<point_t>();\n\tauto yR = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector<point_t>();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution<double> urd(-500.0, 500.0);\n\tstd::vector<point_t> points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n                return point_t { 1000 + urd(re), 1000 + urd(re) };\n        });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n"}
{"id": 58809, "name": "Address of a variable", "VB": "Dim TheAddress as long\nDim SecVar as byte\nDim MyVar as byte\n    MyVar = 10\n\n\nTheAddress = varptr(MyVar)\n\n\nMEMSET(TheAddress, 102, SizeOf(byte))\n\n\nshowmessage \"MyVar = \" + str$(MyVar)\n\n\nMEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))\n\n\nshowmessage \"SecVar = \" + str$(SecVar)\n", "C++": "int i;\nvoid* address_of_i = &i;\n"}
{"id": 58810, "name": "Inheritance_Single", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n", "C++": "class Animal\n{\n  \n};\n\nclass Dog: public Animal\n{\n  \n};\n\nclass Lab: public Dog\n{\n  \n};\n\nclass Collie: public Dog\n{\n  \n};\n\nclass Cat: public Animal\n{\n  \n};\n"}
{"id": 58811, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "C++": "#include <map>\n"}
{"id": 58812, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "C++": "#include <map>\n"}
{"id": 58813, "name": "Color wheel", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 58814, "name": "Color wheel", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n", "C++": "\n#include \"colorwheelwidget.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <cmath>\n\nnamespace {\n\nQColor hsvToRgb(int h, double s, double v) {\n    double hp = h/60.0;\n    double c = s * v;\n    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n    double m = v - c;\n    double r = 0, g = 0, b = 0;\n    if (hp <= 1) {\n        r = c;\n        g = x;\n    } else if (hp <= 2) {\n        r = x;\n        g = c;\n    } else if (hp <= 3) {\n        g = c;\n        b = x;\n    } else if (hp <= 4) {\n        g = x;\n        b = c;\n    } else if (hp <= 5) {\n        r = x;\n        b = c;\n    } else {\n        r = c;\n        b = x;\n    }\n    r += m;\n    g += m;\n    b += m;\n    return QColor(r * 255, g * 255, b * 255);\n}\n\n}\n\nColorWheelWidget::ColorWheelWidget(QWidget *parent)\n    : QWidget(parent) {\n    setWindowTitle(tr(\"Color Wheel\"));\n    resize(400, 400);\n}\n\nvoid ColorWheelWidget::paintEvent(QPaintEvent *event) {\n    QPainter painter(this);\n    painter.setRenderHint(QPainter::Antialiasing);\n    const QColor backgroundColor(0, 0, 0);\n    const QColor white(255, 255, 255);\n    painter.fillRect(event->rect(), backgroundColor);\n    const int margin = 10;\n    const double diameter = std::min(width(), height()) - 2*margin;\n    QPointF center(width()/2.0, height()/2.0);\n    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,\n                diameter, diameter);\n    for (int angle = 0; angle < 360; ++angle) {\n        QColor color(hsvToRgb(angle, 1.0, 1.0));\n        QRadialGradient gradient(center, diameter/2.0);\n        gradient.setColorAt(0, white);\n        gradient.setColorAt(1, color);\n        QBrush brush(gradient);\n        QPen pen(brush, 1.0);\n        painter.setPen(pen);\n        painter.setBrush(brush);\n        painter.drawPie(rect, angle * 16, 16);\n    }\n}\n"}
{"id": 58815, "name": "Find words which contain the most consonants", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 58816, "name": "Find words which contain the most consonants", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\n\ndim b(25)  \ndim c(128) \n\nwith new regexp\n  .pattern=\"([^aeiou])\"\n  .global=true\nfor each i in a\n  if len(trim(i))>10 then\n   set matches= .execute(i)   \n   rep=false\n   for each m in matches  \n     x=asc(m)  \n     c(x)=c(x)+1\n     if c(x)>1 then rep=true :exit for\n   next\n   erase c\n   if not rep then   \n     x1=matches.count\n     b(x1)=b(x1)&\" \"&i  \n   end if    \n  end if\nnext\nend with \n\n\nfor i=25 to 0 step -1\n  if b(i)<>\"\" then  wscript.echo i & \"  \"& b(i) & vbcrlf\nnext\n", "C++": "#include <bitset>\n#include <cctype>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n\n\nsize_t consonants(const std::string& word) {\n    std::bitset<26> bits;\n    size_t bit = 0;\n    for (char ch : word) {\n        ch = std::tolower(static_cast<unsigned char>(ch));\n        if (ch < 'a' || ch > 'z')\n            continue;\n        switch (ch) {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u':\n            break;\n        default:\n            bit = ch - 'a';\n            if (bits.test(bit))\n                return 0;\n            bits.set(bit);\n            break;\n        }\n    }\n    return bits.count();\n}\n\nint main(int argc, char** argv) {\n    const char* filename(argc < 2 ? \"unixdict.txt\" : argv[1]);\n    std::ifstream in(filename);\n    if (!in) {\n        std::cerr << \"Cannot open file '\" << filename << \"'.\\n\";\n        return EXIT_FAILURE;\n    }\n    std::string word;\n    std::map<size_t, std::vector<std::string>, std::greater<int>> map;\n    while (getline(in, word)) {\n        if (word.size() <= 10)\n            continue;\n        size_t count = consonants(word);\n        if (count != 0)\n            map[count].push_back(word);\n    }\n    const int columns = 4;\n    for (const auto& p : map) {\n        std::cout << p.first << \" consonants (\" << p.second.size() << \"):\\n\";\n        int n = 0;\n        for (const auto& word : p.second) {\n            std::cout << std::left << std::setw(18) << word;\n            ++n;\n            if (n % columns == 0)\n                std::cout << '\\n';\n        }\n        if (n % columns != 0)\n            std::cout << '\\n';\n        std::cout << '\\n';\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 58817, "name": "Minesweeper game", "VB": "Option Explicit\n\nPublic vTime As Single\nPublic PlaysCount As Long\n\nSub Main_MineSweeper()\nDim Userf As New cMinesweeper\n\n    \n    \n    Userf.Show 0, True\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\nusing namespace std;\ntypedef unsigned char byte;\n\nenum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };\n\nclass fieldData\n{\npublic:\n    fieldData() : value( CLOSED ), open( false ) {}\n    byte value;\n    bool open, mine;\n};\n\nclass game\n{\npublic:\n    ~game()\n    { if( field ) delete [] field; }\n\n    game( int x, int y )\n    {\n        go = false; wid = x; hei = y;\n\tfield = new fieldData[x * y];\n\tmemset( field, 0, x * y * sizeof( fieldData ) );\n\toMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;\n\tmMines = 0;\n\tint mx, my, m = 0;\n\tfor( ; m < oMines; m++ )\n\t{\n\t    do\n\t    { mx = rand() % wid; my = rand() % hei; }\n\t    while( field[mx + wid * my].mine );\n\t    field[mx + wid * my].mine = true;\n\t}\n\tgraphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; \n\tgraphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; \n    }\n\t\n    void gameLoop()\n    {\n\tstring c, r, a;\n\tint col, row;\n\twhile( !go )\n\t{\n\t    drawBoard();\n\t    cout << \"Enter column, row and an action( c r a ):\\nActions: o => open, f => flag, ? => unknown\\n\";\n\t    cin >> c >> r >> a;\n\t    if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;\n\t    col = c[0] - 65; row = r[0] - 49;\n\t    makeMove( col, row, a );\n\t}\n    }\n\nprivate:\n    void makeMove( int x, int y, string a )\n    {\n\tfieldData* fd = &field[wid * y + x];\n\tif( fd->open && fd->value < CLOSED )\n\t{\n\t    cout << \"This cell is already open!\";\n\t    Sleep( 3000 ); return;\n\t}\n\tif( a[0] == 'O' ) openCell( x, y );\n\telse if( a[0] == 'F' ) \n\t{\n\t    fd->open = true;\n\t    fd->value = FLAG;\n\t    mMines++;\n\t    checkWin();\n\t}\n\telse\n\t{\n\t    fd->open = true;\n\t    fd->value = UNKNOWN;\n\t}\n    }\n\n    bool openCell( int x, int y )\n    {\n\tif( !isInside( x, y ) ) return false;\n\tif( field[x + y * wid].mine ) boom();\n\telse \n\t{\n\t    if( field[x + y * wid].value == FLAG )\n\t    {\n\t\tfield[x + y * wid].value = CLOSED;\n\t\tfield[x + y * wid].open = false;\n\t\tmMines--;\n\t    }\n\t    recOpen( x, y );\n\t    checkWin();\n\t}\n\treturn true;\n    }\n\n    void drawBoard()\n    {\n\tsystem( \"cls\" );\n\tcout << \"Marked mines: \" << mMines << \" from \" << oMines << \"\\n\\n\";\t\t\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"  \" << ( char )( 65 + x ) << \" \"; \n\tcout << \"\\n\"; int yy;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = y * wid;\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << \"+---\";\n\n\t    cout << \"+\\n\"; fieldData* fd;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy]; cout<< \"| \";\n\t\tif( !fd->open ) cout << ( char )graphs[1] << \" \";\n\t\telse \n\t\t{\n\t\t    if( fd->value > 9 )\n\t\t\tcout << ( char )graphs[fd->value - 9] << \" \";\n\t\t    else\n\t\t    {\n\t\t\tif( fd->value < 1 ) cout << \"  \";\n\t\t\t    else cout << ( char )(fd->value + 48 ) << \" \";\n\t\t    }\n\t\t}\n\t    }\n\t    cout << \"| \" << y + 1 << \"\\n\";\n\t}\n\tfor( int x = 0; x < wid; x++ )\n\t    cout << \"+---\";\n\n\tcout << \"+\\n\\n\";\n    }\n\n    void checkWin()\n    {\n\tint z = wid * hei - oMines, yy;\n\tfieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->open && fd->value != FLAG ) z--;\n\t    }\n\t}\n\tif( !z ) lastMsg( \"Congratulations, you won the game!\");\n    }\n\n    void boom()\n    {\n\tint yy; fieldData* fd;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    yy = wid * y;\n\t    for( int x = 0; x < wid; x++ )\n\t    {\n\t\tfd = &field[x + yy];\n\t\tif( fd->value == FLAG )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = fd->mine ? MINE : ERR;\n\t\t}\n\t\telse if( fd->mine )\n\t\t{\n\t\t    fd->open = true;\n\t\t    fd->value = MINE;\n\t\t}\n\t    }\n\t}\n\tlastMsg( \"B O O O M M M M M !\" );\n    }\n\n    void lastMsg( string s )\n    {\n\tgo = true; drawBoard();\n\tcout << s << \"\\n\\n\";\n    }\n\n    bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }\n\n    void recOpen( int x, int y )\n    {\n\tif( !isInside( x, y ) || field[x + y * wid].open ) return;\n\tint bc = getMineCount( x, y );\n\tfield[x + y * wid].open = true;\n\tfield[x + y * wid].value = bc;\n\tif( bc ) return;\n\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\trecOpen( x + xx, y + yy );\n\t    }\n    }\n\n    int getMineCount( int x, int y )\n    {\n\tint m = 0;\n\tfor( int yy = -1; yy < 2; yy++ )\n\t    for( int xx = -1; xx < 2; xx++ )\n\t    {\n\t\tif( xx == 0 && yy == 0 ) continue;\n\t\tif( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;\n\t    }\n\t\t\n\treturn m;\n    }\n\t\n    int wid, hei, mMines, oMines;\n    fieldData* field; bool go;\n    int graphs[6];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n    game g( 4, 6 ); g.gameLoop();\n    return system( \"pause\" );\n}\n"}
{"id": 58818, "name": "Kosaraju", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 58819, "name": "Kosaraju", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n", "C++": "#include <functional>\n#include <iostream>\n#include <ostream>\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\nstd::vector<int> kosaraju(std::vector<std::vector<int>>& g) {\n    \n    auto size = g.size();\n    std::vector<bool> vis(size);           \n    std::vector<int> l(size);              \n    auto x = size;                         \n    std::vector<std::vector<int>> t(size); \n\n    \n    std::function<void(int)> visit;\n    visit = [&](int u) {\n        if (!vis[u]) {\n            vis[u] = true;\n            for (auto v : g[u]) {\n                visit(v);\n                t[v].push_back(u); \n            }\n            l[--x] = u;\n        }\n    };\n\n    \n    for (int i = 0; i < g.size(); ++i) {\n        visit(i);\n    }\n    std::vector<int> c(size); \n\n    \n    std::function<void(int, int)> assign;\n    assign = [&](int u, int root) {\n        if (vis[u]) { \n            vis[u] = false;\n            c[u] = root;\n            for (auto v : t[u]) {\n                assign(v, root);\n            }\n        }\n    };\n\n    \n    for (auto u : l) {\n        assign(u, u);\n    }\n\n    return c;\n}\n\nstd::vector<std::vector<int>> g = {\n    {1},\n    {2},\n    {0},\n    {1, 2, 4},\n    {3, 5},\n    {2, 6},\n    {5},\n    {4, 6, 7},\n};\n\nint main() {\n    using namespace std;\n\n    cout << kosaraju(g) << endl;\n\n    return 0;\n}\n"}
{"id": 58820, "name": "Nested templated data", "VB": "Public Sub test()\n    Dim t(2) As Variant\n    t(0) = [{1,2}]\n    t(1) = [{3,4,1}]\n    t(2) = 5\n    p = [{\"Payload#0\",\"Payload#1\",\"Payload#2\",\"Payload#3\",\"Payload#4\",\"Payload#5\",\"Payload#6\"}]\n    Dim q(6) As Boolean\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            For j = LBound(t(i)) To UBound(t(i))\n                q(t(i)(j)) = True\n                t(i)(j) = p(t(i)(j) + 1)\n            Next j\n        Else\n            q(t(i)) = True\n            t(i) = p(t(i) + 1)\n        End If\n    Next i\n    For i = LBound(t) To UBound(t)\n        If IsArray(t(i)) Then\n            Debug.Print Join(t(i), \", \")\n        Else\n            Debug.Print t(i)\n        End If\n    Next i\n    For i = LBound(q) To UBound(q)\n        If Not q(i) Then Debug.Print p(i + 1); \" is not used\"\n    Next i\nEnd Sub\n", "C++": "#include <iostream>\n#include <set>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n\ntemplate<typename P>\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n    if(index < 0 || index >= (int)size(payloads)) cout << \"null\";        \n    else cout << \"'\" << payloads[index] << \"'\";\n    if (!isLast) cout << \", \";  \n}\n\n\ntemplate<typename P, typename... Ts>\nvoid PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)\n{\n    std::apply  \n    (\n        [&payloads, isLast](Ts const&... tupleArgs)\n        {\n            size_t n{0};\n            cout << \"[\";\n            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n            cout << \"]\";\n            cout << (isLast ? \"\\n\" : \",\\n\");\n        }, nestedTuple\n    );\n}\n\n\nvoid FindUniqueIndexes(set<int> &indexes, int index)\n{\n    indexes.insert(index);\n}\n\n\ntemplate<typename... Ts>\nvoid FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)\n{\n    std::apply\n    (\n        [&indexes](Ts const&... tupleArgs)\n        {\n            (FindUniqueIndexes(indexes, tupleArgs),...);\n        }, nestedTuple\n    );\n}\n\n\ntemplate<typename P>\nvoid PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)\n{\n    for(size_t i = 0; i < size(payloads); i++)\n    {\n        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n    }\n}\n\nint main()\n{\n    \n    vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n    const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; \n\n    \n    auto tpl = make_tuple(make_tuple(\n        make_tuple(1, 2),\n        make_tuple(3, 4, 1),\n        5));\n\n    cout << \"Mapping indexes to payloads:\\n\";\n    PrintPayloads(payloads, tpl);      \n\n    cout << \"\\nFinding unused payloads:\\n\";\n    set<int> usedIndexes;\n    FindUniqueIndexes(usedIndexes, tpl);\n    PrintUnusedPayloads(usedIndexes, payloads);\n\n    cout << \"\\nMapping to some out of range payloads:\\n\";\n    PrintPayloads(shortPayloads, tpl);      \n    \n    return 0;\n}\n"}
{"id": 58821, "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", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 58822, "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", "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": 58823, "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", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 58824, "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", "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": 58825, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 58826, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58827, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58828, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 58829, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 58830, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 58831, "name": "Loops_Continue", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 58832, "name": "General FizzBuzz", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 58833, "name": "String case", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 58834, "name": "MD5", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 58835, "name": "Date manipulation", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 58836, "name": "Sorting algorithms_Sleep sort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 58837, "name": "Loops_Nested", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 58838, "name": "Remove duplicate elements", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 58839, "name": "Look-and-say sequence", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 58840, "name": "Stack", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 58841, "name": "Conditional structures", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 58842, "name": "Sort using a custom comparator", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 58843, "name": "Sorting algorithms_Selection sort", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 58844, "name": "Apply a callback to an array", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 58845, "name": "Singleton", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 58846, "name": "Loops_Downward for", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 58847, "name": "Loops_For", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 58848, "name": "Long multiplication", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 58849, "name": "Bulls and cows", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 58850, "name": "Sorting algorithms_Bubble sort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 58851, "name": "File input_output", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 58852, "name": "Arithmetic_Integer", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 58853, "name": "Matrix transposition", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 58854, "name": "Man or boy test", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 58855, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 58856, "name": "Find limit of recursion", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 58857, "name": "Perfect numbers", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 58858, "name": "Arbitrary-precision integers (included)", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 58859, "name": "Inverted index", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 58860, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 58861, "name": "Least common multiple", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 58862, "name": "Loops_Break", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 58863, "name": "Middle three digits", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 58864, "name": "Literals_String", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 58865, "name": "Enumerations", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 58866, "name": "Unix_ls", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 58867, "name": "Move-to-front algorithm", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 58868, "name": "Execute a system command", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 58869, "name": "XML validation", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 58870, "name": "Longest increasing subsequence", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 58871, "name": "Brace expansion", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 58872, "name": "Modular inverse", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 58873, "name": "Hello world_Web server", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 58874, "name": "Active Directory_Connect", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 58875, "name": "Literals_Floating point", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 58876, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 58877, "name": "Church numerals", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 58878, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 58879, "name": "Break OO privacy", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 58880, "name": "Object serialization", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 58881, "name": "Long year", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 58882, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 58883, "name": "Associative array_Merging", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 58884, "name": "Markov chain text generator", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 58885, "name": "Dijkstra's algorithm", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 58886, "name": "Associative array_Iteration", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 58887, "name": "Hash join", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 58888, "name": "Respond to an unknown method call", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 58889, "name": "Inheritance_Single", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 58890, "name": "Associative array_Creation", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 58891, "name": "Polymorphism", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 58892, "name": "Reflection_List properties", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 58893, "name": "Align columns", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 58894, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 58895, "name": "URL parser", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 58896, "name": "Dynamic variable names", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 58897, "name": "Reflection_List methods", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 58898, "name": "Send an unknown method call", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 58899, "name": "Variables", "C#": "int j;\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 58900, "name": "Add a variable to a class instance at runtime", "C#": "\n\n\n\n\n\n\n\nusing System;\nusing System.Dynamic;\n\nnamespace DynamicClassVariable\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            \n            \n            dynamic sampleObj = new ExpandoObject();\n            \n            sampleObj.bar = 1;\n            Console.WriteLine( \"sampleObj.bar = {0}\", sampleObj.bar );\n\n            \n            \n            \n            \n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n}\n", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n"}
{"id": 58901, "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": 58902, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 58903, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 58904, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 58905, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58906, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58907, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58908, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58909, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58910, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 58911, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 58912, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 58913, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 58914, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 58915, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 58916, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 58917, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 58918, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 58919, "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", "PHP": "<?php\n$h  =                             0;\n$s  =   file_get_contents(__FILE__);\n$l  =                    strlen($s);\nforeach ( count_chars($s, 1) as $c )\n                               $h -=\n                       ( $c / $l ) *\n                  log( $c / $l, 2 );\necho                             $h;\n"}
{"id": 58920, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 58921, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 58922, "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", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 58923, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 58924, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 58925, "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", "PHP": "<?php\necho \"<h1>\" . \"Choose: ROCK - PAPER - SCISSORS\" . \"</h1>\";\necho \"<h2>\";\necho \"\";\n\n$player = strtoupper( $_GET[\"moves\"] );\n$wins = [\n    'ROCK' => 'SCISSORS',\n    'PAPER' => 'ROCK',\n    'SCISSORS' => 'PAPER'\n  ];\n$a_i = array_rand($wins);\necho \"<br>\";\necho \"Player chooses \" . \"<i style=\\\"color:blue\\\">\" . $player . \"</i>\";\necho \"<br>\";\necho \"<br>\" . \"A.I chooses \" . \"<i style=\\\"color:red\\\">\"  . $a_i . \"</i>\";\n\n$results = \"\";\nif ($player == $a_i){\n$results = \"Draw\";\n} else if($wins[$a_i] == $player ){\n  $results = \"A.I wins\";\n} else {\n  $results = \"Player wins\";\n}\n\necho \"<br>\" . $results;\n?>\n"}
{"id": 58926, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 58927, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 58928, "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", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 58929, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 58930, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 58931, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 58932, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 58933, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 58934, "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", "PHP": "$server = \"speedtest.tele2.net\";\n$user = \"anonymous\";\n$pass = \"ftptest@example.com\";\n\n$conn = ftp_connect($server);\nif (!$conn) {\n    die('unable to connect to: '. $server);\n}\n$login = ftp_login($conn, $user, $pass);\nif (!$login) {\n    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;\n} else{\n    echo 'connected successfully'.PHP_EOL;\n    $directory = ftp_nlist($conn,'');\n    print_r($directory);\n}\nif (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {\n    echo \"Successfully downloaded file\".PHP_EOL;\n} else {\n    echo \"failed to download file\";\n}\n"}
{"id": 58935, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 58936, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 58937, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 58938, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 58939, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 58940, "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", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 58941, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 58942, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 58943, "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", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 58944, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 58945, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 58946, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 58947, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 58948, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 58949, "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", "PHP": "<?php\n$colors = array(array(  0,   0,   0),   // black\n                array(255,   0,   0),   // red\n                array(  0, 255,   0),   // green\n                array(  0,   0, 255),   // blue\n                array(255,   0, 255),   // magenta\n                array(  0, 255, 255),   // cyan\n                array(255, 255,   0),   // yellow\n                array(255, 255, 255));  // white\n\ndefine('BARWIDTH', 640 / count($colors));\ndefine('HEIGHT',   480);\n\n$image = imagecreate(BARWIDTH * count($colors), HEIGHT);\n\nforeach ($colors as $position => $color) {\n    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);\n    imagefilledrectangle($image, $position * BARWIDTH, 0,\n                         $position * BARWIDTH + BARWIDTH - 1,\n                         HEIGHT - 1, $color);\n}\n\nheader('Content-type:image/png');\nimagepng($image);\nimagedestroy($image);\n"}
{"id": 58950, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 58951, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 58952, "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", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 58953, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 58954, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 58955, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 58956, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 58957, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 58958, "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", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 58959, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 58960, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 58961, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 58962, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 58963, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 58964, "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", "PHP": "$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];\n$lc_allowed = array_map('strtolower', $allowed);\n\n$tests = [\n    ['MyData.a##',true],\n    ['MyData.tar.Gz',true],\n    ['MyData.gzip',false],\n    ['MyData.7z.backup',false],\n    ['MyData...',false],\n    ['MyData',false],\n    ['archive.tar.gz', true]\n];\n\nforeach ($tests as $test) {\n    $ext = pathinfo($test[0], PATHINFO_EXTENSION);\n    if (in_array(strtolower($ext), $lc_allowed)) {\n        $result = 'true';\n    } else {\n        $result = 'false';\n    }\n    printf(\"%20s : %s \\n\", $test[0],$result);\n}\n"}
{"id": 58965, "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", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 58966, "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", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 58967, "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", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 58968, "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", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 58969, "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", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 58970, "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", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 58971, "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", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 58972, "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", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 58973, "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", "PHP": "<?php\n$time = new DateTime('March 7 2009 7:30pm EST');\n$time->modify('+12 hours');\necho $time->format('c');\n?>\n"}
{"id": 58974, "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", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 58975, "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", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 58976, "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", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 58977, "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", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 58978, "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", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 58979, "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", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 58980, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 58981, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 58982, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 58983, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 58984, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 58985, "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", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 58986, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 58987, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 58988, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 58989, "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", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 58990, "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", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 58991, "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", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 58992, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 58993, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 58994, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 58995, "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", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 58996, "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", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 58997, "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", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 58998, "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", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 58999, "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", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 59000, "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", "PHP": "function stoogeSort(&$arr, $i, $j)\n{\n\tif($arr[$j] < $arr[$i])\n\t{\n\t\tlist($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);\n\t}\n\tif(($j - $i) > 1)\n\t{\n\t\t$t = ($j - $i + 1) / 3;\n\t\tstoogesort($arr, $i, $j - $t);\n\t\tstoogesort($arr, $i + $t, $j);\n\t\tstoogesort($arr, $i, $j - $t);\n\t}\n}\n"}
{"id": 59001, "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", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 59002, "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", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 59003, "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", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 59004, "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", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 59005, "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", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 59006, "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", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 59007, "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", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 59008, "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", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 59009, "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", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 59010, "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", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 59011, "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", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 59012, "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", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 59013, "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", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 59014, "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", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 59015, "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", "PHP": "class Singleton {\n  protected static $instance = null;\n  public $test_var;\n  private function __construct(){\n\n  }\n  public static function getInstance(){\n    if (is_null(self::$instance)){\n      self::$instance = new self();\n    }\n    return self::$instance;\n  }\n}\n\n$foo = Singleton::getInstance();\n$foo->test_var = 'One';\n\n$bar = Singleton::getInstance();\necho $bar->test_var; //Prints 'One'\n\n$fail = new Singleton(); //Fatal error\n"}
{"id": 59016, "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", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 59017, "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", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 59018, "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", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 59019, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 59020, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 59021, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 59022, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 59023, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 59024, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 59025, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 59026, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 59027, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 59028, "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", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 59029, "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", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 59030, "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", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 59031, "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", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 59032, "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", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 59033, "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", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 59034, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 59035, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 59036, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 59037, "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", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 59038, "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", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 59039, "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", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 59040, "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", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 59041, "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", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 59042, "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", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 59043, "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", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 59044, "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", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 59045, "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", "PHP": "<?php\nfunction A($k,$x1,$x2,$x3,$x4,$x5) {\n    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {\n        return A(--$k,$b,$x1,$x2,$x3,$x4);\n    };\n    return $k <= 0 ? $x4() + $x5() : $b();\n}  \n\necho A(10, function () { return  1; },\n           function () { return -1; },\n           function () { return -1; },\n           function () { return  1; }, \n           function () { return  0; }) . \"\\n\";\n?>\n"}
{"id": 59046, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59047, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59048, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59049, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59050, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59051, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59052, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 59053, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 59054, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 59055, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 59056, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 59057, "name": "Sorting algorithms_Bead sort", "Python": "\nfrom itertools import zip_longest\n\n\ndef beadsort(l):\n    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n\nprint(beadsort([5,3,1,7,4,1,1]))\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 59058, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 59059, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 59060, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 59061, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 59062, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 59063, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "PHP": "<?php\n\nfunction buildInvertedIndex($filenames)\n{\n    $invertedIndex = [];\n\n    foreach($filenames as $filename)\n    {\n        $data = file_get_contents($filename);\n\n        if($data === false) die('Unable to read file: ' . $filename);\n\n        preg_match_all('/(\\w+)/', $data, $matches, PREG_SET_ORDER);\n\n        foreach($matches as $match)\n        {\n            $word = strtolower($match[0]);\n\n            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];\n            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;\n        }\n    }\n\n    return $invertedIndex;\n}\n\nfunction lookupWord($invertedIndex, $word)\n{\n    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;\n}\n\n$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);\n\nforeach(['cat', 'is', 'banana', 'it'] as $word)\n{\n    $matches = lookupWord($invertedIndex, $word);\n\n    if($matches !== false)\n    {\n        echo \"Found the word \\\"$word\\\" in the following files: \" . implode(', ', $matches) . \"\\n\";\n    }\n    else\n    {\n        echo \"Unable to find the word \\\"$word\\\" in the index\\n\";\n    }\n}\n"}
{"id": 59064, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59065, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59066, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59067, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59068, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59069, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59070, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 59071, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 59072, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 59073, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 59074, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 59075, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 59076, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 59077, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 59078, "name": "Hello world_Line printer", "Python": "lp = open(\"/dev/lp0\")\nlp.write(\"Hello World!\\n\")\nlp.close()\n", "PHP": "<?php\nfile_put_contents('/dev/lp0', 'Hello world!');\n?>\n"}
{"id": 59079, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 59080, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 59081, "name": "Trabb Pardo–Knuth algorithm", "Python": "Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def f(x): return abs(x) ** 0.5 + 5 * x**3\n\n>>> print(', '.join('%s:%s' % (x, v if v<=400 else \"TOO LARGE!\")\n\t           for x,v in ((y, f(float(y))) for y in input('\\nnumbers: ').strip().split()[:11][::-1])))\n\n11 numbers: 1 2 3 4 5 6 7 8 9 10 11\n11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0\n>>>\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 59082, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 59083, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 59084, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 59085, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 59086, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 59087, "name": "Odd word problem", "Python": "from sys import stdin, stdout\n\ndef char_in(): return stdin.read(1)\ndef char_out(c): stdout.write(c)\n\ndef odd(prev = lambda: None):\n\ta = char_in()\n\tif not a.isalpha():\n\t\tprev()\n\t\tchar_out(a)\n\t\treturn a != '.'\n\n\t\n\tdef clos():\n\t\tchar_out(a)\n\t\tprev()\n\n\treturn odd(clos)\n\ndef even():\n\twhile True:\n\t\tc = char_in()\n\t\tchar_out(c)\n\t\tif not c.isalpha(): return c != '.'\n\ne = False\nwhile odd() if e else even():\n\te = not e\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 59088, "name": "Table creation_Postal addresses", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 59089, "name": "Table creation_Postal addresses", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 59090, "name": "Table creation_Postal addresses", "Python": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute()\n<sqlite3.Cursor object at 0x013265C0>\n>>>\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 59091, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 59092, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 59093, "name": "Soundex", "Python": "from itertools import groupby\n\ndef soundex(word):\n   codes = (\"bfpv\",\"cgjkqsxz\", \"dt\", \"l\", \"mn\", \"r\")\n   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)\n   cmap2 = lambda kar: soundDict.get(kar, '9')\n   sdx =  ''.join(cmap2(kar) for kar in word.lower())\n   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')\n   sdx3 = sdx2[0:4].ljust(4,'0')\n   return sdx3\n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 59094, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 59095, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 59096, "name": "Bitmap_Histogram", "Python": "from PIL import Image\n\n\nimage = Image.open(\"lena.jpg\")\n\nwidth, height = image.size\n\namount = width * height\n\n\ntotal = 0\n\nbw_image = Image.new('L', (width, height), 0)\n\nbm_image = Image.new('1', (width, height), 0)\n\nfor h in range(0, height):\n    for w in range(0, width):\n        r, g, b = image.getpixel((w, h))\n\n        greyscale = int((r + g + b) / 3)\n        total += greyscale\n\n        bw_image.putpixel((w, h), gray_scale)\n\n\navg = total / amount\n\nblack = 0\nwhite = 1\n\nfor h in range(0, height):\n    for w in range(0, width):\n        v = bw_image.getpixel((w, h))\n\n        if v >= avg:\n            bm_image.putpixel((w, h), white)\n        else:\n            bm_image.putpixel((w, h), black)\n\nbw_image.show()\nbm_image.show()\n", "PHP": "define('src_name', 'input.jpg');\t// source image\ndefine('dest_name', 'output.jpg');\t// destination image\n\n$img = imagecreatefromjpeg(src_name);\t// read image\n\nif(empty($img)){\n\techo 'Image could not be loaded!'; \n\texit; \n}\n\n$black = imagecolorallocate($img, 0, 0, 0);\n$white = imagecolorallocate($img, 255, 255, 255);\n$width = imagesx($img);\n$height = imagesy($img);\n\n$array_lum = array(); \t// for storage of luminosity of each pixel\n$sum_lum = 0;\t\t// total sum of luminosity\n$average_lum = 0;\t// average luminosity of whole image\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\t\t$color = imagecolorat($img, $x, $y);\n\t\t$r = ($color >> 16) & 0xFF;\n\t\t$g = ($color >> 8) & 0xFF;\n\t\t$b = $color & 0xFF;\n\n\t\t$array_lum[$x][$y] = ($r + $g + $b);\n\n\t\t$sum_lum += $array_lum[$x][$y];\n\t}\n}\n\n$average_lum = $sum_lum / ($width * $height);\n\nfor($x = 0; $x < $width; $x++){\t\n\tfor($y = 0; $y < $height; $y++){\n\n\n\t\tif($array_lum[$x][$y] > $average_lum){\n\t\t\timagesetpixel($img, $x, $y, $white);\n\t\t}\n\t\telse{\n\t\t\timagesetpixel($img, $x, $y, $black);\n\t\t}\n\t}\n}\n\nimagejpeg($img, dest_name);\n\nif(!file_exists(dest_name)){\n\techo 'Image not saved! Check permission!';\n}\n"}
{"id": 59097, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 59098, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 59099, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 59100, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 59101, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 59102, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 59103, "name": "SOAP", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n"}
{"id": 59104, "name": "SOAP", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n"}
{"id": 59105, "name": "SOAP", "Python": "from SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http://example.com/soap/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n", "PHP": "<?php\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n$client = new SoapClient(\"http://example.com/soap/definition.wsdl\");\n\nprint_r($client->__getTypes());\n\nprint_r($client->__getFunctions());\n?>\n"}
{"id": 59106, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 59107, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 59108, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 59109, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 59110, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 59111, "name": "Modulinos", "Python": "\n\n\n\ndef meaning_of_life():\n  return 42\n\nif __name__ == \"__main__\":\n  print(\"Main: The meaning of life is %s\" % meaning_of_life())\n", "PHP": "<?php\nfunction meaning_of_life() {\n\treturn 42;\n}\n\nfunction main($args) {\n\techo \"Main: The meaning of life is \" . meaning_of_life() . \"\\n\";\n}\n\nif (preg_match(\"/scriptedmain/\", $_SERVER[\"SCRIPT_NAME\"])) {\n\tmain($argv);\n}\n?>\n"}
{"id": 59112, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 59113, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 59114, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "PHP": "<?php\nforeach(scandir('.') as $fileName){\n    echo $fileName.\"\\n\";\n}\n"}
{"id": 59115, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 59116, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 59117, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 59118, "name": "Active Directory_Search for a user", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 59119, "name": "Active Directory_Search for a user", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 59120, "name": "Active Directory_Search for a user", "Python": "Import-Module ActiveDirectory\n\n$searchData = \"user name\"\n$searchBase = \"DC=example,DC=com\"\n\n\nget-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase\n", "PHP": "<?php\n\n$l = ldap_connect('ldap.example.com');\nldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($l, LDAP_OPT_REFERRALS, false);\n\n$bind = ldap_bind($l, 'me@example.com', 'password');\n\n$base = 'dc=example, dc=com';\n$criteria = '(&(objectClass=user)(sAMAccountName=username))';\n$attributes = array('displayName', 'company');\n\n$search = ldap_search($l, $base, $criteria, $attributes);\n$entries = ldap_get_entries($l, $search);\n\nvar_dump($entries);\n"}
{"id": 59121, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 59122, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 59123, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 59124, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 59125, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 59126, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 59127, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 59128, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 59129, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 59130, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 59131, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 59132, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 59133, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 59134, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 59135, "name": "Self-describing numbers", "Python": ">>> def isSelfDescribing(n):\n\ts = str(n)\n\treturn all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))\n\n>>> [x for x in range(4000000) if isSelfDescribing(x)]\n[1210, 2020, 21200, 3211000]\n>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]\n[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 59136, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 59137, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 59138, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 59139, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 59140, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 59141, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 59142, "name": "Bitmap_Bézier curves_Cubic", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n"}
{"id": 59143, "name": "Bitmap_Bézier curves_Cubic", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n"}
{"id": 59144, "name": "Bitmap_Bézier curves_Cubic", "Python": "def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):\n    pts = []\n    for i in range(n+1):\n        t = i / n\n        a = (1. - t)**3\n        b = 3. * t * (1. - t)**2\n        c = 3.0 * t**2 * (1.0 - t)\n        d = t**3\n        \n        x = int(a * x0 + b * x1 + c * x2 + d * x3)\n        y = int(a * y0 + b * y1 + c * y2 + d * y3)\n        pts.append( (x, y) )\n    for i in range(n):\n        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])\nBitmap.cubicbezier = cubicbezier\n\nbitmap = Bitmap(17,17)\nbitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)\nbitmap.chardisplay()\n\n\n\n", "PHP": "<?\n\n$image = imagecreate(200, 200);\n\nimagecolorallocate($image, 255, 255, 255);\n$color = imagecolorallocate($image, 255, 0, 0);\ncubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);\nimagepng($image);\n\nfunction cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {\n\t$pts = array();\n\n\tfor($i = 0; $i <= $n; $i++) {\n\t\t$t = $i / $n;\n\t\t$t1 = 1 - $t;\n\t\t$a = pow($t1, 3);\n\t\t$b = 3 * $t * pow($t1, 2);\n\t\t$c = 3 * pow($t, 2) * $t1;\n\t\t$d = pow($t, 3);\n\n\t\t$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);\n\t\t$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);\n\t\t$pts[$i] = array($x, $y);\n\t}\n\n\tfor($i = 0; $i < $n; $i++) {\n\t\timageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);\n\t}\n}\n"}
{"id": 59145, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 59146, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 59147, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "PHP": "<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n"}
{"id": 59148, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 59149, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 59150, "name": "Update a configuration file", "Python": "\n\n\n\n\nimport re\nimport string\n\n\n\n\n\nDISABLED_PREFIX = ';'\n\n\n\n\n\nclass Option(object):\n    \n\n    \n    def __init__(self, name, value=None, disabled=False,\n                 disabled_prefix=DISABLED_PREFIX):\n        \n        self.name = str(name)\n        self.value = value\n        self.disabled = bool(disabled)\n        self.disabled_prefix = disabled_prefix\n\n    \n    def __str__(self):\n        \n        disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]\n        value = (' %s' % self.value, '')[self.value is None]\n        return ''.join((disabled, self.name, value))\n\n    \n    def get(self):\n        \n        enabled = not bool(self.disabled)\n        if self.value is None:\n            value = enabled\n        else:\n            value = enabled and self.value\n        return value\n\n    \n\n\n\nclass Config(object):\n    \n    \n    reOPTION = r'^\\s*(?P<disabled>%s*)\\s*(?P<name>\\w+)(?:\\s+(?P<value>.+?))?\\s*$'\n\n    \n    def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):\n        \n        self.disabled_prefix = disabled_prefix\n        self.contents = []          \n        self.options = {}           \n        self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)\n        if fname:\n            self.parse_file(fname)\n\n    \n    def __str__(self):\n        \n        return '\\n'.join(map(str, self.contents))\n\n    \n    def parse_file(self, fname):\n        \n        with open(fname) as f:\n            self.parse_lines(f)\n        return self\n\n    \n    def parse_lines(self, lines):\n        \n        for line in lines:\n            self.parse_line(line)\n        return self\n\n    \n    def parse_line(self, line):\n        \n        s = ''.join(c for c in line.strip() if c in string.printable) \n        moOPTION = self.creOPTION.match(s)\n        if moOPTION:\n            name = moOPTION.group('name').upper()\n            if not name in self.options:\n                self.add_option(name, moOPTION.group('value'),\n                                moOPTION.group('disabled'))\n        else:\n            if not s.startswith(self.disabled_prefix):\n                self.contents.append(line.rstrip())\n        return self\n\n    \n    def add_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = Option(name, value, disabled)\n        self.options[name] = opt\n        self.contents.append(opt)\n        return opt\n\n    \n    def set_option(self, name, value=None, disabled=False):\n        \n        name = name.upper()\n        opt = self.options.get(name)\n        if opt:\n            opt.value = value\n            opt.disabled = disabled\n        else:\n            opt = self.add_option(name, value, disabled)\n        return opt\n\n    \n    def enable_option(self, name, value=None):\n        \n        return self.set_option(name, value, False)\n\n    \n    def disable_option(self, name, value=None):\n        \n        return self.set_option(name, value, True)\n\n    \n    def get_option(self, name):\n        \n        opt = self.options.get(name.upper())\n        value = opt.get() if opt else None\n        return value\n\n\n\n\n\nif __name__ == '__main__':\n    import sys\n    cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)\n    cfg.disable_option('needspeeling')\n    cfg.enable_option('seedsremoved')\n    cfg.enable_option('numberofbananas', 1024)\n    cfg.enable_option('numberofstrawberries', 62000)\n    print cfg\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 59151, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 59152, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 59153, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 59154, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 59155, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 59156, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 59157, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 59158, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 59159, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\n$zero = function($f) { return function ($x) { return $x; }; };\n\n$succ = function($n) { \n  return function($f) use (&$n) { \n    return function($x) use (&$n, &$f) {\n      return $f( ($n($f))($x) );\n    };\n  };\n};\n\n$add = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($f))(($n($f))($x));\n    };\n  };\n};\n\n$mult = function($n, $m) {\n  return function($f) use (&$n, &$m) {\n    return function($x) use (&$f, &$n, &$m) {\n      return ($m($n($f)))($x);\n    };\n  };\n};\n\n$power = function($b,$e) {\n  return $e($b);\n};\n\n$to_int = function($f) {\n  $count_up = function($i) { return $i+1; };\n  return ($f($count_up))(0);\n};\n\n$from_int = function($x) {\n  $countdown = function($i) use (&$countdown) { \n    global $zero, $succ;\n    if ( $i == 0 ) {\n      return $zero;\n    } else {\n      return $succ($countdown($i-1));\n    };\n  };\n  return $countdown($x);\n};\n\n$three = $succ($succ($succ($zero)));\n$four = $from_int(4);\nforeach (array($add($three,$four), $mult($three,$four),\n\t       $power($three,$four), $power($four,$three)) as $ch) {\n  print($to_int($ch));\n  print(\"\\n\");\n}\n?>\n"}
{"id": 59160, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59161, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59162, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59163, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59164, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59165, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59166, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 59167, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 59168, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "PHP": "$myObj = new Object();\n$serializedObj = serialize($myObj);\n"}
{"id": 59169, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 59170, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 59171, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 59172, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59173, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59174, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59175, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59176, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59177, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59178, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 59179, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 59180, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "PHP": "<?php\n\nfunction markovChainTextGenerator($text, $keySize, $maxWords) {\n\n    $token = array();\n    $position = 0;\n    $maxPosition = strlen($text);\n    while ($position < $maxPosition) {\n        if (preg_match('/^(\\S+)/', substr($text, $position, 25), $matches)) {\n            $token[] = $matches[1];\n            $position += strlen($matches[1]);\n        }\n        elseif (preg_match('/^(\\s+)/', substr($text, $position, 25), $matches)) {\n            $position += strlen($matches[1]);\n        }\n        else {\n            die(\n                'Unknown token found at position ' . $position . ' : ' . \n                substr($text, $position, 25) . '...' . PHP_EOL\n            );\n        }\n    }\n\n    $dictionary = array();\n    for ($i = 0 ; $i < count($token) - $keySize ; $i++) {\n        $prefix = '';\n        $separator = '';\n        for ($c = 0 ; $c < $keySize ; $c++) {\n            $prefix .= $separator . $token[$i + $c];\n            $separator = '.';\n        }\n        $dictionary[$prefix][] = $token[$i + $keySize];\n    }\n\n    $rand = rand(0, count($token) - $keySize);\n    $startToken = array();\n    for ($c = 0 ; $c < $keySize ; $c++) {\n        array_push($startToken, $token[$rand + $c]);\n    }\n\n    $text = implode(' ', $startToken);\n    $words = $keySize;\n    do {\n        $tokenKey = implode('.', $startToken);\n        $rand = rand(0, count($dictionary[$tokenKey]) - 1);\n        $newToken = $dictionary[$tokenKey][$rand];\n        $text .= ' ' . $newToken;\n        $words++;\n        array_shift($startToken);\n        array_push($startToken, $newToken);\n    } while($words < $maxWords);\n    return $text;\n\n}\n\nsrand(5678);\n\n$text = markovChainTextGenerator(\n    file_get_contents(__DIR__ . '/inc/alice_oz.txt'),\n    3,\n    308\n);\n\necho wordwrap($text, 100, PHP_EOL) . PHP_EOL;\n"}
{"id": 59181, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 59182, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 59183, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 59184, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 59185, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 59186, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 59187, "name": "Here document", "Python": "print()\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 59188, "name": "Here document", "Python": "print()\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 59189, "name": "Here document", "Python": "print()\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 59190, "name": "Here document", "Python": "print()\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 59191, "name": "Here document", "Python": "print()\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 59192, "name": "Here document", "Python": "print()\n", "PHP": "$address = <<<END\n1, High Street,\n$town_name,\nWest Midlands.\nWM4 5HD.\nEND;\n"}
{"id": 59193, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 59194, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 59195, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 59196, "name": "Respond to an unknown method call", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 59197, "name": "Respond to an unknown method call", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 59198, "name": "Respond to an unknown method call", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n", "PHP": "<?php\nclass Example {\n  function foo() {\n    echo \"this is foo\\n\";\n  }\n  function bar() {\n    echo \"this is bar\\n\";\n  }\n  function __call($name, $args) {\n    echo \"tried to handle unknown method $name\\n\";\n    if ($args)\n      echo \"it had arguments: \", implode(', ', $args), \"\\n\";\n  }\n}\n\n$example = new Example();\n\n$example->foo();        // prints \"this is foo\"\n$example->bar();        // prints \"this is bar\"\n$example->grill();      // prints \"tried to handle unknown method grill\"\n$example->ding(\"dong\"); // prints \"tried to handle unknown method ding\"\n\n?>\n"}
{"id": 59199, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 59200, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 59201, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 59202, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 59203, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 59204, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 59205, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 59206, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 59207, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "PHP": "class Point\n{\n  protected $_x;\n\n  protected $_y;\n  \n  public function __construct()\n  {\n    switch( func_num_args() )\n    {\n      case 1:\n        $point = func_get_arg( 0 );\n        $this->setFromPoint( $point );\n        break;\n      case 2:\n        $x = func_get_arg( 0 );\n        $y = func_get_arg( 1 );\n        $this->setX( $x );\n        $this->setY( $y );\n        break;\n      default:\n        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );\n    }\n  }\n  \n  public function setFromPoint( Point $point )\n  {\n    $this->setX( $point->getX() );\n    $this->setY( $point->getY() );\n  }\n  \n  public function getX()\n  {\n    return $this->_x;\n  }\n  \n  public function setX( $x )\n  {\n    if( !is_numeric( $x ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_x = (float) $x;\n  }\n  \n  public function getY()\n  {\n    return $this->_y;\n  }\n  \n  public function setY( $y )\n  {\n    if( !is_numeric( $y ) )\n    {\n      throw new InvalidArgumentException( 'expecting numeric value' );\n    }\n    \n    $this->_y = (float) $y;\n  }\n  \n  public function output()\n  {\n    echo $this->__toString();\n  }\n  \n  public function __toString()\n  {\n    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';\n  }\n}\n"}
{"id": 59208, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "PHP": "<?php\ndefine('MINEGRID_WIDTH',  6);\ndefine('MINEGRID_HEIGHT', 4);\n\ndefine('MINESWEEPER_NOT_EXPLORED', -1);\ndefine('MINESWEEPER_MINE',         -2);\ndefine('MINESWEEPER_FLAGGED',      -3);\ndefine('MINESWEEPER_FLAGGED_MINE', -4);\ndefine('ACTIVATED_MINE',           -5);\n\nfunction check_field($field) {\n    if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nfunction explore_field($field) {\n    if (!isset($_SESSION['minesweeper'][$field])\n     || !in_array($_SESSION['minesweeper'][$field],\n                  array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {\n        return;\n    }\n\n    $mines = 0;\n\n    $fields  = &$_SESSION['minesweeper'];\n\n\n    if ($field % MINEGRID_WIDTH !== 1) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);\n        $mines += check_field(@$fields[$field - 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);\n    }\n\n    $mines += check_field(@$fields[$field - MINEGRID_WIDTH]);\n    $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);\n\n    if ($field % MINEGRID_WIDTH !== 0) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);\n        $mines += check_field(@$fields[$field + 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);\n    }\n    \n    $fields[$field] = $mines;\n    \n    if ($mines === 0) {\n        if ($field % MINEGRID_WIDTH !== 1) {\n            explore_field($field - MINEGRID_WIDTH - 1);\n            explore_field($field - 1);\n            explore_field($field + MINEGRID_WIDTH - 1);\n        }\n        \n        explore_field($field - MINEGRID_WIDTH);\n        explore_field($field + MINEGRID_WIDTH);\n        \n        if ($field % MINEGRID_WIDTH !== 0) {\n            explore_field($field - MINEGRID_WIDTH + 1);\n            explore_field($field + 1);\n            explore_field($field + MINEGRID_WIDTH + 1);\n        }\n    }\n}\n\nsession_start(); // will start session storage\n\nif (!isset($_SESSION['minesweeper'])) {\n\n    $_SESSION['minesweeper'] = array_fill(1,\n                                         MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                         MINESWEEPER_NOT_EXPLORED);\n\n    $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                     0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);\n\n    $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);\n    \n    foreach ($random_keys as $key) {\n        $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;\n    }\n\n    $_SESSION['numberofmines'] = $number_of_mines;\n}\n\nif (isset($_GET['explore'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['explore']])) {\n        switch ($_SESSION['minesweeper'][$_GET['explore']]) {\n            case MINESWEEPER_NOT_EXPLORED:\n                explore_field($_GET['explore']);\n                break;\n            case MINESWEEPER_MINE:\n                $lost = 1;\n                $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\nelseif (isset($_GET['flag'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['flag']])) {\n        $tile = &$_SESSION['minesweeper'][$_GET['flag']];\n        switch ($tile) {\n            case MINESWEEPER_NOT_EXPLORED:\n                $tile = MINESWEEPER_FLAGGED;\n                break;\n            case MINESWEEPER_MINE:\n                $tile = MINESWEEPER_FLAGGED_MINE;\n                break;\n            case MINESWEEPER_FLAGGED:\n                $tile = MINESWEEPER_NOT_EXPLORED;\n                break;\n            case MINESWEEPER_FLAGGED_MINE:\n                $tile = MINESWEEPER_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\n\nif (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])\n && !in_array(MINESWEEPER_FLAGGED,      $_SESSION['minesweeper'])) {\n    $won = true;\n}\n?>\n<!DOCTYPE html>\n<title>Minesweeper</title>\n<style>\ntable {\n    border-collapse: collapse;\n}\n\ntd, a {\n    text-align:      center;\n    width:           1em;\n    height:          1em;\n}\n\na {\n    display:         block;\n    color:           black;\n    text-decoration: none;\n    font-size:       2em;\n}\n</style>\n<script>\nfunction flag(number, e) {\n    if (e.which === 2 || e.which === 3) {\n        location = '?flag=' + number;\n        return false;\n    }\n}\n</script>\n<?php\n    echo \"<p>This field contains $_SESSION[numberofmines] mines.\";\n?>\n<table border=\"1\">\n<?php\n\n$mine_copy = $_SESSION['minesweeper'];\n\nfor ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {\n    echo '<tr>';\n    for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {\n        echo '<td>';\n        \n        $number = array_shift($mine_copy);\n        switch ($number) {\n            case MINESWEEPER_FLAGGED:\n            case MINESWEEPER_FLAGGED_MINE:\n                if (!empty($lost) || !empty($won)) {\n                    if ($number === MINESWEEPER_FLAGGED_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                else {\n                    echo '<a href=# onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">?</a>';\n                }\n                break;\n            case ACTIVATED_MINE:\n                echo '<a>:(</a>';\n                break;\n            case MINESWEEPER_MINE:\n            case MINESWEEPER_NOT_EXPLORED:\n\n\n\n\n                \n                if (!empty($lost)) {\n                    if ($number === MINESWEEPER_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                elseif (!empty($won)) {\n                    echo '<a>*</a>';\n                }\n                else {\n                    echo '<a href=\"?explore=',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         '\" onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">.</a>';\n                }\n                break;\n            case 0:\n                echo '<a></a>';\n                break;\n            default:\n                echo '<a>', $number, '</a>';\n                break;\n        }\n    }\n}\n?>\n</table>\n<?php\nif (!empty($lost)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>You lost :(. <a href=\"?\">Reboot?</a>';\n}\nelseif (!empty($won)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>Congratulations. You won :).';\n}\n"}
{"id": 59209, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "PHP": "<?php\ndefine('MINEGRID_WIDTH',  6);\ndefine('MINEGRID_HEIGHT', 4);\n\ndefine('MINESWEEPER_NOT_EXPLORED', -1);\ndefine('MINESWEEPER_MINE',         -2);\ndefine('MINESWEEPER_FLAGGED',      -3);\ndefine('MINESWEEPER_FLAGGED_MINE', -4);\ndefine('ACTIVATED_MINE',           -5);\n\nfunction check_field($field) {\n    if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nfunction explore_field($field) {\n    if (!isset($_SESSION['minesweeper'][$field])\n     || !in_array($_SESSION['minesweeper'][$field],\n                  array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {\n        return;\n    }\n\n    $mines = 0;\n\n    $fields  = &$_SESSION['minesweeper'];\n\n\n    if ($field % MINEGRID_WIDTH !== 1) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);\n        $mines += check_field(@$fields[$field - 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);\n    }\n\n    $mines += check_field(@$fields[$field - MINEGRID_WIDTH]);\n    $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);\n\n    if ($field % MINEGRID_WIDTH !== 0) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);\n        $mines += check_field(@$fields[$field + 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);\n    }\n    \n    $fields[$field] = $mines;\n    \n    if ($mines === 0) {\n        if ($field % MINEGRID_WIDTH !== 1) {\n            explore_field($field - MINEGRID_WIDTH - 1);\n            explore_field($field - 1);\n            explore_field($field + MINEGRID_WIDTH - 1);\n        }\n        \n        explore_field($field - MINEGRID_WIDTH);\n        explore_field($field + MINEGRID_WIDTH);\n        \n        if ($field % MINEGRID_WIDTH !== 0) {\n            explore_field($field - MINEGRID_WIDTH + 1);\n            explore_field($field + 1);\n            explore_field($field + MINEGRID_WIDTH + 1);\n        }\n    }\n}\n\nsession_start(); // will start session storage\n\nif (!isset($_SESSION['minesweeper'])) {\n\n    $_SESSION['minesweeper'] = array_fill(1,\n                                         MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                         MINESWEEPER_NOT_EXPLORED);\n\n    $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                     0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);\n\n    $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);\n    \n    foreach ($random_keys as $key) {\n        $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;\n    }\n\n    $_SESSION['numberofmines'] = $number_of_mines;\n}\n\nif (isset($_GET['explore'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['explore']])) {\n        switch ($_SESSION['minesweeper'][$_GET['explore']]) {\n            case MINESWEEPER_NOT_EXPLORED:\n                explore_field($_GET['explore']);\n                break;\n            case MINESWEEPER_MINE:\n                $lost = 1;\n                $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\nelseif (isset($_GET['flag'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['flag']])) {\n        $tile = &$_SESSION['minesweeper'][$_GET['flag']];\n        switch ($tile) {\n            case MINESWEEPER_NOT_EXPLORED:\n                $tile = MINESWEEPER_FLAGGED;\n                break;\n            case MINESWEEPER_MINE:\n                $tile = MINESWEEPER_FLAGGED_MINE;\n                break;\n            case MINESWEEPER_FLAGGED:\n                $tile = MINESWEEPER_NOT_EXPLORED;\n                break;\n            case MINESWEEPER_FLAGGED_MINE:\n                $tile = MINESWEEPER_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\n\nif (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])\n && !in_array(MINESWEEPER_FLAGGED,      $_SESSION['minesweeper'])) {\n    $won = true;\n}\n?>\n<!DOCTYPE html>\n<title>Minesweeper</title>\n<style>\ntable {\n    border-collapse: collapse;\n}\n\ntd, a {\n    text-align:      center;\n    width:           1em;\n    height:          1em;\n}\n\na {\n    display:         block;\n    color:           black;\n    text-decoration: none;\n    font-size:       2em;\n}\n</style>\n<script>\nfunction flag(number, e) {\n    if (e.which === 2 || e.which === 3) {\n        location = '?flag=' + number;\n        return false;\n    }\n}\n</script>\n<?php\n    echo \"<p>This field contains $_SESSION[numberofmines] mines.\";\n?>\n<table border=\"1\">\n<?php\n\n$mine_copy = $_SESSION['minesweeper'];\n\nfor ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {\n    echo '<tr>';\n    for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {\n        echo '<td>';\n        \n        $number = array_shift($mine_copy);\n        switch ($number) {\n            case MINESWEEPER_FLAGGED:\n            case MINESWEEPER_FLAGGED_MINE:\n                if (!empty($lost) || !empty($won)) {\n                    if ($number === MINESWEEPER_FLAGGED_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                else {\n                    echo '<a href=# onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">?</a>';\n                }\n                break;\n            case ACTIVATED_MINE:\n                echo '<a>:(</a>';\n                break;\n            case MINESWEEPER_MINE:\n            case MINESWEEPER_NOT_EXPLORED:\n\n\n\n\n                \n                if (!empty($lost)) {\n                    if ($number === MINESWEEPER_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                elseif (!empty($won)) {\n                    echo '<a>*</a>';\n                }\n                else {\n                    echo '<a href=\"?explore=',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         '\" onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">.</a>';\n                }\n                break;\n            case 0:\n                echo '<a></a>';\n                break;\n            default:\n                echo '<a>', $number, '</a>';\n                break;\n        }\n    }\n}\n?>\n</table>\n<?php\nif (!empty($lost)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>You lost :(. <a href=\"?\">Reboot?</a>';\n}\nelseif (!empty($won)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>Congratulations. You won :).';\n}\n"}
{"id": 59210, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "PHP": "<?php\ndefine('MINEGRID_WIDTH',  6);\ndefine('MINEGRID_HEIGHT', 4);\n\ndefine('MINESWEEPER_NOT_EXPLORED', -1);\ndefine('MINESWEEPER_MINE',         -2);\ndefine('MINESWEEPER_FLAGGED',      -3);\ndefine('MINESWEEPER_FLAGGED_MINE', -4);\ndefine('ACTIVATED_MINE',           -5);\n\nfunction check_field($field) {\n    if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nfunction explore_field($field) {\n    if (!isset($_SESSION['minesweeper'][$field])\n     || !in_array($_SESSION['minesweeper'][$field],\n                  array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {\n        return;\n    }\n\n    $mines = 0;\n\n    $fields  = &$_SESSION['minesweeper'];\n\n\n    if ($field % MINEGRID_WIDTH !== 1) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);\n        $mines += check_field(@$fields[$field - 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);\n    }\n\n    $mines += check_field(@$fields[$field - MINEGRID_WIDTH]);\n    $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);\n\n    if ($field % MINEGRID_WIDTH !== 0) {\n        $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);\n        $mines += check_field(@$fields[$field + 1]);\n        $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);\n    }\n    \n    $fields[$field] = $mines;\n    \n    if ($mines === 0) {\n        if ($field % MINEGRID_WIDTH !== 1) {\n            explore_field($field - MINEGRID_WIDTH - 1);\n            explore_field($field - 1);\n            explore_field($field + MINEGRID_WIDTH - 1);\n        }\n        \n        explore_field($field - MINEGRID_WIDTH);\n        explore_field($field + MINEGRID_WIDTH);\n        \n        if ($field % MINEGRID_WIDTH !== 0) {\n            explore_field($field - MINEGRID_WIDTH + 1);\n            explore_field($field + 1);\n            explore_field($field + MINEGRID_WIDTH + 1);\n        }\n    }\n}\n\nsession_start(); // will start session storage\n\nif (!isset($_SESSION['minesweeper'])) {\n\n    $_SESSION['minesweeper'] = array_fill(1,\n                                         MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                         MINESWEEPER_NOT_EXPLORED);\n\n    $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,\n                                     0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);\n\n    $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);\n    \n    foreach ($random_keys as $key) {\n        $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;\n    }\n\n    $_SESSION['numberofmines'] = $number_of_mines;\n}\n\nif (isset($_GET['explore'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['explore']])) {\n        switch ($_SESSION['minesweeper'][$_GET['explore']]) {\n            case MINESWEEPER_NOT_EXPLORED:\n                explore_field($_GET['explore']);\n                break;\n            case MINESWEEPER_MINE:\n                $lost = 1;\n                $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\nelseif (isset($_GET['flag'])) {\n    if(isset($_SESSION['minesweeper'][$_GET['flag']])) {\n        $tile = &$_SESSION['minesweeper'][$_GET['flag']];\n        switch ($tile) {\n            case MINESWEEPER_NOT_EXPLORED:\n                $tile = MINESWEEPER_FLAGGED;\n                break;\n            case MINESWEEPER_MINE:\n                $tile = MINESWEEPER_FLAGGED_MINE;\n                break;\n            case MINESWEEPER_FLAGGED:\n                $tile = MINESWEEPER_NOT_EXPLORED;\n                break;\n            case MINESWEEPER_FLAGGED_MINE:\n                $tile = MINESWEEPER_MINE;\n                break;\n            default:\n\n                break;\n        }\n    }\n    else {\n        die('Tile doesn\\'t exist.');\n    }\n}\n\nif (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])\n && !in_array(MINESWEEPER_FLAGGED,      $_SESSION['minesweeper'])) {\n    $won = true;\n}\n?>\n<!DOCTYPE html>\n<title>Minesweeper</title>\n<style>\ntable {\n    border-collapse: collapse;\n}\n\ntd, a {\n    text-align:      center;\n    width:           1em;\n    height:          1em;\n}\n\na {\n    display:         block;\n    color:           black;\n    text-decoration: none;\n    font-size:       2em;\n}\n</style>\n<script>\nfunction flag(number, e) {\n    if (e.which === 2 || e.which === 3) {\n        location = '?flag=' + number;\n        return false;\n    }\n}\n</script>\n<?php\n    echo \"<p>This field contains $_SESSION[numberofmines] mines.\";\n?>\n<table border=\"1\">\n<?php\n\n$mine_copy = $_SESSION['minesweeper'];\n\nfor ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {\n    echo '<tr>';\n    for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {\n        echo '<td>';\n        \n        $number = array_shift($mine_copy);\n        switch ($number) {\n            case MINESWEEPER_FLAGGED:\n            case MINESWEEPER_FLAGGED_MINE:\n                if (!empty($lost) || !empty($won)) {\n                    if ($number === MINESWEEPER_FLAGGED_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                else {\n                    echo '<a href=# onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">?</a>';\n                }\n                break;\n            case ACTIVATED_MINE:\n                echo '<a>:(</a>';\n                break;\n            case MINESWEEPER_MINE:\n            case MINESWEEPER_NOT_EXPLORED:\n\n\n\n\n                \n                if (!empty($lost)) {\n                    if ($number === MINESWEEPER_MINE) {\n                        echo '<a>*</a>';\n                    }\n                    else {\n                        echo '<a>.</a>';\n                    }\n                }\n                elseif (!empty($won)) {\n                    echo '<a>*</a>';\n                }\n                else {\n                    echo '<a href=\"?explore=',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         '\" onmousedown=\"return flag(',\n                         ($x - 1) * MINEGRID_WIDTH + $y,\n                         ',event)\" oncontextmenu=\"return false\">.</a>';\n                }\n                break;\n            case 0:\n                echo '<a></a>';\n                break;\n            default:\n                echo '<a>', $number, '</a>';\n                break;\n        }\n    }\n}\n?>\n</table>\n<?php\nif (!empty($lost)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>You lost :(. <a href=\"?\">Reboot?</a>';\n}\nelseif (!empty($won)) {\n    unset($_SESSION['minesweeper']);\n    echo '<p>Congratulations. You won :).';\n}\n"}
{"id": 59211, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 59212, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 59213, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 59214, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 59215, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 59216, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 59217, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59218, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59219, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59220, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59221, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59222, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59223, "name": "Dynamic variable names", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 59224, "name": "Dynamic variable names", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 59225, "name": "Dynamic variable names", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n", "PHP": "<?php\n$varname = rtrim(fgets(STDIN)); # type in \"foo\" on standard input\n$$varname = 42;\necho \"$foo\\n\"; # prints \"42\"\n?>\n"}
{"id": 59226, "name": "Reflection_List methods", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 59227, "name": "Reflection_List methods", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 59228, "name": "Reflection_List methods", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n", "PHP": "<?\nclass Foo {\n    function bar(int $x) {\n    }\n}\n\n$method_names = get_class_methods('Foo');\nforeach ($method_names as $name) {\n    echo \"$name\\n\";\n    $method_info = new ReflectionMethod('Foo', $name);\n    echo $method_info;\n}\n?>\n"}
{"id": 59229, "name": "Comments", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n", "PHP": "# this is commented\n\n"}
{"id": 59230, "name": "Comments", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n", "PHP": "# this is commented\n\n"}
{"id": 59231, "name": "Comments", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n", "PHP": "# this is commented\n\n"}
{"id": 59232, "name": "Send an unknown method call", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 59233, "name": "Send an unknown method call", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 59234, "name": "Send an unknown method call", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n", "PHP": "<?php\nclass Example {\n  function foo($x) {\n    return 42 + $x;\n  }\n}\n\n$example = new Example();\n\n$name = 'foo';\necho $example->$name(5), \"\\n\";        // prints \"47\"\n\necho call_user_func(array($example, $name), 5), \"\\n\";\n?>\n"}
{"id": 59235, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 59236, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 59237, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 59238, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 59239, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 59240, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 59241, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 59242, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 59243, "name": "Runtime evaluation_In an environment", "Python": ">>> def eval_with_x(code, a, b):\n\treturn eval(code, {'x':b}) - eval(code, {'x':a})\n\n>>> eval_with_x('2 ** x', 3, 5)\n24\n", "PHP": "<?php\nfunction eval_with_x($code, $a, $b) {\n    $x = $a;\n    $first = eval($code);\n    $x = $b;\n    $second = eval($code);\n    return $second - $first;\n}\n \necho eval_with_x('return 3 * $x;', 5, 10), \"\\n\"; # Prints \"15\".\n?>\n"}
{"id": 59244, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59245, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59246, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59247, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59248, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59249, "name": "Runtime evaluation", "Python": ">>> exec \n10\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59250, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 59251, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 59252, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 59253, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 59254, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 59255, "name": "Permutations with repetitions", "Python": "\n\nfrom itertools import product\n\n\n\ndef replicateM(n):\n    \n    def rep(m):\n        def go(x):\n            return [[]] if 1 > x else (\n                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))\n            )\n        return go(n)\n    return lambda m: rep(m)\n\n\n\n\ndef main():\n    \n    print(\n        fTable(main.__doc__ + ':\\n')(repr)(showList)(\n\n            replicateM(2)\n\n        )([[1, 2, 3], 'abc'])\n    )\n\n\n\n\n\ndef liftA2List(f):\n    \n    return lambda xs: lambda ys: [\n        f(*xy) for xy in product(xs, ys)\n    ]\n\n\n\n\n\n\ndef fTable(s):\n    \n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(\n        showList(x) if isinstance(x, list) else repr(x) for x in xs\n    ) + ']'\n\n\n\nif __name__ == '__main__':\n    main()\n", "PHP": "<?php\nfunction permutate($values, $size, $offset) {\n    $count = count($values);\n    $array = array();\n    for ($i = 0; $i < $size; $i++) {\n        $selector = ($offset / pow($count,$i)) % $count;\n        $array[$i] = $values[$selector];\n    }\n    return $array;\n}\n\nfunction permutations($values, $size) {\n    $a = array();\n    $c = pow(count($values), $size);\n    for ($i = 0; $i<$c; $i++) {\n        $a[$i] = permutate($values, $size, $i);        \n    }\n    return $a;\n}\n\n$permutations = permutations(['bat','fox','cow'], 2);\nforeach ($permutations as $permutation) {\n    echo join(',', $permutation).\"\\n\";\n}\n"}
{"id": 59256, "name": "OpenWebNet password", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n"}
{"id": 59257, "name": "OpenWebNet password", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n"}
{"id": 59258, "name": "OpenWebNet password", "Python": "def ownCalcPass (password, nonce, test=False) :\n    start = True    \n    num1 = 0\n    num2 = 0\n    password = int(password)\n    if test:\n        print(\"password: %08x\" % (password))\n    for c in nonce :\n        if c != \"0\":\n            if start:\n                num2 = password\n            start = False\n        if test:\n            print(\"c: %s num1: %08x num2: %08x\" % (c, num1, num2))\n        if c == '1':\n            num1 = (num2 & 0xFFFFFF80) >> 7\n            num2 = num2 << 25\n        elif c == '2':\n            num1 = (num2 & 0xFFFFFFF0) >> 4\n            num2 = num2 << 28\n        elif c == '3':\n            num1 = (num2 & 0xFFFFFFF8) >> 3\n            num2 = num2 << 29\n        elif c == '4':\n            num1 = num2 << 1\n            num2 = num2 >> 31\n        elif c == '5':\n            num1 = num2 << 5\n            num2 = num2 >> 27\n        elif c == '6':\n            num1 = num2 << 12\n            num2 = num2 >> 20\n        elif c == '7':\n            num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )\n            num2 = ( num2 & 0xFF000000 ) >> 8\n        elif c == '8':\n            num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )\n            num2 = (num2 & 0x00FF0000) >> 8\n        elif c == '9':\n            num1 = ~num2\n        else :\n            num1 = num2\n\n        num1 &= 0xFFFFFFFF\n        num2 &= 0xFFFFFFFF\n        if (c not in \"09\"):\n            num1 |= num2\n        if test:\n            print(\"     num1: %08x num2: %08x\" % (num1, num2))\n        num2 = num1\n    return num1\n\ndef test_passwd_calc(passwd, nonce, expected):\n    res = ownCalcPass(passwd, nonce, False)\n    m = passwd+' '+nonce+' '+str(res)+' '+str(expected)\n    if res == int(expected) :\n        print('PASS '+m)\n    else :\n        print('FAIL '+m)\n\nif __name__ == '__main__':\n    test_passwd_calc('12345','603356072','25280520')\n    test_passwd_calc('12345','410501656','119537670')\n    test_passwd_calc('12345','630292165','4269684735')\n", "PHP": "function ownCalcPass($password, $nonce) {\n    $msr = 0x7FFFFFFF;\n    $m_1 = (int)0xFFFFFFFF;\n    $m_8 = (int)0xFFFFFFF8;\n    $m_16 = (int)0xFFFFFFF0;\n    $m_128 = (int)0xFFFFFF80;\n    $m_16777216 = (int)0xFF000000;\n    $flag = True;\n    $num1 = 0;\n    $num2 = 0;\n\n    foreach (str_split($nonce) as $c) {\n        $num1 = $num1 & $m_1;\n        $num2 = $num2 & $m_1;\n        if ($c == '1') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_128;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 6;\n            $num2 = $num2 << 25;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '2') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_16;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 3;\n            $num2 = $num2 << 28;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '3') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & $m_8;\n            $num1 = $num1 >> 1;\n            $num1 = $num1 & $msr;\n            $num1 = $num1 >> 2;\n            $num2 = $num2 << 29;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '4') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 1;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 30;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '5') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 5;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 26;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '6') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 << 12;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 19;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '7') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFF00;\n            $num1 = $num1 + (( $num2 & 0xFF ) << 24 );\n            $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );\n            $num2 = $num2 & $m_16777216;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '8') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = $num2 & 0xFFFF;\n            $num1 = $num1 << 16;\n            $numx = $num2 >> 1;\n            $numx = $numx & $msr;\n            $numx = $numx >> 23;\n            $num1 = $num1 + $numx;\n            $num2 = $num2 & 0xFF0000;\n            $num2 = $num2 >> 1;\n            $num2 = $num2 & $msr;\n            $num2 = $num2 >> 7;\n            $num1 = $num1 + $num2;\n            $flag = False;\n        } elseif ($c == '9') {\n            $length = !$flag;\n            if (!$length) {\n                $num2 = $password;\n            }\n            $num1 = ~(int)$num2;\n            $flag = False;\n        } else {\n            $num1 = $num2;\n        }\n        $num2 = $num1;\n    }\n    return sprintf('%u', $num1 & $m_1);\n}\n"}
{"id": 59259, "name": "Monads_Writer monad", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n"}
{"id": 59260, "name": "Monads_Writer monad", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n"}
{"id": 59261, "name": "Monads_Writer monad", "Python": "\nfrom __future__ import annotations\n\nimport functools\nimport math\nimport os\n\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import List\nfrom typing import TypeVar\nfrom typing import Union\n\n\nT = TypeVar(\"T\")\n\n\nclass Writer(Generic[T]):\n    def __init__(self, value: Union[T, Writer[T]], *msgs: str):\n        if isinstance(value, Writer):\n            self.value: T = value.value\n            self.msgs: List[str] = value.msgs + list(msgs)\n        else:\n            self.value = value\n            self.msgs = list(f\"{msg}: {self.value}\" for msg in msgs)\n\n    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        writer = func(self.value)\n        return Writer(writer, *self.msgs)\n\n    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:\n        return self.bind(func)\n\n    def __str__(self):\n        return f\"{self.value}\\n{os.linesep.join(reversed(self.msgs))}\"\n\n    def __repr__(self):\n        return f\"Writer({self.value}, \\\"{', '.join(reversed(self.msgs))}\\\")\"\n\n\ndef lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:\n    \n\n    @functools.wraps(func)\n    def wrapped(value):\n        return Writer(func(value), msg)\n\n    return wrapped\n\n\nif __name__ == \"__main__\":\n    square_root = lift(math.sqrt, \"square root\")\n    add_one = lift(lambda x: x + 1, \"add one\")\n    half = lift(lambda x: x / 2, \"div two\")\n\n    print(Writer(5, \"initial\") >> square_root >> add_one >> half)\n", "PHP": "class WriterMonad {\n\n\t\n\tprivate $value;\n\t\n\tprivate $logs;\n\n\tprivate function __construct($value, array $logs = []) {\n\t\t$this->value = $value;\n\t\t$this->logs = $logs;\n\t}\n\n\tpublic static function unit($value, string $log): WriterMonad {\n\t\treturn new WriterMonad($value, [\"{$log}: {$value}\"]);\n\t}\n\n\tpublic function bind(callable $mapper): WriterMonad  {\n\t\t$mapped = $mapper($this->value);\n\t\tassert($mapped instanceof WriterMonad);\n\t\treturn new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);\n\t}\n\n\tpublic function value() {\n\t\treturn $this->value;\n\t}\n\n\tpublic function logs(): array {\n\t\treturn $this->logs;\n\t}\n}\n\n$root = fn(float $i): float => sqrt($i);\n$addOne = fn(float $i): float => $i + 1;\n$half = fn(float $i): float => $i / 2;\n\n$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);\n\n$result = WriterMonad::unit(5, \"Initial value\")\n\t->bind($m($root, \"square root\"))\n\t->bind($m($addOne, \"add one\"))\n\t->bind($m($half, \"half\"));\n\nprint \"The Golden Ratio is: {$result->value()}\\n\";\nprint join(\"\\n\", $result->logs());\n"}
{"id": 59262, "name": "Canny edge detector", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n"}
{"id": 59263, "name": "Canny edge detector", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n"}
{"id": 59264, "name": "Canny edge detector", "Python": "\nimport numpy as np\nfrom scipy.ndimage.filters import convolve, gaussian_filter\nfrom scipy.misc import imread, imshow\n\t\ndef CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):\n\tim = np.array(im, dtype=float) \n \n\t\n\tim2 = gaussian_filter(im, blur)\n\n\t\n\tim3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) \n\tim3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])\n\n\t\n\tgrad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)\n\ttheta = np.arctan2(im3v, im3h)\n\tthetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 \n\n\t\n\tgradSup = grad.copy()\n\tfor r in range(im.shape[0]):\n\t\tfor c in range(im.shape[1]):\n\t\t\t\n\t\t\tif r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:\n\t\t\t\tgradSup[r, c] = 0\n\t\t\t\tcontinue\n\t\t\ttq = thetaQ[r, c] % 4\n\n\t\t\tif tq == 0: \n\t\t\t\tif grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 1: \n\t\t\t\tif grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 2: \n\t\t\t\tif grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:\n\t\t\t\t\tgradSup[r, c] = 0\n\t\t\tif tq == 3: \n\t\t\t\tif grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:\n\t\t\t\t\tgradSup[r, c] = 0\n\n\t\n\tstrongEdges = (gradSup > highThreshold)\n\n\t\n\tthresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)\n\n\t\n\t\n\tfinalEdges = strongEdges.copy()\n\tcurrentPixels = []\n\tfor r in range(1, im.shape[0]-1):\n\t\tfor c in range(1, im.shape[1]-1):\t\n\t\t\tif thresholdedEdges[r, c] != 1:\n\t\t\t\tcontinue \n\t\t\t\n\t\t\t\n\t\t\tlocalPatch = thresholdedEdges[r-1:r+2,c-1:c+2]\n\t\t\tpatchMax = localPatch.max()\n\t\t\tif patchMax == 2:\n\t\t\t\tcurrentPixels.append((r, c))\n\t\t\t\tfinalEdges[r, c] = 1\n\n\t\n\twhile len(currentPixels) > 0:\n\t\tnewPix = []\n\t\tfor r, c in currentPixels:\n\t\t\tfor dr in range(-1, 2):\n\t\t\t\tfor dc in range(-1, 2):\n\t\t\t\t\tif dr == 0 and dc == 0: continue\n\t\t\t\t\tr2 = r+dr\n\t\t\t\t\tc2 = c+dc\n\t\t\t\t\tif thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\tnewPix.append((r2, c2))\n\t\t\t\t\t\tfinalEdges[r2, c2] = 1\n\t\tcurrentPixels = newPix\n\n\treturn finalEdges\n\nif __name__==\"__main__\":\n\tim = imread(\"test.jpg\", mode=\"L\") \n\tfinalEdges = CannyEdgeDetector(im)\n\timshow(finalEdges)\n", "PHP": "\nfunction RGBtoHSV($r, $g, $b) {\n\t$r = $r/255.; // convert to range 0..1\n\t$g = $g/255.;\n\t$b = $b/255.;\n\t$cols = array(\"r\" => $r, \"g\" => $g, \"b\" => $b);\n\tasort($cols, SORT_NUMERIC);\n\t$min = key(array_slice($cols, 1)); // \"r\", \"g\" or \"b\"\n\t$max = key(array_slice($cols, -1)); // \"r\", \"g\" or \"b\"\n\n\tif($cols[$min] == $cols[$max]) {\n\t\t$h = 0;\n\t} else {\n\t\tif($max == \"r\") {\n\t\t\t$h = 60. * ( 0 + ( ($cols[\"g\"]-$cols[\"b\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"g\") {\n\t\t\t$h = 60. * ( 2 + ( ($cols[\"b\"]-$cols[\"r\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t} elseif ($max == \"b\") {\n\t\t\t$h = 60. * ( 4 + ( ($cols[\"r\"]-$cols[\"g\"]) / ($cols[$max]-$cols[$min]) ) );\n\t\t}\n\t\tif($h < 0) {\n\t\t\t$h += 360;\n\t\t}\n\t}\n\n\tif($cols[$max] == 0) {\n\t\t$s = 0;\n\t} else {\n\t\t$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );\n\t\t$s = $s * 255;\n\t}\n\n\t$v = $cols[$max];\n\t$v = $v * 255;\n\n\treturn(array($h, $s, $v));\n}\n\n$filename = \"image.png\";\n$dimensions = getimagesize($filename);\n$w = $dimensions[0]; // width\n$h = $dimensions[1]; // height\n\n$im = imagecreatefrompng($filename);\n\nfor($hi=0; $hi < $h; $hi++) {\n\n\tfor($wi=0; $wi < $w; $wi++) {\n\t\t$rgb = imagecolorat($im, $wi, $hi);\n\n\t\t$r = ($rgb >> 16) & 0xFF;\n\t\t$g = ($rgb >> 8) & 0xFF;\n\t\t$b = $rgb & 0xFF;\n\t\t$hsv = RGBtoHSV($r, $g, $b);\n\n\t\t$brgb = imagecolorat($im, $wi, $hi+1);\n\t\t$br = ($brgb >> 16) & 0xFF;\n\t\t$bg = ($brgb >> 8) & 0xFF;\n\t\t$bb = $brgb & 0xFF;\n\t\t$bhsv = RGBtoHSV($br, $bg, $bb);\n\n\t\tif($hsv[2]-$bhsv[2] > 20) { \n                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));\n\t\t} \n                else {\n\t\t    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));\n\t\t}\n\t\t\t\n        }\n        \n}\n\nheader('Content-Type: image/jpeg');\nimagepng($im);\nimagedestroy($im);\n"}
{"id": 59265, "name": "Add a variable to a class instance at runtime", "Python": "class empty(object):\n    pass\ne = empty()\n", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n"}
{"id": 59266, "name": "Add a variable to a class instance at runtime", "Python": "class empty(object):\n    pass\ne = empty()\n", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n"}
{"id": 59267, "name": "Add a variable to a class instance at runtime", "Python": "class empty(object):\n    pass\ne = empty()\n", "PHP": "class E {};\n\n$e=new E();\n\n$e->foo=1;\n\n$e->{\"foo\"} = 1; // using a runtime name\n$x = \"foo\";\n$e->$x = 1; // using a runtime name in a variable\n"}
{"id": 59268, "name": "Periodic table", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n"}
{"id": 59269, "name": "Periodic table", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n"}
{"id": 59270, "name": "Periodic table", "Python": "def perta(atomic) -> (int, int):\n\n    NOBLES = 2, 10, 18, 36, 54, 86, 118\n    INTERTWINED = 0, 0, 0, 0, 0, 57, 89\n    INTERTWINING_SIZE = 14\n    LINE_WIDTH = 18\n\n    prev_noble = 0\n    for row, noble in enumerate(NOBLES):\n        if atomic <= noble:  \n            nb_elem = noble - prev_noble  \n            rank =  atomic - prev_noble  \n            if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:  \n                row += 2\n                col = rank + 1\n            else:  \n                \n                nb_empty = LINE_WIDTH - nb_elem  \n                inside_left_element_rank = 2 if noble > 2 else 1\n                col = rank + (nb_empty if rank > inside_left_element_rank else 0)\n            break\n        prev_noble = noble\n    return row+1, col\n\n\n\n\n\nTESTS = {\n    1: (1, 1),\n    2: (1, 18),\n    29: (4,11),\n    42: (5, 6),\n    58: (8, 5),\n    59: (8, 6),\n    57: (8, 4),\n    71: (8, 18),\n    72: (6, 4),\n    89: (9, 4),\n    90: (9, 5),\n    103: (9, 18),\n}\n\nfor input, out in TESTS.items():\n    found = perta(input)\n    print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))\n", "PHP": "<?php\n\n\nclass PeriodicTable\n{\n    private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);\n    \n    private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);\n    \n    public function rowAndColumn($n)\n    {\n        $i = 7;\n        while ($this->aArray[$i] > $n)\n            $i--;\n        $m = $n + $this->bArray[$i];\n        return array(floor($m / 18) + 1, $m % 18 + 1);\n    }\n}\n\n$pt = new PeriodicTable();\n\nforeach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {\n    list($r, $c) = $pt->rowAndColumn($n);\n    echo $n, \" -> \", $r, \" \", $c, PHP_EOL;\n} \n?>\n"}
{"id": 59271, "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", "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": 59272, "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", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 59273, "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", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 59274, "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", "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": 59275, "name": "Count occurrences of a substring", "VB": "Public Sub Main() \n  \n  Print countSubstring(\"the three truths\", \"th\") \n  Print countSubstring(\"ababababab\", \"abab\") \n  Print countSubString(\"zzzzzzzzzzzzzzz\", \"z\")\n\nEnd \n\nFunction countSubstring(s As String, search As String) As Integer \n\n  If s = \"\" Or search = \"\" Then Return 0 \n  Dim count As Integer = 0, length As Integer = Len(search) \n  For i As Integer = 1 To Len(s) \n    If Mid(s, i, length) = Search Then \n      count += 1 \n      i += length - 1 \n    End If \n  Next \n  Return count \n\nEnd Function\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": 59276, "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", "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": 59277, "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", "PHP": "<?php\n\n\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '/' . implode('/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \n\n$dirs = array(\n '/home/user1/tmp/coverage/test',\n '/home/user1/tmp/covert/operator',\n '/home/user1/tmp/coven/members',\n);\n\n\nif('/home/user1/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n"}
{"id": 59278, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 59279, "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", "PHP": "<?php\n$a = array();\narray_push($a, 0);\n\n$used = array();\narray_push($used, 0);\n\n$used1000 = array();\narray_push($used1000, 0);\n\n$foundDup = false;\n$n = 1;\n\nwhile($n <= 15 || !$foundDup || count($used1000) < 1001) {\n\t$next = $a[$n - 1] - $n;\n\tif ($next < 1 || in_array($next, $used)) {\n\t\t$next += 2 * $n;\n\t}\n\t$alreadyUsed = in_array($next, $used);\n\tarray_push($a, $next);\n\tif (!$alreadyUsed) {\n\t\tarray_push($used, $next);\n\t\tif (0 <= $next && $next <= 1000) {\n\t\t\tarray_push($used1000, $next);\n\t\t}\n\t}\n\tif ($n == 14) {\n\t\techo \"The first 15 terms of the Recaman sequence are : [\";\n\t\tforeach($a as $i => $v) {\n\t\t\tif ( $i == count($a) - 1)\n\t\t\t\techo \"$v\";\n\t\t\telse\n\t\t\t\techo \"$v, \";\n\t\t}\n\t\techo \"]\\n\";\n\t}\n\tif (!$foundDup && $alreadyUsed) {\n\t\tprintf(\"The first duplicate term is a[%d] = %d\\n\", $n, $next);\n\t\t$foundDup = true;\n\t}\n\tif (count($used1000) == 1001) {\n\t\tprintf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", $n);\n\t}\n\t$n++;\n}\n"}
{"id": 59280, "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", "PHP": "<?php\nconst BOARD_NUM = 9;\nconst ROW_NUM = 3;\n$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);\n\nfunction isGameOver($board, $pin) {\n\t$pat = \n\t\t'/X{3}|' . //Horz\n\t\t'X..X..X..|' . //Vert Left\n\t\t'.X..X..X.|' . //Vert Middle\n\t\t'..X..X..X|' . //Vert Right\n\t\t'..X.X.X..|' . //Diag TL->BR\n\t\t'X...X...X|' . //Diag TR->BL\n\t\t'[^\\.]{9}/i'; //Cat's game\n\tif ($pin == 'O') $pat = str_replace('X', 'O', $pat);\n\treturn preg_match($pat, $board);\n}\n\n$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;\n$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';\n$oppTurn = $turn == 'X'? 'O' : 'X';\n$gameOver = isGameOver($boardStr, $oppTurn);\n\necho '<style>';\necho 'td {width: 200px; height: 200px; text-align: center; }';\necho '.pin {font-size:72pt; text-decoration:none; color: black}';\necho '.pin.X {color:red}';\necho '.pin.O {color:blue}';\necho '</style>';\necho '<table border=\"1\">';\n$p = 0;\nfor ($r = 0; $r < ROW_NUM; $r++) {\n\techo '<tr>';\n\tfor ($c = 0; $c < ROW_NUM; $c++) {\n\t\t$pin = $boardStr[$p];\n\t\t\n\t\techo '<td>';\t\t\n\t\tif ($gameOver || $pin != '.') echo '<span class=\"pin ', $pin, '\">', $pin, '</span>'; //Occupied\n\t\telse { //Available\n\t\t\t$boardDelta = $boardStr;\n\t\t\t$boardDelta[$p] = $turn;\t\t\n\t\t\techo '<a class=\"pin ', $pin, '\" href=\"?b=', $boardDelta, '\">';\n\t\t\techo $boardStr[$p];\n\t\t\techo '</a>';\n\t\t}\n\t\t\n\t\techo '</td>';\t\n\t\t$p++;\n\t}\n\techo '</tr>';\n\techo '<input type=\"hidden\" name=\"b\" value=\"', $boardStr, '\"/>';\n}\necho '</table>';\necho '<a href=\"?b=', $EMPTY_BOARD_STR, '\">Reset</a>';\nif ($gameOver) echo '<h1>Game Over!</h1>';\n"}
{"id": 59281, "name": "DNS query", "VB": "#include \"win\\winsock2.bi\"\n\nFunction GetSiteAddress(stuff As String = \"www.freebasic.net\") As Long\n    Dim As WSADATA _wsadate\n    Dim As in_addr addr\n    Dim As hostent Ptr res\n    Dim As Integer i = 0\n    \n    WSAStartup(MAKEWORD(2,2),@_wsadate)\n    res = gethostbyname(stuff)\n    \n    If res Then\n        Print !\"\\nURL: \"; stuff\n        While (res->h_addr_list[i] <> 0)\n            addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i]))\n            Print \"IPv4 address: \";*inet_ntoa(addr)\n            i+=1\n        Wend\n        WSACleanup()\n        Return 1\n    Else\n        Print \"website error?\"\n        Return 0\n    End If\nEnd Function\n\nGetSiteAddress \"rosettacode.org\"\nGetSiteAddress \"www.kame.net\"\n\nSleep\n", "PHP": "<?php\n  $ipv4_record = dns_get_record(\"www.kame.net\",DNS_A);\n  $ipv6_record = dns_get_record(\"www.kame.net\",DNS_AAAA);\n  print \"ipv4: \" . $ipv4_record[0][\"ip\"] . \"\\n\";\n  print \"ipv6: \" . $ipv6_record[0][\"ipv6\"] . \"\\n\";\n?>\n"}
{"id": 59282, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\n", "PHP": "<?php\nfunction Y($f) {\n  $g = function($w) use($f) {\n    return $f(function() use($w) {\n      return call_user_func_array($w($w), func_get_args());\n    });\n  };\n  return $g($g);\n}\n\n$fibonacci = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };\n});\n\necho $fibonacci(10), \"\\n\";\n\n$factorial = Y(function($f) {\n  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };\n});\n\necho $factorial(10), \"\\n\";\n?>\n"}
{"id": 59283, "name": "Return multiple values", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\n", "PHP": "function addsub($x, $y) {\n  return array($x + $y, $x - $y);\n}\n"}
{"id": 59284, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 59285, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\n", "PHP": "#!/usr/bin/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and / operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n"}
{"id": 59286, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\n", "PHP": "for ($i = 1; $i <= 10; $i++) {\n    echo $i;\n    if ($i % 5 == 0) {\n        echo \"\\n\";\n        continue;\n    }\n    echo ', ';\n}\n"}
{"id": 59287, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\n", "PHP": "<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n"}
{"id": 59288, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 59289, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "PHP": "<?php  \n  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];\n  \n  function fileLine ($lineNum, $file) {\n    $count = 0;\n    while (!feof($file)) {\n      $count++;\n      $line = fgets($file);\n      if ($count == $lineNum) return $line;\n    }\n    die(\"Requested file has fewer than \".$lineNum.\" lines!\");\n  }\n    \n  @ $fp = fopen(\"$DOCROOT/exercises/words.txt\", 'r');\n  if (!$fp) die(\"Input file not found!\");\n  echo fileLine(7, $fp);\n?>\n"}
{"id": 59290, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n", "PHP": "$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; // ALPHABETA\necho strtolower($str), \"\\n\"; // alphabeta\n\necho ucfirst($str), \"\\n\"; // AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; // fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; // FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; // fOo bAr bAz\n"}
{"id": 59291, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n", "PHP": "$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n"}
{"id": 59292, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n", "PHP": "<?php\n\n$buffer = 1;\n$pids = [];\n\nfor ($i = 1; $i < $argc; $i++) {\n    $pid = pcntl_fork();\n    if ($pid < 0) {\n        die(\"failed to start child process\");\n    }\n\n    if ($pid === 0) {\n        sleep($argv[$i] + $buffer);\n        echo $argv[$i] . \"\\n\";\n        exit();\n    }\n    \n    $pids[] = $pid;\n}\n\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n}\n"}
{"id": 59293, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "PHP": "<?php\nfor ($i = 0; $i < 10; $i++)\n    for ($j = 0; $j < 10; $j++)\n        $a[$i][$j] = rand(1, 20);\n\nforeach ($a as $row) {\n    foreach ($row as $element) {\n        echo \" $element\";\n        if ($element == 20)\n            break 2; // 2 is the number of loops we want to break out of\n    }\n    echo \"\\n\";\n}\necho \"\\n\";\n?>\n"}
{"id": 59294, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 59295, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "PHP": "<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p / 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n"}
{"id": 59296, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "PHP": "$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n"}
{"id": 59297, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n", "PHP": "<?php\n\nfunction lookAndSay($str) {\n\n\treturn preg_replace_callback('#(.)\\1*#', function($matches) {\n\t\n\t\treturn strlen($matches[0]).$matches[1];\n\t}, $str);\n}\n\n$num = \"1\";\n\nforeach(range(1,10) as $i) {\n\n\techo $num.\"<br/>\";\n\t$num = lookAndSay($num);\n}\n\n?>\n"}
{"id": 59298, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "PHP": "$stack = array();\n\nempty( $stack ); // true\n\narray_push( $stack, 1 ); // or $stack[] = 1;\narray_push( $stack, 2 ); // or $stack[] = 2;\n\nempty( $stack ); // false\n\necho array_pop( $stack ); // outputs \"2\"\necho array_pop( $stack ); // outputs \"1\"\n"}
{"id": 59299, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "PHP": "<?php\n\n$foo = 3;\n\nif ($foo == 2)\n\n\nif ($foo == 3)\n\nelse\n\n\nif ($foo != 0)\n{\n\n}\nelse\n{\n\n}\n\n?>\n"}
{"id": 59300, "name": "Read a configuration file", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n", "PHP": "<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);\n\n\n\n\n\n$conf = preg_replace_callback(\n    '/^([a-z]+)\\s*=((?=.*\\,.*).*)$/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n$conf = preg_replace('/^([a-z]+)\\s*=$/mi', '$1 = true', $conf);\n\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n"}
{"id": 59301, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n", "PHP": "<?php\nfunction mycmp($s1, $s2)\n{\n    if ($d = strlen($s2) - strlen($s1))\n        return $d;\n    return strcasecmp($s1, $s2);\n}\n\n$strings = array(\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\");\nusort($strings, \"mycmp\");\n?>\n"}
{"id": 59302, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n", "PHP": "function selection_sort(&$arr) {\n    $n = count($arr);\n    for($i = 0; $i < count($arr); $i++) {\n        $min = $i;\n        for($j = $i + 1; $j < $n; $j++){\n            if($arr[$j] < $arr[$min]){\n                $min = $j;\n            }\n        }\n        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);\n    }\n}\n"}
{"id": 59303, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n", "PHP": "function cube($n)\n{\n   return($n * $n * $n);\n}\n\n$a = array(1, 2, 3, 4, 5);\n$b = array_map(\"cube\", $a);\nprint_r($b);\n"}
{"id": 59304, "name": "Case-sensitivity of identifiers", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n", "PHP": "<?php\n\n\n\n$dog = 'Benjamin';\n$Dog = 'Samba';\n$DOG = 'Bernie';\n\necho \"There are 3 dogs named {$dog}, {$Dog} and {$DOG}\\n\";\n\n\nfunction DOG() { return 'Bernie'; }\n\necho 'There is only 1 dog named ' . dog() . \"\\n\";\n"}
{"id": 59305, "name": "Loops_Downward for", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n", "PHP": "for ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n"}
{"id": 59306, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "PHP": "file_put_contents($filename, $data)\n"}
{"id": 59307, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "PHP": "for ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n"}
{"id": 59308, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "PHP": "<?php\nfunction longMult($a, $b)\n{\n  $as = (string) $a;\n  $bs = (string) $b;\n  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)\n    {\n      for($p = 0; $p < $pi; $p++)\n        {\n          $regi[$ai][] = 0;\n        }\n      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)\n        {\n          $regi[$ai][] = $as[$ai] * $bs[$bi];\n        }\n    }\n  return $regi;\n}\n\nfunction longAdd($arr)\n{\n  $outer = count($arr);\n  $inner = count($arr[$outer-1]) + $outer;\n  for($i = 0; $i <= $inner; $i++)\n    {\n      for($o = 0; $o < $outer; $o++)\n        {\n          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;\n          @$sum[$i] += $val;\n        }\n    }\n  return $sum;\n}\n\nfunction carry($arr)\n{\n  for($i = 0; $i < count($arr); $i++)\n    {\n      $s = (string) $arr[$i];\n      switch(strlen($s))\n        {\n          case 2:\n            $arr[$i] = $s{1};\n            @$arr[$i+1] += $s{0};\n            break;\n          case 3:\n            $arr[$i] = $s{2};\n            @$arr[$i+1] += $s{0}.$s{1};\n            break;\n        }\n    }\n  return ltrim(implode('',array_reverse($arr)),'0');\n}\n\nfunction lm($a,$b)\n{\n  return carry(longAdd(longMult($a,$b)));\n}\n\nif(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')\n  {\n    echo 'pass!';\n  }; // 2^64 * 2^64\n"}
{"id": 59309, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n", "PHP": "<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"/^[1-9]{{$size}}$/\", $g);\n}\n?>\n"}
{"id": 59310, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n", "PHP": "function bubbleSort(array $array){\n    foreach($array as $i => &$val){\n        foreach($array as $k => &$val2){\n            if($k <= $i)\n                continue;\n            if($val > $val2) {\n                list($val, $val2) = [$val2, $val];\n                break;\n            }\n        }\n    }\n    return $array;\n}\n"}
{"id": 59311, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "PHP": "<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\n"}
{"id": 59312, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n", "PHP": "<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a / $b), \"\\n\",\n    \"flooring quotient:   \", floor($a / $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; // PHP 5.6+ only\n?>\n"}
{"id": 59313, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n", "PHP": "function transpose($m) {\n  if (count($m) == 0) // special case: empty matrix\n    return array();\n  else if (count($m) == 1) // special case: row matrix\n    return array_chunk($m[0], 1);\n\n  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value\n  return call_user_func_array('array_map', $m);\n}\n"}
{"id": 59314, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59315, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "PHP": "<?php\nfunction a() {\n    static $i = 0;\n    print ++$i . \"\\n\";\n    a();\n}\na();\n"}
{"id": 59316, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "PHP": "function is_perfect($number)\n{\n    $sum = 0;\n    for($i = 1; $i < $number; $i++)\n    {\n        if($number % $i == 0)\n            $sum += $i;\n    }\n    return $sum == $number;\n}\n\necho \"Perfect numbers from 1 to 33550337:\" . PHP_EOL;\nfor($num = 1; $num < 33550337; $num++)\n{\n    if(is_perfect($num))\n        echo $num . PHP_EOL;\n}\n"}
{"id": 59317, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "PHP": "<?php\nfunction columns($arr) {\n    if (count($arr) == 0)\n        return array();\n    else if (count($arr) == 1)\n        return array_chunk($arr[0], 1);\n\n    array_unshift($arr, NULL);\n\n    $transpose = call_user_func_array('array_map', $arr);\n    return array_map('array_filter', $transpose);\n}\n\nfunction beadsort($arr) {\n    foreach ($arr as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n\nprint_r(beadsort(array(5,3,1,7,4,1,1)));\n?>\n"}
{"id": 59318, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "PHP": "<?php\n$y = bcpow('5', bcpow('4', bcpow('3', '2')));\nprintf(\"5**4**3**2 = %s...%s and has %d digits\\n\", substr($y,0,20), substr($y,-20), strlen($y));\n?>\n"}
{"id": 59319, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59320, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "PHP": "echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) / gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n"}
{"id": 59321, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "PHP": "while (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n"}
{"id": 59322, "name": "Trabb Pardo–Knuth algorithm", "VB": "dim s(10)\nprint \"Enter 11 numbers.\"\nfor i = 0 to 10\n  print i +1;\n  input \" => \"; s(i)\nnext i\nprint\n\nfor i = 10 to 0 step -1\n  print \"f(\"; s(i); \") = \";\n  r = f(s(i))\n  if r > 400 then\n    print \"-=< overflow >=-\"\n  else\n    print r\n  end if\nnext i\nend\n\nfunction f(n)\n  f = sqr(abs(n)) + 5 * n * n * n\nend function\n", "PHP": "<?php\n\n\n\nfunction f($n)\n{\n    return sqrt(abs($n)) + 5 * $n * $n * $n;\n}\n\n$sArray = [];\necho \"Enter 11 numbers.\\n\";\nfor ($i = 0; $i <= 10; $i++) {\n    echo $i + 1, \" - Enter number: \"; \n    array_push($sArray, (float)fgets(STDIN)); \n}\necho PHP_EOL;\n\n$sArray = array_reverse($sArray);\n\nforeach ($sArray as $s) {\n    $r = f($s);\n    echo \"f(\", $s, \") = \";\n    if ($r > 400) \n        echo \"overflow\\n\";\n    else\n        echo $r, PHP_EOL;\n}\n?>\n"}
{"id": 59323, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "PHP": "\n\n\nfunction middlethree($integer)\n{\n\t$int \t= (int)str_replace('-','',$integer);\n\t$length = strlen($int);\n\n\tif(is_int($int))\n\t{\n\t\tif($length >= 3)\n\t\t{\n\t\t\tif($length % 2 == 1)\n\t\t\t{\n\t\t\t\t$middle = floor($length / 2) - 1;\n\t\t\t\treturn substr($int,$middle, 3);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 'The value must contain an odd amount of digits...';\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 'The value must contain at least three digits...';\t\n\t\t}\n\t}\n\telse\n\t{\n\t\treturn 'The value does not appear to be an integer...';\n\t}\n}\n\n$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);\n\nforeach($numbers as $nums)\n{\n\techo $nums.' : '.middlethree($nums). '<br>';\n}\n"}
{"id": 59324, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "PHP": "$odd = function ($prev) use ( &$odd ) {\n\t$a = fgetc(STDIN);\n\tif (!ctype_alpha($a)) {\n\t\t$prev();\n\t\tfwrite(STDOUT, $a);\n\t\treturn $a != '.';\n\t}\n\t$clos = function () use ($a , $prev) {\n\t\tfwrite(STDOUT, $a);\n\t\t$prev();\n\t};\n\treturn $odd($clos);\n};\n$even = function () {\n\twhile (true) {\n\t\t$c = fgetc(STDIN);\n\t\tfwrite(STDOUT, $c);\n\t\tif (!ctype_alpha($c)) {\n\t\t\treturn $c != \".\";\n\t\t}\n\t}\n};\n$prev = function(){};\n$e = false;\nwhile ($e ? $odd($prev) : $even()) {\n\t$e = !$e;\n}\n"}
{"id": 59325, "name": "Table creation_Postal addresses", "VB": "Option Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n", "PHP": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\");\n?>\n"}
{"id": 59326, "name": "Soundex", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n", "PHP": "<?php\necho soundex(\"Soundex\"), \"\\n\"; // S532\necho soundex(\"Example\"), \"\\n\"; // E251\necho soundex(\"Sownteks\"), \"\\n\"; // S532\necho soundex(\"Ekzampul\"), \"\\n\"; // E251\n?>\n"}
{"id": 59327, "name": "Literals_String", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n", "PHP": "'c';                      # character\n'hello';                  # these two strings are the same\n\"hello\";\n'Hi $name. How are you?'; # result: \"Hi $name. How are you?\"\n\"Hi $name. How are you?\"; # result: \"Hi Bob. How are you?\"\n'\\n';                     # 2-character string with a backslash and \"n\"\n\"\\n\";                     # newline character\n`ls`;                     # runs a command in the shell and returns the output as a string\n<<END                     # Here-Document\nHi, whatever goes here gets put into the string,\nincluding newlines and $variables,\nuntil the label we put above\nEND;\n<<'END'                   # Here-Document like single-quoted\nSame as above, but no interpolation of $variables.\nEND;\n"}
{"id": 59328, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "PHP": "\n$fruits = array( \"apple\", \"banana\", \"cherry\" );\n$fruits = array( \"apple\" => 0, \"banana\" => 1, \"cherry\" => 2 );\n\nclass Fruit {\n  const APPLE = 0;\n  const BANANA = 1;\n  const CHERRY = 2;\n}\n\n$value = Fruit::APPLE;\n\ndefine(\"FRUIT_APPLE\", 0);\ndefine(\"FRUIT_BANANA\", 1);\ndefine(\"FRUIT_CHERRY\", 2);\n"}
{"id": 59329, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 59330, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "PHP": "<?php\nfunction brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {\n   do {\n     switch($s[$_s]) {\n       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;\n       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;\n       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;\n       case '<': $_d--; break;\n       case '.': $o .= $d[$_d]; break;\n       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;\n       case '[':\n         if((int)ord($d[$_d]) == 0) {\n           $brackets = 1;\n           while($brackets && $_s++ < strlen($s)) {\n             if($s[$_s] == '[')\n               $brackets++;\n             else if($s[$_s] == ']')\n               $brackets--;\n           }\n         }\n         else {\n             $pos = $_s++-1;\n           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))\n             $_s = $pos;\n         }\n         break;\n       case ']': return ((int)ord($d[$_d]) != 0);\n    }\n  } while(++$_s < strlen($s));\n}\n\nfunction brainfuck($source, $input='') {\n  $data         = array();\n  $data[0]      = chr(0);\n  $data_index   = 0;\n  $source_index = 0;\n  $input_index  = 0;\n  $output       = '';\n  \n  brainfuck_interpret($source, $source_index,\n                      $data,   $data_index,\n                      $input,  $input_index,\n                      $output);\n  return $output;\n}\n\n$code = \"\n    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\n    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\n\";\n$inp = '123';\nprint brainfuck( $code, $inp );\n"}
{"id": 59331, "name": "Calendar - for _REAL_ programmers", "VB": "OPTION COMPARE BINARY\nOPTION EXPLICIT ON\nOPTION INFER ON\nOPTION STRICT ON\n\nIMPORTS SYSTEM.GLOBALIZATION\nIMPORTS SYSTEM.TEXT\nIMPORTS SYSTEM.RUNTIME.INTEROPSERVICES\nIMPORTS SYSTEM.RUNTIME.COMPILERSERVICES\n\nMODULE ARGHELPER\n    READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()\n\n    DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN\n\n    SUB INITIALIZEARGUMENTS(ARGS AS STRING())\n        FOR EACH ITEM IN ARGS\n            ITEM = ITEM.TOUPPERINVARIANT()\n\n            IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> \"\"\"\"C THEN\n                DIM COLONPOS = ITEM.INDEXOF(\":\"C, STRINGCOMPARISON.ORDINAL)\n\n                IF COLONPOS <> -1 THEN\n                    \n                    _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))\n                END IF\n            END IF\n        NEXT\n    END SUB\n\n    SUB FROMARGUMENT(OF T)(\n            KEY AS STRING,\n            <OUT> BYREF VAR AS T,\n            GETDEFAULT AS FUNC(OF T),\n            TRYPARSE AS TRYPARSE(OF STRING, T),\n            OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)\n\n        DIM VALUE AS STRING = NOTHING\n        IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN\n            IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN\n                CONSOLE.WRITELINE($\"INVALID VALUE FOR {KEY}: {VALUE}\")\n                ENVIRONMENT.EXIT(-1)\n            END IF\n        ELSE\n            VAR = GETDEFAULT()\n        END IF\n    END SUB\nEND MODULE\n\nMODULE PROGRAM\n    SUB MAIN(ARGS AS STRING())\n        DIM DT AS DATE\n        DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER\n        DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN\n\n        INITIALIZEARGUMENTS(ARGS)\n        FROMARGUMENT(\"DATE\", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)\n        FROMARGUMENT(\"COLS\", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)\n        FROMARGUMENT(\"ROWS\", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)\n        FROMARGUMENT(\"MS/ROW\", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \\ 20)\n        FROMARGUMENT(\"VSTRETCH\", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"HSTRETCH\", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n        FROMARGUMENT(\"WSIZE\", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n\n        \n        IF RESIZEWINDOW THEN\n            CONSOLE.WINDOWWIDTH = COLUMNS + 1\n            CONSOLE.WINDOWHEIGHT = ROWS\n        END IF\n\n        IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \\ 22, 1)\n\n        FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)\n            CONSOLE.WRITE(ROW)\n        NEXT\n    END SUB\n\n    ITERATOR FUNCTION GETCALENDARROWS(\n            DT AS DATE,\n            WIDTH AS INTEGER,\n            HEIGHT AS INTEGER,\n            MONTHSPERROW AS INTEGER,\n            VERTSTRETCH AS BOOLEAN,\n            HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n\n        DIM YEAR = DT.YEAR\n        DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))\n        \n        DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3\n\n        YIELD \"[SNOOPY]\".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n        YIELD ENVIRONMENT.NEWLINE\n\n        DIM MONTH = 0\n        DO WHILE MONTH < 12\n            DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)\n\n            DIM CELLWIDTH = WIDTH \\ MONTHSPERROW\n            DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \\ 20)\n\n            DIM CELLHEIGHT = MONTHGRIDHEIGHT \\ CALENDARROWCOUNT\n            DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \\ 20\n\n            \n            DIM GETMONTHFROM =\n                FUNCTION(M AS INTEGER) BUILDMONTH(\n                    DT:=NEW DATE(DT.YEAR, M, 1),\n                    WIDTH:=CELLCONTENTWIDTH,\n                    HEIGHT:=CELLCONTENTHEIGHT,\n                    VERTSTRETCH:=VERTSTRETCH,\n                    HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))\n\n            \n            DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =\n                ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)\n\n            DIM CALENDARROW AS IENUMERABLE(OF STRING) =\n                INTERLEAVED(\n                    MONTHSTHISROW,\n                    USEINNERSEPARATOR:=FALSE,\n                    USEOUTERSEPARATOR:=TRUE,\n                    OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)\n\n            DIM EN = CALENDARROW.GETENUMERATOR()\n            DIM HASNEXT = EN.MOVENEXT()\n            DO WHILE HASNEXT\n\n                DIM CURRENT AS STRING = EN.CURRENT\n\n                \n                \n                HASNEXT = EN.MOVENEXT()\n                YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)\n            LOOP\n\n            MONTH += MONTHSPERROW\n        LOOP\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION INTERLEAVED(OF T)(\n            SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),\n            OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL INNERSEPARATOR AS T = NOTHING,\n            OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,\n            OPTIONAL OUTERSEPARATOR AS T = NOTHING,\n            OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)\n        DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING\n\n        TRY\n            SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()\n            DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH\n            DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN\n\n            DIM ANYPREVITERS AS BOOLEAN = FALSE\n            DO\n                \n                DIM FIRSTACTIVE = -1, LASTACTIVE = -1\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()\n                    IF ENUMERATORSTATES(I) THEN\n                        IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I\n                        LASTACTIVE = I\n                    END IF\n                NEXT\n\n                \n                \n                DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)\n                IF NOT THISITERHASRESULTS THEN EXIT DO\n\n                \n                IF ANYPREVITERS THEN\n                    IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR\n                ELSE\n                    ANYPREVITERS = TRUE\n                END IF\n\n                \n                FOR I = 0 TO NUMSOURCES - 1\n                    IF ENUMERATORSTATES(I) THEN\n                        \n                        IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR\n                        YIELD SOURCEENUMERATORS(I).CURRENT\n                    END IF\n                NEXT\n            LOOP\n\n        FINALLY\n            IF SOURCEENUMERATORS ISNOT NOTHING THEN\n                FOR EACH EN IN SOURCEENUMERATORS\n                    EN.DISPOSE()\n                NEXT\n            END IF\n        END TRY\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n        CONST DAY_WDT = 2 \n        CONST ALLDAYS_WDT = DAY_WDT * 7 \n\n        \n        DT = NEW DATE(DT.YEAR, DT.MONTH, 1)\n\n        \n        DIM DAYSEP AS NEW STRING(\" \"C, MATH.MIN((WIDTH - ALLDAYS_WDT) \\ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))\n        \n        DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \\ 7)\n\n        \n        DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6\n\n        \n        DIM LEFTPAD AS NEW STRING(\" \"C, (WIDTH - BLOCKWIDTH) \\ 2)\n        \n        DIM FULLPAD AS NEW STRING(\" \"C, WIDTH)\n\n        \n        DIM SB AS NEW STRINGBUILDER(LEFTPAD)\n        DIM NUMLINES = 0\n\n        \n        \n        \n        DIM ENDLINE =\n         FUNCTION() AS IENUMERABLE(OF STRING)\n             DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)\n             SB.CLEAR()\n             SB.APPEND(LEFTPAD)\n\n             \n             RETURN IF(NUMLINES >= HEIGHT,\n                 ENUMERABLE.EMPTY(OF STRING)(),\n                 ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)\n                     YIELD FINISHEDLINE\n                     NUMLINES += 1\n\n                     FOR I = 1 TO VERTBLANKCOUNT\n                         IF NUMLINES >= HEIGHT THEN RETURN\n                         YIELD FULLPAD\n                         NUMLINES += 1\n                     NEXT\n                 END FUNCTION())\n         END FUNCTION\n\n        \n        SB.APPEND(PADCENTER(DT.TOSTRING(\"MMMM\", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())\n        SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))\n        FOR EACH L IN ENDLINE()\n            YIELD L\n        NEXT\n\n        \n        DIM STARTWKDY = CINT(DT.DAYOFWEEK)\n\n        \n        DIM FIRSTPAD AS NEW STRING(\" \"C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)\n        SB.APPEND(FIRSTPAD)\n\n        DIM D = DT\n        DO WHILE D.MONTH = DT.MONTH\n            SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $\"{{0,{DAY_WDT}}}\", D.DAY)\n\n            \n            IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN\n                FOR EACH L IN ENDLINE()\n                    YIELD L\n                NEXT\n            ELSE\n                SB.APPEND(DAYSEP)\n            END IF\n\n            D = D.ADDDAYS(1)\n        LOOP\n\n        \n        DIM NEXTLINES AS IENUMERABLE(OF STRING)\n        DO\n            NEXTLINES = ENDLINE()\n            FOR EACH L IN NEXTLINES\n                YIELD L\n            NEXT\n        LOOP WHILE NEXTLINES.ANY()\n    END FUNCTION\n\n    \n    \n    \n    \n    \n    \n    \n    <EXTENSION()>\n    PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = \" \"C) AS STRING\n        RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \\ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)\n    END FUNCTION\nEND MODULE\n", "PHP": "<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; // MAGICAL SEMICOLON\n"}
{"id": 59332, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "PHP": "<?php\n\nfunction symbolTable() {\n    $symbol = array();\n    for ($c = ord('a') ; $c <= ord('z') ; $c++) {\n        $symbol[$c - ord('a')] = chr($c);\n    }\n    return $symbol;\n}\n\nfunction mtfEncode($original, $symbol) {\n    $encoded = array();\n    for ($i = 0 ; $i < strlen($original) ; $i++) {\n        $char = $original[$i];\n        $position = array_search($char, $symbol);\n        $encoded[] = $position;\n        $mtf = $symbol[$position];\n        unset($symbol[$position]);\n        array_unshift($symbol, $mtf);\n    }\n    return $encoded;\n}\n\nfunction mtfDecode($encoded, $symbol) {\n    $decoded = '';\n    foreach ($encoded AS $position) {\n        $char = $symbol[$position];\n        $decoded .= $char;\n        unset($symbol[$position]);\n        array_unshift($symbol, $char);\n    }\n    return $decoded;\n}\n\nforeach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {\n    $encoded = mtfEncode($original, symbolTable());\n    $decoded = mtfDecode($encoded, symbolTable());\n    echo\n        $original,\n        ' -> [', implode(',', $encoded), ']',\n        ' -> ', $decoded,\n        ' : ', ($original === $decoded ? 'OK' : 'Error'),\n        PHP_EOL;\n}\n"}
{"id": 59333, "name": "Execute a system command", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n", "PHP": "@exec($command,$output);\necho nl2br($output);\n"}
{"id": 59334, "name": "XML validation", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n", "PHP": "libxml_use_internal_errors(true);\n\n$xml = new DOMDocument();\n$xml->load('shiporder.xml');\n\nif (!$xml->schemaValidate('shiporder.xsd')) {\n    var_dump(libxml_get_errors()); exit;\n} else {\n    echo 'success';\n}\n"}
{"id": 59335, "name": "Longest increasing subsequence", "VB": "Sub Lis(arr() As Integer)\n    Dim As Integer lb = Lbound(arr), ub = Ubound(arr)\n    Dim As Integer i, lo, hi, mitad, newl, l = 0\n\tDim As Integer p(ub), m(ub)\n    \n\tFor i = lb To ub\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmitad = Int((lo+hi)/2)\n\t\t\tIf arr(m(mitad)) < arr(i) Then\n\t\t\t\tlo = mitad + 1\n            Else\n\t\t\t\thi = mitad - 1\n            End If\n        Loop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then l = newl\n    Next i\n    \n    Dim As Integer res(l)\n\tDim As Integer k = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\tres(i) = arr(k)\n\t\tk = p(k)\n    Next i\n\t\n    For i = Lbound(res) To Ubound(res)-1\n        Print res(i); \" \";\n    Next i\nEnd Sub\n\nDim As Integer arrA(5) => {3,2,6,4,5,1}\nLis(arrA())\nPrint\nDim As Integer arrB(15) => {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}\nLis(arrB())\n\nSleep\n", "PHP": "<?php\nclass Node {\n    public $val;\n    public $back = NULL;\n}\n\nfunction lis($n) {\n    $pileTops = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($pileTops)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($pileTops[$mid]->val >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        $node = new Node();\n        $node->val = $x;\n        if ($i != 0)\n            $node->back = $pileTops[$i-1];\n        $pileTops[$i] = $node;\n    }\n    $result = array();\n    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;\n         $node != NULL; $node = $node->back)\n        $result[] = $node->val;\n\n    return array_reverse($result);\n}\n\nprint_r(lis(array(3, 2, 6, 4, 5, 1)));\nprint_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));\n?>\n"}
{"id": 59336, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n", "PHP": "function getitem($s,$depth=0) {\n    $out = [''];\n    while ($s) {\n        $c = $s[0];\n        if ($depth && ($c == ',' || $c == '}')) {\n            return [$out, $s];\n        }\n        if ($c == '{') {\n            $x = getgroup(substr($s, 1), $depth + 1);\n            if($x) {\n                $tmp = [];\n                foreach($out as $a) {\n                    foreach($x[0] as $b) { \n                        $tmp[] = $a . $b;\n                    }\n                }\n                $out = $tmp;\n                $s = $x[1];\n                continue;\n            }\n        }\n        if ($c == '\\\\' && strlen($s) > 1) {\n            list($s, $c) = [substr($s, 1), ($c . $s[1])];\n        }\n\n        $tmp = [];\n        foreach($out as $a) {\n            $tmp[] = $a . $c;\n        }\n        $out = $tmp;\n        $s = substr($s, 1);\n        \n    }\n    return [$out, $s];\n}\nfunction getgroup($s,$depth) {\n    list($out, $comma) = [[], false];\n    while ($s) {\n        list($g, $s) = getitem($s, $depth);\n        if (!$s) {\n            break;\n        }\n        $out = array_merge($out, $g);\n        if ($s[0] == '}') {\n            if ($comma) {\n                return [$out, substr($s, 1)];\n            }\n\n            $tmp = [];\n            foreach($out as $a) {\n                $tmp[] = '{' . $a . '}';\n            }\n            return [$tmp, substr($s, 1)];\n        }\n        if ($s[0] == ',') {\n            list($comma, $s) = [true, substr($s, 1)];\n        }\n    }\n    return null;\n}\n\n$lines = <<< 'END'\n~/{Downloads,Pictures}/*.{jpg,gif,png}\nIt{{em,alic}iz,erat}e{d,}, please.\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\nEND;\n\nforeach( explode(\"\\n\", $lines) as $line ) {\n    printf(\"\\n%s\\n\", $line);\n    foreach( getitem($line)[0] as $expansion ) {\n        printf(\"    %s\\n\", $expansion);\n    }\n}\n"}
{"id": 59337, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "PHP": "<?php\n\nfunction is_describing($number) {\n    foreach (str_split((int) $number) as $place => $value) {\n        if (substr_count($number, $place) != $value) { \n            return false;\n        }\n    }    \n    return true;\n}\n\nfor ($i = 0; $i <= 50000000; $i += 10) {\n    if (is_describing($i)) {\n        echo $i . PHP_EOL;\n    }\n}\n\n?>\n"}
{"id": 59338, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "PHP": "<?php\nfunction invmod($a,$n){\n        if ($n < 0) $n = -$n;\n        if ($a < 0) $a = $n - (-$a % $n);\n\t$t = 0; $nt = 1; $r = $n; $nr = $a % $n;\n\twhile ($nr != 0) {\n\t\t$quot= intval($r/$nr);\n\t\t$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;\n\t\t$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;\n\t}\n\tif ($r > 1) return -1;\n\tif ($t < 0) $t += $n;\n\treturn $t;\n}\n\tprintf(\"%d\\n\", invmod(42, 2017));\n?>\n"}
{"id": 59339, "name": "Hello world_Web server", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n", "PHP": "<?php\n\n$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');\n\nsocket_bind($socket, 0,                                        8080);\nsocket_listen($socket);\n\n$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';\n\nfor (;;) {\n\n    if ($client = @socket_accept($socket)) {\n        socket_write($client, \"HTTP/1.1 200 OK\\r\\n\" .\n               \"Content-length: \" . strlen($msg) . \"\\r\\n\" .\n               \"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\" .\n               $msg);\n    }\n    else usleep(100000); // limits CPU usage by sleeping after doing every request\n}\n?>\n"}
{"id": 59340, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "PHP": "<?php\n\n$conf = file_get_contents('update-conf-file.txt');\n\n$conf = preg_replace('/^(needspeeling)(|\\s*\\S*)$/mi', '; $1', $conf);\n\n$conf = preg_replace('/^;?\\s*(seedsremoved)/mi', '$1', $conf);\n\n$conf = preg_replace('/^(numberofbananas)(|\\s*\\S*)$/mi', '$1 1024', $conf);\n\nif (preg_match('/^;?\\s*(numberofstrawberries)/mi', $conf, $matches)) {\n    $conf = preg_replace('/^(numberofstrawberries)(|\\s*\\S*)$/mi', '$1 62000', $conf);\n} else {\n    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;\n}\n\necho $conf;\n"}
{"id": 59341, "name": "Literals_Floating point", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n", "PHP": ".12\n0.1234\n1.2e3\n7E-10\n"}
{"id": 59342, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59343, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "PHP": "<?php\nclass SimpleClass {\n    private $answer = \"hello\\\"world\\nforever :)\";\n}\n \n$class = new SimpleClass;\nob_start();\n\n\n\nvar_export($class);\n$class_content = ob_get_clean();\n \n$class_content = preg_replace('\"^SimpleClass::__set_state\\(\"', 'return ', $class_content);\n$class_content = preg_replace('\"\\)$\"', ';', $class_content);\n\n$new_class = eval($class_content);\necho $new_class['answer'];\n"}
{"id": 59344, "name": "Long year", "VB": "Public Sub Main() \n  \n  For y As Integer = 2000 To 2100 \n    If isLongYear(y) Then Print y, \n  Next\n  \nEnd \n\nFunction p(y As Integer) As Integer \n  \n  Return (y + (y \\ 4) - (y \\ 100) + (y \\ 400)) Mod 7 \n  \nEnd Function \n\nFunction isLongYear(y As Integer) As Boolean \n  \n  If p(y) = 4 Then Return True \n  If p(y - 1) = 3 Then Return True \n  Return False \n  \nEnd Function\n", "PHP": "function isLongYear($year) {\n  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));\n}\n\nfor ($y=1995; $y<=2045; ++$y) {\n  if (isLongYear($y)) {\n    printf(\"%s\\n\", $y);\n  }\n}\n"}
{"id": 59345, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59346, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "PHP": "<?\n$base = array(\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\");\n$update = array(\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974);\n\n$result = $update + $base; // Notice that the order is reversed\nprint_r($result);\n?>\n"}
{"id": 59347, "name": "Dijkstra's algorithm", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n", "PHP": "<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n"}
{"id": 59348, "name": "Associative array_Iteration", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n", "PHP": "<?php\n$pairs = array( \"hello\" => 1,\n\t\t\"world\" => 2,\n\t\t\"!\"     => 3 );\n\nforeach($pairs as $k => $v) {\n  echo \"(k,v) = ($k, $v)\\n\";\n}\n\nforeach(array_keys($pairs) as $key) {\n  echo \"key = $key, value = $pairs[$key]\\n\";\n}\n\nforeach($pairs as $value) {\n  echo \"values = $value\\n\";\n}\n?>\n"}
{"id": 59349, "name": "Hash join", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n", "PHP": "<?php\nfunction hashJoin($table1, $index1, $table2, $index2) {\n\n    foreach ($table1 as $s)\n        $h[$s[$index1]][] = $s;\n\n    foreach ($table2 as $r)\n    \tforeach ($h[$r[$index2]] as $s)\n\t    $result[] = array($s, $r);\n    return $result;\n}\n\n$table1 = array(array(27, \"Jonah\"),\n           array(18, \"Alan\"),\n           array(28, \"Glory\"),\n           array(18, \"Popeye\"),\n           array(28, \"Alan\"));\n$table2 = array(array(\"Jonah\", \"Whales\"),\n           array(\"Jonah\", \"Spiders\"),\n           array(\"Alan\", \"Ghosts\"),\n           array(\"Alan\", \"Zombies\"),\n           array(\"Glory\", \"Buffy\"),\n           array(\"Bob\", \"foo\"));\n\nforeach (hashJoin($table1, 1, $table2, 0) as $row)\n    print_r($row);\n?>\n"}
{"id": 59350, "name": "Inheritance_Single", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n", "PHP": "class Animal {\n\n}\n\nclass Dog extends Animal {\n\n}\n\nclass Cat extends Animal {\n\n}\n\nclass Lab extends Dog {\n\n}\n\nclass Collie extends Dog {\n\n}\n"}
{"id": 59351, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "PHP": "$array = array();\n$array = []; // Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); // bar\necho($array['moo']); // Undefined index\n\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\necho(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null\n"}
{"id": 59352, "name": "Reflection_List properties", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n", "PHP": "<?\nclass Foo {\n}\n$obj = new Foo();\n$obj->bar = 42;\n$obj->baz = true;\n\nvar_dump(get_object_vars($obj));\n?>\n"}
{"id": 59353, "name": "Align columns", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n", "PHP": "<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); // see http://bugs.php.net/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n"}
{"id": 59354, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59355, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "PHP": "<?php\n\n$urls = array(\n    'foo://example.com:8042/over/there?name=ferret#nose',\n    'urn:example:animal:ferret:nose',\n    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',\n    'ftp://ftp.is.co.za/rfc/rfc1808.txt',\n    'http://www.ietf.org/rfc/rfc2396.txt#header1',\n    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',\n    'mailto:John.Doe@example.com',\n    'news:comp.infosystems.www.servers.unix',\n    'tel:+1-816-555-1212',\n    'telnet://192.0.2.16:80/',\n    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',\n);\n\nforeach ($urls AS $url) {\n    $p = parse_url($url);\n    echo $url, PHP_EOL;\n    print_r($p);\n    echo PHP_EOL;\n}\n"}
{"id": 59356, "name": "Variables", "VB": "Dim variable As datatype\nDim var1,var2,... As datatype\n", "PHP": "<?php\n\n\n\n\n\n# NULL typed variable\n$null = NULL;\t\t\t\tvar_dump($null);\t// output: null\n\n# defining a boolean\n$boolean = true;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = false;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n\n# bool and boolean is the same\n$boolean = (bool)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n$boolean = (boolean)1;\t\t\tvar_dump($boolean);\t// output: boolean true\n\n$boolean = (bool)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n$boolean = (boolean)0;\t\t\tvar_dump($boolean);\t// output: boolean false\n\n# defining an integer\n$int = 0;\t\t\t\tvar_dump($int);\t\t// output: int 0\n\n# defining a float,\n$float = 0.01;\t\t\t\tvar_dump($float);\t// output: float 0.01\n\n# which is also identical to \"real\" and \"double\"\nvar_dump((double)$float);\t\t\t\t\t// output: float 0.01\nvar_dump((real)$float);\t\t\t\t\t\t// output: float 0.01\n\n# casting back to int (auto flooring the value)\nvar_dump((int)$float);\t\t\t\t\t\t// output: int 0\nvar_dump((int)($float+1));\t\t\t\t\t// output: int 1\nvar_dump((int)($float+1.9));\t\t\t\t\t// output: int 1\n\n# defining a string\n$string = 'string';\nvar_dump($string);\t\t\t\t\t\t// output: string 'string' (length=6)\n\n# referencing a variable (there are no pointers in PHP).\n$another_string = &$string;\nvar_dump($another_string);\n\n\n$string = \"I'm the same string!\";\nvar_dump($another_string);\n\n# \"deleting\" a variable from memory\nunset($another_string);\n\n$string = 'string';\n\n$parsed_string = \"This is a $string\";\nvar_dump($parsed_string);\n\n$parsed_string .= \" with another {$string}\";\nvar_dump($parsed_string);\n\n\n# with string parsing\n$heredoc = <<<HEREDOC\nThis is the content of \\$string: {$string}\nHEREDOC;\nvar_dump($heredoc);\n\n\n# without string parsing (notice the single quotes surrounding NOWDOC)\n$nowdoc = <<<'NOWDOC'\nThis is the content of \\$string: {$string}\nNOWDOC;\nvar_dump($nowdoc);\n\n\n# as of PHP5, defining an object typed stdClass => standard class\n$stdObject = new stdClass();\tvar_dump($stdObject);\n\n# defining an object typed Foo\nclass Foo {}\n$foo = new Foo();\t\tvar_dump($foo);\n\n# defining an empty array\n$array = array();\t\tvar_dump($array);\n\n\n\n$assoc = array(\n\t0 => $int,\n\t'integer' => $int,\n\t1 => $float,\n\t'float' => $float,\n\t2 => $string,\n\t'string' => $string,\n\t3 => NULL, // <=== key 3 is NULL\n\t3, // <=== this is a value, not a key (key is 4)\n\t5 => $stdObject,\n\t'Foo' => $foo,\n);\nvar_dump($assoc);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction a_function()\n{\n\t# not reachable\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean false\n\n\tglobal $foo;\n\t# \"global\" (reachable) inside a_function()'s scope\n\tvar_dump(isset($foo));\t\t\t\t// output: boolean true\n}\n\na_function();\n\n\n"}
{"id": 59357, "name": "Runtime evaluation", "VB": "#macro assign(sym, expr)\n    __fb_unquote__(__fb_eval__(\"#undef \" + sym))\n    __fb_unquote__(__fb_eval__(\"#define \" + sym + \" \" + __fb_quote__(__fb_eval__(expr))))\n#endmacro\n\n#define a, b, x\n\nassign(\"a\", 8)\nassign(\"b\", 7)\nassign(\"x\", Sqr(a) + (Sin(b*3)/2))\nPrint x\n\nassign(\"x\", \"goodbye\")\nPrint x\n\nSleep\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59358, "name": "Runtime evaluation", "VB": "#macro assign(sym, expr)\n    __fb_unquote__(__fb_eval__(\"#undef \" + sym))\n    __fb_unquote__(__fb_eval__(\"#define \" + sym + \" \" + __fb_quote__(__fb_eval__(expr))))\n#endmacro\n\n#define a, b, x\n\nassign(\"a\", 8)\nassign(\"b\", 7)\nassign(\"x\", Sqr(a) + (Sin(b*3)/2))\nPrint x\n\nassign(\"x\", \"goodbye\")\nPrint x\n\nSleep\n", "PHP": "<?php\n  $code = 'echo \"hello world\"';\n  eval($code);\n  $code = 'return \"hello world\"';\n  print eval($code);\n"}
{"id": 59359, "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", "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": 59360, "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", "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": 59361, "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", "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": 59362, "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", "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": 59363, "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", "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": 59364, "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", "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": 59365, "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", "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": 59366, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 59367, "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", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59368, "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", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59369, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n"}
{"id": 59370, "name": "Checkpoint synchronization", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n"}
{"id": 59371, "name": "Variable-length quantity", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 59372, "name": "String case", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 59373, "name": "MD5", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 59374, "name": "Date manipulation", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 59375, "name": "Sorting algorithms_Sleep sort", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 59376, "name": "Loops_Nested", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 59377, "name": "Remove duplicate elements", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 59378, "name": "Look-and-say sequence", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 59379, "name": "Stack", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 59380, "name": "Totient function", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 59381, "name": "Conditional structures", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 59382, "name": "Sort using a custom comparator", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59383, "name": "Animation", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 59384, "name": "Sorting algorithms_Radix sort", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n"}
{"id": 59385, "name": "List comprehensions", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 59386, "name": "Sorting algorithms_Selection sort", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 59387, "name": "Apply a callback to an array", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 59388, "name": "Singleton", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n"}
{"id": 59389, "name": "Safe addition", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 59390, "name": "Loops_Downward for", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 59391, "name": "Write entire file", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n"}
{"id": 59392, "name": "Loops_For", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59393, "name": "Non-continuous subsequences", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 59394, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 59395, "name": "Twin primes", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 59396, "name": "Roots of unity", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n"}
{"id": 59397, "name": "Long multiplication", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 59398, "name": "Pell's equation", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n"}
{"id": 59399, "name": "Bulls and cows", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 59400, "name": "Sorting algorithms_Bubble sort", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 59401, "name": "File input_output", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 59402, "name": "Arithmetic_Integer", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 59403, "name": "Matrix transposition", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 59404, "name": "Man or boy test", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n"}
{"id": 59405, "name": "Short-circuit evaluation", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 59406, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 59407, "name": "Find limit of recursion", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 59408, "name": "Image noise", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 59409, "name": "Perfect numbers", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 59410, "name": "Arbitrary-precision integers (included)", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 59411, "name": "Inverted index", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n"}
{"id": 59412, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 59413, "name": "Least common multiple", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 59414, "name": "Loops_Break", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 59415, "name": "Water collected between towers", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 59416, "name": "Sum and product puzzle", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n"}
{"id": 59417, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 59418, "name": "Parsing_Shunting-yard algorithm", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 59419, "name": "Middle three digits", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 59420, "name": "Stern-Brocot sequence", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 59421, "name": "Documentation", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n"}
{"id": 59422, "name": "Documentation", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n"}
{"id": 59423, "name": "Problem of Apollonius", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n"}
{"id": 59424, "name": "Chat server", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59425, "name": "FASTA format", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n"}
{"id": 59426, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 59427, "name": "Find palindromic numbers in both binary and ternary bases", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 59428, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 59429, "name": "Cipolla's algorithm", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 59430, "name": "Literals_String", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n"}
{"id": 59431, "name": "GUI_Maximum window dimensions", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n"}
{"id": 59432, "name": "Enumerations", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 59433, "name": "Knapsack problem_Unbounded", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n", "C#": "\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) / 2;\n                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n"}
{"id": 59434, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 59435, "name": "Range extraction", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 59436, "name": "Type detection", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n", "C#": "using System;\n\nnamespace TypeDetection {\n    class C { }\n    struct S { }\n    enum E {\n        NONE,\n    }\n\n    class Program {\n        static void ShowType<T>(T t) {\n            Console.WriteLine(\"The type of '{0}' is {1}\", t, t.GetType());\n        }\n\n        static void Main() {\n            ShowType(5);\n            ShowType(7.5);\n            ShowType('d');\n            ShowType(true);\n            ShowType(\"Rosetta\");\n            ShowType(new C());\n            ShowType(new S());\n            ShowType(E.NONE);\n            ShowType(new int[] { 1, 2, 3 });\n        }\n    }\n}\n"}
{"id": 59437, "name": "Maximum triangle path sum", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n"}
{"id": 59438, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 59439, "name": "Four bit adder", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 59440, "name": "Unix_ls", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 59441, "name": "UTF-8 encode and decode", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n"}
{"id": 59442, "name": "Magic squares of doubly even order", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n"}
{"id": 59443, "name": "Same fringe", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n"}
{"id": 59444, "name": "Peaceful chess queen armies", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59445, "name": "Move-to-front algorithm", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 59446, "name": "Execute a system command", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 59447, "name": "XML validation", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n"}
{"id": 59448, "name": "Longest increasing subsequence", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 59449, "name": "Scope modifiers", "Java": "public \n\nprotected \n\n\nprivate \n\nstatic \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npublic void function(int x){\n   \n   int y;\n   \n   {\n      int z;\n      \n   }\n   \n}\n", "C#": "public \nprotected \ninternal \nprotected internal \nprivate \n\nprivate protected \n\n\n\n\n\n\n\n\n\n\n\n"}
{"id": 59450, "name": "Brace expansion", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n"}
{"id": 59451, "name": "GUI component interaction", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n"}
{"id": 59452, "name": "One of n lines in a file", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 59453, "name": "Addition chains", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n"}
{"id": 59454, "name": "Repeat", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 59455, "name": "Modular inverse", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 59456, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 59457, "name": "Hello world_Web server", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 59458, "name": "Terminal control_Clear the screen", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n", "C#": "System.Console.Clear();\n"}
{"id": 59459, "name": "Active Directory_Connect", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n"}
{"id": 59460, "name": "Pythagorean quadruples", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59461, "name": "Sokoban", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n"}
{"id": 59462, "name": "Practical numbers", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n"}
{"id": 59463, "name": "Literals_Floating point", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n"}
{"id": 59464, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 59465, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 59466, "name": "Erdős-primes", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n", "C#": "using System; using static System.Console;\nclass Program {\n  const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];\n  static void Main(string[] args) {\n    f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)\n      f[b] = f[a] * (b + 1);\n    int pc = 0, nth = 0, lv = 0;\n    for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {\n        if (i < first) Write(\"{0,5:n0}{1}\", i, pc++ % 5 == 4 ? \"\\n\" : \"  \");\n        nth++; lv = i; }\n    Write(\"\\nCount of Erdős primes between 1 and {0:n0}: {1}\\n{2} Erdős prime (the last one under {3:n0}): {4:n0}\", first, pc, ord(nth), lmt, lv); }\n\n  static string ord(int n) {\n    return string.Format(\"{0:n0}\", n) + new string[]{\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"}[n % 10]; }\n\n  static bool is_erdos_prime(int p) {\n    if (!is_pr(p)) return false; int m = 0, t;\n    while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;\n    return true;\n    bool is_pr(int x) {\n      if (x < 4) return x > 1; if ((x & 1) == 0) return false;\n      for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;\n    return true; } } }\n"}
{"id": 59467, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59468, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59469, "name": "Solve a Numbrix puzzle", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59470, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 59471, "name": "Church numerals", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 59472, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59473, "name": "Solve a Hopido puzzle", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59474, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 59475, "name": "Nonogram solver", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 59476, "name": "Word search", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n"}
{"id": 59477, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 59478, "name": "Break OO privacy", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 59479, "name": "Object serialization", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n"}
{"id": 59480, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 59481, "name": "Eertree", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 59482, "name": "Long year", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 59483, "name": "Zumkeller numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59484, "name": "Zumkeller numbers", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59485, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 59486, "name": "Associative array_Merging", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 59487, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 59488, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 59489, "name": "Metallic ratios", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 59490, "name": "Markov chain text generator", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n"}
{"id": 59491, "name": "Dijkstra's algorithm", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n"}
{"id": 59492, "name": "Geometric algebra", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n"}
{"id": 59493, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 59494, "name": "Suffix tree", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 59495, "name": "Associative array_Iteration", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 59496, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n"}
{"id": 59497, "name": "Define a primitive data type", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n"}
{"id": 59498, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59499, "name": "Solve a Holy Knight's tour", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 59500, "name": "Hash join", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n"}
{"id": 59501, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 59502, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 59503, "name": "Polynomial synthetic division", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 59504, "name": "Latin Squares in reduced form", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n"}
{"id": 59505, "name": "Closest-pair problem", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n"}
{"id": 59506, "name": "Inheritance_Single", "Java": "public class Animal{\n   \n}\n", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n"}
{"id": 59507, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n"}
{"id": 59508, "name": "Associative array_Creation", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n"}
{"id": 59509, "name": "Color wheel", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n"}
{"id": 59510, "name": "Polymorphism", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 59511, "name": "Square root by hand", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n"}
{"id": 59512, "name": "Square root by hand", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n", "C#": "using System;\nusing static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n    static void Main(string[] args) {\n        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;\n        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;\n        DateTime st = DateTime.Now;\n        if (args.Length > 0) int.TryParse(args[0], out n);\n        if (n > 0) n0 = n; else n = 1;\n        do {\n            Write(d); i = (i - k * d) * 100; k = 20 * j;\n            for (d = 1; d <= 10; d++)\n                if ((k + d) * d > i) { d -= 1; break; }\n            j = j * 10 + d; k += d; if (n0 > 0) n--;\n        } while (n > 0);\n        if (n0 > 0) WriteLine(\"\\nTime taken for {0} digits: {1}\", n0, DateTime.Now - st); }\n\n}\n"}
{"id": 59513, "name": "Reflection_List properties", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n"}
{"id": 59514, "name": "Minimal steps down to 1", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MinimalStepsDownToOne {\n\n    public static void main(String[] args) {\n        runTasks(getFunctions1());\n        runTasks(getFunctions2());\n        runTasks(getFunctions3());\n    }\n    \n    private static void runTasks(List<Function> functions) {\n        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);\n\n        \n        int max = 10;\n        populateMap(minPath, functions, max);\n        System.out.printf(\"%nWith functions:  %s%n\", functions);\n        System.out.printf(\"  Minimum steps to 1:%n\");\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int steps = minPath.get(n).size();\n            System.out.printf(\"    %2d: %d step%1s: %s%n\", n, steps, steps == 1 ? \"\" : \"s\", minPath.get(n));\n        }\n        \n        \n        displayMaxMin(minPath, functions, 2000);\n\n        \n        displayMaxMin(minPath, functions, 20000);\n\n        \n        displayMaxMin(minPath, functions, 100000);\n    }\n    \n    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        populateMap(minPath, functions, max);\n        List<Integer> maxIntegers = getMaxMin(minPath, max);\n        int maxSteps = maxIntegers.remove(0);\n        int numCount = maxIntegers.size();\n        System.out.printf(\"  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n\", numCount == 1 ? \"is\" : \"are\", numCount, numCount == 1 ? \"\" : \"s\", max, maxSteps, maxIntegers);\n        \n    }\n    \n    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {\n        int maxSteps = Integer.MIN_VALUE;\n        List<Integer> maxIntegers = new ArrayList<Integer>();\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int len = minPath.get(n).size();\n            if ( len > maxSteps ) {\n                maxSteps = len;\n                maxIntegers.clear();\n                maxIntegers.add(n);\n            }\n            else if ( len == maxSteps ) {\n                maxIntegers.add(n);\n            }\n        }\n        maxIntegers.add(0, maxSteps);\n        return maxIntegers;\n    }\n\n    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        for ( int n = 2 ; n <= max ; n++ ) {\n            if ( minPath.containsKey(n) ) {\n                continue;\n            }\n            Function minFunction = null;\n            int minSteps = Integer.MAX_VALUE;\n            for ( Function f : functions ) {\n                if ( f.actionOk(n) ) {\n                    int result = f.action(n);\n                    int steps = 1 + minPath.get(result).size();\n                    if ( steps < minSteps ) {\n                        minFunction = f;\n                        minSteps = steps;\n                    }\n                }\n            }\n            int result = minFunction.action(n);\n            List<String> path = new ArrayList<String>();\n            path.add(minFunction.toString(n));\n            path.addAll(minPath.get(result));\n            minPath.put(n, path);\n        }\n        \n    }\n\n    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {\n        Map<Integer,List<String>> minPath = new HashMap<>();\n        for ( int i = 2 ; i <= max ; i++ ) {\n            for ( Function f : functions ) {\n                if ( f.actionOk(i) ) {\n                    int result = f.action(i);\n                    if ( result == 1 ) {\n                        List<String> path = new ArrayList<String>();\n                        path.add(f.toString(i));\n                        minPath.put(i, path);\n                    }\n                }\n            }\n        }\n        return minPath;\n    }\n\n    private static List<Function> getFunctions3() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide2Function());\n        functions.add(new Divide3Function());\n        functions.add(new Subtract2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions2() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract2Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions1() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n    \n    public abstract static class Function {\n        abstract public int action(int n);\n        abstract public boolean actionOk(int n);\n        abstract public String toString(int n);\n    }\n    \n    public static class Divide2Function extends Function {\n        @Override public int action(int n) {\n            return n/2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 2 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/2 -> \" + n/2;\n        }\n        \n        @Override public String toString() {\n            return \"Divisor 2\";\n        }\n        \n    }\n\n    public static class Divide3Function extends Function {\n        @Override public int action(int n) {\n            return n/3;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 3 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/3 -> \" + n/3;\n        }\n\n        @Override public String toString() {\n            return \"Divisor 3\";\n        }\n\n    }\n\n    public static class Subtract1Function extends Function {\n        @Override public int action(int n) {\n            return n-1;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return true;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-1 -> \" + (n-1);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 1\";\n        }\n\n    }\n\n    public static class Subtract2Function extends Function {\n        @Override public int action(int n) {\n            return n-2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n > 2;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-2 -> \" + (n-2);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 2\";\n        }\n\n    }\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class MinimalSteps\n{\n    public static void Main() {\n        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });\n        var lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n        Console.WriteLine();\n\n        subtractors = new [] { 2 };\n        lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n    }\n\n    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {\n        for (int goal = 1; goal <= limit; goal++) {\n            var x = lookup[goal];\n            if (x.param == 0) {\n                Console.WriteLine($\"{goal} cannot be reached with these numbers.\");\n                continue;\n            }\n            Console.Write($\"{goal} takes {x.steps} {(x.steps == 1 ? \"step\" : \"steps\")}: \");\n            for (int n = goal; n > 1; ) {\n                Console.Write($\"{n},{x.op}{x.param}=> \");\n                n = x.op == '/' ? n / x.param : n - x.param;\n                x = lookup[n];\n            }\n            Console.WriteLine(\"1\");\n        }\n    }\n\n    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {\n        var maxSteps = lookup.Max(x => x.steps);\n        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();\n        Console.WriteLine(items.Count == 1\n            ? $\"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}\"\n            : $\"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}\"\n        );\n    }\n\n    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)\n    {\n        var lookup = new (char op, int param, int steps)[goal+1];\n        lookup[1] = ('/', 1, 0);\n        for (int n = 1; n < lookup.Length; n++) {\n            var ln = lookup[n];\n            if (ln.param == 0) continue;\n            for (int d = 0; d < divisors.Length; d++) {\n                int target = n * divisors[d];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);\n            }\n            for (int s = 0; s < subtractors.Length; s++) {\n                int target = n + subtractors[s];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);\n            }\n        }\n        return lookup;\n    }\n\n    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(\", \", source);\n}\n"}
{"id": 59515, "name": "Align columns", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n"}
{"id": 59516, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 59517, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 59518, "name": "URL parser", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 59519, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 59520, "name": "Base58Check encoding", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 59521, "name": "Dynamic variable names", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n"}
{"id": 59522, "name": "Data Encryption Standard", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace DES {\n    class Program {\n        \n        static string ByteArrayToString(byte[] ba) {\n            return BitConverter.ToString(ba).Replace(\"-\", \"\");\n        }\n\n        \n        \n        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(messageBytes, 0, messageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] encryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n\n            return encryptedMessageBytes;\n        }\n\n        \n        \n        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {\n            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n            \n            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);\n            CryptoStreamMode mode = CryptoStreamMode.Write;\n\n            \n            MemoryStream memStream = new MemoryStream();\n            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);\n            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);\n            cryptoStream.FlushFinalBlock();\n\n            \n            byte[] decryptedMessageBytes = new byte[memStream.Length];\n            memStream.Position = 0;\n            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);\n\n            return decryptedMessageBytes;\n        }\n\n        static void Main(string[] args) {\n            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };\n            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };\n\n            byte[] encStr = Encrypt(plainBytes, keyBytes);\n            Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr));\n\n            byte[] decBytes = Decrypt(encStr, keyBytes);\n            Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decBytes));\n        }\n    }\n}\n"}
{"id": 59523, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n"}
{"id": 59524, "name": "Fibonacci matrix-exponentiation", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n"}
{"id": 59525, "name": "Commatizing numbers", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n"}
{"id": 59526, "name": "Arithmetic coding_As a generalized change of radix", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59527, "name": "Empty program", "Java": "module EmptyProgram\n    {\n    void run()\n        {\n        }\n    }\n", "C#": "using System;\nclass Program\n{\n  public static void Main()\n  {\n  }\n}\n"}
{"id": 59528, "name": "Kosaraju", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 59529, "name": "Reflection_List methods", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n"}
{"id": 59530, "name": "Send an unknown method call", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n"}
{"id": 59531, "name": "Twelve statements", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n"}
{"id": 59532, "name": "Transportation problem", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.util.Arrays.stream;\nimport static java.util.stream.Collectors.toCollection;\n\npublic class TransportationProblem {\n\n    private static int[] demand;\n    private static int[] supply;\n    private static double[][] costs;\n    private static Shipment[][] matrix;\n\n    private static class Shipment {\n        final double costPerUnit;\n        final int r, c;\n        double quantity;\n\n        public Shipment(double q, double cpu, int r, int c) {\n            quantity = q;\n            costPerUnit = cpu;\n            this.r = r;\n            this.c = c;\n        }\n    }\n\n    static void init(String filename) throws Exception {\n\n        try (Scanner sc = new Scanner(new File(filename))) {\n            int numSources = sc.nextInt();\n            int numDestinations = sc.nextInt();\n\n            List<Integer> src = new ArrayList<>();\n            List<Integer> dst = new ArrayList<>();\n\n            for (int i = 0; i < numSources; i++)\n                src.add(sc.nextInt());\n\n            for (int i = 0; i < numDestinations; i++)\n                dst.add(sc.nextInt());\n\n            \n            int totalSrc = src.stream().mapToInt(i -> i).sum();\n            int totalDst = dst.stream().mapToInt(i -> i).sum();\n            if (totalSrc > totalDst)\n                dst.add(totalSrc - totalDst);\n            else if (totalDst > totalSrc)\n                src.add(totalDst - totalSrc);\n\n            supply = src.stream().mapToInt(i -> i).toArray();\n            demand = dst.stream().mapToInt(i -> i).toArray();\n\n            costs = new double[supply.length][demand.length];\n            matrix = new Shipment[supply.length][demand.length];\n\n            for (int i = 0; i < numSources; i++)\n                for (int j = 0; j < numDestinations; j++)\n                    costs[i][j] = sc.nextDouble();\n        }\n    }\n\n    static void northWestCornerRule() {\n\n        for (int r = 0, northwest = 0; r < supply.length; r++)\n            for (int c = northwest; c < demand.length; c++) {\n\n                int quantity = Math.min(supply[r], demand[c]);\n                if (quantity > 0) {\n                    matrix[r][c] = new Shipment(quantity, costs[r][c], r, c);\n\n                    supply[r] -= quantity;\n                    demand[c] -= quantity;\n\n                    if (supply[r] == 0) {\n                        northwest = c;\n                        break;\n                    }\n                }\n            }\n    }\n\n    static void steppingStone() {\n        double maxReduction = 0;\n        Shipment[] move = null;\n        Shipment leaving = null;\n\n        fixDegenerateCase();\n\n        for (int r = 0; r < supply.length; r++) {\n            for (int c = 0; c < demand.length; c++) {\n\n                if (matrix[r][c] != null)\n                    continue;\n\n                Shipment trial = new Shipment(0, costs[r][c], r, c);\n                Shipment[] path = getClosedPath(trial);\n\n                double reduction = 0;\n                double lowestQuantity = Integer.MAX_VALUE;\n                Shipment leavingCandidate = null;\n\n                boolean plus = true;\n                for (Shipment s : path) {\n                    if (plus) {\n                        reduction += s.costPerUnit;\n                    } else {\n                        reduction -= s.costPerUnit;\n                        if (s.quantity < lowestQuantity) {\n                            leavingCandidate = s;\n                            lowestQuantity = s.quantity;\n                        }\n                    }\n                    plus = !plus;\n                }\n                if (reduction < maxReduction) {\n                    move = path;\n                    leaving = leavingCandidate;\n                    maxReduction = reduction;\n                }\n            }\n        }\n\n        if (move != null) {\n            double q = leaving.quantity;\n            boolean plus = true;\n            for (Shipment s : move) {\n                s.quantity += plus ? q : -q;\n                matrix[s.r][s.c] = s.quantity == 0 ? null : s;\n                plus = !plus;\n            }\n            steppingStone();\n        }\n    }\n\n    static LinkedList<Shipment> matrixToList() {\n        return stream(matrix)\n                .flatMap(row -> stream(row))\n                .filter(s -> s != null)\n                .collect(toCollection(LinkedList::new));\n    }\n\n    static Shipment[] getClosedPath(Shipment s) {\n        LinkedList<Shipment> path = matrixToList();\n        path.addFirst(s);\n\n        \n        \n        while (path.removeIf(e -> {\n            Shipment[] nbrs = getNeighbors(e, path);\n            return nbrs[0] == null || nbrs[1] == null;\n        }));\n\n        \n        Shipment[] stones = path.toArray(new Shipment[path.size()]);\n        Shipment prev = s;\n        for (int i = 0; i < stones.length; i++) {\n            stones[i] = prev;\n            prev = getNeighbors(prev, path)[i % 2];\n        }\n        return stones;\n    }\n\n    static Shipment[] getNeighbors(Shipment s, LinkedList<Shipment> lst) {\n        Shipment[] nbrs = new Shipment[2];\n        for (Shipment o : lst) {\n            if (o != s) {\n                if (o.r == s.r && nbrs[0] == null)\n                    nbrs[0] = o;\n                else if (o.c == s.c && nbrs[1] == null)\n                    nbrs[1] = o;\n                if (nbrs[0] != null && nbrs[1] != null)\n                    break;\n            }\n        }\n        return nbrs;\n    }\n\n    static void fixDegenerateCase() {\n        final double eps = Double.MIN_VALUE;\n\n        if (supply.length + demand.length - 1 != matrixToList().size()) {\n\n            for (int r = 0; r < supply.length; r++)\n                for (int c = 0; c < demand.length; c++) {\n                    if (matrix[r][c] == null) {\n                        Shipment dummy = new Shipment(eps, costs[r][c], r, c);\n                        if (getClosedPath(dummy).length == 0) {\n                            matrix[r][c] = dummy;\n                            return;\n                        }\n                    }\n                }\n        }\n    }\n\n    static void printResult(String filename) {\n        System.out.printf(\"Optimal solution %s%n%n\", filename);\n        double totalCosts = 0;\n\n        for (int r = 0; r < supply.length; r++) {\n            for (int c = 0; c < demand.length; c++) {\n\n                Shipment s = matrix[r][c];\n                if (s != null && s.r == r && s.c == c) {\n                    System.out.printf(\" %3s \", (int) s.quantity);\n                    totalCosts += (s.quantity * s.costPerUnit);\n                } else\n                    System.out.printf(\"  -  \");\n            }\n            System.out.println();\n        }\n        System.out.printf(\"%nTotal costs: %s%n%n\", totalCosts);\n    }\n\n    public static void main(String[] args) throws Exception {\n\n        for (String filename : new String[]{\"input1.txt\", \"input2.txt\",\n            \"input3.txt\"}) {\n            init(filename);\n            northWestCornerRule();\n            steppingStone();\n            printResult(filename);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace TransportationProblem {\n    class Shipment {\n        public Shipment(double q, double cpu, int r, int c) {\n            Quantity = q;\n            CostPerUnit = cpu;\n            R = r;\n            C = c;\n        }\n\n        public double CostPerUnit { get; }\n\n        public double Quantity { get; set; }\n\n        public int R { get; }\n\n        public int C { get; }\n    }\n\n    class Program {\n        private static int[] demand;\n        private static int[] supply;\n        private static double[,] costs;\n        private static Shipment[,] matrix;\n\n        static void Init(string filename) {\n            string line;\n            using (StreamReader file = new StreamReader(filename)) {\n                line = file.ReadLine();\n                var numArr = line.Split();\n                int numSources = int.Parse(numArr[0]);\n                int numDestinations = int.Parse(numArr[1]);\n\n                List<int> src = new List<int>();\n                List<int> dst = new List<int>();\n\n                line = file.ReadLine();\n                numArr = line.Split();\n                for (int i = 0; i < numSources; i++) {\n                    src.Add(int.Parse(numArr[i]));\n                }\n\n                line = file.ReadLine();\n                numArr = line.Split();\n                for (int i = 0; i < numDestinations; i++) {\n                    dst.Add(int.Parse(numArr[i]));\n                }\n\n                \n                int totalSrc = src.Sum();\n                int totalDst = dst.Sum();\n                if (totalSrc > totalDst) {\n                    dst.Add(totalSrc - totalDst);\n                } else if (totalDst > totalSrc) {\n                    src.Add(totalDst - totalSrc);\n                }\n\n                supply = src.ToArray();\n                demand = dst.ToArray();\n\n                costs = new double[supply.Length, demand.Length];\n                matrix = new Shipment[supply.Length, demand.Length];\n\n                for (int i = 0; i < numSources; i++) {\n                    line = file.ReadLine();\n                    numArr = line.Split();\n                    for (int j = 0; j < numDestinations; j++) {\n                        costs[i, j] = int.Parse(numArr[j]);\n                    }\n                }\n            }\n        }\n\n        static void NorthWestCornerRule() {\n            for (int r = 0, northwest = 0; r < supply.Length; r++) {\n                for (int c = northwest; c < demand.Length; c++) {\n                    int quantity = Math.Min(supply[r], demand[c]);\n                    if (quantity > 0) {\n                        matrix[r, c] = new Shipment(quantity, costs[r, c], r, c);\n\n                        supply[r] -= quantity;\n                        demand[c] -= quantity;\n\n                        if (supply[r] == 0) {\n                            northwest = c;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        static void SteppingStone() {\n            double maxReduction = 0;\n            Shipment[] move = null;\n            Shipment leaving = null;\n\n            FixDegenerateCase();\n\n            for (int r = 0; r < supply.Length; r++) {\n                for (int c = 0; c < demand.Length; c++) {\n                    if (matrix[r, c] != null) {\n                        continue;\n                    }\n\n                    Shipment trial = new Shipment(0, costs[r, c], r, c);\n                    Shipment[] path = GetClosedPath(trial);\n\n                    double reduction = 0;\n                    double lowestQuantity = int.MaxValue;\n                    Shipment leavingCandidate = null;\n\n                    bool plus = true;\n                    foreach (var s in path) {\n                        if (plus) {\n                            reduction += s.CostPerUnit;\n                        } else {\n                            reduction -= s.CostPerUnit;\n                            if (s.Quantity < lowestQuantity) {\n                                leavingCandidate = s;\n                                lowestQuantity = s.Quantity;\n                            }\n                        }\n                        plus = !plus;\n                    }\n                    if (reduction < maxReduction) {\n                        move = path;\n                        leaving = leavingCandidate;\n                        maxReduction = reduction;\n                    }\n                }\n            }\n\n            if (move != null) {\n                double q = leaving.Quantity;\n                bool plus = true;\n                foreach (var s in move) {\n                    s.Quantity += plus ? q : -q;\n                    matrix[s.R, s.C] = s.Quantity == 0 ? null : s;\n                    plus = !plus;\n                }\n                SteppingStone();\n            }\n        }\n\n        static List<Shipment> MatrixToList() {\n            List<Shipment> newList = new List<Shipment>();\n            foreach (var item in matrix) {\n                if (null != item) {\n                    newList.Add(item);\n                }\n            }\n            return newList;\n        }\n\n        static Shipment[] GetClosedPath(Shipment s) {\n            List<Shipment> path = MatrixToList();\n            path.Add(s);\n\n            \n            \n            int before;\n            do {\n                before = path.Count;\n                path.RemoveAll(ship => {\n                    var nbrs = GetNeighbors(ship, path);\n                    return nbrs[0] == null || nbrs[1] == null;\n                });\n            } while (before != path.Count);\n\n            \n            Shipment[] stones = path.ToArray();\n            Shipment prev = s;\n            for (int i = 0; i < stones.Length; i++) {\n                stones[i] = prev;\n                prev = GetNeighbors(prev, path)[i % 2];\n            }\n            return stones;\n        }\n\n        static Shipment[] GetNeighbors(Shipment s, List<Shipment> lst) {\n            Shipment[] nbrs = new Shipment[2];\n            foreach (var o in lst) {\n                if (o != s) {\n                    if (o.R == s.R && nbrs[0] == null) {\n                        nbrs[0] = o;\n                    } else if (o.C == s.C && nbrs[1] == null) {\n                        nbrs[1] = o;\n                    }\n                    if (nbrs[0] != null && nbrs[1] != null) {\n                        break;\n                    }\n                }\n            }\n            return nbrs;\n        }\n\n        static void FixDegenerateCase() {\n            const double eps = double.Epsilon;\n            if (supply.Length + demand.Length - 1 != MatrixToList().Count) {\n                for (int r = 0; r < supply.Length; r++) {\n                    for (int c = 0; c < demand.Length; c++) {\n                        if (matrix[r, c] == null) {\n                            Shipment dummy = new Shipment(eps, costs[r, c], r, c);\n                            if (GetClosedPath(dummy).Length == 0) {\n                                matrix[r, c] = dummy;\n                                return;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        static void PrintResult(string filename) {\n            Console.WriteLine(\"Optimal solution {0}\\n\", filename);\n            double totalCosts = 0;\n\n            for (int r = 0; r < supply.Length; r++) {\n                for (int c = 0; c < demand.Length; c++) {\n                    Shipment s = matrix[r, c];\n                    if (s != null && s.R == r && s.C == c) {\n                        Console.Write(\" {0,3} \", s.Quantity);\n                        totalCosts += (s.Quantity * s.CostPerUnit);\n                    } else {\n                        Console.Write(\"  -  \");\n                    }\n                }\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nTotal costs: {0}\\n\", totalCosts);\n        }\n\n        static void Main() {\n            foreach (var filename in new string[] { \"input1.txt\", \"input2.txt\", \"input3.txt\" }) {\n                Init(filename);\n                NorthWestCornerRule();\n                SteppingStone();\n                PrintResult(filename);\n            }\n        }\n    }\n}\n"}
{"id": 59533, "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": 59534, "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", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 59535, "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", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 59536, "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", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 59537, "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", "Java": "import java.util.Arrays;\nimport java.util.Comparator;\n\npublic class FileExt{\n\tpublic static void main(String[] args){\n\t\tString[] tests = {\"text.txt\", \"text.TXT\", \"test.tar.gz\", \"test/test2.exe\", \"test\\\\test2.exe\", \"test\", \"a/b/c\\\\d/foo\"};\n\t\tString[] exts = {\".txt\",\".gz\",\"\",\".bat\"};\n\t\t\n\t\tSystem.out.println(\"Extensions: \" + Arrays.toString(exts) + \"\\n\");\n\t\t\n\t\tfor(String test:tests){\n\t\t\tSystem.out.println(test +\": \" + extIsIn(test, exts));\n\t\t}\n\t}\n\t\n\tpublic static boolean extIsIn(String test, String... exts){\n\t\tint lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\\\')); \n\t\tString filename = test.substring(lastSlash + 1);\n\t\t\n\t\t\n\t\tint lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');\n\t\tString ext = filename.substring(lastDot);\n\t\t\n\t\tArrays.sort(exts);\n\t\t\n\t\treturn Arrays.binarySearch(exts, ext, new Comparator<String>() { \n\t\t\t@Override                                                \n\t\t\tpublic int compare(String o1, String o2) {\n\t\t\t\treturn o1.compareToIgnoreCase(o2);\n\t\t\t}\n\t\t}) >= 0;\n\t}\n}\n"}
{"id": 59538, "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", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 59539, "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", "Java": "import java.util.*;\n\npublic class Game24Player {\n    final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n        \"nnnnooo\"};\n    final String ops = \"+-*/^\";\n\n    String solution;\n    List<Integer> digits;\n\n    public static void main(String[] args) {\n        new Game24Player().play();\n    }\n\n    void play() {\n        digits = getSolvableDigits();\n\n        Scanner in = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Make 24 using these digits: \");\n            System.out.println(digits);\n            System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n            System.out.print(\"> \");\n\n            String line = in.nextLine();\n            if (line.equalsIgnoreCase(\"q\")) {\n                System.out.println(\"\\nThanks for playing\");\n                return;\n            }\n\n            if (line.equalsIgnoreCase(\"s\")) {\n                System.out.println(solution);\n                digits = getSolvableDigits();\n                continue;\n            }\n\n            char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n            try {\n                validate(entry);\n\n                if (evaluate(infixToPostfix(entry))) {\n                    System.out.println(\"\\nCorrect! Want to try another? \");\n                    digits = getSolvableDigits();\n                } else {\n                    System.out.println(\"\\nNot correct.\");\n                }\n\n            } catch (Exception e) {\n                System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n            }\n        }\n    }\n\n    void validate(char[] input) throws Exception {\n        int total1 = 0, parens = 0, opsCount = 0;\n\n        for (char c : input) {\n            if (Character.isDigit(c))\n                total1 += 1 << (c - '0') * 4;\n            else if (c == '(')\n                parens++;\n            else if (c == ')')\n                parens--;\n            else if (ops.indexOf(c) != -1)\n                opsCount++;\n            if (parens < 0)\n                throw new Exception(\"Parentheses mismatch.\");\n        }\n\n        if (parens != 0)\n            throw new Exception(\"Parentheses mismatch.\");\n\n        if (opsCount != 3)\n            throw new Exception(\"Wrong number of operators.\");\n\n        int total2 = 0;\n        for (int d : digits)\n            total2 += 1 << d * 4;\n\n        if (total1 != total2)\n            throw new Exception(\"Not the same digits.\");\n    }\n\n    boolean evaluate(char[] line) throws Exception {\n        Stack<Float> s = new Stack<>();\n        try {\n            for (char c : line) {\n                if ('0' <= c && c <= '9')\n                    s.push((float) c - '0');\n                else\n                    s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return (Math.abs(24 - s.peek()) < 0.001F);\n    }\n\n    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    List<Integer> randomDigits() {\n        Random r = new Random();\n        List<Integer> result = new ArrayList<>(4);\n        for (int i = 0; i < 4; i++)\n            result.add(r.nextInt(9) + 1);\n        return result;\n    }\n\n    List<Integer> getSolvableDigits() {\n        List<Integer> result;\n        do {\n            result = randomDigits();\n        } while (!isSolvable(result));\n        return result;\n    }\n\n    boolean isSolvable(List<Integer> digits) {\n        Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);\n        permute(digits, dPerms, 0);\n\n        int total = 4 * 4 * 4;\n        List<List<Integer>> oPerms = new ArrayList<>(total);\n        permuteOperators(oPerms, 4, total);\n\n        StringBuilder sb = new StringBuilder(4 + 3);\n\n        for (String pattern : patterns) {\n            char[] patternChars = pattern.toCharArray();\n\n            for (List<Integer> dig : dPerms) {\n                for (List<Integer> opr : oPerms) {\n\n                    int i = 0, j = 0;\n                    for (char c : patternChars) {\n                        if (c == 'n')\n                            sb.append(dig.get(i++));\n                        else\n                            sb.append(ops.charAt(opr.get(j++)));\n                    }\n\n                    String candidate = sb.toString();\n                    try {\n                        if (evaluate(candidate.toCharArray())) {\n                            solution = postfixToInfix(candidate);\n                            return true;\n                        }\n                    } catch (Exception ignored) {\n                    }\n                    sb.setLength(0);\n                }\n            }\n        }\n        return false;\n    }\n\n    String postfixToInfix(String postfix) {\n        class Expression {\n            String op, ex;\n            int prec = 3;\n\n            Expression(String e) {\n                ex = e;\n            }\n\n            Expression(String e1, String e2, String o) {\n                ex = String.format(\"%s %s %s\", e1, o, e2);\n                op = o;\n                prec = ops.indexOf(o) / 2;\n            }\n        }\n\n        Stack<Expression> expr = new Stack<>();\n\n        for (char c : postfix.toCharArray()) {\n            int idx = ops.indexOf(c);\n            if (idx != -1) {\n\n                Expression r = expr.pop();\n                Expression l = expr.pop();\n\n                int opPrec = idx / 2;\n\n                if (l.prec < opPrec)\n                    l.ex = '(' + l.ex + ')';\n\n                if (r.prec <= opPrec)\n                    r.ex = '(' + r.ex + ')';\n\n                expr.push(new Expression(l.ex, r.ex, \"\" + c));\n            } else {\n                expr.push(new Expression(\"\" + c));\n            }\n        }\n        return expr.peek().ex;\n    }\n\n    char[] infixToPostfix(char[] infix) throws Exception {\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n        try {\n            for (char c : infix) {\n                int idx = ops.indexOf(c);\n                if (idx != -1) {\n                    if (s.isEmpty())\n                        s.push(idx);\n                    else {\n                        while (!s.isEmpty()) {\n                            int prec2 = s.peek() / 2;\n                            int prec1 = idx / 2;\n                            if (prec2 >= prec1)\n                                sb.append(ops.charAt(s.pop()));\n                            else\n                                break;\n                        }\n                        s.push(idx);\n                    }\n                } else if (c == '(') {\n                    s.push(-2);\n                } else if (c == ')') {\n                    while (s.peek() != -2)\n                        sb.append(ops.charAt(s.pop()));\n                    s.pop();\n                } else {\n                    sb.append(c);\n                }\n            }\n            while (!s.isEmpty())\n                sb.append(ops.charAt(s.pop()));\n\n        } catch (EmptyStackException e) {\n            throw new Exception(\"Invalid entry.\");\n        }\n        return sb.toString().toCharArray();\n    }\n\n    void permute(List<Integer> lst, Set<List<Integer>> res, int k) {\n        for (int i = k; i < lst.size(); i++) {\n            Collections.swap(lst, i, k);\n            permute(lst, res, k + 1);\n            Collections.swap(lst, k, i);\n        }\n        if (k == lst.size())\n            res.add(new ArrayList<>(lst));\n    }\n\n    void permuteOperators(List<List<Integer>> res, int n, int total) {\n        for (int i = 0, npow = n * n; i < total; i++)\n            res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n    }\n}\n"}
{"id": 59540, "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", "Java": "import java.util.Scanner;\nimport java.util.Random;\n\npublic class CheckpointSync{\n\tpublic static void main(String[] args){\n\t\tSystem.out.print(\"Enter number of workers to use: \");\n\t\tScanner in = new Scanner(System.in);\n\t\tWorker.nWorkers = in.nextInt();\n\t\tSystem.out.print(\"Enter number of tasks to complete:\");\n\t\trunTasks(in.nextInt());\n\t}\n\t\n\t\n\tprivate static void runTasks(int nTasks){\n\t\tfor(int i = 0; i < nTasks; i++){\n\t\t\tSystem.out.println(\"Starting task number \" + (i+1) + \".\");\n\t\t\trunThreads();\n\t\t\tWorker.checkpoint();\n\t\t}\n\t}\n\t\n\t\n\tprivate static void runThreads(){\n\t\tfor(int i = 0; i < Worker.nWorkers; i ++){\n\t\t\tnew Thread(new Worker(i+1)).start();\n\t\t}\n\t}\n\t\n\t\n\tpublic static class Worker implements Runnable{\n\t\tpublic Worker(int threadID){\n\t\t\tthis.threadID = threadID;\n\t\t}\n\t\tpublic void run(){\n\t\t\twork();\n\t\t}\n\t\t\n\t\t\n\t\tprivate synchronized void work(){\n\t\t\ttry {\n\t\t\t\tint workTime = rgen.nextInt(900) + 100;\n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" will work for \" + workTime + \" msec.\");\n\t\t\t\tThread.sleep(workTime); \n\t\t\t\tnFinished++; \n\t\t\t\tSystem.out.println(\"Worker \" + threadID + \" is ready\");\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tpublic static synchronized void checkpoint(){\n\t\t\twhile(nFinished != nWorkers){\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(10);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tSystem.err.println(\"Error: thread execution interrupted\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFinished = 0;\n\t\t}\n\t\n\t\t\n\t\tprivate int threadID;\n\t\t\n\t\t\n\t\tprivate static Random rgen = new Random();\n\t\tprivate static int nFinished = 0;\n\t\tpublic static int nWorkers = 0;\n\t}\n}\n"}
{"id": 59541, "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", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 59542, "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", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 59543, "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", "Java": "import java.io.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class SHA256MerkleTree {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"missing file argument\");\n            System.exit(1);\n        }\n        try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {\n            byte[] digest = sha256MerkleTree(in, 1024);\n            if (digest != null)\n                System.out.println(digestToString(digest));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static String digestToString(byte[] digest) {\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i < digest.length; ++i)\n            result.append(String.format(\"%02x\", digest[i]));\n        return result.toString();\n    }\n\n    private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {\n        byte[] buffer = new byte[blockSize];\n        int bytes;\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        List<byte[]> digests = new ArrayList<>();\n        while ((bytes = in.read(buffer)) > 0) {\n            md.reset();\n            md.update(buffer, 0, bytes);\n            digests.add(md.digest());\n        }\n        int length = digests.size();\n        if (length == 0)\n            return null;\n        while (length > 1) {\n            int j = 0;\n            for (int i = 0; i < length; i += 2, ++j) {\n                byte[] digest1 = digests.get(i);\n                if (i + 1 < length) {\n                    byte[] digest2 = digests.get(i + 1);\n                    md.reset();\n                    md.update(digest1);\n                    md.update(digest2);\n                    digests.set(j, md.digest());\n                } else {\n                    digests.set(j, digest1);\n                }\n            }\n            length = j;\n        }\n        return digests.get(0);\n    }\n}\n"}
{"id": 59544, "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", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 59545, "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", "Java": "import javax.swing.*;\n\npublic class GetInputSwing {\n    public static void main(String[] args) throws Exception {\n        int number = Integer.parseInt(\n                JOptionPane.showInputDialog (\"Enter an Integer\"));\n        String string = JOptionPane.showInputDialog (\"Enter a String\");\n    }\n}\n"}
{"id": 59546, "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", "Java": "final PVector t = new PVector(20, 30, 60);\n\nvoid setup() {\n  size(450, 400);\n  noLoop();\n  background(0, 0, 200);\n  stroke(-1);\n  sc(7, 400, -60, t);\n}\n\nPVector sc(int o, float l, final int a, final PVector s) {\n  if (o > 0) {\n    sc(--o, l *= .5, -a, s).z += a;\n    sc(o, l, a, s).z += a;\n    sc(o, l, -a, s);\n  } else line(s.x, s.y, \n    s.x += cos(radians(s.z)) * l, \n    s.y += sin(radians(s.z)) * l);\n  return s;\n}\n"}
{"id": 59547, "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", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n"}
{"id": 59548, "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", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 59549, "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", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 59550, "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", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 59551, "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", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 59552, "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", "Java": "import java.time.*;\nimport java.time.format.*;\n\nclass Main {  \n  public static void main(String args[]) { \n    String dateStr = \"March 7 2009 7:30pm EST\";\n\n    DateTimeFormatter df = new DateTimeFormatterBuilder()\n\t\t\t\t.parseCaseInsensitive()\n\t\t\t\t.appendPattern(\"MMMM d yyyy h:mma zzz\")\n\t\t\t\t.toFormatter();\n\t\t\n    ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);\n  \n    System.out.println(\"Date: \" + dateStr);\n    System.out.println(\"+12h: \" + after12Hours.format(df));\n\n    ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of(\"CET\"));\n    System.out.println(\"+12h (in Central Europe): \" + after12HoursInCentralEuropeTime.format(df));\n  }\n}\n"}
{"id": 59553, "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", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 59554, "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", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 59555, "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", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 59556, "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", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 59557, "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", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 59558, "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", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 59559, "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", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 59560, "name": "Stack", "Go": "var intStack []int\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 59561, "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", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 59562, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 59563, "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", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n"}
{"id": 59564, "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", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n"}
{"id": 59565, "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", "Java": "import java.util.Arrays;\n\npublic class Stooge {\n    public static void main(String[] args) {\n        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};\n        stoogeSort(nums);\n        System.out.println(Arrays.toString(nums));\n    }\n\n    public static void stoogeSort(int[] L) {\n        stoogeSort(L, 0, L.length - 1);\n    }\n\n    public static void stoogeSort(int[] L, int i, int j) {\n        if (L[j] < L[i]) {\n            int tmp = L[i];\n            L[i] = L[j];\n            L[j] = tmp;\n        }\n        if (j - i > 1) {\n            int t = (j - i + 1) / 3;\n            stoogeSort(L, i, j - t);\n            stoogeSort(L, i + t, j);\n            stoogeSort(L, i, j - t);\n        }\n    }\n}\n"}
{"id": 59566, "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", "Java": "import java.util.Random;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class GaltonBox {\n    public static void main( final String[] args ) {\n        new GaltonBox( 8, 200 ).run();\n    }\n\n    private final int        m_pinRows;\n    private final int        m_startRow;\n    private final Position[] m_balls;\n    private final Random     m_random = new Random();\n\n    public GaltonBox( final int pinRows, final int ballCount ) {\n        m_pinRows  = pinRows;\n        m_startRow = pinRows + 1;\n        m_balls    = new Position[ ballCount ];\n\n        for ( int ball = 0; ball < ballCount; ball++ )\n            m_balls[ ball ] = new Position( m_startRow, 0, 'o' );\n    }\n\n    private static class Position {\n        int  m_row;\n        int  m_col;\n        char m_char;\n\n        Position( final int row, final int col, final char ch ) {\n            m_row  = row;\n            m_col  = col;\n            m_char = ch;\n        }\n    }\n\n    public void run() {\n        for ( int ballsInPlay = m_balls.length; ballsInPlay > 0;  ) {\n            ballsInPlay = dropBalls();\n            print();\n        }\n    }\n\n    private int dropBalls() {\n        int ballsInPlay = 0;\n        int ballToStart = -1;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( m_balls[ ball ].m_row == m_startRow )\n                ballToStart = ball;\n\n        \n        for ( int ball = 0; ball < m_balls.length; ball++ )\n            if ( ball == ballToStart ) {\n                m_balls[ ball ].m_row = m_pinRows;\n                ballsInPlay++;\n            }\n            else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {\n                m_balls[ ball ].m_row -= 1;\n                m_balls[ ball ].m_col += m_random.nextInt( 2 );\n                if ( 0 != m_balls[ ball ].m_row )\n                    ballsInPlay++;\n            }\n\n        return ballsInPlay;\n    }\n\n    private void print() {\n        for ( int row = m_startRow; row --> 1;  ) {\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == row )\n                    printBall( m_balls[ ball ] );\n            System.out.println();\n            printPins( row );\n        }\n        printCollectors();\n        System.out.println();\n    }\n\n    private static void printBall( final Position pos ) {\n        for ( int col = pos.m_row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = 0; col < pos.m_col; col++ )\n            System.out.print( \"  \" );\n        System.out.print( pos.m_char );\n    }\n\n    private void printPins( final int row ) {\n        for ( int col = row + 1; col --> 0;  )\n            System.out.print( ' ' );\n        for ( int col = m_startRow - row; col --> 0;  )\n            System.out.print( \". \" );\n        System.out.println();\n    }\n\n    private void printCollectors() {\n        final List<List<Position>> collectors = new ArrayList<List<Position>>();\n\n        for ( int col = 0; col < m_startRow; col++ ) {\n            final List<Position> collector = new ArrayList<Position>();\n\n            collectors.add( collector );\n            for ( int ball = 0; ball < m_balls.length; ball++ )\n                if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )\n                    collector.add( m_balls[ ball ] );\n        }\n\n        for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {\n            for ( int col = 0; col < m_startRow; col++ ) {\n                final List<Position> collector = collectors.get( col );\n                final int            pos       = row + collector.size() - rows;\n\n                System.out.print( '|' );\n                if ( pos >= 0 )\n                    System.out.print( collector.get( pos ).m_char );\n                else\n                    System.out.print( ' ' );\n            }\n            System.out.println( '|' );\n        }\n    }\n\n    private static final int longest( final List<List<Position>> collectors ) {\n        int result = 0;\n\n        for ( final List<Position> collector : collectors )\n            result = Math.max( collector.size(), result );\n\n        return result;\n    }\n}\n"}
{"id": 59567, "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", "Java": "import java.util.Arrays;\n\npublic class CircleSort {\n\n    public static void main(String[] args) {\n        circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});\n    }\n\n    public static void circleSort(int[] arr) {\n        if (arr.length > 0)\n            do {\n                System.out.println(Arrays.toString(arr));\n            } while (circleSortR(arr, 0, arr.length - 1, 0) != 0);\n    }\n\n    private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {\n        if (lo == hi)\n            return numSwaps;\n\n        int high = hi;\n        int low = lo;\n        int mid = (hi - lo) / 2;\n\n        while (lo < hi) {\n            if (arr[lo] > arr[hi]) {\n                swap(arr, lo, hi);\n                numSwaps++;\n            }\n            lo++;\n            hi--;\n        }\n\n        if (lo == hi && arr[lo] > arr[hi + 1]) {\n            swap(arr, lo, hi + 1);\n            numSwaps++;\n        }\n\n        numSwaps = circleSortR(arr, low, low + mid, numSwaps);\n        numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);\n\n        return numSwaps;\n    }\n\n    private static void swap(int[] arr, int idx1, int idx2) {\n        int tmp = arr[idx1];\n        arr[idx1] = arr[idx2];\n        arr[idx2] = tmp;\n    }\n}\n"}
{"id": 59568, "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", "Java": "package kronecker;\n\n\npublic class ProductFractals {\n  \n  public static int[][] product(final int[][] a, final int[][] b) {\n    \n    \n    final int[][] c = new int[a.length*b.length][];\n    \n    \n    for (int ix = 0; ix < c.length; ix++) {\n      final int num_cols = a[0].length*b[0].length;\n      c[ix] = new int[num_cols];\n    }\n    \n    \n    for (int ia = 0; ia < a.length; ia++) {\n      for (int ja = 0; ja < a[ia].length; ja++) {\n        \n        for (int ib = 0; ib < b.length; ib++) {\n          for (int jb = 0; jb < b[ib].length; jb++) {\n             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];\n          }\n        }\n      }\n    }\n\n    \n    return c;\n  }\n\n  \n  public static void show_matrix(final int[][] m, final char nz, final char z) {\n    for (int im = 0; im < m.length; im++) {\n      for (int jm = 0; jm < m[im].length; jm++) {\n        System.out.print(m[im][jm] == 0 ? z : nz);\n      }\n      System.out.println();\n    }\n  }\n\n  \n  public static int[][] power(final int[][] m, final int n) {\n    \n    int[][] m_pow = m;\n    \n    \n    for (int ix = 1; ix < n; ix++) {\n      m_pow = product(m, m_pow);\n    }\n    return m_pow;\n  }\n\n  \n  private static void test(final int[][] m, final int n) {\n    System.out.println(\"Test matrix\");\n    show_matrix(m, '*', ' ');\n    final int[][] m_pow = power(m, n);\n    System.out.println(\"Matrix power \" + n);\n    show_matrix(m_pow, '*', ' ');\n  }\n\n  \n  private static void test1() {\n    \n    final int[][] m = {{0, 1, 0},\n                       {1, 1, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test2() {\n    \n    final int[][] m = {{1, 1, 1},\n                       {1, 0, 1},\n                       {1, 1, 1}};\n    \n    test(m, 4);\n  }\n\n  \n  private static void test3() {\n    \n    final int[][] m = {{1, 0, 1},\n                       {1, 0, 1},\n                       {0, 1, 0}};\n    \n    test(m, 4);\n  }\n\n  \n  public static void main(final String[] args) {\n    \n    test1();\n    test2();\n    test3();\n  }\n\n}\n"}
{"id": 59569, "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", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 59570, "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", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 59571, "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", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n"}
{"id": 59572, "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", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class CircularPrimes {\n    public static void main(String[] args) {\n        System.out.println(\"First 19 circular primes:\");\n        int p = 2;\n        for (int count = 0; count < 19; ++p) {\n            if (isCircularPrime(p)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.print(p);\n                ++count;\n            }\n        }\n        System.out.println();\n        System.out.println(\"Next 4 circular primes:\");\n        int repunit = 1, digits = 1;\n        for (; repunit < p; ++digits)\n            repunit = 10 * repunit + 1;\n        BigInteger bignum = BigInteger.valueOf(repunit);\n        for (int count = 0; count < 4; ) {\n            if (bignum.isProbablePrime(15)) {\n                if (count > 0)\n                    System.out.print(\", \");\n                System.out.printf(\"R(%d)\", digits);\n                ++count;\n            }\n            ++digits;\n            bignum = bignum.multiply(BigInteger.TEN);\n            bignum = bignum.add(BigInteger.ONE);\n        }\n        System.out.println();\n        testRepunit(5003);\n        testRepunit(9887);\n        testRepunit(15073);\n        testRepunit(25031);\n    }\n\n    private static boolean isPrime(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 (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\n    private static int cycle(int n) {\n        int m = n, p = 1;\n        while (m >= 10) {\n            p *= 10;\n            m /= 10;\n        }\n        return m + 10 * (n % p);\n    }\n\n    private static boolean isCircularPrime(int p) {\n        if (!isPrime(p))\n            return false;\n        int p2 = cycle(p);\n        while (p2 != p) {\n            if (p2 < p || !isPrime(p2))\n                return false;\n            p2 = cycle(p2);\n        }\n        return true;\n    }\n\n    private static void testRepunit(int digits) {\n        BigInteger repunit = repunit(digits);\n        if (repunit.isProbablePrime(15))\n            System.out.printf(\"R(%d) is probably prime.\\n\", digits);\n        else\n            System.out.printf(\"R(%d) is not prime.\\n\", digits);\n    }\n\n    private static BigInteger repunit(int digits) {\n        char[] ch = new char[digits];\n        Arrays.fill(ch, '1');\n        return new BigInteger(new String(ch));\n    }\n}\n"}
{"id": 59573, "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", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 59574, "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", "Java": "public static int[] sort(int[] old) {\n    \n    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {\n        \n        int[] tmp = new int[old.length];\n        \n        int j = 0;\n\n        \n        for (int i = 0; i < old.length; i++) {\n            \n            boolean move = old[i] << shift >= 0;\n\n            \n            if (shift == 0 ? !move : move) {\n                tmp[j] = old[i];\n                j++;\n            } else {\n                \n                old[i - j] = old[i];\n            }\n        }\n\n        \n        for (int i = j; i < tmp.length; i++) {\n            tmp[i] = old[i - j];\n        }\n\n        \n        old = tmp;\n    }\n\n    return old;\n}\n"}
{"id": 59575, "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", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n"}
{"id": 59576, "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", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 59577, "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", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 59578, "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", "Java": "public class JacobiSymbol {\n\n    public static void main(String[] args) {\n        int max = 30;\n        System.out.printf(\"n\\\\k \");\n        for ( int k = 1 ; k <= max ; k++ ) {\n            System.out.printf(\"%2d  \", k);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 1 ; n <= max ; n += 2 ) {\n            System.out.printf(\"%2d  \", n);\n            for ( int k = 1 ; k <= max ; k++ ) {\n                System.out.printf(\"%2d  \", jacobiSymbol(k, n));\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    \n    \n    private static int jacobiSymbol(int k, int n) {\n        if ( k < 0 || n % 2 == 0 ) {\n            throw new IllegalArgumentException(\"Invalid value. k = \" + k + \", n = \" + n);\n        }\n        k %= n;\n        int jacobi = 1;\n        while ( k > 0 ) {\n            while ( k % 2 == 0 ) {\n                k /= 2;\n                int r = n % 8;\n                if ( r == 3 || r == 5 ) {\n                    jacobi = -jacobi;\n                }\n            }\n            int temp = n;\n            n = k;\n            k = temp;\n            if ( k % 4 == 3 && n % 4 == 3 ) {\n                jacobi = -jacobi;\n            }\n            k %= n;\n        }\n        if ( n == 1 ) {\n            return jacobi;\n        }\n        return 0;\n    }\n\n}\n"}
{"id": 59579, "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", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 59580, "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", "Java": "import java.util.*;\n\npublic class KdTree {\n    private int dimensions_;\n    private Node root_ = null;\n    private Node best_ = null;\n    private double bestDistance_ = 0;\n    private int visited_ = 0;\n    \n    public KdTree(int dimensions, List<Node> nodes) {\n        dimensions_ = dimensions;\n        root_ = makeTree(nodes, 0, nodes.size(), 0);\n    }\n    \n    public Node findNearest(Node target) {\n        if (root_ == null)\n            throw new IllegalStateException(\"Tree is empty!\");\n        best_ = null;\n        visited_ = 0;\n        bestDistance_ = 0;\n        nearest(root_, target, 0);\n        return best_;\n    }\n    \n    public int visited() {\n        return visited_;\n    }\n    \n    public double distance() {\n        return Math.sqrt(bestDistance_);\n    }\n    \n    private void nearest(Node root, Node target, int index) {\n        if (root == null)\n            return;\n        ++visited_;\n        double d = root.distance(target);\n        if (best_ == null || d < bestDistance_) {\n            bestDistance_ = d;\n            best_ = root;\n        }\n        if (bestDistance_ == 0)\n            return;\n        double dx = root.get(index) - target.get(index);\n        index = (index + 1) % dimensions_;\n        nearest(dx > 0 ? root.left_ : root.right_, target, index);\n        if (dx * dx >= bestDistance_)\n            return;\n        nearest(dx > 0 ? root.right_ : root.left_, target, index);\n    }\n    \n    private Node makeTree(List<Node> nodes, int begin, int end, int index) {\n        if (end <= begin)\n            return null;\n        int n = begin + (end - begin)/2;\n        Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));\n        index = (index + 1) % dimensions_;\n        node.left_ = makeTree(nodes, begin, n, index);\n        node.right_ = makeTree(nodes, n + 1, end, index);\n        return node;\n    }\n    \n    private static class NodeComparator implements Comparator<Node> {\n        private int index_;\n\n        private NodeComparator(int index) {\n            index_ = index;\n        }\n        public int compare(Node n1, Node n2) {\n            return Double.compare(n1.get(index_), n2.get(index_));\n        }\n    }\n    \n    public static class Node {\n        private double[] coords_;\n        private Node left_ = null;\n        private Node right_ = null;\n\n        public Node(double[] coords) {\n            coords_ = coords;\n        }\n        public Node(double x, double y) {\n            this(new double[]{x, y});\n        }\n        public Node(double x, double y, double z) {\n            this(new double[]{x, y, z});\n        }\n        double get(int index) {\n            return coords_[index];\n        }\n        double distance(Node node) {\n            double dist = 0;\n            for (int i = 0; i < coords_.length; ++i) {\n                double d = coords_[i] - node.coords_[i];\n                dist += d * d;\n            }\n            return dist;\n        }\n        public String toString() {\n            StringBuilder s = new StringBuilder(\"(\");\n            for (int i = 0; i < coords_.length; ++i) {\n                if (i > 0)\n                    s.append(\", \");\n                s.append(coords_[i]);\n            }\n            s.append(')');\n            return s.toString();\n        }\n    }\n}\n"}
{"id": 59581, "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", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 59582, "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", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 59583, "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", "Java": "class Singleton\n{\n    private static Singleton myInstance;\n    public static Singleton getInstance()\n    {\n        if (myInstance == null)\n        {\n            synchronized(Singleton.class)\n            {\n                if (myInstance == null)\n                {\n                    myInstance = new Singleton();\n                }\n            }\n        }\n\n        return myInstance;\n    }\n\n    protected Singleton()\n    {\n        \n    }\n\n    \n}\n"}
{"id": 59584, "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", "Java": "public class SafeAddition {\n    private static double stepDown(double d) {\n        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);\n    }\n\n    private static double stepUp(double d) {\n        return Math.nextUp(d);\n    }\n\n    private static double[] safeAdd(double a, double b) {\n        return new double[]{stepDown(a + b), stepUp(a + b)};\n    }\n\n    public static void main(String[] args) {\n        double a = 1.2;\n        double b = 0.03;\n        double[] result = safeAdd(a, b);\n        System.out.printf(\"(%.2f + %.2f) is in the range %.16f..%.16f\", a, b, result[0], result[1]);\n    }\n}\n"}
{"id": 59585, "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", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 59586, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 59587, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 59588, "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", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 59589, "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", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 59590, "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", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PalindromicGapfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 20 palindromic gapful numbers ending in:\");\n        displayMap(getPalindromicGapfulEnding(20, 20));\n\n        System.out.printf(\"%nLast 15 of first 100 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(15, 100));\n\n        System.out.printf(\"%nLast 10 of first 1000 palindromic gapful numbers ending in:%n\");\n        displayMap(getPalindromicGapfulEnding(10, 1000));\n    }\n    \n    private static void displayMap(Map<Integer,List<Long>> map) {\n        for ( int key = 1 ; key <= 9 ; key++ ) {\n            System.out.println(key + \" : \" + map.get(key));\n        }\n    }\n    \n    public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {\n        Map<Integer,List<Long>> map = new HashMap<>();\n        Map<Integer,Integer> mapCount = new HashMap<>();\n        for ( int i = 1 ; i <= 9 ; i++ ) {\n            map.put(i, new ArrayList<>());\n            mapCount.put(i, 0);\n        }\n        boolean notPopulated = true;\n        for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {\n            if ( isGapful(n) ) {\n                int index = (int) (n % 10);\n                if ( mapCount.get(index) < firstHowMany ) {\n                    map.get(index).add(n);\n                    mapCount.put(index, mapCount.get(index) + 1);\n                    if ( map.get(index).size() > countReturned ) {\n                        map.get(index).remove(0);\n                    }\n                }\n                boolean finished = true;\n                for ( int i = 1 ; i <= 9 ; i++ ) {\n                    if ( mapCount.get(i) < firstHowMany ) {\n                        finished = false;\n                        break;\n                    }\n                }\n                if ( finished ) {\n                    notPopulated = false;\n                }\n            }\n        }\n        return map;\n    }\n    \n    public static boolean isGapful(long n) {\n        String s = Long.toString(n);\n        return n % Long.parseLong(\"\" + s.charAt(0) + s.charAt(s.length()-1)) == 0;\n    }\n    \n    public static int length(long n) {\n        int length = 0;\n        while ( n > 0 ) {\n            length += 1;\n            n /= 10;\n        }\n        return length;\n    }\n    \n    public static long nextPalindrome(long n) {\n        int length = length(n);\n        if ( length % 2 == 0 ) {\n            length /= 2;\n            while ( length > 0 ) {\n                n /= 10;\n                length--;\n            }\n            n += 1;\n            if ( powerTen(n) ) {\n                return Long.parseLong(n + reverse(n/10));\n            }\n            return Long.parseLong(n + reverse(n));\n        }\n        length = (length - 1) / 2;\n        while ( length > 0 ) {\n            n /= 10;\n            length--;\n        }\n        n += 1;\n        if ( powerTen(n) ) {\n            return Long.parseLong(n + reverse(n/100));\n        }\n        return Long.parseLong(n + reverse(n/10));\n    }\n    \n    private static boolean powerTen(long n) {\n        while ( n > 9 && n % 10 == 0 ) {\n            n /= 10;\n        }\n        return n == 1;\n    }\n        \n    private static String reverse(long n) {\n        return (new StringBuilder(n + \"\")).reverse().toString();\n    }\n\n}\n"}
{"id": 59591, "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", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 59592, "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", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 59593, "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", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n"}
{"id": 59594, "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", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class FibonacciWordFractal extends JPanel {\n    String wordFractal;\n\n    FibonacciWordFractal(int n) {\n        setPreferredSize(new Dimension(450, 620));\n        setBackground(Color.white);\n        wordFractal = wordFractal(n);\n    }\n\n    public String wordFractal(int n) {\n        if (n < 2)\n            return n == 1 ? \"1\" : \"\";\n\n        \n        StringBuilder f1 = new StringBuilder(\"1\");\n        StringBuilder f2 = new StringBuilder(\"0\");\n\n        for (n = n - 2; n > 0; n--) {\n            String tmp = f2.toString();\n            f2.append(f1);\n\n            f1.setLength(0);\n            f1.append(tmp);\n        }\n\n        return f2.toString();\n    }\n\n    void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {\n        for (int n = 0; n < wordFractal.length(); n++) {\n            g.drawLine(x, y, x + dx, y + dy);\n            x += dx;\n            y += dy;\n            if (wordFractal.charAt(n) == '0') {\n                int tx = dx;\n                dx = (n % 2 == 0) ? -dy : dy;\n                dy = (n % 2 == 0) ? tx : -tx;\n            }\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        drawWordFractal(g, 20, 20, 1, 0);\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(\"Fibonacci Word Fractal\");\n            f.setResizable(false);\n            f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59595, "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", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 59596, "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", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 59597, "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", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 59598, "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", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 59599, "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", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 59600, "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", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 59601, "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", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 59602, "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", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 59603, "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", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 59604, "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", "Java": "public class ProductOfDivisors {\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    private static long divisorProduct(long n) {\n        return (long) Math.pow(n, divisorCount(n) / 2.0);\n    }\n\n    public static void main(String[] args) {\n        final long limit = 50;\n        System.out.printf(\"Product of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; n++) {\n            System.out.printf(\"%11d\", divisorProduct(n));\n            if (n % 5 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 59605, "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", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 59606, "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", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 59607, "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", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 59608, "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", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 59609, "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", "Java": "import java.util.function.DoubleSupplier;\n\npublic class ManOrBoy {\n    \n    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,\n                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {\n        \n        DoubleSupplier B = new DoubleSupplier() {\n            int m = k;\n            public double getAsDouble() {\n                return A(--m, this, x1, x2, x3, x4);\n            }\n        };\n                \n        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();\n    }\n    \n    public static void main(String[] args) {\n        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));\n    }\n}\n"}
{"id": 59610, "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", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 59611, "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", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 59612, "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", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 59613, "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", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 59614, "name": "Carmichael 3 strong pseudoprimes", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n", "Java": "public class Test {\n\n    static int mod(int n, int m) {\n        return ((n % m) + m) % m;\n    }\n\n    static boolean isPrime(int n) {\n        if (n == 2 || n == 3)\n            return true;\n        else if (n < 2 || n % 2 == 0 || n % 3 == 0)\n            return false;\n        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;\n                div += inc, inc = 6 - inc)\n            if (n % div == 0)\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        for (int p = 2; p < 62; p++) {\n            if (!isPrime(p))\n                continue;\n            for (int h3 = 2; h3 < p; h3++) {\n                int g = h3 + p;\n                for (int d = 1; d < g; d++) {\n                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)\n                        continue;\n                    int q = 1 + (p - 1) * g / d;\n                    if (!isPrime(q))\n                        continue;\n                    int r = 1 + (p * q / h3);\n                    if (!isPrime(r) || (q * r) % (p - 1) != 1)\n                        continue;\n                    System.out.printf(\"%d x %d x %d%n\", p, q, r);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59615, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 59616, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 59617, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 59618, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 59619, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 59620, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n    private static final int SIZE = 15;\n    private final char[][] canvas = new char[SIZE][SIZE];\n\n    public Cistercian(int n) {\n        initN();\n        draw(n);\n    }\n\n    public void initN() {\n        for (var row : canvas) {\n            Arrays.fill(row, ' ');\n            row[5] = 'x';\n        }\n    }\n\n    private void horizontal(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void vertical(int r1, int r2, int c) {\n        for (int r = r1; r <= r2; r++) {\n            canvas[r][c] = 'x';\n        }\n    }\n\n    private void diagd(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r + c - c1][c] = 'x';\n        }\n    }\n\n    private void diagu(int c1, int c2, int r) {\n        for (int c = c1; c <= c2; c++) {\n            canvas[r - c + c1][c] = 'x';\n        }\n    }\n\n    private void draw(int v) {\n        var thousands = v / 1000;\n        v %= 1000;\n\n        var hundreds = v / 100;\n        v %= 100;\n\n        var tens = v / 10;\n        var ones = v % 10;\n\n        drawPart(1000 * thousands);\n        drawPart(100 * hundreds);\n        drawPart(10 * tens);\n        drawPart(ones);\n    }\n\n    private void drawPart(int v) {\n        switch (v) {\n            case 1:\n                horizontal(6, 10, 0);\n                break;\n            case 2:\n                horizontal(6, 10, 4);\n                break;\n            case 3:\n                diagd(6, 10, 0);\n                break;\n            case 4:\n                diagu(6, 10, 4);\n                break;\n            case 5:\n                drawPart(1);\n                drawPart(4);\n                break;\n            case 6:\n                vertical(0, 4, 10);\n                break;\n            case 7:\n                drawPart(1);\n                drawPart(6);\n                break;\n            case 8:\n                drawPart(2);\n                drawPart(6);\n                break;\n            case 9:\n                drawPart(1);\n                drawPart(8);\n                break;\n\n            case 10:\n                horizontal(0, 4, 0);\n                break;\n            case 20:\n                horizontal(0, 4, 4);\n                break;\n            case 30:\n                diagu(0, 4, 4);\n                break;\n            case 40:\n                diagd(0, 4, 0);\n                break;\n            case 50:\n                drawPart(10);\n                drawPart(40);\n                break;\n            case 60:\n                vertical(0, 4, 0);\n                break;\n            case 70:\n                drawPart(10);\n                drawPart(60);\n                break;\n            case 80:\n                drawPart(20);\n                drawPart(60);\n                break;\n            case 90:\n                drawPart(10);\n                drawPart(80);\n                break;\n\n            case 100:\n                horizontal(6, 10, 14);\n                break;\n            case 200:\n                horizontal(6, 10, 10);\n                break;\n            case 300:\n                diagu(6, 10, 14);\n                break;\n            case 400:\n                diagd(6, 10, 10);\n                break;\n            case 500:\n                drawPart(100);\n                drawPart(400);\n                break;\n            case 600:\n                vertical(10, 14, 10);\n                break;\n            case 700:\n                drawPart(100);\n                drawPart(600);\n                break;\n            case 800:\n                drawPart(200);\n                drawPart(600);\n                break;\n            case 900:\n                drawPart(100);\n                drawPart(800);\n                break;\n\n            case 1000:\n                horizontal(0, 4, 14);\n                break;\n            case 2000:\n                horizontal(0, 4, 10);\n                break;\n            case 3000:\n                diagd(0, 4, 10);\n                break;\n            case 4000:\n                diagu(0, 4, 14);\n                break;\n            case 5000:\n                drawPart(1000);\n                drawPart(4000);\n                break;\n            case 6000:\n                vertical(10, 14, 0);\n                break;\n            case 7000:\n                drawPart(1000);\n                drawPart(6000);\n                break;\n            case 8000:\n                drawPart(2000);\n                drawPart(6000);\n                break;\n            case 9000:\n                drawPart(1000);\n                drawPart(8000);\n                break;\n\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        for (var row : canvas) {\n            builder.append(row);\n            builder.append('\\n');\n        }\n        return builder.toString();\n    }\n\n    public static void main(String[] args) {\n        for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n            System.out.printf(\"%d:\\n\", number);\n            var c = new Cistercian(number);\n            System.out.println(c);\n        }\n    }\n}\n"}
{"id": 59621, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 59622, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 59623, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 59624, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "Java": "package org.rosettacode;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class InvertedIndex {\n\n    List<String> stopwords = Arrays.asList(\"a\", \"able\", \"about\",\n            \"across\", \"after\", \"all\", \"almost\", \"also\", \"am\", \"among\", \"an\",\n            \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"because\", \"been\", \"but\",\n            \"by\", \"can\", \"cannot\", \"could\", \"dear\", \"did\", \"do\", \"does\",\n            \"either\", \"else\", \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\",\n            \"had\", \"has\", \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\",\n            \"however\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\",\n            \"least\", \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n            \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"often\",\n            \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\", \"said\", \"say\",\n            \"says\", \"she\", \"should\", \"since\", \"so\", \"some\", \"than\", \"that\",\n            \"the\", \"their\", \"them\", \"then\", \"there\", \"these\", \"they\", \"this\",\n            \"tis\", \"to\", \"too\", \"twas\", \"us\", \"wants\", \"was\", \"we\", \"were\",\n            \"what\", \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\",\n            \"will\", \"with\", \"would\", \"yet\", \"you\", \"your\");\n\n    Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();\n    List<String> files = new ArrayList<String>();\n\n    public void indexFile(File file) throws IOException {\n        int fileno = files.indexOf(file.getPath());\n        if (fileno == -1) {\n            files.add(file.getPath());\n            fileno = files.size() - 1;\n        }\n\n        int pos = 0;\n        BufferedReader reader = new BufferedReader(new FileReader(file));\n        for (String line = reader.readLine(); line != null; line = reader\n                .readLine()) {\n            for (String _word : line.split(\"\\\\W+\")) {\n                String word = _word.toLowerCase();\n                pos++;\n                if (stopwords.contains(word))\n                    continue;\n                List<Tuple> idx = index.get(word);\n                if (idx == null) {\n                    idx = new LinkedList<Tuple>();\n                    index.put(word, idx);\n                }\n                idx.add(new Tuple(fileno, pos));\n            }\n        }\n        System.out.println(\"indexed \" + file.getPath() + \" \" + pos + \" words\");\n    }\n\n    public void search(List<String> words) {\n        for (String _word : words) {\n            Set<String> answer = new HashSet<String>();\n            String word = _word.toLowerCase();\n            List<Tuple> idx = index.get(word);\n            if (idx != null) {\n                for (Tuple t : idx) {\n                    answer.add(files.get(t.fileno));\n                }\n            }\n            System.out.print(word);\n            for (String f : answer) {\n                System.out.print(\" \" + f);\n            }\n            System.out.println(\"\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            InvertedIndex idx = new InvertedIndex();\n            for (int i = 1; i < args.length; i++) {\n                idx.indexFile(new File(args[i]));\n            }\n            idx.search(Arrays.asList(args[0].split(\",\")));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private class Tuple {\n        private int fileno;\n        private int position;\n\n        public Tuple(int fileno, int position) {\n            this.fileno = fileno;\n            this.position = position;\n        }\n    }\n}\n"}
{"id": 59625, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 59626, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 59627, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 59628, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 59629, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 59630, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 59631, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "Java": "import java.io.FileWriter;\nimport java.io.IOException;\n \npublic class LinePrinter {\n  public static void main(String[] args) {\n    try {\n      FileWriter lp0 = new FileWriter(\"/dev/lp0\");\n      lp0.write(\"Hello World!\");\n      lp0.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n    }\n  }\n}\n"}
{"id": 59632, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n"}
{"id": 59633, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 59634, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 59635, "name": "Jaro similarity", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n"}
{"id": 59636, "name": "Sum and product puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n", "Java": "package org.rosettacode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\npublic class SumAndProductPuzzle {\n    private final long beginning;\n    private final int maxSum;\n    private static final int MIN_VALUE = 2;\n    private List<int[]> firstConditionExcludes = new ArrayList<>();\n    private List<int[]> secondConditionExcludes = new ArrayList<>();\n    \n    public static void main(String... args){\n        \n        if (args.length == 0){\n            new SumAndProductPuzzle(100).run();\n            new SumAndProductPuzzle(1684).run();\n            new SumAndProductPuzzle(1685).run();\n        } else {\n            for (String arg : args){\n                try{\n                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();\n                } catch (NumberFormatException e){\n                    System.out.println(\"Please provide only integer arguments. \" +\n                            \"Provided argument \" + arg + \" was not an integer. \" +\n                            \"Alternatively, calling the program with no arguments \" +\n                            \"will run the puzzle where maximum sum equals 100, 1684, and 1865.\");\n                }\n            }\n        }\n    }\n    \n    public SumAndProductPuzzle(int maxSum){\n        this.beginning = System.currentTimeMillis();\n        this.maxSum = maxSum;\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" started at \" + String.valueOf(beginning) + \".\");\n    }\n    \n    public void run(){\n        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){\n            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){\n                \n                if (isSumNoGreaterThanMax(x,y) &&\n                    isSKnowsPCannotKnow(x,y) &&\n                    isPKnowsNow(x,y) &&\n                    isSKnowsNow(x,y)\n                    ){\n                    System.out.println(\"Found solution x is \" + String.valueOf(x) + \" y is \" + String.valueOf(y) + \n                            \" in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n                }\n            }\n        }\n        System.out.println(\"Run with maximum sum of \" + String.valueOf(maxSum) + \n                \" ended in \" + String.valueOf(System.currentTimeMillis() - beginning) + \"ms.\");\n    }\n    \n    public boolean isSumNoGreaterThanMax(int x, int y){\n        return x + y <= maxSum;\n    }\n    \n    public boolean isSKnowsPCannotKnow(int x, int y){\n        \n        if (firstConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        for (int[] addends : sumAddends(x, y)){\n            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {\n                firstConditionExcludes.add(new int[] {x, y});\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    public boolean isPKnowsNow(int x, int y){\n        \n        if (secondConditionExcludes.contains(new int[] {x, y})){\n            return false;\n        }\n        \n        int countSolutions = 0;\n        for (int[] factors : productFactors(x, y)){\n            if (isSKnowsPCannotKnow(factors[0], factors[1])){\n                countSolutions++;\n            }\n        }\n        \n        if (countSolutions == 1){\n            return true;\n        } else {\n            secondConditionExcludes.add(new int[] {x, y});\n            return false;\n        }\n    }\n    \n    public boolean isSKnowsNow(int x, int y){\n        \n        int countSolutions = 0;\n        for (int[] addends : sumAddends(x, y)){\n            if (isPKnowsNow(addends[0], addends[1])){\n                countSolutions++;\n            }\n        }\n        return countSolutions == 1;\n    }\n    \n    public List<int[]> sumAddends(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int sum = x + y;\n        \n        for (int addend = MIN_VALUE; addend < sum - addend; addend++){\n            if (isSumNoGreaterThanMax(addend, sum - addend)){\n                list.add(new int[]{addend, sum - addend});\n            }\n        }\n        return list;\n    }\n    \n    public List<int[]> productFactors(int x, int y){\n        \n        List<int[]> list = new ArrayList<>();\n        int product = x * y;\n        \n        for (int factor = MIN_VALUE; factor < product / factor; factor++){\n            if (product % factor == 0){\n                if (isSumNoGreaterThanMax(factor, product / factor)){\n                    list.add(new int[]{factor, product / factor});\n                }\n            }\n        }\n        return list;\n    }\n}\n"}
{"id": 59637, "name": "Fairshare between two and more", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 59638, "name": "Fairshare between two and more", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 59639, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 59640, "name": "Prime triangle", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n"}
{"id": 59641, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 59642, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 59643, "name": "Sequence_ nth number with exactly n divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SequenceNthNumberWithExactlyNDivisors {\n\n    public static void main(String[] args) {\n        int max = 45;\n        smallPrimes(max);\n        for ( int n = 1; n <= max ; n++ ) {\n            System.out.printf(\"A073916(%d) = %s%n\", n, OEISA073916(n));\n        }\n    }\n    \n    private static List<Integer> smallPrimes = new ArrayList<>();\n    \n    private static void smallPrimes(int numPrimes) {\n        smallPrimes.add(2);\n        for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {\n            if ( isPrime(n) ) {\n                smallPrimes.add(n);\n                count++;\n            }\n        }\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\n        for ( long d = 3 ; d*d <= test ; d += 2 ) {\n            if ( test % d == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static int getDivisorCount(long n) {\n        int count = 1;\n        while ( n % 2 == 0 ) {\n            n /= 2;\n            count += 1;\n        }\n        for ( long d = 3 ; d*d <= n ; d += 2 ) {\n            long q = n / d;\n            long r = n % d;\n            int dc = 0;\n            while ( r == 0 ) {\n                dc += count;\n                n = q;\n                q = n / d;\n                r = n % d;\n            }\n            count += dc;\n        }\n        if ( n != 1 ) {\n            count *= 2;\n        }\n        return count;\n    }\n    \n    private static BigInteger OEISA073916(int n) {\n        if ( isPrime(n) ) {\n            return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);\n        }\n        int count = 0;\n        int result = 0;\n        for ( int i = 1 ; count < n ; i++ ) {\n            if ( n % 2 == 1 ) {\n                \n                int sqrt = (int) Math.sqrt(i);\n                if ( sqrt*sqrt != i ) {\n                    continue;\n                }\n            }\n            if ( getDivisorCount(i) == n ) {\n                count++;\n                result = i;\n            }\n        }\n        return BigInteger.valueOf(result);\n    }\n\n}\n"}
{"id": 59644, "name": "Sequence_ smallest number with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n", "Java": "import java.util.Arrays;\n\npublic class OEIS_A005179 {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        int[] seq = new int[max];\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, n = 0; n < max; ++i) {\n            int k = count_divisors(i);\n            if (k <= max && seq[k - 1] == 0) {        \n                seq[k- 1] = i;\n                n++;\n            }\n        }\n        System.out.println(Arrays.toString(seq));\n    }\n}\n"}
{"id": 59645, "name": "Pancake numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n", "Java": "public class Pancake {\n    private static int pancake(int n) {\n        int gap = 2;\n        int sum = 2;\n        int adj = -1;\n        while (sum < n) {\n            adj++;\n            gap = 2 * gap - 1;\n            sum += gap;\n        }\n        return n + adj;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 4; i++) {\n            for (int j = 1; j < 6; j++) {\n                int n = 5 * i + j;\n                System.out.printf(\"p(%2d) = %2d  \", n, pancake(n));\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59646, "name": "Generate random chess position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n", "Java": "import static java.lang.Math.abs;\nimport java.util.Random;\n\npublic class Fen {\n    static Random rand = new Random();\n\n    public static void main(String[] args) {\n        System.out.println(createFen());\n    }\n\n    static String createFen() {\n        char[][] grid = new char[8][8];\n\n        placeKings(grid);\n        placePieces(grid, \"PPPPPPPP\", true);\n        placePieces(grid, \"pppppppp\", true);\n        placePieces(grid, \"RNBQBNR\", false);\n        placePieces(grid, \"rnbqbnr\", false);\n\n        return toFen(grid);\n    }\n\n    static void placeKings(char[][] grid) {\n        int r1, c1, r2, c2;\n        while (true) {\n            r1 = rand.nextInt(8);\n            c1 = rand.nextInt(8);\n            r2 = rand.nextInt(8);\n            c2 = rand.nextInt(8);\n            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)\n                break;\n        }\n        grid[r1][c1] = 'K';\n        grid[r2][c2] = 'k';\n    }\n\n    static void placePieces(char[][] grid, String pieces, boolean isPawn) {\n        int numToPlace = rand.nextInt(pieces.length());\n        for (int n = 0; n < numToPlace; n++) {\n            int r, c;\n            do {\n                r = rand.nextInt(8);\n                c = rand.nextInt(8);\n\n            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n\n            grid[r][c] = pieces.charAt(n);\n        }\n    }\n\n    static String toFen(char[][] grid) {\n        StringBuilder fen = new StringBuilder();\n        int countEmpty = 0;\n        for (int r = 0; r < 8; r++) {\n            for (int c = 0; c < 8; c++) {\n                char ch = grid[r][c];\n                System.out.printf(\"%2c \", ch == 0 ? '.' : ch);\n                if (ch == 0) {\n                    countEmpty++;\n                } else {\n                    if (countEmpty > 0) {\n                        fen.append(countEmpty);\n                        countEmpty = 0;\n                    }\n                    fen.append(ch);\n                }\n            }\n            if (countEmpty > 0) {\n                fen.append(countEmpty);\n                countEmpty = 0;\n            }\n            fen.append(\"/\");\n            System.out.println();\n        }\n        return fen.append(\" w - - 0 1\").toString();\n    }\n}\n"}
{"id": 59647, "name": "Esthetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n    interface RecTriConsumer<A, B, C> {\n        void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);\n    }\n\n    private static boolean isEsthetic(long n, long b) {\n        if (n == 0) {\n            return false;\n        }\n        var i = n % b;\n        var n2 = n / b;\n        while (n2 > 0) {\n            var j = n2 % b;\n            if (Math.abs(i - j) != 1) {\n                return false;\n            }\n            n2 /= b;\n            i = j;\n        }\n        return true;\n    }\n\n    private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n        var esths = new ArrayList<Long>();\n        var dfs = new RecTriConsumer<Long, Long, Long>() {\n            public void accept(Long n, Long m, Long i) {\n                accept(this, n, m, i);\n            }\n\n            @Override\n            public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {\n                if (n <= i && i <= m) {\n                    esths.add(i);\n                }\n                if (i == 0 || i > m) {\n                    return;\n                }\n                var d = i % 10;\n                var i1 = i * 10 + d - 1;\n                var i2 = i1 + 2;\n                if (d == 0) {\n                    f.accept(f, n, m, i2);\n                } else if (d == 9) {\n                    f.accept(f, n, m, i1);\n                } else {\n                    f.accept(f, n, m, i1);\n                    f.accept(f, n, m, i2);\n                }\n            }\n        };\n\n        LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n        var le = esths.size();\n        System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n        if (all) {\n            for (int i = 0; i < esths.size(); i++) {\n                System.out.printf(\"%d \", esths.get(i));\n                if ((i + 1) % perLine == 0) {\n                    System.out.println();\n                }\n            }\n        } else {\n            for (int i = 0; i < perLine; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n            System.out.println();\n            System.out.println(\"............\");\n            for (int i = le - perLine; i < le; i++) {\n                System.out.printf(\"%d \", esths.get(i));\n            }\n        }\n        System.out.println();\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        IntStream.rangeClosed(2, 16).forEach(b -> {\n            System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n            var n = 1L;\n            var c = 0L;\n            while (c < 6 * b) {\n                if (isEsthetic(n, b)) {\n                    c++;\n                    if (c >= 4 * b) {\n                        System.out.printf(\"%s \", Long.toString(n, b));\n                    }\n                }\n                n++;\n            }\n            System.out.println();\n        });\n        System.out.println();\n\n        \n        listEsths(1000, 1010, 9999, 9898, 16, true);\n        listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n        listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n        listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n        listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n    }\n}\n"}
{"id": 59648, "name": "Topswops", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n", "Java": "public class Topswops {\n    static final int maxBest = 32;\n    static int[] best;\n\n    static private void trySwaps(int[] deck, int f, int d, int n) {\n        if (d > best[n])\n            best[n] = d;\n\n        for (int i = n - 1; i >= 0; i--) {\n            if (deck[i] == -1 || deck[i] == i)\n                break;\n            if (d + best[i] <= best[n])\n                return;\n        }\n\n        int[] deck2 = deck.clone();\n        for (int i = 1; i < n; i++) {\n            final int k = 1 << i;\n            if (deck2[i] == -1) {\n                if ((f & k) != 0)\n                    continue;\n            } else if (deck2[i] != i)\n                continue;\n\n            deck2[0] = i;\n            for (int j = i - 1; j >= 0; j--)\n                deck2[i - j] = deck[j]; \n            trySwaps(deck2, f | k, d + 1, n);\n        }\n    }\n\n    static int topswops(int n) {\n        assert(n > 0 && n < maxBest);\n        best[n] = 0;\n        int[] deck0 = new int[n + 1];\n        for (int i = 1; i < n; i++)\n            deck0[i] = -1;\n        trySwaps(deck0, 1, 0, n);\n        return best[n];\n    }\n\n    public static void main(String[] args) {\n        best = new int[maxBest];\n        for (int i = 1; i < 11; i++)\n            System.out.println(i + \": \" + topswops(i));\n    }\n}\n"}
{"id": 59649, "name": "Old Russian measure of length", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n", "Java": "public class OldRussianMeasures {\n\n    final static String[] keys = {\"tochka\", \"liniya\", \"centimeter\", \"diuym\",\n        \"vershok\", \"piad\", \"fut\", \"arshin\", \"meter\", \"sazhen\", \"kilometer\",\n        \"versta\", \"milia\"};\n\n    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,\n        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,\n        1066.8, 7467.6};\n\n    public static void main(String[] a) {\n        if (a.length == 2 && a[0].matches(\"[+-]?\\\\d*(\\\\.\\\\d+)?\")) {\n            double inputVal = lookup(a[1]);\n            if (!Double.isNaN(inputVal)) {\n                double magnitude = Double.parseDouble(a[0]);\n                double meters = magnitude * inputVal;\n                System.out.printf(\"%s %s to: %n%n\", a[0], a[1]);\n                for (String k: keys)\n                    System.out.printf(\"%10s: %g%n\", k, meters / lookup(k));\n                return;\n            }\n        }\n        System.out.println(\"Please provide a number and unit\");\n\n    }\n\n    public static double lookup(String key) {\n        for (int i = 0; i < keys.length; i++)\n            if (keys[i].equals(key))\n                return values[i];\n        return Double.NaN;\n    }\n}\n"}
{"id": 59650, "name": "Rate counter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n"}
{"id": 59651, "name": "Rate counter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n", "Java": "import java.util.function.Consumer;\n\npublic class RateCounter {\n\n    public static void main(String[] args) {\n        for (double d : benchmark(10, x -> System.out.print(\"\"), 10))\n            System.out.println(d);\n    }\n\n    static double[] benchmark(int n, Consumer<Integer> f, int arg) {\n        double[] timings = new double[n];\n        for (int i = 0; i < n; i++) {\n            long time = System.nanoTime();\n            f.accept(arg);\n            timings[i] = System.nanoTime() - time;\n        }\n        return timings;\n    }\n}\n"}
{"id": 59652, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n", "Java": "public class AntiPrimesPlus {\n\n    static int count_divisors(int n) {\n        int count = 0;\n        for (int i = 1; i * i <= n; ++i) {\n            if (n % i == 0) {\n                if (i == n / i)\n                    count++;\n                else\n                    count += 2;\n            }\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        final int max = 15;\n        System.out.printf(\"The first %d terms of the sequence are:\\n\", max);\n        for (int i = 1, next = 1; next <= max; ++i) {\n            if (next == count_divisors(i)) {           \n                System.out.printf(\"%d \", i);\n                next++;\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 59653, "name": "Pythagoras tree", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class PythagorasTree extends JPanel {\n    final int depthLimit = 7;\n    float hue = 0.15f;\n\n    public PythagorasTree() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,\n            int depth) {\n\n        if (depth == depthLimit)\n            return;\n\n        float dx = x2 - x1;\n        float dy = y1 - y2;\n\n        float x3 = x2 - dy;\n        float y3 = y2 - dx;\n        float x4 = x1 - dy;\n        float y4 = y1 - dx;\n        float x5 = x4 + 0.5F * (dx - dy);\n        float y5 = y4 - 0.5F * (dx + dy);\n\n        Path2D square = new Path2D.Float();\n        square.moveTo(x1, y1);\n        square.lineTo(x2, y2);\n        square.lineTo(x3, y3);\n        square.lineTo(x4, y4);\n        square.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));\n        g.fill(square);\n        g.setColor(Color.lightGray);\n        g.draw(square);\n\n        Path2D triangle = new Path2D.Float();\n        triangle.moveTo(x3, y3);\n        triangle.lineTo(x4, y4);\n        triangle.lineTo(x5, y5);\n        triangle.closePath();\n\n        g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));\n        g.fill(triangle);\n        g.setColor(Color.lightGray);\n        g.draw(triangle);\n\n        drawTree(g, x4, y4, x5, y5, depth + 1);\n        drawTree(g, x5, y5, x3, y3, depth + 1);\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        drawTree((Graphics2D) g, 275, 500, 375, 500, 0);\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(\"Pythagoras Tree\");\n            f.setResizable(false);\n            f.add(new PythagorasTree(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59654, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 59655, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "Java": "public class App {\n    private static long mod(long x, long y) {\n        long m = x % y;\n        if (m < 0) {\n            if (y < 0) {\n                return m - y;\n            } else {\n                return m + y;\n            }\n        }\n        return m;\n    }\n\n    public static class RNG {\n        \n        private final long[] a1 = {0, 1403580, -810728};\n        private static final long m1 = (1L << 32) - 209;\n        private long[] x1;\n        \n        private final long[] a2 = {527612, 0, -1370589};\n        private static final long m2 = (1L << 32) - 22853;\n        private long[] x2;\n        \n        private static final long d = m1 + 1;\n\n        public void seed(long state) {\n            x1 = new long[]{state, 0, 0};\n            x2 = new long[]{state, 0, 0};\n        }\n\n        public long nextInt() {\n            long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1);\n            long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2);\n            long z = mod(x1i - x2i, m1);\n\n            \n            x1 = new long[]{x1i, x1[0], x1[1]};\n            \n            x2 = new long[]{x2i, x2[0], x2[1]};\n\n            return z + 1;\n        }\n\n        public double nextFloat() {\n            return 1.0 * nextInt() / d;\n        }\n    }\n\n    public static void main(String[] args) {\n        RNG rng = new RNG();\n\n        rng.seed(1234567);\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println(rng.nextInt());\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int value = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[value]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d%n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 59656, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59657, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59658, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "Java": "public class ColorfulNumbers {\n    private int count[] = new int[8];\n    private boolean used[] = new boolean[10];\n    private int largest = 0;\n\n    public static void main(String[] args) {\n        System.out.printf(\"Colorful numbers less than 100:\\n\");\n        for (int n = 0, count = 0; n < 100; ++n) {\n            if (isColorful(n))\n                System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n        }\n\n        ColorfulNumbers c = new ColorfulNumbers();\n\n        System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n        System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n        int total = 0;\n        for (int d = 0; d < 8; ++d) {\n            System.out.printf(\"%d   %,d\\n\", d + 1, c.count[d]);\n            total += c.count[d];\n        }\n        System.out.printf(\"\\nTotal: %,d\\n\", total);\n    }\n\n    private ColorfulNumbers() {\n        countColorful(0, 0, 0);\n    }\n\n    public static boolean isColorful(int n) {\n        \n        if (n < 0 || n > 98765432)\n            return false;\n        int digit_count[] = new int[10];\n        int digits[] = new int[8];\n        int num_digits = 0;\n        for (int m = n; m > 0; m /= 10) {\n            int d = m % 10;\n            if (n > 9 && (d == 0 || d == 1))\n                return false;\n            if (++digit_count[d] > 1)\n                return false;\n            digits[num_digits++] = d;\n        }\n        \n        int products[] = new int[36];\n        for (int i = 0, product_count = 0; i < num_digits; ++i) {\n            for (int j = i, p = 1; j < num_digits; ++j) {\n                p *= digits[j];\n                for (int k = 0; k < product_count; ++k) {\n                    if (products[k] == p)\n                        return false;\n                }\n                products[product_count++] = p;\n            }\n        }\n        return true;\n    }\n\n    private void countColorful(int taken, int n, int digits) {\n        if (taken == 0) {\n            for (int d = 0; d < 10; ++d) {\n                used[d] = true;\n                countColorful(d < 2 ? 9 : 1, d, 1);\n                used[d] = false;\n            }\n        } else {\n            if (isColorful(n)) {\n                ++count[digits - 1];\n                if (n > largest)\n                    largest = n;\n            }\n            if (taken < 9) {\n                for (int d = 2; d < 10; ++d) {\n                    if (!used[d]) {\n                        used[d] = true;\n                        countColorful(taken + 1, n * 10 + d, digits + 1);\n                        used[d] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59659, "name": "Rosetta Code_Tasks without examples", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"html\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {    \n    ex := `<li><a href=\"/wiki/(.*?)\"`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    tasks := make([]string, len(matches))\n    for i, match := range matches {\n        tasks[i] = match[1]\n    }\n    const base = \"http:\n    const limit = 3 \n    ex = `(?s)using any language you may know.</div>(.*?)<div id=\"toc\"`\n    ex2 := `</?[^>]*>` \n    re = regexp.MustCompile(ex)\n    re2 := regexp.MustCompile(ex2)\n    for i, task := range tasks {\n        page = base + task\n        resp, _ = http.Get(page)\n        body, _ = ioutil.ReadAll(resp.Body)\n        match := re.FindStringSubmatch(string(body))\n        resp.Body.Close()\n        text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], \"\"))\n        fmt.Println(strings.Replace(task, \"_\", \" \", -1), \"\\n\", text)\n        if i == limit-1 {\n            break\n        }\n        time.Sleep(5 * time.Second) \n    }\n}\n", "Java": "import java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\n\npublic class TasksWithoutExamples {\n    private static String readPage(HttpClient client, URI uri) throws IOException, InterruptedException {\n        var request = HttpRequest.newBuilder()\n            .GET()\n            .uri(uri)\n            .timeout(Duration.ofSeconds(5))\n            .setHeader(\"accept\", \"text/html\")\n            .build();\n\n        var response = client.send(request, HttpResponse.BodyHandlers.ofString());\n        return response.body();\n    }\n\n    private static void process(HttpClient client, String base, String task) {\n        try {\n            var re = Pattern.compile(\".*using any language you may know.</div>(.*?)<div id=\\\"toc\\\".*\", Pattern.DOTALL + Pattern.MULTILINE);\n            var re2 = Pattern.compile(\"</?[^>]*>\");\n\n            var page = base + task;\n            String body = readPage(client, new URI(page));\n\n            var matcher = re.matcher(body);\n            if (matcher.matches()) {\n                var group = matcher.group(1);\n                var m2 = re2.matcher(group);\n                var text = m2.replaceAll(\"\");\n                System.out.println(text);\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {\n        var re = Pattern.compile(\"<li><a href=\\\"/wiki/(.*?)\\\"\", Pattern.DOTALL + Pattern.MULTILINE);\n\n        var client = HttpClient.newBuilder()\n            .version(HttpClient.Version.HTTP_1_1)\n            .followRedirects(HttpClient.Redirect.NORMAL)\n            .connectTimeout(Duration.ofSeconds(5))\n            .build();\n\n        var uri = new URI(\"http\", \"rosettacode.org\", \"/wiki/Category:Programming_Tasks\", \"\");\n        var body = readPage(client, uri);\n        var matcher = re.matcher(body);\n\n        var tasks = new ArrayList<String>();\n        while (matcher.find()) {\n            tasks.add(matcher.group(1));\n        }\n\n        var base = \"http:\n        var limit = 3L;\n\n        tasks.stream().limit(limit).forEach(task -> process(client, base, task));\n    }\n}\n"}
{"id": 59660, "name": "Sine wave", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os/exec\"\n)\n\nfunc main() {\n    synthType := \"sine\"\n    duration := \"5\"\n    frequency := \"440\"\n    cmd := exec.Command(\"play\", \"-n\", \"synth\", duration, synthType, frequency)\n    err := cmd.Run()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import processing.sound.*;\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\nsine.freq(500);\nsine.play();\n\ndelay(5000);\n"}
{"id": 59661, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "Java": "public class Class1 extends Class2\n{\n\t\n}\n"}
{"id": 59662, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "Java": "public class Class1 extends Class2\n{\n\t\n}\n"}
{"id": 59663, "name": "Stern-Brocot sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n"}
{"id": 59664, "name": "Numeric error propagation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n", "Java": "public class Approx {\n    private double value;\n    private double error;\n    \n    public Approx(){this.value = this.error = 0;}\n    \n    public Approx(Approx b){\n        this.value = b.value;\n        this.error = b.error;\n    }\n    \n    public Approx(double value, double error){\n        this.value = value;\n        this.error = error;\n    }\n    \n    public Approx add(Approx b){\n        value+= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx add(double b){\n        value+= b;\n        return this;\n    }\n    \n    public Approx sub(Approx b){\n        value-= b.value;\n        error = Math.sqrt(error * error + b.error * b.error);\n        return this;\n    }\n    \n    public Approx sub(double b){\n        value-= b;\n        return this;\n    }\n    \n    public Approx mult(Approx b){\n        double oldVal = value;\n        value*= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx mult(double b){\n        value*= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx div(Approx b){\n        double oldVal = value;\n        value/= b.value;\n        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +\n                                  (b.error*b.error) / (b.value*b.value));\n        return this;\n    }\n\n    public Approx div(double b){\n        value/= b;\n        error = Math.abs(b * error);\n        return this;\n    }\n    \n    public Approx pow(double b){\n        double oldVal = value;\n        value = Math.pow(value, b);\n        error = Math.abs(value * b * (error / oldVal));\n        return this;\n    }\n    \n    @Override\n    public String toString(){return value+\"±\"+error;}\n    \n    public static void main(String[] args){\n        Approx x1 = new Approx(100, 1.1);\n        Approx y1 = new Approx(50, 1.2);\n        Approx x2 = new Approx(200, 2.2);\n        Approx y2 = new Approx(100, 2.3);\n        \n        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);\n        \n        System.out.println(x1);\n    }\n}\n"}
{"id": 59665, "name": "Soundex", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n"}
{"id": 59666, "name": "List rooted trees", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n    private static final List<Long> TREE_LIST = new ArrayList<>();\n\n    private static final List<Integer> OFFSET = new ArrayList<>();\n\n    static {\n        for (int i = 0; i < 32; i++) {\n            if (i == 1) {\n                OFFSET.add(1);\n            } else {\n                OFFSET.add(0);\n            }\n        }\n    }\n\n    private static void append(long t) {\n        TREE_LIST.add(1 | (t << 1));\n    }\n\n    private static void show(long t, int l) {\n        while (l-- > 0) {\n            if (t % 2 == 1) {\n                System.out.print('(');\n            } else {\n                System.out.print(')');\n            }\n            t = t >> 1;\n        }\n    }\n\n    private static void listTrees(int n) {\n        for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {\n            show(TREE_LIST.get(i), n * 2);\n            System.out.println();\n        }\n    }\n\n    private static void assemble(int n, long t, int sl, int pos, int rem) {\n        if (rem == 0) {\n            append(t);\n            return;\n        }\n\n        var pp = pos;\n        var ss = sl;\n\n        if (sl > rem) {\n            ss = rem;\n            pp = OFFSET.get(ss);\n        } else if (pp >= OFFSET.get(ss + 1)) {\n            ss--;\n            if (ss == 0) {\n                return;\n            }\n            pp = OFFSET.get(ss);\n        }\n\n        assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);\n        assemble(n, t, ss, pp + 1, rem);\n    }\n\n    private static void makeTrees(int n) {\n        if (OFFSET.get(n + 1) != 0) {\n            return;\n        }\n        if (n > 0) {\n            makeTrees(n - 1);\n        }\n        assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);\n        OFFSET.set(n + 1, TREE_LIST.size());\n    }\n\n    private static void test(int n) {\n        if (n < 1 || n > 12) {\n            throw new IllegalArgumentException(\"Argument must be between 1 and 12\");\n        }\n\n        append(0);\n\n        makeTrees(n);\n        System.out.printf(\"Number of %d-trees: %d\\n\", n, OFFSET.get(n + 1) - OFFSET.get(n));\n        listTrees(n);\n    }\n\n    public static void main(String[] args) {\n        test(5);\n    }\n}\n"}
{"id": 59667, "name": "Documentation", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n", "Java": "\npublic class Doc{\n   \n   private String field;\n\n   \n   public int method(long num) throws BadException{\n      \n   }\n}\n"}
{"id": 59668, "name": "Problem of Apollonius", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n", "Java": "public class Circle\n{\n public double[] center;\n public double radius;\n public Circle(double[] center, double radius)\n {\n  this.center = center;\n  this.radius = radius;\n }\n public String toString()\n {\n  return String.format(\"Circle[x=%.2f,y=%.2f,r=%.2f]\",center[0],center[1],\n\t\t       radius);\n }\n}\n\npublic class ApolloniusSolver\n{\n\n public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,\n\t\t\t\t      int s2, int s3)\n {\n  float x1 = c1.center[0];\n  float y1 = c1.center[1];\n  float r1 = c1.radius;\n  float x2 = c2.center[0];\n  float y2 = c2.center[1];\n  float r2 = c2.radius;\n  float x3 = c3.center[0];\n  float y3 = c3.center[1];\n  float r3 = c3.radius;\n\n  \n  \n  float v11 = 2*x2 - 2*x1;\n  float v12 = 2*y2 - 2*y1;\n  float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;\n  float v14 = 2*s2*r2 - 2*s1*r1;\n\n  float v21 = 2*x3 - 2*x2;\n  float v22 = 2*y3 - 2*y2;\n  float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;\n  float v24 = 2*s3*r3 - 2*s2*r2;\n\n  float w12 = v12/v11;\n  float w13 = v13/v11;\n  float w14 = v14/v11;\n\n  float w22 = v22/v21-w12;\n  float w23 = v23/v21-w13;\n  float w24 = v24/v21-w14;\n\n  float P = -w23/w22;\n  float Q = w24/w22;\n  float M = -w12*P-w13;\n  float N = w14 - w12*Q;\n\n  float a = N*N + Q*Q - 1;\n  float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;\n  float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;\n\n  \n  \n  float D = b*b-4*a*c;\n  float rs = (-b-Math.sqrt(D))/(2*a);\n  float xs = M + N * rs;\n  float ys = P + Q * rs;\n  return new Circle(new double[]{xs,ys}, rs);\n }\n public static void main(final String[] args)\n {\n  Circle c1 = new Circle(new double[]{0,0}, 1);\n  Circle c2 = new Circle(new double[]{4,0}, 1);\n  Circle c3 = new Circle(new double[]{2,4}, 2);\n  \n  System.out.println(solveApollonius(c1,c2,c3,1,1,1));\n  \n  System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1));\n }\n}\n"}
{"id": 59669, "name": "Longest common suffix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n", "Java": "import java.util.List;\n\npublic class App {\n    private static String lcs(List<String> a) {\n        var le = a.size();\n        if (le == 0) {\n            return \"\";\n        }\n        if (le == 1) {\n            return a.get(0);\n        }\n        var le0 = a.get(0).length();\n        var minLen = le0;\n        for (int i = 1; i < le; i++) {\n            if (a.get(i).length() < minLen) {\n                minLen = a.get(i).length();\n            }\n        }\n        if (minLen == 0) {\n            return \"\";\n        }\n        var res = \"\";\n        var a1 = a.subList(1, a.size());\n        for (int i = 1; i < minLen; i++) {\n            var suffix = a.get(0).substring(le0 - i);\n            for (String e : a1) {\n                if (!e.endsWith(suffix)) {\n                    return res;\n                }\n            }\n            res = suffix;\n        }\n        return \"\";\n    }\n\n    public static void main(String[] args) {\n        var tests = List.of(\n            List.of(\"baabababc\", \"baabc\", \"bbbabc\"),\n            List.of(\"baabababc\", \"baabc\", \"bbbazc\"),\n            List.of(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"),\n            List.of(\"longest\", \"common\", \"suffix\"),\n            List.of(\"suffix\"),\n            List.of(\"\")\n        );\n        for (List<String> test : tests) {\n            System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n        }\n    }\n}\n"}
{"id": 59670, "name": "Chat server", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 59671, "name": "Chat server", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 59672, "name": "Idiomatically determine all the lowercase and uppercase letters", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n", "Java": "import java.util.stream.IntStream;\n\npublic class Letters {\n    public static void main(String[] args) throws Exception {\n        System.out.print(\"Upper case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isUpperCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n\n        System.out.print(\"Lower case: \");\n        IntStream.rangeClosed(0, 0x10FFFF)\n                 .filter(Character::isLowerCase)\n                 .limit(72)\n                 .forEach(n -> System.out.printf(\"%c\", n));\n        System.out.println(\"...\");\n    }\n}\n"}
{"id": 59673, "name": "Sum of elements below main diagonal of matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n", "Java": "public static void main(String[] args) {\n    int[][] matrix = {{1, 3, 7, 8, 10},\n                      {2, 4, 16, 14, 4},\n                      {3, 1, 9, 18, 11},\n                      {12, 14, 17, 18, 20},\n                      {7, 1, 3, 9, 5}};\n    int sum = 0;\n    for (int row = 1; row < matrix.length; row++) {\n        for (int col = 0; col < row; col++) {\n            sum += matrix[row][col];\n        }\n    }\n    System.out.println(sum);\n}\n"}
{"id": 59674, "name": "Sorting algorithms_Tree sort on a linked list", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n"}
{"id": 59675, "name": "Sorting algorithms_Tree sort on a linked list", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n", "Java": "\nimport java.util.*;\n\npublic class TreeSortTest {\n    public static void main(String[] args) {\n        test1();\n        System.out.println();\n        test2();\n    }\n\n    \n    private static void test1() {\n        LinkedList<Integer> list = new LinkedList<>();\n        Random r = new Random();\n        for (int i = 0; i < 16; ++i)\n            list.add(Integer.valueOf(r.nextInt(100)));\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n\n    \n    private static void test2() {\n        LinkedList<String> list = new LinkedList<>();\n        String[] strings = { \"one\", \"two\", \"three\", \"four\", \"five\",\n            \"six\", \"seven\", \"eight\", \"nine\", \"ten\"};\n        for (String str : strings)\n            list.add(str);\n        System.out.println(\"before sort: \" + list);\n        list.treeSort();\n        System.out.println(\" after sort: \" + list);\n    }\n}\n"}
{"id": 59676, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 59677, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 59678, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n"}
{"id": 59679, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "Java": "import java.util.function.Function;\n\npublic class NumericalIntegrationAdaptiveSimpsons {\n\n    public static void main(String[] args) {\n        Function<Double,Double> f = x -> sin(x);\n        System.out.printf(\"integrate sin(x), x = 0 .. Pi = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);\n        functionCount = 0;\n        System.out.printf(\"integrate sin(x), x = 0 .. 1 = %2.12f.  Function calls = %d%n\", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);\n    }\n    \n    private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {\n        double fa = function.apply(a);\n        double fb = function.apply(b);\n        Triple t =  quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);\n    }\n    \n    private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {\n        Triple left  = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);\n        Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);\n        double delta = left.s + right.s - whole;\n        if ( Math.abs(delta) <= 15*error ) {\n            return left.s + right.s + delta / 15;\n        }\n        return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +\n               quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);\n    }\n    \n    private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {\n        double m = (a + b) / 2;\n        double fm = function.apply(m);\n        return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));\n    }\n    \n    private static class Triple {\n        double x, fx, s;\n        private Triple(double m, double fm, double s) {\n            this.x = m;\n            this.fx = fm;\n            this.s = s;\n        }\n    }\n    \n    private static int functionCount = 0;\n    \n    private static double sin(double x) {\n        functionCount++;\n        return Math.sin(x);\n    }\n    \n}\n"}
{"id": 59680, "name": "FASTA format", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n", "Java": "import java.io.*;\nimport java.util.Scanner;\n\npublic class ReadFastaFile {\n\n    public static void main(String[] args) throws FileNotFoundException {\n\n        boolean first = true;\n\n        try (Scanner sc = new Scanner(new File(\"test.fasta\"))) {\n            while (sc.hasNextLine()) {\n                String line = sc.nextLine().trim();\n                if (line.charAt(0) == '>') {\n                    if (first)\n                        first = false;\n                    else\n                        System.out.println();\n                    System.out.printf(\"%s: \", line.substring(1));\n                } else {\n                    System.out.print(line);\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 59681, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 59682, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 59683, "name": "Window creation_X11", "Go": "package main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"github.com/jezek/xgb\"\n    \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n    \n    X, err := xgb.NewConn()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    points := []xproto.Point{\n        {10, 10},\n        {10, 20},\n        {20, 10},\n        {20, 20}};\n\n    polyline := []xproto.Point{\n        {50, 10},\n        { 5, 20},     \n        {25,-20},\n        {10, 10}};\n\n    segments := []xproto.Segment{\n        {100, 10, 140, 30},\n        {110, 25, 130, 60}};\n\n    rectangles := []xproto.Rectangle{\n        { 10, 50, 40, 20},\n        { 80, 50, 10, 40}};\n\n    arcs := []xproto.Arc{\n        {10, 100, 60, 40, 0, 90 << 6},\n        {90, 100, 55, 40, 0, 270 << 6}};\n\n    setup := xproto.Setup(X)\n    \n    screen := setup.DefaultScreen(X)\n\n    \n    foreground, _ := xproto.NewGcontextId(X)\n    mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n    values := []uint32{screen.BlackPixel, 0}\n    xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n    \n    win, _ := xproto.NewWindowId(X)\n    winDrawable := xproto.Drawable(win)\n\n    \n    mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n    values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n    xproto.CreateWindow(X,                  \n            screen.RootDepth,               \n            win,                            \n            screen.Root,                    \n            0, 0,                           \n            150, 150,                       \n            10,                             \n            xproto.WindowClassInputOutput,  \n            screen.RootVisual,              \n            mask, values)                   \n\n    \n    xproto.MapWindow(X, win)\n\n    for {\n        evt, err := X.WaitForEvent()\n        switch evt.(type) {\n            case xproto.ExposeEvent:\n                \n                xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n                \n                xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n                \n                xproto.PolySegment(X, winDrawable, foreground, segments)\n\n                \n                xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n                \n                xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n            default:\n                \n        }\n\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    return\n}\n", "Java": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n  public static void main(String[] args) {\n    Runnable runnable = new Runnable() {\n      public void run() {\n\tcreateAndShow();\n      }\n    };\n    SwingUtilities.invokeLater(runnable);\n  }\n\t\n  static void createAndShow() {\n    JFrame frame = new JFrame(\"Hello World\");\n    frame.setSize(640,480);\n    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n}\n"}
{"id": 59684, "name": "Finite state machine", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n"}
{"id": 59685, "name": "Vibrating rectangles", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n", "Java": "\n\nint counter = 100;\n\nvoid setup(){\n  size(1000,1000);\n}\n\nvoid draw(){\n  \n  for(int i=0;i<20;i++){\n    fill(counter - 5*i);\n    rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i);\n  }\n  counter++;\n  \n  if(counter > 255)\n    counter = 100;\n  \n  delay(100);\n}\n"}
{"id": 59686, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 59687, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 59688, "name": "Pseudo-random numbers_PCG32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "Java": "public class PCG32 {\n    private static final long N = 6364136223846793005L;\n\n    private long state = 0x853c49e6748fea9bL;\n    private long inc = 0xda3e39cb94b95bdbL;\n\n    public void seed(long seedState, long seedSequence) {\n        state = 0;\n        inc = (seedSequence << 1) | 1;\n        nextInt();\n        state = state + seedState;\n        nextInt();\n    }\n\n    public int nextInt() {\n        long old = state;\n        state = old * N + inc;\n        int shifted = (int) (((old >>> 18) ^ old) >>> 27);\n        int rot = (int) (old >>> 59);\n        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));\n    }\n\n    public double nextFloat() {\n        var u = Integer.toUnsignedLong(nextInt());\n        return (double) u / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var r = new PCG32();\n\n        r.seed(42, 54);\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println(Integer.toUnsignedString(r.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        r.seed(987654321, 1);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(r.nextFloat() * 5.0);\n            counts[j]++;\n        }\n\n        System.out.println(\"The counts for 100,000 repetitions are:\");\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"  %d : %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 59689, "name": "Deconvolution_1D", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    h := []float64{-8, -9, -3, -1, -6, 7}\n    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n        96, 31, 55, 36, 29, -43, -7}\n    fmt.Println(h)\n    fmt.Println(deconv(g, f))\n    fmt.Println(f)\n    fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n    h := make([]float64, len(g)-len(f)+1)\n    for n := range h {\n        h[n] = g[n]\n        var lower int\n        if n >= len(f) {\n            lower = n - len(f) + 1\n        }\n        for i := lower; i < n; i++ {\n            h[n] -= h[i] * f[n-i]\n        }\n        h[n] /= f[0]\n    }\n    return h\n}\n", "Java": "import java.util.Arrays;\n\npublic class Deconvolution1D {\n    public static int[] deconv(int[] g, int[] f) {\n        int[] h = new int[g.length - f.length + 1];\n        for (int n = 0; n < h.length; n++) {\n            h[n] = g[n];\n            int lower = Math.max(n - f.length + 1, 0);\n            for (int i = lower; i < n; i++)\n                h[n] -= h[i] * f[n - i];\n            h[n] /= f[0];\n        }\n        return h;\n    }\n\n    public static void main(String[] args) {\n        int[] h = { -8, -9, -3, -1, -6, 7 };\n        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };\n        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n                96, 31, 55, 36, 29, -43, -7 };\n\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"h = \" + Arrays.toString(h) + \"\\n\");\n        sb.append(\"deconv(g, f) = \" + Arrays.toString(deconv(g, f)) + \"\\n\");\n        sb.append(\"f = \" + Arrays.toString(f) + \"\\n\");\n        sb.append(\"deconv(g, h) = \" + Arrays.toString(deconv(g, h)) + \"\\n\");\n        System.out.println(sb.toString());\n    }\n}\n"}
{"id": 59690, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 59691, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 59692, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "Java": "import static java.util.Arrays.*;\nimport static java.lang.System.out;\n\npublic class NYSIIS {\n\n    final static String[][] first = {{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"},\n    {\"PH\", \"FF\"}, {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}};\n\n    final static String[][] last = {{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"},\n    {\"RT\", \"D\"}, {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}};\n\n    final static String Vowels = \"AEIOU\";\n\n    public static void main(String[] args) {\n        stream(args).parallel().map(n -> transcode(n)).forEach(out::println);\n    }\n\n    static String transcode(String s) {\n        int len = s.length();\n        StringBuilder sb = new StringBuilder(len);\n\n        for (int i = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (c >= 'a' && c <= 'z')\n                sb.append((char) (c - 32));\n            else if (c >= 'A' && c <= 'Z')\n                sb.append(c);\n        }\n\n        replace(sb, 0, first);\n        replace(sb, sb.length() - 2, last);\n\n        len = sb.length();\n        sb.append(\" \");\n        for (int i = 1; i < len; i++) {\n            char prev = sb.charAt(i - 1);\n            char curr = sb.charAt(i);\n            char next = sb.charAt(i + 1);\n\n            if (curr == 'E' && next == 'V')\n                sb.replace(i, i + 2, \"AF\");\n\n            else if (isVowel(curr))\n                sb.setCharAt(i, 'A');\n\n            else if (curr == 'Q')\n                sb.setCharAt(i, 'G');\n\n            else if (curr == 'Z')\n                sb.setCharAt(i, 'S');\n\n            else if (curr == 'M')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K' && next == 'N')\n                sb.setCharAt(i, 'N');\n\n            else if (curr == 'K')\n                sb.setCharAt(i, 'C');\n\n            else if (sb.indexOf(\"SCH\", i) == i)\n                sb.replace(i, i + 3, \"SSS\");\n\n            else if (curr == 'P' && next == 'H')\n                sb.replace(i, i + 2, \"FF\");\n\n            else if (curr == 'H' && (!isVowel(prev) || !isVowel(next)))\n                sb.setCharAt(i, prev);\n\n            else if (curr == 'W' && isVowel(prev))\n                sb.setCharAt(i, prev);\n\n            if (sb.charAt(i) == prev) {\n                sb.deleteCharAt(i--);\n                len--;\n            }\n        }\n        sb.setLength(sb.length() - 1); \n\n        int lastPos = sb.length() - 1;\n        if (lastPos > 1) {\n\n            if (sb.lastIndexOf(\"AY\") == lastPos - 1)\n                sb.delete(lastPos - 1, lastPos + 1).append(\"Y\");\n\n            else if (sb.charAt(lastPos) == 'S')\n                sb.setLength(lastPos);\n\n            else if (sb.charAt(lastPos) == 'A')\n                sb.setLength(lastPos);\n        }\n\n        if (sb.length() > 6)\n            sb.insert(6, '[').append(']');\n\n        return String.format(\"%s -> %s\", s, sb);\n    }\n\n    private static void replace(StringBuilder sb, int start, String[][] maps) {\n        if (start >= 0)\n            for (String[] map : maps) {\n                if (sb.indexOf(map[0]) == start) {\n                    sb.replace(start, start + map[0].length(), map[1]);\n                    break;\n                }\n            }\n    }\n\n    private static boolean isVowel(char c) {\n        return Vowels.indexOf(c) != -1;\n    }\n}\n"}
{"id": 59693, "name": "Disarium numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n"}
{"id": 59694, "name": "Disarium numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n", "Java": "import java.lang.Math;\n\npublic class DisariumNumbers {\n    public static boolean is_disarium(int num) {\n        int n = num;\n        int len = Integer.toString(n).length();\n        int sum = 0;\n        int i = 1;\n        while (n > 0) {\n            sum += Math.pow(n % 10, len - i + 1);\n            n /= 10;\n            i ++;\n        }\n        return sum  == num;\n    }\n\n    public static void main(String[] args) {\n        int i = 0;\n        int count = 0;\n        while (count <= 18) {\n            if (is_disarium(i)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n            i++;\n        }\n        System.out.printf(\"%s\", \"\\n\");\n    }\n}\n"}
{"id": 59695, "name": "Sierpinski pentagon", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n"}
{"id": 59696, "name": "Bitmap_Histogram", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n", "Java": "import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic enum ImageProcessing {\n    ;\n\n    public static void main(String[] args) throws IOException {\n        BufferedImage img = ImageIO.read(new File(\"example.png\"));\n\n        BufferedImage bwimg = toBlackAndWhite(img);\n\n        ImageIO.write(bwimg, \"png\", new File(\"example-bw.png\"));\n    }\n\n    private static int luminance(int rgb) {\n        int r = (rgb >> 16) & 0xFF;\n        int g = (rgb >> 8) & 0xFF;\n        int b = rgb & 0xFF;\n        return (r + b + g) / 3;\n    }\n\n    private static BufferedImage toBlackAndWhite(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = computeHistogram(img);\n\n        int median = getMedian(width * height, histo);\n\n        BufferedImage bwimg = new BufferedImage(width, height, img.getType());\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);\n            }\n        }\n        return bwimg;\n    }\n\n    private static int[] computeHistogram(BufferedImage img) {\n        int width = img.getWidth();\n        int height = img.getHeight();\n\n        int[] histo = new int[256];\n        for (int y = 0; y < height; y++) {\n            for (int x = 0; x < width; x++) {\n                histo[luminance(img.getRGB(x, y))]++;\n            }\n        }\n        return histo;\n    }\n\n    private static int getMedian(int total, int[] histo) {\n        int median = 0;\n        int sum = 0;\n        for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {\n            sum += histo[i];\n            median++;\n        }\n        return median;\n    }\n}\n"}
{"id": 59697, "name": "Mutex", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n", "Java": "import java.util.concurrent.Semaphore;\n\npublic class VolatileClass{\n   public Semaphore mutex = new Semaphore(1); \n                                              \n   public void needsToBeSynched(){\n      \n   }\n   \n}\n"}
{"id": 59698, "name": "Metronome", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 \n\tvar bpb = 4    \n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}\n", "Java": "class Metronome{\n\tdouble bpm;\n\tint measure, counter;\n\tpublic Metronome(double bpm, int measure){\n\t\tthis.bpm = bpm;\n\t\tthis.measure = measure;\t\n\t}\n\tpublic void start(){\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tThread.sleep((long)(1000*(60.0/bpm)));\n\t\t\t}catch(InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tcounter++;\n\t\t\tif (counter%measure==0){\n\t\t\t\t System.out.println(\"TICK\");\n\t\t\t}else{\n\t\t\t\t System.out.println(\"TOCK\");\n\t\t\t}\n\t\t}\n\t}\n}\npublic class test {\n\tpublic static void main(String[] args) {\n\t\tMetronome metronome1 = new Metronome(120,4);\n\t\tmetronome1.start();\n\t}\n}\n"}
{"id": 59699, "name": "EKG sequence convergence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n    for _, j := range a {\n        if j == b {\n            return true\n        }\n    }\n    return false\n}\n\nfunc gcd(a, b int) int {\n    for a != b {\n        if a > b {\n            a -= b\n        } else {\n            b -= a\n        }\n    }\n    return a\n}\n\nfunc areSame(s, t []int) bool {\n    le := len(s)\n    if le != len(t) {\n        return false\n    }\n    sort.Ints(s)\n    sort.Ints(t)\n    for i := 0; i < le; i++ {\n        if s[i] != t[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100\n    starts := [5]int{2, 5, 7, 9, 10}\n    var ekg [5][limit]int\n\n    for s, start := range starts {\n        ekg[s][0] = 1\n        ekg[s][1] = start\n        for n := 2; n < limit; n++ {\n            for i := 2; ; i++ {\n                \n                \n                if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n                    ekg[s][n] = i\n                    break\n                }\n            }\n        }\n        fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n    }   \n\n    \n    for i := 2; i < limit; i++ {\n        if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n            fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n            return\n        }\n    }\n    fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n    public static void main(String[] args) {\n        System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n        for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n            System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n        }\n        System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n        List<Integer> ekg5 = ekg(5, 100);\n        List<Integer> ekg7 = ekg(7, 100);\n        for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n            if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n                System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n                break;\n            }\n        }\n    }\n    \n    \n    private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {\n        List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));\n        Collections.sort(list1);\n        List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));\n        Collections.sort(list2);\n        for ( int i = 0 ; i < n ; i++ ) {\n            if ( list1.get(i) != list2.get(i) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    \n    \n    private static List<Integer> ekg(int two, int maxN) {\n        List<Integer> result = new ArrayList<>();\n        result.add(1);\n        result.add(two);\n        Map<Integer,Integer> seen = new HashMap<>();\n        seen.put(1, 1);\n        seen.put(two, 1);\n        int minUnseen = two == 2 ? 3 : 2;\n        int prev = two;\n        for ( int n = 3 ; n <= maxN ; n++ ) {\n            int test = minUnseen - 1;\n            while ( true ) {\n                test++;\n                if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n                    \n                    result.add(test);\n                    seen.put(test, n);\n                    prev = test;\n                    if ( minUnseen == test ) {\n                        do {\n                            minUnseen++;\n                        } while ( seen.containsKey(minUnseen) );\n                    }\n                    break;\n                }\n            }\n        }\n        return result;\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": 59700, "name": "Rep-string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n"}
{"id": 59701, "name": "Terminal control_Preserve screen", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"\\033[?1049h\\033[H\")\n    fmt.Println(\"Alternate screen buffer\\n\")\n    s := \"s\"\n    for i := 5; i > 0; i-- {\n        if i == 1 {\n            s = \"\"\n        }\n        fmt.Printf(\"\\rgoing back in %d second%s...\", i, s)\n        time.Sleep(time.Second)\n    }\n    fmt.Print(\"\\033[?1049l\")\n}\n", "Java": "public class PreserveScreen\n{\n    public static void main(String[] args) throws InterruptedException {\n        System.out.print(\"\\033[?1049h\\033[H\");\n        System.out.println(\"Alternate screen buffer\\n\");\n        for (int i = 5; i > 0; i--) {\n            String s = (i > 1) ? \"s\" : \"\";\n            System.out.printf(\"\\rgoing back in %d second%s...\", i, s);\n            Thread.sleep(1000);\n        }\n        System.out.print(\"\\033[?1049l\");\n    }\n}\n"}
{"id": 59702, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 59703, "name": "Changeable words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class ChangeableWords {\n    public static void main(String[] args) {\n        try {\n            final String fileName = \"unixdict.txt\";\n            List<String> dictionary = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() > 11)\n                        dictionary.add(line);\n                }\n            }\n            System.out.printf(\"Changeable words in %s:\\n\", fileName);\n            int n = 1;\n            for (String word1 : dictionary) {\n                for (String word2 : dictionary) {\n                    if (word1 != word2 && hammingDistance(word1, word2) == 1)\n                        System.out.printf(\"%2d: %-14s -> %s\\n\", n++, word1, word2);\n                }\n            }\n        } catch (Exception e)  {\n            e.printStackTtexture();\n        }\n    }\n\n    private static int hammingDistance(String str1, String str2) {\n        int len1 = str1.length();\n        int len2 = str2.length();\n        if (len1 != len2)\n            return 0;\n        int count = 0;\n        for (int i = 0; i < len1; ++i) {\n            if (str1.charAt(i) != str2.charAt(i))\n                ++count;\n            \n            if (count == 2)\n                break;\n        }\n        return count;\n    }\n}\n"}
{"id": 59704, "name": "Window management", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n", "Java": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n   \n   public static void main( final String[] args ) {\n      EventQueue.invokeLater( () -> new WindowController() );\n   }\n\n   private JComboBox<ControlledWindow> list;\n\n   \n   private class ControlButton extends JButton {\n      private ControlButton( final String name ) {\n         super(\n            new AbstractAction( name ) {\n               public void actionPerformed( final ActionEvent e ) {\n                  try {\n                     WindowController.class.getMethod( \"do\" + name )\n                        .invoke ( WindowController.this );\n                  } catch ( final Exception x ) { \n                     x.printStackTrace();        \n                  }\n               }\n            }\n         );\n      }\n   }\n\n   \n   public WindowController() {\n      super( \"Controller\" );\n\n      final JPanel main = new JPanel();\n      final JPanel controls = new JPanel();\n\n      setLocationByPlatform( true );\n      setResizable( false );\n      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n      setLayout( new BorderLayout( 3, 3 ) );\n      getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n      add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n      main.add( list = new JComboBox<>() );\n      add( main, BorderLayout.CENTER );\n      controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n      controls.add( new ControlButton( \"Add\"      ) );\n      controls.add( new ControlButton( \"Hide\"     ) );\n      controls.add( new ControlButton( \"Show\"     ) );\n      controls.add( new ControlButton( \"Close\"    ) );\n      controls.add( new ControlButton( \"Maximise\" ) );\n      controls.add( new ControlButton( \"Minimise\" ) );\n      controls.add( new ControlButton( \"Move\"     ) );\n      controls.add( new ControlButton( \"Resize\"   ) );\n      add( controls, BorderLayout.EAST );\n      pack();\n      setVisible( true );\n   }\n\n   \n   private static class ControlledWindow extends JFrame {\n      private int num;\n\n      public ControlledWindow( final int num ) {\n         super( Integer.toString( num ) );\n         this.num = num;\n         setLocationByPlatform( true );\n         getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n         setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n         add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n         pack();\n         setVisible( true );\n      }\n\n      public String toString() {\n         return \"Window \" + num;\n      }\n   }\n\n   \n   \n\n   public void doAdd() {\n      list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n      pack();\n   }\n\n   public void doHide() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( false );\n   }\n\n   public void doShow() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setVisible( true );\n   }\n\n   public void doClose() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.dispose();\n   }\n\n   public void doMinimise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setState( Frame.ICONIFIED );\n   }\n\n   public void doMaximise() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      window.setExtendedState( Frame.MAXIMIZED_BOTH );\n   }\n\n   public void doMove() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int hPos = getInt( \"Horizontal position?\" );\n      if ( -1 == hPos ) {\n         return;\n      }\n      final int vPos = getInt( \"Vertical position?\" );\n      if ( -1 == vPos ) {\n         return;\n      }\n      window.setLocation ( hPos, vPos );\n   }\n\n   public void doResize() {\n      final JFrame window = getWindow();\n      if ( null == window ) {\n         return;\n      }\n      final int width = getInt( \"Width?\" );\n      if ( -1 == width ) {\n         return;\n      }\n      final int height = getInt( \"Height?\" );\n      if ( -1 == height ) {\n         return;\n      }\n      window.setBounds ( window.getX(), window.getY(), width, height );\n   }\n\n   private JFrame getWindow() {\n      final JFrame window = ( JFrame ) list.getSelectedItem();\n      if ( null == window ) {\n         JOptionPane.showMessageDialog( this, \"Add a window first\" );\n      }\n      return window;\n   }\n\n   private int getInt(final String prompt) {\n      final String s = JOptionPane.showInputDialog( prompt );\n      if ( null == s ) {\n         return -1;\n      }\n      try {\n         return Integer.parseInt( s );\n      } catch ( final NumberFormatException x ) {\n         JOptionPane.showMessageDialog( this, \"Not a number\" );\n         return -1;\n      }\n   }\n}\n"}
{"id": 59705, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 59706, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 59707, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "Java": "class SpecialPrimes {\n    private static boolean isPrime(int n) {\n        if (n < 2)  return false;\n        if (n%2 == 0) return n == 2;\n        if (n%3 == 0) return n == 3;\n        int d = 5;\n        while (d*d <= n) {\n            if (n%d == 0) return false;\n            d += 2;\n            if (n%d == 0) return false;\n            d += 4;\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"Special primes under 1,050:\");\n        System.out.println(\"Prime1 Prime2 Gap\");\n        int lastSpecial = 3;\n        int lastGap = 1;\n        System.out.printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n        for (int i = 5; i < 1050; i += 2) {\n            if (isPrime(i) && (i-lastSpecial) > lastGap) {\n                lastGap = i - lastSpecial;\n                System.out.printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n                lastSpecial = i;\n            }\n        }\n    }\n}\n"}
{"id": 59708, "name": "Mayan numerals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst (\n    ul = \"╔\"\n    uc = \"╦\"\n    ur = \"╗\"\n    ll = \"╚\"\n    lc = \"╩\"\n    lr = \"╝\"\n    hb = \"═\"\n    vb = \"║\"\n)\n\nvar mayan = [5]string{\n    \"    \",\n    \" ∙  \",\n    \" ∙∙ \",\n    \"∙∙∙ \",\n    \"∙∙∙∙\",\n}\n\nconst (\n    m0 = \" Θ  \"\n    m5 = \"────\"\n)\n\nfunc dec2vig(n uint64) []uint64 {\n    vig := strconv.FormatUint(n, 20)\n    res := make([]uint64, len(vig))\n    for i, d := range vig {\n        res[i], _ = strconv.ParseUint(string(d), 20, 64)\n    }\n    return res\n}\n\nfunc vig2quin(n uint64) [4]string {\n    if n >= 20 {\n        panic(\"Cant't convert a number >= 20\")\n    }\n    res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}\n    if n == 0 {\n        res[3] = m0\n        return res\n    }\n    fives := n / 5\n    rem := n % 5\n    res[3-fives] = mayan[rem]\n    for i := 3; i > 3-int(fives); i-- {\n        res[i] = m5\n    }\n    return res\n}\n\nfunc draw(mayans [][4]string) {\n    lm := len(mayans)\n    fmt.Print(ul)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(uc)\n        } else {\n            fmt.Println(ur)\n        }\n    }\n    for i := 1; i < 5; i++ {\n        fmt.Print(vb)\n        for j := 0; j < lm; j++ {\n            fmt.Print(mayans[j][i-1])\n            fmt.Print(vb)\n        }\n        fmt.Println()\n    }\n    fmt.Print(ll)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(lc)\n        } else {\n            fmt.Println(lr)\n        }\n    }\n}\n\nfunc main() {\n    numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}\n    for _, n := range numbers {\n        fmt.Printf(\"Converting %d to Mayan:\\n\", n)\n        vigs := dec2vig(n)\n        lv := len(vigs)\n        mayans := make([][4]string, lv)\n        for i, vig := range vigs {\n            mayans[i] = vig2quin(vig)\n        }\n        draw(mayans)\n        fmt.Println()\n    }\n}\n", "Java": "import java.math.BigInteger;\n\npublic class MayanNumerals {\n\n    public static void main(String[] args) {\n        for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {\n            displayMyan(BigInteger.valueOf(base10));\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static char[] digits = \"0123456789ABCDEFGHJK\".toCharArray();\n    private static BigInteger TWENTY = BigInteger.valueOf(20);\n    \n    private static void displayMyan(BigInteger numBase10) {\n        System.out.printf(\"As base 10:  %s%n\", numBase10);\n        String numBase20 = \"\";\n        while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {\n            numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;\n            numBase10 = numBase10.divide(TWENTY);\n        }\n        System.out.printf(\"As base 20:  %s%nAs Mayan:%n\", numBase20);\n        displayMyanLine1(numBase20);\n        displayMyanLine2(numBase20);\n        displayMyanLine3(numBase20);\n        displayMyanLine4(numBase20);\n        displayMyanLine5(numBase20);\n        displayMyanLine6(numBase20);\n    }\n \n    private static char boxUL = Character.toChars(9556)[0];\n    private static char boxTeeUp = Character.toChars(9574)[0];\n    private static char boxUR = Character.toChars(9559)[0];\n    private static char boxHorz = Character.toChars(9552)[0];\n    private static char boxVert = Character.toChars(9553)[0];\n    private static char theta = Character.toChars(952)[0];\n    private static char boxLL = Character.toChars(9562)[0];\n    private static char boxLR = Character.toChars(9565)[0];\n    private static char boxTeeLow = Character.toChars(9577)[0];\n    private static char bullet = Character.toChars(8729)[0];\n    private static char dash = Character.toChars(9472)[0];\n    \n    private static void displayMyanLine1(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxUL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeUp : boxUR);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String getBullet(int count) {\n        StringBuilder sb = new StringBuilder();\n        switch ( count ) {\n        case 1:  sb.append(\" \" + bullet + \"  \"); break;\n        case 2:  sb.append(\" \" + bullet + bullet + \" \"); break;\n        case 3:  sb.append(\"\" + bullet + bullet + bullet + \" \"); break;\n        case 4:  sb.append(\"\" + bullet + bullet + bullet + bullet); break;\n        default:  throw new IllegalArgumentException(\"Must be 1-4:  \" + count);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine2(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'G':  sb.append(getBullet(1)); break;\n            case 'H':  sb.append(getBullet(2)); break;\n            case 'J':  sb.append(getBullet(3)); break;\n            case 'K':  sb.append(getBullet(4)); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n    \n    private static String DASH = getDash();\n    \n    private static String getDash() {\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < 4 ; i++ ) {\n            sb.append(dash);\n        }\n        return sb.toString();\n    }\n\n    private static void displayMyanLine3(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case 'B':  sb.append(getBullet(1)); break;\n            case 'C':  sb.append(getBullet(2)); break;\n            case 'D':  sb.append(getBullet(3)); break;\n            case 'E':  sb.append(getBullet(4)); break;\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine4(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '6':  sb.append(getBullet(1)); break;\n            case '7':  sb.append(getBullet(2)); break;\n            case '8':  sb.append(getBullet(3)); break;\n            case '9':  sb.append(getBullet(4)); break;\n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine5(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxVert);\n            }\n            switch ( chars[i] ) {\n            case '0':  sb.append(\" \" + theta + \"  \"); break;\n            case '1':  sb.append(getBullet(1)); break;\n            case '2':  sb.append(getBullet(2)); break;\n            case '3':  sb.append(getBullet(3)); break;\n            case '4':  sb.append(getBullet(4)); break;\n            case '5': case '6': case '7': case '8': case '9': \n            case 'A': case 'B': case 'C': case 'D': case 'E':\n            case 'F': case 'G': case 'H': case 'J': case 'K':\n                sb.append(DASH); break;\n            default :  sb.append(\"    \");\n            }\n            sb.append(boxVert);\n        }\n        System.out.println(sb.toString());\n    }\n\n    private static void displayMyanLine6(String base20) {\n        char[] chars = base20.toCharArray();\n        StringBuilder sb = new StringBuilder();\n        for ( int i = 0 ; i < chars.length ; i++ ) {\n            if ( i == 0 ) {\n                sb.append(boxLL);\n            }\n            for ( int j = 0 ; j < 4 ; j++ ) {\n                sb.append(boxHorz);\n            }\n            sb.append(i < chars.length-1 ? boxTeeLow : boxLR);\n        }\n        System.out.println(sb.toString());\n    }\n\n}\n"}
{"id": 59709, "name": "Ramsey's theorem", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n"}
{"id": 59710, "name": "Ramsey's theorem", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n", "Java": "import java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class RamseysTheorem {\n\n    static char[][] createMatrix() {\n        String r = \"-\" + Integer.toBinaryString(53643);\n        int len = r.length();\n        return IntStream.range(0, len)\n                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))\n                .map(String::toCharArray)\n                .toArray(char[][]::new);\n    }\n\n    \n    static String ramseyCheck(char[][] mat) {\n        int len = mat.length;\n        char[] connectivity = \"------\".toCharArray();\n\n        for (int a = 0; a < len; a++) {\n            for (int b = 0; b < len; b++) {\n                if (a == b)\n                    continue;\n                connectivity[0] = mat[a][b];\n                for (int c = 0; c < len; c++) {\n                    if (a == c || b == c)\n                        continue;\n                    connectivity[1] = mat[a][c];\n                    connectivity[2] = mat[b][c];\n                    for (int d = 0; d < len; d++) {\n                        if (a == d || b == d || c == d)\n                            continue;\n                        connectivity[3] = mat[a][d];\n                        connectivity[4] = mat[b][d];\n                        connectivity[5] = mat[c][d];\n\n                        \n                        \n                        String conn = new String(connectivity);\n                        if (conn.indexOf('0') == -1)\n                            return String.format(\"Fail, found wholly connected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                        else if (conn.indexOf('1') == -1)\n                            return String.format(\"Fail, found wholly unconnected: \"\n                                    + \"%d %d %d %d\", a, b, c, d);\n                    }\n                }\n            }\n        }\n        return \"Satisfies Ramsey condition.\";\n    }\n\n    public static void main(String[] a) {\n        char[][] mat = createMatrix();\n        for (char[] s : mat)\n            System.out.println(Arrays.toString(s));\n        System.out.println(ramseyCheck(mat));\n    }\n}\n"}
{"id": 59711, "name": "GUI_Maximum window dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n"}
{"id": 59712, "name": "Four is magic", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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": "public class FourIsMagic {\n\n    public static void main(String[] args) {\n        for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {\n            String magic = fourIsMagic(n);\n            System.out.printf(\"%d = %s%n\", n, toSentence(magic));\n        }\n    }\n    \n    private static final String toSentence(String s) {\n        return s.substring(0,1).toUpperCase() + s.substring(1) + \".\";\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String fourIsMagic(long n) {\n        if ( n == 4 ) {\n            return numToString(n) + \" is magic\";\n        }\n        String result = numToString(n);\n        return result + \" is \" + numToString(result.length()) + \", \" + fourIsMagic(result.length());\n    }\n    \n    private static final String numToString(long n) {\n        if ( n < 0 ) { \n            return \"negative \" + numToString(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \" \" + numToString(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToString(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToString(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 59713, "name": "Getting the number of decimals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n", "Java": "public static int findNumOfDec(double x){\n    String str = String.valueOf(x);\n    if(str.endsWith(\".0\")) return 0;\n    else return (str.substring(str.indexOf('.')).length() - 1);\n}\n"}
{"id": 59714, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 59715, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 59716, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 59717, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\nclass Test {\n    final static int nMax = 250;\n    final static int nBranches = 4;\n\n    static BigInteger[] rooted = new BigInteger[nMax + 1];\n    static BigInteger[] unrooted = new BigInteger[nMax + 1];\n    static BigInteger[] c = new BigInteger[nBranches];\n\n    static void tree(int br, int n, int l, int inSum, BigInteger cnt) {\n        int sum = inSum;\n        for (int b = br + 1; b <= nBranches; b++) {\n            sum += n;\n\n            if (sum > nMax || (l * 2 >= sum && b >= nBranches))\n                return;\n\n            BigInteger tmp = rooted[n];\n            if (b == br + 1) {\n                c[br] = tmp.multiply(cnt);\n            } else {\n                c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));\n                c[br] = c[br].divide(BigInteger.valueOf(b - br));\n            }\n\n            if (l * 2 < sum)\n                unrooted[sum] = unrooted[sum].add(c[br]);\n\n            if (b < nBranches)\n                rooted[sum] = rooted[sum].add(c[br]);\n\n            for (int m = n - 1; m > 0; m--)\n                tree(b, m, l, sum, c[br]);\n        }\n    }\n\n    static void bicenter(int s) {\n        if ((s & 1) == 0) {\n            BigInteger tmp = rooted[s / 2];\n            tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);\n            unrooted[s] = unrooted[s].add(tmp.shiftRight(1));\n        }\n    }\n\n    public static void main(String[] args) {\n        Arrays.fill(rooted, BigInteger.ZERO);\n        Arrays.fill(unrooted, BigInteger.ZERO);\n        rooted[0] = rooted[1] = BigInteger.ONE;\n        unrooted[0] = unrooted[1] = BigInteger.ONE;\n\n        for (int n = 1; n <= nMax; n++) {\n            tree(0, n, n, 1, BigInteger.ONE);\n            bicenter(n);\n            System.out.printf(\"%d: %s%n\", n, unrooted[n]);\n        }\n    }\n}\n"}
{"id": 59718, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59719, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59720, "name": "Parse an IP Address", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n"}
{"id": 59721, "name": "Knapsack problem_Unbounded", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n"}
{"id": 59722, "name": "Textonyms", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n"}
{"id": 59723, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 59724, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "Java": "package astar;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Comparator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n\nclass AStar {\n    private final List<Node> open;\n    private final List<Node> closed;\n    private final List<Node> path;\n    private final int[][] maze;\n    private Node now;\n    private final int xstart;\n    private final int ystart;\n    private int xend, yend;\n    private final boolean diag;\n\n    \n    static class Node implements Comparable {\n        public Node parent;\n        public int x, y;\n        public double g;\n        public double h;\n        Node(Node parent, int xpos, int ypos, double g, double h) {\n            this.parent = parent;\n            this.x = xpos;\n            this.y = ypos;\n            this.g = g;\n            this.h = h;\n       }\n       \n       @Override\n       public int compareTo(Object o) {\n           Node that = (Node) o;\n           return (int)((this.g + this.h) - (that.g + that.h));\n       }\n   }\n\n    AStar(int[][] maze, int xstart, int ystart, boolean diag) {\n        this.open = new ArrayList<>();\n        this.closed = new ArrayList<>();\n        this.path = new ArrayList<>();\n        this.maze = maze;\n        this.now = new Node(null, xstart, ystart, 0, 0);\n        this.xstart = xstart;\n        this.ystart = ystart;\n        this.diag = diag;\n    }\n    \n    public List<Node> findPathTo(int xend, int yend) {\n        this.xend = xend;\n        this.yend = yend;\n        this.closed.add(this.now);\n        addNeigborsToOpenList();\n        while (this.now.x != this.xend || this.now.y != this.yend) {\n            if (this.open.isEmpty()) { \n                return null;\n            }\n            this.now = this.open.get(0); \n            this.open.remove(0); \n            this.closed.add(this.now); \n            addNeigborsToOpenList();\n        }\n        this.path.add(0, this.now);\n        while (this.now.x != this.xstart || this.now.y != this.ystart) {\n            this.now = this.now.parent;\n            this.path.add(0, this.now);\n        }\n        return this.path;\n    }\n     \n    public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){\n        Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();\n        if(maze[stateNode.getR()][stateNode.getC()] == 2){\n            if(isNodeILegal(stateNode, stateNode.expandDirection())){     \n                exploreNodes.add(stateNode.expandDirection());\n         }\n     }\n    \n    public void AStarSearch(){\n        this.start.setCostToGoal(this.start.calculateCost(this.goal));\n        this.start.setPathCost(0);\n        this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());\n        Mazecoord intialNode = this.start;\n        Mazecoord stateNode = intialNode;\n        frontier.add(intialNode);\n        \n        while (true){\n            if(frontier.isEmpty()){\n                System.out.println(\"fail\");\n                System.out.println(explored.size());\n                System.exit(-1);\n            }\n     }\n    \n    \n    public int calculateCost(Mazecoord goal){\n        int rState = this.getR();\n        int rGoal = goal.getR();\n        int diffR = rState - rGoal;\n        int diffC = this.getC() - goal.getC();\n        if(diffR * diffC > 0) {     \n            return Math.abs(diffR) + Math.abs(diffC);\n        } else {\n            return Math.max(Math.abs(diffR), Math.abs(diffC));\n        }\n    }\n\n    public Coord getFather(){\n        return this.father;\n    }\n\n    public void setFather(Mazecoord node){\n        this.father = node;\n    }\n\n   public int getAStartCost() {\n        return AStartCost;\n    }\n\n    public void setAStartCost(int aStartCost) {\n        AStartCost = aStartCost;\n    }\n\n    public int getCostToGoal() {\n        return costToGoal;\n    }\n\n    public void setCostToGoal(int costToGoal) {\n        this.costToGoal = costToGoal;\n    }\n    \n    private double distance(int dx, int dy) {\n        if (this.diag) { \n            return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend); \n        } else {\n            return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend); \n        }\n    }\n    private void addNeigborsToOpenList() {\n        Node node;\n        for (int x = -1; x <= 1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (!this.diag && x != 0 && y != 0) {\n                    continue; \n                }\n                node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));\n                if ((x != 0 || y != 0) \n                    && this.now.x + x >= 0 && this.now.x + x < this.maze[0].length \n                    && this.now.y + y >= 0 && this.now.y + y < this.maze.length\n                    && this.maze[this.now.y + y][this.now.x + x] != -1 \n                    && !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) { \n                        node.g = node.parent.g + 1.; \n                        node.g += maze[this.now.y + y][this.now.x + x]; \n\n                        \n                        \n                        \n                        this.open.add(node);\n                }\n            }\n        }\n        Collections.sort(this.open);\n    }\n\n    public static void main(String[] args) {\n        \n        \n        int[][] maze = {\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n            {  0,  0,  0,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,  0,  0,100,  0,  0},\n            {  0,  0,100,100,100,100,  0,  0},\n            {  0,  0,  0,  0,  0,  0,  0,  0},\n        };\n        AStar as = new AStar(maze, 0, 0, true);\n        List<Node> path = as.findPathTo(7, 7);\n        if (path != null) {\n            path.forEach((n) -> {\n                System.out.print(\"[\" + n.x + \", \" + n.y + \"] \");\n                maze[n.y][n.x] = -1;\n            });\n            System.out.printf(\"\\nTotal cost: %.02f\\n\", path.get(path.size() - 1).g);\n\n            for (int[] maze_row : maze) {\n                for (int maze_entry : maze_row) {\n                    switch (maze_entry) {\n                        case 0:\n                            System.out.print(\"_\");\n                            break;\n                        case -1:\n                            System.out.print(\"*\");\n                            break;\n                        default:\n                            System.out.print(\"#\");\n                    }\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 59725, "name": "Teacup rim text", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Teacup {\n    public static void main(String[] args) {\n        if (args.length != 1) {\n            System.err.println(\"usage: java Teacup dictionary\");\n            System.exit(1);\n        }\n        try {\n            findTeacupWords(loadDictionary(args[0]));\n        } catch (Exception ex) {\n            System.err.println(ex.getMessage());\n        }\n    }\n\n    \n    private static Set<String> loadDictionary(String fileName) throws IOException {\n        Set<String> words = new TreeSet<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String word;\n            while ((word = reader.readLine()) != null)\n                words.add(word);\n            return words;\n        }\n    }\n\n    private static void findTeacupWords(Set<String> words) {\n        List<String> teacupWords = new ArrayList<>();\n        Set<String> found = new HashSet<>();\n        for (String word : words) {\n            int len = word.length();\n            if (len < 3 || found.contains(word))\n                continue;\n            teacupWords.clear();\n            teacupWords.add(word);\n            char[] chars = word.toCharArray();\n            for (int i = 0; i < len - 1; ++i) {\n                String rotated = new String(rotate(chars));\n                if (rotated.equals(word) || !words.contains(rotated))\n                    break;\n                teacupWords.add(rotated);\n            }\n            if (teacupWords.size() == len) {\n                found.addAll(teacupWords);\n                System.out.print(word);\n                for (int i = 1; i < len; ++i)\n                    System.out.print(\" \" + teacupWords.get(i));\n                System.out.println();\n            }\n        }\n    }\n\n    private static char[] rotate(char[] ch) {\n        char c = ch[0];\n        System.arraycopy(ch, 1, ch, 0, ch.length - 1);\n        ch[ch.length - 1] = c;\n        return ch;\n    }\n}\n"}
{"id": 59726, "name": "Increasing gaps between consecutive Niven numbers", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n", "Java": "public class NivenNumberGaps {\n\n    \n    \n    public static void main(String[] args) {\n        long prevGap = 0;\n        long prevN = 1;\n        long index = 0;\n        System.out.println(\"Gap      Gap Index   Starting Niven\");\n        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {\n            if ( isNiven(n) ) {\n                index++;\n                long curGap = n - prevN;\n                if ( curGap > prevGap ) {\n                    System.out.printf(\"%3d  %,13d  %,15d%n\", curGap, index, prevN);\n                    prevGap = curGap;\n                }\n                prevN = n;\n            }\n        }\n    }\n    \n    public static boolean isNiven(long n) {\n        long sum = 0;\n        long nSave = n;\n        while ( n > 0 ) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return nSave % sum == 0;\n    }\n\n}\n"}
{"id": 59727, "name": "Print debugging statement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n", "Java": "import java.util.Objects;\n\npublic class PrintDebugStatement {\n    \n    private static void printDebug(String message) {\n        Objects.requireNonNull(message);\n\n        RuntimeException exception = new RuntimeException();\n        StackTraceElement[] stackTrace = exception.getStackTrace();\n        \n        \n        StackTraceElement stackTraceElement = stackTrace[1];\n        String fileName = stackTraceElement.getFileName();\n        String className = stackTraceElement.getClassName();\n        String methodName = stackTraceElement.getMethodName();\n        int lineNumber = stackTraceElement.getLineNumber();\n\n        System.out.printf(\"[DEBUG][%s %s.%s#%d] %s\\n\", fileName, className, methodName, lineNumber, message);\n    }\n\n    private static void blah() {\n        printDebug(\"Made It!\");\n    }\n\n    public static void main(String[] args) {\n        printDebug(\"Hello world.\");\n        blah();\n\n        Runnable oops = () -> printDebug(\"oops\");\n        oops.run();\n    }\n}\n"}
{"id": 59728, "name": "Superellipse", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59729, "name": "Superellipse", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.pow;\nimport java.util.Hashtable;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class SuperEllipse extends JPanel implements ChangeListener {\n    private double exp = 2.5;\n\n    public SuperEllipse() {\n        setPreferredSize(new Dimension(650, 650));\n        setBackground(Color.white);\n        setFont(new Font(\"Serif\", Font.PLAIN, 18));\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setStroke(new BasicStroke(2));\n        g.setColor(new Color(0xEEEEEE));\n\n        int w = getWidth();\n        int h = getHeight();\n        int spacing = 25;\n\n        for (int i = 0; i < w / spacing; i++) {\n            g.drawLine(0, i * spacing, w, i * spacing);\n            g.drawLine(i * spacing, 0, i * spacing, w);\n        }\n        g.drawLine(0, h - 1, w, h - 1);\n\n        g.setColor(new Color(0xAAAAAA));\n        g.drawLine(0, w / 2, w, w / 2);\n        g.drawLine(w / 2, 0, w / 2, w);\n    }\n\n    void drawLegend(Graphics2D g) {\n        g.setColor(Color.black);\n        g.setFont(getFont());\n        g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45);\n        g.drawString(\"a = b = 200\", getWidth() - 150, 75);\n    }\n\n    void drawEllipse(Graphics2D g) {\n\n        final int a = 200; \n        double[] points = new double[a + 1];\n\n        Path2D p = new Path2D.Double();\n        p.moveTo(a, 0);\n\n        \n        for (int x = a; x >= 0; x--) {\n            points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); \n            p.lineTo(x, -points[x]);\n        }\n\n        \n        for (int x = 0; x <= a; x++)\n            p.lineTo(x, points[x]);\n\n        for (int x = a; x >= 0; x--)\n            p.lineTo(-x, points[x]);\n\n        for (int x = 0; x <= a; x++)\n            p.lineTo(-x, -points[x]);\n\n        g.translate(getWidth() / 2, getHeight() / 2);\n        g.setStroke(new BasicStroke(2));\n\n        g.setColor(new Color(0x25B0C4DE, true));\n        g.fill(p);\n\n        g.setColor(new Color(0xB0C4DE)); \n        g.draw(p);\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        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n        drawGrid(g);\n        drawLegend(g);\n        drawEllipse(g);\n    }\n\n    @Override\n    public void stateChanged(ChangeEvent e) {\n        JSlider source = (JSlider) e.getSource();\n        exp = source.getValue() / 2.0;\n        repaint();\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(\"Super Ellipse\");\n            f.setResizable(false);\n            SuperEllipse panel = new SuperEllipse();\n            f.add(panel, BorderLayout.CENTER);\n\n            JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);\n            exponent.addChangeListener(panel);\n            exponent.setMajorTickSpacing(1);\n            exponent.setPaintLabels(true);\n            exponent.setBackground(Color.white);\n            exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n\n            Hashtable<Integer, JLabel> labelTable = new Hashtable<>();\n            for (int i = 1; i < 10; i++)\n                labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));\n            exponent.setLabelTable(labelTable);\n\n            f.add(exponent, BorderLayout.SOUTH);\n\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59730, "name": "Permutations_Rank of a permutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n"}
{"id": 59731, "name": "Permutations_Rank of a permutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\nclass RankPermutation\n{\n  public static BigInteger getRank(int[] permutation)\n  {\n    int n = permutation.length;\n    BitSet usedDigits = new BitSet();\n    BigInteger rank = BigInteger.ZERO;\n    for (int i = 0; i < n; i++)\n    {\n      rank = rank.multiply(BigInteger.valueOf(n - i));\n      int digit = 0;\n      int v = -1;\n      while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])\n        digit++;\n      usedDigits.set(v);\n      rank = rank.add(BigInteger.valueOf(digit));\n    }\n    return rank;\n  }\n  \n  public static int[] getPermutation(int n, BigInteger rank)\n  {\n    int[] digits = new int[n];\n    for (int digit = 2; digit <= n; digit++)\n    {\n      BigInteger divisor = BigInteger.valueOf(digit);\n      digits[n - digit] = rank.mod(divisor).intValue();\n      if (digit < n)\n        rank = rank.divide(divisor);\n    }\n    BitSet usedDigits = new BitSet();\n    int[] permutation = new int[n];\n    for (int i = 0; i < n; i++)\n    {\n      int v = usedDigits.nextClearBit(0);\n      for (int j = 0; j < digits[i]; j++)\n        v = usedDigits.nextClearBit(v + 1);\n      permutation[i] = v;\n      usedDigits.set(v);\n    }\n    return permutation;\n  }\n  \n  public static void main(String[] args)\n  {\n    for (int i = 0; i < 6; i++)\n    {\n      int[] permutation = getPermutation(3, BigInteger.valueOf(i));\n      System.out.println(String.valueOf(i) + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n    }\n    Random rnd = new Random();\n    for (int n : new int[] { 12, 144 })\n    {\n      BigInteger factorial = BigInteger.ONE;\n      for (int i = 2; i <= n; i++)\n        factorial = factorial.multiply(BigInteger.valueOf(i));\n      \n      System.out.println(\"n = \" + n);\n      for (int i = 0; i < 5; i++)\n      {\n        BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);\n        rank = rank.mod(factorial);\n        int[] permutation = getPermutation(n, rank);\n        System.out.println(\"  \" + rank + \" --> \" + Arrays.toString(permutation) + \" --> \" + getRank(permutation));\n      }\n    }\n  }\n  \n}\n"}
{"id": 59732, "name": "Range extraction", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 59733, "name": "Type detection", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n"}
{"id": 59734, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n"}
{"id": 59735, "name": "Zhang-Suen thinning algorithm", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n"}
{"id": 59736, "name": "Variable declaration reset", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n"}
{"id": 59737, "name": "Find first and last set bit of a long integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 59738, "name": "Find first and last set bit of a long integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n", "Java": "public class FirstLastBits {\n\n    \n    public static int mssb(int x) {\n        return Integer.highestOneBit(x);\n    }\n\n    public static long mssb(long x) {\n        return Long.highestOneBit(x);\n    }\n\n    public static int mssb_idx(int x) {\n        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(long x) {\n        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);\n    }\n\n    public static int mssb_idx(BigInteger x) {\n\treturn x.bitLength() - 1;\n    }\n\n    \n    public static int lssb(int x) {\n        return Integer.lowestOneBit(x);\n    }\n\n    public static long lssb(long x) {\n        return Long.lowestOneBit(x);\n    }\n\n    public static int lssb_idx(int x) {\n        return Integer.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(long x) {\n        return Long.numberOfTrailingZeros(x);\n    }\n\n    public static int lssb_idx(BigInteger x) {\n\treturn x.getLowestSetBit();\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"int:\");\n        int n1 = 1;\n        for (int i = 0; ; i++, n1 *= 42) {\n            System.out.printf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n                              i, n1, n1,\n                              mssb(n1), mssb_idx(n1),\n                              lssb(n1), lssb_idx(n1));\n            if (n1 >= Integer.MAX_VALUE / 42)\n                break;\n        }\n        System.out.println();\n        System.out.println(\"long:\");\n        long n2 = 1;\n        for (int i = 0; ; i++, n2 *= 42) {\n            System.out.printf(\"42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\\n\",\n                              i, n2, n2,\n                              mssb(n2), mssb_idx(n2),\n                              lssb(n2), lssb_idx(n2));\n            if (n2 >= Long.MAX_VALUE / 42)\n                break;\n        }\n\tSystem.out.println();\n\tSystem.out.println(\"BigInteger:\");\n\tBigInteger n3 = BigInteger.ONE;\n\tBigInteger k = BigInteger.valueOf(1302);\n\tfor (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {\n\t    System.out.printf(\"1302**%02d = %30d(x%28x): M %2d L %2d\\n\",\n\t\t\t      i, n3, n3,\n\t\t\t      mssb_idx(n3),\n\t\t\t      lssb_idx(n3));\n\t}\n    }\n}\n"}
{"id": 59739, "name": "Numbers with equal rises and falls", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n", "Java": "public class EqualRisesFalls {\n    public static void main(String[] args) {\n        final int limit1 = 200;\n        final int limit2 = 10000000;\n        System.out.printf(\"The first %d numbers in the sequence are:\\n\", limit1);\n        int n = 0;\n        for (int count = 0; count < limit2; ) {\n            if (equalRisesAndFalls(++n)) {\n                ++count;\n                if (count <= limit1)\n                    System.out.printf(\"%3d%c\", n, count % 20 == 0 ? '\\n' : ' ');\n            }\n        }\n        System.out.printf(\"\\nThe %dth number in the sequence is %d.\\n\", limit2, n);\n    }\n\n    private static boolean equalRisesAndFalls(int n) {\n        int total = 0;\n        for (int previousDigit = -1; n > 0; n /= 10) {\n            int digit = n % 10;\n            if (previousDigit > digit)\n                ++total;\n            else if (previousDigit >= 0 && previousDigit < digit)\n                --total;\n            previousDigit = digit;\n        }\n        return total == 0;\n    }\n}\n"}
{"id": 59740, "name": "Koch curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n"}
{"id": 59741, "name": "Draw pixel 2", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 640, 480)\n    img := image.NewRGBA(rect)\n\n    \n    blue := color.RGBA{0, 0, 255, 255}\n    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)\n\n    \n    yellow := color.RGBA{255, 255, 0, 255}\n    width := img.Bounds().Dx()\n    height := img.Bounds().Dy()\n    rand.Seed(time.Now().UnixNano())\n    x := rand.Intn(width)\n    y := rand.Intn(height)\n    img.Set(x, y, yellow)\n\n    \n    cmap := map[color.Color]string{blue: \"blue\", yellow: \"yellow\"}\n    for i := 0; i < width; i++ {\n        for j := 0; j < height; j++ {\n            c := img.At(i, j)\n            if cmap[c] == \"yellow\" {\n                fmt.Printf(\"The color of the pixel at (%d, %d) is yellow\\n\", i, j)\n            }\n        }\n    }\n}\n", "Java": "\n\nsize(640,480);\n\nstroke(#ffff00);\n\nellipse(random(640),random(480),1,1);\n"}
{"id": 59742, "name": "Draw a pixel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n"}
{"id": 59743, "name": "Draw a pixel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n"}
{"id": 59744, "name": "Words from neighbour ones", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n"}
{"id": 59745, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 59746, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "Java": "public class GateLogic\n{\n  \n  public interface OneInputGate\n  {  boolean eval(boolean input);  }\n  \n  public interface TwoInputGate\n  {  boolean eval(boolean input1, boolean input2);  }\n  \n  public interface MultiGate\n  {  boolean[] eval(boolean... inputs);  }\n  \n  \n  public static OneInputGate NOT = new OneInputGate() {\n    public boolean eval(boolean input)\n    {  return !input;  }\n  };\n  \n  \n  public static TwoInputGate AND = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 && input2;  }\n  };\n  \n  \n  public static TwoInputGate OR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {  return input1 || input2;  }\n  };\n  \n  \n  public static TwoInputGate XOR = new TwoInputGate() {\n    public boolean eval(boolean input1, boolean input2)\n    {\n      return OR.eval(\n               AND.eval(input1, NOT.eval(input2)),\n               AND.eval(NOT.eval(input1), input2)\n             );\n    }\n  };\n  \n  \n  public static MultiGate HALF_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 2)\n        throw new IllegalArgumentException();\n      return new boolean[] {\n        XOR.eval(inputs[0], inputs[1]),  \n        AND.eval(inputs[0], inputs[1])   \n      };\n    }\n  };\n  \n  \n  public static MultiGate FULL_ADDER = new MultiGate() {\n    public boolean[] eval(boolean... inputs)\n    {\n      if (inputs.length != 3)\n        throw new IllegalArgumentException();\n      \n      \n      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);\n      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);\n      return new boolean[] {\n        haOutputs2[0],                         \n        OR.eval(haOutputs1[1], haOutputs2[1])  \n      };\n    }\n  };\n  \n  public static MultiGate buildAdder(final int numBits)\n  {\n    return new MultiGate() {\n      public boolean[] eval(boolean... inputs)\n      {\n        \n        if (inputs.length != (numBits << 1))\n          throw new IllegalArgumentException();\n        boolean[] outputs = new boolean[numBits + 1];\n        boolean[] faInputs = new boolean[3];\n        boolean[] faOutputs = null;\n        for (int i = 0; i < numBits; i++)\n        {\n          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  \n          faInputs[1] = inputs[i];                                   \n          faInputs[2] = inputs[numBits + i];                         \n          faOutputs = FULL_ADDER.eval(faInputs);\n          outputs[i] = faOutputs[0];                                 \n        }\n        if (faOutputs != null)\n          outputs[numBits] = faOutputs[1];                           \n        return outputs;\n      }\n    };\n  }\n  \n  public static void main(String[] args)\n  {\n    int numBits = Integer.parseInt(args[0]);\n    int firstNum = Integer.parseInt(args[1]);\n    int secondNum = Integer.parseInt(args[2]);\n    int maxNum = 1 << numBits;\n    if ((firstNum < 0) || (firstNum >= maxNum))\n    {\n      System.out.println(\"First number is out of range\");\n      return;\n    }\n    if ((secondNum < 0) || (secondNum >= maxNum))\n    {\n      System.out.println(\"Second number is out of range\");\n      return;\n    }\n    \n    MultiGate multiBitAdder = buildAdder(numBits);\n    \n    boolean[] inputs = new boolean[numBits << 1];\n    String firstNumDisplay = \"\";\n    String secondNumDisplay = \"\";\n    for (int i = 0; i < numBits; i++)\n    {\n      boolean firstBit = ((firstNum >>> i) & 1) == 1;\n      boolean secondBit = ((secondNum >>> i) & 1) == 1;\n      inputs[i] = firstBit;\n      inputs[numBits + i] = secondBit;\n      firstNumDisplay = (firstBit ? \"1\" : \"0\") + firstNumDisplay;\n      secondNumDisplay = (secondBit ? \"1\" : \"0\") + secondNumDisplay;\n    }\n    \n    boolean[] outputs = multiBitAdder.eval(inputs);\n    int outputNum = 0;\n    String outputNumDisplay = \"\";\n    String outputCarryDisplay = null;\n    for (int i = numBits; i >= 0; i--)\n    {\n      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);\n      if (i == numBits)\n        outputCarryDisplay = outputs[i] ? \"1\" : \"0\";\n      else\n        outputNumDisplay += (outputs[i] ? \"1\" : \"0\");\n    }\n    System.out.println(\"numBits=\" + numBits);\n    System.out.println(\"A=\" + firstNumDisplay + \" (\" + firstNum + \"), B=\" + secondNumDisplay + \" (\" + secondNum + \"), S=\" + outputCarryDisplay + \" \" + outputNumDisplay + \" (\" + outputNum + \")\");\n    return;\n  }\n  \n}\n"}
{"id": 59747, "name": "Magic squares of singly even order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n", "Java": "public class MagicSquareSinglyEven {\n\n    public static void main(String[] args) {\n        int n = 6;\n        for (int[] row : magicSquareSinglyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%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 n) {\n        if (n < 3 || n % 2 == 0)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int value = 0;\n        int gridSize = n * n;\n        int c = n / 2, r = 0;\n\n        int[][] result = new int[n][n];\n\n        while (++value <= gridSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n\n    static int[][] magicSquareSinglyEven(final int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4 plus 2\");\n\n        int size = n * n;\n        int halfN = n / 2;\n        int subSquareSize = size / 4;\n\n        int[][] subSquare = magicSquareOdd(halfN);\n        int[] quadrantFactors = {0, 2, 3, 1};\n        int[][] result = new int[n][n];\n\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int quadrant = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subSquare[r % halfN][c % halfN];\n                result[r][c] += quadrantFactors[quadrant] * subSquareSize;\n            }\n        }\n\n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n\n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n\n                    if (c == 0 && r == nColsLeft)\n                        continue;\n\n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n\n        return result;\n    }\n}\n"}
{"id": 59748, "name": "Generate Chess960 starting position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Chess960{\n\tprivate static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');\n\n\tpublic static List<Character> generateFirstRank(){\n\t\tdo{\n\t\t\tCollections.shuffle(pieces);\n\t\t}while(!check(pieces.toString().replaceAll(\"[^\\\\p{Upper}]\", \"\"))); \n\t\t\n\t\treturn pieces;\n\t}\n\n\tprivate static boolean check(String rank){\n\t\tif(!rank.matches(\".*R.*K.*R.*\")) return false;\t\t\t\n\t\tif(!rank.matches(\".*B(..|....|......|)B.*\")) return false;\t\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i < 10; i++){\n\t\t\tSystem.out.println(generateFirstRank());\n\t\t}\n\t}\n}\n"}
{"id": 59749, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 59750, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 59751, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 59752, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "Java": "public class ScriptedMain {\n\tpublic static int meaningOfLife() {\n\t\treturn 42;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Main: The meaning of life is \" + meaningOfLife());\n\t}\n}\n"}
{"id": 59753, "name": "Perlin noise", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n    X := int(math.Floor(x)) & 255\n    Y := int(math.Floor(y)) & 255\n    Z := int(math.Floor(z)) & 255\n    x -= math.Floor(x)\n    y -= math.Floor(y)\n    z -= math.Floor(z)\n    u := fade(x)\n    v := fade(y)\n    w := fade(z)\n    A := p[X] + Y\n    AA := p[A] + Z\n    AB := p[A+1] + Z\n    B := p[X+1] + Y\n    BA := p[B] + Z\n    BB := p[B+1] + Z\n    return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n        grad(p[BA], x-1, y, z)),\n        lerp(u, grad(p[AB], x, y-1, z),\n            grad(p[BB], x-1, y-1, z))),\n        lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n            grad(p[BA+1], x-1, y, z-1)),\n            lerp(u, grad(p[AB+1], x, y-1, z-1),\n                grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n    \n    \n    \n    switch hash & 15 {\n    case 0, 12:\n        return x + y\n    case 1, 14:\n        return y - x\n    case 2:\n        return x - y\n    case 3:\n        return -x - y\n    case 4:\n        return x + z\n    case 5:\n        return z - x\n    case 6:\n        return x - z\n    case 7:\n        return -x - z\n    case 8:\n        return y + z\n    case 9, 13:\n        return z - y\n    case 10:\n        return y - z\n    }\n    \n    return -y - z\n}\n\nvar permutation = []int{\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n    140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n    247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n    57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n    74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n    60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n    65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n    200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n    52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n    207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n    119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n    129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n    218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n    81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n    184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n    222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)\n", "Java": "\n\npublic final class ImprovedNoise {\n   static public double noise(double x, double y, double z) {\n      int X = (int)Math.floor(x) & 255,                  \n          Y = (int)Math.floor(y) & 255,                  \n          Z = (int)Math.floor(z) & 255;\n      x -= Math.floor(x);                                \n      y -= Math.floor(y);                                \n      z -= Math.floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      \n\n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  \n                                     grad(p[BA  ], x-1, y  , z   )), \n                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\n   static double lerp(double t, double a, double b) { return a + t * (b - a); }\n   static double grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,\n   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,\n   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,\n   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,\n   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,\n   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,\n   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,\n   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,\n   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,\n   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,\n   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,\n   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,\n   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180\n   };\n   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }\n}\n"}
{"id": 59754, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "Java": "package rosetta;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class UnixLS {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.list(Path.of(\"\")).sorted().forEach(System.out::println);\n\t}\n}\n"}
{"id": 59755, "name": "UTF-8 encode and decode", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n"}
{"id": 59756, "name": "Xiaolin Wu's line algorithm", "Go": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n    return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n    return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n    return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n    return 1 - fpart(x)\n}\n\n\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n    \n    dx := x2 - x1\n    dy := y2 - y1\n    ax := dx\n    if ax < 0 {\n        ax = -ax\n    }\n    ay := dy\n    if ay < 0 {\n        ay = -ay\n    }\n    \n    var plot func(int, int, float64)\n    if ax < ay {\n        x1, y1 = y1, x1\n        x2, y2 = y2, x2\n        dx, dy = dy, dx\n        plot = func(x, y int, c float64) {\n            g.SetPx(y, x, uint16(c*math.MaxUint16))\n        }\n    } else {\n        plot = func(x, y int, c float64) {\n            g.SetPx(x, y, uint16(c*math.MaxUint16))\n        }\n    }\n    if x2 < x1 {\n        x1, x2 = x2, x1\n        y1, y2 = y2, y1\n    }\n    gradient := dy / dx\n\n    \n    xend := round(x1)\n    yend := y1 + gradient*(xend-x1)\n    xgap := rfpart(x1 + .5)\n    xpxl1 := int(xend) \n    ypxl1 := int(ipart(yend))\n    plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n    intery := yend + gradient \n\n    \n    xend = round(x2)\n    yend = y2 + gradient*(xend-x2)\n    xgap = fpart(x2 + 0.5)\n    xpxl2 := int(xend) \n    ypxl2 := int(ipart(yend))\n    plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n    \n    for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n        plot(x, int(ipart(intery)), rfpart(intery))\n        plot(x, int(ipart(intery))+1, fpart(intery))\n        intery = intery + gradient\n    }\n}\n", "Java": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n    public XiaolinWu() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n    }\n\n    void plot(Graphics2D g, double x, double y, double c) {\n        g.setColor(new Color(0f, 0f, 0f, (float)c));\n        g.fillOval((int) x, (int) y, 2, 2);\n    }\n\n    int ipart(double x) {\n        return (int) x;\n    }\n\n    double fpart(double x) {\n        return x - floor(x);\n    }\n\n    double rfpart(double x) {\n        return 1.0 - fpart(x);\n    }\n\n    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n        boolean steep = abs(y1 - y0) > abs(x1 - x0);\n        if (steep)\n            drawLine(g, y0, x0, y1, x1);\n\n        if (x0 > x1)\n            drawLine(g, x1, y1, x0, y0);\n\n        double dx = x1 - x0;\n        double dy = y1 - y0;\n        double gradient = dy / dx;\n\n        \n        double xend = round(x0);\n        double yend = y0 + gradient * (xend - x0);\n        double xgap = rfpart(x0 + 0.5);\n        double xpxl1 = xend; \n        double ypxl1 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n        }\n\n        \n        double intery = yend + gradient;\n\n        \n        xend = round(x1);\n        yend = y1 + gradient * (xend - x1);\n        xgap = fpart(x1 + 0.5);\n        double xpxl2 = xend; \n        double ypxl2 = ipart(yend);\n\n        if (steep) {\n            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n        } else {\n            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n        }\n\n        \n        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n            if (steep) {\n                plot(g, ipart(intery), x, rfpart(intery));\n                plot(g, ipart(intery) + 1, x, fpart(intery));\n            } else {\n                plot(g, x, ipart(intery), rfpart(intery));\n                plot(g, x, ipart(intery) + 1, fpart(intery));\n            }\n            intery = intery + gradient;\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        drawLine(g, 550, 170, 50, 435);\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(\"Xiaolin Wu's line algorithm\");\n            f.setResizable(false);\n            f.add(new XiaolinWu(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59757, "name": "Keyboard macros", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"unsafe\"\n\nfunc main() {\n    d := C.XOpenDisplay(nil)\n    f7, f6 := C.CString(\"F7\"), C.CString(\"F6\")\n    defer C.free(unsafe.Pointer(f7))\n    defer C.free(unsafe.Pointer(f6))\n\n    if d != nil {\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),\n            C.Mod1Mask, \n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),\n            C.Mod1Mask,\n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n\n        var event C.XEvent\n        for {\n            C.XNextEvent(d, &event)\n            if C.getXEvent_type(event) == C.KeyPress {\n                xkeyEvent := C.getXEvent_xkey(event)\n                s := C.XLookupKeysym(&xkeyEvent, 0)\n                if s == C.XK_F7 {\n                    fmt.Println(\"something's happened\")\n                } else if s == C.XK_F6 {\n                    break\n                }\n            }\n        }\n\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n    } else {\n        fmt.Println(\"XOpenDisplay did not succeed\")\n    }\n}\n", "Java": "package keybord.macro.demo;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nclass KeyboardMacroDemo {\n    public static void main( String [] args ) {\n        final JFrame frame = new JFrame();\n        \n        String directions = \"<html><b>Ctrl-S</b> to show frame title<br>\"\n                                 +\"<b>Ctrl-H</b> to hide it</html>\";\n                                 \n        frame.add( new JLabel(directions));\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        \n        frame.addKeyListener( new KeyAdapter(){\n            public void keyReleased( KeyEvent e ) {\n                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){\n                    frame.setTitle(\"Hello there\");\n                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){\n                    frame.setTitle(\"\");\n                }\n            }\n        });\n        frame.pack();\n        frame.setVisible(true);\n    }\n}\n"}
{"id": 59758, "name": "McNuggets problem", "Go": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n    sv := make([]bool, limit+1) \n    for s := 0; s <= limit; s += 6 {\n        for n := s; n <= limit; n += 9 {\n            for t := n; t <= limit; t += 20 {\n                sv[t] = true\n            }\n        }\n    }\n    for i := limit; i >= 0; i-- {\n        if !sv[i] {\n            fmt.Println(\"Maximum non-McNuggets number is\", i)\n            return\n        }\n    }\n}\n\nfunc main() {\n    mcnugget(100)\n}\n", "Java": "public class McNuggets {\n\n    public static void main(String... args) {\n        int[] SIZES = new int[] { 6, 9, 20 };\n        int MAX_TOTAL = 100;\n        \n        int numSizes = SIZES.length;\n        int[] counts = new int[numSizes];\n        int maxFound = MAX_TOTAL + 1;\n        boolean[] found = new boolean[maxFound];\n        int numFound = 0;\n        int total = 0;\n        boolean advancedState = false;\n        do {\n            if (!found[total]) {\n                found[total] = true;\n                numFound++;\n            }\n            \n            \n            advancedState = false;\n            for (int i = 0; i < numSizes; i++) {\n                int curSize = SIZES[i];\n                if ((total + curSize) > MAX_TOTAL) {\n                    \n                    total -= counts[i] * curSize;\n                    counts[i] = 0;\n                }\n                else {\n                    \n                    counts[i]++;\n                    total += curSize;\n                    advancedState = true;\n                    break;\n                }\n            }\n            \n        } while ((numFound < maxFound) && advancedState);\n        \n        if (numFound < maxFound) {\n            \n            for (int i = MAX_TOTAL; i >= 0; i--) {\n                if (!found[i]) {\n                    System.out.println(\"Largest non-McNugget number in the search space is \" + i);\n                    break;\n                }\n            }\n        }\n        else {\n            System.out.println(\"All numbers in the search space are McNugget numbers\");\n        }\n        \n        return;\n    }\n}\n"}
{"id": 59759, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 59760, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 59761, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 59762, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "Java": "public class Extreme {\n    public static void main(String[] args) {\n        double negInf = -1.0 / 0.0; \n        double inf = 1.0 / 0.0; \n        double nan = 0.0 / 0.0; \n        double negZero = -2.0 / inf;\n\n        System.out.println(\"Negative inf: \" + negInf);\n        System.out.println(\"Positive inf: \" + inf);\n        System.out.println(\"NaN: \" + nan);\n        System.out.println(\"Negative 0: \" + negZero);\n        System.out.println(\"inf + -inf: \" + (inf + negInf));\n        System.out.println(\"0 * NaN: \" + (0 * nan));\n        System.out.println(\"NaN == NaN: \" + (nan == nan));\n    }\n}\n"}
{"id": 59763, "name": "Pseudo-random numbers_Xorshift star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "Java": "public class XorShiftStar {\n    private static final long MAGIC = Long.parseUnsignedLong(\"2545F4914F6CDD1D\", 16);\n    private long state;\n\n    public void seed(long num) {\n        state = num;\n    }\n\n    public int nextInt() {\n        long x;\n        int answer;\n\n        x = state;\n        x = x ^ (x >>> 12);\n        x = x ^ (x << 25);\n        x = x ^ (x >>> 27);\n        state = x;\n        answer = (int) ((x * MAGIC) >> 32);\n\n        return answer;\n    }\n\n    public float nextFloat() {\n        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);\n    }\n\n    public static void main(String[] args) {\n        var rng = new XorShiftStar();\n        rng.seed(1234567);\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println(Integer.toUnsignedString(rng.nextInt()));\n        System.out.println();\n\n        int[] counts = {0, 0, 0, 0, 0};\n        rng.seed(987654321);\n        for (int i = 0; i < 100_000; i++) {\n            int j = (int) Math.floor(rng.nextFloat() * 5.0);\n            counts[j]++;\n        }\n        for (int i = 0; i < counts.length; i++) {\n            System.out.printf(\"%d: %d\\n\", i, counts[i]);\n        }\n    }\n}\n"}
{"id": 59764, "name": "Four is the number of letters in the ...", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class FourIsTheNumberOfLetters {\n\n    public static void main(String[] args) {\n        String [] words = neverEndingSentence(201);\n        System.out.printf(\"Display the first 201 numbers in the sequence:%n%3d: \", 1);\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            System.out.printf(\"%2d \", numberOfLetters(words[i]));\n            if ( (i+1) % 25 == 0 ) {\n                System.out.printf(\"%n%3d: \", i+2);\n            }\n        }\n        System.out.printf(\"%nTotal number of characters in the sentence is %d%n\", characterCount(words));\n        for ( int i = 3 ; i <= 7 ; i++ ) {\n            int index = (int) Math.pow(10, i);\n            words = neverEndingSentence(index);\n            String last = words[words.length-1].replace(\",\", \"\");\n            System.out.printf(\"Number of letters of the %s word is %d. The word is \\\"%s\\\".  The sentence length is %,d characters.%n\", toOrdinal(index), numberOfLetters(last), last, characterCount(words));\n        }\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static void displaySentence(String[] words, int lineLength) {\n        int currentLength = 0;\n        for ( String word : words ) {\n            if ( word.length() + currentLength > lineLength ) {\n                String first = word.substring(0, lineLength-currentLength);\n                String second = word.substring(lineLength-currentLength);\n                System.out.println(first);\n                System.out.print(second);\n                currentLength = second.length();\n            }\n            else {\n                System.out.print(word);\n                currentLength += word.length();\n            }\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n            System.out.print(\" \");\n            currentLength++;\n            if ( currentLength == lineLength ) {\n                System.out.println();\n                currentLength = 0;\n            }\n        }\n        System.out.println();\n    }\n    \n    private static int numberOfLetters(String word) {\n        return word.replace(\",\",\"\").replace(\"-\",\"\").length();\n    }\n    \n    private static long characterCount(String[] words) {\n        int characterCount = 0;\n        for ( int i = 0 ; i < words.length ; i++ ) {\n            characterCount += words[i].length() + 1;\n        }        \n        \n        characterCount--;\n        return characterCount;\n    }\n    \n    private static String[] startSentence = new String[] {\"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\", \"first\", \"word\", \"of\", \"this\", \"sentence,\"};\n    \n    private static String[] neverEndingSentence(int wordCount) {\n        String[] words = new String[wordCount];\n        int index;\n        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {\n            words[index] = startSentence[index];\n        }\n        int sentencePosition = 1;\n        while ( index < wordCount ) {\n            \n            \n            sentencePosition++;\n            String word = words[sentencePosition-1];\n            for ( String wordLoop : numToString(numberOfLetters(word)).split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n            \n            words[index] = \"in\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            words[index] = \"the\";\n            index++;\n            if ( index == wordCount ) {\n                break;\n            }\n            \n            for ( String wordLoop : (toOrdinal(sentencePosition) + \",\").split(\" \") ) {\n                words[index] = wordLoop;\n                index++;\n                if ( index == wordCount ) {\n                    break;\n                }\n            }\n        }\n        return words;\n    }\n    \n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n    \n}\n"}
{"id": 59765, "name": "ASCII art diagram converter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n    private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                      ID                       |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    QDCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ANCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    NSCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n            \"|                    ARCOUNT                    |\\r\\n\" +\n            \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n    public static void main(String[] args) {\n        validate(TEST);\n        display(TEST);\n        Map<String,List<Integer>> asciiMap = decode(TEST);\n        displayMap(asciiMap);\n        displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n    }\n\n    private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {\n        System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n        String bin = new BigInteger(hex,16).toString(2);\n\n        \n        int length = 0;\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            length += pos.get(1) - pos.get(0) + 1;\n        }\n        while ( length > bin.length() ) {\n            bin = \"0\" + bin;\n        }\n        System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n        System.out.printf(\"Name      Size  Bit Pattern%n\");\n        System.out.printf(\"-------- -----  -----------%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            int start = pos.get(0);\n            int end   = pos.get(1);\n            System.out.printf(\"%-8s    %2d  %s%n\", code, end-start+1, bin.substring(start, end+1));\n        }\n\n    }\n\n\n    private static void display(String ascii) {\n        System.out.printf(\"%nDiagram:%n%n\");\n        for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n            System.out.println(s);\n        }\n    }\n\n    private static void displayMap(Map<String,List<Integer>> asciiMap) {\n        System.out.printf(\"%nDecode:%n%n\");\n\n\n        System.out.printf(\"Name      Size  Start    End%n\");\n        System.out.printf(\"-------- -----  -----  -----%n\");\n        for ( String code : asciiMap.keySet() ) {\n            List<Integer> pos = asciiMap.get(code);\n            System.out.printf(\"%-8s    %2d     %2d     %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n        }\n\n    }\n\n    private static Map<String,List<Integer>> decode(String ascii) {\n        Map<String,List<Integer>> map = new LinkedHashMap<>();\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n        int length = split[0].length() - 1;\n        for ( int i = 1 ; i < split.length ; i += 2 ) {\n            int barIndex = 1;\n            String test = split[i];\n            int next;\n            while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n                \n                List<Integer> startEnd = new ArrayList<>();\n                startEnd.add((barIndex/size) + (i/2)*(length/size));\n                startEnd.add(((next-1)/size) + (i/2)*(length/size));\n                String code = test.substring(barIndex, next).replace(\" \", \"\");\n                map.put(code, startEnd);\n                \n                barIndex = next + 1;\n            }\n        }\n\n        return map;\n    }\n\n    private static void validate(String ascii) {\n        String[] split = TEST.split(\"\\\\r\\\\n\");\n        if ( split.length % 2 != 1 ) {\n            throw new RuntimeException(\"ERROR 1:  Invalid number of input lines.  Line count = \" + split.length);\n        }\n        int size = 0;\n        for ( int i = 0 ; i < split.length ; i++ ) {\n            String test = split[i];\n            if ( i % 2 == 0 ) {\n                \n                if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n                    throw new RuntimeException(\"ERROR 2:  Improper line format.  Line = \" + test);\n                }\n                if ( size == 0 ) {\n                    int firstPlus = test.indexOf(\"+\");\n                    int secondPlus = test.indexOf(\"+\", 1);\n                    size = secondPlus - firstPlus;\n                }\n                if ( ((test.length()-1) % size) != 0 ) {\n                    throw new RuntimeException(\"ERROR 3:  Improper line format.  Line = \" + test);\n                }\n                \n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    if ( test.charAt(j) != '+' ) {\n                        throw new RuntimeException(\"ERROR 4:  Improper line format.  Line = \" + test);\n                    }\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        if ( test.charAt(k) != '-' ) {\n                            throw new RuntimeException(\"ERROR 5:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n            }\n            else {\n                \n                if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n                    throw new RuntimeException(\"ERROR 6:  Improper line format.  Line = \" + test);\n                }\n                for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n                    for ( int k = j+1 ; k < j + size ; k++ ) {\n                        \n                        if ( test.charAt(k) == '|' ) {\n                            throw new RuntimeException(\"ERROR 7:  Improper line format.  Line = \" + test);\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n\n}\n"}
{"id": 59766, "name": "Levenshtein distance_Alignment", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"github.com/biogo/biogo/align\"\n    ab \"github.com/biogo/biogo/alphabet\"\n    \"github.com/biogo/biogo/feat\"\n    \"github.com/biogo/biogo/seq/linear\"\n)\n\nfunc main() {\n    \n    \n    lc := ab.Must(ab.NewAlphabet(\"-abcdefghijklmnopqrstuvwxyz\",\n        feat.Undefined, '-', 0, true))\n    \n    \n    \n    \n    nw := make(align.NW, lc.Len())\n    for i := range nw {\n        r := make([]int, lc.Len())\n        nw[i] = r\n        for j := range r {\n            if j != i {\n                r[j] = -1\n            }\n        }\n    }\n    \n    a := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"rosettacode\"))}\n    a.Alpha = lc\n    b := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"raisethysword\"))}\n    b.Alpha = lc\n    \n    aln, err := nw.Align(a, b)\n    \n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fa := align.Format(a, b, aln, '-')\n    fmt.Printf(\"%s\\n%s\\n\", fa[0], fa[1])\n    aa := fmt.Sprint(fa[0])\n    ba := fmt.Sprint(fa[1])\n    ma := make([]byte, len(aa))\n    for i := range ma {\n        if aa[i] == ba[i] {\n            ma[i] = ' '\n        } else {\n            ma[i] = '|'\n        }\n    }\n    fmt.Println(string(ma))\n}\n", "Java": "public class LevenshteinAlignment {\n\n    public static String[] alignment(String a, String b) {\n        a = a.toLowerCase();\n        b = b.toLowerCase();\n        \n        int[][] costs = new int[a.length()+1][b.length()+1];\n        for (int j = 0; j <= b.length(); j++)\n            costs[0][j] = j;\n        for (int i = 1; i <= a.length(); i++) {\n            costs[i][0] = i;\n            for (int j = 1; j <= b.length(); j++) {\n                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);\n            }\n        }\n\n\t\n\tStringBuilder aPathRev = new StringBuilder();\n\tStringBuilder bPathRev = new StringBuilder();\n\tfor (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {\n\t    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append(b.charAt(--j));\n\t    } else if (costs[i][j] == 1 + costs[i-1][j]) {\n\t\taPathRev.append(a.charAt(--i));\n\t\tbPathRev.append('-');\n\t    } else if (costs[i][j] == 1 + costs[i][j-1]) {\n\t\taPathRev.append('-');\n\t\tbPathRev.append(b.charAt(--j));\n\t    }\n\t}\n        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};\n    }\n\n    public static void main(String[] args) {\n\tString[] result = alignment(\"rosettacode\", \"raisethysword\");\n\tSystem.out.println(result[0]);\n\tSystem.out.println(result[1]);\n    }\n}\n"}
{"id": 59767, "name": "Same fringe", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n", "Java": "import java.util.*;\n\nclass SameFringe\n{\n  public interface Node<T extends Comparable<? super T>>\n  {\n    Node<T> getLeft();\n    Node<T> getRight();\n    boolean isLeaf();\n    T getData();\n  }\n  \n  public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>\n  {\n    private final T data;\n    public SimpleNode<T> left;\n    public SimpleNode<T> right;\n    \n    public SimpleNode(T data)\n    {  this(data, null, null);  }\n    \n    public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)\n    {\n      this.data = data;\n      this.left = left;\n      this.right = right;\n    }\n    \n    public Node<T> getLeft()\n    {  return left;  }\n    \n    public Node<T> getRight()\n    {  return right;  }\n    \n    public boolean isLeaf()\n    {  return ((left == null) && (right == null));  }\n    \n    public T getData()\n    {  return data;  }\n    \n    public SimpleNode<T> addToTree(T data)\n    {\n      int cmp = data.compareTo(this.data);\n      if (cmp == 0)\n        throw new IllegalArgumentException(\"Same data!\");\n      if (cmp < 0)\n      {\n        if (left == null)\n          return (left = new SimpleNode<T>(data));\n        return left.addToTree(data);\n      }\n      if (right == null)\n        return (right = new SimpleNode<T>(data));\n      return right.addToTree(data);\n    }\n  }\n  \n  public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)\n  {\n    Stack<Node<T>> stack1 = new Stack<Node<T>>();\n    Stack<Node<T>> stack2 = new Stack<Node<T>>();\n    stack1.push(node1);\n    stack2.push(node2);\n    \n    while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))\n      if (!node1.getData().equals(node2.getData()))\n        return false;\n    \n    return (node1 == null) && (node2 == null);\n  }\n  \n  private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)\n  {\n    while (!stack.isEmpty())\n    {\n      Node<T> node = stack.pop();\n      if (node.isLeaf())\n        return node;\n      Node<T> rightNode = node.getRight();\n      if (rightNode != null)\n        stack.push(rightNode);\n      Node<T> leftNode = node.getLeft();\n      if (leftNode != null)\n        stack.push(leftNode);\n    }\n    return null;\n  }\n  \n  public static void main(String[] args)\n  {\n    SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));\n    SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));\n    SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));\n    System.out.print(\"Leaves for set 1: \");\n    simpleWalk(headNode1);\n    System.out.println();\n    System.out.print(\"Leaves for set 2: \");\n    simpleWalk(headNode2);\n    System.out.println();\n    System.out.print(\"Leaves for set 3: \");\n    simpleWalk(headNode3);\n    System.out.println();\n    System.out.println(\"areLeavesSame(1, 2)? \" + areLeavesSame(headNode1, headNode2));\n    System.out.println(\"areLeavesSame(2, 3)? \" + areLeavesSame(headNode2, headNode3));\n  }\n  \n  public static void simpleWalk(Node<Integer> node)\n  {\n    if (node.isLeaf())\n      System.out.print(node.getData() + \" \");\n    else\n    {\n      Node<Integer> left = node.getLeft();\n      if (left != null)\n        simpleWalk(left);\n      Node<Integer> right = node.getRight();\n      if (right != null)\n        simpleWalk(right);\n    }\n  }\n}\n"}
{"id": 59768, "name": "Simulate input_Keyboard", "Go": "package main\n\nimport (\n    \"github.com/micmonay/keybd_event\"\n    \"log\"\n    \"runtime\"\n    \"time\"\n)\n\nfunc main() {\n    kb, err := keybd_event.NewKeyBonding()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    if runtime.GOOS == \"linux\" {\n        time.Sleep(2 * time.Second)\n    }\n\n    \n    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)\n\n    \n    err = kb.Launching()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "Java": "import java.awt.Robot\npublic static void type(String str){\n   Robot robot = new Robot();\n   for(char ch:str.toCharArray()){\n      if(Character.isUpperCase(ch)){\n         robot.keyPress(KeyEvent.VK_SHIFT);\n         robot.keyPress((int)ch);\n         robot.keyRelease((int)ch);\n         robot.keyRelease(KeyEvent.VK_SHIFT);\n      }else{\n         char upCh = Character.toUpperCase(ch);\n         robot.keyPress((int)upCh);\n         robot.keyRelease((int)upCh);\n      }\n   }\n}\n"}
{"id": 59769, "name": "Peaceful chess queen armies", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Peaceful {\n    enum Piece {\n        Empty,\n        Black,\n        White,\n    }\n\n    public static class Position {\n        public int x, y;\n\n        public Position(int x, int y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Position) {\n                Position pos = (Position) obj;\n                return pos.x == x && pos.y == y;\n            }\n            return false;\n        }\n    }\n\n    private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n        if (m == 0) {\n            return true;\n        }\n        boolean placingBlack = true;\n        for (int i = 0; i < n; ++i) {\n            inner:\n            for (int j = 0; j < n; ++j) {\n                Position pos = new Position(i, j);\n                for (Position queen : pBlackQueens) {\n                    if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                for (Position queen : pWhiteQueens) {\n                    if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {\n                        continue inner;\n                    }\n                }\n                if (placingBlack) {\n                    pBlackQueens.add(pos);\n                    placingBlack = false;\n                } else {\n                    pWhiteQueens.add(pos);\n                    if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                        return true;\n                    }\n                    pBlackQueens.remove(pBlackQueens.size() - 1);\n                    pWhiteQueens.remove(pWhiteQueens.size() - 1);\n                    placingBlack = true;\n                }\n            }\n        }\n        if (!placingBlack) {\n            pBlackQueens.remove(pBlackQueens.size() - 1);\n        }\n        return false;\n    }\n\n    private static boolean isAttacking(Position queen, Position pos) {\n        return queen.x == pos.x\n            || queen.y == pos.y\n            || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);\n    }\n\n    private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n        Piece[] board = new Piece[n * n];\n        Arrays.fill(board, Piece.Empty);\n\n        for (Position queen : blackQueens) {\n            board[queen.x + n * queen.y] = Piece.Black;\n        }\n        for (Position queen : whiteQueens) {\n            board[queen.x + n * queen.y] = Piece.White;\n        }\n        for (int i = 0; i < board.length; ++i) {\n            if ((i != 0) && i % n == 0) {\n                System.out.println();\n            }\n\n            Piece b = board[i];\n            if (b == Piece.Black) {\n                System.out.print(\"B \");\n            } else if (b == Piece.White) {\n                System.out.print(\"W \");\n            } else {\n                int j = i / n;\n                int k = i - j * n;\n                if (j % 2 == k % 2) {\n                    System.out.print(\"• \");\n                } else {\n                    System.out.print(\"◦ \");\n                }\n            }\n        }\n        System.out.println('\\n');\n    }\n\n    public static void main(String[] args) {\n        List<Position> nms = List.of(\n            new Position(2, 1),\n            new Position(3, 1),\n            new Position(3, 2),\n            new Position(4, 1),\n            new Position(4, 2),\n            new Position(4, 3),\n            new Position(5, 1),\n            new Position(5, 2),\n            new Position(5, 3),\n            new Position(5, 4),\n            new Position(5, 5),\n            new Position(6, 1),\n            new Position(6, 2),\n            new Position(6, 3),\n            new Position(6, 4),\n            new Position(6, 5),\n            new Position(6, 6),\n            new Position(7, 1),\n            new Position(7, 2),\n            new Position(7, 3),\n            new Position(7, 4),\n            new Position(7, 5),\n            new Position(7, 6),\n            new Position(7, 7)\n        );\n        for (Position nm : nms) {\n            int m = nm.y;\n            int n = nm.x;\n            System.out.printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n);\n            List<Position> blackQueens = new ArrayList<>();\n            List<Position> whiteQueens = new ArrayList<>();\n            if (place(m, n, blackQueens, whiteQueens)) {\n                printBoard(n, blackQueens, whiteQueens);\n            } else {\n                System.out.println(\"No solution exists.\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 59770, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "Java": "while (true) {\n   System.out.println(\"SPAM\");\n}\n"}
{"id": 59771, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 59772, "name": "Active Directory_Search for a user", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapSearchDemo {\n\n    public static void main(String[] args) throws IOException, LdapException, CursorException {\n        new LdapSearchDemo().demonstrateSearch();\n    }\n\n    private void demonstrateSearch() throws IOException, LdapException, CursorException {\n        try (LdapConnection conn = new LdapNetworkConnection(\"localhost\", 11389)) {\n            conn.bind(\"uid=admin,ou=system\", \"********\");\n            search(conn, \"*mil*\");\n            conn.unBind();\n        }\n    }\n\n    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {\n        String baseDn = \"ou=users,o=mojo\";\n        String filter = \"(&(objectClass=person)(&(uid=\" + uid + \")))\";\n        SearchScope scope = SearchScope.SUBTREE;\n        String[] attributes = {\"dn\", \"cn\", \"sn\", \"uid\"};\n        int ksearch = 0;\n\n        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);\n        while (cursor.next()) {\n            ksearch++;\n            Entry entry = cursor.get();\n            System.out.printf(\"Search entry %d = %s%n\", ksearch, entry);\n        }\n    }\n}\n"}
{"id": 59773, "name": "Singular value decomposition", "Go": "<package main\n\nimport (\n    \"fmt\"\n    \"gonum.org/v1/gonum/mat\"\n    \"log\"\n)\n\nfunc matPrint(m mat.Matrix) {\n    fa := mat.Formatted(m, mat.Prefix(\"\"), mat.Squeeze())\n    fmt.Printf(\"%13.10f\\n\", fa)\n}\n\nfunc main() {\n    var svd mat.SVD\n    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})\n    ok := svd.Factorize(a, mat.SVDFull)\n    if !ok {\n        log.Fatal(\"Something went wrong!\")\n    }\n    u := mat.NewDense(2, 2, nil)\n    svd.UTo(u)\n    fmt.Println(\"U:\")\n    matPrint(u)\n    values := svd.Values(nil)\n    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})\n    fmt.Println(\"\\nΣ:\")\n    matPrint(sigma)\n    vt := mat.NewDense(2, 2, nil)\n    svd.VTo(vt)\n    fmt.Println(\"\\nVT:\")\n    matPrint(vt)\n}\n", "Java": "import Jama.Matrix;\npublic class SingularValueDecomposition {\n    public static void main(String[] args) {\n        double[][] matrixArray = {{3, 0}, {4, 5}};\n        var matrix = new Matrix(matrixArray);\n        var svd = matrix.svd();\n        svd.getU().print(0, 10); \n        svd.getS().print(0, 10);\n        svd.getV().print(0, 10);\n    }\n}\n"}
{"id": 59774, "name": "Test integerness", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n", "Java": "import java.math.BigDecimal;\nimport java.util.List;\n\npublic class TestIntegerness {\n    private static boolean isLong(double d) {\n        return isLong(d, 0.0);\n    }\n\n    private static boolean isLong(double d, double tolerance) {\n        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;\n    }\n\n    @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n    private static boolean isBigInteger(BigDecimal bd) {\n        try {\n            bd.toBigIntegerExact();\n            return true;\n        } catch (ArithmeticException ex) {\n            return false;\n        }\n    }\n\n    private static class Rational {\n        long num;\n        long denom;\n\n        Rational(int num, int denom) {\n            this.num = num;\n            this.denom = denom;\n        }\n\n        boolean isLong() {\n            return num % denom == 0;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s/%s\", num, denom);\n        }\n    }\n\n    private static class Complex {\n        double real;\n        double imag;\n\n        Complex(double real, double imag) {\n            this.real = real;\n            this.imag = imag;\n        }\n\n        boolean isLong() {\n            return TestIntegerness.isLong(real) && imag == 0.0;\n        }\n\n        @Override\n        public String toString() {\n            if (imag >= 0.0) {\n                return String.format(\"%s + %si\", real, imag);\n            }\n            return String.format(\"%s - %si\", real, imag);\n        }\n    }\n\n    public static void main(String[] args) {\n        List<Double> da = List.of(25.000000, 24.999999, 25.000100);\n        for (Double d : da) {\n            boolean exact = isLong(d);\n            System.out.printf(\"%.6f is %s integer%n\", d, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        double tolerance = 0.00001;\n        System.out.printf(\"With a tolerance of %.5f:%n\", tolerance);\n        for (Double d : da) {\n            boolean fuzzy = isLong(d, tolerance);\n            System.out.printf(\"%.6f is %s integer%n\", d, fuzzy ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);\n        for (Double f : fa) {\n            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));\n            System.out.printf(\"%s is %s integer%n\", f, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));\n        for (Complex c : ca) {\n            boolean exact = c.isLong();\n            System.out.printf(\"%s is %s integer%n\", c, exact ? \"an\" : \"not an\");\n        }\n        System.out.println();\n\n        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));\n        for (Rational r : ra) {\n            boolean exact = r.isLong();\n            System.out.printf(\"%s is %s integer%n\", r, exact ? \"an\" : \"not an\");\n        }\n    }\n}\n"}
{"id": 59775, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 59776, "name": "Rodrigues’ rotation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector [3]float64\ntype matrix [3]vector\n\nfunc norm(v vector) float64 {\n    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])\n}\n\nfunc normalize(v vector) vector {\n    length := norm(v)\n    return vector{v[0] / length, v[1] / length, v[2] / length}\n}\n\nfunc dotProduct(v1, v2 vector) float64 {\n    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n}\n\nfunc crossProduct(v1, v2 vector) vector {\n    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}\n}\n\nfunc getAngle(v1, v2 vector) float64 {\n    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))\n}\n\nfunc matrixMultiply(m matrix, v vector) vector {\n    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}\n}\n\nfunc aRotate(p, v vector, a float64) vector {\n    ca, sa := math.Cos(a), math.Sin(a)\n    t := 1 - ca\n    x, y, z := v[0], v[1], v[2]\n    r := matrix{\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},\n    }\n    return matrixMultiply(r, p)\n}\n\nfunc main() {\n    v1 := vector{5, -6, 4}\n    v2 := vector{8, 5, -30}\n    a := getAngle(v1, v2)\n    cp := crossProduct(v1, v2)\n    ncp := normalize(cp)\n    np := aRotate(v1, ncp, a)\n    fmt.Println(np)\n}\n", "Java": "\n\nclass Vector{\n  private double x, y, z;\n\n  public Vector(double x1,double y1,double z1){\n    x = x1;\n    y = y1;\n    z = z1;\n  }\n  \n  void printVector(int x,int y){\n    text(\"( \" + this.x + \" )  \\u00ee + ( \" + this.y + \" ) + \\u0135 ( \" + this.z + \") \\u006b\\u0302\",x,y);\n  }\n\n  public double norm() {\n    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);\n  }\n  \n  public Vector normalize(){\n    double length = this.norm();\n    return new Vector(this.x / length, this.y / length, this.z / length);\n  }\n  \n  public double dotProduct(Vector v2) {\n    return this.x*v2.x + this.y*v2.y + this.z*v2.z;\n  }\n  \n  public Vector crossProduct(Vector v2) {\n    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);\n  }\n  \n  public double getAngle(Vector v2) {\n    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));\n  }\n  \n  public Vector aRotate(Vector v, double a) {\n    double ca = Math.cos(a), sa = Math.sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    Vector[] r = {\n        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),\n        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),\n        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)\n    };\n    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));\n  }\n}\n\nvoid setup(){\n  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);\n  double a = v1.getAngle(v2);\n  Vector cp = v1.crossProduct(v2);\n  Vector normCP = cp.normalize();\n  Vector np = v1.aRotate(normCP,a);\n  \n  size(1200,600);\n  fill(#000000);\n  textSize(30);\n  \n  text(\"v1 = \",10,100);\n  v1.printVector(60,100);\n  text(\"v2 = \",10,150);\n  v2.printVector(60,150);\n  text(\"rV = \",10,200);\n  np.printVector(60,200);\n}\n"}
{"id": 59777, "name": "Rodrigues’ rotation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector [3]float64\ntype matrix [3]vector\n\nfunc norm(v vector) float64 {\n    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])\n}\n\nfunc normalize(v vector) vector {\n    length := norm(v)\n    return vector{v[0] / length, v[1] / length, v[2] / length}\n}\n\nfunc dotProduct(v1, v2 vector) float64 {\n    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n}\n\nfunc crossProduct(v1, v2 vector) vector {\n    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}\n}\n\nfunc getAngle(v1, v2 vector) float64 {\n    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))\n}\n\nfunc matrixMultiply(m matrix, v vector) vector {\n    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}\n}\n\nfunc aRotate(p, v vector, a float64) vector {\n    ca, sa := math.Cos(a), math.Sin(a)\n    t := 1 - ca\n    x, y, z := v[0], v[1], v[2]\n    r := matrix{\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},\n    }\n    return matrixMultiply(r, p)\n}\n\nfunc main() {\n    v1 := vector{5, -6, 4}\n    v2 := vector{8, 5, -30}\n    a := getAngle(v1, v2)\n    cp := crossProduct(v1, v2)\n    ncp := normalize(cp)\n    np := aRotate(v1, ncp, a)\n    fmt.Println(np)\n}\n", "Java": "\n\nclass Vector{\n  private double x, y, z;\n\n  public Vector(double x1,double y1,double z1){\n    x = x1;\n    y = y1;\n    z = z1;\n  }\n  \n  void printVector(int x,int y){\n    text(\"( \" + this.x + \" )  \\u00ee + ( \" + this.y + \" ) + \\u0135 ( \" + this.z + \") \\u006b\\u0302\",x,y);\n  }\n\n  public double norm() {\n    return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);\n  }\n  \n  public Vector normalize(){\n    double length = this.norm();\n    return new Vector(this.x / length, this.y / length, this.z / length);\n  }\n  \n  public double dotProduct(Vector v2) {\n    return this.x*v2.x + this.y*v2.y + this.z*v2.z;\n  }\n  \n  public Vector crossProduct(Vector v2) {\n    return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x);\n  }\n  \n  public double getAngle(Vector v2) {\n    return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm()));\n  }\n  \n  public Vector aRotate(Vector v, double a) {\n    double ca = Math.cos(a), sa = Math.sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    Vector[] r = {\n        new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa),\n        new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa),\n        new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t)\n    };\n    return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2]));\n  }\n}\n\nvoid setup(){\n  Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d);\n  double a = v1.getAngle(v2);\n  Vector cp = v1.crossProduct(v2);\n  Vector normCP = cp.normalize();\n  Vector np = v1.aRotate(normCP,a);\n  \n  size(1200,600);\n  fill(#000000);\n  textSize(30);\n  \n  text(\"v1 = \",10,100);\n  v1.printVector(60,100);\n  text(\"v2 = \",10,150);\n  v2.printVector(60,150);\n  text(\"rV = \",10,200);\n  np.printVector(60,200);\n}\n"}
{"id": 59778, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 59779, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 59780, "name": "Death Star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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 javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n"}
{"id": 59781, "name": "Lucky and even lucky numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n    for i := 0; i < luckySize; i++ {\n        luckyOdd[i] = i*2 + 1\n        luckyEven[i] = i*2 + 2\n    }\n}\n\nfunc filterLuckyOdd() {\n    for n := 2; n < len(luckyOdd); n++ {\n        m := luckyOdd[n-1]\n        end := (len(luckyOdd)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyOdd[j:], luckyOdd[j+1:])\n            luckyOdd = luckyOdd[:len(luckyOdd)-1]\n        }\n    }\n}\n\nfunc filterLuckyEven() {\n    for n := 2; n < len(luckyEven); n++ {\n        m := luckyEven[n-1]\n        end := (len(luckyEven)/m)*m - 1\n        for j := end; j >= m-1; j -= m {\n            copy(luckyEven[j:], luckyEven[j+1:])\n            luckyEven = luckyEven[:len(luckyEven)-1]\n        }\n    }\n}\n\nfunc printSingle(j int, odd bool) error {\n    if odd {\n        if j >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n    } else {\n        if j >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", j)\n        }\n        fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n    }\n    return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n    if odd {\n        if k >= len(luckyOdd) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyOdd[j-1 : k])\n    } else {\n        if k >= len(luckyEven) {\n            return fmt.Errorf(\"the argument, %d, is too big\", k)\n        }\n        fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n        fmt.Println(luckyEven[j-1 : k])\n    }\n    return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n    var r []int\n    if odd {\n        max := luckyOdd[len(luckyOdd)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyOdd {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    } else {\n        max := luckyEven[len(luckyEven)-1]\n        if j > max || k > max {\n            return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n        }\n        for _, num := range luckyEven {\n            if num < j {\n                continue\n            }\n            if num > k {\n                break\n            }\n            r = append(r, num)\n        }\n        fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n        fmt.Println(r)\n    }\n    return nil\n}\n\nfunc main() {\n    nargs := len(os.Args)\n    if nargs < 2 || nargs > 4 {\n        log.Fatal(\"there must be between 1 and 3 command line arguments\")\n    }\n    filterLuckyOdd()\n    filterLuckyEven()\n    j, err := strconv.Atoi(os.Args[1])\n    if err != nil || j < 1 {\n        log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n    }\n    if nargs == 2 {\n        if err := printSingle(j, true); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    if nargs == 3 {\n        k, err := strconv.Atoi(os.Args[2])\n        if err != nil {\n            log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n        }\n        if k >= 0 {\n            if j > k {\n                log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n            }\n            if err := printRange(j, k, true); err != nil {\n                log.Fatal(err)\n            }\n        } else {\n            l := -k\n            if j > l {\n                log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n            }\n            if err := printBetween(j, l, true); err != nil {\n                log.Fatal(err)\n            }\n        }\n        return\n    }\n\n    var odd bool\n    switch lucky := strings.ToLower(os.Args[3]); lucky {\n    case \"lucky\":\n        odd = true\n    case \"evenlucky\":\n        odd = false\n    default:\n        log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n    }\n    if os.Args[2] == \",\" {\n        if err := printSingle(j, odd); err != nil {\n            log.Fatal(err)\n        }\n        return\n    }\n\n    k, err := strconv.Atoi(os.Args[2])\n    if err != nil {\n        log.Fatal(\"second argument must be an integer or a comma\")\n    }\n    if k >= 0 {\n        if j > k {\n            log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n        }\n        if err := printRange(j, k, odd); err != nil {\n            log.Fatal(err)\n        }\n    } else {\n        l := -k\n        if j > l {\n            log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n        }\n        if err := printBetween(j, l, odd); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LuckyNumbers {\n\n    private static int MAX = 200000;\n    private static List<Integer> luckyEven = luckyNumbers(MAX, true);\n    private static List<Integer> luckyOdd = luckyNumbers(MAX, false);\n    \n    public static void main(String[] args) {\n        \n        if ( args.length == 1 || ( args.length == 2 && args[1].compareTo(\"lucky\") == 0 ) ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"LuckyNumber(%d) = %d%n\", n, luckyOdd.get(n-1));\n        }\n        \n        else if ( args.length == 2 && args[1].compareTo(\"evenLucky\") == 0 ) {\n            int n = Integer.parseInt(args[0]);\n            System.out.printf(\"EvenLuckyNumber(%d) = %d%n\", n, luckyEven.get(n-1));            \n        }\n        \n        else if ( args.length == 2 || args.length == 3 ) {\n            int j = Integer.parseInt(args[0]);\n            int k = Integer.parseInt(args[1]);\n            \n            if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                System.out.printf(\"LuckyNumber(%d) through LuckyNumber(%d) = %s%n\", j, k, luckyOdd.subList(j-1, k));\n            }\n            \n            else if ( args.length == 3 && k > 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                System.out.printf(\"EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n\", j, k, luckyEven.subList(j-1, k));\n            }\n            \n            else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo(\"lucky\") == 0 ) ) {\n                int n = Collections.binarySearch(luckyOdd, j);\n                int m = Collections.binarySearch(luckyOdd, -k);\n                System.out.printf(\"Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n            \n            else if ( args.length == 3 && k < 0 && args[2].compareTo(\"evenLucky\") == 0 ) {\n                int n = Collections.binarySearch(luckyEven, j);\n                int m = Collections.binarySearch(luckyEven, -k);\n                System.out.printf(\"Even Lucky Numbers in the range %d to %d inclusive = %s%n\", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));\n            }\n        }\n    }\n    \n    private static List<Integer> luckyNumbers(int max, boolean even) {\n        List<Integer> luckyList = new ArrayList<>();\n        for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {\n            luckyList.add(i);\n        }\n        int start = 1;\n        boolean removed = true;\n        while ( removed ) {\n            removed = false;\n            int increment = luckyList.get(start);\n            List<Integer> remove = new ArrayList<>();\n            for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {\n                remove.add(0, i);\n                removed = true;\n            }\n            for ( int i : remove ) {\n                luckyList.remove(i);\n            }\n            start++;\n        }\n        return luckyList;\n    }\n\n}\n"}
{"id": 59782, "name": "Simple database", "Go": "package main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n    \"time\"\n    \"unicode\"\n)\n\n\n\ntype Item struct {\n    Stamp time.Time\n    Name  string\n    Tags  []string `json:\",omitempty\"`\n    Notes string   `json:\",omitempty\"`\n}\n\n\nfunc (i *Item) String() string {\n    s := i.Stamp.Format(time.ANSIC) + \"\\n  Name:  \" + i.Name\n    if len(i.Tags) > 0 {\n        s = fmt.Sprintf(\"%s\\n  Tags:  %v\", s, i.Tags)\n    }\n    if i.Notes > \"\" {\n        s += \"\\n  Notes: \" + i.Notes\n    }\n    return s\n}\n\n\ntype db []*Item\n\n\nfunc (d db) Len() int           { return len(d) }\nfunc (d db) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }\nfunc (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) }\n\n\nconst fn = \"sdb.json\"\n\nfunc main() {\n    if len(os.Args) == 1 {\n        latest()\n        return\n    }\n    switch os.Args[1] {\n    case \"add\":\n        add()\n    case \"latest\":\n        latest()\n    case \"tags\":\n        tags()\n    case \"all\":\n        all()\n    case \"help\":\n        help()\n    default:\n        usage(\"unrecognized command\")\n    }\n}\n\nfunc usage(err string) {\n    if err > \"\" {\n        fmt.Println(err)\n    }\n    fmt.Println(`usage:  sdb [command] [data]\n    where command is one of add, latest, tags, all, or help.`)\n}\n\nfunc help() {\n    usage(\"\")\n    fmt.Println(`\nCommands must be in lower case.\nIf no command is specified, the default command is latest.\n\nLatest prints the latest item.\nAll prints all items in chronological order.\nTags prints the lastest item for each tag.\nHelp prints this message.\n\nAdd adds data as a new record.  The format is,\n\n  name [tags] [notes]\n\nName is the name of the item and is required for the add command.\n\nTags are optional.  A tag is a single word.\nA single tag can be specified without enclosing brackets.\nMultiple tags can be specified by enclosing them in square brackets.\n\nText remaining after tags is taken as notes.  Notes do not have to be\nenclosed in quotes or brackets.  The brackets above are only showing\nthat notes are optional.\n\nQuotes may be useful however--as recognized by your operating system shell\nor command line--to allow entry of arbitrary text.  In particular, quotes\nor escape characters may be needed to prevent the shell from trying to\ninterpret brackets or other special characters.\n\nExamples:\nsdb add Bookends                        \nsdb add Bookends rock my favorite       \nsdb add Bookends [rock folk]            \nsdb add Bookends [] \"Simon & Garfunkel\" \nsdb add \"Simon&Garfunkel [artist]\"      \n    \nAs shown in the last example, if you use features of your shell to pass\nall data as a single string, the item name and tags will still be identified\nby separating whitespace.\n    \nThe database is stored in JSON format in the file \"sdb.json\"\n`)  \n}\n\n\nfunc load() (db, bool) {\n    d, f, ok := open()\n    if ok {\n        f.Close()\n        if len(d) == 0 {\n            fmt.Println(\"no items\")\n            ok = false\n        }\n    }\n    return d, ok\n}\n\n\nfunc open() (d db, f *os.File, ok bool) {\n    var err error\n    f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)\n    if err != nil {\n        fmt.Println(\"cant open??\")\n        fmt.Println(err)\n        return\n    }\n    jd := json.NewDecoder(f)\n    err = jd.Decode(&d)\n    \n    if err != nil && err != io.EOF {\n        fmt.Println(err)\n        f.Close()\n        return\n    }\n    ok = true\n    return\n}\n\n\nfunc latest() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    fmt.Println(d[len(d)-1])\n}\n\n\nfunc all() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    sort.Sort(d)\n    for _, i := range d {\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(i)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n\n\nfunc tags() {\n    d, ok := load()\n    if !ok {\n        return\n    }\n    \n    \n    \n    latest := make(map[string]*Item)\n    for _, item := range d {\n        for _, tag := range item.Tags {\n            li, ok := latest[tag]\n            if !ok || item.Stamp.After(li.Stamp) {\n                latest[tag] = item\n            }\n        }\n    }\n    \n    \n    type itemTags struct {\n        item *Item\n        tags []string\n    }\n    inv := make(map[*Item][]string)\n    for tag, item := range latest {\n        inv[item] = append(inv[item], tag)\n    }\n    \n    li := make(db, len(inv))\n    i := 0\n    for item := range inv {\n        li[i] = item\n        i++\n    }\n    sort.Sort(li)\n    \n    for _, item := range li {\n        tags := inv[item]\n        fmt.Println(\"-----------------------------------\")\n        fmt.Println(\"Latest item with tags\", tags)\n        fmt.Println(item)\n    }\n    fmt.Println(\"-----------------------------------\")\n}\n    \n\nfunc add() { \n    if len(os.Args) < 3 {\n        usage(\"add command requires data\")\n        return\n    } else if len(os.Args) == 3 {\n        add1()\n    } else {\n        add4()\n    }\n}   \n\n\nfunc add1() {\n    data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace)\n    if data == \"\" {\n        \n        usage(\"invalid name\")\n        return \n    }\n    sep := strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(data, nil, \"\")\n        return\n    }\n    name := data[:sep]\n    data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace)\n    if data == \"\" {\n        \n        addItem(name, nil, \"\")\n        return\n    }\n    if data[0] == '[' {\n        sep = strings.Index(data, \"]\")\n        if sep < 0 {\n            \n            addItem(name, strings.Fields(data[1:]), \"\")\n        } else {\n            \n            addItem(name, strings.Fields(data[1:sep]),\n                strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n        }\n        return\n    }\n    sep = strings.IndexFunc(data, unicode.IsSpace)\n    if sep < 0 {\n        \n        addItem(name, []string{data}, \"\")\n    } else {\n        \n        addItem(name, []string{data[:sep]},\n            strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))\n    }\n}\n\n\nfunc add4() {\n    name := os.Args[2]\n    tag1 := os.Args[3]\n    if tag1[0] != '[' {\n        \n        addItem(name, []string{tag1}, strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    if tag1[len(tag1)-1] == ']' {\n        \n        addItem(name, strings.Fields(tag1[1:len(tag1)-1]),\n            strings.Join(os.Args[4:], \" \"))\n        return\n    }\n    \n    var tags []string\n    if tag1 > \"[\" {\n        tags = []string{tag1[1:]}\n    }\n    for x, tag := range os.Args[4:] {\n        if tag[len(tag)-1] != ']' {\n            tags = append(tags, tag)\n        } else {\n            \n            if tag > \"]\" {\n                tags = append(tags, tag[:len(tag)-1])\n            }\n            addItem(name, tags, strings.Join(os.Args[5+x:], \" \"))\n            return\n        }\n    }\n    \n    addItem(name, tags, \"\")\n}\n\n\nfunc addItem(name string, tags []string, notes string) {\n    db, f, ok := open()\n    if !ok {\n        return\n    }\n    defer f.Close()\n    \n    db = append(db, &Item{time.Now(), name, tags, notes})\n    sort.Sort(db)\n    js, err := json.MarshalIndent(db, \"\", \"  \")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if _, err = f.Seek(0, 0); err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Truncate(0)\n    if _, err = f.Write(js); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.io.*;\nimport java.text.*;\nimport java.util.*;\n\npublic class SimpleDatabase {\n\n    final static String filename = \"simdb.csv\";\n\n    public static void main(String[] args) {\n        if (args.length < 1 || args.length > 3) {\n            printUsage();\n            return;\n        }\n\n        switch (args[0].toLowerCase()) {\n            case \"add\":\n                addItem(args);\n                break;\n            case \"latest\":\n                printLatest(args);\n                break;\n            case \"all\":\n                printAll();\n                break;\n            default:\n                printUsage();\n                break;\n        }\n    }\n\n    private static class Item implements Comparable<Item>{\n        final String name;\n        final String date;\n        final String category;\n\n        Item(String n, String d, String c) {\n            name = n;\n            date = d;\n            category = c;\n        }\n\n        @Override\n        public int compareTo(Item item){\n            return date.compareTo(item.date);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"%s,%s,%s%n\", name, date, category);\n        }\n    }\n\n    private static void addItem(String[] input) {\n        if (input.length < 2) {\n            printUsage();\n            return;\n        }\n        List<Item> db = load();\n        SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n        String date = sdf.format(new Date());\n        String cat = (input.length == 3) ? input[2] : \"none\";\n        db.add(new Item(input[1], date, cat));\n        store(db);\n    }\n\n    private static void printLatest(String[] a) {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        if (a.length == 2) {\n            for (Item item : db)\n                if (item.category.equals(a[1]))\n                    System.out.println(item);\n        } else {\n            System.out.println(db.get(0));\n        }\n    }\n\n    private static void printAll() {\n        List<Item> db = load();\n        if (db.isEmpty()) {\n            System.out.println(\"No entries in database.\");\n            return;\n        }\n        Collections.sort(db);\n        for (Item item : db)\n            System.out.println(item);\n    }\n\n    private static List<Item> load() {\n        List<Item> db = new ArrayList<>();\n        try (Scanner sc = new Scanner(new File(filename))) {\n            while (sc.hasNext()) {\n                String[] item = sc.nextLine().split(\",\");\n                db.add(new Item(item[0], item[1], item[2]));\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return db;\n    }\n\n    private static void store(List<Item> db) {\n        try (FileWriter fw = new FileWriter(filename)) {\n            for (Item item : db)\n                fw.write(item.toString());\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n\n    private static void printUsage() {\n         System.out.println(\"Usage:\");\n         System.out.println(\"  simdb cmd [categoryName]\");\n         System.out.println(\"  add     add item, followed by optional category\");\n         System.out.println(\"  latest  print last added item(s), followed by \"\n                 + \"optional category\");\n         System.out.println(\"  all     print all\");\n         System.out.println(\"  For instance: add \\\"some item name\\\" \"\n                 + \"\\\"some category name\\\"\");\n    }\n}\n"}
{"id": 59783, "name": "Hough transform", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\n  }\n}\n"}
{"id": 59784, "name": "Hough transform", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class HoughTransform\n{\n  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)\n  {\n    int width = inputData.width;\n    int height = inputData.height;\n    int maxRadius = (int)Math.ceil(Math.hypot(width, height));\n    int halfRAxisSize = rAxisSize >>> 1;\n    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);\n    \n    \n    double[] sinTable = new double[thetaAxisSize];\n    double[] cosTable = new double[thetaAxisSize];\n    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n    {\n      double thetaRadians = theta * Math.PI / thetaAxisSize;\n      sinTable[theta] = Math.sin(thetaRadians);\n      cosTable[theta] = Math.cos(thetaRadians);\n    }\n    \n    for (int y = height - 1; y >= 0; y--)\n    {\n      for (int x = width - 1; x >= 0; x--)\n      {\n        if (inputData.contrast(x, y, minContrast))\n        {\n          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)\n          {\n            double r = cosTable[theta] * x + sinTable[theta] * y;\n            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;\n            outputData.accumulate(theta, rScaled, 1);\n          }\n        }\n      }\n    }\n    return outputData;\n  }\n  \n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n    \n    public void accumulate(int x, int y, int delta)\n    {  set(x, y, get(x, y) + delta);  }\n    \n    public boolean contrast(int x, int y, int minContrast)\n    {\n      int centerValue = get(x, y);\n      for (int i = 8; i >= 0; i--)\n      {\n        if (i == 4)\n          continue;\n        int newx = x + (i % 3) - 1;\n        int newy = y + (i / 3) - 1;\n        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))\n          continue;\n        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)\n          return true;\n      }\n      return false;\n    }\n    \n    public int getMax()\n    {\n      int max = dataArray[0];\n      for (int i = width * height - 1; i > 0; i--)\n        if (dataArray[i] > max)\n          max = dataArray[i];\n      return max;\n    }\n  }\n  \n  public static ArrayData getArrayDataFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData arrayData = new ArrayData(width, height);\n    \n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);\n        arrayData.set(x, height - 1 - y, rgbValue);\n      }\n    }\n    return arrayData;\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException\n  {\n    int max = arrayData.getMax();\n    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < arrayData.height; y++)\n    {\n      for (int x = 0; x < arrayData.width; x++)\n      {\n        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);\n        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    ArrayData inputData = getArrayDataFromImage(args[0]);\n    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);\n    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);\n    writeOutputImage(args[1], outputData);\n    return;\n  }\n}\n"}
{"id": 59785, "name": "Verify distribution uniformity_Chi-squared test", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n"}
{"id": 59786, "name": "Welch's t-test", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 59787, "name": "Welch's t-test", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"math\"\n)\n\nvar (\n  d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,\n    23.1, 19.6, 19.0, 21.7, 21.4}\n  d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,\n    21.9, 22.1, 22.9, 20.5, 24.4}\n  d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8}\n  d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8,\n    20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8}\n  d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0}\n  d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7,\n    23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2}\n  d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n  d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n  x  = []float64{3.0, 4.0, 1.0, 2.1}\n  y  = []float64{490.2, 340.0, 433.9}\n)\n\nfunc main() {\n  fmt.Printf(\"%.6f\\n\", pValue(d1, d2))\n  fmt.Printf(\"%.6f\\n\", pValue(d3, d4))\n  fmt.Printf(\"%.6f\\n\", pValue(d5, d6))\n  fmt.Printf(\"%.6f\\n\", pValue(d7, d8))\n  fmt.Printf(\"%.6f\\n\", pValue(x, y))\n}\n\nfunc mean(a []float64) float64 {\n  sum := 0.\n  for _, x := range a {\n    sum += x\n  }\n  return sum / float64(len(a))\n}\n\nfunc sv(a []float64) float64 {\n  m := mean(a)\n  sum := 0.\n  for _, x := range a {\n    d := x - m\n    sum += d * d\n  }\n  return sum / float64(len(a)-1)\n}\n\nfunc welch(a, b []float64) float64 {\n  return (mean(a) - mean(b)) /\n    math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b)))\n}\n\nfunc dof(a, b []float64) float64 {\n  sva := sv(a)\n  svb := sv(b)\n  n := sva/float64(len(a)) + svb/float64(len(b))\n  return n * n /\n    (sva*sva/float64(len(a)*len(a)*(len(a)-1)) +\n      svb*svb/float64(len(b)*len(b)*(len(b)-1)))\n}\n\nfunc simpson0(n int, upper float64, f func(float64) float64) float64 {\n  sum := 0.\n  nf := float64(n)\n  dx0 := upper / nf\n  sum += f(0) * dx0\n  sum += f(dx0*.5) * dx0 * 4\n  x0 := dx0\n  for i := 1; i < n; i++ {\n    x1 := float64(i+1) * upper / nf\n    xmid := (x0 + x1) * .5\n    dx := x1 - x0\n    sum += f(x0) * dx * 2\n    sum += f(xmid) * dx * 4\n    x0 = x1\n  }\n  return (sum + f(upper)*dx0) / 6\n}\n\nfunc pValue(a, b []float64) float64 {\n  ν := dof(a, b)\n  t := welch(a, b)\n  g1, _ := math.Lgamma(ν / 2)\n  g2, _ := math.Lgamma(.5)\n  g3, _ := math.Lgamma(ν/2 + .5)\n  return simpson0(2000, ν/(t*t+ν),\n    func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) /\n    math.Exp(g1+g2-g3)\n}\n", "Java": "import org.apache.commons.math3.distribution.TDistribution;\n\npublic class WelchTTest {\n    public static double[] meanvar(double[] a) {\n        double m = 0.0, v = 0.0;\n        int n = a.length;\n        \n        for (double x: a) {\n            m += x;\n        }\n        m /= n;\n        \n        for (double x: a) {\n            v += (x - m) * (x - m);\n        }\n        v /= (n - 1);\n        \n        return new double[] {m, v};\n    \n    }\n    \n    public static double[] welch_ttest(double[] x, double[] y) {\n        double mx, my, vx, vy, t, df, p;\n        double[] res;\n        int nx = x.length, ny = y.length;\n        \n        res = meanvar(x);\n        mx = res[0];\n        vx = res[1];\n        \n        res = meanvar(y);\n        my = res[0];\n        vy = res[1];\n        \n        t = (mx-my)/Math.sqrt(vx/nx+vy/ny);\n        df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));\n        TDistribution dist = new TDistribution(df);\n        p = 2.0*dist.cumulativeProbability(-Math.abs(t));\n        return new double[] {t, df, p};\n    }\n\n    public static void main(String[] args) {\n        double x[] = {3.0, 4.0, 1.0, 2.1};\n        double y[] = {490.2, 340.0, 433.9};\n        double res[] = welch_ttest(x, y);\n        System.out.println(\"t = \" + res[0]);\n        System.out.println(\"df = \" + res[1]);\n        System.out.println(\"p = \" + res[2]);\n    }\n}\n"}
{"id": 59788, "name": "Topological sort_Extracted top item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n"}
{"id": 59789, "name": "Topological sort_Extracted top item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\n\npublic class TopologicalSort2 {\n\n    public static void main(String[] args) {\n        String s = \"top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,\"\n                + \"des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1\";\n\n        Graph g = new Graph(s, new int[][]{\n            {0, 10}, {0, 2}, {0, 3},\n            {1, 10}, {1, 3}, {1, 4},\n            {2, 17}, {2, 5}, {2, 9},\n            {3, 6}, {3, 7}, {3, 8}, {3, 9},\n            {10, 11}, {10, 12}, {10, 13},\n            {11, 14}, {11, 15},\n            {13, 16}, {13, 17},});\n\n        System.out.println(\"Top levels: \" + g.toplevels());\n        String[] files = {\"top1\", \"top2\", \"ip1\"};\n        for (String f : files)\n            System.out.printf(\"Compile order for %s %s%n\", f, g.compileOrder(f));\n    }\n}\n\nclass Graph {\n    List<String> vertices;\n    boolean[][] adjacency;\n    int numVertices;\n\n    public Graph(String s, int[][] edges) {\n        vertices = asList(s.split(\",\"));\n        numVertices = vertices.size();\n        adjacency = new boolean[numVertices][numVertices];\n\n        for (int[] edge : edges)\n            adjacency[edge[0]][edge[1]] = true;\n    }\n\n    List<String> toplevels() {\n        List<String> result = new ArrayList<>();\n        \n        outer:\n        for (int c = 0; c < numVertices; c++) {\n            for (int r = 0; r < numVertices; r++) {\n                if (adjacency[r][c])\n                    continue outer;\n            }\n            result.add(vertices.get(c));\n        }\n        return result;\n    }\n\n    List<String> compileOrder(String item) {\n        LinkedList<String> result = new LinkedList<>();\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        queue.add(vertices.indexOf(item));\n\n        while (!queue.isEmpty()) {\n            int r = queue.poll();\n            for (int c = 0; c < numVertices; c++) {\n                if (adjacency[r][c] && !queue.contains(c)) {\n                    queue.add(c);\n                }\n            }\n            result.addFirst(vertices.get(r));\n        }\n        return result.stream().distinct().collect(toList());\n    }\n}\n"}
{"id": 59790, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 59791, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 59792, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 59793, "name": "Superpermutation minimisation", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n", "Java": "import static java.util.stream.IntStream.rangeClosed;\n\npublic class Test {\n    final static int nMax = 12;\n\n    static char[] superperm;\n    static int pos;\n    static int[] count = new int[nMax];\n\n    static int factSum(int n) {\n        return rangeClosed(1, n)\n                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();\n    }\n\n    static boolean r(int n) {\n        if (n == 0)\n            return false;\n\n        char c = superperm[pos - n];\n        if (--count[n] == 0) {\n            count[n] = n;\n            if (!r(n - 1))\n                return false;\n        }\n        superperm[pos++] = c;\n        return true;\n    }\n\n    static void superPerm(int n) {\n        String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n        pos = n;\n        superperm = new char[factSum(n)];\n\n        for (int i = 0; i < n + 1; i++)\n            count[i] = i;\n        for (int i = 1; i < n + 1; i++)\n            superperm[i - 1] = chars.charAt(i);\n\n        while (r(n)) {\n        }\n    }\n\n    public static void main(String[] args) {\n        for (int n = 0; n < nMax; n++) {\n            superPerm(n);\n            System.out.printf(\"superPerm(%2d) len = %d\", n, superperm.length);\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59794, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n"}
{"id": 59795, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n"}
{"id": 59796, "name": "Summarize and say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n"}
{"id": 59797, "name": "Summarize and say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n", "Java": "import java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.IntStream;\n\npublic class SelfReferentialSequence {\n\n    static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);\n\n    public static void main(String[] args) {\n        Seeds res = IntStream.range(0, 1000_000)\n                .parallel()\n                .mapToObj(n -> summarize(n, false))\n                .collect(Seeds::new, Seeds::accept, Seeds::combine);\n\n        System.out.println(\"Seeds:\");\n        res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));\n\n        System.out.println(\"\\nSequence:\");\n        summarize(res.seeds.get(0)[0], true);\n    }\n\n    static int[] summarize(int seed, boolean display) {\n        String n = String.valueOf(seed);\n\n        String k = Arrays.toString(n.chars().sorted().toArray());\n        if (!display && cache.get(k) != null)\n            return new int[]{seed, cache.get(k)};\n\n        Set<String> seen = new HashSet<>();\n        StringBuilder sb = new StringBuilder();\n\n        int[] freq = new int[10];\n\n        while (!seen.contains(n)) {\n            seen.add(n);\n\n            int len = n.length();\n            for (int i = 0; i < len; i++)\n                freq[n.charAt(i) - '0']++;\n\n            sb.setLength(0);\n            for (int i = 9; i >= 0; i--) {\n                if (freq[i] != 0) {\n                    sb.append(freq[i]).append(i);\n                    freq[i] = 0;\n                }\n            }\n            if (display)\n                System.out.println(n);\n            n = sb.toString();\n        }\n\n        cache.put(k, seen.size());\n\n        return new int[]{seed, seen.size()};\n    }\n\n    static class Seeds {\n        int largest = Integer.MIN_VALUE;\n        List<int[]> seeds = new ArrayList<>();\n\n        void accept(int[] s) {\n            int size = s[1];\n            if (size >= largest) {\n                if (size > largest) {\n                    largest = size;\n                    seeds.clear();\n                }\n                seeds.add(s);\n            }\n        }\n\n        void combine(Seeds acc) {\n            acc.seeds.forEach(this::accept);\n        }\n    }\n}\n"}
{"id": 59798, "name": "Spelling of ordinal numbers", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 59799, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 59800, "name": "Addition chains", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 59801, "name": "Numeric separator syntax", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n", "Java": "public class NumericSeparatorSyntax {\n\n    public static void main(String[] args) {\n        runTask(\"Underscore allowed as seperator\", 1_000);\n        runTask(\"Multiple consecutive underscores allowed:\", 1__0_0_0);\n        runTask(\"Many multiple consecutive underscores allowed:\", 1________________________00);\n        runTask(\"Underscores allowed in multiple positions\", 1__4__4);\n        runTask(\"Underscores allowed in negative number\", -1__4__4);\n        runTask(\"Underscores allowed in floating point number\", 1__4__4e-5);\n        runTask(\"Underscores allowed in floating point exponent\", 1__4__440000e-1_2);\n        \n        \n        \n        \n    }\n    \n    private static void runTask(String description, long n) {\n        runTask(description, n, \"%d\");\n    }\n\n    private static void runTask(String description, double n) {\n        runTask(description, n, \"%3.7f\");\n    }\n\n    private static void runTask(String description, Number n, String format) {\n        System.out.printf(\"%s:  \" + format + \"%n\", description, n);\n    }\n\n}\n"}
{"id": 59802, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n"}
{"id": 59803, "name": "Sparkline in unicode", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n"}
{"id": 59804, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 59805, "name": "Simulate input_Mouse", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n", "Java": "Point p = component.getLocation();\nRobot robot = new Robot();\nrobot.mouseMove(p.getX(), p.getY()); \nrobot.mousePress(InputEvent.BUTTON1_MASK); \n                                       \nrobot.mouseRelease(InputEvent.BUTTON1_MASK);\n"}
{"id": 59806, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 59807, "name": "Terminal control_Clear the screen", "Go": "cls\n", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n"}
{"id": 59808, "name": "Sunflower fractal", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n", "Java": "\n\nsize(1000,1000);\nsurface.setTitle(\"Sunflower...\");\n\nint iter = 3000;\nfloat factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;\nfloat x = width/2.0, y = height/2.0;\ndouble maxRad = pow(iter,factor)/iter;\nint i;\n \nbackground(#add8e6); \n \nfor(i=0;i<=iter;i++){\n  r = pow(i,factor)/iter;\n\n  if(r/maxRad < diskRatio){\n    stroke(#000000);        \n  }\n  else\n    stroke(#ffff00);       \n\n  theta = 2*PI*factor*i;\n  ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));\n}\n"}
{"id": 59809, "name": "Vogel's approximation method", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport java.util.concurrent.*;\n\npublic class VogelsApproximationMethod {\n\n    final static int[] demand = {30, 20, 70, 30, 60};\n    final static int[] supply = {50, 60, 50, 50};\n    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},\n    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};\n\n    final static int nRows = supply.length;\n    final static int nCols = demand.length;\n\n    static boolean[] rowDone = new boolean[nRows];\n    static boolean[] colDone = new boolean[nCols];\n    static int[][] result = new int[nRows][nCols];\n\n    static ExecutorService es = Executors.newFixedThreadPool(2);\n\n    public static void main(String[] args) throws Exception {\n        int supplyLeft = stream(supply).sum();\n        int totalCost = 0;\n\n        while (supplyLeft > 0) {\n            int[] cell = nextCell();\n            int r = cell[0];\n            int c = cell[1];\n\n            int quantity = Math.min(demand[c], supply[r]);\n            demand[c] -= quantity;\n            if (demand[c] == 0)\n                colDone[c] = true;\n\n            supply[r] -= quantity;\n            if (supply[r] == 0)\n                rowDone[r] = true;\n\n            result[r][c] = quantity;\n            supplyLeft -= quantity;\n\n            totalCost += quantity * costs[r][c];\n        }\n\n        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));\n        System.out.println(\"Total cost: \" + totalCost);\n\n        es.shutdown();\n    }\n\n    static int[] nextCell() throws Exception {\n        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));\n        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));\n\n        int[] res1 = f1.get();\n        int[] res2 = f2.get();\n\n        if (res1[3] == res2[3])\n            return res1[2] < res2[2] ? res1 : res2;\n\n        return (res1[3] > res2[3]) ? res2 : res1;\n    }\n\n    static int[] diff(int j, int len, boolean isRow) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int minP = -1;\n        for (int i = 0; i < len; i++) {\n            if (isRow ? colDone[i] : rowDone[i])\n                continue;\n            int c = isRow ? costs[j][i] : costs[i][j];\n            if (c < min1) {\n                min2 = min1;\n                min1 = c;\n                minP = i;\n            } else if (c < min2)\n                min2 = c;\n        }\n        return new int[]{min2 - min1, min1, minP};\n    }\n\n    static int[] maxPenalty(int len1, int len2, boolean isRow) {\n        int md = Integer.MIN_VALUE;\n        int pc = -1, pm = -1, mc = -1;\n        for (int i = 0; i < len1; i++) {\n            if (isRow ? rowDone[i] : colDone[i])\n                continue;\n            int[] res = diff(i, len2, isRow);\n            if (res[0] > md) {\n                md = res[0];  \n                pm = i;       \n                mc = res[1];  \n                pc = res[2];  \n            }\n        }\n        return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};\n    }\n}\n"}
{"id": 59810, "name": "Air mass", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    RE  = 6371000 \n    DD  = 0.001   \n    FIN = 1e7     \n)\n\n\nfunc rho(a float64) float64 { return math.Exp(-a / 8500) }\n\n\nfunc radians(degrees float64) float64 { return degrees * math.Pi / 180 }\n\n\n\n\nfunc height(a, z, d float64) float64 {\n    aa := RE + a\n    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))\n    return hh - RE\n}\n\n\nfunc columnDensity(a, z float64) float64 {\n    sum := 0.0\n    d := 0.0\n    for d < FIN {\n        delta := math.Max(DD, DD*d) \n        sum += rho(height(a, z, d+0.5*delta)) * delta\n        d += delta\n    }\n    return sum\n}\n\nfunc airmass(a, z float64) float64 {\n    return columnDensity(a, z) / columnDensity(a, 0)\n}\n\nfunc main() {\n    fmt.Println(\"Angle     0 m              13700 m\")\n    fmt.Println(\"------------------------------------\")\n    for z := 0; z <= 90; z += 5 {\n        fz := float64(z)\n        fmt.Printf(\"%2d      %11.8f      %11.8f\\n\", z, airmass(0, fz), airmass(13700, fz))\n    }\n}\n", "Java": "public class AirMass {\n    public static void main(String[] args) {\n        System.out.println(\"Angle     0 m              13700 m\");\n        System.out.println(\"------------------------------------\");\n        for (double z = 0; z <= 90; z+= 5) {\n            System.out.printf(\"%2.0f      %11.8f      %11.8f\\n\",\n                            z, airmass(0.0, z), airmass(13700.0, z));\n        }\n    }\n\n    private static double rho(double a) {\n        \n        return Math.exp(-a / 8500.0);\n    }\n\n    private static double height(double a, double z, double d) {\n        \n        \n        \n        double aa = RE + a;\n        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));\n        return hh - RE;\n    }\n\n    private static double columnDensity(double a, double z) {\n        \n        double sum = 0.0, d = 0.0;\n        while (d < FIN) {\n            \n            double delta = Math.max(DD * d, DD);\n            sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n            d += delta;\n        }\n        return sum;\n    }\n     \n    private static double airmass(double a, double z) {\n        return columnDensity(a, z) / columnDensity(a, 0.0);\n    }\n\n    private static final double RE = 6371000.0; \n    private static final double DD = 0.001; \n    private static final double FIN = 10000000.0; \n}\n"}
{"id": 59811, "name": "Sorting algorithms_Pancake sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n"}
{"id": 59812, "name": "Chemical calculator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar atomicMass = map[string]float64{\n    \"H\":   1.008,\n    \"He\":  4.002602,\n    \"Li\":  6.94,\n    \"Be\":  9.0121831,\n    \"B\":   10.81,\n    \"C\":   12.011,\n    \"N\":   14.007,\n    \"O\":   15.999,\n    \"F\":   18.998403163,\n    \"Ne\":  20.1797,\n    \"Na\":  22.98976928,\n    \"Mg\":  24.305,\n    \"Al\":  26.9815385,\n    \"Si\":  28.085,\n    \"P\":   30.973761998,\n    \"S\":   32.06,\n    \"Cl\":  35.45,\n    \"Ar\":  39.948,\n    \"K\":   39.0983,\n    \"Ca\":  40.078,\n    \"Sc\":  44.955908,\n    \"Ti\":  47.867,\n    \"V\":   50.9415,\n    \"Cr\":  51.9961,\n    \"Mn\":  54.938044,\n    \"Fe\":  55.845,\n    \"Co\":  58.933194,\n    \"Ni\":  58.6934,\n    \"Cu\":  63.546,\n    \"Zn\":  65.38,\n    \"Ga\":  69.723,\n    \"Ge\":  72.630,\n    \"As\":  74.921595,\n    \"Se\":  78.971,\n    \"Br\":  79.904,\n    \"Kr\":  83.798,\n    \"Rb\":  85.4678,\n    \"Sr\":  87.62,\n    \"Y\":   88.90584,\n    \"Zr\":  91.224,\n    \"Nb\":  92.90637,\n    \"Mo\":  95.95,\n    \"Ru\":  101.07,\n    \"Rh\":  102.90550,\n    \"Pd\":  106.42,\n    \"Ag\":  107.8682,\n    \"Cd\":  112.414,\n    \"In\":  114.818,\n    \"Sn\":  118.710,\n    \"Sb\":  121.760,\n    \"Te\":  127.60,\n    \"I\":   126.90447,\n    \"Xe\":  131.293,\n    \"Cs\":  132.90545196,\n    \"Ba\":  137.327,\n    \"La\":  138.90547,\n    \"Ce\":  140.116,\n    \"Pr\":  140.90766,\n    \"Nd\":  144.242,\n    \"Pm\":  145,\n    \"Sm\":  150.36,\n    \"Eu\":  151.964,\n    \"Gd\":  157.25,\n    \"Tb\":  158.92535,\n    \"Dy\":  162.500,\n    \"Ho\":  164.93033,\n    \"Er\":  167.259,\n    \"Tm\":  168.93422,\n    \"Yb\":  173.054,\n    \"Lu\":  174.9668,\n    \"Hf\":  178.49,\n    \"Ta\":  180.94788,\n    \"W\":   183.84,\n    \"Re\":  186.207,\n    \"Os\":  190.23,\n    \"Ir\":  192.217,\n    \"Pt\":  195.084,\n    \"Au\":  196.966569,\n    \"Hg\":  200.592,\n    \"Tl\":  204.38,\n    \"Pb\":  207.2,\n    \"Bi\":  208.98040,\n    \"Po\":  209,\n    \"At\":  210,\n    \"Rn\":  222,\n    \"Fr\":  223,\n    \"Ra\":  226,\n    \"Ac\":  227,\n    \"Th\":  232.0377,\n    \"Pa\":  231.03588,\n    \"U\":   238.02891,\n    \"Np\":  237,\n    \"Pu\":  244,\n    \"Am\":  243,\n    \"Cm\":  247,\n    \"Bk\":  247,\n    \"Cf\":  251,\n    \"Es\":  252,\n    \"Fm\":  257,\n    \"Uue\": 315,\n    \"Ubn\": 299,\n}\n\nfunc replaceParens(s string) string {\n    var letter byte = 'a'\n    for {\n        start := strings.IndexByte(s, '(')\n        if start == -1 {\n            break\n        }\n    restart:\n        for i := start + 1; i < len(s); i++ {\n            if s[i] == ')' {\n                expr := s[start+1 : i]\n                symbol := fmt.Sprintf(\"@%c\", letter)\n                s = strings.Replace(s, s[start:i+1], symbol, 1)\n                atomicMass[symbol] = evaluate(expr)\n                letter++\n                break\n            }\n            if s[i] == '(' {\n                start = i\n                goto restart\n            }\n        }\n    }\n    return s\n}\n\nfunc evaluate(s string) float64 {\n    s += string('[') \n    var symbol, number string\n    sum := 0.0\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        switch {\n        case c >= '@' && c <= '[': \n            n := 1\n            if number != \"\" {\n                n, _ = strconv.Atoi(number)\n            }\n            if symbol != \"\" {\n                sum += atomicMass[symbol] * float64(n)\n            }\n            if c == '[' {\n                break\n            }\n            symbol = string(c)\n            number = \"\"\n        case c >= 'a' && c <= 'z':\n            symbol += string(c)\n        case c >= '0' && c <= '9':\n            number += string(c)\n        default:\n            panic(fmt.Sprintf(\"Unexpected symbol %c in molecule\", c))\n        }\n    }\n    return sum\n}\n\nfunc main() {\n    molecules := []string{\n        \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\", \"COOH(C(CH3)2)3CH3\",\n        \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\",\n    }\n    for _, molecule := range molecules {\n        mass := evaluate(replaceParens(molecule))\n        fmt.Printf(\"%17s -> %7.3f\\n\", molecule, mass)\n    }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\npublic class ChemicalCalculator {\n    private static final Map<String, Double> atomicMass = new HashMap<>();\n\n    static {\n        atomicMass.put(\"H\", 1.008);\n        atomicMass.put(\"He\", 4.002602);\n        atomicMass.put(\"Li\", 6.94);\n        atomicMass.put(\"Be\", 9.0121831);\n        atomicMass.put(\"B\", 10.81);\n        atomicMass.put(\"C\", 12.011);\n        atomicMass.put(\"N\", 14.007);\n        atomicMass.put(\"O\", 15.999);\n        atomicMass.put(\"F\", 18.998403163);\n        atomicMass.put(\"Ne\", 20.1797);\n        atomicMass.put(\"Na\", 22.98976928);\n        atomicMass.put(\"Mg\", 24.305);\n        atomicMass.put(\"Al\", 26.9815385);\n        atomicMass.put(\"Si\", 28.085);\n        atomicMass.put(\"P\", 30.973761998);\n        atomicMass.put(\"S\", 32.06);\n        atomicMass.put(\"Cl\", 35.45);\n        atomicMass.put(\"Ar\", 39.948);\n        atomicMass.put(\"K\", 39.0983);\n        atomicMass.put(\"Ca\", 40.078);\n        atomicMass.put(\"Sc\", 44.955908);\n        atomicMass.put(\"Ti\", 47.867);\n        atomicMass.put(\"V\", 50.9415);\n        atomicMass.put(\"Cr\", 51.9961);\n        atomicMass.put(\"Mn\", 54.938044);\n        atomicMass.put(\"Fe\", 55.845);\n        atomicMass.put(\"Co\", 58.933194);\n        atomicMass.put(\"Ni\", 58.6934);\n        atomicMass.put(\"Cu\", 63.546);\n        atomicMass.put(\"Zn\", 65.38);\n        atomicMass.put(\"Ga\", 69.723);\n        atomicMass.put(\"Ge\", 72.630);\n        atomicMass.put(\"As\", 74.921595);\n        atomicMass.put(\"Se\", 78.971);\n        atomicMass.put(\"Br\", 79.904);\n        atomicMass.put(\"Kr\", 83.798);\n        atomicMass.put(\"Rb\", 85.4678);\n        atomicMass.put(\"Sr\", 87.62);\n        atomicMass.put(\"Y\", 88.90584);\n        atomicMass.put(\"Zr\", 91.224);\n        atomicMass.put(\"Nb\", 92.90637);\n        atomicMass.put(\"Mo\", 95.95);\n        atomicMass.put(\"Ru\", 101.07);\n        atomicMass.put(\"Rh\", 102.90550);\n        atomicMass.put(\"Pd\", 106.42);\n        atomicMass.put(\"Ag\", 107.8682);\n        atomicMass.put(\"Cd\", 112.414);\n        atomicMass.put(\"In\", 114.818);\n        atomicMass.put(\"Sn\", 118.710);\n        atomicMass.put(\"Sb\", 121.760);\n        atomicMass.put(\"Te\", 127.60);\n        atomicMass.put(\"I\", 126.90447);\n        atomicMass.put(\"Xe\", 131.293);\n        atomicMass.put(\"Cs\", 132.90545196);\n        atomicMass.put(\"Ba\", 137.327);\n        atomicMass.put(\"La\", 138.90547);\n        atomicMass.put(\"Ce\", 140.116);\n        atomicMass.put(\"Pr\", 140.90766);\n        atomicMass.put(\"Nd\", 144.242);\n        atomicMass.put(\"Pm\", 145.0);\n        atomicMass.put(\"Sm\", 150.36);\n        atomicMass.put(\"Eu\", 151.964);\n        atomicMass.put(\"Gd\", 157.25);\n        atomicMass.put(\"Tb\", 158.92535);\n        atomicMass.put(\"Dy\", 162.500);\n        atomicMass.put(\"Ho\", 164.93033);\n        atomicMass.put(\"Er\", 167.259);\n        atomicMass.put(\"Tm\", 168.93422);\n        atomicMass.put(\"Yb\", 173.054);\n        atomicMass.put(\"Lu\", 174.9668);\n        atomicMass.put(\"Hf\", 178.49);\n        atomicMass.put(\"Ta\", 180.94788);\n        atomicMass.put(\"W\", 183.84);\n        atomicMass.put(\"Re\", 186.207);\n        atomicMass.put(\"Os\", 190.23);\n        atomicMass.put(\"Ir\", 192.217);\n        atomicMass.put(\"Pt\", 195.084);\n        atomicMass.put(\"Au\", 196.966569);\n        atomicMass.put(\"Hg\", 200.592);\n        atomicMass.put(\"Tl\", 204.38);\n        atomicMass.put(\"Pb\", 207.2);\n        atomicMass.put(\"Bi\", 208.98040);\n        atomicMass.put(\"Po\", 209.0);\n        atomicMass.put(\"At\", 210.0);\n        atomicMass.put(\"Rn\", 222.0);\n        atomicMass.put(\"Fr\", 223.0);\n        atomicMass.put(\"Ra\", 226.0);\n        atomicMass.put(\"Ac\", 227.0);\n        atomicMass.put(\"Th\", 232.0377);\n        atomicMass.put(\"Pa\", 231.03588);\n        atomicMass.put(\"U\", 238.02891);\n        atomicMass.put(\"Np\", 237.0);\n        atomicMass.put(\"Pu\", 244.0);\n        atomicMass.put(\"Am\", 243.0);\n        atomicMass.put(\"Cm\", 247.0);\n        atomicMass.put(\"Bk\", 247.0);\n        atomicMass.put(\"Cf\", 251.0);\n        atomicMass.put(\"Es\", 252.0);\n        atomicMass.put(\"Fm\", 257.0);\n        atomicMass.put(\"Uue\", 315.0);\n        atomicMass.put(\"Ubn\", 299.0);\n    }\n\n    private static double evaluate(String s) {\n        String sym = s + \"[\";\n        double sum = 0.0;\n        StringBuilder symbol = new StringBuilder();\n        String number = \"\";\n        for (int i = 0; i < sym.length(); ++i) {\n            char c = sym.charAt(i);\n            if ('@' <= c && c <= '[') {\n                \n                int n = 1;\n                if (!number.isEmpty()) {\n                    n = Integer.parseInt(number);\n                }\n                if (symbol.length() > 0) {\n                    sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;\n                }\n                if (c == '[') {\n                    break;\n                }\n                symbol = new StringBuilder(String.valueOf(c));\n                number = \"\";\n            } else if ('a' <= c && c <= 'z') {\n                symbol.append(c);\n            } else if ('0' <= c && c <= '9') {\n                number += c;\n            } else {\n                throw new RuntimeException(\"Unexpected symbol \" + c + \" in molecule\");\n            }\n        }\n        return sum;\n    }\n\n    private static String replaceParens(String s) {\n        char letter = 'a';\n        String si = s;\n        while (true) {\n            int start = si.indexOf('(');\n            if (start == -1) {\n                break;\n            }\n\n            for (int i = start + 1; i < si.length(); ++i) {\n                if (si.charAt(i) == ')') {\n                    String expr = si.substring(start + 1, i);\n                    String symbol = \"@\" + letter;\n                    String pattern = Pattern.quote(si.substring(start, i + 1));\n                    si = si.replaceFirst(pattern, symbol);\n                    atomicMass.put(symbol, evaluate(expr));\n                    letter++;\n                    break;\n                }\n                if (si.charAt(i) == '(') {\n                    start = i;\n                }\n            }\n        }\n        return si;\n    }\n\n    public static void main(String[] args) {\n        List<String> molecules = List.of(\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        );\n        for (String molecule : molecules) {\n            double mass = evaluate(replaceParens(molecule));\n            System.out.printf(\"%17s -> %7.3f\\n\", molecule, mass);\n        }\n    }\n}\n"}
{"id": 59813, "name": "Active Directory_Connect", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n", "Java": "import java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n    public static void main(String[] args) throws LdapException, IOException {\n        try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n            connection.bind();\n            connection.unBind();\n        }\n    }\n}\n"}
{"id": 59814, "name": "Permutations by swapping", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n", "Java": "package org.rosettacode.java;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\n\npublic class HeapsAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tObject[] array = IntStream.range(0, 4)\n\t\t\t\t.boxed()\n\t\t\t\t.toArray();\n\t\tHeapsAlgorithm algorithm = new HeapsAlgorithm();\n\t\talgorithm.recursive(array);\n\t\tSystem.out.println();\n\t\talgorithm.loop(array);\n\t}\n\n\tvoid recursive(Object[] array) {\n\t\trecursive(array, array.length, true);\n\t}\n\n\tvoid recursive(Object[] array, int n, boolean plus) {\n\t\tif (n == 1) {\n\t\t\toutput(array, plus);\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trecursive(array, n - 1, i == 0);\n\t\t\t\tswap(array, n % 2 == 0 ? i : 0, n - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid output(Object[] array, boolean plus) {\n\t\tSystem.out.println(Arrays.toString(array) + (plus ? \" +1\" : \" -1\"));\n\t}\n\n\tvoid swap(Object[] array, int a, int b) {\n\t\tObject o = array[a];\n\t\tarray[a] = array[b];\n\t\tarray[b] = o;\n\t}\n\n\tvoid loop(Object[] array) {\n\t\tloop(array, array.length);\n\t}\n\n\tvoid loop(Object[] array, int n) {\n\t\tint[] c = new int[n];\n\t\toutput(array, true);\n\t\tboolean plus = false;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (c[i] < i) {\n\t\t\t\tif (i % 2 == 0) {\n\t\t\t\t\tswap(array, 0, i);\n\t\t\t\t} else {\n\t\t\t\t\tswap(array, c[i], i);\n\t\t\t\t}\n\t\t\t\toutput(array, plus);\n\t\t\t\tplus = !plus;\n\t\t\t\tc[i]++;\n\t\t\t\ti = 0;\n\t\t\t} else {\n\t\t\t\tc[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 59815, "name": "Pythagorean quadruples", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 59816, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 59817, "name": "Image convolution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/jpeg\"\n    \"math\"\n    \"os\"\n)\n\n\n\nfunc kf3(k *[9]float64, src, dst *image.Gray) {\n    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {\n        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {\n            var sum float64\n            var i int\n            for yo := y - 1; yo <= y+1; yo++ {\n                for xo := x - 1; xo <= x+1; xo++ {\n                    if (image.Point{xo, yo}).In(src.Rect) {\n                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)\n                    } else {\n                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)\n                    }\n                    i++\n                }\n            }\n            dst.SetGray(x, y,\n                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})\n        }\n    }\n}\n\nvar blur = [9]float64{\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9}\n\n\n\nfunc blurY(src *image.YCbCr) *image.YCbCr {\n    dst := *src\n\n    \n    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {\n        return &dst\n    }\n\n    \n    srcGray := image.Gray{src.Y, src.YStride, src.Rect}\n    dstGray := srcGray\n    dstGray.Pix = make([]uint8, len(src.Y))\n    kf3(&blur, &srcGray, &dstGray) \n\n    \n    dst.Y = dstGray.Pix                   \n    dst.Cb = append([]uint8{}, src.Cb...) \n    dst.Cr = append([]uint8{}, src.Cr...)\n    return &dst\n}\n\nfunc main() {\n    \n    \n    f, err := os.Open(\"Lenna100.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    img, err := jpeg.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n    y, ok := img.(*image.YCbCr)\n    if !ok {\n        fmt.Println(\"expected color jpeg\")\n        return\n    }\n    f, err = os.Create(\"blur.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.awt.image.*;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.*;\n\npublic class ImageConvolution\n{\n  public static class ArrayData\n  {\n    public final int[] dataArray;\n    public final int width;\n    public final int height;\n    \n    public ArrayData(int width, int height)\n    {\n      this(new int[width * height], width, height);\n    }\n    \n    public ArrayData(int[] dataArray, int width, int height)\n    {\n      this.dataArray = dataArray;\n      this.width = width;\n      this.height = height;\n    }\n    \n    public int get(int x, int y)\n    {  return dataArray[y * width + x];  }\n    \n    public void set(int x, int y, int value)\n    {  dataArray[y * width + x] = value;  }\n  }\n  \n  private static int bound(int value, int endIndex)\n  {\n    if (value < 0)\n      return 0;\n    if (value < endIndex)\n      return value;\n    return endIndex - 1;\n  }\n  \n  public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)\n  {\n    int inputWidth = inputData.width;\n    int inputHeight = inputData.height;\n    int kernelWidth = kernel.width;\n    int kernelHeight = kernel.height;\n    if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd width\");\n    if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))\n      throw new IllegalArgumentException(\"Kernel must have odd height\");\n    int kernelWidthRadius = kernelWidth >>> 1;\n    int kernelHeightRadius = kernelHeight >>> 1;\n    \n    ArrayData outputData = new ArrayData(inputWidth, inputHeight);\n    for (int i = inputWidth - 1; i >= 0; i--)\n    {\n      for (int j = inputHeight - 1; j >= 0; j--)\n      {\n        double newValue = 0.0;\n        for (int kw = kernelWidth - 1; kw >= 0; kw--)\n          for (int kh = kernelHeight - 1; kh >= 0; kh--)\n            newValue += kernel.get(kw, kh) * inputData.get(\n                          bound(i + kw - kernelWidthRadius, inputWidth),\n                          bound(j + kh - kernelHeightRadius, inputHeight));\n        outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));\n      }\n    }\n    return outputData;\n  }\n  \n  public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException\n  {\n    BufferedImage inputImage = ImageIO.read(new File(filename));\n    int width = inputImage.getWidth();\n    int height = inputImage.getHeight();\n    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);\n    ArrayData reds = new ArrayData(width, height);\n    ArrayData greens = new ArrayData(width, height);\n    ArrayData blues = new ArrayData(width, height);\n    for (int y = 0; y < height; y++)\n    {\n      for (int x = 0; x < width; x++)\n      {\n        int rgbValue = rgbData[y * width + x];\n        reds.set(x, y, (rgbValue >>> 16) & 0xFF);\n        greens.set(x, y, (rgbValue >>> 8) & 0xFF);\n        blues.set(x, y, rgbValue & 0xFF);\n      }\n    }\n    return new ArrayData[] { reds, greens, blues };\n  }\n  \n  public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException\n  {\n    ArrayData reds = redGreenBlue[0];\n    ArrayData greens = redGreenBlue[1];\n    ArrayData blues = redGreenBlue[2];\n    BufferedImage outputImage = new BufferedImage(reds.width, reds.height,\n                                                  BufferedImage.TYPE_INT_ARGB);\n    for (int y = 0; y < reds.height; y++)\n    {\n      for (int x = 0; x < reds.width; x++)\n      {\n        int red = bound(reds.get(x, y), 256);\n        int green = bound(greens.get(x, y), 256);\n        int blue = bound(blues.get(x, y), 256);\n        outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);\n      }\n    }\n    ImageIO.write(outputImage, \"PNG\", new File(filename));\n    return;\n  }\n  \n  public static void main(String[] args) throws IOException\n  {\n    int kernelWidth = Integer.parseInt(args[2]);\n    int kernelHeight = Integer.parseInt(args[3]);\n    int kernelDivisor = Integer.parseInt(args[4]);\n    System.out.println(\"Kernel size: \" + kernelWidth + \"x\" + kernelHeight +\n                       \", divisor=\" + kernelDivisor);\n    int y = 5;\n    ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);\n    for (int i = 0; i < kernelHeight; i++)\n    {\n      System.out.print(\"[\");\n      for (int j = 0; j < kernelWidth; j++)\n      {\n        kernel.set(j, i, Integer.parseInt(args[y++]));\n        System.out.print(\" \" + kernel.get(j, i) + \" \");\n      }\n      System.out.println(\"]\");\n    }\n    \n    ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);\n    for (int i = 0; i < dataArrays.length; i++)\n      dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);\n    writeOutputImage(args[1], dataArrays);\n    return;\n  }\n}\n"}
{"id": 59818, "name": "Dice game probabilities", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n", "Java": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}\n"}
{"id": 59819, "name": "Sokoban", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    level := `\n#######\n#     #\n#     #\n#. #  #\n#. $$ #\n#.$$  #\n#.#  @#\n#######`\n    fmt.Printf(\"level:%s\\n\", level)\n    fmt.Printf(\"solution:\\n%s\\n\", solve(level))\n}   \n    \nfunc solve(board string) string {\n    buffer = make([]byte, len(board))\n    width := strings.Index(board[1:], \"\\n\") + 1\n    dirs := []struct {\n        move, push string \n        dPos       int\n    }{\n        {\"u\", \"U\", -width},\n        {\"r\", \"R\", 1},\n        {\"d\", \"D\", width},\n        {\"l\", \"L\", -1},\n    }\n    visited := map[string]bool{board: true}\n    open := []state{state{board, \"\", strings.Index(board, \"@\")}}\n    for len(open) > 0 {\n        s1 := &open[0]\n        open = open[1:]\n        for _, dir := range dirs {\n            var newBoard, newSol string\n            newPos := s1.pos + dir.dPos\n            switch s1.board[newPos] {\n            case '$', '*':\n                newBoard = s1.push(dir.dPos)\n                if newBoard == \"\" || visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.push\n                if strings.IndexAny(newBoard, \".+\") < 0 {\n                    return newSol\n                }\n            case ' ', '.':\n                newBoard = s1.move(dir.dPos)\n                if visited[newBoard] {\n                    continue\n                }\n                newSol = s1.cSol + dir.move\n            default:\n                continue\n            }\n            open = append(open, state{newBoard, newSol, newPos})\n            visited[newBoard] = true\n        }\n    }\n    return \"No solution\"\n}\n\ntype state struct {\n    board string\n    cSol  string\n    pos   int\n}\n\nvar buffer []byte\n\nfunc (s *state) move(dPos int) string {\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    newPos := s.pos + dPos\n    if buffer[newPos] == ' ' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    return string(buffer)\n}\n\nfunc (s *state) push(dPos int) string {\n    newPos := s.pos + dPos\n    boxPos := newPos + dPos\n    switch s.board[boxPos] {\n    case ' ', '.':\n    default:\n        return \"\"\n    }\n    copy(buffer, s.board)\n    if buffer[s.pos] == '@' {\n        buffer[s.pos] = ' '\n    } else {\n        buffer[s.pos] = '.'\n    }\n    if buffer[newPos] == '$' {\n        buffer[newPos] = '@'\n    } else {\n        buffer[newPos] = '+'\n    }\n    if buffer[boxPos] == ' ' {\n        buffer[boxPos] = '$'\n    } else {\n        buffer[boxPos] = '*'\n    }\n    return string(buffer)\n}\n", "Java": "import java.util.*;\n\npublic class Sokoban {\n    String destBoard, currBoard;\n    int playerX, playerY, nCols;\n\n    Sokoban(String[] board) {\n        nCols = board[0].length();\n        StringBuilder destBuf = new StringBuilder();\n        StringBuilder currBuf = new StringBuilder();\n\n        for (int r = 0; r < board.length; r++) {\n            for (int c = 0; c < nCols; c++) {\n\n                char ch = board[r].charAt(c);\n\n                destBuf.append(ch != '$' && ch != '@' ? ch : ' ');\n                currBuf.append(ch != '.' ? ch : ' ');\n\n                if (ch == '@') {\n                    this.playerX = c;\n                    this.playerY = r;\n                }\n            }\n        }\n        destBoard = destBuf.toString();\n        currBoard = currBuf.toString();\n    }\n\n    String move(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newPlayerPos = (y + dy) * nCols + x + dx;\n\n        if (trialBoard.charAt(newPlayerPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[newPlayerPos] = '@';\n\n        return new String(trial);\n    }\n\n    String push(int x, int y, int dx, int dy, String trialBoard) {\n\n        int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n        if (trialBoard.charAt(newBoxPos) != ' ')\n            return null;\n\n        char[] trial = trialBoard.toCharArray();\n        trial[y * nCols + x] = ' ';\n        trial[(y + dy) * nCols + x + dx] = '@';\n        trial[newBoxPos] = '$';\n\n        return new String(trial);\n    }\n\n    boolean isSolved(String trialBoard) {\n        for (int i = 0; i < trialBoard.length(); i++)\n            if ((destBoard.charAt(i) == '.')\n                    != (trialBoard.charAt(i) == '$'))\n                return false;\n        return true;\n    }\n\n    String solve() {\n        class Board {\n            String cur, sol;\n            int x, y;\n\n            Board(String s1, String s2, int px, int py) {\n                cur = s1;\n                sol = s2;\n                x = px;\n                y = py;\n            }\n        }\n        char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};\n        int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};\n\n        Set<String> history = new HashSet<>();\n        LinkedList<Board> open = new LinkedList<>();\n\n        history.add(currBoard);\n        open.add(new Board(currBoard, \"\", playerX, playerY));\n\n        while (!open.isEmpty()) {\n            Board item = open.poll();\n            String cur = item.cur;\n            String sol = item.sol;\n            int x = item.x;\n            int y = item.y;\n\n            for (int i = 0; i < dirs.length; i++) {\n                String trial = cur;\n                int dx = dirs[i][0];\n                int dy = dirs[i][1];\n\n                \n                if (trial.charAt((y + dy) * nCols + x + dx) == '$') {\n\n                    \n                    if ((trial = push(x, y, dx, dy, trial)) != null) {\n\n                        \n                        if (!history.contains(trial)) {\n\n                            String newSol = sol + dirLabels[i][1];\n\n                            if (isSolved(trial))\n                                return newSol;\n\n                            open.add(new Board(trial, newSol, x + dx, y + dy));\n                            history.add(trial);\n                        }\n                    }\n\n                \n                } else if ((trial = move(x, y, dx, dy, trial)) != null) {\n\n                    if (!history.contains(trial)) {\n                        String newSol = sol + dirLabels[i][0];\n                        open.add(new Board(trial, newSol, x + dx, y + dy));\n                        history.add(trial);\n                    }\n                }\n            }\n        }\n        return \"No solution\";\n    }\n\n    public static void main(String[] a) {\n        String level = \"#######,#     #,#     #,#. #  #,#. $$ #,\"\n                + \"#.$$  #,#.#  @#,#######\";\n        System.out.println(new Sokoban(level.split(\",\")).solve());\n    }\n}\n"}
{"id": 59820, "name": "Practical numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc powerset(set []int) [][]int {\n    if len(set) == 0 {\n        return [][]int{{}}\n    }\n    head := set[0]\n    tail := set[1:]\n    p1 := powerset(tail)\n    var p2 [][]int\n    for _, s := range powerset(tail) {\n        h := []int{head}\n        h = append(h, s...)\n        p2 = append(p2, h)\n    }\n    return append(p1, p2...)\n}\n\nfunc isPractical(n int) bool {\n    if n == 1 {\n        return true\n    }\n    divs := rcu.ProperDivisors(n)\n    subsets := powerset(divs)\n    found := make([]bool, n) \n    count := 0\n    for _, subset := range subsets {\n        sum := rcu.SumInts(subset)\n        if sum > 0 && sum < n && !found[sum] {\n            found[sum] = true\n            count++\n            if count == n-1 {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"In the range 1..333, there are:\")\n    var practical []int\n    for i := 1; i <= 333; i++ {\n        if isPractical(i) {\n            practical = append(practical, i)\n        }\n    }\n    fmt.Println(\" \", len(practical), \"practical numbers\")\n    fmt.Println(\"  The first ten are\", practical[0:10])\n    fmt.Println(\"  The final ten are\", practical[len(practical)-10:])\n    fmt.Println(\"\\n666 is practical:\", isPractical(666))\n}\n", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n"}
{"id": 59821, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 59822, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 59823, "name": "Erdős-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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 main() {\n    limit := int(1e6)\n    c := sieve(limit - 1)\n    var erdos []int\n    for i := 2; i < limit; {\n        if !c[i] {\n            found := true\n            for j, fact := 1, 1; fact < i; {\n                if !c[i-fact] {\n                    found = false\n                    break\n                }\n                j++\n                fact = fact * j\n            }\n            if found {\n                erdos = append(erdos, i)\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i += 1\n        }\n    }\n    lowerLimit := 2500\n    var erdosLower []int\n    for _, e := range erdos {\n        if e < lowerLimit {\n            erdosLower = append(erdosLower, e)\n        } else {\n            break\n        }\n    }\n    fmt.Printf(\"The %d Erdős primes under %s are\\n\", len(erdosLower), commatize(lowerLimit))\n    for i, e := range erdosLower {\n        fmt.Printf(\"%6d\", e)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    show := 7875\n    fmt.Printf(\"\\n\\nThe %s Erdős prime is %s.\\n\", commatize(show), commatize(erdos[show-1]))\n}\n", "Java": "import java.util.*;\n\npublic class ErdosPrimes {\n    public static void main(String[] args) {\n        boolean[] sieve = primeSieve(1000000);\n        int maxPrint = 2500;\n        int maxCount = 7875;\n        System.out.printf(\"Erd\\u0151s primes less than %d:\\n\", maxPrint);\n        for (int count = 0, prime = 1; count < maxCount; ++prime) {\n            if (erdos(sieve, prime)) {\n                ++count;\n                if (prime < maxPrint) {\n                    System.out.printf(\"%6d\", prime);\n                    if (count % 10 == 0)\n                        System.out.println();\n                }\n                if (count == maxCount)\n                    System.out.printf(\"\\n\\nThe %dth Erd\\u0151s prime is %d.\\n\", maxCount, prime);\n            }\n        }\n    }\n\n    private static boolean erdos(boolean[] sieve, int p) {\n        if (!sieve[p])\n            return false;\n        for (int k = 1, f = 1; f < p; ++k, f *= k) {\n            if (sieve[p - f])\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3; ; p += 2) {\n            int q = p * p;\n            if (q >= limit)\n                break;\n            if (sieve[p]) {\n                int inc = 2 * p;\n                for (; q < limit; q += inc)\n                    sieve[q] = false;\n            }\n        }\n        return sieve;\n    }\n}\n"}
{"id": 59824, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59825, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59826, "name": "Solve a Numbrix puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nvar example1 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,00,46,45,00,55,74,00,00\",\n    \"00,38,00,00,43,00,00,78,00\",\n    \"00,35,00,00,00,00,00,71,00\",\n    \"00,00,33,00,00,00,59,00,00\",\n    \"00,17,00,00,00,00,00,67,00\",\n    \"00,18,00,00,11,00,00,64,00\",\n    \"00,00,24,21,00,01,02,00,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n    \"00,00,00,00,00,00,00,00,00\",\n    \"00,11,12,15,18,21,62,61,00\",\n    \"00,06,00,00,00,00,00,60,00\",\n    \"00,33,00,00,00,00,00,57,00\",\n    \"00,32,00,00,00,00,00,56,00\",\n    \"00,37,00,01,00,00,00,73,00\",\n    \"00,38,00,00,00,00,00,72,00\",\n    \"00,43,44,47,48,51,76,77,00\",\n    \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n    grid        [][]int\n    clues       []int\n    totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n    if count > totalToFill {\n        return true\n    }\n\n    back := grid[r][c]\n\n    if back != 0 && back != count {\n        return false\n    }\n\n    if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n        return false\n    }\n\n    if back == count {\n        nextClue++\n    }\n\n    grid[r][c] = count\n    for _, move := range moves {\n        if solve(r+move[1], c+move[0], count+1, nextClue) {\n            return true\n        }\n    }\n    grid[r][c] = back\n    return false\n}\n\nfunc printResult(n int) {\n    fmt.Println(\"Solution for example\", n, \"\\b:\")\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                continue\n            }\n            fmt.Printf(\"%2d \", i)\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    for n, board := range [2][]string{example1, example2} {\n        nRows := len(board) + 2\n        nCols := len(strings.Split(board[0], \",\")) + 2\n        startRow, startCol := 0, 0\n        grid = make([][]int, nRows)\n        totalToFill = (nRows - 2) * (nCols - 2)\n        var lst []int\n\n        for r := 0; r < nRows; r++ {\n            grid[r] = make([]int, nCols)\n            for c := 0; c < nCols; c++ {\n                grid[r][c] = -1\n            }\n            if r >= 1 && r < nRows-1 {\n                row := strings.Split(board[r-1], \",\")\n                for c := 1; c < nCols-1; c++ {\n                    val, _ := strconv.Atoi(row[c-1])\n                    if val > 0 {\n                        lst = append(lst, val)\n                    }\n                    if val == 1 {\n                        startRow, startCol = r, c\n                    }\n                    grid[r][c] = val\n                }\n            }\n        }\n\n        sort.Ints(lst)\n        clues = lst\n        if solve(startRow, startCol, 1, 0) {\n            printResult(n + 1)\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class Numbrix {\n\n    final static String[] board = {\n        \"00,00,00,00,00,00,00,00,00\",\n        \"00,00,46,45,00,55,74,00,00\",\n        \"00,38,00,00,43,00,00,78,00\",\n        \"00,35,00,00,00,00,00,71,00\",\n        \"00,00,33,00,00,00,59,00,00\",\n        \"00,17,00,00,00,00,00,67,00\",\n        \"00,18,00,00,11,00,00,64,00\",\n        \"00,00,24,21,00,01,02,00,00\",\n        \"00,00,00,00,00,00,00,00,00\"};\n\n    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\n    static int[][] grid;\n    static int[] clues;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 2;\n        int nCols = board[0].split(\",\").length + 2;\n        int startRow = 0, startCol = 0;\n\n        grid = new int[nRows][nCols];\n        totalToFill = (nRows - 2) * (nCols - 2);\n        List<Integer> lst = new ArrayList<>();\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n\n            if (r >= 1 && r < nRows - 1) {\n\n                String[] row = board[r - 1].split(\",\");\n\n                for (int c = 1; c < nCols - 1; c++) {\n                    int val = Integer.parseInt(row[c - 1]);\n                    if (val > 0)\n                        lst.add(val);\n                    if (val == 1) {\n                        startRow = r;\n                        startCol = c;\n                    }\n                    grid[r][c] = val;\n                }\n            }\n        }\n\n        clues = lst.stream().sorted().mapToInt(i -> i).toArray();\n\n        if (solve(startRow, startCol, 1, 0))\n            printResult();\n    }\n\n    static boolean solve(int r, int c, int count, int nextClue) {\n        if (count > totalToFill)\n            return true;\n\n        if (grid[r][c] != 0 && grid[r][c] != count)\n            return false;\n\n        if (grid[r][c] == 0 && nextClue < clues.length)\n            if (clues[nextClue] == count)\n                return false;\n\n        int back = grid[r][c];\n        if (back == count)\n            nextClue++;\n\n        grid[r][c] = count;\n        for (int[] move : moves)\n            if (solve(r + move[1], c + move[0], count + 1, nextClue))\n                return true;\n\n        grid[r][c] = back;\n        return false;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    continue;\n                System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59827, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 59828, "name": "Church numerals", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n    return func(x any) any {\n        return x\n    }\n}\n\nfunc (c church) succ() church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return f(c(f)(x))\n        }\n    }\n}\n\nfunc (c church) add(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(f)(d(f)(x))\n        }\n    }\n}\n\nfunc (c church) mul(d church) church {\n    return func(f fn) fn {\n        return func(x any) any {\n            return c(d(f))(x)\n        }\n    }\n}\n\nfunc (c church) pow(d church) church {\n    di := d.toInt()\n    prod := c\n    for i := 1; i < di; i++ {\n        prod = prod.mul(c)\n    }\n    return prod\n}\n\nfunc (c church) toInt() int {\n    return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n    if i == 0 {\n        return zero\n    } else {\n        return intToChurch(i - 1).succ()\n    }\n}\n\nfunc incr(i any) any {\n    return i.(int) + 1\n}\n\nfunc main() {\n    z := church(zero)\n    three := z.succ().succ().succ()\n    four := three.succ()\n\n    fmt.Println(\"three        ->\", three.toInt())\n    fmt.Println(\"four         ->\", four.toInt())\n    fmt.Println(\"three + four ->\", three.add(four).toInt())\n    fmt.Println(\"three * four ->\", three.mul(four).toInt())\n    fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n    fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n    fmt.Println(\"5 -> five    ->\", intToChurch(5).toInt())\n}\n", "Java": "package lvijay;\n\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Function;\n\npublic class Church {\n    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {\n    }\n\n    public static ChurchNum zero() {\n        return f -> x -> x;\n    }\n\n    public static ChurchNum next(ChurchNum n) {\n        return f -> x -> f.apply(n.apply(f).apply(x));\n    }\n\n    public static ChurchNum plus(ChurchNum a) {\n        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n    }\n\n    public static ChurchNum pow(ChurchNum m) {\n        return n -> m.apply(n);\n    }\n\n    public static ChurchNum mult(ChurchNum a) {\n        return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n    }\n\n    public static ChurchNum toChurchNum(int n) {\n        if (n <= 0) {\n            return zero();\n        }\n        return next(toChurchNum(n - 1));\n    }\n\n    public static int toInt(ChurchNum c) {\n        AtomicInteger counter = new AtomicInteger(0);\n        ChurchNum funCounter = f -> {\n            counter.incrementAndGet();\n            return f;\n        };\n\n        plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n        return counter.get();\n    }\n\n    public static void main(String[] args) {\n        ChurchNum zero  = zero();\n        ChurchNum three = next(next(next(zero)));\n        ChurchNum four  = next(next(next(next(zero))));\n\n        System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); \n        System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); \n\n        System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); \n        System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); \n\n        \n        System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); \n        System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); \n\n        System.out.println(\"  8=\" + toInt(toChurchNum(8))); \n    }\n}\n"}
{"id": 59829, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59830, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59831, "name": "Solve a Hopido puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nvar board = []string{\n    \".00.00.\",\n    \"0000000\",\n    \"0000000\",\n    \".00000.\",\n    \"..000..\",\n    \"...0...\",\n}\n\nvar moves = [][2]int{\n    {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n    if count > totalToFill {\n        return true\n    }\n    nbrs := neighbors(r, c)\n    if len(nbrs) == 0 && count != totalToFill {\n        return false\n    }\n    sort.Slice(nbrs, func(i, j int) bool {\n        return nbrs[i][2] < nbrs[j][2]\n    })\n\n    for _, nb := range nbrs {\n        r = nb[0]\n        c = nb[1]\n        grid[r][c] = count\n        if solve(r, c, count+1) {\n            return true\n        }\n        grid[r][c] = 0\n    }\n    return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n    for _, m := range moves {\n        x := m[0]\n        y := m[1]\n        if grid[r+y][c+x] == 0 {\n            num := countNeighbors(r+y, c+x) - 1\n            nbrs = append(nbrs, [3]int{r + y, c + x, num})\n        }\n    }\n    return\n}\n\nfunc countNeighbors(r, c int) int {\n    num := 0\n    for _, m := range moves {\n        if grid[r+m[1]][c+m[0]] == 0 {\n            num++\n        }\n    }\n    return num\n}\n\nfunc printResult() {\n    for _, row := range grid {\n        for _, i := range row {\n            if i == -1 {\n                fmt.Print(\"   \")\n            } else {\n                fmt.Printf(\"%2d \", i)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    nRows := len(board) + 6\n    nCols := len(board[0]) + 6\n    grid = make([][]int, nRows)\n    for r := 0; r < nRows; r++ {\n        grid[r] = make([]int, nCols)\n        for c := 0; c < nCols; c++ {\n            grid[r][c] = -1\n        }\n        for c := 3; c < nCols-3; c++ {\n            if r >= 3 && r < nRows-3 {\n                if board[r-3][c-3] == '0' {\n                    grid[r][c] = 0\n                    totalToFill++\n                }\n            }\n        }\n    }\n    pos, r, c := -1, 0, 0\n    for {\n        for {\n            pos++\n            r = pos / nCols\n            c = pos % nCols\n            if grid[r][c] != -1 {\n                break\n            }\n        }\n        grid[r][c] = 1\n        if solve(r, c, 2) {\n            break\n        }\n        grid[r][c] = 0\n        if pos >= nRows*nCols {\n            break\n        }\n    }\n    printResult()\n}\n", "Java": "import java.util.*;\n\npublic class Hopido {\n\n    final static String[] board = {\n        \".00.00.\",\n        \"0000000\",\n        \"0000000\",\n        \".00000.\",\n        \"..000..\",\n        \"...0...\"};\n\n    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},\n    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};\n    static int[][] grid;\n    static int totalToFill;\n\n    public static void main(String[] args) {\n        int nRows = board.length + 6;\n        int nCols = board[0].length() + 6;\n\n        grid = new int[nRows][nCols];\n\n        for (int r = 0; r < nRows; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 3; c < nCols - 3; c++)\n                if (r >= 3 && r < nRows - 3) {\n                    if (board[r - 3].charAt(c - 3) == '0') {\n                        grid[r][c] = 0;\n                        totalToFill++;\n                    }\n                }\n        }\n\n        int pos = -1, r, c;\n        do {\n            do {\n                pos++;\n                r = pos / nCols;\n                c = pos % nCols;\n            } while (grid[r][c] == -1);\n\n            grid[r][c] = 1;\n            if (solve(r, c, 2))\n                break;\n            grid[r][c] = 0;\n\n        } while (pos < nRows * nCols);\n\n        printResult();\n    }\n\n    static boolean solve(int r, int c, int count) {\n        if (count > totalToFill)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != totalToFill)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59832, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 59833, "name": "Nonogram solver", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n    for i := range bs {\n        if bs[i] && other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n    for i := range bs {\n        if bs[i] || other[i] {\n            bs[i] = true\n        } else {\n            bs[i] = false\n        }\n    }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n    if cond {\n        return s1\n    }\n    return s2\n}\n\nfunc newPuzzle(data [2]string) {\n    rowData := strings.Fields(data[0])\n    colData := strings.Fields(data[1])\n    rows := getCandidates(rowData, len(colData))\n    cols := getCandidates(colData, len(rowData))\n\n    for {\n        numChanged := reduceMutual(cols, rows)\n        if numChanged == -1 {\n            fmt.Println(\"No solution\")\n            return\n        }\n        if numChanged == 0 {\n            break\n        }\n    }\n\n    for _, row := range rows {\n        for i := 0; i < len(cols); i++ {\n            fmt.Printf(iff(row[0][i], \"# \", \". \"))\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\n\nfunc getCandidates(data []string, le int) [][]BitSet {\n    var result [][]BitSet\n    for _, s := range data {\n        var lst []BitSet\n        a := []byte(s)\n        sumBytes := 0\n        for _, b := range a {\n            sumBytes += int(b - 'A' + 1)\n        }\n        prep := make([]string, len(a))\n        for i, b := range a {\n            prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n        }\n        for _, r := range genSequence(prep, le-sumBytes+1) {\n            bits := []byte(r[1:])\n            bitset := make(BitSet, len(bits))\n            for i, b := range bits {\n                bitset[i] = b == '1'\n            }\n            lst = append(lst, bitset)\n        }\n        result = append(result, lst)\n    }\n    return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n    le := len(ones)\n    if le == 0 {\n        return []string{strings.Repeat(\"0\", numZeros)}\n    }\n    var result []string\n    for x := 1; x < numZeros-le+2; x++ {\n        skipOne := ones[1:]\n        for _, tail := range genSequence(skipOne, numZeros-x) {\n            result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n        }\n    }\n    return result\n}\n\n\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n    countRemoved1 := reduce(cols, rows)\n    if countRemoved1 == -1 {\n        return -1\n    }\n    countRemoved2 := reduce(rows, cols)\n    if countRemoved2 == -1 {\n        return -1\n    }\n    return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n    countRemoved := 0\n    for i := 0; i < len(a); i++ {\n        commonOn := make(BitSet, len(b))\n        for j := 0; j < len(b); j++ {\n            commonOn[j] = true\n        }\n        commonOff := make(BitSet, len(b))\n\n        \n        for _, candidate := range a[i] {\n            commonOn.and(candidate)\n            commonOff.or(candidate)\n        }\n\n        \n        for j := 0; j < len(b); j++ {\n            fi, fj := i, j\n            for k := len(b[j]) - 1; k >= 0; k-- {\n                cnd := b[j][k]\n                if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n                    lb := len(b[j])\n                    copy(b[j][k:], b[j][k+1:])\n                    b[j][lb-1] = nil\n                    b[j] = b[j][:lb-1]\n                    countRemoved++\n                }\n            }\n            if len(b[j]) == 0 {\n                return -1\n            }\n        }\n    }\n    return countRemoved\n}\n\nfunc main() {\n    p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n    p2 := [2]string{\n        \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n        \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n    }\n\n    p3 := [2]string{\n        \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n            \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n            \"AAAAD BDG CEF CBDB BBB FC\",\n    }\n\n    p4 := [2]string{\n        \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n        \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n            \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n    }\n\n    for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n        newPuzzle(puzzleData)\n    }\n}\n", "Java": "import java.util.*;\nimport static java.util.Arrays.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class NonogramSolver {\n\n    static String[] p1 = {\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"};\n\n    static String[] p2 = {\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\", \"D D AE \"\n        + \"CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"};\n\n    static String[] p3 = {\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \"\n        + \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n        \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \"\n        + \"AAAAD BDG CEF CBDB BBB FC\"};\n\n    static String[] p4 = {\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q \"\n        + \"R AN AAN EI H G\", \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \"\n        + \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"};\n\n    public static void main(String[] args) {\n        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})\n            newPuzzle(puzzleData);\n    }\n\n    static void newPuzzle(String[] data) {\n        String[] rowData = data[0].split(\"\\\\s\");\n        String[] colData = data[1].split(\"\\\\s\");\n\n        List<List<BitSet>> cols, rows;\n        rows = getCandidates(rowData, colData.length);\n        cols = getCandidates(colData, rowData.length);\n\n        int numChanged;\n        do {\n            numChanged = reduceMutual(cols, rows);\n            if (numChanged == -1) {\n                System.out.println(\"No solution\");\n                return;\n            }\n        } while (numChanged > 0);\n\n        for (List<BitSet> row : rows) {\n            for (int i = 0; i < cols.size(); i++)\n                System.out.print(row.get(0).get(i) ? \"# \" : \". \");\n            System.out.println();\n        }\n        System.out.println();\n    }\n\n    \n    static List<List<BitSet>> getCandidates(String[] data, int len) {\n        List<List<BitSet>> result = new ArrayList<>();\n\n        for (String s : data) {\n            List<BitSet> lst = new LinkedList<>();\n\n            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();\n            List<String> prep = stream(s.split(\"\"))\n                    .map(x -> repeat(x.charAt(0) - 'A' + 1, \"1\")).collect(toList());\n\n            for (String r : genSequence(prep, len - sumChars + 1)) {\n                char[] bits = r.substring(1).toCharArray();\n                BitSet bitset = new BitSet(bits.length);\n                for (int i = 0; i < bits.length; i++)\n                    bitset.set(i, bits[i] == '1');\n                lst.add(bitset);\n            }\n            result.add(lst);\n        }\n        return result;\n    }\n\n    \n    static List<String> genSequence(List<String> ones, int numZeros) {\n        if (ones.isEmpty())\n            return asList(repeat(numZeros, \"0\"));\n\n        List<String> result = new ArrayList<>();\n        for (int x = 1; x < numZeros - ones.size() + 2; x++) {\n            List<String> skipOne = ones.stream().skip(1).collect(toList());\n            for (String tail : genSequence(skipOne, numZeros - x))\n                result.add(repeat(x, \"0\") + ones.get(0) + tail);\n        }\n        return result;\n    }\n\n    static String repeat(int n, String s) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < n; i++)\n            sb.append(s);\n        return sb.toString();\n    }\n\n    \n\n    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {\n        int countRemoved1 = reduce(cols, rows);\n        if (countRemoved1 == -1)\n            return -1;\n\n        int countRemoved2 = reduce(rows, cols);\n        if (countRemoved2 == -1)\n            return -1;\n\n        return countRemoved1 + countRemoved2;\n    }\n\n    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {\n        int countRemoved = 0;\n\n        for (int i = 0; i < a.size(); i++) {\n\n            BitSet commonOn = new BitSet();\n            commonOn.set(0, b.size());\n            BitSet commonOff = new BitSet();\n\n            \n            for (BitSet candidate : a.get(i)) {\n                commonOn.and(candidate);\n                commonOff.or(candidate);\n            }\n\n            \n            for (int j = 0; j < b.size(); j++) {\n                final int fi = i, fj = j;\n\n                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))\n                        || (!commonOff.get(fj) && cnd.get(fi))))\n                    countRemoved++;\n\n                if (b.get(j).isEmpty())\n                    return -1;\n            }\n        }\n        return countRemoved;\n    }\n}\n"}
{"id": 59834, "name": "Word search", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n    nRows    = 10\n    nCols    = nRows\n    gridSize = nRows * nCols\n    minWords = 25\n)\n\nvar (\n    re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n    re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n    numAttempts int\n    cells       [nRows][nCols]byte\n    solutions   []string\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if re1.MatchString(word) {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc createWordSearch(words []string) *grid {\n    var gr *grid\nouter:\n    for i := 1; i < 100; i++ {\n        gr = new(grid)\n        messageLen := gr.placeMessage(\"Rosetta Code\")\n        target := gridSize - messageLen\n        cellsFilled := 0\n        rand.Shuffle(len(words), func(i, j int) {\n            words[i], words[j] = words[j], words[i]\n        })\n        for _, word := range words {\n            cellsFilled += gr.tryPlaceWord(word)\n            if cellsFilled == target {\n                if len(gr.solutions) >= minWords {\n                    gr.numAttempts = i\n                    break outer\n                } else { \n                    break\n                }\n            }\n        }\n    }\n    return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n    msg = strings.ToUpper(msg)\n    msg = re2.ReplaceAllLiteralString(msg, \"\")\n    messageLen := len(msg)\n    if messageLen > 0 && messageLen < gridSize {\n        gapSize := gridSize / messageLen\n        for i := 0; i < messageLen; i++ {\n            pos := i*gapSize + rand.Intn(gapSize)\n            gr.cells[pos/nCols][pos%nCols] = msg[i]\n        }\n        return messageLen\n    }\n    return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n    randDir := rand.Intn(len(dirs))\n    randPos := rand.Intn(gridSize)\n    for dir := 0; dir < len(dirs); dir++ {\n        dir = (dir + randDir) % len(dirs)\n        for pos := 0; pos < gridSize; pos++ {\n            pos = (pos + randPos) % gridSize\n            lettersPlaced := gr.tryLocation(word, dir, pos)\n            if lettersPlaced > 0 {\n                return lettersPlaced\n            }\n        }\n    }\n    return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n    r := pos / nCols\n    c := pos % nCols\n    le := len(word)\n\n    \n    if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n        (dirs[dir][0] == -1 && (le-1) > c) ||\n        (dirs[dir][1] == 1 && (le+r) > nRows) ||\n        (dirs[dir][1] == -1 && (le-1) > r) {\n        return 0\n    }\n    overlaps := 0\n\n    \n    rr := r\n    cc := c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n            return 0\n        }\n        cc += dirs[dir][0]\n        rr += dirs[dir][1]\n    }\n\n    \n    rr = r\n    cc = c\n    for i := 0; i < le; i++ {\n        if gr.cells[rr][cc] == word[i] {\n            overlaps++\n        } else {\n            gr.cells[rr][cc] = word[i]\n        }\n        if i < le-1 {\n            cc += dirs[dir][0]\n            rr += dirs[dir][1]\n        }\n    }\n\n    lettersPlaced := le - overlaps\n    if lettersPlaced > 0 {\n        sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n        gr.solutions = append(gr.solutions, sol)\n    }\n    return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n    if gr.numAttempts == 0 {\n        fmt.Println(\"No grid to display\")\n        return\n    }\n    size := len(gr.solutions)\n    fmt.Println(\"Attempts:\", gr.numAttempts)\n    fmt.Println(\"Number of words:\", size)\n    fmt.Println(\"\\n     0  1  2  3  4  5  6  7  8  9\")\n    for r := 0; r < nRows; r++ {\n        fmt.Printf(\"\\n%d   \", r)\n        for c := 0; c < nCols; c++ {\n            fmt.Printf(\" %c \", gr.cells[r][c])\n        }\n    }\n    fmt.Println(\"\\n\")\n    for i := 0; i < size-1; i += 2 {\n        fmt.Printf(\"%s   %s\\n\", gr.solutions[i], gr.solutions[i+1])\n    }\n    if size%2 == 1 {\n        fmt.Println(gr.solutions[size-1])\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    unixDictPath := \"/usr/share/dict/words\"\n    printResult(createWordSearch(readWords(unixDictPath)))\n}\n", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n"}
{"id": 59835, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 59836, "name": "Break OO privacy", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported   int \n\tunexported int \n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n\n\n\n\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) \n\tv = v.Elem()              \n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t\n\tfmt.Printf(\"    %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) \n\t\tfmt.Printf(\"    %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t\n\tv.Field(0).SetInt(16)\n\t\n\t\n\t\n\t\n\n\t\n\t\n\t\n\tvp := v.Field(1).Addr()            \n\tup := unsafe.Pointer(vp.Pointer()) \n\tp := (*int)(up)                    \n\tfmt.Printf(\"  vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\"  up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\"   p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 \n\t\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\n\n\n\n\n\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 59837, "name": "Object serialization", "Go": "package main\n\nimport (\n    \"encoding/gob\"\n    \"fmt\"\n    \"os\"\n)\n\ntype printable interface {\n    print()\n}\n\nfunc main() {\n    \n    animals := []printable{\n        &Animal{Alive: true},\n        &Cat{},\n        &Lab{\n            Dog:   Dog{Animal: Animal{Alive: true}},\n            Color: \"yellow\",\n        },\n        &Collie{Dog: Dog{\n            Animal:           Animal{Alive: true},\n            ObedienceTrained: true,\n        }},\n    }\n\n    \n    fmt.Println(\"created:\")\n    for _, a := range animals {\n        a.print()\n    }\n\n    \n    f, err := os.Create(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, a := range animals {\n        gob.Register(a)\n    }\n    err = gob.NewEncoder(f).Encode(animals)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n\n    \n    f, err = os.Open(\"objects.dat\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var clones []printable\n    gob.NewDecoder(f).Decode(&clones)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    fmt.Println(\"\\nloaded from objects.dat:\")\n    for _, c := range clones {\n        c.print()\n    }\n}\n\ntype Animal struct {\n    Alive bool\n}\n\nfunc (a *Animal) print() {\n    if a.Alive {\n        fmt.Println(\"   live animal, unspecified type\")\n    } else {\n        fmt.Println(\"   dead animal, unspecified type\")\n    }\n}\n\ntype Dog struct {\n    Animal\n    ObedienceTrained bool\n}\n\nfunc (d *Dog) print() {\n    switch {\n    case !d.Alive:\n        fmt.Println(\"   dead dog\")\n    case d.ObedienceTrained:\n        fmt.Println(\"   trained dog\")\n    default:\n        fmt.Println(\"   dog, not trained\")\n    }\n}\n\ntype Cat struct {\n    Animal\n    LitterBoxTrained bool\n}\n    \nfunc (c *Cat) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead cat\")\n    case c.LitterBoxTrained:\n        fmt.Println(\"   litter box trained cat\")\n    default:\n        fmt.Println(\"   cat, not litter box trained\")\n    }\n}\n\ntype Lab struct {\n    Dog \n    Color string\n}   \n\nfunc (l *Lab) print() {\n    var r string\n    if l.Color == \"\" {\n        r = \"lab, color unspecified\"\n    } else {\n        r = l.Color + \" lab\"\n    }\n    switch {\n    case !l.Alive:\n        fmt.Println(\"   dead\", r)\n    case l.ObedienceTrained:\n        fmt.Println(\"   trained\", r)\n    default:\n        fmt.Printf(\"   %s, not trained\\n\", r)\n    }\n}   \n\ntype Collie struct {\n    Dog \n    CatchesFrisbee bool\n}   \n\nfunc (c *Collie) print() {\n    switch {\n    case !c.Alive:\n        fmt.Println(\"   dead collie\")\n    case c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, catches frisbee\")\n    case c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   trained collie, but doesn't catch frisbee\")\n    case !c.ObedienceTrained && c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, but catches frisbee\")\n    case !c.ObedienceTrained && !c.CatchesFrisbee:\n        fmt.Println(\"   collie, not trained, doesn't catch frisbee\")\n    }\n}\n", "Java": "import java.io.*;\n\n\nclass Entity implements Serializable {\n    \n    \n    static final long serialVersionUID = 3504465751164822571L;\n    String name = \"Entity\";\n    public String toString() { return name; }\n}\n\nclass Person extends Entity implements Serializable {\n    static final long serialVersionUID = -9170445713373959735L;\n    Person() { name = \"Cletus\"; }\n}\n\npublic class SerializationTest {\n    public static void main(String[] args) {\n        Person instance1 = new Person();\n        System.out.println(instance1);\n\n        Entity instance2 = new Entity();\n        System.out.println(instance2);\n\n        \n        try {\n            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"objects.dat\")); \n\n            out.writeObject(instance1); \n            out.writeObject(instance2);\n            out.close();\n            System.out.println(\"Serialized...\");\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while serializing\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n\n        \n        try {\n            ObjectInput in = new ObjectInputStream(new FileInputStream(\"objects.dat\")); \n\n            Object readObject1 = in.readObject(); \n            Object readObject2 = in.readObject(); \n            in.close();\n            System.out.println(\"Deserialized...\");\n\n            System.out.println(readObject1);\n            System.out.println(readObject2);\n        } catch (IOException e) {\n            System.err.println(\"Something screwed up while deserializing\");\n            e.printStackTrace();\n            System.exit(1);\n        } catch (ClassNotFoundException e) {\n            System.err.println(\"Unknown class for deserialized object\");\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n}\n"}
{"id": 59838, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 59839, "name": "Eertree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tree := eertree([]byte(\"eertree\"))\n    fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n    length int\n    edges\n    suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n    tree := []node{\n        evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n        oddRoot:  {length: -1, suffix: oddRoot, edges: edges{}},\n    }\n    suffix := oddRoot\n    var n, k int\n    for i, c := range s {\n        for n = suffix; ; n = tree[n].suffix {\n            k = tree[n].length\n            if b := i - k - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        if e, ok := tree[n].edges[c]; ok {\n            suffix = e\n            continue\n        }\n        suffix = len(tree)\n        tree = append(tree, node{length: k + 2, edges: edges{}})\n        tree[n].edges[c] = suffix\n        if tree[suffix].length == 1 {\n            tree[suffix].suffix = 0\n            continue\n        }\n        for {\n            n = tree[n].suffix\n            if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n                break\n            }\n        }\n        tree[suffix].suffix = tree[n].edges[c]\n    }\n    return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n    var children func(int, string)\n    children = func(n int, p string) {\n        for c, n := range tree[n].edges {\n            c := string(c)\n            p := c + p + c\n            s = append(s, p)\n            children(n, p)\n        }\n    }\n    children(0, \"\")\n    for c, n := range tree[1].edges {\n        c := string(c)\n        s = append(s, c)\n        children(n, c)\n    }\n    return\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 59840, "name": "Long year", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    centuries := []string{\"20th\", \"21st\", \"22nd\"}\n    starts := []int{1900, 2000, 2100} \n    for i := 0; i < len(centuries); i++ {\n        var longYears []int\n        fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n        for j := starts[i]; j < starts[i] + 100; j++ {\n            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n            if _, week := t.ISOWeek(); week == 53 {\n                longYears = append(longYears, j)\n            }\n        }\n        fmt.Println(longYears)\n    }\n}\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 59841, "name": "Zumkeller numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n    divs := []int{1, n}\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            j := n / i\n            divs = append(divs, i)\n            if i != j {\n                divs = append(divs, j)\n            }\n        }\n    }\n    return divs\n}\n\nfunc sum(divs []int) int {\n    sum := 0\n    for _, div := range divs {\n        sum += div\n    }\n    return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n    if sum == 0 {\n        return true\n    }\n    le := len(divs)\n    if le == 0 {\n        return false\n    }\n    last := divs[le-1]\n    divs = divs[0 : le-1]\n    if last > sum {\n        return isPartSum(divs, sum)\n    }\n    return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n    divs := getDivisors(n)\n    sum := sum(divs)\n    \n    if sum%2 == 1 {\n        return false\n    }\n    \n    if n%2 == 1 {\n        abundance := sum - 2*n\n        return abundance > 0 && abundance%2 == 0\n    }\n    \n    return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n    fmt.Println(\"The first 220 Zumkeller numbers are:\")\n    for i, count := 2, 0; count < 220; i++ {\n        if isZumkeller(i) {\n            fmt.Printf(\"%3d \", i)\n            count++\n            if count%20 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if isZumkeller(i) {\n            fmt.Printf(\"%5d \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n    for i, count := 3, 0; count < 40; i += 2 {\n        if (i % 10 != 5) && isZumkeller(i) {\n            fmt.Printf(\"%7d \", i)\n            count++\n            if count%8 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Println()\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n"}
{"id": 59842, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 59843, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 59844, "name": "Associative array_Merging", "Go": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n    result := make(assoc)\n    for k, v := range base {\n        result[k] = v\n    }\n    for k, v := range update {\n        result[k] = v\n    }\n    return result\n}\n\nfunc main() {\n    base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n    update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n    result := merge(base, update)\n    fmt.Println(result)\n}\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 59845, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 59846, "name": "Metallic ratios", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n    \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n    fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n    fmt.Print(\"First 15 elements: \")\n    var x0, x1 int64 = 1, 1\n    fmt.Printf(\"%d, %d\", x0, x1)\n    for i := 1; i <= 13; i++ {\n        x2 := b*x1 + x0\n        fmt.Printf(\", %d\", x2)\n        x0, x1 = x1, x2\n    }\n    fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n    ratio := big.NewRat(1, 1)\n    iters := 0\n    prev := ratio.FloatString(dp)\n    for {\n        iters++\n        x2.Mul(bb, x1)\n        x2.Add(x2, x0)\n        this := ratio.SetFrac(x2, x1).FloatString(dp)\n        if prev == this {\n            plural := \"s\"\n            if iters == 1 {\n                plural = \" \"\n            }\n            fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n            return\n        }\n        prev = this\n        x0.Set(x1)\n        x1.Set(x2)\n    }\n}\n\nfunc main() {\n    for b := int64(0); b < 10; b++ {\n        lucas(b)\n        metallic(b, 32)\n    }\n    fmt.Println(\"Golden ratio, where b = 1:\")\n    metallic(1, 256)\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 59847, "name": "Markov chain text generator", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"markov: \")\n\tinput := flag.String(\"in\", \"alice_oz.txt\", \"input file\")\n\tn := flag.Int(\"n\", 2, \"number of words to use as prefix\")\n\truns := flag.Int(\"runs\", 1, \"number of runs to generate\")\n\twordsPerRun := flag.Int(\"words\", 300, \"number of words per run\")\n\tstartOnCapital := flag.Bool(\"capital\", false, \"start output with a capitalized prefix\")\n\tstopAtSentence := flag.Bool(\"sentence\", false, \"end output at a sentence ending punctuation mark (after n words)\")\n\tflag.Parse()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tm, err := NewMarkovFromFile(*input, *n)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < *runs; i++ {\n\t\terr = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Markov struct {\n\tn           int\n\tcapitalized int \n\tsuffix      map[string][]string\n}\n\n\n\nfunc NewMarkovFromFile(filename string, n int) (*Markov, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close() \n\treturn NewMarkov(f, n)\n}\n\n\n\nfunc NewMarkov(r io.Reader, n int) (*Markov, error) {\n\tm := &Markov{\n\t\tn:      n,\n\t\tsuffix: make(map[string][]string),\n\t}\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\n\twindow := make([]string, 0, n)\n\tfor sc.Scan() {\n\t\tword := sc.Text()\n\t\tif len(window) > 0 {\n\t\t\tprefix := strings.Join(window, \" \")\n\t\t\tm.suffix[prefix] = append(m.suffix[prefix], word)\n\t\t\t\n\t\t\tif isCapitalized(prefix) {\n\t\t\t\tm.capitalized++\n\t\t\t}\n\t\t}\n\t\twindow = appendMax(n, window, word)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\n\n\n\n\nfunc (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {\n\t\n\t\n\t\n\tbw := bufio.NewWriter(w)\n\n\tvar i int\n\tif startCapital {\n\t\ti = rand.Intn(m.capitalized)\n\t} else {\n\t\ti = rand.Intn(len(m.suffix))\n\t}\n\tvar prefix string\n\tfor prefix = range m.suffix {\n\t\tif startCapital && !isCapitalized(prefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti--\n\t}\n\n\tbw.WriteString(prefix) \n\tprefixWords := strings.Fields(prefix)\n\tn -= len(prefixWords)\n\n\tfor {\n\t\tsuffixChoices := m.suffix[prefix]\n\t\tif len(suffixChoices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ti = rand.Intn(len(suffixChoices))\n\t\tsuffix := suffixChoices[i]\n\t\t\n\t\tbw.WriteByte(' ') \n\t\tif _, err := bw.WriteString(suffix); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn--\n\t\tif n < 0 && (!stopSentence || isSentenceEnd(suffix)) {\n\t\t\tbreak\n\t\t}\n\n\t\tprefixWords = appendMax(m.n, prefixWords, suffix)\n\t\tprefix = strings.Join(prefixWords, \" \")\n\t}\n\treturn bw.Flush()\n}\n\nfunc isCapitalized(s string) bool {\n\t\n\t\n\t\n\tr, _ := utf8.DecodeRuneInString(s)\n\treturn unicode.IsUpper(r)\n}\n\nfunc isSentenceEnd(s string) bool {\n\tr, _ := utf8.DecodeLastRuneInString(s)\n\t\n\t\n\t\n\treturn r == '.' || r == '?' || r == '!'\n}\n\nfunc appendMax(max int, slice []string, value string) []string {\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tif len(slice)+1 > max {\n\t\tn := copy(slice, slice[1:])\n\t\tslice = slice[:n]\n\t}\n\treturn append(slice, value)\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.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Random;\n\npublic class MarkovChain {\n    private static Random r = new Random();\n\n    private static String markov(String filePath, int keySize, int outputSize) throws IOException {\n        if (keySize < 1) throw new IllegalArgumentException(\"Key size can't be less than 1\");\n        Path path = Paths.get(filePath);\n        byte[] bytes = Files.readAllBytes(path);\n        String[] words = new String(bytes).trim().split(\" \");\n        if (outputSize < keySize || outputSize >= words.length) {\n            throw new IllegalArgumentException(\"Output size is out of range\");\n        }\n        Map<String, List<String>> dict = new HashMap<>();\n\n        for (int i = 0; i < (words.length - keySize); ++i) {\n            StringBuilder key = new StringBuilder(words[i]);\n            for (int j = i + 1; j < i + keySize; ++j) {\n                key.append(' ').append(words[j]);\n            }\n            String value = (i + keySize < words.length) ? words[i + keySize] : \"\";\n            if (!dict.containsKey(key.toString())) {\n                ArrayList<String> list = new ArrayList<>();\n                list.add(value);\n                dict.put(key.toString(), list);\n            } else {\n                dict.get(key.toString()).add(value);\n            }\n        }\n\n        int n = 0;\n        int rn = r.nextInt(dict.size());\n        String prefix = (String) dict.keySet().toArray()[rn];\n        List<String> output = new ArrayList<>(Arrays.asList(prefix.split(\" \")));\n\n        while (true) {\n            List<String> suffix = dict.get(prefix);\n            if (suffix.size() == 1) {\n                if (Objects.equals(suffix.get(0), \"\")) return output.stream().reduce(\"\", (a, b) -> a + \" \" + b);\n                output.add(suffix.get(0));\n            } else {\n                rn = r.nextInt(suffix.size());\n                output.add(suffix.get(rn));\n            }\n            if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce(\"\", (a, b) -> a + \" \" + b);\n            n++;\n            prefix = output.stream().skip(n).limit(keySize).reduce(\"\", (a, b) -> a + \" \" + b).trim();\n        }\n    }\n\n    public static void main(String[] args) throws IOException {\n        System.out.println(markov(\"alice_oz.txt\", 3, 200));\n    }\n}\n"}
{"id": 59848, "name": "Dijkstra's algorithm", "Go": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \n\tpr    map[Vertex]int \n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\n\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\ntype Vertex int\n\n\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 59849, "name": "Geometric algebra", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype vector []float64\n\nfunc e(n uint) vector {\n    if n > 4 {\n        panic(\"n must be less than 5\")\n    }\n    result := make(vector, 32)\n    result[1<<n] = 1.0\n    return result\n}\n\nfunc cdot(a, b vector) vector {\n    return mul(vector{0.5}, add(mul(a, b), mul(b, a)))\n}\n\nfunc neg(x vector) vector {\n    return mul(vector{-1}, x)\n}\n\nfunc bitCount(i int) int {\n    i = i - ((i >> 1) & 0x55555555)\n    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n    i = (i + (i >> 4)) & 0x0F0F0F0F\n    i = i + (i >> 8)\n    i = i + (i >> 16)\n    return i & 0x0000003F\n}\n\nfunc reorderingSign(i, j int) float64 {\n    i >>= 1\n    sum := 0\n    for i != 0 {\n        sum += bitCount(i & j)\n        i >>= 1\n    }\n    cond := (sum & 1) == 0\n    if cond {\n        return 1.0\n    }\n    return -1.0\n}\n\nfunc add(a, b vector) vector {\n    result := make(vector, 32)\n    copy(result, a)\n    for i, _ := range b {\n        result[i] += b[i]\n    }\n    return result\n}\n\nfunc mul(a, b vector) vector {\n    result := make(vector, 32)\n    for i, _ := range a {\n        if a[i] != 0 {\n            for j, _ := range b {\n                if b[j] != 0 {\n                    s := reorderingSign(i, j) * a[i] * b[j]\n                    k := i ^ j\n                    result[k] += s\n                }\n            }\n        }\n    }\n    return result\n}\n\nfunc randomVector() vector {\n    result := make(vector, 32)\n    for i := uint(0); i < 5; i++ {\n        result = add(result, mul(vector{rand.Float64()}, e(i)))\n    }\n    return result\n}\n\nfunc randomMultiVector() vector {\n    result := make(vector, 32)\n    for i := 0; i < 32; i++ {\n        result[i] = rand.Float64()\n    }\n    return result\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for i := uint(0); i < 5; i++ {\n        for j := uint(0); j < 5; j++ {\n            if i < j {\n                if cdot(e(i), e(j))[0] != 0 {\n                    fmt.Println(\"Unexpected non-null scalar product.\")\n                    return\n                }\n            } else if i == j {\n                if cdot(e(i), e(j))[0] == 0 {\n                    fmt.Println(\"Unexpected null scalar product.\")\n                }\n            }\n        }\n    }\n\n    a := randomMultiVector()\n    b := randomMultiVector()\n    c := randomMultiVector()\n    x := randomVector()\n\n    \n    fmt.Println(mul(mul(a, b), c))\n    fmt.Println(mul(a, mul(b, c)))\n\n    \n    fmt.Println(mul(a, add(b, c)))\n    fmt.Println(add(mul(a, b), mul(a, c)))\n\n    \n    fmt.Println(mul(add(a, b), c))\n    fmt.Println(add(mul(a, c), mul(b, c)))\n\n    \n    fmt.Println(mul(x, x))\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n"}
{"id": 59850, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 59851, "name": "Suffix tree", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    vis(buildTree(\"banana$\"))\n}\n\ntype tree []node\n\ntype node struct {\n    sub string \n    ch  []int  \n}\n\nfunc buildTree(s string) tree {\n    t := tree{node{}} \n    for i := range s {\n        t = t.addSuffix(s[i:])\n    }\n    return t\n}\n\nfunc (t tree) addSuffix(suf string) tree {\n    n := 0\n    for i := 0; i < len(suf); {\n        b := suf[i]\n        ch := t[n].ch\n        var x2, n2 int\n        for ; ; x2++ {\n            if x2 == len(ch) {\n                \n                n2 = len(t)\n                t = append(t, node{sub: suf[i:]})\n                t[n].ch = append(t[n].ch, n2)\n                return t\n            }\n            n2 = ch[x2]\n            if t[n2].sub[0] == b {\n                break\n            }\n        }\n        \n        sub2 := t[n2].sub\n        j := 0\n        for ; j < len(sub2); j++ {\n            if suf[i+j] != sub2[j] {\n                \n                n3 := n2\n                \n                n2 = len(t)\n                t = append(t, node{sub2[:j], []int{n3}})\n                t[n3].sub = sub2[j:] \n                t[n].ch[x2] = n2\n                break \n            }\n        }\n        i += j \n        n = n2 \n    }\n    return t\n}\n\nfunc vis(t tree) {\n    if len(t) == 0 {\n        fmt.Println(\"<empty>\")\n        return\n    }\n    var f func(int, string)\n    f = func(n int, pre string) {\n        children := t[n].ch\n        if len(children) == 0 {\n            fmt.Println(\"╴\", t[n].sub)\n            return\n        }\n        fmt.Println(\"┐\", t[n].sub)\n        last := len(children) - 1\n        for _, ch := range children[:last] {\n            fmt.Print(pre, \"├─\")\n            f(ch, pre+\"│ \")\n        }\n        fmt.Print(pre, \"└─\")\n        f(children[last], pre+\"  \")\n    }\n    f(0, \"\")\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SuffixTreeProblem {\n    private static class Node {\n        String sub = \"\";                       \n        List<Integer> ch = new ArrayList<>();  \n    }\n\n    private static class SuffixTree {\n        private List<Node> nodes = new ArrayList<>();\n\n        public SuffixTree(String str) {\n            nodes.add(new Node());\n            for (int i = 0; i < str.length(); ++i) {\n                addSuffix(str.substring(i));\n            }\n        }\n\n        private void addSuffix(String suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.length()) {\n                char b = suf.charAt(i);\n                List<Integer> children = nodes.get(n).ch;\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    if (x2 == children.size()) {\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = suf.substring(i);\n                        nodes.add(temp);\n                        children.add(n2);\n                        return;\n                    }\n                    n2 = children.get(x2);\n                    if (nodes.get(n2).sub.charAt(0) == b) break;\n                    x2++;\n                }\n                \n                String sub2 = nodes.get(n2).sub;\n                int j = 0;\n                while (j < sub2.length()) {\n                    if (suf.charAt(i + j) != sub2.charAt(j)) {\n                        \n                        int n3 = n2;\n                        \n                        n2 = nodes.size();\n                        Node temp = new Node();\n                        temp.sub = sub2.substring(0, j);\n                        temp.ch.add(n3);\n                        nodes.add(temp);\n                        nodes.get(n3).sub = sub2.substring(j);  \n                        nodes.get(n).ch.set(x2, n2);\n                        break;  \n                    }\n                    j++;\n                }\n                i += j;  \n                n = n2;  \n            }\n        }\n\n        public void visualize() {\n            if (nodes.isEmpty()) {\n                System.out.println(\"<empty>\");\n                return;\n            }\n            visualize_f(0, \"\");\n        }\n\n        private void visualize_f(int n, String pre) {\n            List<Integer> children = nodes.get(n).ch;\n            if (children.isEmpty()) {\n                System.out.println(\"- \" + nodes.get(n).sub);\n                return;\n            }\n            System.out.println(\"┐ \" + nodes.get(n).sub);\n            for (int i = 0; i < children.size() - 1; i++) {\n                Integer c = children.get(i);\n                System.out.print(pre + \"├─\");\n                visualize_f(c, pre + \"│ \");\n            }\n            System.out.print(pre + \"└─\");\n            visualize_f(children.get(children.size() - 1), pre + \"  \");\n        }\n    }\n\n    public static void main(String[] args) {\n        new SuffixTree(\"banana$\").visualize();\n    }\n}\n"}
{"id": 59852, "name": "Associative array_Iteration", "Go": "myMap := map[string]int {\n\t   \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value := range myMap {\n    fmt.Printf(\"key = %s, value = %d\\n\", key, value)\n}\n\n\nfor key := range myMap {\n    fmt.Printf(\"key = %s\\n\", key)\n}\n\n\nfor _, value := range myMap {\n    fmt.Printf(\"value = %d\\n\", value)\n}\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 59853, "name": "Define a primitive data type", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 59854, "name": "Define a primitive data type", "Go": "package main\n\nimport \"fmt\"\n\ntype TinyInt int\n\nfunc NewTinyInt(i int) TinyInt {\n    if i < 1 {\n        i = 1\n    } else if i > 10 {\n        i = 10\n    }\n    return TinyInt(i)\n}\n\nfunc (t1 TinyInt) Add(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) + int(t2))\n}\n\nfunc (t1 TinyInt) Sub(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) - int(t2))\n}\n\nfunc (t1 TinyInt) Mul(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) * int(t2))\n}\n\nfunc (t1 TinyInt) Div(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) / int(t2))\n}\n\nfunc (t1 TinyInt) Rem(t2 TinyInt) TinyInt {\n    return NewTinyInt(int(t1) % int(t2))\n}\n\nfunc (t TinyInt) Inc() TinyInt {\n    return t.Add(TinyInt(1))\n}\n\nfunc (t TinyInt) Dec() TinyInt {\n    return t.Sub(TinyInt(1))\n}\n\nfunc main() {\n    t1 := NewTinyInt(6)\n    t2 := NewTinyInt(3)\n    fmt.Println(\"t1      =\", t1)\n    fmt.Println(\"t2      =\", t2)\n    fmt.Println(\"t1 + t2 =\", t1.Add(t2))\n    fmt.Println(\"t1 - t2 =\", t1.Sub(t2))\n    fmt.Println(\"t1 * t2 =\", t1.Mul(t2))\n    fmt.Println(\"t1 / t2 =\", t1.Div(t2))\n    fmt.Println(\"t1 % t2 =\", t1.Rem(t2))\n    fmt.Println(\"t1 + 1  =\", t1.Inc())\n    fmt.Println(\"t1 - 1  =\", t1.Dec())\n}\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 59855, "name": "AVL tree", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n"}
{"id": 59856, "name": "AVL tree", "Go": "package avl\n\n\n\n\n\n\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\ntype Node struct {\n    Data    Key      \n    Balance int      \n    Link    [2]*Node \n}\n\n\n\n\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\n\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\n\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n", "Java": "public class AVLtree {\n\n    private Node root;\n\n    private static class Node {\n        private int key;\n        private int balance;\n        private int height;\n        private Node left;\n        private Node right;\n        private Node parent;\n\n        Node(int key, Node parent) {\n            this.key = key;\n            this.parent = parent;\n        }\n    }\n\n    public boolean insert(int key) {\n        if (root == null) {\n            root = new Node(key, null);\n            return true;\n        }\n\n        Node n = root;\n        while (true) {\n            if (n.key == key)\n                return false;\n\n            Node parent = n;\n\n            boolean goLeft = n.key > key;\n            n = goLeft ? n.left : n.right;\n\n            if (n == null) {\n                if (goLeft) {\n                    parent.left = new Node(key, parent);\n                } else {\n                    parent.right = new Node(key, parent);\n                }\n                rebalance(parent);\n                break;\n            }\n        }\n        return true;\n    }\n\n    private void delete(Node node) {\n        if (node.left == null && node.right == null) {\n            if (node.parent == null) {\n                root = null;\n            } else {\n                Node parent = node.parent;\n                if (parent.left == node) {\n                    parent.left = null;\n                } else {\n                    parent.right = null;\n                }\n                rebalance(parent);\n            }\n            return;\n        }\n\n        if (node.left != null) {\n            Node child = node.left;\n            while (child.right != null) child = child.right;\n            node.key = child.key;\n            delete(child);\n        } else {\n            Node child = node.right;\n            while (child.left != null) child = child.left;\n            node.key = child.key;\n            delete(child);\n        }\n    }\n\n    public void delete(int delKey) {\n        if (root == null)\n            return;\n\n        Node child = root;\n        while (child != null) {\n            Node node = child;\n            child = delKey >= node.key ? node.right : node.left;\n            if (delKey == node.key) {\n                delete(node);\n                return;\n            }\n        }\n    }\n\n    private void rebalance(Node n) {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent != null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node rotateLeft(Node a) {\n\n        Node b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right != null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateRight(Node a) {\n\n        Node b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left != null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent != null) {\n            if (b.parent.right == a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node rotateLeftThenRight(Node n) {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node rotateRightThenLeft(Node n) {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(Node n) {\n        if (n == null)\n            return -1;\n        return n.height;\n    }\n\n    private void setBalance(Node... nodes) {\n        for (Node n : nodes) {\n            reheight(n);\n            n.balance = height(n.right) - height(n.left);\n        }\n    }\n\n    public void printBalance() {\n        printBalance(root);\n    }\n\n    private void printBalance(Node n) {\n        if (n != null) {\n            printBalance(n.left);\n            System.out.printf(\"%s \", n.balance);\n            printBalance(n.right);\n        }\n    }\n\n    private void reheight(Node node) {\n        if (node != null) {\n            node.height = 1 + Math.max(height(node.left), height(node.right));\n        }\n    }\n\n    public static void main(String[] args) {\n        AVLtree tree = new AVLtree();\n\n        System.out.println(\"Inserting values 1 to 10\");\n        for (int i = 1; i < 10; i++)\n            tree.insert(i);\n\n        System.out.print(\"Printing balance: \");\n        tree.printBalance();\n    }\n}\n"}
{"id": 59857, "name": "Penrose tiling", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\ntype tiletype int\n\nconst (\n    kite tiletype = iota\n    dart\n)\n\ntype tile struct {\n    tt          tiletype\n    x, y        float64\n    angle, size float64\n}\n\nvar gr = (1 + math.Sqrt(5)) / 2 \n\nconst theta = math.Pi / 5 \n\nfunc setupPrototiles(w, h int) []tile {\n    var proto []tile\n    \n    for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {\n        ww := float64(w / 2)\n        hh := float64(h / 2)\n        proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})\n    }\n    return proto\n}\n\nfunc distinctTiles(tls []tile) []tile {\n    tileset := make(map[tile]bool)\n    for _, tl := range tls {\n        tileset[tl] = true\n    }\n    distinct := make([]tile, len(tileset))\n    for tl, _ := range tileset {\n        distinct = append(distinct, tl)\n    }\n    return distinct\n}\n\nfunc deflateTiles(tls []tile, gen int) []tile {\n    if gen <= 0 {\n        return tls\n    }\n    var next []tile\n    for _, tl := range tls {\n        x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr\n        var nx, ny float64\n        if tl.tt == dart {\n            next = append(next, tile{kite, x, y, a + 5*theta, size})\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                nx = x + math.Cos(a-4*theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-4*theta*sign)*gr*tl.size\n                next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})\n            }\n        } else {\n            for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {\n                next = append(next, tile{dart, x, y, a - 4*theta*sign, size})\n                nx = x + math.Cos(a-theta*sign)*gr*tl.size\n                ny = y - math.Sin(a-theta*sign)*gr*tl.size\n                next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})\n            }\n        }\n    }\n    \n    tls = distinctTiles(next)\n    return deflateTiles(tls, gen-1)\n}\n\nfunc drawTiles(dc *gg.Context, tls []tile) {\n    dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}\n    for _, tl := range tls {\n        angle := tl.angle - theta\n        dc.MoveTo(tl.x, tl.y)\n        ord := tl.tt\n        for i := 0; i < 3; i++ {\n            x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)\n            y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)\n            dc.LineTo(x, y)\n            angle += theta\n        }\n        dc.ClosePath()\n        if ord == kite {\n            dc.SetHexColor(\"FFA500\") \n        } else {\n            dc.SetHexColor(\"FFFF00\") \n        }\n        dc.FillPreserve()\n        dc.SetHexColor(\"A9A9A9\") \n        dc.SetLineWidth(1)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    w, h := 700, 450\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    tiles := deflateTiles(setupPrototiles(w, h), 5)\n    drawTiles(dc, tiles)\n    dc.SavePNG(\"penrose_tiling.png\")\n}\n", "Java": "import java.awt.*;\nimport java.util.List;\nimport java.awt.geom.Path2D;\nimport java.util.*;\nimport javax.swing.*;\nimport static java.lang.Math.*;\nimport static java.util.stream.Collectors.toList;\n\npublic class PenroseTiling extends JPanel {\n    \n    class Tile {\n        double x, y, angle, size;\n        Type type;\n\n        Tile(Type t, double x, double y, double a, double s) {\n            type = t;\n            this.x = x;\n            this.y = y;\n            angle = a;\n            size = s;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Tile) {\n                Tile t = (Tile) o;\n                return type == t.type && x == t.x && y == t.y && angle == t.angle;\n            }\n            return false;\n        }\n    }\n\n    enum Type {\n        Kite, Dart\n    }\n\n    static final double G = (1 + sqrt(5)) / 2; \n    static final double T = toRadians(36); \n\n    List<Tile> tiles = new ArrayList<>();\n\n    public PenroseTiling() {\n        int w = 700, h = 450;\n        setPreferredSize(new Dimension(w, h));\n        setBackground(Color.white);\n\n        tiles = deflateTiles(setupPrototiles(w, h), 5);\n    }\n\n    List<Tile> setupPrototiles(int w, int h) {\n        List<Tile> proto = new ArrayList<>();\n\n        \n        for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)\n            proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));\n\n        return proto;\n    }\n\n    List<Tile> deflateTiles(List<Tile> tls, int generation) {\n        if (generation <= 0)\n            return tls;\n\n        List<Tile> next = new ArrayList<>();\n\n        for (Tile tile : tls) {\n            double x = tile.x, y = tile.y, a = tile.angle, nx, ny;\n            double size = tile.size / G;\n\n            if (tile.type == Type.Dart) {\n                next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    nx = x + cos(a - 4 * T * sign) * G * tile.size;\n                    ny = y - sin(a - 4 * T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));\n                }\n\n            } else {\n\n                for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {\n                    next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));\n\n                    nx = x + cos(a - T * sign) * G * tile.size;\n                    ny = y - sin(a - T * sign) * G * tile.size;\n                    next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));\n                }\n            }\n        }\n        \n        tls = next.stream().distinct().collect(toList());\n\n        return deflateTiles(tls, generation - 1);\n    }\n\n    void drawTiles(Graphics2D g) {\n        double[][] dist = {{G, G, G}, {-G, -1, -G}};\n        for (Tile tile : tiles) {\n            double angle = tile.angle - T;\n            Path2D path = new Path2D.Double();\n            path.moveTo(tile.x, tile.y);\n\n            int ord = tile.type.ordinal();\n            for (int i = 0; i < 3; i++) {\n                double x = tile.x + dist[ord][i] * tile.size * cos(angle);\n                double y = tile.y - dist[ord][i] * tile.size * sin(angle);\n                path.lineTo(x, y);\n                angle += T;\n            }\n            path.closePath();\n            g.setColor(ord == 0 ? Color.orange : Color.yellow);\n            g.fill(path);\n            g.setColor(Color.darkGray);\n            g.draw(path);\n        }\n    }\n\n    @Override\n    public void paintComponent(Graphics og) {\n        super.paintComponent(og);\n        Graphics2D g = (Graphics2D) og;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        drawTiles(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(\"Penrose Tiling\");\n            f.setResizable(false);\n            f.add(new PenroseTiling(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59858, "name": "Sphenic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    const limit = 1000000\n    limit2 := int(math.Cbrt(limit)) \n    primes := rcu.Primes(limit / 6)\n    pc := len(primes)\n    var sphenic []int\n    fmt.Println(\"Sphenic numbers less than 1,000:\")\n    for i := 0; i < pc-2; i++ {\n        if primes[i] > limit2 {\n            break\n        }\n        for j := i + 1; j < pc-1; j++ {\n            prod := primes[i] * primes[j]\n            if prod+primes[j+1] >= limit {\n                break\n            }\n            for k := j + 1; k < pc; k++ {\n                res := prod * primes[k]\n                if res >= limit {\n                    break\n                }\n                sphenic = append(sphenic, res)\n            }\n        }\n    }\n    sort.Ints(sphenic)\n    ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })\n    rcu.PrintTable(sphenic[:ix], 15, 3, false)\n    fmt.Println(\"\\nSphenic triplets less than 10,000:\")\n    var triplets [][3]int\n    for i := 0; i < len(sphenic)-2; i++ {\n        s := sphenic[i]\n        if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {\n            triplets = append(triplets, [3]int{s, s + 1, s + 2})\n        }\n    }\n    ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })\n    for i := 0; i < ix; i++ {\n        fmt.Printf(\"%4d \", triplets[i])\n        if (i+1)%3 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThere are %s sphenic numbers less than 1,000,000.\\n\", rcu.Commatize(len(sphenic)))\n    fmt.Printf(\"There are %s sphenic triplets less than 1,000,000.\\n\", rcu.Commatize(len(triplets)))\n    s := sphenic[199999]\n    pf := rcu.PrimeFactors(s)\n    fmt.Printf(\"The 200,000th sphenic number is %s (%d*%d*%d).\\n\", rcu.Commatize(s), pf[0], pf[1], pf[2])\n    fmt.Printf(\"The 5,000th sphenic triplet is %v.\\n.\", triplets[4999])\n}\n", "Java": "import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SphenicNumbers {\n    public static void main(String[] args) {\n        final int limit = 1000000;\n        final int imax = limit / 6;\n        boolean[] sieve = primeSieve(imax + 1);\n        boolean[] sphenic = new boolean[limit + 1];\n        for (int i = 0; i <= imax; ++i) {\n            if (!sieve[i])\n                continue;\n            int jmax = Math.min(imax, limit / (i * i));\n            if (jmax <= i)\n                break;\n            for (int j = i + 1; j <= jmax; ++j) {\n                if (!sieve[j])\n                    continue;\n                int p = i * j;\n                int kmax = Math.min(imax, limit / p);\n                if (kmax <= j)\n                    break;\n                for (int k = j + 1; k <= kmax; ++k) {\n                    if (!sieve[k])\n                        continue;\n                    assert(p * k <= limit);\n                    sphenic[p * k] = true;\n                }\n            }\n        }\n    \n        System.out.println(\"Sphenic numbers < 1000:\");\n        for (int i = 0, n = 0; i < 1000; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++n;\n            System.out.printf(\"%3d%c\", i, n % 15 == 0 ? '\\n' : ' ');\n        }\n    \n        System.out.println(\"\\nSphenic triplets < 10,000:\");\n        for (int i = 0, n = 0; i < 10000; ++i) {\n            if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n                ++n;\n                System.out.printf(\"(%d, %d, %d)%c\",\n                                  i - 2, i - 1, i, n % 3 == 0 ? '\\n' : ' ');\n            }\n        }\n    \n        int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n        for (int i = 0; i < limit; ++i) {\n            if (!sphenic[i])\n                continue;\n            ++count;\n            if (count == 200000)\n                s200000 = i;\n            if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n                ++triplets;\n                if (triplets == 5000)\n                    t5000 = i;\n            }\n        }\n    \n        System.out.printf(\"\\nNumber of sphenic numbers < 1,000,000: %d\\n\", count);\n        System.out.printf(\"Number of sphenic triplets < 1,000,000: %d\\n\", triplets);\n    \n        List<Integer> factors = primeFactors(s200000);\n        assert(factors.size() == 3);\n        System.out.printf(\"The 200,000th sphenic number: %d = %d * %d * %d\\n\",\n                          s200000, factors.get(0), factors.get(1),\n                          factors.get(2));\n        System.out.printf(\"The 5,000th sphenic triplet: (%d, %d, %d)\\n\",\n                          t5000 - 2, t5000 - 1, t5000);\n    }\n\n    private static boolean[] primeSieve(int limit) {\n        boolean[] sieve = new boolean[limit];\n        Arrays.fill(sieve, true);\n        if (limit > 0)\n            sieve[0] = false;\n        if (limit > 1)\n            sieve[1] = false;\n        for (int i = 4; i < limit; i += 2)\n            sieve[i] = false;\n        for (int p = 3, sq = 9; sq < limit; p += 2) {\n            if (sieve[p]) {\n                for (int q = sq; q < limit; q += p << 1)\n                    sieve[q] = false;\n            }\n            sq += (p + 1) << 2;\n        }\n        return sieve;\n    }\n    \n    private static List<Integer> primeFactors(int n) {\n        List<Integer> factors = new ArrayList<>();\n        if (n > 1 && (n & 1) == 0) {\n            factors.add(2);\n            while ((n & 1) == 0)\n                n >>= 1;\n        }\n        for (int p = 3; p * p <= n; p += 2) {\n            if (n % p == 0) {\n                factors.add(p);\n                while (n % p == 0)\n                    n /= p;\n            }\n        }\n        if (n > 1)\n            factors.add(n);\n        return factors;\n    }\n}\n"}
{"id": 59859, "name": "Find duplicate files", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"crypto/md5\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"path/filepath\"\n    \"sort\"\n    \"time\"\n)\n\ntype fileData struct {\n    filePath string\n    info     os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc checksum(filePath string) hash {\n    bytes, err := ioutil.ReadFile(filePath)\n    check(err)\n    return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n    var dups [][2]fileData\n    m := make(map[hash]fileData)\n    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        if !info.IsDir() && info.Size() >= minSize {\n            h := checksum(path)\n            fd, ok := m[h]\n            fd2 := fileData{path, info}\n            if !ok {\n                m[h] = fd2\n            } else {\n                dups = append(dups, [2]fileData{fd, fd2})\n            }\n        }\n        return nil\n    })\n    check(werr)\n    return dups\n}\n\nfunc main() {\n    dups := findDuplicates(\".\", 1)\n    fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n    fmt.Println(\"File name                 Size      Date last modified\")\n    fmt.Println(\"==========================================================\")\n    sort.Slice(dups, func(i, j int) bool {\n        return dups[i][0].info.Size() > dups[j][0].info.Size() \n    })\n    for _, dup := range dups {\n        for i := 0; i < 2; i++ {\n            d := dup[i]\n            fmt.Printf(\"%-20s  %8d    %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n        }\n        fmt.Println()\n    }\n}\n", "Java": "import java.io.*;\nimport java.nio.*;\nimport java.nio.file.*;\nimport java.nio.file.attribute.*;\nimport java.security.*;\nimport java.util.*;\n\npublic class DuplicateFiles {\n    public static void main(String[] args) {\n        if (args.length != 2) {\n            System.err.println(\"Directory name and minimum file size are required.\");\n            System.exit(1);\n        }\n        try {\n            findDuplicateFiles(args[0], Long.parseLong(args[1]));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void findDuplicateFiles(String directory, long minimumSize)\n        throws IOException, NoSuchAlgorithmException {\n        System.out.println(\"Directory: '\" + directory + \"', minimum size: \" + minimumSize + \" bytes.\");\n        Path path = FileSystems.getDefault().getPath(directory);\n        FileVisitor visitor = new FileVisitor(path, minimumSize);\n        Files.walkFileTree(path, visitor);\n        System.out.println(\"The following sets of files have the same size and checksum:\");\n        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {\n            Map<Object, List<String>> map = e.getValue();\n            if (!containsDuplicates(map))\n                continue;\n            List<List<String>> fileSets = new ArrayList<>(map.values());\n            for (List<String> files : fileSets)\n                Collections.sort(files);\n            Collections.sort(fileSets, new StringListComparator());\n            FileKey key = e.getKey();\n            System.out.println();\n            System.out.println(\"Size: \" + key.size_ + \" bytes\");\n            for (List<String> files : fileSets) {\n                for (int i = 0, n = files.size(); i < n; ++i) {\n                    if (i > 0)\n                        System.out.print(\" = \");\n                    System.out.print(files.get(i));\n                }\n                System.out.println();\n            }\n        }\n    }\n\n    private static class StringListComparator implements Comparator<List<String>> {\n        public int compare(List<String> a, List<String> b) {\n            int len1 = a.size(), len2 = b.size();\n            for (int i = 0; i < len1 && i < len2; ++i) {\n                int c = a.get(i).compareTo(b.get(i));\n                if (c != 0)\n                    return c;\n            }\n            return Integer.compare(len1, len2);\n        }\n    }\n\n    private static boolean containsDuplicates(Map<Object, List<String>> map) {\n        if (map.size() > 1)\n            return true;\n        for (List<String> files : map.values()) {\n            if (files.size() > 1)\n                return true;\n        }\n        return false;\n    }\n\n    private static class FileVisitor extends SimpleFileVisitor<Path> {\n        private MessageDigest digest_;\n        private Path directory_;\n        private long minimumSize_;\n        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();\n\n        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {\n            directory_ = directory;\n            minimumSize_ = minimumSize;\n            digest_ = MessageDigest.getInstance(\"MD5\");\n        }\n\n        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n            if (attrs.size() >= minimumSize_) {\n                FileKey key = new FileKey(file, attrs, getMD5Sum(file));\n                Map<Object, List<String>> map = fileMap_.get(key);\n                if (map == null)\n                    fileMap_.put(key, map = new HashMap<>());\n                List<String> files = map.get(attrs.fileKey());\n                if (files == null)\n                    map.put(attrs.fileKey(), files = new ArrayList<>());\n                Path relative = directory_.relativize(file);\n                files.add(relative.toString());\n            }\n            return FileVisitResult.CONTINUE;\n        }\n\n        private byte[] getMD5Sum(Path file) throws IOException {\n            digest_.reset();\n            try (InputStream in = new FileInputStream(file.toString())) {\n                byte[] buffer = new byte[8192];\n                int bytes;\n                while ((bytes = in.read(buffer)) != -1) {\n                    digest_.update(buffer, 0, bytes);\n                }\n            }\n            return digest_.digest();\n        }\n    }\n\n    private static class FileKey implements Comparable<FileKey> {\n        private byte[] hash_;\n        private long size_;\n\n        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {\n            size_ = attrs.size();\n            hash_ = hash;\n        }\n\n        public int compareTo(FileKey other) {\n            int c = Long.compare(other.size_, size_);\n            if (c == 0)\n                c = hashCompare(hash_, other.hash_);\n            return c;\n        }\n    }\n\n    private static int hashCompare(byte[] a, byte[] b) {\n        int len1 = a.length, len2 = b.length;\n        for (int i = 0; i < len1 && i < len2; ++i) {\n            int c = Byte.compare(a[i], b[i]);\n            if (c != 0)\n                return c;\n        }\n        return Integer.compare(len1, len2);\n    }\n}\n"}
{"id": 59860, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59861, "name": "Solve a Holy Knight's tour", "Go": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n    {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx    \" +\n    \" x xx   \" +\n    \" xxxxxxx\" +\n    \"xxx  x x\" +\n    \"x x  xxx\" +\n    \"sxxxxxx \" +\n    \"  xx x  \" +\n    \"   xxx  \"\n\nvar board2 = \".....s.x.....\" +\n    \".....x.x.....\" +\n    \"....xxxxx....\" +\n    \".....xxx.....\" +\n    \"..x..x.x..x..\" +\n    \"xxxxx...xxxxx\" +\n    \"..xx.....xx..\" +\n    \"xxxxx...xxxxx\" +\n    \"..x..x.x..x..\" +\n    \".....xxx.....\" +\n    \"....xxxxx....\" +\n    \".....x.x.....\" +\n    \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n    if idx > cnt {\n        return true\n    }\n    for i := 0; i < len(moves); i++ {\n        x := sx + moves[i][0]\n        y := sy + moves[i][1]\n        if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n            pz[x][y] = idx\n            if solve(pz, sz, x, y, idx+1, cnt) {\n                return true\n            }\n            pz[x][y] = 0\n        }\n    }\n    return false\n}\n\nfunc findSolution(b string, sz int) {\n    pz := make([][]int, sz)\n    for i := 0; i < sz; i++ {\n        pz[i] = make([]int, sz)\n        for j := 0; j < sz; j++ {\n            pz[i][j] = -1\n        }\n    }\n    var x, y, idx, cnt int\n    for j := 0; j < sz; j++ {\n        for i := 0; i < sz; i++ {\n            switch b[idx] {\n            case 'x':\n                pz[i][j] = 0\n                cnt++\n            case 's':\n                pz[i][j] = 1\n                cnt++\n                x, y = i, j\n            }\n            idx++\n        }\n    }\n\n    if solve(pz, sz, x, y, 2, cnt) {\n        for j := 0; j < sz; j++ {\n            for i := 0; i < sz; i++ {\n                if pz[i][j] != -1 {\n                    fmt.Printf(\"%02d  \", pz[i][j])\n                } else {\n                    fmt.Print(\"--  \")\n                }\n            }\n            fmt.Println()\n        }\n    } else {\n        fmt.Println(\"Cannot solve this puzzle!\")\n    }\n}\n\nfunc main() {\n    findSolution(board1, 8)\n    fmt.Println()\n    findSolution(board2, 13)\n}\n", "Java": "import java.util.*;\n\npublic class HolyKnightsTour {\n\n    final static String[] board = {\n        \" xxx    \",\n        \" x xx   \",\n        \" xxxxxxx\",\n        \"xxx  x x\",\n        \"x x  xxx\",\n        \"1xxxxxx \",\n        \"  xx x  \",\n        \"   xxx  \"};\n\n    private final static int base = 12;\n    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},\n    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};\n    private static int[][] grid;\n    private static int total = 2;\n\n    public static void main(String[] args) {\n        int row = 0, col = 0;\n\n        grid = new int[base][base];\n\n        for (int r = 0; r < base; r++) {\n            Arrays.fill(grid[r], -1);\n            for (int c = 2; c < base - 2; c++) {\n                if (r >= 2 && r < base - 2) {\n                    if (board[r - 2].charAt(c - 2) == 'x') {\n                        grid[r][c] = 0;\n                        total++;\n                    }\n                    if (board[r - 2].charAt(c - 2) == '1') {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n        }\n\n        grid[row][col] = 1;\n\n        if (solve(row, col, 2))\n            printResult();\n    }\n\n    private static boolean solve(int r, int c, int count) {\n        if (count == total)\n            return true;\n\n        List<int[]> nbrs = neighbors(r, c);\n\n        if (nbrs.isEmpty() && count != total)\n            return false;\n\n        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);\n\n        for (int[] nb : nbrs) {\n            r = nb[0];\n            c = nb[1];\n            grid[r][c] = count;\n            if (solve(r, c, count + 1))\n                return true;\n            grid[r][c] = 0;\n        }\n\n        return false;\n    }\n\n    private static List<int[]> neighbors(int r, int c) {\n        List<int[]> nbrs = new ArrayList<>();\n\n        for (int[] m : moves) {\n            int x = m[0];\n            int y = m[1];\n            if (grid[r + y][c + x] == 0) {\n                int num = countNeighbors(r + y, c + x) - 1;\n                nbrs.add(new int[]{r + y, c + x, num});\n            }\n        }\n        return nbrs;\n    }\n\n    private static int countNeighbors(int r, int c) {\n        int num = 0;\n        for (int[] m : moves)\n            if (grid[r + m[1]][c + m[0]] == 0)\n                num++;\n        return num;\n    }\n\n    private static void printResult() {\n        for (int[] row : grid) {\n            for (int i : row) {\n                if (i == -1)\n                    System.out.printf(\"%2s \", ' ');\n                else\n                    System.out.printf(\"%2d \", i);\n            }\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59862, "name": "Order disjoint list items", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype indexSort struct {\n\tval sort.Interface\n\tind []int\n}\n\nfunc (s indexSort) Len() int           { return len(s.ind) }\nfunc (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }\nfunc (s indexSort) Swap(i, j int) {\n\ts.val.Swap(s.ind[i], s.ind[j])\n\ts.ind[i], s.ind[j] = s.ind[j], s.ind[i]\n}\n\nfunc disjointSliceSort(m, n []string) []string {\n\ts := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}\n\tused := make(map[int]bool)\n\tfor _, nw := range n {\n\t\tfor i, mw := range m {\n\t\t\tif used[i] || mw != nw {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tused[i] = true\n\t\t\ts.ind = append(s.ind, i)\n\t\t\tbreak\n\t\t}\n\t}\n\tsort.Sort(s)\n\treturn s.val.(sort.StringSlice)\n}\n\nfunc disjointStringSort(m, n string) string {\n\treturn strings.Join(\n\t\tdisjointSliceSort(strings.Fields(m), strings.Fields(n)), \" \")\n}\n\nfunc main() {\n\tfor _, data := range []struct{ m, n string }{\n\t\t{\"the cat sat on the mat\", \"mat cat\"},\n\t\t{\"the cat sat on the mat\", \"cat mat\"},\n\t\t{\"A B C A B C A B C\", \"C A C A\"},\n\t\t{\"A B C A B D A B E\", \"E A D A\"},\n\t\t{\"A B\", \"B\"},\n\t\t{\"A B\", \"B A\"},\n\t\t{\"A B B A\", \"B A\"},\n\t} {\n\t\tmp := disjointStringSort(data.m, data.n)\n\t\tfmt.Printf(\"%s → %s » %s\\n\", data.m, data.n, mp)\n\t}\n\n}\n", "Java": "import java.util.Arrays;\nimport java.util.BitSet;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class OrderDisjointItems {\n\n    public static void main(String[] args) {\n        final String[][] MNs = {{\"the cat sat on the mat\", \"mat cat\"},\n        {\"the cat sat on the mat\", \"cat mat\"},\n        {\"A B C A B C A B C\", \"C A C A\"}, {\"A B C A B D A B E\", \"E A D A\"},\n        {\"A B\", \"B\"}, {\"A B\", \"B A\"}, {\"A B B A\", \"B A\"}, {\"X X Y\", \"X\"}};\n\n        for (String[] a : MNs) {\n            String[] r = orderDisjointItems(a[0].split(\" \"), a[1].split(\" \"));\n            System.out.printf(\"%s | %s -> %s%n\", a[0], a[1], Arrays.toString(r));\n        }\n    }\n\n    \n    static String[] orderDisjointItems(String[] m, String[] n) {\n        for (String e : n) {\n            int idx = ArrayUtils.indexOf(m, e);\n            if (idx != -1)\n                m[idx] = null;\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (m[i] == null)\n                m[i] = n[j++];\n        }\n        return m;\n    }\n\n    \n    static String[] orderDisjointItems2(String[] m, String[] n) {\n        BitSet bitSet = new BitSet(m.length);\n        for (String e : n) {\n            int idx = -1;\n            do {\n                idx = ArrayUtils.indexOf(m, e, idx + 1);\n            } while (idx != -1 && bitSet.get(idx));\n            if (idx != -1)\n                bitSet.set(idx);\n        }\n        for (int i = 0, j = 0; i < m.length; i++) {\n            if (bitSet.get(i))\n                m[i] = n[j++];\n        }\n        return m;\n    }\n}\n"}
{"id": 59863, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 59864, "name": "Here document", "Go": "var m = `    leading spaces\n\nand blank lines`\n", "Java": "package rosettacode.heredoc;\npublic class MainApp {\n\tpublic static void main(String[] args) {\n\t\tString hereDoc = \"\"\"\n\t\t\t\tThis is a multiline string.\n\t\t\t\tIt includes all of this text,\n\t\t\t\tbut on separate lines in the code.\n\t\t\t\t \"\"\";\n\t\tSystem.out.println(hereDoc);\n\t}\n}\n"}
{"id": 59865, "name": "Hash join", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    tableA := []struct {\n        value int\n        key   string\n    }{\n        {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n        {28, \"Alan\"},\n    }\n    tableB := []struct {\n        key   string\n        value string\n    }{\n        {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n    }\n    \n    h := map[string][]int{}\n    for i, r := range tableA {\n        h[r.key] = append(h[r.key], i)\n    }\n    \n    for _, x := range tableB {\n        for _, a := range h[x.key] {\n            fmt.Println(tableA[a], x)\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 59866, "name": "Ramanujan primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n"}
{"id": 59867, "name": "Ramanujan primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nvar count []int\n\nfunc primeCounter(limit int) {\n    count = make([]int, limit)\n    for i := 0; i < limit; i++ {\n        count[i] = 1\n    }\n    if limit > 0 {\n        count[0] = 0\n    }\n    if limit > 1 {\n        count[1] = 0\n    }\n    for i := 4; i < limit; i += 2 {\n        count[i] = 0\n    }\n    for p, sq := 3, 9; sq < limit; p += 2 {\n        if count[p] != 0 {\n            for q := sq; q < limit; q += p << 1 {\n                count[q] = 0\n            }\n        }\n        sq += (p + 1) << 2\n    }\n    sum := 0\n    for i := 0; i < limit; i++ {\n        sum += count[i]\n        count[i] = sum\n    }\n}\n\nfunc primeCount(n int) int {\n    if n < 1 {\n        return 0\n    }\n    return count[n]\n}\n\nfunc ramanujanMax(n int) int {\n    fn := float64(n)\n    return int(math.Ceil(4 * fn * math.Log(4*fn)))\n}\n\nfunc ramanujanPrime(n int) int {\n    if n == 1 {\n        return 2\n    }\n    for i := ramanujanMax(n); i >= 2*n; i-- {\n        if i%2 == 1 {\n            continue\n        }\n        if primeCount(i)-primeCount(i/2) < n {\n            return i + 1\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    start := time.Now()\n    primeCounter(1 + ramanujanMax(1e6))\n    fmt.Println(\"The first 100 Ramanujan primes are:\")\n    rams := make([]int, 100)\n    for n := 0; n < 100; n++ {\n        rams[n] = ramanujanPrime(n + 1)\n    }\n    for i, r := range rams {\n        fmt.Printf(\"%5s \", rcu.Commatize(r))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Printf(\"\\nThe 1,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(1000)))\n\n    fmt.Printf(\"\\nThe 10,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(10000)))\n\n    fmt.Printf(\"\\nThe 100,000th Ramanujan prime is %6s\\n\", rcu.Commatize(ramanujanPrime(100000)))\n\n    fmt.Printf(\"\\nThe 1,000,000th Ramanujan prime is %7s\\n\", rcu.Commatize(ramanujanPrime(1000000)))\n\n    fmt.Println(\"\\nTook\", time.Since(start))\n}\n", "Java": "import java.util.Arrays;\n\npublic class RamanujanPrimes {\n    public static void main(String[] args) {\n        long start = System.nanoTime();\n        System.out.println(\"First 100 Ramanujan primes:\");\n        PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000));\n        for (int i = 1; i <= 100; ++i) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"%,5d%c\", p, i % 10 == 0 ? '\\n' : ' ');\n        }\n        System.out.println();\n        for (int i = 1000; i <= 100000; i *= 10) {\n            int p = ramanujanPrime(pc, i);\n            System.out.printf(\"The %,dth Ramanujan prime is %,d.\\n\", i, p);\n        }\n        long end = System.nanoTime();\n        System.out.printf(\"\\nElapsed time: %.1f milliseconds\\n\", (end - start) / 1e6);\n    }\n\n    private static int ramanujanMax(int n) {\n        return (int)Math.ceil(4 * n * Math.log(4 * n));\n    }\n\n    private static int ramanujanPrime(PrimeCounter pc, int n) {\n        for (int i = ramanujanMax(n); i >= 0; --i) {\n            if (pc.primeCount(i) - pc.primeCount(i / 2) < n)\n                return i + 1;\n        }\n        return 0;\n    }\n\n    private static class PrimeCounter {\n        private PrimeCounter(int limit) {\n            count = new int[limit];\n            Arrays.fill(count, 1);\n            if (limit > 0)\n                count[0] = 0;\n            if (limit > 1)\n                count[1] = 0;\n            for (int i = 4; i < limit; i += 2)\n                count[i] = 0;\n            for (int p = 3, sq = 9; sq < limit; p += 2) {\n                if (count[p] != 0) {\n                    for (int q = sq; q < limit; q += p << 1)\n                        count[q] = 0;\n                }\n                sq += (p + 1) << 2;\n            }\n            Arrays.parallelPrefix(count, (x, y) -> x + y);\n        }\n\n        private int primeCount(int n) {\n            return n < 1 ? 0 : count[n];\n        }\n\n        private int[] count;\n    }\n}\n"}
{"id": 59868, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 59869, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 59870, "name": "Sierpinski 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)\n\nvar cx, cy, h float64\n\nfunc lineTo(newX, newY float64) {\n    dc.LineTo(newX-width/2+h, height-newY+2*h)\n    cx, cy = newX, newY\n}\n\nfunc lineN() { lineTo(cx, cy-2*h) }\nfunc lineS() { lineTo(cx, cy+2*h) }\nfunc lineE() { lineTo(cx+2*h, cy) }\nfunc lineW() { lineTo(cx-2*h, cy) }\n\nfunc lineNW() { lineTo(cx-h, cy-h) }\nfunc lineNE() { lineTo(cx+h, cy-h) }\nfunc lineSE() { lineTo(cx+h, cy+h) }\nfunc lineSW() { lineTo(cx-h, cy+h) }\n\nfunc sierN(level int) {\n    if level == 1 {\n        lineNE()\n        lineN()\n        lineNW()\n    } else {\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n        lineN()\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n    }\n}\n\nfunc sierE(level int) {\n    if level == 1 {\n        lineSE()\n        lineE()\n        lineNE()\n    } else {\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n        lineE()\n        sierN(level - 1)\n        lineNE()\n        sierE(level - 1)\n    }\n}\n\nfunc sierS(level int) {\n    if level == 1 {\n        lineSW()\n        lineS()\n        lineSE()\n    } else {\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n        lineS()\n        sierE(level - 1)\n        lineSE()\n        sierS(level - 1)\n    }\n}\n\nfunc sierW(level int) {\n    if level == 1 {\n        lineNW()\n        lineW()\n        lineSW()\n    } else {\n        sierW(level - 1)\n        lineNW()\n        sierN(level - 1)\n        lineW()\n        sierS(level - 1)\n        lineSW()\n        sierW(level - 1)\n    }\n}\n\nfunc squareCurve(level int) {\n    sierN(level)\n    lineNE()\n    sierE(level)\n    lineSE()\n    sierS(level)\n    lineSW()\n    sierW(level)\n    lineNW()\n    lineNE() \n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    level := 5\n    cx, cy = width/2, height\n    h = cx / math.Pow(2, float64(level+1))\n    squareCurve(level)\n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_curve.png\")\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_curve.svg\"))) {\n            SierpinskiCurve s = new SierpinskiCurve(writer);\n            s.currentAngle = 45;\n            s.currentX = 5;\n            s.currentY = 10;\n            s.lineLength = 7;\n            s.begin(545);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiCurve(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                case 'G':\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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F--XF--F--XF\";\n    private static final String PRODUCTION = \"XF+G+XF--F--XF+G+X\";\n    private static final int ANGLE = 45;\n}\n"}
{"id": 59871, "name": "Most frequent k chars distance", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype cf struct {\n    c rune\n    f int\n}\n\nfunc reverseStr(s string) string {\n    runes := []rune(s)\n    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n        runes[i], runes[j] = runes[j], runes[i]\n    }\n    return string(runes)\n}\n\nfunc indexOfCf(cfs []cf, r rune) int {\n    for i, cf := range cfs {\n        if cf.c == r {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc minOf(i, j int) int {\n    if i < j {\n        return i\n    }\n    return j\n}\n\nfunc mostFreqKHashing(input string, k int) string {\n    var cfs []cf\n    for _, r := range input {\n        ix := indexOfCf(cfs, r)\n        if ix >= 0 {\n            cfs[ix].f++\n        } else {\n            cfs = append(cfs, cf{r, 1})\n        }\n    }\n    sort.SliceStable(cfs, func(i, j int) bool {\n        return cfs[i].f > cfs[j].f \n    })\n    acc := \"\"\n    min := minOf(len(cfs), k)\n    for _, cf := range cfs[:min] {\n        acc += fmt.Sprintf(\"%c%c\", cf.c, cf.f)\n    }\n    return acc\n}\n\nfunc mostFreqKSimilarity(input1, input2 string) int {\n    similarity := 0\n    runes1, runes2 := []rune(input1), []rune(input2)\n    for i := 0; i < len(runes1); i += 2 {\n        for j := 0; j < len(runes2); j += 2 {\n            if runes1[i] == runes2[j] {\n                freq1, freq2 := runes1[i+1], runes2[j+1]\n                if freq1 != freq2 {\n                    continue \n                }\n                similarity += int(freq1)\n            }\n        }\n    }\n    return similarity\n}\n\nfunc mostFreqKSDF(input1, input2 string, k, maxDistance int) {\n    fmt.Println(\"input1 :\", input1)\n    fmt.Println(\"input2 :\", input2)\n    s1 := mostFreqKHashing(input1, k)\n    s2 := mostFreqKHashing(input2, k)\n    fmt.Printf(\"mfkh(input1, %d) = \", k)\n    for i, c := range s1 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    fmt.Printf(\"\\nmfkh(input2, %d) = \", k)\n    for i, c := range s2 {\n        if i%2 == 0 {\n            fmt.Printf(\"%c\", c)\n        } else {\n            fmt.Printf(\"%d\", c)\n        }\n    }\n    result := maxDistance - mostFreqKSimilarity(s1, s2)\n    fmt.Printf(\"\\nSDF(input1, input2, %d, %d) = %d\\n\\n\", k, maxDistance, result)\n}\n\nfunc main() {\n    pairs := [][2]string{\n        {\"research\", \"seeking\"},\n        {\"night\", \"nacht\"},\n        {\"my\", \"a\"},\n        {\"research\", \"research\"},\n        {\"aaaaabbbb\", \"ababababa\"},\n        {\"significant\", \"capabilities\"},\n    }\n    for _, pair := range pairs {\n        mostFreqKSDF(pair[0], pair[1], 2, 10)\n    }\n\n    s1 := \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\"\n    s2 := \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\"\n    mostFreqKSDF(s1, s2, 2, 100)\n    s1 = \"abracadabra12121212121abracadabra12121212121\"\n    s2 = reverseStr(s1)\n    mostFreqKSDF(s1, s2, 2, 100)\n}\n", "Java": "import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class SDF {\n\n    \n    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {\n\n        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();\n\n        for (char element : array) {\n            Integer count = countMap.get(element);\n            count = (count == null) ? 1 : count + 1;\n            countMap.put(element, count);\n        }\n\n        return countMap;\n    }\n    \n    \n    private static <K, V extends Comparable<? super V>>\n            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { \n\tList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());\n\t\n\tCollections.sort(list, new Comparator<Map.Entry<K, V>>() {\n\t\tpublic int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n\t\t    return o2.getValue().compareTo(o1.getValue());\n\t\t}\n\t    });\n\n\t\n\t\n\tHashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();\n\tfor (Map.Entry<K, V> entry : list) {\n\t    sortedHashMap.put(entry.getKey(), entry.getValue());\n\t} \n\treturn sortedHashMap;\n    }\n    \n    public static String mostOcurrencesElement(char[] array, int k) {\n        HashMap<Character, Integer> countMap = countElementOcurrences(array);\n        System.out.println(countMap);\n        Map<Character, Integer> map = descendingSortByValues(countMap); \n        System.out.println(map);\n        int i = 0;\n        String output = \"\";\n        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {\n\t    if (i++ >= k)\n\t\tbreak;\n            output += \"\" + pairs.getKey() + pairs.getValue();\n        }\n        return output;\n    }\n    \n    public static int getDiff(String str1, String str2, int limit) {\n        int similarity = 0;\n\tint k = 0;\n\tfor (int i = 0; i < str1.length() ; i = k) {\n\t    k ++;\n\t    if (Character.isLetter(str1.charAt(i))) {\n\t\tint pos = str2.indexOf(str1.charAt(i));\n\t\t\t\t\n\t\tif (pos >= 0) {\t\n\t\t    String digitStr1 = \"\";\n\t\t    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {\n\t\t\tdigitStr1 += str1.charAt(k);\n\t\t\tk++;\n\t\t    }\n\t\t\t\t\t\n\t\t    int k2 = pos+1;\n\t\t    String digitStr2 = \"\";\n\t\t    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {\n\t\t\tdigitStr2 += str2.charAt(k2);\n\t\t\tk2++;\n\t\t    }\n\t\t\t\t\t\n\t\t    similarity += Integer.parseInt(digitStr2)\n\t\t\t+ Integer.parseInt(digitStr1);\n\t\t\t\t\t\n\t\t} \n\t    }\n\t}\n\treturn Math.abs(limit - similarity);\n    }\n    \n    public static int SDFfunc(String str1, String str2, int limit) {\n        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);\n    }\n\n    public static void main(String[] args) {\n        String input1 = \"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV\";\n        String input2 = \"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG\";\n        System.out.println(SDF.SDFfunc(input1,input2,100));\n\n    }\n\n}\n"}
{"id": 59872, "name": "Text completion", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n)\n\nfunc levenshtein(s, t string) int {\n    d := make([][]int, len(s)+1)\n    for i := range d {\n        d[i] = make([]int, len(t)+1)\n    }\n    for i := range d {\n        d[i][0] = i\n    }\n    for j := range d[0] {\n        d[0][j] = j\n    }\n    for j := 1; j <= len(t); j++ {\n        for i := 1; i <= len(s); i++ {\n            if s[i-1] == t[j-1] {\n                d[i][j] = d[i-1][j-1]\n            } else {\n                min := d[i-1][j]\n                if d[i][j-1] < min {\n                    min = d[i][j-1]\n                }\n                if d[i-1][j-1] < min {\n                    min = d[i-1][j-1]\n                }\n                d[i][j] = min + 1\n            }\n        }\n\n    }\n    return d[len(s)][len(t)]\n}\n\nfunc main() {\n    search := \"complition\"\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    words := bytes.Fields(b)\n    var lev [4][]string\n    for _, word := range words {\n        s := string(word)\n        ld := levenshtein(search, s)\n        if ld < 4 {\n            lev[ld] = append(lev[ld], s)\n        }\n    }\n    fmt.Printf(\"Input word: %s\\n\\n\", search)\n    for i := 1; i < 4; i++ {\n        length := float64(len(search))\n        similarity := (length - float64(i)) * 100 / length\n        fmt.Printf(\"Words which are %4.1f%% similar:\\n\", similarity)\n        fmt.Println(lev[i])\n        fmt.Println()\n    }\n}\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\n\n\npublic class textCompletionConcept {\n    public static int correct = 0;\n    public static ArrayList<String> listed = new ArrayList<>();\n    public static void main(String[]args) throws IOException, URISyntaxException {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Input word: \");\n        String errorRode = input.next();\n        File file = new File(new \n        File(textCompletionConcept.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath() + File.separator + \"words.txt\");\n        Scanner reader = new Scanner(file);\n        while(reader.hasNext()){\n            double percent;\n            String compareToThis = reader.nextLine();\n                    char[] s1 = errorRode.toCharArray();\n                    char[] s2 = compareToThis.toCharArray();\n                    int maxlen = Math.min(s1.length, s2.length);\n                    for (int index = 0; index < maxlen; index++) {\n                        String x = String.valueOf(s1[index]);\n                        String y = String.valueOf(s2[index]);\n                        if (x.equals(y)) {\n                            correct++;\n                        }\n                    }\n                    double length = Math.max(s1.length, s2.length);\n                    percent = correct / length;\n                    percent *= 100;\n                    boolean perfect = false;\n                    if (percent >= 80 && compareToThis.charAt(0) == errorRode.charAt(0)) {\n                        if(String.valueOf(percent).equals(\"100.00\")){\n                            perfect = true;\n                        }\n                        String addtoit = compareToThis + \" : \" + String.format(\"%.2f\", percent) + \"% similar.\";\n                        listed.add(addtoit);\n                    }\n                    if(compareToThis.contains(errorRode) && !perfect && errorRode.length() * 2 > compareToThis.length()){\n                        String addtoit = compareToThis + \" : 80.00% similar.\";\n                        listed.add(addtoit);\n                    }\n            correct = 0;\n        }\n\n        for(String x : listed){\n            if(x.contains(\"100.00% similar.\")){\n                System.out.println(x);\n                listed.clear();\n                break;\n            }\n        }\n\n        for(String x : listed){\n            System.out.println(x);\n        }\n    }\n}\n"}
{"id": 59873, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 59874, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 59875, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 59876, "name": "Pig the dice game_Player", "Go": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID   int\n\tMessageID  int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer        PlayerID\n\t\tturnCount     int\n\t\tturnRollCount int\n\t\tturnScore     int\n\t\tlastRoll      int\n\t\tscores        [2]int\n\t\tverbose       bool\n\t}\n)\n\nconst (\n\t\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t\n\tplayer1  = PlayerID(0)\n\tplayer2  = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t\n\tmaxScore = 100\n\t\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\"    Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\"    Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\"    %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\"    Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n\nfunc main() {\n\t\n\trand.Seed(time.Now().UnixNano())\n\n\t\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}\n", "Java": "import java.util.Scanner;\n\npublic class Pigdice {\n\n\tpublic static void main(String[] args) {\n\t\tScanner scan = new Scanner(System.in);\n\t\tint players = 0;\n\t\t\n\t\t\n\t\twhile(true) {\n\t\t\t\n\t\t\tSystem.out.println(\"Hello, welcome to Pig Dice the game! How many players? \");\n\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\tif(nextInt > 0) {\n\t\t\t\t\tplayers = nextInt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.out.println(\"That wasn't an integer. Try again. \\n\");\n\t\t\t\tscan.next();\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Alright, starting with \" + players + \" players. \\n\");\n\t\t\n\t\t\n\t\tplay(players, scan);\n\t\t\n\t\tscan.close();\n\t}\n\t\n\tpublic static void play(int group, Scanner scan) {\n\t\t\n\t\tfinal int STRATEGIES = 5;\n\t\t\n\t\t\n\t\tDice dice = new Dice();\n\t\t\n\t\t\n\t\tPlayer[] players = new Player[group];\n\t\tfor(int count = 0; count < group; count++) {\n\t\t\tplayers[count] = new Player(count);\n\t\t\tSystem.out.println(\"Player \" + players[count].getNumber() + \"  is alive! \");\n\t\t}\n\t\t\n\t\t\n\t\tSystem.out.println(\"Each strategy is numbered 0 - \" + (STRATEGIES - 1) + \". They are as follows: \");\n\t\tSystem.out.println(\">> Enter '0' for a human player. \");\n\t\tSystem.out.println(\">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.\");\n\t\tSystem.out.println(\">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. \");\n\t\tSystem.out.println(\">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. \");\n\t\tSystem.out.println(\">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. \");\n\t\t\n\t\t\n\t\tfor(Player player : players) {\n\t\t\tSystem.out.println(\"\\nWhat strategy would you like player \" + player.getNumber() + \" to use? \");\n\n\t\t\t\n\t\t\twhile(true) {\n\t\t\t\tif(scan.hasNextInt()) {\n\t\t\t\t\tint nextInt = scan.nextInt();\n\t\t\t\t\tif (nextInt < Strategy.STRATEGIES.length) {\n\t\t\t\t\t\tplayer.setStrategy(Strategy.STRATEGIES[nextInt]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(\"That wasn't an option. Try again. \");\n\t\t\t\t\tscan.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tint max = 0;\n\t\twhile(max < 100) {\n\t\t\t\n\t\t\t\n\t\t\tfor(Player player : players) {\n\t\t\t\tSystem.out.println(\">> Beginning Player \" + player.getNumber() + \"'s turn. \");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.setMax(max);\n\t\t\t\twhile(true) {\n\t\t\t\t\tMove choice = player.choose();\n\t\t\t\t\tif(choice == Move.ROLL) {\n\t\t\t\t\t\tint roll = dice.roll();\n\t\t\t\t\t\tSystem.out.println(\"   A \" + roll + \" was rolled. \");\n\t\t\t\t\t\tplayer.setTurnPoints(player.getTurnPoints() + roll);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.incIter();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(roll == 1) {\n\t\t\t\t\t\t\tplayer.setTurnPoints(0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"   The player has held. \");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.addPoints(player.getTurnPoints());\n\t\t\t\tSystem.out.println(\"   Player \" + player.getNumber() + \"'s turn is now over. Their total is \" + player.getPoints() + \". \\n\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tplayer.resetIter();\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max < player.getPoints()) {\n\t\t\t\t\tmax = player.getPoints();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(max >= 100) {\n\t\t\t\t\tSystem.out.println(\"Player \" + player.getNumber() + \" wins with \" + max + \" points! End scores: \");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfor(Player p : players) {\n\t\t\t\t\t\tSystem.out.println(\"Player \" + p.getNumber() + \" had \" + p.getPoints() + \" points. \");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n}\n"}
{"id": 59877, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n"}
{"id": 59878, "name": "Lychrel numbers", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) \nvar ten = big.NewInt(10)\n\n\n\n\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"      Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\"                Lychrel seeds:\", seeds)\n\tfmt.Println(\"            Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\"          Lychrel palindromes:\", pals)\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class Lychrel {\n\n    static Map<BigInteger, Tuple> cache = new HashMap<>();\n\n    static class Tuple {\n        final Boolean flag;\n        final BigInteger bi;\n\n        Tuple(boolean f, BigInteger b) {\n            flag = f;\n            bi = b;\n        }\n    }\n\n    static BigInteger rev(BigInteger bi) {\n        String s = new StringBuilder(bi.toString()).reverse().toString();\n        return new BigInteger(s);\n    }\n\n    static Tuple lychrel(BigInteger n) {\n        Tuple res;\n        if ((res = cache.get(n)) != null)\n            return res;\n\n        BigInteger r = rev(n);\n        res = new Tuple(true, n);\n        List<BigInteger> seen = new ArrayList<>();\n\n        for (int i = 0; i < 500; i++) {\n            n = n.add(r);\n            r = rev(n);\n\n            if (n.equals(r)) {\n                res = new Tuple(false, BigInteger.ZERO);\n                break;\n            }\n\n            if (cache.containsKey(n)) {\n                res = cache.get(n);\n                break;\n            }\n\n            seen.add(n);\n        }\n\n        for (BigInteger bi : seen)\n            cache.put(bi, res);\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n\n        List<BigInteger> seeds = new ArrayList<>();\n        List<BigInteger> related = new ArrayList<>();\n        List<BigInteger> palin = new ArrayList<>();\n\n        for (int i = 1; i <= 10_000; i++) {\n            BigInteger n = BigInteger.valueOf(i);\n\n            Tuple t = lychrel(n);\n\n            if (!t.flag)\n                continue;\n\n            if (n.equals(t.bi))\n                seeds.add(t.bi);\n            else\n                related.add(t.bi);\n\n            if (n.equals(t.bi))\n                palin.add(t.bi);\n        }\n\n        System.out.printf(\"%d Lychrel seeds: %s%n\", seeds.size(), seeds);\n        System.out.printf(\"%d Lychrel related%n\", related.size());\n        System.out.printf(\"%d Lychrel palindromes: %s%n\", palin.size(), palin);\n    }\n}\n"}
{"id": 59879, "name": "Erdös-Selfridge categorization of primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nvar limit = int(math.Log(1e6) * 1e6 * 1.2) \nvar primes = rcu.Primes(limit)\n\nvar prevCats = make(map[int]int)\n\nfunc cat(p int) int {\n    if v, ok := prevCats[p]; ok {\n        return v\n    }\n    pf := rcu.PrimeFactors(p + 1)\n    all := true\n    for _, f := range pf {\n        if f != 2 && f != 3 {\n            all = false\n            break\n        }\n    }\n    if all {\n        return 1\n    }\n    if p > 2 {\n        len := len(pf)\n        for i := len - 1; i >= 1; i-- {\n            if pf[i-1] == pf[i] {\n                pf = append(pf[:i], pf[i+1:]...)\n            }\n        }\n    }\n    for c := 2; c <= 11; c++ {\n        all := true\n        for _, f := range pf {\n            if cat(f) >= c {\n                all = false\n                break\n            }\n        }\n        if all {\n            prevCats[p] = c\n            return c\n        }\n    }\n    return 12\n}\n\nfunc main() {\n    es := make([][]int, 12)\n    fmt.Println(\"First 200 primes:\\n\")\n    for _, p := range primes[0:200] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 6; c++ {\n        if len(es[c-1]) > 0 {\n            fmt.Println(\"Category\", c, \"\\b:\")\n            fmt.Println(es[c-1])\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"First million primes:\\n\")\n    for _, p := range primes[200:1e6] {\n        c := cat(p)\n        es[c-1] = append(es[c-1], p)\n    }\n    for c := 1; c <= 12; c++ {\n        e := es[c-1]\n        if len(e) > 0 {\n            format := \"Category %-2d: First = %7d  Last = %8d  Count = %6d\\n\"\n            fmt.Printf(format, c, e[0], e[len(e)-1], len(e))\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class ErdosSelfridge {\n    private int[] primes;\n    private int[] category;\n\n    public static void main(String[] args) {\n        ErdosSelfridge es = new ErdosSelfridge(1000000);\n\n        System.out.println(\"First 200 primes:\");\n        for (var e : es.getPrimesByCategory(200).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %d:\\n\", category);\n            for (int i = 0, n = primes.size(); i != n; ++i)\n                System.out.printf(\"%4d%c\", primes.get(i), (i + 1) % 15 == 0 ? '\\n' : ' ');\n            System.out.printf(\"\\n\\n\");\n        }\n\n        System.out.println(\"First 1,000,000 primes:\");\n        for (var e : es.getPrimesByCategory(1000000).entrySet()) {\n            int category = e.getKey();\n            List<Integer> primes = e.getValue();\n            System.out.printf(\"Category %2d: first = %7d  last = %8d  count = %d\\n\", category,\n                              primes.get(0), primes.get(primes.size() - 1), primes.size());\n        }\n    }\n\n    private ErdosSelfridge(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);\n        List<Integer> primeList = new ArrayList<>();\n        for (int i = 0; i < limit; ++i)\n            primeList.add(primeGen.nextPrime());\n        primes = new int[primeList.size()];\n        for (int i = 0; i < primes.length; ++i)\n            primes[i] = primeList.get(i);\n        category = new int[primes.length];\n    }\n\n    private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {\n        Map<Integer, List<Integer>> result = new TreeMap<>();\n        for (int i = 0; i < limit; ++i) {\n            var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());\n            p.add(primes[i]);\n        }\n        return result;\n    }\n\n    private int getCategory(int index) {\n        if (category[index] != 0)\n            return category[index];\n        int maxCategory = 0;\n        int n = primes[index] + 1;\n        for (int i = 0; n > 1; ++i) {\n            int p = primes[i];\n            if (p * p > n)\n                break;\n            int count = 0;\n            for (; n % p == 0; ++count)\n                n /= p;\n            if (count != 0) {\n                int category = (p <= 3) ? 1 : 1 + getCategory(i);\n                maxCategory = Math.max(maxCategory, category);\n            }\n        }\n        if (n > 1) {\n            int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));\n            maxCategory = Math.max(maxCategory, category);\n        }\n        category[index] = maxCategory;\n        return maxCategory;\n    }\n\n    private int getIndex(int prime) {\n       return Arrays.binarySearch(primes, prime);\n    }\n}\n"}
{"id": 59880, "name": "Sierpinski square curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n"}
{"id": 59881, "name": "Sierpinski square curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"github.com/trubitsyn/go-lindenmayer\"\n    \"log\"\n    \"math\"\n)\n\nconst twoPi = 2 * math.Pi\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n)\n\nvar cx, cy, h, theta float64\n\nfunc main() {\n    dc.SetRGB(0, 0, 1) \n    dc.Clear()\n    cx, cy = 10, height/2+5\n    h = 6\n    sys := lindenmayer.Lsystem{\n        Variables: []rune{'X'},\n        Constants: []rune{'F', '+', '-'},\n        Axiom:     \"F+XF+F+XF\",\n        Rules: []lindenmayer.Rule{\n            {\"X\", \"XF-F+F-XF+F+XF-F+F-X\"},\n        },\n        Angle: math.Pi / 2, \n    }\n    result := lindenmayer.Iterate(&sys, 5)\n    operations := map[rune]func(){\n        'F': func() {\n            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)\n            dc.LineTo(newX, newY)\n            cx, cy = newX, newY\n        },\n        '+': func() {\n            theta = math.Mod(theta+sys.Angle, twoPi)\n        },\n        '-': func() {\n            theta = math.Mod(theta-sys.Angle, twoPi)\n        },\n    }\n    if err := lindenmayer.Process(result, operations); err != nil {\n        log.Fatal(err)\n    }\n    \n    operations['+']()\n    operations['F']()\n\n    \n    dc.SetRGB255(255, 255, 0) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_square_curve.png\")\n}\n", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n"}
{"id": 59882, "name": "Powerful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 59883, "name": "Powerful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\nconst adj = 0.0001 \n\nvar primes = []uint64{\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n} \n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc isSquareFree(x uint64) bool {\n    for _, p := range primes {\n        p2 := p * p\n        if p2 > x {\n            break\n        }\n        if x%p2 == 0 {\n            return false\n        }\n    }\n    return true\n}\n\nfunc iroot(x, p uint64) uint64 {\n    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)\n}\n\nfunc ipow(x, p uint64) uint64 {\n    prod := uint64(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\nfunc powerful(n, k uint64) []uint64 {\n    set := make(map[uint64]bool)\n    var f func(m, r uint64) \n    f = func(m, r uint64) {\n        if r < k {\n            set[m] = true\n            return\n        }\n        for v := uint64(1); v <= iroot(n/m, r); v++ {\n            if r > k {\n                if !isSquareFree(v) || gcd(m, v) != 1 {\n                    continue\n                }\n            }\n            f(m*ipow(v, r), r-1)\n        }\n    }\n    f(1, (1<<k)-1)\n    list := make([]uint64, 0, len(set))\n    for key := range set {\n        list = append(list, key)\n    }\n    sort.Slice(list, func(i, j int) bool {\n        return list[i] < list[j]\n    })\n    return list\n}\n\nfunc main() {\n    power := uint64(10)\n    for k := uint64(2); k <= 10; k++ {\n        power *= 10\n        a := powerful(power, k)\n        le := len(a)\n        h, t := a[0:5], a[le-5:]\n        fmt.Printf(\"%d %2d-powerful numbers <= 10^%-2d: %v ... %v\\n\", le, k, k, h, t)\n    }\n    fmt.Println()\n    for k := uint64(2); k <= 10; k++ {\n        power := uint64(1)\n        var counts []int\n        for j := uint64(0); j < k+10; j++ {\n            a := powerful(power, k)\n            counts = append(counts, len(a))\n            power *= 10\n        }\n        j := k + 10\n        fmt.Printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\\n\", k, j, counts)\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class PowerfulNumbers {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Task:  For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            BigInteger max = BigInteger.valueOf(10).pow(k);\n            List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);\n            System.out.printf(\"There are %d %d-powerful numbers between 1 and %d.  %nList: %s%n\", powerfulNumbers.size(), k, max, getList(powerfulNumbers));\n        }\n        System.out.printf(\"%nTask:  For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n\");\n        for ( int k = 2 ; k <= 10 ; k++ ) {\n            List<Integer> powCount = new ArrayList<>();\n            for ( int j = 0 ; j < k+10 ; j++ ) {\n                BigInteger max = BigInteger.valueOf(10).pow(j);\n                powCount.add(countPowerFulNumbers(max, k));\n            }\n            System.out.printf(\"Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n\", k, k+9, powCount);\n        }\n        \n    }\n    \n    private static String getList(List<BigInteger> list) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(list.subList(0, 5).toString().replace(\"]\", \"\"));\n        sb.append(\" ... \");\n        sb.append(list.subList(list.size()-5, list.size()).toString().replace(\"[\", \"\"));\n        return sb.toString();\n    }\n\n    private static int countPowerFulNumbers(BigInteger max, int k) {\n        return potentialPowerful(max, k).size();\n    }\n\n    private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {\n        List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));\n        Collections.sort(powerfulNumbers);\n        return powerfulNumbers;\n    }\n\n    private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {\n        \n        int[] indexes = new int[k];\n        for ( int i = 0 ; i < k ; i++ ) {\n            indexes[i] = 1;\n        }\n\n        Set<BigInteger> powerful = new HashSet<>();\n        boolean foundPower = true;\n        while ( foundPower ) {\n            \n            boolean genPowerful = false;\n            for ( int index = 0 ; index < k ; index++ ) {\n                BigInteger power = BigInteger.ONE;\n                for ( int i = 0 ; i < k ; i++ ) {\n                    power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));\n                }\n                if ( power.compareTo(max) <= 0 ) {\n                    powerful.add(power);\n                    indexes[0] += 1;\n                    genPowerful = true;\n                    break;\n                }\n                else {\n                    indexes[index] = 1;\n                    if ( index < k-1 ) {\n                        indexes[index+1] += 1;\n                    }\n                }\n            }\n            if ( ! genPowerful ) {\n                foundPower = false;\n            }\n        }\n\n        return powerful;\n    }\n    \n}\n"}
{"id": 59884, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 59885, "name": "Polynomial synthetic division", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {\n    out := make([]*big.Rat, len(dividend))\n    for i, c := range dividend {\n        out[i] = new(big.Rat).Set(c)\n    }\n    for i := 0; i < len(dividend)-(len(divisor)-1); i++ {\n        out[i].Quo(out[i], divisor[0])\n        if coef := out[i]; coef.Sign() != 0 {\n            var a big.Rat\n            for j := 1; j < len(divisor); j++ {\n                out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))\n            }\n        }\n    }\n    separator := len(out) - (len(divisor) - 1)\n    return out[:separator], out[separator:]\n}\n\nfunc main() {\n    N := []*big.Rat{\n        big.NewRat(1, 1),\n        big.NewRat(-12, 1),\n        big.NewRat(0, 1),\n        big.NewRat(-42, 1)}\n    D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}\n    Q, R := div(N, D)\n    fmt.Printf(\"%v / %v = %v remainder %v\\n\", N, D, Q, R)\n}\n", "Java": "import java.util.Arrays;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        int[] N = {1, -12, 0, -42};\n        int[] D = {1, -3};\n\n        System.out.printf(\"%s / %s = %s\",\n                Arrays.toString(N),\n                Arrays.toString(D),\n                Arrays.deepToString(extendedSyntheticDivision(N, D)));\n    }\n\n    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {\n        int[] out = dividend.clone();\n        int normalizer = divisor[0];\n\n        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {\n            out[i] /= normalizer;\n\n            int coef = out[i];\n            if (coef != 0) {\n                for (int j = 1; j < divisor.length; j++)\n                    out[i + j] += -divisor[j] * coef;\n            }\n        }\n\n        int separator = out.length - (divisor.length - 1);\n\n        return new int[][]{\n            Arrays.copyOfRange(out, 0, separator),\n            Arrays.copyOfRange(out, separator, out.length)\n        };\n    }\n}\n"}
{"id": 59886, "name": "Odd words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    count := 0\n    fmt.Println(\"The odd words with length > 4 in\", wordList, \"are:\")\n    for _, word := range words {\n        rword := []rune(word) \n        if len(rword) > 8 {\n            var sb strings.Builder\n            for i := 0; i < len(rword); i += 2 {\n                sb.WriteRune(rword[i])\n            }\n            s := sb.String()\n            idx := sort.SearchStrings(words, s)      \n            if idx < len(words) && words[idx] == s { \n                count = count + 1\n                fmt.Printf(\"%2d: %-12s -> %s\\n\", count, word, s)\n            }\n        }\n    }\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class OddWords {\n    public static void main(String[] args) {\n        try {\n            Set<String> dictionary = new TreeSet<>();\n            final int minLength = 5;\n            String fileName = \"unixdict.txt\";\n            if (args.length != 0)\n                fileName = args[0];\n            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        dictionary.add(line);\n                }\n            }\n            StringBuilder word1 = new StringBuilder();\n            StringBuilder word2 = new StringBuilder();\n            List<StringPair> evenWords = new ArrayList<>();\n            List<StringPair> oddWords = new ArrayList<>();\n            for (String word : dictionary) {\n                int length = word.length();\n                if (length < minLength + 2 * (minLength/2))\n                    continue;\n                word1.setLength(0);\n                word2.setLength(0);\n                for (int i = 0; i < length; ++i) {\n                    if ((i & 1) == 0)\n                        word1.append(word.charAt(i));\n                    else\n                        word2.append(word.charAt(i));\n                }\n                String oddWord = word1.toString();\n                String evenWord = word2.toString();\n                if (dictionary.contains(oddWord))\n                    oddWords.add(new StringPair(word, oddWord));\n                if (dictionary.contains(evenWord))\n                    evenWords.add(new StringPair(word, evenWord));\n            }\n            System.out.println(\"Odd words:\");\n            printWords(oddWords);\n            System.out.println(\"\\nEven words:\");\n            printWords(evenWords);\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n\n    private static void printWords(List<StringPair> strings) {\n        int n = 1;\n        for (StringPair pair : strings) {\n            System.out.printf(\"%2d: %-14s%s\\n\", n++,\n                                    pair.string1, pair.string2);\n        }\n    }\n\n    private static class StringPair {\n        private String string1;\n        private String string2;\n        private StringPair(String s1, String s2) {\n            string1 = s1;\n            string2 = s2;\n        }\n    }\n}\n"}
{"id": 59887, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n"}
{"id": 59888, "name": "Ramanujan's constant", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/ALTree/bigfloat\"\n    \"math/big\"\n)\n\nconst (\n    prec = 256 \n    ps   = \"3.1415926535897932384626433832795028841971693993751058209749445923078164\"\n)\n\nfunc q(d int64) *big.Float {\n    pi, _ := new(big.Float).SetPrec(prec).SetString(ps)\n    t := new(big.Float).SetPrec(prec).SetInt64(d)\n    t.Sqrt(t)\n    t.Mul(pi, t)\n    return bigfloat.Exp(t)\n}\n\nfunc main() {\n    fmt.Println(\"Ramanujan's constant to 32 decimal places is:\")\n    fmt.Printf(\"%.32f\\n\", q(163))\n    heegners := [4][2]int64{\n        {19, 96},\n        {43, 960},\n        {67, 5280},\n        {163, 640320},\n    }\n    fmt.Println(\"\\nHeegner numbers yielding 'almost' integers:\")\n    t := new(big.Float).SetPrec(prec)\n    for _, h := range heegners {\n        qh := q(h[0])\n        c := h[1]*h[1]*h[1] + 744\n        t.SetInt64(c)\n        t.Sub(t, qh)\n        fmt.Printf(\"%3d: %51.32f ≈ %18d (diff: %.32f)\\n\", h[0], qh, c, t)\n    }\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class RamanujanConstant {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Ramanujan's Constant to 100 digits = %s%n%n\", ramanujanConstant(163, 100));\n        System.out.printf(\"Heegner numbers yielding 'almost' integers:%n\");\n        List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);\n        List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);\n        for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {\n            int heegnerNumber = heegnerNumbers.get(i);\n            int heegnerVal = heegnerVals.get(i);\n            BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));\n            BigDecimal compute = ramanujanConstant(heegnerNumber, 50);\n            System.out.printf(\"%3d : %50s ~ %18s (diff ~ %s)%n\", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());\n        }\n    }\n    \n    public static BigDecimal ramanujanConstant(int sqrt, int digits) {\n        \n        MathContext mc = new MathContext(digits + 5);  \n        return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));\n    }\n\n    \n    public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {\n        BigDecimal e = BigDecimal.ONE;\n        BigDecimal ak = e;\n        int k = 0;\n        BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));\n        while ( true ) {\n            k++;\n            ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);\n            e = e.add(ak, mc);\n            if ( ak.compareTo(min) < 0 ) {\n                break;\n            }\n        }\n        return e;\n        \n    }\n    \n    \n    public static BigDecimal bigPi(MathContext mc) {\n        int k = 0;\n        BigDecimal ak = BigDecimal.ONE;\n        BigDecimal a = ak;\n        BigDecimal b = BigDecimal.ZERO;\n        BigDecimal c = BigDecimal.valueOf(640320);\n        BigDecimal c3 = c.pow(3);\n        double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);\n        double digits = 0;\n        while ( digits < mc.getPrecision() ) {\n            k++;\n            digits += digitePerTerm;\n            BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));\n            BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);\n            ak = ak.multiply(term, mc);\n            a = a.add(ak, mc);\n            b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);\n        }\n        BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);\n        return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);\n    }\n\n    \n    public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {\n        \n        double sqrt = Math.sqrt(squareDecimal.doubleValue());\n        BigDecimal x0 = new BigDecimal(sqrt, mc);\n        BigDecimal two = BigDecimal.valueOf(2);\n        while ( true ) {\n            BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);\n            String x1String = x1.toPlainString();\n            String x0String = x0.toPlainString();\n            if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {\n                break;\n            }\n            x0 = x1;\n        }\n        return x0;\n    }\n    \n}\n"}
{"id": 59889, "name": "Word break problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype dict map[string]bool\n\nfunc newDict(words ...string) dict {\n    d := dict{}\n    for _, w := range words {\n        d[w] = true\n    }\n    return d\n}\n\nfunc (d dict) wordBreak(s string) (broken []string, ok bool) {\n    if s == \"\" {\n        return nil, true\n    }\n    type prefix struct {\n        length int\n        broken []string\n    }\n    bp := []prefix{{0, nil}}\n    for end := 1; end <= len(s); end++ {\n        for i := len(bp) - 1; i >= 0; i-- {\n            w := s[bp[i].length:end]\n            if d[w] {\n                b := append(bp[i].broken, w)\n                if end == len(s) {\n                    return b, true\n                }\n                bp = append(bp, prefix{end, b})\n                break\n            }\n        }\n    }\n    return nil, false\n}\n\nfunc main() {\n    d := newDict(\"a\", \"bc\", \"abc\", \"cd\", \"b\")\n    for _, s := range []string{\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"} {\n        if b, ok := d.wordBreak(s); ok {\n            fmt.Printf(\"%s: %s\\n\", s, strings.Join(b, \" \"))\n        } else {\n            fmt.Println(\"can't break\")\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n"}
{"id": 59890, "name": "Brilliant numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n"}
{"id": 59891, "name": "Brilliant numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nvar primes = rcu.Primes(1e8 - 1)\n\ntype res struct {\n    bc   interface{}\n    next int\n}\n\nfunc getBrilliant(digits, limit int, countOnly bool) res {\n    var brilliant []int\n    count := 0\n    pow := 1\n    next := math.MaxInt\n    for k := 1; k <= digits; k++ {\n        var s []int\n        for _, p := range primes {\n            if p >= pow*10 {\n                break\n            }\n            if p > pow {\n                s = append(s, p)\n            }\n        }\n        for i := 0; i < len(s); i++ {\n            for j := i; j < len(s); j++ {\n                prod := s[i] * s[j]\n                if prod < limit {\n                    if countOnly {\n                        count++\n                    } else {\n                        brilliant = append(brilliant, prod)\n                    }\n                } else {\n                    if next > prod {\n                        next = prod\n                    }\n                    break\n                }\n            }\n        }\n        pow *= 10\n    }\n    if countOnly {\n        return res{count, next}\n    }\n    return res{brilliant, next}\n}\n\nfunc main() {\n    fmt.Println(\"First 100 brilliant numbers:\")\n    brilliant := getBrilliant(2, 10000, false).bc.([]int)\n    sort.Ints(brilliant)\n    brilliant = brilliant[0:100]\n    for i := 0; i < len(brilliant); i++ {\n        fmt.Printf(\"%4d \", brilliant[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n    for k := 1; k <= 13; k++ {\n        limit := int(math.Pow(10, float64(k)))\n        r := getBrilliant(k, limit, true)\n        total := r.bc.(int)\n        next := r.next\n        climit := rcu.Commatize(limit)\n        ctotal := rcu.Commatize(total + 1)\n        cnext := rcu.Commatize(next)\n        fmt.Printf(\"First >= %18s is %14s in the series: %18s\\n\", climit, ctotal, cnext)\n    }\n}\n", "Java": "import java.util.*;\n\npublic class BrilliantNumbers {\n    public static void main(String[] args) {\n        var primesByDigits = getPrimesByDigits(100000000);\n        System.out.println(\"First 100 brilliant numbers:\");\n        List<Integer> brilliantNumbers = new ArrayList<>();\n        for (var primes : primesByDigits) {\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                int prime1 = primes.get(i);\n                for (int j = i; j < n; ++j) {\n                    int prime2 = primes.get(j);\n                    brilliantNumbers.add(prime1 * prime2);\n                }\n            }\n            if (brilliantNumbers.size() >= 100)\n                break;\n        }\n        Collections.sort(brilliantNumbers);\n        for (int i = 0; i < 100; ++i) {\n            char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n            System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n        }\n        System.out.println();\n        long power = 10;\n        long count = 0;\n        for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n            var primes = primesByDigits.get(p / 2);\n            long position = count + 1;\n            long minProduct = 0;\n            int n = primes.size();\n            for (int i = 0; i < n; ++i) {\n                long prime1 = primes.get(i);\n                var primes2 = primes.subList(i, n);\n                int q = (int)((power + prime1 - 1) / prime1);\n                int j = Collections.binarySearch(primes2, q);\n                if (j == n)\n                    continue;\n                if (j < 0)\n                    j = -(j + 1);\n                long prime2 = primes2.get(j);\n                long product = prime1 * prime2;\n                if (minProduct == 0 || product < minProduct)\n                    minProduct = product;\n                position += j;\n                if (prime1 >= prime2)\n                    break;\n            }\n            System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n                                p, minProduct, position);\n            power *= 10;\n            if (p % 2 == 1) {\n                long size = primes.size();\n                count += size * (size + 1) / 2;\n            }\n        }\n    }\n\n    private static List<List<Integer>> getPrimesByDigits(int limit) {\n        PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n        List<List<Integer>> primesByDigits = new ArrayList<>();\n        List<Integer> primes = new ArrayList<>();\n        for (int p = 10; p <= limit; ) {\n            int prime = primeGen.nextPrime();\n            if (prime > p) {\n                primesByDigits.add(primes);\n                primes = new ArrayList<>();\n                p *= 10;\n            }\n            primes.add(prime);\n        }\n        return primesByDigits;\n    }\n}\n"}
{"id": 59892, "name": "Word ladder", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n"}
{"id": 59893, "name": "Word ladder", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n    for _, e := range a {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc oneAway(a, b string) bool {\n    sum := 0\n    for i := 0; i < len(a); i++ {\n        if a[i] != b[i] {\n            sum++\n        }\n    }\n    return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n    l := len(a)\n    var poss []string\n    for _, word := range words {\n        if len(word) == l {\n            poss = append(poss, word)\n        }\n    }\n    todo := [][]string{{a}}\n    for len(todo) > 0 {\n        curr := todo[0]\n        todo = todo[1:]\n        var next []string\n        for _, word := range poss {\n            if oneAway(word, curr[len(curr)-1]) {\n                next = append(next, word)\n            }\n        }\n        if contains(next, b) {\n            curr = append(curr, b)\n            fmt.Println(strings.Join(curr, \" -> \"))\n            return\n        }\n        for i := len(poss) - 1; i >= 0; i-- {\n            if contains(next, poss[i]) {\n                copy(poss[i:], poss[i+1:])\n                poss[len(poss)-1] = \"\"\n                poss = poss[:len(poss)-1]\n            }\n        }\n        for _, s := range next {\n            temp := make([]string, len(curr))\n            copy(temp, curr)\n            temp = append(temp, s)\n            todo = append(todo, temp)\n        }\n    }\n    fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    words := make([]string, len(bwords))\n    for i, bword := range bwords {\n        words[i] = string(bword)\n    }\n    pairs := [][]string{\n        {\"boy\", \"man\"},\n        {\"girl\", \"lady\"},\n        {\"john\", \"jane\"},\n        {\"child\", \"adult\"},\n    }\n    for _, pair := range pairs {\n        wordLadder(words, pair[0], pair[1])\n    }\n}\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n    private static int distance(String s1, String s2) {\n        assert s1.length() == s2.length();\n        return (int) IntStream.range(0, s1.length())\n            .filter(i -> s1.charAt(i) != s2.charAt(i))\n            .count();\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n        wordLadder(words, fw, tw, 8);\n    }\n\n    private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n        if (fw.length() != tw.length()) {\n            throw new IllegalArgumentException(\"From word and to word must have the same length\");\n        }\n\n        Set<String> ws = words.get(fw.length());\n        if (ws.contains(fw)) {\n            List<String> primeList = new ArrayList<>();\n            primeList.add(fw);\n\n            PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n                int cmp1 = Integer.compare(chain1.size(), chain2.size());\n                if (cmp1 == 0) {\n                    String last1 = chain1.get(chain1.size() - 1);\n                    int d1 = distance(last1, tw);\n\n                    String last2 = chain2.get(chain2.size() - 1);\n                    int d2 = distance(last2, tw);\n\n                    return Integer.compare(d1, d2);\n                }\n                return cmp1;\n            });\n            queue.add(primeList);\n\n            while (queue.size() > 0) {\n                List<String> curr = queue.remove();\n                if (curr.size() > limit) {\n                    continue;\n                }\n\n                String last = curr.get(curr.size() - 1);\n                for (String word : ws) {\n                    if (distance(last, word) == 1) {\n                        if (word.equals(tw)) {\n                            curr.add(word);\n                            System.out.println(String.join(\" -> \", curr));\n                            return;\n                        }\n\n                        if (!curr.contains(word)) {\n                            List<String> cp = new ArrayList<>(curr);\n                            cp.add(word);\n                            queue.add(cp);\n                        }\n                    }\n                }\n            }\n        }\n\n        System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n    }\n\n    public static void main(String[] args) throws IOException {\n        Map<Integer, Set<String>> words = new HashMap<>();\n        for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n            Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n            wl.add(line);\n        }\n\n        wordLadder(words, \"boy\", \"man\");\n        wordLadder(words, \"girl\", \"lady\");\n        wordLadder(words, \"john\", \"jane\");\n        wordLadder(words, \"child\", \"adult\");\n        wordLadder(words, \"cat\", \"dog\");\n        wordLadder(words, \"lead\", \"gold\");\n        wordLadder(words, \"white\", \"black\");\n        wordLadder(words, \"bubble\", \"tickle\", 12);\n    }\n}\n"}
{"id": 59894, "name": "Earliest difference between prime gaps", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n"}
{"id": 59895, "name": "Earliest difference between prime gaps", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(1e9)\n    gapStarts := make(map[int]int)\n    primes := rcu.Primes(limit * 5)\n    for i := 1; i < len(primes); i++ {\n        gap := primes[i] - primes[i-1]\n        if _, ok := gapStarts[gap]; !ok {\n            gapStarts[gap] = primes[i-1]\n        }\n    }\n    pm := 10\n    gap1 := 2\n    for {\n        for _, ok := gapStarts[gap1]; !ok; {\n            gap1 += 2\n        }\n        start1 := gapStarts[gap1]\n        gap2 := gap1 + 2\n        if _, ok := gapStarts[gap2]; !ok {\n            gap1 = gap2 + 2\n            continue\n        }\n        start2 := gapStarts[gap2]\n        diff := start2 - start1\n        if diff < 0 {\n            diff = -diff\n        }\n        if diff > pm {\n            cpm := rcu.Commatize(pm)\n            cst1 := rcu.Commatize(start1)\n            cst2 := rcu.Commatize(start2)\n            cd := rcu.Commatize(diff)\n            fmt.Printf(\"Earliest difference > %s between adjacent prime gap starting primes:\\n\", cpm)\n            fmt.Printf(\"Gap %d starts at %s, gap %d starts at %s, difference is %s.\\n\\n\", gap1, cst1, gap2, cst2, cd)\n            if pm == limit {\n                break\n            }\n            pm *= 10\n        } else {\n            gap1 = gap2\n        }\n    }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n    private Map<Integer, Integer> gapStarts = new HashMap<>();\n    private int lastPrime;\n    private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n    public static void main(String[] args) {\n        final int limit = 100000000;\n        PrimeGaps pg = new PrimeGaps();\n        for (int pm = 10, gap1 = 2;;) {\n            int start1 = pg.findGapStart(gap1);\n            int gap2 = gap1 + 2;\n            int start2 = pg.findGapStart(gap2);\n            int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n            if (diff > pm) {\n                System.out.printf(\n                    \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n                    + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n                    pm, gap1, start1, gap2, start2, diff);\n                if (pm == limit)\n                    break;\n                pm *= 10;\n            } else {\n                gap1 = gap2;\n            }\n        }\n    }\n\n    private int findGapStart(int gap) {\n        Integer start = gapStarts.get(gap);\n        if (start != null)\n            return start;\n        for (;;) {\n            int prev = lastPrime;\n            lastPrime = primeGenerator.nextPrime();\n            int diff = lastPrime - prev;\n            gapStarts.putIfAbsent(diff, prev);\n            if (diff == gap)\n                return prev;\n        }\n    }\n}\n"}
{"id": 59896, "name": "Latin Squares in reduced form", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype matrix [][]int\n\n\nfunc dList(n, start int) (r matrix) {\n    start-- \n    a := make([]int, n)\n    for i := range a {\n        a[i] = i\n    }\n    a[0], a[start] = start, a[0]\n    sort.Ints(a[1:])\n    first := a[1]\n    \n    var recurse func(last int)\n    recurse = func(last int) {\n        if last == first {\n            \n            \n            for j, v := range a[1:] { \n                if j+1 == v {\n                    return \n                }\n            }\n            \n            b := make([]int, n)\n            copy(b, a)\n            for i := range b {\n                b[i]++ \n            }\n            r = append(r, b)\n            return\n        }\n        for i := last; i >= 1; i-- {\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n        }\n    }\n    recurse(n - 1)\n    return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n    if n <= 0 {\n        if echo {\n            fmt.Println(\"[]\\n\")\n        }\n        return 0\n    } else if n == 1 {\n        if echo {\n            fmt.Println(\"[1]\\n\")\n        }\n        return 1\n    }\n    rlatin := make(matrix, n)\n    for i := 0; i < n; i++ {\n        rlatin[i] = make([]int, n)\n    }\n    \n    for j := 0; j < n; j++ {\n        rlatin[0][j] = j + 1\n    }\n\n    count := uint64(0)\n    \n    var recurse func(i int)\n    recurse = func(i int) {\n        rows := dList(n, i) \n    outer:\n        for r := 0; r < len(rows); r++ {\n            copy(rlatin[i-1], rows[r])\n            for k := 0; k < i-1; k++ {\n                for j := 1; j < n; j++ {\n                    if rlatin[k][j] == rlatin[i-1][j] {\n                        if r < len(rows)-1 {\n                            continue outer\n                        } else if i > 2 {\n                            return\n                        }\n                    }\n                }\n            }\n            if i < n {\n                recurse(i + 1)\n            } else {\n                count++\n                if echo {\n                    printSquare(rlatin, n)\n                }\n            }\n        }\n        return\n    }\n\n    \n    recurse(2)\n    return count\n}\n\nfunc printSquare(latin matrix, n int) {\n    for i := 0; i < n; i++ {\n        fmt.Println(latin[i])\n    }\n    fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n    if n == 0 {\n        return 1\n    }\n    prod := uint64(1)\n    for i := uint64(2); i <= n; i++ {\n        prod *= i\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n    reducedLatinSquare(4, true)\n\n    fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n    fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n    for n := uint64(1); n <= 6; n++ {\n        size := reducedLatinSquare(int(n), false)\n        f := factorial(n - 1)\n        f *= f * n * size\n        fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n"}
{"id": 59897, "name": "UPC", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n"}
{"id": 59898, "name": "UPC", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nvar bits = []string{\n    \"0 0 0 1 1 0 1 \",\n    \"0 0 1 1 0 0 1 \",\n    \"0 0 1 0 0 1 1 \",\n    \"0 1 1 1 1 0 1 \",\n    \"0 1 0 0 0 1 1 \",\n    \"0 1 1 0 0 0 1 \",\n    \"0 1 0 1 1 1 1 \",\n    \"0 1 1 1 0 1 1 \",\n    \"0 1 1 0 1 1 1 \",\n    \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n    lhs = make(map[string]int)\n    rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n    s = \"# #\"\n    m = \" # # \"\n    e = \"# #\"\n    d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n    for i := 0; i <= 9; i++ {\n        lt := make([]byte, 7)\n        rt := make([]byte, 7)\n        for j := 0; j < 14; j += 2 {\n            if bits[i][j] == '1' {\n                lt[j/2] = '#'\n                rt[j/2] = ' '\n            } else {\n                lt[j/2] = ' '\n                rt[j/2] = '#'\n            }\n        }\n        lhs[string(lt)] = i\n        rhs[string(rt)] = i\n    }\n}\n\nfunc reverse(s string) string {\n    b := []byte(s)\n    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n        b[i], b[j] = b[j], b[i]\n    }\n    return string(b)\n}\n\nfunc main() {\n    barcodes := []string{\n        \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n        \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n        \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n        \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n        \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n        \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \",\n    }\n\n    \n    \n    expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n        s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n    rx := regexp.MustCompile(expr)\n    fmt.Println(\"UPC-A barcodes:\")\n    for i, bc := range barcodes {\n        for j := 0; j <= 1; j++ {\n            if !rx.MatchString(bc) {\n                fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n                break\n            }\n            codes := rx.FindStringSubmatch(bc)\n            digits := make([]int, 12)\n            var invalid, ok bool \n            for i := 1; i <= 6; i++ {\n                digits[i-1], ok = lhs[codes[i]]\n                if !ok {\n                    invalid = true\n                }\n                digits[i+5], ok = rhs[codes[i+6]]\n                if !ok {\n                    invalid = true\n                }\n            }\n            if invalid { \n                if j == 0 { \n                    bc = reverse(bc)\n                    continue\n                } else {\n                    fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n                    break\n                }\n            }\n            sum := 0\n            for i, d := range digits {\n                sum += weights[i] * d\n            }\n            if sum%10 != 0 {\n                fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n                break\n            } else {\n                ud := \"\"\n                if j == 1 {\n                    ud = \"(upside down)\"\n                }\n                fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n                break\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n"}
{"id": 59899, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 59900, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 59901, "name": "Playfair cipher", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \n    var used [26]bool \n    if p.pfo == noQ {\n        used[16] = true \n    } else {\n        used[9] = true \n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \n    plainText = strings.ToUpper(plainText)\n    \n    var cleanText strings.Builder\n    \n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \n        \n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is :\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword : \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y/n : \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text : \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is :\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is :\", decodedText)\n}\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 59902, "name": "Closest-pair problem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n"}
{"id": 59903, "name": "Inheritance_Single", "Go": "package main\n\ntype animal struct {\n    alive bool\n}\n\ntype dog struct {\n    animal\n    obedienceTrained bool\n}\n\ntype cat struct {\n    animal\n    litterBoxTrained bool\n}\n\ntype lab struct {\n    dog\n    color string\n}\n\ntype collie struct {\n    dog\n    catchesFrisbee bool\n}\n\nfunc main() {\n    var pet lab\n    pet.alive = true\n    pet.obedienceTrained = false\n    pet.color = \"yellow\"\n}\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 59904, "name": "Associative array_Creation", "Go": "\nvar x map[string]int\n\n\nx = make(map[string]int)\n\n\nx = make(map[string]int, 42)\n\n\nx[\"foo\"] = 3\n\n\ny1 := x[\"bar\"]     \ny2, ok := x[\"bar\"] \n\n\ndelete(x, \"foo\")\n\n\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 59905, "name": "Wilson primes of order n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"rcu\"\n)\n\nfunc main() {\n    const LIMIT = 11000\n    primes := rcu.Primes(LIMIT)\n    facts := make([]*big.Int, LIMIT)\n    facts[0] = big.NewInt(1)\n    for i := int64(1); i < LIMIT; i++ {\n        facts[i] = new(big.Int)\n        facts[i].Mul(facts[i-1], big.NewInt(i))\n    }\n    sign := int64(1)\n    f := new(big.Int)\n    zero := new(big.Int)\n    fmt.Println(\" n:  Wilson primes\")\n    fmt.Println(\"--------------------\")\n    for n := 1; n < 12; n++ {\n        fmt.Printf(\"%2d:  \", n)\n        sign = -sign\n        for _, p := range primes {\n            if p < n {\n                continue\n            }\n            f.Mul(facts[n-1], facts[p-n])\n            f.Sub(f, big.NewInt(sign))\n            p2 := int64(p * p)\n            bp2 := big.NewInt(p2)\n            if f.Rem(f, bp2).Cmp(zero) == 0 {\n                fmt.Printf(\"%d \", p)\n            }\n        }\n        fmt.Println()\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class WilsonPrimes {\n    public static void main(String[] args) {\n        final int limit = 11000;\n        BigInteger[] f = new BigInteger[limit];\n        f[0] = BigInteger.ONE;\n        BigInteger factorial = BigInteger.ONE;\n        for (int i = 1; i < limit; ++i) {\n            factorial = factorial.multiply(BigInteger.valueOf(i));\n            f[i] = factorial;\n        }\n        List<Integer> primes = generatePrimes(limit);\n        System.out.printf(\" n | Wilson primes\\n--------------------\\n\");\n        BigInteger s = BigInteger.valueOf(-1);\n        for (int n = 1; n <= 11; ++n) {\n            System.out.printf(\"%2d |\", n);\n            for (int p : primes) {\n                if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)\n                        .mod(BigInteger.valueOf(p * p))\n                        .equals(BigInteger.ZERO))\n                    System.out.printf(\" %d\", p);\n            }\n            s = s.negate();\n            System.out.println();\n        }\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": 59906, "name": "Color wheel", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nconst tau = 2 * math.Pi\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc colorWheel(dc *gg.Context) {\n    width, height := dc.Width(), dc.Height()\n    centerX, centerY := width/2, height/2\n    radius := centerX\n    if centerY < radius {\n        radius = centerY\n    }\n    for y := 0; y < height; y++ {\n        dy := float64(y - centerY)\n        for x := 0; x < width; x++ {\n            dx := float64(x - centerX)\n            dist := math.Sqrt(dx*dx + dy*dy)\n            if dist <= float64(radius) {\n                theta := math.Atan2(dy, dx)\n                hue := (theta + math.Pi) / tau\n                r, g, b := hsb2rgb(hue, 1, 1)\n                dc.SetRGB255(r, g, b)\n                dc.SetPixel(x, y)\n            }\n        }\n    }\n}\n\nfunc main() {\n    const width, height = 480, 480\n    dc := gg.NewContext(width, height)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    colorWheel(dc)\n    dc.SavePNG(\"color_wheel.png\")\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n"}
{"id": 59907, "name": "Plasma effect", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport static java.awt.image.BufferedImage.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class PlasmaEffect extends JPanel {\n    float[][] plasma;\n    float hueShift = 0;\n    BufferedImage img;\n\n    public PlasmaEffect() {\n        Dimension dim = new Dimension(640, 640);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);\n        plasma = createPlasma(dim.height, dim.width);\n\n        \n        new Timer(42, (ActionEvent e) -> {\n            hueShift = (hueShift + 0.02f) % 1;\n            repaint();\n        }).start();\n    }\n\n    float[][] createPlasma(int w, int h) {\n        float[][] buffer = new float[h][w];\n\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n\n                double value = sin(x / 16.0);\n                value += sin(y / 8.0);\n                value += sin((x + y) / 16.0);\n                value += sin(sqrt(x * x + y * y) / 8.0);\n                value += 4; \n                value /= 8; \n\n                \n                assert (value >= 0.0 && value <= 1.0) : \"Hue value out of bounds\";\n\n                buffer[y][x] = (float) value;\n            }\n        return buffer;\n    }\n\n    void drawPlasma(Graphics2D g) {\n        int h = plasma.length;\n        int w = plasma[0].length;\n        for (int y = 0; y < h; y++)\n            for (int x = 0; x < w; x++) {\n                float hue = hueShift + plasma[y][x] % 1;\n                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));\n            }\n        g.drawImage(img, 0, 0, null);\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        drawPlasma(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(\"Plasma Effect\");\n            f.setResizable(false);\n            f.add(new PlasmaEffect(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59908, "name": "Rhonda numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc contains(a []int, n int) bool {\n    for _, e := range a {\n        if e == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    for b := 2; b <= 36; b++ {\n        if rcu.IsPrime(b) {\n            continue\n        }\n        count := 0\n        var rhonda []int\n        for n := 1; count < 15; n++ {\n            digits := rcu.Digits(n, b)\n            if !contains(digits, 0) {\n                var anyEven = false\n                for _, d := range digits {\n                    if d%2 == 0 {\n                        anyEven = true\n                        break\n                    }\n                }\n                if b != 10 || (contains(digits, 5) && anyEven) {\n                    calc1 := 1\n                    for _, d := range digits {\n                        calc1 *= d\n                    }\n                    calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))\n                    if calc1 == calc2 {\n                        rhonda = append(rhonda, n)\n                        count++\n                    }\n                }\n            }\n        }\n        if len(rhonda) > 0 {\n            fmt.Printf(\"\\nFirst 15 Rhonda numbers in base %d:\\n\", b)\n            rhonda2 := make([]string, len(rhonda))\n            counts2 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda2[i] = fmt.Sprintf(\"%d\", r)\n                counts2[i] = len(rhonda2[i])\n            }\n            rhonda3 := make([]string, len(rhonda))\n            counts3 := make([]int, len(rhonda))\n            for i, r := range rhonda {\n                rhonda3[i] = strconv.FormatInt(int64(r), b)\n                counts3[i] = len(rhonda3[i])\n            }\n            maxLen2 := rcu.MaxInts(counts2)\n            maxLen3 := rcu.MaxInts(counts3)\n            maxLen := maxLen2\n            if maxLen3 > maxLen {\n                maxLen = maxLen3\n            }\n            maxLen++\n            fmt.Printf(\"In base 10: %*s\\n\", maxLen, rhonda2)\n            fmt.Printf(\"In base %-2d: %*s\\n\", b, maxLen, rhonda3)\n        }\n    }\n}\n", "Java": "public class RhondaNumbers {\n    public static void main(String[] args) {\n        final int limit = 15;\n        for (int base = 2; base <= 36; ++base) {\n            if (isPrime(base))\n                continue;\n            System.out.printf(\"First %d Rhonda numbers to base %d:\\n\", limit, base);\n            int numbers[] = new int[limit];\n            for (int n = 1, count = 0; count < limit; ++n) {\n                if (isRhonda(base, n))\n                    numbers[count++] = n;\n            }\n            System.out.printf(\"In base 10:\");\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %d\", numbers[i]);\n            System.out.printf(\"\\nIn base %d:\", base);\n            for (int i = 0; i < limit; ++i)\n                System.out.printf(\" %s\", Integer.toString(numbers[i], base));\n            System.out.printf(\"\\n\\n\");\n        }\n    }\n    \n    private static int digitProduct(int base, int n) {\n        int product = 1;\n        for (; n != 0; n /= base)\n            product *= n % base;\n        return product;\n    }\n     \n    private static int primeFactorSum(int n) {\n        int sum = 0;\n        for (; (n & 1) == 0; n >>= 1)\n            sum += 2;\n        for (int p = 3; p * p <= n; p += 2)\n            for (; n % p == 0; n /= p)\n                sum += p;\n        if (n > 1)\n            sum += n;\n        return sum;\n    }\n     \n    private static boolean isPrime(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 (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     \n    private static boolean isRhonda(int base, int n) {\n        return digitProduct(base, n) == base * primeFactorSum(n);\n    }\n}\n"}
{"id": 59909, "name": "Polymorphism", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float64\n}\n\ntype circle struct {\n    x, y, r float64\n}\n\ntype printer interface {\n    print()\n}\n\nfunc (p *point) print() {\n    fmt.Println(p.x, p.y)\n}\n\nfunc (c *circle) print() {\n    fmt.Println(c.x, c.y, c.r)\n}\n\nfunc main() {\n    var i printer            \n    i = newPoint(3, 4)       \n    i.print()                \n    i = newCircle(5, 12, 13) \n    i.print()                \n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *point) getX() float64  { return p.x }\nfunc (p *point) getY() float64  { return p.y }\nfunc (p *point) setX(v float64) { p.x = v }\nfunc (p *point) setY(v float64) { p.y = v }\n\nfunc (c *circle) getX() float64  { return c.x }\nfunc (c *circle) getY() float64  { return c.y }\nfunc (c *circle) getR() float64  { return c.r }\nfunc (c *circle) setX(v float64) { c.x = v }\nfunc (c *circle) setY(v float64) { c.y = v }\nfunc (c *circle) setR(v float64) { c.r = v }\n\n\n\nfunc (p *point) clone() *point   { r := *p; return &r }\nfunc (c *circle) clone() *circle { r := *c; return &r }\n\n\nfunc (p *point) set(q *point)   { *p = *q }\nfunc (c *circle) set(d *circle) { *c = *d }\n\n\n\n\n\n\n\n\n\n\nfunc newPoint(x, y float64) *point {\n    return &point{x, y}\n}\nfunc newCircle(x, y, r float64) *circle {\n    return &circle{x, y, r}\n}\n\n\n", "Java": "class Point {\n   protected int x, y;\n   public Point() { this(0); }\n   public Point(int x) { this(x, 0); }\n   public Point(int x, int y) { this.x = x; this.y = y; }\n   public Point(Point p) { this(p.x, p.y); }\n   public int getX() { return this.x; }\n   public int getY() { return this.y; }\n   public void setX(int x) { this.x = x; }\n   public void setY(int y) { this.y = y; }\n   public void print() { System.out.println(\"Point x: \" + this.x + \" y: \" + this.y); }\n}\n\nclass Circle extends Point {\n   private int r;\n   public Circle(Point p) { this(p, 0); }\n   public Circle(Point p, int r) { super(p); this.r = r; }\n   public Circle() { this(0); }\n   public Circle(int x) { this(x, 0); }\n   public Circle(int x, int y) { this(x, y, 0); }\n   public Circle(int x, int y, int r) { super(x, y); this.r = r; }\n   public Circle(Circle c) { this(c.x, c.y, c.r); }\n   public int getR() { return this.r; }\n   public void setR(int r) { this.r = r; }\n   public void print() { System.out.println(\"Circle x: \" + this.x + \" y: \" + this.y + \" r: \" + this.r); }\n}\n\npublic class test {\n  public static void main(String args[]) {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();     \n  }\n}\n"}
{"id": 59910, "name": "Create an object_Native demonstration", "Go": "package romap\n\ntype Romap struct{ imap map[byte]int }\n\n\nfunc New(m map[byte]int) *Romap {\n    if m == nil {\n        return nil\n    }\n    return &Romap{m}\n}\n\n\nfunc (rom *Romap) Get(key byte) (int, bool) {\n    i, ok := rom.imap[key]\n    return i, ok\n}\n\n\nfunc (rom *Romap) Reset(key byte) {\n    _, ok := rom.imap[key]\n    if ok {\n        rom.imap[key] = 0 \n    }\n}\n", "Java": "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n\npublic class ImmutableMap {\n\n    public static void main(String[] args) {\n        Map<String,Integer> hashMap = getImmutableMap();\n        try {\n            hashMap.put(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put new value.\");\n        }\n        try {\n            hashMap.clear();\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to clear map.\");\n        }\n        try {\n            hashMap.putIfAbsent(\"Test\", 23);\n        }\n        catch (UnsupportedOperationException e) {\n            System.out.println(\"ERROR:  Unable to put if absent.\");\n        }\n        \n        for ( String key : hashMap.keySet() ) {\n            System.out.printf(\"key = %s, value = %s%n\", key, hashMap.get(key));\n        }\n    }\n    \n    private static Map<String,Integer> getImmutableMap() {\n        Map<String,Integer> hashMap = new HashMap<>();\n        hashMap.put(\"Key 1\", 34);\n        hashMap.put(\"Key 2\", 105);\n        hashMap.put(\"Key 3\", 144);\n\n        return Collections.unmodifiableMap(hashMap);\n    }\n    \n}\n"}
{"id": 59911, "name": "Execute CopyPasta Language", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/atotto/clipboard\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n    \"runtime\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        clipboard.WriteAll(\"\") \n        log.Fatal(err)\n    }\n}\n\nfunc interpret(source string) {\n    source2 := source\n    if runtime.GOOS == \"windows\" {\n        source2 = strings.ReplaceAll(source, \"\\r\\n\", \"\\n\")\n    }\n    lines := strings.Split(source2, \"\\n\")\n    le := len(lines)\n    for i := 0; i < le; i++ {\n        lines[i] = strings.TrimSpace(lines[i]) \n        switch lines[i] {\n        case \"Copy\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Copy command.\")\n            }\n            i++\n            err := clipboard.WriteAll(lines[i])\n            check(err)\n        case \"CopyFile\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the CopyFile command.\")\n            }\n            i++\n            if lines[i] == \"TheF*ckingCode\" {\n                err := clipboard.WriteAll(source)\n                check(err)                \n            } else {\n                bytes, err := ioutil.ReadFile(lines[i])\n                check(err)\n                err = clipboard.WriteAll(string(bytes))\n                check(err)                \n            }\n        case \"Duplicate\":\n            if i == le-1 {\n                log.Fatal(\"There are no lines after the Duplicate command.\")\n            }\n            i++\n            times, err := strconv.Atoi(lines[i])\n            check(err)\n            if times < 0 {\n                log.Fatal(\"Can't duplicate text a negative number of times.\")\n            }\n            text, err := clipboard.ReadAll()\n            check(err)\n            err = clipboard.WriteAll(strings.Repeat(text, times+1))\n            check(err)\n        case \"Pasta!\":\n            text, err := clipboard.ReadAll()\n            check(err)\n            fmt.Println(text)\n            return\n        default:\n            if lines[i] == \"\" {\n                continue \n            }\n            log.Fatal(\"Unknown command, \" + lines[i])\n        }\n    }\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There should be exactly one command line argument, the CopyPasta file path.\")\n    }\n    bytes, err := ioutil.ReadFile(os.Args[1])\n    check(err)\n    interpret(string(bytes))\n    err = clipboard.WriteAll(\"\") \n    check(err)\n}\n", "Java": "import java.io.File;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class Copypasta\n{\n\t\n\tpublic static void fatal_error(String errtext)\n\t{\n\t\tStackTraceElement[] stack = Thread.currentThread().getStackTrace();\n\t\tStackTraceElement main = stack[stack.length - 1];\n\t\tString mainClass = main.getClassName();\n\t\tSystem.out.println(\"%\" + errtext);\n\t\tSystem.out.println(\"usage: \" + mainClass + \" [filename.cp]\");\n\t\tSystem.exit(1);\n\t}\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tString fname = null;\n\t\tString source = null;\n\t\ttry\n\t\t{\n\t\t\tfname = args[0];\n\t\t\tsource = new String(Files.readAllBytes(new File(fname).toPath()));\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tfatal_error(\"error while trying to read from specified file\");\n\t\t}\n\n\t\t\n\t\tArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split(\"\\n\")));\n\t\t\n\t\t\n\t\tString clipboard = \"\";\n\t\t\n\t\t\n\t\tint loc = 0;\n\t\twhile(loc < lines.size())\n\t\t{\n\t\t\t\n\t\t\tString command = lines.get(loc).trim();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(command.equals(\"Copy\"))\n\t\t\t\t\tclipboard += lines.get(loc + 1);\n\t\t\t\telse if(command.equals(\"CopyFile\"))\n\t\t\t\t{\n\t\t\t\t\tif(lines.get(loc + 1).equals(\"TheF*ckingCode\"))\n\t\t\t\t\t\tclipboard += source;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tString filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));\n\t\t\t\t\t\tclipboard += filetext;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Duplicate\"))\n\t\t\t\t{\n\t\t\t\t\tString origClipboard = clipboard;\n\n\t\t\t\t\tint amount = Integer.parseInt(lines.get(loc + 1)) - 1;\n\t\t\t\t\tfor(int i = 0; i < amount; i++)\n\t\t\t\t\t\tclipboard += origClipboard;\n\t\t\t\t}\n\t\t\t\telse if(command.equals(\"Pasta!\"))\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(clipboard);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfatal_error(\"unknown command '\" + command + \"' encountered on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tfatal_error(\"error while executing command '\" + command + \"' on line \" + new Integer(loc + 1).toString());\n\t\t\t}\n\n\t\t\t\n\t\t\tloc += 2;\n\t\t}\n\t}\n}\n"}
{"id": 59912, "name": "Square root by hand", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n"}
{"id": 59913, "name": "Square root by hand", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\nvar ten = big.NewInt(10)\nvar twenty = big.NewInt(20)\nvar hundred = big.NewInt(100)\n\nfunc sqrt(n float64, limit int) {\n    if n < 0 {\n        log.Fatal(\"Number cannot be negative\")\n    }\n    count := 0\n    for n != math.Trunc(n) {\n        n *= 100\n        count--\n    }\n    i := big.NewInt(int64(n))\n    j := new(big.Int).Sqrt(i)\n    count += len(j.String())\n    k := new(big.Int).Set(j)\n    d := new(big.Int).Set(j)\n    t := new(big.Int)\n    digits := 0\n    var sb strings.Builder\n    for digits < limit {\n        sb.WriteString(d.String())\n        t.Mul(k, d)\n        i.Sub(i, t)\n        i.Mul(i, hundred)\n        k.Mul(j, twenty)\n        d.Set(one)\n        for d.Cmp(ten) <= 0 {\n            t.Add(k, d)\n            t.Mul(t, d)\n            if t.Cmp(i) > 0 {\n                d.Sub(d, one)\n                break\n            }\n            d.Add(d, one)\n        }\n        j.Mul(j, ten)\n        j.Add(j, d)\n        k.Add(k, d)\n        digits = digits + 1\n    }\n    root := strings.TrimRight(sb.String(), \"0\")\n    if len(root) == 0 {\n        root = \"0\"\n    }\n    if count > 0 {\n        root = root[0:count] + \".\" + root[count:]\n    } else if count == 0 {\n        root = \"0.\" + root\n    } else {\n        root = \"0.\" + strings.Repeat(\"0\", -count) + root\n    }\n    root = strings.TrimSuffix(root, \".\")\n    fmt.Println(root)\n}\n\nfunc main() {\n    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}\n    digits := []int{500, 80, 8, 8, 8}\n    for i, n := range numbers {\n        fmt.Printf(\"First %d significant digits (at most) of the square root of %g:\\n\", digits[i], n)\n        sqrt(n, digits[i])\n        fmt.Println()\n    }\n}\n", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n"}
{"id": 59914, "name": "Reflection_List properties", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\n\ntype t struct {\n\tX    int\n\tnext *t\n}\n\nfunc main() {\n\treport(t{})\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tt := reflect.TypeOf(x)\n\tn := t.NumField()\n\tfmt.Printf(\"Type %v has %d fields:\\n\", t, n)\n\tfmt.Println(\"Name     Type     Exported\")\n\tfor i := 0; i < n; i++ {\n\t\tf := t.Field(i)\n\t\tfmt.Printf(\"%-8s %-8v %-8t\\n\",\n\t\t\tf.Name,\n\t\t\tf.Type,\n\t\t\tf.PkgPath == \"\",\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n"}
{"id": 59915, "name": "Minimal steps down to 1", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n    divs, subs []int\n    mins       [][]string\n)\n\n\nfunc minsteps(n int) {\n    if n == 1 {\n        mins[1] = []string{}\n        return\n    }\n    min := limit\n    var p, q int\n    var op byte\n    for _, div := range divs {\n        if n%div == 0 {\n            d := n / div\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, div, '/'\n            }\n        }\n    }\n    for _, sub := range subs {\n        if d := n - sub; d >= 1 {\n            steps := len(mins[d]) + 1\n            if steps < min {\n                min = steps\n                p, q, op = d, sub, '-'\n            }\n        }\n    }\n    mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n    mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n    for r := 0; r < 2; r++ {\n        divs = []int{2, 3}\n        if r == 0 {\n            subs = []int{1}\n        } else {\n            subs = []int{2}\n        }\n        mins = make([][]string, limit+1)\n        fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n        fmt.Println(\"  Minimum number of steps to diminish the following numbers down to 1 is:\")\n        for i := 1; i <= limit; i++ {\n            minsteps(i)\n            if i <= 10 {\n                steps := len(mins[i])\n                plural := \"s\"\n                if steps == 1 {\n                    plural = \" \"\n                }\n                fmt.Printf(\"    %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n            }\n        }\n        for _, lim := range []int{2000, 20000, 50000} {\n            max := 0\n            for _, min := range mins[0 : lim+1] {\n                m := len(min)\n                if m > max {\n                    max = m\n                }\n            }\n            var maxs []int\n            for i, min := range mins[0 : lim+1] {\n                if len(min) == max {\n                    maxs = append(maxs, i)\n                }\n            }\n            nums := len(maxs)\n            verb, verb2, plural := \"are\", \"have\", \"s\"\n            if nums == 1 {\n                verb, verb2, plural = \"is\", \"has\", \"\"\n            }\n            fmt.Printf(\"  There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n            fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n            fmt.Println(\"   \", maxs)\n        }\n        fmt.Println()\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MinimalStepsDownToOne {\n\n    public static void main(String[] args) {\n        runTasks(getFunctions1());\n        runTasks(getFunctions2());\n        runTasks(getFunctions3());\n    }\n    \n    private static void runTasks(List<Function> functions) {\n        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);\n\n        \n        int max = 10;\n        populateMap(minPath, functions, max);\n        System.out.printf(\"%nWith functions:  %s%n\", functions);\n        System.out.printf(\"  Minimum steps to 1:%n\");\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int steps = minPath.get(n).size();\n            System.out.printf(\"    %2d: %d step%1s: %s%n\", n, steps, steps == 1 ? \"\" : \"s\", minPath.get(n));\n        }\n        \n        \n        displayMaxMin(minPath, functions, 2000);\n\n        \n        displayMaxMin(minPath, functions, 20000);\n\n        \n        displayMaxMin(minPath, functions, 100000);\n    }\n    \n    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        populateMap(minPath, functions, max);\n        List<Integer> maxIntegers = getMaxMin(minPath, max);\n        int maxSteps = maxIntegers.remove(0);\n        int numCount = maxIntegers.size();\n        System.out.printf(\"  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n\", numCount == 1 ? \"is\" : \"are\", numCount, numCount == 1 ? \"\" : \"s\", max, maxSteps, maxIntegers);\n        \n    }\n    \n    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {\n        int maxSteps = Integer.MIN_VALUE;\n        List<Integer> maxIntegers = new ArrayList<Integer>();\n        for ( int n = 2 ; n <= max ; n++ ) {\n            int len = minPath.get(n).size();\n            if ( len > maxSteps ) {\n                maxSteps = len;\n                maxIntegers.clear();\n                maxIntegers.add(n);\n            }\n            else if ( len == maxSteps ) {\n                maxIntegers.add(n);\n            }\n        }\n        maxIntegers.add(0, maxSteps);\n        return maxIntegers;\n    }\n\n    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {\n        for ( int n = 2 ; n <= max ; n++ ) {\n            if ( minPath.containsKey(n) ) {\n                continue;\n            }\n            Function minFunction = null;\n            int minSteps = Integer.MAX_VALUE;\n            for ( Function f : functions ) {\n                if ( f.actionOk(n) ) {\n                    int result = f.action(n);\n                    int steps = 1 + minPath.get(result).size();\n                    if ( steps < minSteps ) {\n                        minFunction = f;\n                        minSteps = steps;\n                    }\n                }\n            }\n            int result = minFunction.action(n);\n            List<String> path = new ArrayList<String>();\n            path.add(minFunction.toString(n));\n            path.addAll(minPath.get(result));\n            minPath.put(n, path);\n        }\n        \n    }\n\n    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {\n        Map<Integer,List<String>> minPath = new HashMap<>();\n        for ( int i = 2 ; i <= max ; i++ ) {\n            for ( Function f : functions ) {\n                if ( f.actionOk(i) ) {\n                    int result = f.action(i);\n                    if ( result == 1 ) {\n                        List<String> path = new ArrayList<String>();\n                        path.add(f.toString(i));\n                        minPath.put(i, path);\n                    }\n                }\n            }\n        }\n        return minPath;\n    }\n\n    private static List<Function> getFunctions3() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide2Function());\n        functions.add(new Divide3Function());\n        functions.add(new Subtract2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions2() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract2Function());\n        return functions;\n    }\n\n    private static List<Function> getFunctions1() {\n        List<Function> functions = new ArrayList<>();\n        functions.add(new Divide3Function());\n        functions.add(new Divide2Function());\n        functions.add(new Subtract1Function());\n        return functions;\n    }\n    \n    public abstract static class Function {\n        abstract public int action(int n);\n        abstract public boolean actionOk(int n);\n        abstract public String toString(int n);\n    }\n    \n    public static class Divide2Function extends Function {\n        @Override public int action(int n) {\n            return n/2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 2 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/2 -> \" + n/2;\n        }\n        \n        @Override public String toString() {\n            return \"Divisor 2\";\n        }\n        \n    }\n\n    public static class Divide3Function extends Function {\n        @Override public int action(int n) {\n            return n/3;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n % 3 == 0;\n        }\n\n        @Override public String toString(int n) {\n            return \"/3 -> \" + n/3;\n        }\n\n        @Override public String toString() {\n            return \"Divisor 3\";\n        }\n\n    }\n\n    public static class Subtract1Function extends Function {\n        @Override public int action(int n) {\n            return n-1;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return true;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-1 -> \" + (n-1);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 1\";\n        }\n\n    }\n\n    public static class Subtract2Function extends Function {\n        @Override public int action(int n) {\n            return n-2;\n        }\n\n        @Override public boolean actionOk(int n) {\n            return n > 2;\n        }\n    \n        @Override public String toString(int n) {\n            return \"-2 -> \" + (n-2);\n        }\n\n        @Override public String toString() {\n            return \"Subtractor 2\";\n        }\n\n    }\n\n}\n"}
{"id": 59916, "name": "Align columns", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n"}
{"id": 59917, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 59918, "name": "URL parser", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo:\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql:\n\t\t\"ftp:\n\t\t\"http:\n\t\t\"ldap:\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet:\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh:\n\t\t\"https:\n\t\t\"http:\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\"    Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\"    Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\"    Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\"    Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\"    Host:\", host)\n\t\t\tfmt.Println(\"    Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\"    Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\"    Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\"    RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\"        Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\"    Fragment:\", u.Fragment)\n\t}\n}\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 59919, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 59920, "name": "Base58Check encoding", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\nconst alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\nvar big0 = new(big.Int)\nvar big58 = big.NewInt(58)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc convertToBase58(hash string, base int) (string, error) {\n    var x, ok = new(big.Int).SetString(hash, base)\n    if !ok {\n        return \"\", fmt.Errorf(\"'%v' is not a valid integer in base '%d'\", hash, base)\n    }\n    var sb strings.Builder\n    var rem = new(big.Int)\n    for x.Cmp(big0) == 1 {\n        x.QuoRem(x, big58, rem)\n        r := rem.Int64()\n        sb.WriteByte(alphabet[r])\n    }\n    return reverse(sb.String()), nil\n}\n\nfunc main() {\n    s := \"25420294593250030202636073700053352635053786165627414518\"\n    b, err := convertToBase58(s, 10)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(s, \"->\", b)\n    hashes := [...]string{\n        \"0x61\",\n        \"0x626262\",\n        \"0x636363\",\n        \"0x73696d706c792061206c6f6e6720737472696e67\",\n        \"0x516b6fcd0f\",\n        \"0xbf4f89001e670274dd\",\n        \"0x572e4794\",\n        \"0xecac89cad93923c02321\",\n        \"0x10c8511e\",\n    }\n    for _, hash := range hashes {\n        b58, err := convertToBase58(hash, 0)\n        if err != nil {\n            log.Fatal(err)\n        }\n        fmt.Printf(\"%-56s -> %s\\n\", hash, b58)\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 59921, "name": "Dynamic variable names", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n"}
{"id": 59922, "name": "Dynamic variable names", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\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    n := 0\n    for n < 1 || n > 5 {\n        fmt.Print(\"How many integer variables do you want to create (max 5) : \")\n        scanner.Scan()\n        n, _ = strconv.Atoi(scanner.Text())\n        check(scanner.Err())\n    }\n    vars := make(map[string]int)\n    fmt.Println(\"OK, enter the variable names and their values, below\")\n    for i := 1; i <= n; {\n        fmt.Println(\"\\n  Variable\", i)\n        fmt.Print(\"    Name  : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if _, ok := vars[name]; ok {\n            fmt.Println(\"  Sorry, you've already created a variable of that name, try again\")\n            continue\n        }\n        var value int\n        var err error\n        for {\n            fmt.Print(\"    Value : \")\n            scanner.Scan()\n            value, err = strconv.Atoi(scanner.Text())\n            check(scanner.Err())\n            if err != nil {\n                fmt.Println(\"  Not a valid integer, try again\")\n            } else {\n                break\n            }\n        }\n        vars[name] = value\n        i++\n    }\n    fmt.Println(\"\\nEnter q to quit\")\n    for {\n        fmt.Print(\"\\nWhich variable do you want to inspect : \")\n        scanner.Scan()\n        name := scanner.Text()\n        check(scanner.Err())\n        if s := strings.ToLower(name); s == \"q\" {\n            return\n        }\n        v, ok := vars[name]\n        if !ok {\n            fmt.Println(\"Sorry there's no variable of that name, try again\")\n        } else {\n            fmt.Println(\"It's value is\", v)\n        }\n    }\n}\n", "Java": "public static void main(String... args){\n        HashMap<String, Integer> vars = new HashMap<String, Integer>();\n        \n        \n        \n        vars.put(\"Variable name\", 3); \n        vars.put(\"Next variable name\", 5);\n        Scanner sc = new Scanner(System.in);\n        String str = sc.next();\n        vars.put(str, sc.nextInt()); \n        \n        System.out.println(vars.get(\"Variable name\")); \n        System.out.println(vars.get(str));\n}\n"}
{"id": 59923, "name": "Data Encryption Standard", "Go": "package main\n\nimport (\n    \"crypto/des\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    key, err := hex.DecodeString(\"0e329232ea6d0d73\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    c, err := des.NewCipher(key)\n    if err != nil {\n        log.Fatal(err)\n    }\n    src, err := hex.DecodeString(\"8787878787878787\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    dst := make([]byte, des.BlockSize)\n    c.Encrypt(dst, src)\n    fmt.Printf(\"%x\\n\", dst)\n}\n", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n"}
{"id": 59924, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 59925, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 59926, "name": "Fibonacci matrix-exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"time\"\n)\n\ntype vector = []*big.Int\ntype matrix []vector\n\nvar (\n    zero = new(big.Int)\n    one  = big.NewInt(1)\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    temp := new(big.Int)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            result[i][j] = new(big.Int)\n            for k := 0; k < rows2; k++ {\n                temp.Mul(m1[i][k], m2[k][j])\n                result[i][j].Add(result[i][j], temp)\n            }\n        }\n    }\n    return result\n}\n\nfunc identityMatrix(n uint64) matrix {\n    if n < 1 {\n        panic(\"Size of identity matrix can't be less than 1\")\n    }\n    ident := make(matrix, n)\n    for i := uint64(0); i < n; i++ {\n        ident[i] = make(vector, n)\n        for j := uint64(0); j < n; j++ {\n            ident[i][j] = new(big.Int)\n            if i == j {\n                ident[i][j].Set(one)\n            }\n        }\n    }\n    return ident\n}\n\nfunc (m matrix) pow(n *big.Int) matrix {\n    le := len(m)\n    if le != len(m[0]) {\n        panic(\"Not a square matrix\")\n    }\n    switch {\n    case n.Cmp(zero) == -1:\n        panic(\"Negative exponents not supported\")\n    case n.Cmp(zero) == 0:\n        return identityMatrix(uint64(le))\n    case n.Cmp(one) == 0:\n        return m\n    }\n    pow := identityMatrix(uint64(le))\n    base := m\n    e := new(big.Int).Set(n)\n    temp := new(big.Int)\n    for e.Cmp(zero) > 0 {\n        temp.And(e, one)\n        if temp.Cmp(one) == 0 {\n            pow = pow.mul(base)\n        }\n        e.Rsh(e, 1)\n        base = base.mul(base)\n    }\n    return pow\n}\n\nfunc fibonacci(n *big.Int) *big.Int {\n    if n.Cmp(zero) == 0 {\n        return zero\n    }\n    m := matrix{{one, one}, {one, zero}}\n    m = m.pow(n.Sub(n, one))\n    return m[0][0]\n}\n\nfunc commatize(n uint64) 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    start := time.Now()\n    n := new(big.Int)\n    for i := uint64(10); i <= 1e7; i *= 10 {\n        n.SetUint64(i)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the %sth Fibonacci number (%s) are:\\n\",\n            commatize(i), commatize(uint64(len(s))))\n        if len(s) > 20 {\n            fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n            if len(s) < 40 {\n                fmt.Printf(\"  Final %-2d : %s\\n\", len(s)-20, s[20:])\n            } else {\n                fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n            }\n        } else {\n            fmt.Printf(\"  All %-2d   : %s\\n\", len(s), s)\n        }\n        fmt.Println()\n    }\n\n    sfxs := []string{\"nd\", \"th\"}\n    for i, e := range []uint{16, 32} {\n        n.Lsh(one, e)\n        s := fibonacci(n).String()\n        fmt.Printf(\"The digits of the 2^%d%s Fibonacci number (%s) are:\\n\", e, sfxs[i],\n            commatize(uint64(len(s))))\n        fmt.Printf(\"  First 20 : %s\\n\", s[0:20])\n        fmt.Printf(\"  Final 20 : %s\\n\", s[len(s)-20:])\n        fmt.Println()\n    }\n\n    fmt.Printf(\"Took %s\\n\\n\", time.Since(start))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Arrays;\n\npublic class FibonacciMatrixExponentiation {\n\n    public static void main(String[] args) {\n        BigInteger mod = BigInteger.TEN.pow(20);\n        for ( int exp : Arrays.asList(32, 64) ) {\n            System.out.printf(\"Last 20 digits of fib(2^%d) = %s%n\", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));\n        }\n        \n        for ( int i = 1 ; i <= 7 ; i++ ) {\n            BigInteger n = BigInteger.TEN.pow(i);\n            System.out.printf(\"fib(%,d) = %s%n\", n, displayFib(fib(n)));\n        }\n    }\n    \n    private static String displayFib(BigInteger fib) {\n        String s = fib.toString();\n        if ( s.length() <= 40 ) {\n            return s;\n        }\n        return s.substring(0, 20) + \" ... \" + s.subSequence(s.length()-20, s.length());\n    }\n\n    \n    private static BigInteger fib(BigInteger k) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes;\n    }\n\n    \n    private static BigInteger fibMod(BigInteger k, BigInteger mod) {\n        BigInteger aRes = BigInteger.ZERO;\n        BigInteger bRes = BigInteger.ONE;\n        BigInteger cRes = BigInteger.ONE;\n        BigInteger aBase = BigInteger.ZERO;\n        BigInteger bBase = BigInteger.ONE;\n        BigInteger cBase = BigInteger.ONE;\n        while ( k.compareTo(BigInteger.ZERO) > 0 ) {\n            if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {\n                BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);\n                BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);\n                BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            k = k.shiftRight(1);\n            BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);\n            BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);\n            BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes.mod(mod);\n    }\n\n}\n"}
{"id": 59927, "name": "Commatizing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar reg = regexp.MustCompile(`(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)`)\n\nfunc reverse(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n\nfunc commatize(s string, startIndex, period int, sep string) string {\n    if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == \"\" {\n        return s\n    }\n    m := reg.FindString(s[startIndex:]) \n    if m == \"\" {\n        return s\n    }\n    splits := strings.Split(m, \".\")\n    ip := splits[0]\n    if len(ip) > period {\n        pi := reverse(ip)\n        for i := (len(ip) - 1) / period * period; i >= period; i -= period {\n            pi = pi[:i] + sep + pi[i:]\n        }\n        ip = reverse(pi)\n    }\n    if strings.Contains(m, \".\") {\n        dp := splits[1]\n        if len(dp) > period {\n            for i := (len(dp) - 1) / period * period; i >= period; i -= period {\n                dp = dp[:i] + sep + dp[i:]\n            }\n        }\n        ip += \".\" + dp\n    }\n    return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)\n}\n\nfunc main() {\n    tests := [...]string{\n        \"123456789.123456789\",\n        \".123456789\",\n        \"57256.1D-4\",\n        \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n        \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n        \"-in Aus$+1411.8millions\",\n        \"===US$0017440 millions=== (in 2000 dollars)\",\n        \"123.e8000 is pretty big.\",\n        \"The land area of the earth is 57268900(29% of the surface) square miles.\",\n        \"Ain't no numbers in this here words, nohow, no way, Jose.\",\n        \"James was never known as 0000000007\",\n        \"Arthur Eddington wrote: I believe there are \" +\n            \"15747724136275002577605653961181555468044717914527116709366231425076185631031296\" +\n            \" protons in the universe.\",\n        \"   $-140000±100 millions.\",\n        \"6/9/1946 was a good year for some.\",\n    }\n    fmt.Println(commatize(tests[0], 0, 2, \"*\"))\n    fmt.Println(commatize(tests[1], 0, 3, \"-\"))\n    fmt.Println(commatize(tests[2], 0, 4, \"__\"))\n    fmt.Println(commatize(tests[3], 0, 5, \" \"))\n    fmt.Println(commatize(tests[4], 0, 3, \".\"))\n    for _, test := range tests[5:] {\n        fmt.Println(commatize(test, 0, 3, \",\"))\n    }\n}\n", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n"}
{"id": 59928, "name": "Arithmetic coding_As a generalized change of radix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc cumulative_freq(freq map[byte]int64) map[byte]int64 {\n    total := int64(0)\n    cf := make(map[byte]int64)\n    for i := 0; i < 256; i++ {\n        b := byte(i)\n        if v, ok := freq[b]; ok {\n            cf[b] = total\n            total += v\n        }\n    }\n    return cf\n}\n\nfunc arithmethic_coding(str string, radix int64) (*big.Int,\n                                *big.Int, map[byte]int64) {\n\n    \n    chars := []byte(str)\n\n    \n    freq := make(map[byte]int64)\n    for _, c := range chars {\n        freq[c] += 1\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    base := len(chars)\n\n    \n    L := big.NewInt(0)\n\n    \n    pf := big.NewInt(1)\n\n    \n    \n    bigBase := big.NewInt(int64(base))\n\n    for _, c := range chars {\n        x := big.NewInt(cf[c])\n\n        L.Mul(L, bigBase)\n        L.Add(L, x.Mul(x, pf))\n        pf.Mul(pf, big.NewInt(freq[c]))\n    }\n\n    \n    U := big.NewInt(0)\n    U.Set(L)\n    U.Add(U, pf)\n\n    bigOne := big.NewInt(1)\n    bigZero := big.NewInt(0)\n    bigRadix := big.NewInt(radix)\n\n    tmp := big.NewInt(0).Set(pf)\n    powr := big.NewInt(0)\n\n    for {\n        tmp.Div(tmp, bigRadix)\n        if tmp.Cmp(bigZero) == 0 {\n            break\n        }\n        powr.Add(powr, bigOne)\n    }\n\n    diff := big.NewInt(0)\n    diff.Sub(U, bigOne)\n    diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))\n\n    return diff, powr, freq\n}\n\nfunc arithmethic_decoding(num *big.Int, radix int64,\n          pow *big.Int, freq map[byte]int64) string {\n\n    powr := big.NewInt(radix)\n\n    enc := big.NewInt(0).Set(num)\n    enc.Mul(enc, powr.Exp(powr, pow, nil))\n\n    base := int64(0)\n    for _, v := range freq {\n        base += v\n    }\n\n    \n    cf := cumulative_freq(freq)\n\n    \n    dict := make(map[int64]byte)\n    for k, v := range cf {\n        dict[v] = k\n    }\n\n    \n    lchar := -1\n    for i := int64(0); i < base; i++ {\n        if v, ok := dict[i]; ok {\n            lchar = int(v)\n        } else if lchar != -1 {\n            dict[i] = byte(lchar)\n        }\n    }\n\n    \n    decoded := make([]byte, base)\n    bigBase := big.NewInt(base)\n\n    for i := base - 1; i >= 0; i-- {\n\n        pow := big.NewInt(0)\n        pow.Exp(bigBase, big.NewInt(i), nil)\n\n        div := big.NewInt(0)\n        div.Div(enc, pow)\n\n        c := dict[div.Int64()]\n        fv := freq[c]\n        cv := cf[c]\n\n        prod := big.NewInt(0).Mul(pow, big.NewInt(cv))\n        diff := big.NewInt(0).Sub(enc, prod)\n        enc.Div(diff, big.NewInt(fv))\n\n        decoded[base-i-1] = c\n    }\n\n    \n    return string(decoded)\n}\n\nfunc main() {\n\n    var radix = int64(10)\n\n    strSlice := []string{\n        `DABDDB`,\n        `DABDDBBDDBA`,\n        `ABRACADABRA`,\n        `TOBEORNOTTOBEORTOBEORNOT`,\n    }\n\n    for _, str := range strSlice {\n        enc, pow, freq := arithmethic_coding(str, radix)\n        dec := arithmethic_decoding(enc, radix, pow, freq)\n        fmt.Printf(\"%-25s=> %19s * %d^%s\\n\", str, enc, radix, pow)\n\n        if str != dec {\n            panic(\"\\tHowever that is incorrect!\")\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n"}
{"id": 59929, "name": "Kosaraju", "Go": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n    0: {1},\n    1: {2},\n    2: {0},\n    3: {1, 2, 4},\n    4: {3, 5},\n    5: {2, 6},\n    6: {5},\n    7: {4, 6, 7},\n}\n\nfunc main() {\n    fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n    \n    vis := make([]bool, len(g))\n    L := make([]int, len(g))\n    x := len(L)                \n    t := make([][]int, len(g)) \n    \n    var Visit func(int)\n    Visit = func(u int) {\n        if !vis[u] {\n            vis[u] = true\n            for _, v := range g[u] {\n                Visit(v)\n                t[v] = append(t[v], u) \n            }\n            x--\n            L[x] = u\n        }\n    }\n    \n    for u := range g {\n        Visit(u)\n    }\n    c := make([]int, len(g)) \n    \n    var Assign func(int, int)\n    Assign = func(u, root int) {\n        if vis[u] { \n            vis[u] = false\n            c[u] = root\n            for _, v := range t[u] {\n                Assign(v, root)\n            }\n        }\n    }\n    \n    for _, u := range L {\n        Assign(u, u)\n    }\n    return c\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n"}
{"id": 59930, "name": "Reflection_List methods", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"reflect\"\n)\n\ntype t int \n\n\nfunc (r t) Twice() t       { return r * 2 }\nfunc (r t) Half() t        { return r / 2 }\nfunc (r t) Less(r2 t) bool { return r < r2 }\nfunc (r t) privateMethod() {}\n\nfunc main() {\n\treport(t(0))\n\treport(image.Point{})\n}\n\nfunc report(x interface{}) {\n\tv := reflect.ValueOf(x)\n\tt := reflect.TypeOf(x) \n\tn := t.NumMethod()\n\tfmt.Printf(\"Type %v has %d exported methods:\\n\", t, n)\n\tconst format = \"%-6s %-46s %s\\n\"\n\tfmt.Printf(format, \"Name\", \"Method expression\", \"Method value\")\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(format,\n\t\t\tt.Method(i).Name,\n\t\t\tt.Method(i).Func.Type(),\n\t\t\tv.Method(i).Type(),\n\t\t)\n\t}\n\tfmt.Println()\n}\n", "Java": "import java.lang.reflect.Method;\n\npublic class ListMethods {\n    public int examplePublicInstanceMethod(char c, double d) {\n        return 42;\n    }\n\n    private boolean examplePrivateInstanceMethod(String s) {\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        Class clazz = ListMethods.class;\n\n        System.out.println(\"All public methods (including inherited):\");\n        for (Method m : clazz.getMethods()) {\n            System.out.println(m);\n        }\n        System.out.println();\n        System.out.println(\"All declared methods (excluding inherited):\");\n        for (Method m : clazz.getDeclaredMethods()) {\n            System.out.println(m);\n        }\n    }\n}\n"}
{"id": 59931, "name": "Send an unknown method call", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype example struct{}\n\n\nfunc (example) Foo() int {\n    return 42\n}\n\nfunc main() {\n    \n    var e example\n    \n    m := reflect.ValueOf(e).MethodByName(\"Foo\")\n    \n    r := m.Call(nil)\n    \n    fmt.Println(r[0].Int()) \n}\n", "Java": "import java.lang.reflect.Method;\n\nclass Example {\n  public int foo(int x) {\n    return 42 + x;\n  }\n}\n\npublic class Main {\n  public static void main(String[] args) throws Exception {\n    Object example = new Example();\n    String name = \"foo\";\n    Class<?> clazz = example.getClass();\n    Method meth = clazz.getMethod(name, int.class);\n    Object result = meth.invoke(example, 5); \n    System.out.println(result);        \n  }\n}\n"}
{"id": 59932, "name": "Particle swarm optimization", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\ntype ff = func([]float64) float64\n\ntype parameters struct{ omega, phip, phig float64 }\n\ntype state struct {\n    iter       int\n    gbpos      []float64\n    gbval      float64\n    min        []float64\n    max        []float64\n    params     parameters\n    pos        [][]float64\n    vel        [][]float64\n    bpos       [][]float64\n    bval       []float64\n    nParticles int\n    nDims      int\n}\n\nfunc (s state) report(testfunc string) {\n    fmt.Println(\"Test Function        :\", testfunc)\n    fmt.Println(\"Iterations           :\", s.iter)\n    fmt.Println(\"Global Best Position :\", s.gbpos)\n    fmt.Println(\"Global Best Value    :\", s.gbval)\n}\n\nfunc psoInit(min, max []float64, params parameters, nParticles int) *state {\n    nDims := len(min)\n    pos := make([][]float64, nParticles)\n    vel := make([][]float64, nParticles)\n    bpos := make([][]float64, nParticles)\n    bval := make([]float64, nParticles)\n    for i := 0; i < nParticles; i++ {\n        pos[i] = min\n        vel[i] = make([]float64, nDims)\n        bpos[i] = min\n        bval[i] = math.Inf(1)\n    }\n    iter := 0\n    gbpos := make([]float64, nDims)\n    for i := 0; i < nDims; i++ {\n        gbpos[i] = math.Inf(1)\n    }\n    gbval := math.Inf(1)\n    return &state{iter, gbpos, gbval, min, max, params,\n        pos, vel, bpos, bval, nParticles, nDims}\n}\n\nfunc pso(fn ff, y *state) *state {\n    p := y.params\n    v := make([]float64, y.nParticles)\n    bpos := make([][]float64, y.nParticles)\n    bval := make([]float64, y.nParticles)\n    gbpos := make([]float64, y.nDims)\n    gbval := math.Inf(1)\n    for j := 0; j < y.nParticles; j++ {\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j] {\n            bpos[j] = y.pos[j]\n            bval[j] = v[j]\n        } else {\n            bpos[j] = y.bpos[j]\n            bval[j] = y.bval[j]\n        }\n        if bval[j] < gbval {\n            gbval = bval[j]\n            gbpos = bpos[j]\n        }\n    }\n    rg := rand.Float64()\n    pos := make([][]float64, y.nParticles)\n    vel := make([][]float64, y.nParticles)\n    for j := 0; j < y.nParticles; j++ {\n        pos[j] = make([]float64, y.nDims)\n        vel[j] = make([]float64, y.nDims)\n        \n        rp := rand.Float64()\n        ok := true\n        for z := 0; z < y.nDims; z++ {\n            pos[j][z] = 0\n            vel[j][z] = 0\n        }\n        for k := 0; k < y.nDims; k++ {\n            vel[j][k] = p.omega*y.vel[j][k] +\n                p.phip*rp*(bpos[j][k]-y.pos[j][k]) +\n                p.phig*rg*(gbpos[k]-y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]\n        }\n        if !ok {\n            for k := 0; k < y.nDims; k++ {\n                pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64()\n            }\n        }\n    }\n    iter := 1 + y.iter\n    return &state{iter, gbpos, gbval, y.min, y.max, y.params,\n        pos, vel, bpos, bval, y.nParticles, y.nDims}\n}\n\nfunc iterate(fn ff, n int, y *state) *state {\n    r := y\n    for i := 0; i < n; i++ {\n        r = pso(fn, r)\n    }\n    return r\n}\n\nfunc mccormick(x []float64) float64 {\n    a, b := x[0], x[1]\n    return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a\n}\n\nfunc michalewicz(x []float64) float64 {\n    m := 10.0\n    sum := 0.0\n    for i := 1; i <= len(x); i++ {\n        j := x[i-1]\n        k := math.Sin(float64(i) * j * j / math.Pi)\n        sum += math.Sin(j) * math.Pow(k, 2*m)\n    }\n    return -sum\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    st := psoInit(\n        []float64{-1.5, -3.0},\n        []float64{4.0, 4.0},\n        parameters{0.0, 0.6, 0.3},\n        100,\n    )\n    st = iterate(mccormick, 40, st)\n    st.report(\"McCormick\")\n    fmt.Println(\"f(-.54719, -1.54719) :\", mccormick([]float64{-.54719, -1.54719}))\n    fmt.Println()\n    st = psoInit(\n        []float64{0.0, 0.0},\n        []float64{math.Pi, math.Pi},\n        parameters{0.3, 0.3, 0.3},\n        1000,\n    )\n    st = iterate(michalewicz, 30, st)\n    st.report(\"Michalewicz (2D)\")\n    fmt.Println(\"f(2.20, 1.57)        :\", michalewicz([]float64{2.2, 1.57}))\n", "Java": "import java.util.Arrays;\nimport java.util.Objects;\nimport java.util.Random;\nimport java.util.function.Function;\n\npublic class App {\n    static class Parameters {\n        double omega;\n        double phip;\n        double phig;\n\n        Parameters(double omega, double phip, double phig) {\n            this.omega = omega;\n            this.phip = phip;\n            this.phig = phig;\n        }\n    }\n\n    static class State {\n        int iter;\n        double[] gbpos;\n        double gbval;\n        double[] min;\n        double[] max;\n        Parameters parameters;\n        double[][] pos;\n        double[][] vel;\n        double[][] bpos;\n        double[] bval;\n        int nParticles;\n        int nDims;\n\n        State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) {\n            this.iter = iter;\n            this.gbpos = gbpos;\n            this.gbval = gbval;\n            this.min = min;\n            this.max = max;\n            this.parameters = parameters;\n            this.pos = pos;\n            this.vel = vel;\n            this.bpos = bpos;\n            this.bval = bval;\n            this.nParticles = nParticles;\n            this.nDims = nDims;\n        }\n\n        void report(String testfunc) {\n            System.out.printf(\"Test Function        : %s\\n\", testfunc);\n            System.out.printf(\"Iterations           : %d\\n\", iter);\n            System.out.printf(\"Global Best Position : %s\\n\", Arrays.toString(gbpos));\n            System.out.printf(\"Global Best value    : %.15f\\n\", gbval);\n        }\n    }\n\n    private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) {\n        int nDims = min.length;\n        double[][] pos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            pos[i] = min.clone();\n        }\n        double[][] vel = new double[nParticles][nDims];\n        double[][] bpos = new double[nParticles][];\n        for (int i = 0; i < nParticles; ++i) {\n            bpos[i] = min.clone();\n        }\n        double[] bval = new double[nParticles];\n        for (int i = 0; i < bval.length; ++i) {\n            bval[i] = Double.POSITIVE_INFINITY;\n        }\n        int iter = 0;\n        double[] gbpos = new double[nDims];\n        for (int i = 0; i < gbpos.length; ++i) {\n            gbpos[i] = Double.POSITIVE_INFINITY;\n        }\n        double gbval = Double.POSITIVE_INFINITY;\n        return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n    }\n\n    private static Random r = new Random();\n\n    private static State pso(Function<double[], Double> fn, State y) {\n        Parameters p = y.parameters;\n        double[] v = new double[y.nParticles];\n        double[][] bpos = new double[y.nParticles][];\n        for (int i = 0; i < y.nParticles; ++i) {\n            bpos[i] = y.min.clone();\n        }\n        double[] bval = new double[y.nParticles];\n        double[] gbpos = new double[y.nDims];\n        double gbval = Double.POSITIVE_INFINITY;\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            v[j] = fn.apply(y.pos[j]);\n            \n            if (v[j] < y.bval[j]) {\n                bpos[j] = y.pos[j];\n                bval[j] = v[j];\n            } else {\n                bpos[j] = y.bpos[j];\n                bval[j] = y.bval[j];\n            }\n            if (bval[j] < gbval) {\n                gbval = bval[j];\n                gbpos = bpos[j];\n            }\n        }\n        double rg = r.nextDouble();\n        double[][] pos = new double[y.nParticles][y.nDims];\n        double[][] vel = new double[y.nParticles][y.nDims];\n        for (int j = 0; j < y.nParticles; ++j) {\n            \n            double rp = r.nextDouble();\n            boolean ok = true;\n            Arrays.fill(vel[j], 0.0);\n            Arrays.fill(pos[j], 0.0);\n            for (int k = 0; k < y.nDims; ++k) {\n                vel[j][k] = p.omega * y.vel[j][k] +\n                    p.phip * rp * (bpos[j][k] - y.pos[j][k]) +\n                    p.phig * rg * (gbpos[k] - y.pos[j][k]);\n                pos[j][k] = y.pos[j][k] + vel[j][k];\n                ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];\n            }\n            if (!ok) {\n                for (int k = 0; k < y.nDims; ++k) {\n                    pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble();\n                }\n            }\n        }\n        int iter = 1 + y.iter;\n        return new State(\n            iter, gbpos, gbval, y.min, y.max, y.parameters,\n            pos, vel, bpos, bval, y.nParticles, y.nDims\n        );\n    }\n\n    private static State iterate(Function<double[], Double> fn, int n, State y) {\n        State r = y;\n        if (n == Integer.MAX_VALUE) {\n            State old = y;\n            while (true) {\n                r = pso(fn, r);\n                if (Objects.equals(r, old)) break;\n                old = r;\n            }\n        } else {\n            for (int i = 0; i < n; ++i) {\n                r = pso(fn, r);\n            }\n        }\n        return r;\n    }\n\n    private static double mccormick(double[] x) {\n        double a = x[0];\n        double b = x[1];\n        return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;\n    }\n\n    private static double michalewicz(double[] x) {\n        int m = 10;\n        int d = x.length;\n        double sum = 0.0;\n        for (int i = 1; i < d; ++i) {\n            double j = x[i - 1];\n            double k = Math.sin(i * j * j / Math.PI);\n            sum += Math.sin(j) * Math.pow(k, 2.0 * m);\n        }\n        return -sum;\n    }\n\n    public static void main(String[] args) {\n        State state = psoInit(\n            new double[]{-1.5, -3.0},\n            new double[]{4.0, 4.0},\n            new Parameters(0.0, 0.6, 0.3),\n            100\n        );\n        state = iterate(App::mccormick, 40, state);\n        state.report(\"McCormick\");\n        System.out.printf(\"f(-.54719, -1.54719) : %.15f\\n\", mccormick(new double[]{-.54719, -1.54719}));\n        System.out.println();\n\n        state = psoInit(\n            new double[]{0.0, 0.0},\n            new double[]{Math.PI, Math.PI},\n            new Parameters(0.3, 3.0, 0.3),\n            1000\n        );\n        state = iterate(App::michalewicz, 30, state);\n        state.report(\"Michalewicz (2D)\");\n        System.out.printf(\"f(2.20, 1.57)        : %.15f\\n\", michalewicz(new double[]{2.20, 1.57}));\n    }\n}\n"}
{"id": 59933, "name": "Interactive programming (repl)", "Go": "package main\n\nimport \"fmt\"\n\nfunc f(s1, s2, sep string) string {\n\treturn s1 + sep + sep + s2\n}\n\nfunc main() {\n\tfmt.Println(f(\"Rosetta\", \"Code\", \":\"))\n}\n", "Java": "public static void main(String[] args) {\n    System.out.println(concat(\"Rosetta\", \"Code\", \":\"));\n}\n\npublic static String concat(String a, String b, String c) {\n   return a + c + c + b;\n}\n\nRosetta::Code\n"}
{"id": 59934, "name": "Index finite lists of positive integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc rank(l []uint) (r big.Int) {\n    for _, n := range l {\n        r.Lsh(&r, n+1)\n        r.SetBit(&r, int(n), 1)\n    }\n    return\n}\n\nfunc unrank(n big.Int) (l []uint) {\n    m := new(big.Int).Set(&n)\n    for a := m.BitLen(); a > 0; {\n        m.SetBit(m, a-1, 0)\n        b := m.BitLen()\n        l = append(l, uint(a-b-1))\n        a = b\n    }\n    return\n}\n\nfunc main() {\n    var b big.Int\n    for i := 0; i <= 10; i++ {\n        b.SetInt64(int64(i))\n        u := unrank(b)\n        r := rank(u)\n        fmt.Println(i, u, &r)\n    }\n    b.SetString(\"12345678901234567890\", 10)\n    u := unrank(b)\n    r := rank(u)\n    fmt.Printf(\"\\n%v\\n%d\\n%d\\n\", &b, u, &r)\n}\n", "Java": "import java.math.BigInteger;\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.Collectors.*;\n\npublic class Test3 {\n    static BigInteger rank(int[] x) {\n        String s = stream(x).mapToObj(String::valueOf).collect(joining(\"F\"));\n        return new BigInteger(s, 16);\n    }\n\n    static List<BigInteger> unrank(BigInteger n) {\n        BigInteger sixteen = BigInteger.valueOf(16);\n        String s = \"\";\n        while (!n.equals(BigInteger.ZERO)) {\n            s = \"0123456789ABCDEF\".charAt(n.mod(sixteen).intValue()) + s;\n            n = n.divide(sixteen);\n        }\n        return stream(s.split(\"F\")).map(x -> new BigInteger(x)).collect(toList());\n    }\n\n    public static void main(String[] args) {\n        int[] s = {1, 2, 3, 10, 100, 987654321};\n        System.out.println(Arrays.toString(s));\n        System.out.println(rank(s));\n        System.out.println(unrank(rank(s)));\n    }\n}\n"}
{"id": 59935, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n"}
{"id": 59936, "name": "Make a backup file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"os\"\n)\n\nfunc main() {\n    fn := \"myth\"\n    bx := \".backup\"\n    \n    var err error\n    if tf, err := os.Readlink(fn); err == nil {\n        fn = tf\n    }\n    \n    var fi os.FileInfo\n    if fi, err = os.Stat(fn); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    if err = os.Rename(fn, fn+bx); err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    err = ioutil.WriteFile(fn, []byte(\"you too!\\n\"), fi.Mode().Perm())\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n"}
{"id": 59937, "name": "Generalised floating point addition", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc repeatedAdd(bf *big.Float, times int) *big.Float {\n    if times < 2 {\n        return bf\n    }\n    var sum big.Float\n    for i := 0; i < times; i++ {\n        sum.Add(&sum, bf)\n    }\n    return &sum\n}\n\nfunc main() {\n    s := \"12345679\"\n    t := \"123456790\"\n    e := 63\n    var bf, extra big.Float\n    for n := -7; n <= 21; n++ {\n        bf.SetString(fmt.Sprintf(\"%se%d\", s, e))\n        extra.SetString(fmt.Sprintf(\"1e%d\", e))\n        bf = *repeatedAdd(&bf, 81)\n        bf.Add(&bf, &extra)\n        fmt.Printf(\"%2d : %s\\n\", n, bf.String())\n        s = t + s\n        e -= 9\n    }\n}\n", "Java": "import java.math.BigDecimal;\n\npublic class GeneralisedFloatingPointAddition {\n\n    public static void main(String[] args) {\n        BigDecimal oneExp72 = new BigDecimal(\"1E72\");\n        for ( int i = 0 ; i <= 21+7 ; i++ ) {\n            String s = \"12345679\";\n            for ( int j = 0 ; j < i ; j++ ) {\n                s += \"012345679\";\n            }\n            int exp = 63 - 9*i;\n            s += \"E\" + exp;\n            BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal(\"1E\" + exp));\n            System.out.printf(\"Test value (%s) equals computed value: %b.  Computed = %s%n\", oneExp72, num.compareTo(oneExp72) == 0 , num);\n        }\n    }\n\n}\n"}
{"id": 59938, "name": "Generalised floating point addition", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc repeatedAdd(bf *big.Float, times int) *big.Float {\n    if times < 2 {\n        return bf\n    }\n    var sum big.Float\n    for i := 0; i < times; i++ {\n        sum.Add(&sum, bf)\n    }\n    return &sum\n}\n\nfunc main() {\n    s := \"12345679\"\n    t := \"123456790\"\n    e := 63\n    var bf, extra big.Float\n    for n := -7; n <= 21; n++ {\n        bf.SetString(fmt.Sprintf(\"%se%d\", s, e))\n        extra.SetString(fmt.Sprintf(\"1e%d\", e))\n        bf = *repeatedAdd(&bf, 81)\n        bf.Add(&bf, &extra)\n        fmt.Printf(\"%2d : %s\\n\", n, bf.String())\n        s = t + s\n        e -= 9\n    }\n}\n", "Java": "import java.math.BigDecimal;\n\npublic class GeneralisedFloatingPointAddition {\n\n    public static void main(String[] args) {\n        BigDecimal oneExp72 = new BigDecimal(\"1E72\");\n        for ( int i = 0 ; i <= 21+7 ; i++ ) {\n            String s = \"12345679\";\n            for ( int j = 0 ; j < i ; j++ ) {\n                s += \"012345679\";\n            }\n            int exp = 63 - 9*i;\n            s += \"E\" + exp;\n            BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal(\"1E\" + exp));\n            System.out.printf(\"Test value (%s) equals computed value: %b.  Computed = %s%n\", oneExp72, num.compareTo(oneExp72) == 0 , num);\n        }\n    }\n\n}\n"}
{"id": 59939, "name": "Reverse the gender of a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n"}
{"id": 59940, "name": "Reverse the gender of a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc reverseGender(s string) string {\n    if strings.Contains(s, \"She\") {\n        return strings.Replace(s, \"She\", \"He\", -1)\n    } else if strings.Contains(s, \"He\") {\n        return strings.Replace(s, \"He\", \"She\", -1)\n    }\n    return s\n}\n\nfunc main() {\n    s := \"She was a soul stripper. She took my heart!\"\n    t := reverseGender(s)\n    fmt.Println(t)\n    fmt.Println(reverseGender(t))\n}\n", "Java": "public class ReallyLameTranslationOfJ {\n\n    public static void main(String[] args) {\n        String s = \"She was a soul stripper. She took my heart!\";\n        System.out.println(cheapTrick(s));\n        System.out.println(cheapTrick(cheapTrick(s)));\n    }\n\n    static String cheapTrick(String s) {\n        if (s.contains(\"She\"))\n            return s.replaceAll(\"She\", \"He\");\n        else if(s.contains(\"He\"))\n            return s.replaceAll(\"He\", \"She\");\n        return s;\n    }\n}\n"}
{"id": 59941, "name": "Audio alarm", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    number := 0\n    for number < 1 {\n        fmt.Print(\"Enter number of seconds delay > 0 : \")\n        scanner.Scan()\n        input := scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n        number, _ = strconv.Atoi(input)\n    }\n\n    filename := \"\"\n    for filename == \"\" {\n        fmt.Print(\"Enter name of .mp3 file to play (without extension) : \")\n        scanner.Scan()\n        filename = scanner.Text()\n        if err := scanner.Err(); err != nil {\n            log.Fatal(err)\n        }\n    }\n\n    cls := \"\\033[2J\\033[0;0H\" \n    fmt.Printf(\"%sAlarm will sound in %d seconds...\", cls, number)\n    time.Sleep(time.Duration(number) * time.Second)\n    fmt.Printf(cls)\n    cmd := exec.Command(\"play\", filename+\".mp3\")\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "Java": "import com.sun.javafx.application.PlatformImpl;\nimport java.io.File;\nimport java.util.Scanner;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport javafx.scene.media.Media;\nimport javafx.scene.media.MediaPlayer;\n\npublic class AudioAlarm {\n\n    public static void main(String[] args) throws InterruptedException {\n        Scanner input = new Scanner(System.in);\n\n        System.out.print(\"Enter a number of seconds: \");\n        int seconds = Integer.parseInt(input.nextLine());\n\n        System.out.print(\"Enter a filename (must end with .mp3 or .wav): \");\n        String audio = input.nextLine();\n\n        TimeUnit.SECONDS.sleep(seconds);\n\n        Media media = new Media(new File(audio).toURI().toString());\n        AtomicBoolean stop = new AtomicBoolean();\n        Runnable onEnd = () -> stop.set(true);\n\n        PlatformImpl.startup(() -> {}); \n\n        MediaPlayer player = new MediaPlayer(media);\n        player.setOnEndOfMedia(onEnd);\n        player.setOnError(onEnd);\n        player.setOnHalted(onEnd);\n        player.play();\n\n        while (!stop.get()) {\n            Thread.sleep(100);\n        }\n        System.exit(0); \n    }\n}\n"}
{"id": 59942, "name": "Decimal floating point number to binary", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n"}
{"id": 59943, "name": "Decimal floating point number to binary", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc decToBin(d float64) string {\n    whole := int64(math.Floor(d))\n    binary := strconv.FormatInt(whole, 2) + \".\"\n    dd := d - float64(whole)\n    for dd > 0.0 {\n        r := dd * 2.0\n        if r >= 1.0 {\n            binary += \"1\"\n            dd = r - 1.0\n        } else {\n            binary += \"0\"\n            dd = r\n        }\n    }\n    return binary\n}\n\nfunc binToDec(s string) float64 {\n    ss := strings.Replace(s, \".\", \"\", 1)\n    num, _ := strconv.ParseInt(ss, 2, 64)\n    ss = strings.Split(s, \".\")[1]\n    ss = strings.Replace(ss, \"1\", \"0\", -1)\n    den, _ := strconv.ParseInt(\"1\" + ss, 2, 64)\n    return float64(num) / float64(den)\n}\n\nfunc main() {\n    f := 23.34375\n    fmt.Printf(\"%v\\t => %s\\n\", f, decToBin(f))\n    s := \"1011.11101\"\n    fmt.Printf(\"%s\\t => %v\\n\", s, binToDec(s))\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class DecimalToBinary {\n\n    public static void main(String[] args) {\n        for ( String s : new String[] {\"23.34375\", \".1\", \"3.1415926535897932\"} ) {\n            String binary = decimalToBinary(new BigDecimal(s));\n            System.out.printf(\"%s => %s%n\", s, binary);\n            System.out.printf(\"%s => %s%n\", binary, binaryToDecimal(binary));\n        }\n    }\n\n    private static BigDecimal binaryToDecimal(String binary) {        \n        return binaryToDecimal(binary, 50);\n    }\n\n    private static BigDecimal binaryToDecimal(String binary, int digits) {\n        int decimalPosition = binary.indexOf(\".\");\n        String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;\n        String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : \"\";\n\n        \n        BigDecimal result = BigDecimal.ZERO;\n        BigDecimal powTwo = BigDecimal.ONE;\n        BigDecimal two = BigDecimal.valueOf(2);\n        for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));\n            powTwo = powTwo.multiply(two);\n        }\n        \n        \n        MathContext mc = new MathContext(digits);\n        powTwo = BigDecimal.ONE;\n        for ( char c : fractional.toCharArray() ) {\n            powTwo = powTwo.divide(two);\n            result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);\n        }\n        \n        return result;\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal) {\n        return decimalToBinary(decimal, 50);\n    }\n    \n    private static String decimalToBinary(BigDecimal decimal, int digits) {\n        BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);\n        BigDecimal fractional = decimal.subtract(integer);\n        \n        StringBuilder sb = new StringBuilder();\n\n        \n        BigDecimal two = BigDecimal.valueOf(2);\n        BigDecimal zero = BigDecimal.ZERO;\n        while ( integer.compareTo(zero) > 0 ) {\n            BigDecimal[] result = integer.divideAndRemainder(two);\n            sb.append(result[1]);\n            integer = result[0];\n        }\n        sb.reverse();\n        \n        \n        int count = 0;\n        if ( fractional.compareTo(zero) != 0 ) {\n            sb.append(\".\");\n        }\n        while ( fractional.compareTo(zero) != 0 ) {\n            count++;\n            fractional = fractional.multiply(two);\n            sb.append(fractional.setScale(0, RoundingMode.FLOOR));\n            if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {\n                fractional = fractional.subtract(BigDecimal.ONE);\n            }\n            if ( count >= digits ) {\n                break;\n            }\n        }\n        \n        return sb.toString();\n    }\n\n}\n"}
{"id": 59944, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 59945, "name": "Runtime evaluation_In an environment", "Go": "package main\n\nimport (\n    \"bitbucket.org/binet/go-eval/pkg/eval\"\n    \"fmt\"\n    \"go/parser\"\n    \"go/token\"\n)\n\nfunc main() {\n    \n    squareExpr := \"x*x\"\n\n    \n    fset := token.NewFileSet()\n    squareAst, err := parser.ParseExpr(squareExpr)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    w := eval.NewWorld()\n\n    \n    wVar := new(intV)\n\n    \n    err = w.DefineVar(\"x\", eval.IntType, wVar)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    squareCode, err := w.CompileExpr(fset, squareAst)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar = 5\n    \n    r0, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    *wVar--\n    \n    r1, err := squareCode.Run()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n\ntype intV int64\n\nfunc (v *intV) String() string              { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64      { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n    *v = intV(o.(eval.IntValue).Get(t))\n}\n", "Java": "import java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.util.Arrays;\nimport javax.tools.JavaCompiler;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.ToolProvider;\n\npublic class Eval {\n    private static final String CLASS_NAME = \"TempPleaseDeleteMe\";\n\n    private static class StringCompiler\n            extends SimpleJavaFileObject {\n        final String m_sourceCode;\n\n        private StringCompiler( final String sourceCode ) {\n            super( URI.create( \"string:\n            m_sourceCode = sourceCode;\n        }\n\n        @Override\n        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {\n            return m_sourceCode;\n        }\n\n        private boolean compile() {\n            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();\n\n            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),\n                null, null, null, Arrays.asList( this )\n            ).call();\n        }\n\n        private double callEval( final double x )\n                throws Exception {\n            final Class<?> clarse = Class.forName( CLASS_NAME );\n            final Method   eval   = clarse.getMethod( \"eval\", double.class );\n\n            return ( Double ) eval.invoke( null, x );\n        }\n    }\n\n    public static double evalWithX( final String code, final double x )\n            throws Exception {\n        final StringCompiler sc = new StringCompiler(\n            \"class \"\n                + CLASS_NAME\n                + \"{public static double eval(double x){return (\"\n                + code\n                + \");}}\"\n            );\n\n        if ( ! sc.compile() ) throw new RuntimeException( \"Compiler error\" );\n        return sc.callEval( x );\n    }\n\n    public static void main( final String [] args ) \n            throws Exception  {\n        final String expression = args [ 0 ];\n        final double x1         = Double.parseDouble( args [ 1 ] );\n        final double x2         = Double.parseDouble( args [ 2 ] );\n\n        System.out.println(\n            evalWithX( expression, x1 )\n            - evalWithX( expression, x2 )\n        );\n    }\n}\n"}
{"id": 59946, "name": "Check Machin-like formulas", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n"}
{"id": 59947, "name": "Check Machin-like formulas", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype mTerm struct {\n    a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n    {{1, 1, 2}, {1, 1, 3}},\n    {{2, 1, 3}, {1, 1, 7}},\n    {{4, 1, 5}, {-1, 1, 239}},\n    {{5, 1, 7}, {2, 3, 79}},\n    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n    for _, m := range testCases {\n        fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n    }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n    if len(m) == 1 {\n        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n    }\n    half := len(m) / 2\n    a := tans(m[:half])\n    b := tans(m[half:])\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n    if coef == 1 {\n        return f\n    }\n    if coef < 0 {\n        r := tanEval(-coef, f)\n        return r.Neg(r)\n    }\n    ca := coef / 2\n    cb := coef - ca\n    a := tanEval(ca, f)\n    b := tanEval(cb, f)\n    r := new(big.Rat)\n    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n"}
{"id": 59948, "name": "MD5_Implementation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"bytes\"\n    \"encoding/binary\"\n)\n\ntype testCase struct {\n    hashCode string\n    string\n}\n\nvar testCases = []testCase{\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\nfunc main() {\n    for _, tc := range testCases {\n        fmt.Printf(\"%s\\n%x\\n\\n\", tc.hashCode, md5(tc.string))\n    }\n}\n\nvar shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}\nvar table [64]uint32\n\nfunc init() {\n    for i := range table {\n        table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))\n    }\n}\n\nfunc md5(s string) (r [16]byte) {\n    padded := bytes.NewBuffer([]byte(s))\n    padded.WriteByte(0x80)\n    for padded.Len() % 64 != 56 {\n        padded.WriteByte(0)\n    }\n    messageLenBits := uint64(len(s)) * 8\n    binary.Write(padded, binary.LittleEndian, messageLenBits)\n\n    var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476\n    var buffer [16]uint32\n    for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { \n        a1, b1, c1, d1 := a, b, c, d\n        for j := 0; j < 64; j++ {\n            var f uint32\n            bufferIndex := j\n            round := j >> 4\n            switch round {\n            case 0:\n                f = (b1 & c1) | (^b1 & d1)\n            case 1:\n                f = (b1 & d1) | (c1 & ^d1)\n                bufferIndex = (bufferIndex*5 + 1) & 0x0F\n            case 2:\n                f = b1 ^ c1 ^ d1\n                bufferIndex = (bufferIndex*3 + 5) & 0x0F\n            case 3:\n                f = c1 ^ (b1 | ^d1)\n                bufferIndex = (bufferIndex * 7) & 0x0F\n            }\n            sa := shift[(round<<2)|(j&3)]\n            a1 += f + buffer[bufferIndex] + table[j]\n            a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1\n        }\n        a, b, c, d = a+a1, b+b1, c+c1, d+d1\n    }\n\n    binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})\n    return\n}\n", "Java": "class MD5\n{\n\n  private static final int INIT_A = 0x67452301;\n  private static final int INIT_B = (int)0xEFCDAB89L;\n  private static final int INIT_C = (int)0x98BADCFEL;\n  private static final int INIT_D = 0x10325476;\n  \n  private static final int[] SHIFT_AMTS = {\n    7, 12, 17, 22,\n    5,  9, 14, 20,\n    4, 11, 16, 23,\n    6, 10, 15, 21\n  };\n  \n  private static final int[] TABLE_T = new int[64];\n  static\n  {\n    for (int i = 0; i < 64; i++)\n      TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));\n  }\n  \n  public static byte[] computeMD5(byte[] message)\n  {\n    int messageLenBytes = message.length;\n    int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;\n    int totalLen = numBlocks << 6;\n    byte[] paddingBytes = new byte[totalLen - messageLenBytes];\n    paddingBytes[0] = (byte)0x80;\n    \n    long messageLenBits = (long)messageLenBytes << 3;\n    for (int i = 0; i < 8; i++)\n    {\n      paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;\n      messageLenBits >>>= 8;\n    }\n    \n    int a = INIT_A;\n    int b = INIT_B;\n    int c = INIT_C;\n    int d = INIT_D;\n    int[] buffer = new int[16];\n    for (int i = 0; i < numBlocks; i ++)\n    {\n      int index = i << 6;\n      for (int j = 0; j < 64; j++, index++)\n        buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);\n      int originalA = a;\n      int originalB = b;\n      int originalC = c;\n      int originalD = d;\n      for (int j = 0; j < 64; j++)\n      {\n        int div16 = j >>> 4;\n        int f = 0;\n        int bufferIndex = j;\n        switch (div16)\n        {\n          case 0:\n            f = (b & c) | (~b & d);\n            break;\n            \n          case 1:\n            f = (b & d) | (c & ~d);\n            bufferIndex = (bufferIndex * 5 + 1) & 0x0F;\n            break;\n            \n          case 2:\n            f = b ^ c ^ d;\n            bufferIndex = (bufferIndex * 3 + 5) & 0x0F;\n            break;\n            \n          case 3:\n            f = c ^ (b | ~d);\n            bufferIndex = (bufferIndex * 7) & 0x0F;\n            break;\n        }\n        int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);\n        a = d;\n        d = c;\n        c = b;\n        b = temp;\n      }\n      \n      a += originalA;\n      b += originalB;\n      c += originalC;\n      d += originalD;\n    }\n    \n    byte[] md5 = new byte[16];\n    int count = 0;\n    for (int i = 0; i < 4; i++)\n    {\n      int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));\n      for (int j = 0; j < 4; j++)\n      {\n        md5[count++] = (byte)n;\n        n >>>= 8;\n      }\n    }\n    return md5;\n  }\n  \n  public static String toHexString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      sb.append(String.format(\"%02X\", b[i] & 0xFF));\n    }\n    return sb.toString();\n  }\n\n  public static void main(String[] args)\n  {\n    String[] testStrings = { \"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" };\n    for (String s : testStrings)\n      System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\");\n    return;\n  }\n  \n}\n"}
{"id": 59949, "name": "K-means++ clustering", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\ntype r2 struct {\n    x, y float64\n}\n\ntype r2c struct {\n    r2\n    c int \n}\n\n\nfunc kmpp(k int, data []r2c) {\n    kMeans(data, kmppSeeds(k, data))\n}\n\n\n\nfunc kmppSeeds(k int, data []r2c) []r2 {\n    s := make([]r2, k)\n    s[0] = data[rand.Intn(len(data))].r2\n    d2 := make([]float64, len(data))\n    for i := 1; i < k; i++ {\n        var sum float64\n        for j, p := range data {\n            _, dMin := nearest(p, s[:i])\n            d2[j] = dMin * dMin\n            sum += d2[j]\n        }\n        target := rand.Float64() * sum\n        j := 0\n        for sum = d2[0]; sum < target; sum += d2[j] {\n            j++\n        }\n        s[i] = data[j].r2\n    }\n    return s\n}\n\n\n\n\nfunc nearest(p r2c, mean []r2) (int, float64) {\n    iMin := 0\n    dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y)\n    for i := 1; i < len(mean); i++ {\n        d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y)\n        if d < dMin {\n            dMin = d\n            iMin = i\n        }\n    }\n    return iMin, dMin\n}\n\n\nfunc kMeans(data []r2c, mean []r2) {\n    \n    for i, p := range data {\n        cMin, _ := nearest(p, mean)\n        data[i].c = cMin\n    }\n    mLen := make([]int, len(mean))\n    for {\n        \n        for i := range mean {\n            mean[i] = r2{}\n            mLen[i] = 0\n        }\n        for _, p := range data {\n            mean[p.c].x += p.x\n            mean[p.c].y += p.y\n            mLen[p.c]++\n        }\n        for i := range mean {\n            inv := 1 / float64(mLen[i])\n            mean[i].x *= inv\n            mean[i].y *= inv\n        }\n        \n        var changes int\n        for i, p := range data {\n            if cMin, _ := nearest(p, mean); cMin != p.c {\n                changes++\n                data[i].c = cMin\n            }\n        }\n        if changes == 0 {\n            return\n        }\n    }\n}\n\n\ntype ecParam struct {\n    k          int\n    nPoints    int\n    xBox, yBox int\n    stdv       int\n}\n\n\nfunc main() {\n    ec := &ecParam{6, 30000, 300, 200, 30}\n    \n    origin, data := genECData(ec)\n    vis(ec, data, \"origin\")\n    fmt.Println(\"Data set origins:\")\n    fmt.Println(\"    x      y\")\n    for _, o := range origin {\n        fmt.Printf(\"%5.1f  %5.1f\\n\", o.x, o.y)\n    }\n\n    kmpp(ec.k, data)\n    \n    fmt.Println(\n        \"\\nCluster centroids, mean distance from centroid, number of points:\")\n    fmt.Println(\"    x      y  distance  points\")\n    cent := make([]r2, ec.k)\n    cLen := make([]int, ec.k)\n    inv := make([]float64, ec.k)\n    for _, p := range data {\n        cent[p.c].x += p.x \n        cent[p.c].y += p.y \n        cLen[p.c]++\n    }\n    for i, iLen := range cLen {\n        inv[i] = 1 / float64(iLen)\n        cent[i].x *= inv[i]\n        cent[i].y *= inv[i]\n    }\n    dist := make([]float64, ec.k)\n    for _, p := range data {\n        dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y)\n    }\n    for i, iLen := range cLen {\n        fmt.Printf(\"%5.1f  %5.1f  %8.1f  %6d\\n\",\n            cent[i].x, cent[i].y, dist[i]*inv[i], iLen)\n    }\n    vis(ec, data, \"clusters\")\n}\n\n\n\n\n\n\n\nfunc genECData(ec *ecParam) (orig []r2, data []r2c) {\n    rand.Seed(time.Now().UnixNano())\n    orig = make([]r2, ec.k)\n    data = make([]r2c, ec.nPoints)\n    for i, n := 0, 0; i < ec.k; i++ {\n        x := rand.Float64() * float64(ec.xBox)\n        y := rand.Float64() * float64(ec.yBox)\n        orig[i] = r2{x, y}\n        for j := ec.nPoints / ec.k; j > 0; j-- {\n            data[n].x = rand.NormFloat64()*float64(ec.stdv) + x\n            data[n].y = rand.NormFloat64()*float64(ec.stdv) + y\n            data[n].c = i\n            n++\n        }\n    }\n    return\n}\n\n\nfunc vis(ec *ecParam, data []r2c, fn string) {\n    colors := make([]color.NRGBA, ec.k)\n    for i := range colors {\n        i3 := i * 3\n        third := i3 / ec.k\n        frac := uint8((i3 % ec.k) * 255 / ec.k)\n        switch third {\n        case 0:\n            colors[i] = color.NRGBA{frac, 255 - frac, 0, 255}\n        case 1:\n            colors[i] = color.NRGBA{0, frac, 255 - frac, 255}\n        case 2:\n            colors[i] = color.NRGBA{255 - frac, 0, frac, 255}\n        }\n    }\n    bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv)\n    im := image.NewNRGBA(bounds)\n    draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    fMinX := float64(bounds.Min.X)\n    fMaxX := float64(bounds.Max.X)\n    fMinY := float64(bounds.Min.Y)\n    fMaxY := float64(bounds.Max.Y)\n    for _, p := range data {\n        imx := math.Floor(p.x)\n        imy := math.Floor(float64(ec.yBox) - p.y)\n        if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY {\n            im.SetNRGBA(int(imx), int(imy), colors[p.c])\n        }\n    }\n    f, err := os.Create(fn + \".png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = png.Encode(f, im)\n    if err != nil {\n        fmt.Println(err)\n    }\n    err = f.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.util.Random;\n\npublic class KMeansWithKpp{\n\t\t\n\t\tpublic Point[] points;\n\t\tpublic Point[] centroids;\n\t\tRandom rand;\n\t\tpublic int n;\n\t\tpublic int k;\n\n\t\t\n\t\tprivate KMeansWithKpp(){\n\t\t}\n\n\t\tKMeansWithKpp(Point[] p, int clusters){\n\t\t\t\tpoints = p;\n\t\t\t\tn = p.length;\n\t\t\t\tk = Math.max(1, clusters);\n\t\t\t\tcentroids = new Point[k];\n\t\t\t\trand = new Random();\n\t\t}\n\n\n\t\tprivate static double distance(Point a, Point b){\n\t\t\t\treturn (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);\n\t\t}\n\n\t\tprivate static int nearest(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tint index = pt.group;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t\t\tindex = i;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn index;\n\t\t}\n\n\t\tprivate static double nearestDistance(Point pt, Point[] others, int len){\n\t\t\t\tdouble minD = Double.MAX_VALUE;\n\t\t\t\tlen = Math.min(others.length, len);\n\t\t\t\tdouble dist;\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\t\tif (minD > (dist = distance(pt, others[i]))) {\n\t\t\t\t\t\t\t\tminD = dist;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn minD;\n\t\t}\n\n\t\tprivate void kpp(){\n\t\t\t\tcentroids[0] = points[rand.nextInt(n)];\n\t\t\t\tdouble[] dist = new double[n];\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor (int i = 1; i < k; i++) {\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tdist[j] = nearestDistance(points[j], centroids, i);\n\t\t\t\t\t\t\t\tsum += dist[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\t\t\tif ((sum -= dist[j]) > 0)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tcentroids[i].x = points[j].x;\n\t\t\t\t\t\t\t\tcentroids[i].y = points[j].y;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tpoints[i].group = nearest(points[i], centroids, k);\n\t\t\t\t}\n\t\t}\n\n\t\tpublic void kMeans(int maxTimes){\n\t\t\t\tif (k == 1 || n <= 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(k >= n){\n\t\t\t\t\t\tfor(int i =0; i < n; i++){\n\t\t\t\t\t\t\t\tpoints[i].group = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxTimes = Math.max(1, maxTimes);\n\t\t\t\tint changed;\n\t\t\t\tint bestPercent = n/1000;\n\t\t\t\tint minIndex;\n\t\t\t\tkpp();\n\t\t\t\tdo {\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x = 0.0;\n\t\t\t\t\t\t\t\tc.y = 0.0;\n\t\t\t\t\t\t\t\tc.group = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tif(pt.group < 0 || pt.group > centroids.length){\n\t\t\t\t\t\t\t\t\t\tpt.group = rand.nextInt(centroids.length);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcentroids[pt.group].x += pt.x;\n\t\t\t\t\t\t\t\tcentroids[pt.group].y = pt.y;\n\t\t\t\t\t\t\t\tcentroids[pt.group].group++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (Point c : centroids) {\n\t\t\t\t\t\t\t\tc.x /= c.group;\n\t\t\t\t\t\t\t\tc.y /= c.group;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\tfor (Point pt : points) {\n\t\t\t\t\t\t\t\tminIndex = nearest(pt, centroids, k);\n\t\t\t\t\t\t\t\tif (k != pt.group) {\n\t\t\t\t\t\t\t\t\t\tchanged++;\n\t\t\t\t\t\t\t\t\t\tpt.group = minIndex;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxTimes--;\n\t\t\t\t} while (changed > bestPercent && maxTimes > 0);\n\t\t}\n}\n\n\n\n\nclass Point{\n\t\tpublic double x;\n\t\tpublic double y;\n\t\tpublic int group;\n\n\t\tPoint(){\n\t\t\t\tx = y = 0.0;\n\t\t\t\tgroup = 0;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){\n\t\t\t\tif (size <= 0)\n\t\t\t\t\t\treturn null;\n\t\t\t\tdouble xdiff, ydiff;\n\t\t\t\txdiff = maxX - minX;\n\t\t\t\tydiff = maxY - minY;\n\t\t\t\tif (minX > maxX) {\n\t\t\t\t\t\txdiff = minX - maxX;\n\t\t\t\t\t\tminX = maxX;\n\t\t\t\t}\n\t\t\t\tif (maxY < minY) {\n\t\t\t\t\t\tydiff = minY - maxY;\n\t\t\t\t\t\tminY = maxY;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tdata[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\n\t\t\n\t\tpublic Point[] getRandomPolarData(double radius, int size){\n\t\t\t\tif (size <= 0) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tPoint[] data = new Point[size];\n\t\t\t\tdouble radi, arg;\n\t\t\t\tRandom rand = new Random();\n\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tradi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\targ = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;\n\t\t\t\t\t\tdata[i].x = radi * Math.cos(arg);\n\t\t\t\t\t\tdata[i].y = radi * Math.sin(arg);\n\t\t\t\t}\n\t\t\t\treturn data;\n\t\t}\n\t\t\n}\n"}
{"id": 59950, "name": "Maze solving", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\" \n    \"math/rand\"\n    \"time\"\n)\n\ntype maze struct { \n    c2 [][]byte \n    h2 [][]byte \n    v2 [][]byte \n}\n\nfunc newMaze(rows, cols int) *maze {\n    c := make([]byte, rows*cols)              \n    h := bytes.Repeat([]byte{'-'}, rows*cols) \n    v := bytes.Repeat([]byte{'|'}, rows*cols) \n    c2 := make([][]byte, rows)                \n    h2 := make([][]byte, rows)                \n    v2 := make([][]byte, rows)                \n    for i := range h2 {\n        c2[i] = c[i*cols : (i+1)*cols]\n        h2[i] = h[i*cols : (i+1)*cols]\n        v2[i] = v[i*cols : (i+1)*cols]\n    }\n    return &maze{c2, h2, v2}\n}   \n    \nfunc (m *maze) String() string {\n    hWall := []byte(\"+---\")\n    hOpen := []byte(\"+   \")\n    vWall := []byte(\"|   \")\n    vOpen := []byte(\"    \")\n    rightCorner := []byte(\"+\\n\")\n    rightWall := []byte(\"|\\n\")\n    var b []byte\n    for r, hw := range m.h2 {\n        for _, h := range hw {\n            if h == '-' || r == 0 {\n                b = append(b, hWall...)\n            } else {\n                b = append(b, hOpen...)\n                if h != '-' && h != 0 {\n                    b[len(b)-2] = h\n                }\n            }\n        }\n        b = append(b, rightCorner...)\n        for c, vw := range m.v2[r] {\n            if vw == '|' || c == 0 {\n                b = append(b, vWall...)\n            } else {\n                b = append(b, vOpen...)\n                if vw != '|' && vw != 0 {\n                    b[len(b)-4] = vw\n                }\n            }\n            if m.c2[r][c] != 0 {\n                b[len(b)-2] = m.c2[r][c]\n            }\n        }\n        b = append(b, rightWall...)\n    }\n    for _ = range m.h2[0] {\n        b = append(b, hWall...)\n    }\n    b = append(b, rightCorner...)\n    return string(b)\n}\n\nfunc (m *maze) gen() {\n    m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))\n}\n\nconst (\n    up = iota\n    dn\n    rt\n    lf\n)\n\nfunc (m *maze) g2(r, c int) {\n    m.c2[r][c] = ' '\n    for _, dir := range rand.Perm(4) {\n        switch dir {\n        case up:\n            if r > 0 && m.c2[r-1][c] == 0 {\n                m.h2[r][c] = 0\n                m.g2(r-1, c)\n            }\n        case lf:\n            if c > 0 && m.c2[r][c-1] == 0 {\n                m.v2[r][c] = 0\n                m.g2(r, c-1)\n            }\n        case dn:\n            if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {\n                m.h2[r+1][c] = 0\n                m.g2(r+1, c)\n            }\n        case rt:\n            if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {\n                m.v2[r][c+1] = 0\n                m.g2(r, c+1)\n            } \n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const height = 4\n    const width = 7\n    m := newMaze(height, width)\n    m.gen() \n    m.solve(\n        rand.Intn(height), rand.Intn(width),\n        rand.Intn(height), rand.Intn(width))\n    fmt.Print(m)\n}   \n    \nfunc (m *maze) solve(ra, ca, rz, cz int) {\n    var rSolve func(ra, ca, dir int) bool\n    rSolve = func(r, c, dir int) bool {\n        if r == rz && c == cz {\n            m.c2[r][c] = 'F'\n            return true\n        }\n        if dir != dn && m.h2[r][c] == 0 {\n            if rSolve(r-1, c, up) {\n                m.c2[r][c] = '^'\n                m.h2[r][c] = '^'\n                return true\n            }\n        }\n        if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 {\n            if rSolve(r+1, c, dn) {\n                m.c2[r][c] = 'v'\n                m.h2[r+1][c] = 'v'\n                return true\n            }\n        }\n        if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 {\n            if rSolve(r, c+1, rt) {\n                m.c2[r][c] = '>'\n                m.v2[r][c+1] = '>'\n                return true\n            }\n        }\n        if dir != rt && m.v2[r][c] == 0 {\n            if rSolve(r, c-1, lf) {\n                m.c2[r][c] = '<'\n                m.v2[r][c] = '<'\n                return true\n            }\n        }\n        return false\n    }\n    rSolve(ra, ca, -1)\n    m.c2[ra][ca] = 'S'\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class MazeSolver\n{\n    \n    private static String[] readLines (InputStream f) throws IOException\n    {\n        BufferedReader r =\n            new BufferedReader (new InputStreamReader (f, \"US-ASCII\"));\n        ArrayList<String> lines = new ArrayList<String>();\n        String line;\n        while ((line = r.readLine()) != null)\n            lines.add (line);\n        return lines.toArray(new String[0]);\n    }\n\n    \n    private static char[][] decimateHorizontally (String[] lines)\n    {\n        final int width = (lines[0].length() + 1) / 2;\n        char[][] c = new char[lines.length][width];\n        for (int i = 0  ;  i < lines.length  ;  i++)\n            for (int j = 0  ;  j < width  ;  j++)\n                c[i][j] = lines[i].charAt (j * 2);\n        return c;\n    }\n\n    \n    private static boolean solveMazeRecursively (char[][] maze,\n                                                 int x, int y, int d)\n    {\n        boolean ok = false;\n        for (int i = 0  ;  i < 4  &&  !ok  ;  i++)\n            if (i != d)\n                switch (i)\n                    {\n                        \n                    case 0:\n                        if (maze[y-1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y - 2, 2);\n                        break;\n                    case 1:\n                        if (maze[y][x+1] == ' ')\n                            ok = solveMazeRecursively (maze, x + 2, y, 3);\n                        break;\n                    case 2:\n                        if (maze[y+1][x] == ' ')\n                            ok = solveMazeRecursively (maze, x, y + 2, 0);\n                        break;\n                    case 3:\n                        if (maze[y][x-1] == ' ')\n                            ok = solveMazeRecursively (maze, x - 2, y, 1);\n                        break;\n                    }\n        \n        if (x == 1  &&  y == 1)\n            ok = true;\n        \n        if (ok)\n            {\n                maze[y][x] = '*';\n                switch (d)\n                    {\n                    case 0:\n                        maze[y-1][x] = '*';\n                        break;\n                    case 1:\n                        maze[y][x+1] = '*';\n                        break;\n                    case 2:\n                        maze[y+1][x] = '*';\n                        break;\n                    case 3:\n                        maze[y][x-1] = '*';\n                        break;\n                    }\n            }\n        return ok;\n    }\n\n    \n    private static void solveMaze (char[][] maze)\n    {\n        solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1);\n    }\n\n    \n    private static String[] expandHorizontally (char[][] maze)\n    {\n        char[] tmp = new char[3];\n        String[] lines = new String[maze.length];\n        for (int i = 0  ;  i < maze.length  ;  i++)\n            {\n                StringBuilder sb = new StringBuilder(maze[i].length * 2);\n                for (int j = 0  ;  j < maze[i].length  ;  j++)\n                    if (j % 2 == 0)\n                        sb.append (maze[i][j]);\n                    else\n                        {\n                            tmp[0] = tmp[1] = tmp[2] = maze[i][j];\n                            if (tmp[1] == '*')\n                                tmp[0] = tmp[2] = ' ';\n                            sb.append (tmp);\n                        }\n                lines[i] = sb.toString();\n            }\n        return lines;\n    }\n\n    \n    public static void main (String[] args) throws IOException\n    {\n        InputStream f = (args.length > 0\n                         ?  new FileInputStream (args[0])\n                         :  System.in);\n        String[] lines = readLines (f);\n        char[][] maze = decimateHorizontally (lines);\n        solveMaze (maze);\n        String[] solvedLines = expandHorizontally (maze);\n        for (int i = 0  ;  i < solvedLines.length  ;  i++)\n            System.out.println (solvedLines[i]);\n    }\n}\n"}
{"id": 59951, "name": "Generate random numbers without repeating a value", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\nfunc generate(from, to int64) {\n    if to < from || from < 0 {\n        log.Fatal(\"Invalid range.\")\n    }\n    span := to - from + 1\n    generated := make([]bool, span) \n    count := span\n    for count > 0 {\n        n := from + rand.Int63n(span) \n        if !generated[n-from] {\n            generated[n-from] = true\n            fmt.Printf(\"%2d \", n)\n            count--\n        }\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    \n    for i := 1; i <= 5; i++ {\n        generate(1, 20)\n    }\n}\n", "Java": "import java.util.*;\n\npublic class RandomShuffle {\n    public static void main(String[] args) {\n        Random rand = new Random();\n        List<Integer> list = new ArrayList<>();\n        for (int j = 1; j <= 20; ++j)\n            list.add(j);\n        Collections.shuffle(list, rand);\n        System.out.println(list);\n    }\n}\n"}
{"id": 59952, "name": "Solve triangle solitare puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype solution struct{ peg, over, land int }\n\ntype move struct{ from, to int }\n\nvar emptyStart = 1\n\nvar board [16]bool\n\nvar jumpMoves = [16][]move{\n    {},\n    {{2, 4}, {3, 6}},\n    {{4, 7}, {5, 9}},\n    {{5, 8}, {6, 10}},\n    {{2, 1}, {5, 6}, {7, 11}, {8, 13}},\n    {{8, 12}, {9, 14}},\n    {{3, 1}, {5, 4}, {9, 13}, {10, 15}},\n    {{4, 2}, {8, 9}},\n    {{5, 3}, {9, 10}},\n    {{5, 2}, {8, 7}},\n    {{9, 8}},\n    {{12, 13}},\n    {{8, 5}, {13, 14}},\n    {{8, 4}, {9, 6}, {12, 11}, {14, 15}},\n    {{9, 5}, {13, 12}},\n    {{10, 6}, {14, 13}},\n}\n\nvar solutions []solution\n\nfunc initBoard() {\n    for i := 1; i < 16; i++ {\n        board[i] = true\n    }\n    board[emptyStart] = false\n}\n\nfunc (sol solution) split() (int, int, int) {\n    return sol.peg, sol.over, sol.land\n}\n\nfunc (mv move) split() (int, int) {\n    return mv.from, mv.to\n}\n\nfunc drawBoard() {\n    var pegs [16]byte\n    for i := 1; i < 16; i++ {\n        if board[i] {\n            pegs[i] = fmt.Sprintf(\"%X\", i)[0]\n        } else {\n            pegs[i] = '-'\n        }\n    }\n    fmt.Printf(\"       %c\\n\", pegs[1])\n    fmt.Printf(\"      %c %c\\n\", pegs[2], pegs[3])\n    fmt.Printf(\"     %c %c %c\\n\", pegs[4], pegs[5], pegs[6])\n    fmt.Printf(\"    %c %c %c %c\\n\", pegs[7], pegs[8], pegs[9], pegs[10])\n    fmt.Printf(\"   %c %c %c %c %c\\n\", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n}\n\nfunc solved() bool {\n    count := 0\n    for _, b := range board {\n        if b {\n            count++\n        }\n    }\n    return count == 1 \n}\n\nfunc solve() {\n    if solved() {\n        return\n    }\n    for peg := 1; peg < 16; peg++ {\n        if board[peg] {\n            for _, mv := range jumpMoves[peg] {\n                over, land := mv.split()\n                if board[over] && !board[land] {\n                    saveBoard := board\n                    board[peg] = false\n                    board[over] = false\n                    board[land] = true\n                    solutions = append(solutions, solution{peg, over, land})\n                    solve()\n                    if solved() {\n                        return \n                    }\n                    board = saveBoard\n                    solutions = solutions[:len(solutions)-1]\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    initBoard()\n    solve()\n    initBoard()\n    drawBoard()\n    fmt.Printf(\"Starting with peg %X removed\\n\\n\", emptyStart)\n    for _, solution := range solutions {\n        peg, over, land := solution.split()\n        board[peg] = false\n        board[over] = false\n        board[land] = true\n        drawBoard()\n        fmt.Printf(\"Peg %X jumped over %X to land on %X\\n\\n\", peg, over, land)\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\n\npublic class IQPuzzle {\n\n    public static void main(String[] args) {\n        System.out.printf(\"  \");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"  %,6d\", start);\n        }\n        System.out.printf(\"%n\");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"%2d\", start);\n            Map<Integer,Integer> solutions = solve(start);    \n            for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {\n                System.out.printf(\"  %,6d\", solutions.containsKey(end) ? solutions.get(end) : 0);\n            }\n            System.out.printf(\"%n\");\n        }\n        int moveNum = 0;\n        System.out.printf(\"%nOne Solution:%n\");\n        for ( Move m : oneSolution ) {\n            moveNum++;\n            System.out.printf(\"Move %d = %s%n\", moveNum, m);\n        }\n    }\n    \n    private static List<Move> oneSolution = null;\n    \n    private static Map<Integer, Integer> solve(int emptyPeg) {\n        Puzzle puzzle = new Puzzle(emptyPeg);\n        Map<Integer,Integer> solutions = new HashMap<>();\n        Stack<Puzzle> stack = new Stack<Puzzle>();\n        stack.push(puzzle);\n        while ( ! stack.isEmpty() ) {\n            Puzzle p = stack.pop();\n            if ( p.solved() ) {\n                solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);\n                if ( oneSolution == null ) {\n                    oneSolution = p.moves;\n                }\n                continue;\n            }\n            for ( Move move : p.getValidMoves() ) {\n                Puzzle pMove = p.move(move);\n                stack.add(pMove);\n            }\n        }\n        \n        return solutions;\n    }\n    \n    private static class Puzzle {\n        \n        public static int MAX_PEGS = 16;\n        private boolean[] pegs = new boolean[MAX_PEGS];  \n        \n        private List<Move> moves;\n\n        public Puzzle(int emptyPeg) {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            pegs[emptyPeg] = false;\n            moves = new ArrayList<>();\n        }\n\n        public Puzzle() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            moves = new ArrayList<>();\n        }\n\n        private static Map<Integer,List<Move>> validMoves = new HashMap<>(); \n        static {\n            validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));\n            validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));\n            validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));\n            validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));\n            validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));\n            validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));\n            validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));\n            validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));\n            validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));\n            validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));\n            validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));\n            validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));\n            validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));\n            validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));\n            validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));\n        }\n        \n        public List<Move> getValidMoves() {\n            List<Move> moves = new ArrayList<Move>();\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    for ( Move testMove : validMoves.get(i) ) {\n                        if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {\n                            moves.add(testMove);\n                        }\n                    }\n                }\n            }\n            return moves;\n        }\n\n        public boolean solved() {\n            boolean foundFirstPeg = false;\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    if ( foundFirstPeg ) {\n                        return false;\n                    }\n                    foundFirstPeg = true;\n                }\n            }\n            return true;\n        }\n        \n        public Puzzle move(Move move) {\n            Puzzle p = new Puzzle();\n            if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {\n                throw new RuntimeException(\"Invalid move.\");\n            }\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                p.pegs[i] = pegs[i];\n            }\n            p.pegs[move.start] = false;\n            p.pegs[move.jump] = false;\n            p.pegs[move.end] = true;\n            for ( Move m : moves ) {\n                p.moves.add(new Move(m.start, m.jump, m.end));\n            }\n            p.moves.add(new Move(move.start, move.jump, move.end));\n            return p;\n        }\n        \n        public int getLastPeg() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    return i;\n                }\n            }\n            throw new RuntimeException(\"ERROR:  Illegal position.\");\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"[\");\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                sb.append(pegs[i] ? 1 : 0);\n                sb.append(\",\");\n            }\n            sb.setLength(sb.length()-1);            \n            sb.append(\"]\");\n            return sb.toString();\n        }\n    }\n    \n    private static class Move {\n        int start;\n        int jump;\n        int end;\n        \n        public Move(int s, int j, int e) {\n            start = s; jump = j; end = e;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"{\");\n            sb.append(\"s=\" + start);\n            sb.append(\", j=\" + jump);\n            sb.append(\", e=\" + end);\n            sb.append(\"}\");\n            return sb.toString();\n        }\n    }\n\n}\n"}
{"id": 59953, "name": "Pseudorandom number generator image", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    img := image.NewNRGBA(image.Rect(0, 0, 1000, 1000))\n    for x := 0; x < 1000; x++ {\n        for y := 0; y < 1000; y++ {\n            col := color.RGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), 255}\n            img.Set(x, y, col)\n        }\n    }\n    fileName := \"pseudorandom_number_generator.png\"\n    imgFile, err := os.Create(fileName)\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer imgFile.Close()\n\n    if err := png.Encode(imgFile, img); err != nil {\n        imgFile.Close()\n        log.Fatal(err)\n    }\n}\n", "Java": "import javax.imageio.ImageIO;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport java.util.Random;\nimport java.util.Scanner;\n\n\npublic class csprngBBS {\n    public static Scanner input = new Scanner(System.in);\n    private static final String fileformat = \"png\";\n    private static String bitsStri = \"\";\n    private static String parityEven = \"\";\n    private static String leastSig = \"\";\n    private static String randomJavaUtil = \"\";\n    private static int width = 0;\n    private static int BIT_LENGTH = 0;\n    private static final Random rand = new SecureRandom();\n    private static BigInteger p = null; \n    private static BigInteger q = null; \n    private static BigInteger m = null;\n    private static BigInteger seed = null; \n    private static BigInteger seedFinal = null;\n    private static final Random randMathUtil = new SecureRandom();\n    public static void main(String[] args) throws IOException {\n        System.out.print(\"Width: \");\n        width = input.nextInt();\n        System.out.print(\"Bit-Length: \");\n        BIT_LENGTH = input.nextInt();\n        System.out.print(\"Generator format: \");\n        String useGenerator = input.next();\n        p = BigInteger.probablePrime(BIT_LENGTH, rand);\n        q = BigInteger.probablePrime(BIT_LENGTH, rand);\n        m = p.multiply(q);\n        seed = BigInteger.probablePrime(BIT_LENGTH,rand);\n        seedFinal = seed.add(BigInteger.ZERO);\n        if(useGenerator.contains(\"parity\") && useGenerator.contains(\"significant\")) {\n            findLeastSignificant();\n            findBitParityEven();\n            createImage(parityEven, \"parityEven\");\n            createImage(leastSig, \"significant\");\n        }\n\n        if(useGenerator.contains(\"parity\") && !useGenerator.contains(\"significant\")){\n            findBitParityEven();\n        }\n\n        if(useGenerator.contains(\"significant\") && !useGenerator.contains(\"parity\")){\n            findLeastSignificant();\n            createImage(leastSig, \"significant\");\n        }\n\n        if(useGenerator.contains(\"util\")){\n            findRandomJava(randMathUtil);\n            createImage(randomJavaUtil, \"randomUtilJava\");\n        }\n    }\n    public static void findRandomJava(Random random){\n        for(int x = 1; x <= Math.pow(width, 2); x++){\n            randomJavaUtil += random.nextInt(2);\n        }\n    }\n\n    public static void findBitParityEven(){\n        for(int x = 1; x <= Math.pow(width, 2); x++) {\n            seed = seed.pow(2).mod(m);\n            bitsStri = convertBinary(seed);\n            char[] bits = bitsStri.toCharArray();\n            int counter = 0;\n            for (char bit : bits) {\n                if (bit == '1') {\n                    counter++;\n                }\n            }\n            if (counter % 2 != 0) {\n                parityEven += \"1\";\n            } else {\n                parityEven += \"0\";\n            }\n        }\n    }\n\n    public static void findLeastSignificant(){\n        seed = seedFinal;\n        for(int x = 1; x <= Math.pow(width, 2); x++){\n            seed = seed.pow(2).mod(m);\n            leastSig += bitsStri.substring(bitsStri.length() - 1);\n        }\n    }\n\n    public static String convertBinary(BigInteger value){\n        StringBuilder total = new StringBuilder();\n        BigInteger two = BigInteger.TWO;\n        while(value.compareTo(BigInteger.ZERO) > 0){\n            total.append(value.mod(two));\n            value = value.divide(two);\n        }\n        return total.reverse().toString();\n    }\n\n    public static void createImage(String useThis, String fileName) throws IOException {\n        int length = csprngBBS.width;\n        \n        BufferedImage bufferedImage = new BufferedImage(length, length, 1);\n        \n        Graphics2D g2d = bufferedImage.createGraphics();\n        for (int y = 1; y <= length; y++) {\n            for (int x = 1; x <= length; x++) {\n                if (useThis.startsWith(\"1\")) {\n                    useThis = useThis.substring(1);\n                    g2d.setColor(Color.BLACK);\n                    g2d.fillRect(x, y, 1, 1);\n                } else if (useThis.startsWith(\"0\")) {\n                    useThis = useThis.substring(1);\n                    g2d.setColor(Color.WHITE);\n                    g2d.fillRect(x, y, 1, 1);\n                }\n            }\n            System.out.print(y + \"\\t\");\n        }\n        \n        g2d.dispose();\n        \n        File file = new File(\"REPLACEFILEPATHHERE\" + fileName + \".\" + fileformat);\n        ImageIO.write(bufferedImage, fileformat, file);\n    }\n}\n"}
{"id": 59954, "name": "Non-transitive dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n    found := make([]bool, 256)\n    for i := 1; i <= 4; i++ {\n        for j := 1; j <= 4; j++ {\n            for k := 1; k <= 4; k++ {\n                for l := 1; l <= 4; l++ {\n                    c := [4]int{i, j, k, l}\n                    sort.Ints(c[:])\n                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n                    if !found[key] {\n                        found[key] = true\n                        res = append(res, c)\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc cmp(x, y [4]int) int {\n    xw := 0\n    yw := 0\n    for i := 0; i < 4; i++ {\n        for j := 0; j < 4; j++ {\n            if x[i] > y[j] {\n                xw++\n            } else if y[j] > x[i] {\n                yw++\n            }\n        }\n    }\n    if xw < yw {\n        return -1\n    } else if xw > yw {\n        return 1\n    }\n    return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n    var c = len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                first := cmp(cs[i], cs[j])\n                if first == -1 {\n                    second := cmp(cs[j], cs[k])\n                    if second == -1 {\n                        third := cmp(cs[i], cs[k])\n                        if third == 1 {\n                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n    c := len(cs)\n    for i := 0; i < c; i++ {\n        for j := 0; j < c; j++ {\n            for k := 0; k < c; k++ {\n                for l := 0; l < c; l++ {\n                    first := cmp(cs[i], cs[j])\n                    if first == -1 {\n                        second := cmp(cs[j], cs[k])\n                        if second == -1 {\n                            third := cmp(cs[k], cs[l])\n                            if third == -1 {\n                                fourth := cmp(cs[i], cs[l])\n                                if fourth == 1 {\n                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return\n}\n\nfunc main() {\n    combs := fourFaceCombs()\n    fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n    it3 := findIntransitive3(combs)\n    fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n    for _, a := range it3 {\n        fmt.Println(a)\n    }\n    it4 := findIntransitive4(combs)\n    fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n    for _, a := range it4 {\n        fmt.Println(a)\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n    private static List<List<Integer>> fourFaceCombos() {\n        List<List<Integer>> res = new ArrayList<>();\n        Set<Integer> found = new HashSet<>();\n\n        for (int i = 1; i <= 4; i++) {\n            for (int j = 1; j <= 4; j++) {\n                for (int k = 1; k <= 4; k++) {\n                    for (int l = 1; l <= 4; l++) {\n                        List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());\n\n                        int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);\n                        if (found.add(key)) {\n                            res.add(c);\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static int cmp(List<Integer> x, List<Integer> y) {\n        int xw = 0;\n        int yw = 0;\n        for (int i = 0; i < 4; i++) {\n            for (int j = 0; j < 4; j++) {\n                if (x.get(i) > y.get(j)) {\n                    xw++;\n                } else if (x.get(i) < y.get(j)) {\n                    yw++;\n                }\n            }\n        }\n        return Integer.compare(xw, yw);\n    }\n\n    private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (List<Integer> kl : cs) {\n                        if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {\n                            res.add(List.of(cs.get(i), cs.get(j), kl));\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {\n        int c = cs.size();\n        List<List<List<Integer>>> res = new ArrayList<>();\n\n        for (int i = 0; i < c; i++) {\n            for (int j = 0; j < c; j++) {\n                if (cmp(cs.get(i), cs.get(j)) == -1) {\n                    for (int k = 0; k < cs.size(); k++) {\n                        if (cmp(cs.get(j), cs.get(k)) == -1) {\n                            for (List<Integer> ll : cs) {\n                                if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {\n                                    res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> combos = fourFaceCombos();\n        System.out.printf(\"Number of eligible 4-faced dice: %d%n\", combos.size());\n        System.out.println();\n\n        List<List<List<Integer>>> it3 = findIntransitive3(combos);\n        System.out.printf(\"%d ordered lists of 3 non-transitive dice found, namely:%n\", it3.size());\n        for (List<List<Integer>> a : it3) {\n            System.out.println(a);\n        }\n        System.out.println();\n\n        List<List<List<Integer>>> it4 = findIntransitive4(combos);\n        System.out.printf(\"%d ordered lists of 4 non-transitive dice found, namely:%n\", it4.size());\n        for (List<List<Integer>> a : it4) {\n            System.out.println(a);\n        }\n    }\n}\n"}
{"id": 59955, "name": "History variables", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"sync\"\n    \"time\"\n)\n\n\ntype history struct {\n    timestamp tsFunc\n    hs        []hset\n}\n\n\ntype tsFunc func() time.Time\n\n\ntype hset struct {\n    int           \n    t   time.Time \n}\n\n\nfunc newHistory(ts tsFunc) history {\n    return history{ts, []hset{{t: ts()}}}\n}   \n    \n\nfunc (h history) int() int {\n    return h.hs[len(h.hs)-1].int\n}\n    \n\nfunc (h *history) set(x int) time.Time {\n    t := h.timestamp()\n    h.hs = append(h.hs, hset{x, t})\n    return t\n}\n\n\nfunc (h history) dump() {\n    for _, hs := range h.hs {\n        fmt.Println(hs.t.Format(time.StampNano), hs.int)\n    }\n}   \n    \n\n\nfunc (h history) recall(t time.Time) (int,  bool) {\n    i := sort.Search(len(h.hs), func(i int) bool {\n        return h.hs[i].t.After(t)\n    })\n    if i > 0 {\n        return h.hs[i-1].int, true\n    }\n    return 0, false\n}\n\n\n\n\n\nfunc newTimestamper() tsFunc {\n    var last time.Time\n    return func() time.Time {\n        if t := time.Now(); t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n        }\n        return last\n    }\n}\n\n\n\nfunc newProtectedTimestamper() tsFunc {\n    var last time.Time\n    var m sync.Mutex\n    return func() (t time.Time) {\n        t = time.Now()\n        m.Lock() \n        if t.After(last) {\n            last = t\n        } else {\n            last.Add(1)\n            t = last\n        }\n        m.Unlock()\n        return\n    }\n}\n\nfunc main() {\n    \n    ts := newTimestamper()\n    \n    h := newHistory(ts)\n    \n    ref := []time.Time{h.set(3), h.set(1), h.set(4)}\n    \n    fmt.Println(\"History of variable h:\")\n    h.dump() \n    \n    \n    fmt.Println(\"Recalling values:\")\n    for _, t := range ref {\n        rv, _ := h.recall(t)\n        fmt.Println(rv)\n    }\n}\n", "Java": "public class HistoryVariable\n{\n    private Object value;\n\n    public HistoryVariable(Object v)\n    {\n        value = v;\n    }\n\n    public void update(Object v)\n    {\n        value = v;\n    }\n\n    public Object undo()\n    {\n        return value;\n    }\n\n    @Override\n    public String toString()\n    {\n        return value.toString();\n    }\n\n    public void dispose()\n    {\n    }\n}\n"}
{"id": 59956, "name": "Perceptron", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst c = 0.00001\n\nfunc linear(x float64) float64 {\n    return x*0.7 + 40\n}\n\ntype trainer struct {\n    inputs []float64\n    answer int\n}\n\nfunc newTrainer(x, y float64, a int) *trainer {\n    return &trainer{[]float64{x, y, 1}, a}\n}\n\ntype perceptron struct {\n    weights  []float64\n    training []*trainer\n}\n\nfunc newPerceptron(n, w, h int) *perceptron {\n    weights := make([]float64, n)\n    for i := 0; i < n; i++ {\n        weights[i] = rand.Float64()*2 - 1\n    }\n\n    training := make([]*trainer, 2000)\n    for i := 0; i < 2000; i++ {\n        x := rand.Float64() * float64(w)\n        y := rand.Float64() * float64(h)\n        answer := 1\n        if y < linear(x) {\n            answer = -1\n        }\n        training[i] = newTrainer(x, y, answer)\n    }\n    return &perceptron{weights, training}\n}\n\nfunc (p *perceptron) feedForward(inputs []float64) int {\n    if len(inputs) != len(p.weights) {\n        panic(\"weights and input length mismatch, program terminated\")\n    }\n    sum := 0.0\n    for i, w := range p.weights {\n        sum += inputs[i] * w\n    }\n    if sum > 0 {\n        return 1\n    }\n    return -1\n}\n\nfunc (p *perceptron) train(inputs []float64, desired int) {\n    guess := p.feedForward(inputs)\n    err := float64(desired - guess)\n    for i := range p.weights {\n        p.weights[i] += c * err * inputs[i]\n    }\n}\n\nfunc (p *perceptron) draw(dc *gg.Context, iterations int) {\n    le := len(p.training)\n    for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le {\n        p.train(p.training[count].inputs, p.training[count].answer)\n    }\n    x := float64(dc.Width())\n    y := linear(x)\n    dc.SetLineWidth(2)\n    dc.SetRGB255(0, 0, 0) \n    dc.DrawLine(0, linear(0), x, y)\n    dc.Stroke()\n    dc.SetLineWidth(1)\n    for i := 0; i < le; i++ {\n        guess := p.feedForward(p.training[i].inputs)\n        x := p.training[i].inputs[0] - 4\n        y := p.training[i].inputs[1] - 4\n        if guess > 0 {\n            dc.SetRGB(0, 0, 1) \n        } else {\n            dc.SetRGB(1, 0, 0) \n        }\n        dc.DrawCircle(x, y, 8)\n        dc.Stroke()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    w, h := 640, 360\n    perc := newPerceptron(3, w, h)\n    dc := gg.NewContext(w, h)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    perc.draw(dc, 2000)\n    dc.SavePNG(\"perceptron.png\")\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.util.*;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class Perceptron extends JPanel {\n\n    class Trainer {\n        double[] inputs;\n        int answer;\n\n        Trainer(double x, double y, int a) {\n            inputs = new double[]{x, y, 1};\n            answer = a;\n        }\n    }\n\n    Trainer[] training = new Trainer[2000];\n    double[] weights;\n    double c = 0.00001;\n    int count;\n\n    public Perceptron(int n) {\n        Random r = new Random();\n        Dimension dim = new Dimension(640, 360);\n        setPreferredSize(dim);\n        setBackground(Color.white);\n\n        weights = new double[n];\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] = r.nextDouble() * 2 - 1;\n        }\n\n        for (int i = 0; i < training.length; i++) {\n            double x = r.nextDouble() * dim.width;\n            double y = r.nextDouble() * dim.height;\n\n            int answer = y < f(x) ? -1 : 1;\n\n            training[i] = new Trainer(x, y, answer);\n        }\n\n        new Timer(10, (ActionEvent e) -> {\n            repaint();\n        }).start();\n    }\n\n    private double f(double x) {\n        return x * 0.7 + 40;\n    }\n\n    int feedForward(double[] inputs) {\n        assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n        double sum = 0;\n        for (int i = 0; i < weights.length; i++) {\n            sum += inputs[i] * weights[i];\n        }\n        return activate(sum);\n    }\n\n    int activate(double s) {\n        return s > 0 ? 1 : -1;\n    }\n\n    void train(double[] inputs, int desired) {\n        int guess = feedForward(inputs);\n        double error = desired - guess;\n        for (int i = 0; i < weights.length; i++) {\n            weights[i] += c * error * inputs[i];\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        \n        int x = getWidth();\n        int y = (int) f(x);\n        g.setStroke(new BasicStroke(2));\n        g.setColor(Color.orange);\n        g.drawLine(0, (int) f(0), x, y);\n\n        train(training[count].inputs, training[count].answer);\n        count = (count + 1) % training.length;\n\n        g.setStroke(new BasicStroke(1));\n        g.setColor(Color.black);\n        for (int i = 0; i < count; i++) {\n            int guess = feedForward(training[i].inputs);\n\n            x = (int) training[i].inputs[0] - 4;\n            y = (int) training[i].inputs[1] - 4;\n\n            if (guess > 0)\n                g.drawOval(x, y, 8, 8);\n            else\n                g.fillOval(x, y, 8, 8);\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(\"Perceptron\");\n            f.setResizable(false);\n            f.add(new Perceptron(3), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 59957, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 59958, "name": "Runtime evaluation", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) \n\n}\n", "Java": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport javax.tools.FileObject;\nimport javax.tools.ForwardingJavaFileManager;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.StandardLocation;\nimport javax.tools.ToolProvider;\n\npublic class Evaluator{\n    public static void main(String[] args){\n        new Evaluator().eval(\n            \"SayHello\",\n            \"public class SayHello{public void speak(){System.out.println(\\\"Hello world\\\");}}\",\n            \"speak\"\n        );\n    }\n\n    void eval(String className, String classCode, String methodName){\n        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();\n        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();\n\n        if ( null == compiler )\n            throw new RuntimeException(\"Could not get a compiler.\");\n\n        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);\n        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){\n            @Override\n            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)\n                    throws IOException{\n                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)\n                    return new SimpleJavaFileObject(URI.create(\"mem:\n                        @Override\n                        public OutputStream openOutputStream()\n                                throws IOException{\n                            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n                            classCache.put(className, baos);\n                            return baos;\n                        }\n                    };\n                else\n                    throw new IllegalArgumentException(\"Unexpected output file requested: \" + location + \", \" + className + \", \" + kind);\n            }\n        };\n        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{\n            add(\n                new SimpleJavaFileObject(URI.create(\"string:\n                    @Override\n                    public CharSequence getCharContent(boolean ignoreEncodingErrors){\n                        return classCode;\n                    }\n                }\n            );\n        }};\n\n        \n        compiler.getTask(null, fjfm, null, null, null, files).call();\n\n        try{\n            Class<?> clarse = new ClassLoader(){\n                @Override\n                public Class<?> findClass(String name){\n                    if (! name.startsWith(className))\n                        throw new IllegalArgumentException(\"This class loader is for \" + className + \" - could not handle \\\"\" + name + '\"');\n                    byte[] bytes = classCache.get(name).toByteArray();\n                    return defineClass(name, bytes, 0, bytes.length);\n                }\n            }.loadClass(className);\n\n            \n            clarse.getMethod(methodName).invoke(clarse.newInstance());\n\n        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){\n            throw new RuntimeException(\"Run failed: \" + x, x);\n        }\n    }\n}\n"}
{"id": 59959, "name": "Pisano period", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(a, b uint) uint {\n    if b == 0 {\n        return a\n    }\n    return gcd(b, a%b)\n}\n\nfunc lcm(a, b uint) uint {\n    return a / gcd(a, b) * b\n}\n\nfunc ipow(x, p uint) uint {\n    prod := uint(1)\n    for p > 0 {\n        if p&1 != 0 {\n            prod *= x\n        }\n        p >>= 1\n        x *= x\n    }\n    return prod\n}\n\n\nfunc getPrimes(n uint) []uint {\n    var primes []uint\n    for i := uint(2); i <= n; i++ {\n        div := n / i\n        mod := n % i\n        for mod == 0 {\n            primes = append(primes, i)\n            n = div\n            div = n / i\n            mod = n % i\n        }\n    }\n    return primes\n}\n\n\nfunc isPrime(n uint) 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 := uint(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\n\nfunc pisanoPeriod(m uint) uint {\n    var p, c uint = 0, 1\n    for i := uint(0); i < m*m; i++ {\n        p, c = c, (p+c)%m\n        if p == 0 && c == 1 {\n            return i + 1\n        }\n    }\n    return 1\n}\n\n\nfunc pisanoPrime(p uint, k uint) uint {\n    if !isPrime(p) || k == 0 {\n        return 0 \n    }\n    return ipow(p, k-1) * pisanoPeriod(p)\n}\n\n\nfunc pisano(m uint) uint {\n    primes := getPrimes(m)\n    primePowers := make(map[uint]uint)\n    for _, p := range primes {\n        primePowers[p]++\n    }\n    var pps []uint\n    for k, v := range primePowers {\n        pps = append(pps, pisanoPrime(k, v))\n    }\n    if len(pps) == 0 {\n        return 1\n    }\n    if len(pps) == 1 {\n        return pps[0]\n    }    \n    f := pps[0]\n    for i := 1; i < len(pps); i++ {\n        f = lcm(f, pps[i])\n    }\n    return f\n}\n\nfunc main() {\n    for p := uint(2); p < 15; p++ {\n        pp := pisanoPrime(p, 2)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%2d: 2) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    for p := uint(2); p < 180; p++ {\n        pp := pisanoPrime(p, 1)\n        if pp > 0 {\n            fmt.Printf(\"pisanoPrime(%3d: 1) = %d\\n\", p, pp)\n        }\n    }\n    fmt.Println()\n    fmt.Println(\"pisano(n) for integers 'n' from 1 to 180 are:\")\n    for n := uint(1); n <= 180; n++ {\n        fmt.Printf(\"%3d \", pisano(n))\n        if n != 1 && n%15 == 0 {\n            fmt.Println()\n        }\n    }    \n    fmt.Println()\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class PisanoPeriod {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Print pisano(p^2) for every prime p lower than 15%n\");\n        for ( long i = 2 ; i < 15 ; i++ ) { \n            if ( isPrime(i) ) {\n                long n = i*i; \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(p) for every prime p lower than 180%n\");\n        for ( long n = 2 ; n < 180 ; n++ ) { \n            if ( isPrime(n) ) { \n                System.out.printf(\"pisano(%d) = %d%n\", n, pisano(n));\n            }\n        }\n\n        System.out.printf(\"%nPrint pisano(n) for every integer from 1 to 180%n\");\n        for ( long n = 1 ; n <= 180 ; n++ ) { \n            System.out.printf(\"%3d  \", pisano(n));\n            if ( n % 10 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n\n        \n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test == 2 ) {\n            return true;\n        }\n        if ( test % 2 == 0 ) {\n            return false;\n        }\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    \n    private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();\n    static {\n        PERIOD_MEMO.put(2L, 3L);\n        PERIOD_MEMO.put(3L, 8L);\n        PERIOD_MEMO.put(5L, 20L);        \n    }\n    \n    \n    private static long pisano(long n) {\n        if ( PERIOD_MEMO.containsKey(n) ) {\n            return PERIOD_MEMO.get(n);\n        }\n        if ( n == 1 ) {\n            return 1;\n        }\n        Map<Long,Long> factors = getFactors(n);\n        \n        \n        \n        if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {\n            long result = 3 * n / 2;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 4*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {\n            long result = 6*n;\n            PERIOD_MEMO.put(n, result);\n            return result;\n        }\n        \n        List<Long> primes = new ArrayList<>(factors.keySet());\n        long prime = primes.get(0);\n        if ( factors.size() == 1 && factors.get(prime) == 1 ) {\n            List<Long> divisors = new ArrayList<>();\n            if ( n % 10 == 1 || n % 10 == 9 ) {\n                for ( long divisor : getDivisors(prime-1) ) {\n                    if ( divisor % 2 == 0 ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            else {\n                List<Long> pPlus1Divisors = getDivisors(prime+1);\n                for ( long divisor : getDivisors(2*prime+2) ) {\n                    if ( !  pPlus1Divisors.contains(divisor) ) {\n                        divisors.add(divisor);\n                    }\n                }\n            }\n            Collections.sort(divisors);\n            for ( long divisor : divisors ) {\n                if ( fibModIdentity(divisor, prime) ) {\n                    PERIOD_MEMO.put(prime, divisor);\n                    return divisor;\n                }\n            }\n            throw new RuntimeException(\"ERROR 144: Divisor not found.\");\n        }\n        long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);\n        for ( int i = 1 ; i < primes.size() ; i++ ) {\n            prime = primes.get(i);\n            period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));\n        }\n        PERIOD_MEMO.put(n, period);\n        return period;\n    }\n    \n    \n    private static boolean fibModIdentity(long n, long mod) {\n        long aRes = 0;\n        long bRes = 1;\n        long cRes = 1;\n        long aBase = 0;\n        long bBase = 1;\n        long cBase = 1;\n        while ( n > 0 ) {\n            if ( n % 2 == 1 ) {\n                long temp1 = 0, temp2 = 0, temp3 = 0;\n                if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {\n                    temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;\n                    temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;\n                    temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;\n                }\n                else {\n                    temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;\n                    temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;\n                    temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;\n                }\n                aRes = temp1;\n                bRes = temp2;\n                cRes = temp3;\n            }\n            n >>= 1L;\n            long temp1 = 0, temp2 = 0, temp3 = 0; \n            if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {\n                temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;\n                temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;\n                temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;\n            }\n            else {\n                temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;\n                temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;\n                temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;\n            }\n            aBase = temp1;\n            bBase = temp2;\n            cBase = temp3;\n        }\n        return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;\n    }\n\n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        \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        \n        return x % modulus;\n    }\n\n    private static final List<Long> getDivisors(long number) {\n        List<Long> divisors = new ArrayList<>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                long div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n    public static long lcm(long a, long b) {\n        return a*b/gcd(a,b);\n    }\n\n    public 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 final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();\n    static {\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        factors.put(2L, 1L);\n        allFactors.put(2L, factors);\n    }\n\n    public static Long MAX_ALL_FACTORS = 100000L;\n\n    public static final Map<Long,Long> getFactors(Long number) {\n        if ( allFactors.containsKey(number) ) {\n            return allFactors.get(number);\n        }\n        Map<Long,Long> factors = new TreeMap<Long,Long>();\n        if ( number % 2 == 0 ) {\n            Map<Long,Long> factorsdDivTwo = getFactors(number/2);\n            factors.putAll(factorsdDivTwo);\n            factors.merge(2L, 1L, (v1, v2) -> v1 + v2);\n            if ( number < MAX_ALL_FACTORS ) {\n                allFactors.put(number, factors);\n            }\n            return factors;\n        }\n        boolean prime = true;\n        long sqrt = (long) Math.sqrt(number);\n        for ( long i = 3 ; i <= sqrt ; i += 2 ) {\n            if ( number % i == 0 ) {\n                prime = false;\n                factors.putAll(getFactors(number/i));\n                factors.merge(i, 1L, (v1, v2) -> v1 + v2);\n                if ( number < MAX_ALL_FACTORS ) {\n                    allFactors.put(number, factors);\n                }\n                return factors;\n            }\n        }\n        if ( prime ) {\n            factors.put(number, 1L);\n            if ( number < MAX_ALL_FACTORS ) { \n                allFactors.put(number, factors);\n            }\n        }\n        return factors;\n    }\n\n}\n"}
{"id": 59960, "name": "Railway circuit", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    right    = 1\n    left     = -1\n    straight = 0\n)\n\nfunc normalize(tracks []int) string {\n    size := len(tracks)\n    a := make([]byte, size)\n    for i := 0; i < size; i++ {\n        a[i] = \"abc\"[tracks[i]+1]\n    }\n\n    \n\n    norm := string(a)\n    for i := 0; i < size; i++ {\n        s := string(a)\n        if s < norm {\n            norm = s\n        }\n        tmp := a[0]\n        copy(a, a[1:])\n        a[size-1] = tmp\n    }\n    return norm\n}\n\nfunc fullCircleStraight(tracks []int, nStraight int) bool {\n    if nStraight == 0 {\n        return true\n    }\n\n    \n    count := 0\n    for _, track := range tracks {\n        if track == straight {\n            count++\n        }\n    }\n    if count != nStraight {\n        return false\n    }\n\n    \n    var straightTracks [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == straight {\n            straightTracks[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if straightTracks[i] != straightTracks[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if straightTracks[i] != straightTracks[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc fullCircleRight(tracks []int) bool {\n    \n    sum := 0\n    for _, track := range tracks {\n        sum += track * 30\n    }\n    if sum%360 != 0 {\n        return false\n    }\n\n    \n    var rTurns [12]int\n    for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ {\n        if tracks[i] == right {\n            rTurns[idx%12]++\n        }\n        idx += tracks[i]\n    }\n    any1, any2 := false, false\n    for i := 0; i <= 5; i++ {\n        if rTurns[i] != rTurns[i+6] {\n            any1 = true\n            break\n        }\n    }\n    for i := 0; i <= 7; i++ {\n        if rTurns[i] != rTurns[i+4] {\n            any2 = true\n            break\n        }\n    }\n    return !any1 || !any2\n}\n\nfunc circuits(nCurved, nStraight int) {\n    solutions := make(map[string][]int)\n    gen := getPermutationsGen(nCurved, nStraight)\n    for gen.hasNext() {\n        tracks := gen.next()\n        if !fullCircleStraight(tracks, nStraight) {\n            continue\n        }\n        if !fullCircleRight(tracks) {\n            continue\n        }\n        tracks2 := make([]int, len(tracks))\n        copy(tracks2, tracks)\n        solutions[normalize(tracks)] = tracks2\n    }\n    report(solutions, nCurved, nStraight)\n}\n\nfunc getPermutationsGen(nCurved, nStraight int) PermutationsGen {\n    if (nCurved+nStraight-12)%4 != 0 {\n        panic(\"input must be 12 + k * 4\")\n    }\n    var trackTypes []int\n    switch nStraight {\n    case 0:\n        trackTypes = []int{right, left}\n    case 12:\n        trackTypes = []int{right, straight}\n    default:\n        trackTypes = []int{right, left, straight}\n    }\n    return NewPermutationsGen(nCurved+nStraight, trackTypes)\n}\n\nfunc report(sol map[string][]int, numC, numS int) {\n    size := len(sol)\n    fmt.Printf(\"\\n%d solution(s) for C%d,%d \\n\", size, numC, numS)\n    if numC <= 20 {\n        for _, tracks := range sol {\n            for _, track := range tracks {\n                fmt.Printf(\"%2d \", track)\n            }\n            fmt.Println()\n        }\n    }\n}\n\n\ntype PermutationsGen struct {\n    NumPositions int\n    choices      []int\n    indices      []int\n    sequence     []int\n    carry        int\n}\n\nfunc NewPermutationsGen(numPositions int, choices []int) PermutationsGen {\n    indices := make([]int, numPositions)\n    sequence := make([]int, numPositions)\n    carry := 0\n    return PermutationsGen{numPositions, choices, indices, sequence, carry}\n}\n\nfunc (p *PermutationsGen) next() []int {\n    p.carry = 1\n\n    \n    for i := 1; i < len(p.indices) && p.carry > 0; i++ {\n        p.indices[i] += p.carry\n        p.carry = 0\n        if p.indices[i] == len(p.choices) {\n            p.carry = 1\n            p.indices[i] = 0\n        }\n    }\n    for j := 0; j < len(p.indices); j++ {\n        p.sequence[j] = p.choices[p.indices[j]]\n    }\n    return p.sequence\n}\n\nfunc (p *PermutationsGen) hasNext() bool {\n    return p.carry != 1\n}\n\nfunc main() {\n    for n := 12; n <= 28; n += 4 {\n        circuits(n, 0)\n    }\n    circuits(12, 4)\n}\n", "Java": "package railwaycircuit;\n\nimport static java.util.Arrays.stream;\nimport java.util.*;\nimport static java.util.stream.IntStream.range;\n\npublic class RailwayCircuit {\n    final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0;\n\n    static String normalize(int[] tracks) {\n        char[] a = new char[tracks.length];\n        for (int i = 0; i < a.length; i++)\n            a[i] = \"abc\".charAt(tracks[i] + 1);\n\n        \n        String norm = new String(a);\n        for (int i = 0, len = a.length; i < len; i++) {\n\n            String s = new String(a);\n            if (s.compareTo(norm) < 0)\n                norm = s;\n\n            char tmp = a[0];\n            for (int j = 1; j < a.length; j++)\n                a[j - 1] = a[j];\n            a[len - 1] = tmp;\n        }\n        return norm;\n    }\n\n    static boolean fullCircleStraight(int[] tracks, int nStraight) {\n        if (nStraight == 0)\n            return true;\n\n        \n        if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight)\n            return false;\n\n        \n        int[] straight = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == STRAIGHT)\n                straight[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6])\n                && range(0, 8).anyMatch(i -> straight[i] != straight[i + 4]));\n    }\n\n    static boolean fullCircleRight(int[] tracks) {\n\n        \n        if (stream(tracks).map(i -> i * 30).sum() % 360 != 0)\n            return false;\n\n        \n        int[] rTurns = new int[12];\n        for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {\n            if (tracks[i] == RIGHT)\n                rTurns[idx % 12]++;\n            idx += tracks[i];\n        }\n\n        return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6])\n                && range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4]));\n    }\n\n    static void circuits(int nCurved, int nStraight) {\n        Map<String, int[]> solutions = new HashMap<>();\n\n        PermutationsGen gen = getPermutationsGen(nCurved, nStraight);\n        while (gen.hasNext()) {\n\n            int[] tracks = gen.next();\n\n            if (!fullCircleStraight(tracks, nStraight))\n                continue;\n\n            if (!fullCircleRight(tracks))\n                continue;\n\n            solutions.put(normalize(tracks), tracks.clone());\n        }\n        report(solutions, nCurved, nStraight);\n    }\n\n    static PermutationsGen getPermutationsGen(int nCurved, int nStraight) {\n        assert (nCurved + nStraight - 12) % 4 == 0 : \"input must be 12 + k * 4\";\n\n        int[] trackTypes = new int[]{RIGHT, LEFT};\n\n        if (nStraight != 0) {\n            if (nCurved == 12)\n                trackTypes = new int[]{RIGHT, STRAIGHT};\n            else\n                trackTypes = new int[]{RIGHT, LEFT, STRAIGHT};\n        }\n\n        return new PermutationsGen(nCurved + nStraight, trackTypes);\n    }\n\n    static void report(Map<String, int[]> sol, int numC, int numS) {\n\n        int size = sol.size();\n        System.out.printf(\"%n%d solution(s) for C%d,%d %n\", size, numC, numS);\n\n        if (size < 10)\n            sol.values().stream().forEach(tracks -> {\n                stream(tracks).forEach(i -> System.out.printf(\"%2d \", i));\n                System.out.println();\n            });\n    }\n\n    public static void main(String[] args) {\n        circuits(12, 0);\n        circuits(16, 0);\n        circuits(20, 0);\n        circuits(24, 0);\n        circuits(12, 4);\n    }\n}\n\nclass PermutationsGen {\n    \n    private int[] indices;\n    private int[] choices;\n    private int[] sequence;\n    private int carry;\n\n    PermutationsGen(int numPositions, int[] choices) {\n        indices = new int[numPositions];\n        sequence = new int[numPositions];\n        this.choices = choices;\n    }\n\n    int[] next() {\n        carry = 1;\n        \n        for (int i = 1; i < indices.length && carry > 0; i++) {\n            indices[i] += carry;\n            carry = 0;\n\n            if (indices[i] == choices.length) {\n                carry = 1;\n                indices[i] = 0;\n            }\n        }\n\n        for (int i = 0; i < indices.length; i++)\n            sequence[i] = choices[indices[i]];\n\n        return sequence;\n    }\n\n    boolean hasNext() {\n        return carry != 1;\n    }\n}\n"}
{"id": 59961, "name": "Free polyominoes enumeration", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype point struct{ x, y int }\ntype polyomino []point\ntype pointset map[point]bool\n\nfunc (p point) rotate90() point  { return point{p.y, -p.x} }\nfunc (p point) rotate180() point { return point{-p.x, -p.y} }\nfunc (p point) rotate270() point { return point{-p.y, p.x} }\nfunc (p point) reflect() point   { return point{-p.x, p.y} }\n\nfunc (p point) String() string { return fmt.Sprintf(\"(%d, %d)\", p.x, p.y) }\n\n\nfunc (p point) contiguous() polyomino {\n    return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y},\n        point{p.x, p.y - 1}, point{p.x, p.y + 1}}\n}\n\n\nfunc (po polyomino) minima() (int, int) {\n    minx := po[0].x\n    miny := po[0].y\n    for i := 1; i < len(po); i++ {\n        if po[i].x < minx {\n            minx = po[i].x\n        }\n        if po[i].y < miny {\n            miny = po[i].y\n        }\n    }\n    return minx, miny\n}\n\nfunc (po polyomino) translateToOrigin() polyomino {\n    minx, miny := po.minima()\n    res := make(polyomino, len(po))\n    for i, p := range po {\n        res[i] = point{p.x - minx, p.y - miny}\n    }\n    sort.Slice(res, func(i, j int) bool {\n        return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y)\n    })\n    return res\n}\n\n\nfunc (po polyomino) rotationsAndReflections() []polyomino {\n    rr := make([]polyomino, 8)\n    for i := 0; i < 8; i++ {\n        rr[i] = make(polyomino, len(po))\n    }\n    copy(rr[0], po)\n    for j := 0; j < len(po); j++ {\n        rr[1][j] = po[j].rotate90()\n        rr[2][j] = po[j].rotate180()\n        rr[3][j] = po[j].rotate270()\n        rr[4][j] = po[j].reflect()\n        rr[5][j] = po[j].rotate90().reflect()\n        rr[6][j] = po[j].rotate180().reflect()\n        rr[7][j] = po[j].rotate270().reflect()\n    }\n    return rr\n}\n\nfunc (po polyomino) canonical() polyomino {\n    rr := po.rotationsAndReflections()\n    minr := rr[0].translateToOrigin()\n    mins := minr.String()\n    for i := 1; i < 8; i++ {\n        r := rr[i].translateToOrigin()\n        s := r.String()\n        if s < mins {\n            minr = r\n            mins = s\n        }\n    }\n    return minr\n}\n\nfunc (po polyomino) String() string {\n    return fmt.Sprintf(\"%v\", []point(po))\n}\n\nfunc (po polyomino) toPointset() pointset {\n    pset := make(pointset, len(po))\n    for _, p := range po {\n        pset[p] = true\n    }\n    return pset\n}\n\n\nfunc (po polyomino) newPoints() polyomino {\n    pset := po.toPointset()\n    m := make(pointset) \n    for _, p := range po {\n        pts := p.contiguous()\n        for _, pt := range pts {\n            if !pset[pt] {\n                m[pt] = true \n            }\n        }\n    }\n    poly := make(polyomino, 0, len(m))\n    for k := range m {\n        poly = append(poly, k)\n    }\n    return poly\n}\n\nfunc (po polyomino) newPolys() []polyomino {\n    pts := po.newPoints()\n    res := make([]polyomino, len(pts))\n    for i, pt := range pts {\n        poly := make(polyomino, len(po))\n        copy(poly, po)\n        poly = append(poly, pt)\n        res[i] = poly.canonical()\n    }\n    return res\n}\n\nvar monomino = polyomino{point{0, 0}}\nvar monominoes = []polyomino{monomino}\n\n\nfunc rank(n int) []polyomino {\n    switch {\n    case n < 0:\n        panic(\"n cannot be negative. Program terminated.\")\n    case n == 0:\n        return []polyomino{}\n    case n == 1:\n        return monominoes\n    default:\n        r := rank(n - 1)\n        m := make(map[string]bool)\n        var polys []polyomino\n        for _, po := range r {\n            for _, po2 := range po.newPolys() {\n                if s := po2.String(); !m[s] {\n                    polys = append(polys, po2)\n                    m[s] = true\n                }\n            }\n        }\n        sort.Slice(polys, func(i, j int) bool {\n            return polys[i].String() < polys[j].String()\n        })\n        return polys\n    }\n}\n\nfunc main() {\n    const n = 5\n    fmt.Printf(\"All free polyominoes of rank %d:\\n\\n\", n)\n    for _, poly := range rank(n) {\n        for _, pt := range poly {\n            fmt.Printf(\"%s \", pt)\n        }\n        fmt.Println()\n    }\n    const k = 10\n    fmt.Printf(\"\\nNumber of free polyominoes of ranks 1 to %d:\\n\", k)\n    for i := 1; i <= k; i++ {\n        fmt.Printf(\"%d \", len(rank(i)))\n    }\n    fmt.Println()\n}\n", "Java": "import java.awt.Point;\nimport java.util.*;\nimport static java.util.Arrays.asList;\nimport java.util.function.Function;\nimport static java.util.Comparator.comparing;\nimport static java.util.stream.Collectors.toList;\n\npublic class FreePolyominoesEnum {\n    static final List<Function<Point, Point>> transforms = new ArrayList<>();\n\n    static {\n        transforms.add(p -> new Point(p.y, -p.x));\n        transforms.add(p -> new Point(-p.x, -p.y));\n        transforms.add(p -> new Point(-p.y, p.x));\n        transforms.add(p -> new Point(-p.x, p.y));\n        transforms.add(p -> new Point(-p.y, -p.x));\n        transforms.add(p -> new Point(p.x, -p.y));\n        transforms.add(p -> new Point(p.y, p.x));\n    }\n\n    static Point findMinima(List<Point> poly) {\n        return new Point(\n                poly.stream().mapToInt(a -> a.x).min().getAsInt(),\n                poly.stream().mapToInt(a -> a.y).min().getAsInt());\n    }\n\n    static List<Point> translateToOrigin(List<Point> poly) {\n        final Point min = findMinima(poly);\n        poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));\n        return poly;\n    }\n\n    static List<List<Point>> rotationsAndReflections(List<Point> poly) {\n        List<List<Point>> lst = new ArrayList<>();\n        lst.add(poly);\n        for (Function<Point, Point> t : transforms)\n            lst.add(poly.stream().map(t).collect(toList()));\n        return lst;\n    }\n\n    static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)\n            .thenComparingInt(p -> p.y);\n\n    static List<Point> normalize(List<Point> poly) {\n        return rotationsAndReflections(poly).stream()\n                .map(lst -> translateToOrigin(lst))\n                .map(lst -> lst.stream().sorted(byCoords).collect(toList()))\n                .min(comparing(Object::toString)) \n                .get();\n    }\n\n    static List<Point> neighborhoods(Point p) {\n        return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),\n                new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));\n    }\n\n    static List<Point> concat(List<Point> lst, Point pt) {\n        List<Point> r = new ArrayList<>();\n        r.addAll(lst);\n        r.add(pt);\n        return r;\n    }\n\n    static List<Point> newPoints(List<Point> poly) {\n        return poly.stream()\n                .flatMap(p -> neighborhoods(p).stream())\n                .filter(p -> !poly.contains(p))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> constructNextRank(List<Point> poly) {\n        return newPoints(poly).stream()\n                .map(p -> normalize(concat(poly, p)))\n                .distinct()\n                .collect(toList());\n    }\n\n    static List<List<Point>> rank(int n) {\n        if (n < 0)\n            throw new IllegalArgumentException(\"n cannot be negative\");\n\n        if (n < 2) {\n            List<List<Point>> r = new ArrayList<>();\n            if (n == 1)\n                r.add(asList(new Point(0, 0)));\n            return r;\n        }\n\n        return rank(n - 1).stream()\n                .parallel()\n                .flatMap(lst -> constructNextRank(lst).stream())\n                .distinct()\n                .collect(toList());\n    }\n\n    public static void main(String[] args) {\n        for (List<Point> poly : rank(5)) {\n            for (Point p : poly)\n                System.out.printf(\"(%d,%d) \", p.x, p.y);\n            System.out.println();\n        }\n    }\n}\n"}
{"id": 59962, "name": "Use a REST API", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar key string\n\nfunc init() {\n\t\n\t\n\tconst keyFile = \"api_key.txt\"\n\tf, err := os.Open(keyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkeydata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tkey = strings.TrimSpace(string(keydata))\n}\n\ntype EventResponse struct {\n\tResults []Result\n\t\n}\n\ntype Result struct {\n\tID          string\n\tStatus      string\n\tName        string\n\tEventURL    string `json:\"event_url\"`\n\tDescription string\n\tTime        EventTime\n\t\n}\n\n\n\ntype EventTime struct{ time.Time }\n\nfunc (et *EventTime) UnmarshalJSON(data []byte) error {\n\tvar msec int64\n\tif err := json.Unmarshal(data, &msec); err != nil {\n\t\treturn err\n\t}\n\tet.Time = time.Unix(0, msec*int64(time.Millisecond))\n\treturn nil\n}\n\nfunc (et EventTime) MarshalJSON() ([]byte, error) {\n\tmsec := et.UnixNano() / int64(time.Millisecond)\n\treturn json.Marshal(msec)\n}\n\n\nfunc (r *Result) String() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintln(&b, \"ID:\", r.ID)\n\tfmt.Fprintln(&b, \"URL:\", r.EventURL)\n\tfmt.Fprintln(&b, \"Time:\", r.Time.Format(time.UnixDate))\n\td := r.Description\n\tconst limit = 65\n\tif len(d) > limit {\n\t\td = d[:limit-1] + \"…\"\n\t}\n\tfmt.Fprintln(&b, \"Description:\", d)\n\treturn b.String()\n}\n\nfunc main() {\n\tv := url.Values{\n\t\t\n\t\t\n\t\t\"topic\": []string{\"photo\"},\n\t\t\"time\":  []string{\",1w\"},\n\t\t\"key\":   []string{key},\n\t}\n\tu := url.URL{\n\t\tScheme:   \"http\",\n\t\tHost:     \"api.meetup.com\",\n\t\tPath:     \"2/open_events.json\",\n\t\tRawQuery: v.Encode(),\n\t}\n\t\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Println(\"HTTP Status:\", resp.Status)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\n\tvar buf bytes.Buffer\n\tif err = json.Indent(&buf, body, \"\", \"  \"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\n\n\tvar evresp EventResponse\n\tjson.Unmarshal(body, &evresp)\n\t\n\n\tfmt.Println(\"Got\", len(evresp.Results), \"events\")\n\tif len(evresp.Results) > 0 {\n\t\tfmt.Println(\"First event:\\n\", &evresp.Results[0])\n\t}\n}\n", "Java": "package src;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.net.URI;\n\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\n\n\n\npublic class EventGetter {\n\t\n\n\tString city = \"\";\n\tString topic = \"\";\n\t\n\tpublic String getEvent(String path_code,String key) throws Exception{\n\t\tString responseString = \"\";\n\t\t\n\t\tURI request = new URIBuilder()\t\t\t\n\t\t\t.setScheme(\"http\")\n\t\t\t.setHost(\"api.meetup.com\")\n\t\t\t.setPath(path_code)\n\t\t\t\n\t\t\t.setParameter(\"topic\", topic)\n\t\t\t.setParameter(\"city\", city)\n\t\t\t\n\t\t\t.setParameter(\"key\", key)\n\t\t\t.build();\n\t\t\n\t\tHttpGet get = new HttpGet(request);\t\t\t\n\t\tSystem.out.println(\"Get request : \"+get.toString());\n\t\t\n\t\tCloseableHttpClient client = HttpClients.createDefault();\n\t\tCloseableHttpResponse response = client.execute(get);\n\t\tresponseString = EntityUtils.toString(response.getEntity());\n\t\t\n\t\treturn responseString;\n\t}\n\t\n\tpublic String getApiKey(String key_path){\n\t\tString key = \"\";\n\t\t\n\t\ttry{\n\t\t\tBufferedReader reader = new BufferedReader(new FileReader(key_path));\t\n\t\t\tkey = reader.readLine().toString();\t\t\t\t\t\t\t\t\t\n\t\t\treader.close();\n\t\t}\n\t\tcatch(Exception e){System.out.println(e.toString());}\n\t\t\n\t\treturn key;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t}\n\t\n}\n"}
{"id": 59963, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n"}
{"id": 59964, "name": "Twelve statements", "Go": "package main\n\nimport \"fmt\"\n\n\nvar solution = make(chan int)\nvar nearMiss = make(chan int)\nvar done = make(chan bool)\n\nfunc main() {\n    \n    for i := 0; i < 4096; i++ {\n        go checkPerm(i)\n    }\n    \n    var ms []int\n    for i := 0; i < 4096; {\n        select {\n        case <-done:\n            i++\n        case s := <-solution:\n            print12(\"solution\", s)\n        case m := <-nearMiss:\n            ms = append(ms, m)\n        }\n    }\n    for _, m := range ms {\n        print12(\"near miss\", m)\n    }\n}\n\nfunc print12(label string, bits int) {\n    fmt.Print(label, \":\")\n    for i := 1; i <= 12; i++ {\n        if bits&1 == 1 {\n            fmt.Print(\" \", i)\n        }\n        bits >>= 1\n    }\n    fmt.Println()\n}\n\nfunc checkPerm(tz int) {\n    \n    \n    ts := func(n uint) bool {\n        return tz>>(n-1)&1 == 1\n    }\n    \n    \n    ntrue := func(xs ...uint) int {\n        nt := 0\n        for _, x := range xs {\n            if ts(x) {\n                nt++\n            }\n        }\n        return nt\n    }\n    \n    \n    \n    \n    var con bool\n    \n    test := func(statement uint, b bool) {\n        switch {\n        case ts(statement) == b:\n        case con:\n            panic(\"bail\")\n        default:\n            con = true\n        }\n    }\n    \n    defer func() {\n        if x := recover(); x != nil {\n            if msg, ok := x.(string); !ok && msg != \"bail\" {\n                panic(x)\n            }\n        }\n        done <- true\n    }()\n\n    \n    test(1, true)\n\n    \n    test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)\n\n    \n    test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)\n\n    \n    test(4, !ts(5) || ts(6) && ts(7))\n\n    \n    test(5, !ts(4) && !ts(3) && !ts(2))\n\n    \n    test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)\n\n    \n    test(7, ts(2) != ts(3))\n\n    \n    test(8, !ts(7) || ts(5) && ts(6))\n\n    \n    test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)\n    \n    \n    test(10, ts(11) && ts(12))\n    \n    \n    test(11, ntrue(7, 8, 9) == 1)\n    \n    \n    test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)\n\n    \n    if con {\n        nearMiss <- tz\n    } else {\n        solution <- tz\n    }\n}\n", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n"}
{"id": 59965, "name": "Deming's funnel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n"}
{"id": 59966, "name": "Deming's funnel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,\n     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,\n    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,\n     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,\n    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,\n    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,\n     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,\n    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,\n     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,\n    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,\n     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,\n     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,\n     0.443, -0.521, -0.799,  0.087,\n}\n\nvar dys = []float64{\n     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,\n     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,\n     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,\n     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,\n    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,\n     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,\n     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,\n     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,\n    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,\n     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,\n    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,\n     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,\n    -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n    x := 0.0\n    result := make([]float64, len(fa))\n    for i, f := range fa {\n        result[i] = x + f\n        x = r(x, f)\n    }\n    return result\n}\n\nfunc mean(fa []float64) float64 {\n    sum := 0.0\n    for _, f := range fa {\n        sum += f\n    }\n    return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n    m := mean(fa)\n    sum := 0.0\n    for _, f := range fa {\n        sum += (f - m) * (f - m)\n    }\n    return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n    rxs := funnel(dxs, r)\n    rys := funnel(dys, r)\n    fmt.Println(label, \" :      x        y\")\n    fmt.Printf(\"Mean    :  %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n    fmt.Printf(\"Std Dev :  %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n    fmt.Println()\n}\n\nfunc main() {\n    experiment(\"Rule 1\", func(_, _ float64) float64 {\n        return 0.0\n    })\n    experiment(\"Rule 2\", func(_, dz float64) float64 {\n        return -dz\n    })\n    experiment(\"Rule 3\", func(z, dz float64) float64 {\n        return -(z + dz)\n    })\n    experiment(\"Rule 4\", func(z, dz float64) float64 {\n        return z + dz\n    })\n}\n", "Java": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n    public static void main(String[] args) {\n        double[] dxs = {\n            -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n            1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n            -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n            0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n            -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n            -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n            0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n            -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n            0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n            -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n            0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n            0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n            0.443, -0.521, -0.799, 0.087};\n\n        double[] dys = {\n            0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n            0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n            0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n            0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n            -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n            0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n            0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n            1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n            -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n            0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n            -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n            1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n            -0.947, -1.424, -0.542, -1.032};\n\n        experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n        experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n        experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n        experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n    }\n\n    static void experiment(String label, double[] dxs, double[] dys,\n            BiFunction<Double, Double, Double> rule) {\n\n        double[] resx = funnel(dxs, rule);\n        double[] resy = funnel(dys, rule);\n        System.out.println(label);\n        System.out.printf(\"Mean x, y:    %.4f, %.4f%n\", mean(resx), mean(resy));\n        System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n        System.out.println();\n    }\n\n    static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {\n        double x = 0;\n        double[] result = new double[input.length];\n\n        for (int i = 0; i < input.length; i++) {\n            double rx = x + input[i];\n            x = rule.apply(x, input[i]);\n            result[i] = rx;\n        }\n        return result;\n    }\n\n    static double mean(double[] xs) {\n        return Arrays.stream(xs).sum() / xs.length;\n    }\n\n    static double stdDev(double[] xs) {\n        double m = mean(xs);\n        return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n    }\n}\n"}
{"id": 59967, "name": "Rosetta Code_Fix code tags", "Go": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"log\"\nimport \"os\"\nimport \"regexp\"\nimport \"strings\"\n\nfunc main() {\n\terr := fix()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc fix() (err error) {\n\tbuf, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, err := Lang(string(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(out)\n\treturn nil\n}\n\nfunc Lang(in string) (out string, err error) {\n\treg := regexp.MustCompile(\"<[^>]+>\")\n\tout = reg.ReplaceAllStringFunc(in, repl)\n\treturn out, nil\n}\n\nfunc repl(in string) (out string) {\n\tif in == \"</code>\" {\n\t\t\n\t\treturn \"</\"+\"lang>\"\n\t}\n\n\t\n\tmid := in[1 : len(in)-1]\n\n\t\n\tvar langs = []string{\n\t\t\"abap\", \"actionscript\", \"actionscript3\", \"ada\", \"apache\", \"applescript\",\n\t\t\"apt_sources\", \"asm\", \"asp\", \"autoit\", \"avisynth\", \"bash\", \"basic4gl\",\n\t\t\"bf\", \"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\", \"cfm\",\n\t\t\"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\", \"d\", \"delphi\",\n\t\t\"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\", \"fortran\", \"freebasic\",\n\t\t\"genero\", \"gettext\", \"glsl\", \"gml\", \"gnuplot\", \"go\", \"groovy\", \"haskell\",\n\t\t\"hq9plus\", \"html4strict\", \"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\",\n\t\t\"java5\", \"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\", \"m68k\",\n\t\t\"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\", \"mysql\", \"nsis\",\n\t\t\"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\", \"oracle11\", \"oracle8\", \"pascal\",\n\t\t\"per\", \"perl\", \"php\", \"php-brief\", \"pic16\", \"pixelbender\", \"plsql\",\n\t\t\"povray\", \"powershell\", \"progress\", \"prolog\", \"providex\", \"python\",\n\t\t\"qbasic\", \"rails\", \"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\",\n\t\t\"scilab\", \"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\", \"verilog\",\n\t\t\"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\", \"whitespace\", \"winbatch\",\n\t\t\"xml\", \"xorg_conf\", \"xpp\", \"z80\",\n\t}\n\tfor _, lang := range langs {\n\t\tif mid == lang {\n\t\t\t\n\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"/\") {\n\t\t\tif mid[len(\"/\"):] == lang {\n\t\t\t\t\n\t\t\t\treturn \"</\"+\"lang>\"\n\t\t\t}\n\t\t}\n\n\t\tif strings.HasPrefix(mid, \"code \") {\n\t\t\tif mid[len(\"code \"):] == lang {\n\t\t\t\t\n\t\t\t\treturn fmt.Sprintf(\"<lang %s>\", lang)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn in\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\n\npublic class FixCodeTags \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tString sourcefile=args[0];\n\t\tString convertedfile=args[1];\n\t\tconvert(sourcefile,convertedfile);\n\t}\n\t\tstatic String[] languages = {\"abap\", \"actionscript\", \"actionscript3\",\n\t\t\t\"ada\", \"apache\", \"applescript\", \"apt_sources\", \"asm\", \"asp\",\n\t\t\t\"autoit\", \"avisynth\", \"bar\", \"bash\", \"basic4gl\", \"bf\",\n\t\t\t\"blitzbasic\", \"bnf\", \"boo\", \"c\", \"caddcl\", \"cadlisp\", \"cfdg\",\n\t\t\t\"cfm\", \"cil\", \"c_mac\", \"cobol\", \"cpp\", \"cpp-qt\", \"csharp\", \"css\",\n\t\t\t\"d\", \"delphi\", \"diff\", \"_div\", \"dos\", \"dot\", \"eiffel\", \"email\",\n\t\t\t\"foo\", \"fortran\", \"freebasic\", \"genero\", \"gettext\", \"glsl\", \"gml\",\n\t\t\t\"gnuplot\", \"go\", \"groovy\", \"haskell\", \"hq9plus\", \"html4strict\",\n\t\t\t\"idl\", \"ini\", \"inno\", \"intercal\", \"io\", \"java\", \"java5\",\n\t\t\t\"javascript\", \"kixtart\", \"klonec\", \"klonecpp\", \"latex\", \"lisp\",\n\t\t\t\"lolcode\", \"lotusformulas\", \"lotusscript\", \"lscript\", \"lua\",\n\t\t\t\"m68k\", \"make\", \"matlab\", \"mirc\", \"modula3\", \"mpasm\", \"mxml\",\n\t\t\t\"mysql\", \"nsis\", \"objc\", \"ocaml\", \"ocaml-brief\", \"oobas\",\n\t\t\t\"oracle11\", \"oracle8\", \"pascal\", \"per\", \"perl\", \"php\", \"php-brief\",\n\t\t\t\"pic16\", \"pixelbender\", \"plsql\", \"povray\", \"powershell\",\n\t\t\t\"progress\", \"prolog\", \"providex\", \"python\", \"qbasic\", \"rails\",\n\t\t\t\"reg\", \"robots\", \"ruby\", \"sas\", \"scala\", \"scheme\", \"scilab\",\n\t\t\t\"sdlbasic\", \"smalltalk\", \"smarty\", \"sql\", \"tcl\", \"teraterm\",\n\t\t\t\"text\", \"thinbasic\", \"tsql\", \"typoscript\", \"vb\", \"vbnet\",\n\t\t\t\"verilog\", \"vhdl\", \"vim\", \"visualfoxpro\", \"visualprolog\",\n\t\t\t\"whitespace\", \"winbatch\", \"xml\", \"xorg_conf\", \"xpp\", \"z80\"};\n\tstatic void convert(String sourcefile,String convertedfile)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedReader br=new BufferedReader(new FileReader(sourcefile));\n\t\t\t\n\t\t\tStringBuffer sb=new StringBuffer(\"\");\n\t\t\tString line;\n\t\t\twhile((line=br.readLine())!=null)\n\t\t\t{\n\t\t\t\tfor(int i=0;i<languages.length;i++)\n\t\t\t\t{\n\t\t\t\t\tString lang=languages[i];\n\t\t\t\t\tline=line.replaceAll(\"<\"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</\"+lang+\">\", \"</\"+\"lang>\");\n\t\t\t\t\tline=line.replaceAll(\"<code \"+lang+\">\", \"<lang \"+lang+\">\");\n\t\t\t\t\tline=line.replaceAll(\"</code>\", \"</\"+\"lang>\");\n\t\t\t\t}\n\t\t\t\tsb.append(line);\n\t\t\t}\n\t\t\tbr.close();\n\t\t\t\n\t\t\tFileWriter fw=new FileWriter(new File(convertedfile));\n\t\t\t\n\t\t\tfw.write(sb.toString());\n\t\t\tfw.close();\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tSystem.out.println(\"Something went horribly wrong: \"+e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 59968, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59969, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59970, "name": "Permutations with repetitions", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    n      = 3\n    values = []string{\"A\", \"B\", \"C\", \"D\"}\n    k      = len(values)\n    decide = func(p []string) bool {\n        return p[0] == \"B\" && p[1] == \"C\"\n    }\n)\n\nfunc main() {\n    pn := make([]int, n)\n    p := make([]string, n)\n    for {\n        \n        for i, x := range pn {\n            p[i] = values[x]\n        }\n        \n        fmt.Println(p)\n        \n        if decide(p) {\n            return \n        }\n        \n        for i := 0; ; {\n            pn[i]++\n            if pn[i] < k {\n                break\n            }\n            pn[i] = 0\n            i++\n            if i == n {\n                return \n            }\n        }\n    }\n}\n", "Java": "import java.util.function.Predicate;\n\npublic class PermutationsWithRepetitions {\n\n    public static void main(String[] args) {\n        char[] chars = {'a', 'b', 'c', 'd'};\n        \n        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);\n    }\n\n    static void permute(char[] a, int k, Predicate<int[]> decider) {\n        int n = a.length;\n        if (k < 1 || k > n)\n            throw new IllegalArgumentException(\"Illegal number of positions.\");\n\n        int[] indexes = new int[n];\n        int total = (int) Math.pow(n, k);\n\n        while (total-- > 0) {\n            for (int i = 0; i < n - (n - k); i++)\n                System.out.print(a[indexes[i]]);\n            System.out.println();\n\n            if (decider.test(indexes))\n                break;\n\n            for (int i = 0; i < n; i++) {\n                if (indexes[i] >= n - 1) {\n                    indexes[i] = 0;\n                } else {\n                    indexes[i]++;\n                    break;\n                }\n            }\n        }\n    }\n}\n"}
{"id": 59971, "name": "Selective file copy", "Go": "package main\n\nimport (\n    \"encoding/json\"\n    \"log\"\n    \"os\"\n    \"bytes\"\n    \"errors\"\n    \"strings\"\n)\n\n\ntype s1 struct {\n    A string\n    B string\n    C int\n    D string\n}\n\n\ntype s2 struct {\n    A string\n    C intString \n    X string\n}\n\ntype intString string\n\nfunc (i *intString) UnmarshalJSON(b []byte) error {\n    if len(b) == 0 || bytes.IndexByte([]byte(\"0123456789-\"), b[0]) < 0 {\n        return errors.New(\"Unmarshal intString expected JSON number\")\n    }\n    *i = intString(b)\n    return nil\n}\n\n\nfunc NewS2() *s2 {\n    return &s2{X: \"XXXXX\"}\n}\n\nfunc main() {\n    \n    o1, err := os.Create(\"o1.json\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    e := json.NewEncoder(o1)\n    for i := 1; i <= 5; i++ {\n        err := e.Encode(s1{\n            strings.Repeat(\"A\", i),\n            strings.Repeat(\"B\", i),\n            i,\n            strings.Repeat(\"D\", i),\n        })\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    o1.Close()\n\n    \n    in, err := os.Open(\"o1.json\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    out, err := os.Create(\"out.json\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    \n    d := json.NewDecoder(in)\n    e = json.NewEncoder(out)\n    for d.More() {\n        \n        \n        \n        \n        s := NewS2()\n        if err = d.Decode(s); err != nil {\n            log.Fatal(err)\n        }\n        if err = e.Encode(s); err != nil {\n            log.Fatal(err)\n        }\n    }\n}\n", "Java": "import java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Scanner;\n\nclass CopysJ {\n\n  public static void main(String[] args) {\n    String ddname_IN  = \"copys.in.txt\";\n    String ddname_OUT = \"copys.out.txt\";\n    if (args.length >= 1) { ddname_IN  = args[0].length() > 0 ? args[0] : ddname_IN; }\n    if (args.length >= 2) { ddname_OUT = args[1].length() > 0 ? args[1] : ddname_OUT; }\n\n    File dd_IN = new File(ddname_IN);\n    File dd_OUT = new File(ddname_OUT);\n\n    try (\n      Scanner scanner_IN = new Scanner(dd_IN);\n      BufferedWriter writer_OUT = new BufferedWriter(new FileWriter(dd_OUT))\n      ) {\n      String a;\n      String b;\n      String c;\n      String d;\n      String c1;\n      String x = \"XXXXX\";\n      String data_IN;\n      String data_OUT;\n      int ib;\n\n      while (scanner_IN.hasNextLine()) {\n        data_IN = scanner_IN.nextLine();\n        ib = 0;\n        a = data_IN.substring(ib, ib += 5);\n        b = data_IN.substring(ib, ib += 5);\n        c = data_IN.substring(ib, ib += 4);\n        c1=Integer.toHexString(new Byte((c.getBytes())[0]).intValue());\n        if (c1.length()<2) { c1=\"0\" + c1; }\n        data_OUT = a + c1 + x;\n        writer_OUT.write(data_OUT);\n        writer_OUT.newLine();\n        System.out.println(data_IN);\n        System.out.println(data_OUT);\n        System.out.println();\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n    return;\n  }\n}\n"}
{"id": 59972, "name": "Idiomatically determine all the characters that can be used for symbols", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"go/ast\"\n\t\"go/parser\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc isValidIdentifier(identifier string) bool {\n\tnode, err := parser.ParseExpr(identifier)\n\tif err != nil {\n\t\treturn false\n\t}\n\tident, ok := node.(*ast.Ident)\n\treturn ok && ident.Name == identifier\n}\n\ntype runeRanges struct {\n\tranges   []string\n\thasStart bool\n\tstart    rune\n\tend      rune\n}\n\nfunc (r *runeRanges) add(cp rune) {\n\tif !r.hasStart {\n\t\tr.hasStart = true\n\t\tr.start = cp\n\t\tr.end = cp\n\t\treturn\n\t}\n\n\tif cp == r.end+1 {\n\t\tr.end = cp\n\t\treturn\n\t}\n\n\tr.writeTo(&r.ranges)\n\n\tr.start = cp\n\tr.end = cp\n}\n\nfunc (r *runeRanges) writeTo(ranges *[]string) {\n\tif r.hasStart {\n\t\tif r.start == r.end {\n\t\t\t*ranges = append(*ranges, fmt.Sprintf(\"%U\", r.end))\n\t\t} else {\n\t\t\t*ranges = append(*ranges, fmt.Sprintf(\"%U-%U\", r.start, r.end))\n\t\t}\n\t}\n}\n\nfunc (r *runeRanges) String() string {\n\tranges := r.ranges\n\tr.writeTo(&ranges)\n\treturn strings.Join(ranges, \", \")\n}\n\nfunc main() {\n\tvar validFirst runeRanges\n\tvar validFollow runeRanges\n\tvar validOnlyFollow runeRanges\n\n\tfor r := rune(0); r <= unicode.MaxRune; r++ {\n\t\tfirst := isValidIdentifier(string([]rune{r}))\n\t\tfollow := isValidIdentifier(string([]rune{'_', r}))\n\t\tif first {\n\t\t\tvalidFirst.add(r)\n\t\t}\n\t\tif follow {\n\t\t\tvalidFollow.add(r)\n\t\t}\n\t\tif follow && !first {\n\t\t\tvalidOnlyFollow.add(r)\n\t\t}\n\t}\n\n\t_, _ = fmt.Println(\"Valid first:\", validFirst.String())\n\t_, _ = fmt.Println(\"Valid follow:\", validFollow.String())\n\t_, _ = fmt.Println(\"Only follow:\", validOnlyFollow.String())\n}\n", "Java": "import java.util.function.IntPredicate;\nimport java.util.stream.IntStream;\n\npublic class Test {\n    public static void main(String[] args) throws Exception {\n        print(\"Java Identifier start:     \", 0, 0x10FFFF, 72,\n                Character::isJavaIdentifierStart, \"%c\");\n\n        print(\"Java Identifier part:      \", 0, 0x10FFFF, 25,\n                Character::isJavaIdentifierPart, \"[%d]\");\n\n        print(\"Identifier ignorable:      \", 0, 0x10FFFF, 25,\n                Character::isIdentifierIgnorable, \"[%d]\");\n\n        print(\"Unicode Identifier start:  \", 0, 0x10FFFF, 72,\n                Character::isUnicodeIdentifierStart, \"%c\");\n\n        print(\"Unicode Identifier part :  \", 0, 0x10FFFF, 25,\n                Character::isUnicodeIdentifierPart, \"[%d]\");\n    }\n\n    static void print(String msg, int start, int end, int limit, \n        IntPredicate p, String fmt) {\n\n        System.out.print(msg);\n        IntStream.rangeClosed(start, end)\n                .filter(p)\n                .limit(limit)\n                .forEach(cp -> System.out.printf(fmt, cp));\n        System.out.println(\"...\");\n    }\n}\n"}
{"id": 59973, "name": "Assertions in design by contract", "Go": "func assert(t bool, s string) {\n\tif !t {\n\t\tpanic(s)\n\t}\n}\n\n\tassert(c == 0, \"some text here\")\n", "Java": "(...)\nint feedForward(double[] inputs) {\n    assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n    double sum = 0;\n    for (int i = 0; i < weights.length; i++) {\n        sum += inputs[i] * weights[i];\n    }\n    return activate(sum);\n}\n(...)\n"}
{"id": 59974, "name": "Assertions in design by contract", "Go": "func assert(t bool, s string) {\n\tif !t {\n\t\tpanic(s)\n\t}\n}\n\n\tassert(c == 0, \"some text here\")\n", "Java": "(...)\nint feedForward(double[] inputs) {\n    assert inputs.length == weights.length : \"weights and input length mismatch\";\n\n    double sum = 0;\n    for (int i = 0; i < weights.length; i++) {\n        sum += inputs[i] * weights[i];\n    }\n    return activate(sum);\n}\n(...)\n"}
{"id": 59975, "name": "Quoting constructs", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n)\n\n\n\n\n\n\n\n\nvar (\n    rl1 = 'a'\n    rl2 = '\\'' \n)\n\n\n\nvar (\n    is1 = \"abc\"\n    is2 = \"\\\"ab\\tc\\\"\" \n)\n\n\n\n\n\n\n\nvar (\n    rs1 = `\nfirst\"\nsecond'\nthird\"\n`\n    rs2 = `This is one way of including a ` + \"`\" + ` in a raw string literal.`\n    rs3 = `\\d+` \n)\n\nfunc main() {\n    fmt.Println(rl1, rl2) \n    fmt.Println(is1, is2)\n    fmt.Println(rs1)\n    fmt.Println(rs2)\n    re := regexp.MustCompile(rs3)\n    fmt.Println(re.FindString(\"abcd1234efgh\"))\n\n    \n\n    \n    n := 3\n    fmt.Printf(\"\\nThere are %d quoting constructs in Go.\\n\", n)\n\n    \n    \n    s := \"constructs\"\n    fmt.Println(\"There are\", n, \"quoting\", s, \"in Go.\")\n\n    \n    \n    mapper := func(placeholder string) string {\n        switch placeholder {\n        case \"NUMBER\":\n            return strconv.Itoa(n)\n        case \"TYPES\":\n            return s\n        }\n        return \"\"\n    }\n    fmt.Println(os.Expand(\"There are ${NUMBER} quoting ${TYPES} in Go.\", mapper))\n}\n", "Java": "module test\n    {\n    @Inject Console console;\n    void run()\n        {\n        \n        Char ch = 'x';\n        console.print( $\"ch={ch.quoted()}\");\n\n        \n        String greeting = \"Hello\";\n        console.print( $\"greeting={greeting.quoted()}\");\n\n        \n        \n        \n        String lines = \\|first line\n                        |second line\\\n                        | continued\n                       ;\n        console.print($|lines=\n                       |{lines}\n                     );\n\n        \n        \n        String name = \"Bob\";\n        String msg  = $|{greeting} {name},\n                       |Have a nice day!\n                       |{ch}{ch}{ch}\n                      ;\n        console.print($|msg=\n                       |{msg}\n                     );\n        }\n    }\n"}
{"id": 59976, "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": 59977, "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#": "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": 59978, "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#": "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": 59979, "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", "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": 59980, "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", "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": 59981, "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", "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": 59982, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        for (int i = 1; i <= 10; i++) {\n            Console.Write(i);\n\n            if (i % 5 == 0) {\n                Console.WriteLine();\n                continue;\n            }\n\n            Console.Write(\", \");\n        }\n    }\n}\n"}
{"id": 59983, "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", "C#": "using System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59984, "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", "C#": "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Rosetta.CheckPointSync;\n\npublic class Program\n{\n    public async Task Main()\n    {\n        RobotBuilder robotBuilder = new RobotBuilder();\n        Task work = robotBuilder.BuildRobots(\n            \"Optimus Prime\", \"R. Giskard Reventlov\", \"Data\", \"Marvin\",\n            \"Bender\", \"Number Six\", \"C3-PO\", \"Dolores\");\n        await work;\n    }\n\n    public class RobotBuilder\n    {\n        static readonly string[] parts = { \"Head\", \"Torso\", \"Left arm\", \"Right arm\", \"Left leg\", \"Right leg\" };\n        static readonly Random rng = new Random();\n        static readonly object key = new object();\n\n        public Task BuildRobots(params string[] robots)\n        {\n            int r = 0;\n            Barrier checkpoint = new Barrier(parts.Length, b => {\n                Console.WriteLine($\"{robots[r]} assembled. Hello, {robots[r]}!\");\n                Console.WriteLine();\n                r++;\n            });\n            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();\n            return Task.WhenAll(tasks);\n        }\n\n        private static int GetTime()\n        {\n            \n            \n            lock (key) {\n                return rng.Next(100, 1000);\n            }\n        }\n\n        private async Task BuildPart(Barrier barrier, string part, string[] robots)\n        {\n            foreach (var robot in robots) {\n                int time = GetTime();\n                Console.WriteLine($\"Constructing {part} for {robot}. This will take {time}ms.\");\n                await Task.Delay(time);\n                Console.WriteLine($\"{part} for {robot} finished.\");\n                barrier.SignalAndWait();\n            }\n        }\n\n    }\n    \n}\n"}
{"id": 59985, "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", "C#": "namespace Vlq\n{\n  using System;\n  using System.Collections.Generic;\n  using System.Linq;\n\n  public static class VarLenQuantity\n  {\n    public static ulong ToVlq(ulong integer)\n    {\n      var array = new byte[8];\n      var buffer = ToVlqCollection(integer)\n        .SkipWhile(b => b == 0)\n        .Reverse()\n        .ToArray();\n      Array.Copy(buffer, array, buffer.Length);\n      return BitConverter.ToUInt64(array, 0);\n    }\n\n    public static ulong FromVlq(ulong integer)\n    {\n      var collection = BitConverter.GetBytes(integer).Reverse();\n      return FromVlqCollection(collection);\n    }\n\n    public static IEnumerable<byte> ToVlqCollection(ulong integer)\n    {\n      if (integer > Math.Pow(2, 56))\n        throw new OverflowException(\"Integer exceeds max value.\");\n\n      var index = 7;\n      var significantBitReached = false;\n      var mask = 0x7fUL << (index * 7);\n      while (index >= 0)\n      {\n        var buffer = (mask & integer);\n        if (buffer > 0 || significantBitReached)\n        {\n          significantBitReached = true;\n          buffer >>= index * 7;\n          if (index > 0)\n            buffer |= 0x80;\n          yield return (byte)buffer;\n        }\n        mask >>= 7;\n        index--;\n      }\n    }\n\n\n    public static ulong FromVlqCollection(IEnumerable<byte> vlq)\n    {\n      ulong integer = 0;\n      var significantBitReached = false;\n\n      using (var enumerator = vlq.GetEnumerator())\n      {\n        int index = 0;\n        while (enumerator.MoveNext())\n        {\n          var buffer = enumerator.Current;\n          if (buffer > 0 || significantBitReached)\n          {\n            significantBitReached = true;\n            integer <<= 7;\n            integer |= (buffer & 0x7fUL);\n          }\n\n          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))\n            break;\n        }\n      }\n      return integer;\n    }\n\n    public static void Main()\n    {\n      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };\n\n      foreach (var original in integers)\n      {\n        Console.WriteLine(\"Original: 0x{0:X}\", original);\n\n        \n        var seq = ToVlqCollection(original);\n        Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(b => b.ToString(\"X2\")).Aggregate(string.Concat));\n\n        var decoded = FromVlqCollection(seq);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        \n        var encoded = ToVlq(original);\n        Console.WriteLine(\"Encoded: 0x{0:X}\", encoded);\n\n        decoded = FromVlq(encoded);\n        Console.WriteLine(\"Decoded: 0x{0:X}\", decoded);\n\n        Console.WriteLine();\n      }\n      Console.WriteLine(\"Press any key to continue...\");\n      Console.ReadKey();\n    }\n  }\n}\n"}
{"id": 59986, "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", "C#": "using System;\n\nnamespace StringCase\n{\n  class Program\n  {\n    public static void Main()\n    {\n      String input = scope .(\"alphaBETA\");\n      input.ToUpper();\n      Console.WriteLine(input);\n      input.ToLower();\n      Console.WriteLine(input);\n    }\n  }\n}\n"}
{"id": 59987, "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", "C#": "using System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n"}
{"id": 59988, "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", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        CultureInfo ci=CultureInfo.CreateSpecificCulture(\"en-US\");\n        string dateString = \"March 7 2009 7:30pm EST\";\n        string format = \"MMMM d yyyy h:mmtt z\";\n        DateTime myDateTime = DateTime.ParseExact(dateString.Replace(\"EST\",\"+6\"),format,ci) ;\n        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;\n        Console.WriteLine(newDateTime.ToString(format).Replace(\"-5\",\"EST\")); \n\n        Console.ReadLine();\n    }\n}\n"}
{"id": 59989, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nclass Program\n{\n    static void ThreadStart(object item)\n    {\n        Thread.Sleep(1000 * (int)item);\n        Console.WriteLine(item);\n    }\n\n    static void SleepSort(IEnumerable<int> items)\n    {\n        foreach (var item in items)\n        {\n            new Thread(ThreadStart).Start(item);\n        }\n    }\n\n    static void Main(string[] arguments)\n    {\n        SleepSort(arguments.Select(int.Parse));\n    }\n}\n"}
{"id": 59990, "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", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args) {\n        int[,] a = new int[10, 10];\n        Random r = new Random();\n\n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                a[i, j] = r.Next(0, 21) + 1;\n            }\n        }\n        \n        for (int i = 0; i < 10; i++) {\n            for (int j = 0; j < 10; j++) {\n                Console.Write(\" {0}\", a[i, j]);\n                if (a[i, j] == 20) {\n                    goto Done;\n                }\n            }\n            Console.WriteLine();\n        }\n    Done:\n        Console.WriteLine();\n    }\n}\n"}
{"id": 59991, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 59992, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "C#": "int[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n"}
{"id": 59993, "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", "C#": "using System;\nusing System.Text;\nusing System.Linq;\n\nclass Program\n{\n    static string lookandsay(string number)\n    {\n        StringBuilder result = new StringBuilder();\n\n        char repeat = number[0];\n        number = number.Substring(1, number.Length-1)+\" \";\n        int times = 1;\n      \n        foreach (char actual in number)\n        {\n            if (actual != repeat)\n            {\n                result.Append(Convert.ToString(times)+repeat);\n                times = 1;\n                repeat = actual;\n            }\n            else\n            {\n                times += 1;\n            }\n        }\n        return result.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        string num = \"1\"; \n\n        foreach (int i in Enumerable.Range(1, 10)) {\n             Console.WriteLine(num);\n             num = lookandsay(num);             \n        }\n    }\n}\n"}
{"id": 59994, "name": "Stack", "Python": "from collections import deque\nstack = deque()\nstack.append(value) \nvalue = stack.pop()\nnot stack \n", "C#": "\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \ntop = stack.Pop();\n\n\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \ntop = stack.Pop();\n"}
{"id": 59995, "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", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 59996, "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", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    static void Main()\n    {\n        for (int i = 1; i <= 25; i++) {\n            int t = Totient(i);\n            WriteLine(i + \"\\t\" + t + (t == i - 1 ? \"\\tprime\" : \"\"));\n        }\n        WriteLine();\n        for (int i = 100; i <= 100_000; i *= 10) {\n            WriteLine($\"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}\");\n        }\n    }\n\n    static int Totient(int n) {\n        if (n < 3) return 1;\n        if (n == 3) return 2;\n\n        int totient = n;\n\n        if ((n & 1) == 0) {\n            totient >>= 1;\n            while (((n >>= 1) & 1) == 0) ;\n        }\n\n        for (int i = 3; i * i <= n; i += 2) {\n            if (n % i == 0) {\n                totient -= totient / i;\n                while ((n /= i) % i == 0) ;\n            }\n        }\n        if (n > 1) totient -= totient / n;\n        return totient;\n    }\n}\n"}
{"id": 59997, "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", "C#": "if (condition)\n{\n   \n}\n\nif (condition)\n{\n  \n}\nelse if (condition2)\n{\n  \n}\nelse\n{\n  \n}\n"}
{"id": 59998, "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", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 59999, "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", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode {\n    class SortCustomComparator {\n        \n        public void CustomSort() {\n            String[] items = { \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n            List<String> list = new List<string>(items);\n\n            DisplayList(\"Unsorted\", list);\n            \n            list.Sort(CustomCompare);\n            DisplayList(\"Descending Length\", list);\n\n            list.Sort();\n            DisplayList(\"Ascending order\", list);\n        }\n\n        \n        public int CustomCompare(String x, String y) {\n            int result = -x.Length.CompareTo(y.Length);\n            if (result == 0) {\n                result = x.ToLower().CompareTo(y.ToLower());\n            }\n\n            return result;\n        }\n\n        \n        public void DisplayList(String header, List<String> theList) {\n            Console.WriteLine(header);\n            Console.WriteLine(\"\".PadLeft(header.Length, '*'));\n            foreach (String str in theList) {\n                Console.WriteLine(str);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 60000, "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", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n"}
{"id": 60001, "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", "C#": "using System;\n\nnamespace RadixSort\n{\n    class Program\n    {\n        static void Sort(int[] old)\n        {\n            int i, j;\n            int[] tmp = new int[old.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < old.Length; ++i)\n                {\n                    bool move = (old[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)  \n                        old[i-j] = old[i];\n                    else                            \n                        tmp[j++] = old[i];\n                }\n                Array.Copy(tmp, 0, old, old.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            int[] old = new int[] { 2, 5, 1, -3, 4 };\n            Console.WriteLine(string.Join(\", \", old));\n            Sort(old);\n            Console.WriteLine(string.Join(\", \", old));\n            Console.Read();\n        }\n    }\n}\n"}
{"id": 60002, "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", "C#": "using System.Linq;\n\nstatic class Program\n{\n  static void Main()\n  {\n    var ts =\n      from a in Enumerable.Range(1, 20)\n      from b in Enumerable.Range(a, 21 - a)\n      from c in Enumerable.Range(b, 21 - b)\n      where a * a + b * b == c * c\n      select new { a, b, c };\n\n      foreach (var t in ts)\n        System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c);\n  }\n}\n"}
{"id": 60003, "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", "C#": "class SelectionSort<T> where T : IComparable {\n    public T[] Sort(T[] list) {\n        int k;\n        T temp;\n\n        for (int i = 0; i < list.Length; i++) {\n            k = i;\n            for (int j=i + 1; j < list.Length; j++) {\n                if (list[j].CompareTo(list[k]) < 0) {\n                    k = j;\n                }\n            }\n            temp = list[i];\n            list[i] = list[k];\n            list[k] = temp;\n        }\n\n        return list;\n    }\n}\n"}
{"id": 60004, "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", "C#": "int[] intArray = { 1, 2, 3, 4, 5 };\n\nint[] squares1 = intArray.Select(x => x * x).ToArray();\n\n\nint[] squares2 = (from x in intArray\n                  select x * x).ToArray();\n\n\nforeach (var i in intArray)\n    Console.WriteLine(i * i);\n"}
{"id": 60005, "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", "C#": "public sealed class Singleton1 \n{\n    private static Singleton1 instance;\n    private static readonly object lockObj = new object();\n    \n    public static Singleton1 Instance {\n        get {\n            lock(lockObj) {\n                if (instance == null) {\n                    instance = new Singleton1();\n                }\n            }\n            return instance;\n        }\n    }\n}\n"}
{"id": 60006, "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", "C#": "using System;\n\nnamespace SafeAddition {\n    class Program {\n        static float NextUp(float d) {\n            if (d == 0.0) return float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl++;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static float NextDown(float d) {\n            if (d == 0.0) return -float.Epsilon;\n            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;\n\n            byte[] bytes = BitConverter.GetBytes(d);\n            int dl = BitConverter.ToInt32(bytes, 0);\n            dl--;\n            bytes = BitConverter.GetBytes(dl);\n\n            return BitConverter.ToSingle(bytes, 0);\n        }\n\n        static Tuple<float, float> SafeAdd(float a, float b) {\n            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));\n        }\n\n        static void Main(string[] args) {\n            float a = 1.20f;\n            float b = 0.03f;\n\n            Console.WriteLine(\"({0} + {1}) is in the range {2}\", a, b, SafeAdd(a, b));\n        }\n    }\n}\n"}
{"id": 60007, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "C#": "for (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n"}
{"id": 60008, "name": "Write entire file", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n", "C#": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n"}
{"id": 60009, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "C#": "using System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 60010, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 60011, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    public static void Main() {\n        var sequence = new[] { \"A\", \"B\", \"C\", \"D\" };\n        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {\n            Console.WriteLine(string.Join(\" \", subset.Select(i => sequence[i])));\n        }\n    }\n    \n    static IEnumerable<List<int>> Subsets(int length) {\n        int[] values = Enumerable.Range(0, length).ToArray();\n        var stack = new Stack<int>(length);\n        for (int i = 0; stack.Count > 0 || i < length; ) {\n            if (i < length) {\n                stack.Push(i++);\n                yield return (from index in stack.Reverse() select values[index]).ToList();\n            } else {\n                i = stack.Pop() + 1;\n                if (stack.Count > 0) i = stack.Pop() + 1;\n            }\n        }\n    }\n\n    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;\n\n}\n"}
{"id": 60012, "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", "C#": "using System;\n\nclass Program {\n\n    static uint[] res = new uint[10];\n    static uint ri = 1, p = 10, count = 0;\n\n    static void TabulateTwinPrimes(uint bound) {\n        if (bound < 5) return; count++;\n        uint cl = (bound - 1) >> 1, i = 1, j,\n             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;\n        var comp = new bool[cl]; bool lp;\n        for (j = 3; j < cl; j += 3) comp[j] = true;\n        while (i < limit) {\n            if (lp = !comp[i]) {\n                uint pr = (i << 1) + 3;\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true;\n            }\n            if (!comp[++i]) {\n                uint pr = (i << 1) + 3;\n                if (lp) {\n                    if (pr > p) {\n                        res[ri++] = count;\n                        p *= 10;\n                    }\n                    count++;\n                    i++;\n                }\n                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)\n                    comp[j] = true; \n            }\n        }\n        cl--;\n        while (i < cl) {\n            lp = !comp[i++];\n            if (!comp[i] && lp) {\n                if ((i++ << 1) + 3 > p) {\n                    res[ri++] = count;\n                    p *= 10;\n                }\n                count++;\n            }\n        }\n        res[ri] = count;\n    }\n\n    static void Main(string[] args) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        string fmt = \"{0,9:n0} twin primes below {1,-13:n0}\";\n        TabulateTwinPrimes(1_000_000_000);\n        sw.Stop();\n        p = 1;\n        for (var j = 1; j <= ri; j++)\n            Console.WriteLine(fmt, res[j], p *= 10);\n        Console.Write(\"{0} sec\", sw.Elapsed.TotalSeconds);\n    }\n}\n"}
{"id": 60013, "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", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nclass Program\n{\n    static IEnumerable<Complex> RootsOfUnity(int degree)\n    {\n        return Enumerable\n            .Range(0, degree)\n            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));\n    }\n\n    static void Main()\n    {\n        var degree = 3;\n        foreach (var root in RootsOfUnity(degree))\n        {\n            Console.WriteLine(root);\n        }\n    }\n}\n"}
{"id": 60014, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "C#": "using System;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n\nclass Program {\n\n  static decimal mx = 1E28M, hm = 1E14M, a;\n\n  \n  struct bi { public decimal hi, lo; }\n\n  \n  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }\n\n  \n  static string toStr(bi a, bool comma = false) {\n    string r = a.hi == 0 ? string.Format(\"{0:0}\", a.lo) :\n                           string.Format(\"{0:0}{1:\" + new string('0', 28) + \"}\", a.hi, a.lo);\n    if (!comma) return r;  string rc = \"\";\n    for (int i = r.Length - 3; i > 0; i -= 3) rc = \",\" + r.Substring(i, 3) + rc;\n    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }\n\n  \n  static decimal Pow_dec(decimal bas, uint exp) {\n    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;\n    if ((exp & 1) == 0) return tmp; return tmp * bas; }\n\n  static void Main(string[] args) {\n    for (uint p = 64; p < 95; p += 30) {        \n      bi x = set4sq(a = Pow_dec(2M, p)), y;     \n      WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a); BI BS = BI.Pow((BI)a, 2);\n      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   \n      a = x.hi * x.lo * 2M;                     \n      y.hi += Math.Floor(a / hm);               \n      y.lo += (a % hm) * hm;                    \n      while (y.lo > mx) { y.lo -= mx; y.hi++; } \n      WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\\n\", toStr(y, true),\n          BS.ToString() == toStr(y) ? \"does\" : \"fails to\"); } }\n\n}\n"}
{"id": 60015, "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", "C#": "using System;\nusing System.Numerics;\n\nstatic class Program\n{\n    static void Fun(ref BigInteger a, ref BigInteger b, int c)\n    {\n        BigInteger t = a; a = b; b = b * c + t;\n    }\n\n    static void SolvePell(int n, ref BigInteger a, ref BigInteger b)\n    {\n        int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;\n        BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;\n        while (true)\n        {\n            y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;\n            Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);\n            if (a * a - n * b * b == 1) return;\n        }\n    }\n\n    static void Main()\n    {\n        BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })\n        {\n            SolvePell(n, ref x, ref y);\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y);\n        }\n    }\n}\n"}
{"id": 60016, "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", "C#": "using System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess ?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess ?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n"}
{"id": 60017, "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", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BubbleSort\n{\n    public static class BubbleSortMethods\n    {\n        \n        \n        \n        public static void BubbleSort<T>(this List<T> list) where T : IComparable\n        {\n            bool madeChanges;\n            int itemCount = list.Count;\n            do\n            {\n                madeChanges = false;\n                itemCount--;\n                for (int i = 0; i < itemCount; i++)\n                {\n                    if (list[i].CompareTo(list[i + 1]) > 0)\n                    {\n                        T temp = list[i + 1];\n                        list[i + 1] = list[i];\n                        list[i] = temp;\n                        madeChanges = true;\n                    }\n                }\n            } while (madeChanges);\n        }\n    }\n\n    \n    \n    class Program\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };\n            testList.BubbleSort();\n            foreach (var t in testList) Console.Write(t + \" \");\n        }\n    }\n}\n"}
{"id": 60018, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "C#": "using System;\nusing System.IO;\n\nnamespace FileIO\n{\n  class Program\n  {\n    static void Main()\n    {\n      String s = scope .();\n      File.ReadAllText(\"input.txt\", s);\n      File.WriteAllText(\"output.txt\", s);\n    }\n  }\n}\n"}
{"id": 60019, "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", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} / {1} = {2}\", a, b, a / b); \n        Console.WriteLine(\"{0} % {1} = {2}\", a, b, a % b); \n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n"}
{"id": 60020, "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", "C#": "using System;\nusing System.Text;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\t\t\t\t\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tdouble[,] m = { {1,2,3},{4,5,6},{7,8,9} };\n\t\t\t\n\t\t\tdouble[,] t = Transpose( m );\t\n\t\t\t\n\t\t\tfor( int i=0; i<t.GetLength(0); i++ )\n\t\t\t{\n\t\t\t\tfor( int j=0; j<t.GetLength(1); j++ )\t\t\n\t\t\t\t\tConsole.Write( t[i,j] + \"  \" );\n\t\t\t\tConsole.WriteLine(\"\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static double[,] Transpose( double[,] m )\n\t\t{\n\t\t\tdouble[,] t = new double[m.GetLength(1),m.GetLength(0)];\n\t\t\tfor( int i=0; i<m.GetLength(0); i++ )\n\t\t\t\tfor( int j=0; j<m.GetLength(1); j++ )\n\t\t\t\t\tt[j,i] = m[i,j];\t\t\t\n\t\t\t\n\t\t\treturn t;\n\t\t}\n\t}\n}\n"}
{"id": 60021, "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", "C#": "using System;\n \ndelegate T Func<T>();\n \nclass ManOrBoy\n{\n    static void Main()\n    {\n        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));\n    }\n \n    static Func<int> C(int i)\n    {\n        return delegate { return i; };\n    }\n \n    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)\n    {\n        Func<int> b = null;\n        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };\n        return k <= 0 ? x4() + x5() : b();\n    }\n}\n"}
{"id": 60022, "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", "C#": "using System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 60023, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 60024, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "C#": "using System;\nclass RecursionLimit\n{\n  static void Main(string[] args)\n  {\n    Recur(0);\n  }\n \n  private static void Recur(int i) \n  {\n    Console.WriteLine(i);\n    Recur(i + 1);\n  }\n}\n"}
{"id": 60025, "name": "Image noise", "Python": "black = color(0)\nwhite = color(255)\n\ndef setup():\n    size(320, 240)\n    \n\n\ndef draw():\n    loadPixels()\n    for i in range(len(pixels)):\n        if random(1) < 0.5:\n            pixels[i] = black\n        else:\n            pixels[i] = white\n\n    updatePixels()\n    fill(0, 128)\n    rect(0, 0, 60, 20)\n    fill(255)\n    text(frameRate, 5, 15)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static Size size = new Size(320, 240);\n    static Rectangle rectsize = new Rectangle(new Point(0, 0), size);\n    static int numpixels = size.Width * size.Height;\n    static int numbytes = numpixels * 3;\n\n    static PictureBox pb;\n    static BackgroundWorker worker;\n\n    static double time = 0;\n    static double frames = 0;\n    static Random rand = new Random();\n\n    static byte tmp;\n    static byte white = 255;\n    static byte black = 0;\n    static int halfmax = int.MaxValue / 2; \n\n    static IEnumerable<byte> YieldVodoo()\n    {\n        \n\n        for (int i = 0; i < numpixels; i++)\n        {\n            tmp = rand.Next() < halfmax ? black : white; \n\n            \n            yield return tmp;\n            yield return tmp;\n            yield return tmp;\n        }\n    }\n\n    static Image Randimg()\n    {\n        \n        var bitmap = new Bitmap(size.Width, size.Height);\n        var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\n\n        Marshal.Copy(\n            YieldVodoo().ToArray<byte>(),\n            0, \n            data.Scan0, \n            numbytes); \n\n        bitmap.UnlockBits(data);\n        return bitmap;\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        var form = new Form();\n\n        form.AutoSize = true;\n        form.Size = new Size(0, 0);\n        form.Text = \"Test\";\n\n        form.FormClosed += delegate\n        {\n            Application.Exit();\n        };\n\n        worker = new BackgroundWorker();\n\n        worker.DoWork += delegate\n        {\n            System.Threading.Thread.Sleep(500); \n\n            while (true)\n            {\n                var a = DateTime.Now;\n                pb.Image = Randimg();\n                var b = DateTime.Now;\n\n                time += (b - a).TotalSeconds;\n                frames += 1;\n\n                if (frames == 30)\n                {\n                    Console.WriteLine(\"{0} frames in {1:0.000} seconds. ({2:0} FPS)\", frames, time, frames / time);\n\n                    time = 0;\n                    frames = 0;\n                }\n            }\n        };\n\n        worker.RunWorkerAsync();\n\n        FlowLayoutPanel flp = new FlowLayoutPanel();\n        form.Controls.Add(flp);\n\n        pb = new PictureBox();\n        pb.Size = size;\n\n        flp.AutoSize = true;\n        flp.Controls.Add(pb);\n\n        form.Show();\n        Application.Run();\n    }\n}\n"}
{"id": 60026, "name": "Perfect numbers", "Python": "def perf1(n):\n    sum = 0\n    for i in range(1, n):\n        if n % i == 0:\n            sum += i\n    return sum == n\n", "C#": "static void Main(string[] args)\n{\n\tConsole.WriteLine(\"Perfect numbers from 1 to 33550337:\");\n\n\tfor (int x = 0; x < 33550337; x++)\n\t{\n\t\tif (IsPerfect(x))\n\t\t\tConsole.WriteLine(x + \" is perfect.\");\n\t}\n\n\tConsole.ReadLine();\n}\n\nstatic bool IsPerfect(int num) \n{\n\tint sum = 0;\n\tfor (int i = 1; i < num; i++)\n\t{\n\t\tif (num % i == 0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum == num ;\n}\n"}
{"id": 60027, "name": "Arbitrary-precision integers (included)", "Python": ">>> y = str( 5**4**3**2 )\n>>> print (\"5**4**3**2 = %s...%s and has %i digits\" % (y[:20], y[-20:], len(y)))\n5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits\n", "C#": "using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Numerics;\n\nstatic class Program {\n    static void Main() {\n        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));\n        string result = n.ToString();\n\n        Debug.Assert(result.Length == 183231);\n        Debug.Assert(result.StartsWith(\"62060698786608744707\"));\n        Debug.Assert(result.EndsWith(\"92256259918212890625\"));\n\n        Console.WriteLine(\"n = 5^4^3^2\");\n        Console.WriteLine(\"n = {0}...{1}\", \n            result.Substring(0, 20),\n            result.Substring(result.Length - 20, 20)\n            );\n\n        Console.WriteLine(\"n digits = {0}\", result.Length);\n    }\n}\n"}
{"id": 60028, "name": "Inverted index", "Python": "\n\nfrom pprint import pprint as pp\nfrom glob import glob\ntry: reduce\nexcept: from functools import reduce\ntry:    raw_input\nexcept: raw_input = input\n\n\ndef parsetexts(fileglob='InvertedIndex/T*.txt'):\n    texts, words = {}, set()\n    for txtfile in glob(fileglob):\n        with open(txtfile, 'r') as f:\n            txt = f.read().split()\n            words |= set(txt)\n            texts[txtfile.split('\\\\')[-1]] = txt\n    return texts, words\n\ndef termsearch(terms): \n    return reduce(set.intersection,\n                  (invindex[term] for term in terms),\n                  set(texts.keys()))\n\ntexts, words = parsetexts()\nprint('\\nTexts')\npp(texts)\nprint('\\nWords')\npp(sorted(words))\n\ninvindex = {word:set(txt\n                        for txt, wrds in texts.items() if word in wrds)\n            for word in words}\nprint('\\nInverted Index')\npp({k:sorted(v) for k,v in invindex.items()})\n\nterms = [\"what\", \"is\", \"it\"]\nprint('\\nTerm Search for: ' + repr(terms))\npp(sorted(termsearch(terms)))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass InvertedIndex\n{\n    static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)\n    {\n        return dictionary\n            .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))\n            .GroupBy(keyValuePair => keyValuePair.Key)\n            .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));\n    }\n\n    static void Main()\n    {\n        Console.Write(\"files: \");\n        var files = Console.ReadLine();\n        Console.Write(\"find: \");\n        var find = Console.ReadLine();\n        var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());\n        Console.WriteLine(\"{0} found in: {1}\", find, string.Join(\" \", Invert(dictionary)[find]));\n    }\n}\n"}
{"id": 60029, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 60030, "name": "Least common multiple", "Python": ">>> import fractions\n>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n", "C#": "Using System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) / gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n"}
{"id": 60031, "name": "Loops_Break", "Python": "from random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n"}
{"id": 60032, "name": "Water collected between towers", "Python": "def water_collected(tower):\n    N = len(tower)\n    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n        for n in range(N)]\n    print(\"highest_left:  \", highest_left)\n    print(\"highest_right: \", highest_right)\n    print(\"water_level:   \", water_level)\n    print(\"tower_level:   \", tower)\n    print(\"total_water:   \", sum(water_level))\n    print(\"\")\n    return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n    [5, 5, 5, 5],\n    [5, 6, 7, 8],\n    [8, 7, 7, 6],\n    [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "C#": "class Program\n{\n    static void Main(string[] args)\n    {\n        int[][] wta = {\n            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },\n            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};\n        string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \"  \";\n        for (int i = 0; i < wta.Length; i++)\n        {\n            int bpf; blk = \"\"; do\n            {\n                string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n                {\n                    if (wta[i][j] > 0)\n                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }\n                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n                }\n                if (bpf > 0) blk = floor + lf + blk;\n            } while (bpf > 0);\n            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n            if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n            System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n                i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n        }\n    }\n}\n"}
{"id": 60033, "name": "Descending primes", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n"}
{"id": 60034, "name": "Descending primes", "Python": "from sympy import isprime\n\ndef descending(xs=range(10)):\n    for x in xs:\n        yield x\n        yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()\n", "C#": "using System;\n\nclass Program {\n\n  static bool ispr(uint n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (uint j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return false; return true; }\n\n  static void Main(string[] args) {\n    uint c = 0; int nc;\n    var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    var nxt = new uint[128];\n    while (true) {\n      nc = 0;\n      foreach (var a in ps) {\n        if (ispr(a))\n          Console.Write(\"{0,8}{1}\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (uint b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) {\n        Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }\n      else break;\n    }\n    Console.WriteLine(\"\\n{0} descending primes found\", c);\n  }\n}\n"}
{"id": 60035, "name": "Sum and product puzzle", "Python": "\n\nfrom collections import Counter\n\ndef decompose_sum(s):\n    return [(a,s-a) for a in range(2,int(s/2+1))]\n\n\nall_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)\n\n\nproduct_counts = Counter(c*d for c,d in all_pairs)\nunique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)\ns_pairs = [(a,b) for a,b in all_pairs if\n    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]\n\n\nproduct_counts = Counter(c*d for c,d in s_pairs)\np_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]\n\n\nsum_counts = Counter(c+d for c,d in p_pairs)\nfinal_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]\n\nprint(final_pairs)\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        const int maxSum = 100;\n        var pairs = (\n            from X in 2.To(maxSum / 2 - 1)\n            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)\n            select new { X, Y, S = X + Y, P = X * Y }\n            ).ToHashSet();\n\n        Console.WriteLine(pairs.Count);\n        \n        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));\n        Console.WriteLine(pairs.Count);\n        \n        foreach (var pair in pairs) Console.WriteLine(pair);\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i <= end; i++) yield return i;\n    }\n    \n    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);\n}\n"}
{"id": 60036, "name": "Parsing_Shunting-yard algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\n\nOpInfo = namedtuple('OpInfo', 'prec assoc')\nL, R = 'Left Right'.split()\n\nops = {\n '^': OpInfo(prec=4, assoc=R),\n '*': OpInfo(prec=3, assoc=L),\n '/': OpInfo(prec=3, assoc=L),\n '+': OpInfo(prec=2, assoc=L),\n '-': OpInfo(prec=2, assoc=L),\n '(': OpInfo(prec=9, assoc=L),\n ')': OpInfo(prec=0, assoc=L),\n }\n\nNUM, LPAREN, RPAREN = 'NUMBER ( )'.split()\n\n\ndef get_input(inp = None):\n    'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'\n    \n    if inp is None:\n        inp = input('expression: ')\n    tokens = inp.strip().split()\n    tokenvals = []\n    for token in tokens:\n        if token in ops:\n            tokenvals.append((token, ops[token]))\n        \n        \n        else:    \n            tokenvals.append((NUM, token))\n    return tokenvals\n\ndef shunting(tokenvals):\n    outq, stack = [], []\n    table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]\n    for token, val in tokenvals:\n        note = action = ''\n        if token is NUM:\n            action = 'Add number to output'\n            outq.append(val)\n            table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        elif token in ops:\n            t1, (p1, a1) = token, val\n            v = t1\n            note = 'Pop ops from stack to output' \n            while stack:\n                t2, (p2, a2) = stack[-1]\n                if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):\n                    if t1 != RPAREN:\n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            break\n                    else:        \n                        if t2 != LPAREN:\n                            stack.pop()\n                            action = '(Pop op)'\n                            outq.append(t2)\n                        else:    \n                            stack.pop()\n                            action = '(Pop & discard \"(\")'\n                            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                            break\n                    table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n                    v = note = ''\n                else:\n                    note = ''\n                    break\n                note = '' \n            note = '' \n            if t1 != RPAREN:\n                stack.append((token, val))\n                action = 'Push op token to stack'\n            else:\n                action = 'Discard \")\"'\n            table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n    note = 'Drain stack to output'\n    while stack:\n        v = ''\n        t2, (p2, a2) = stack[-1]\n        action = '(Pop op)'\n        stack.pop()\n        outq.append(t2)\n        table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )\n        v = note = ''\n    return table\n\nif __name__ == '__main__':\n    infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n    print( 'For infix expression: %r\\n' % infix )\n    rp = shunting(get_input(infix))\n    maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]\n    row = rp[0]\n    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n    for row in rp[1:]:\n        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))\n\n    print('\\n The final output RPN is: %r' % rp[-1][2])\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        Console.WriteLine(infix.ToPostfix());\n    }\n}\n\npublic static class ShuntingYard\n{\n    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators\n        = new (string symbol, int precedence, bool rightAssociative) [] {\n            (\"^\", 4, true),\n            (\"*\", 3, false),\n            (\"/\", 3, false),\n            (\"+\", 2, false),\n            (\"-\", 2, false)\n    }.ToDictionary(op => op.symbol);\n\n    public static string ToPostfix(this string infix) {\n        string[] tokens = infix.Split(' ');\n        var stack = new Stack<string>();\n        var output = new List<string>();\n        foreach (string token in tokens) {\n            if (int.TryParse(token, out _)) {\n                output.Add(token);\n                Print(token);\n            } else if (operators.TryGetValue(token, out var op1)) {\n                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {\n                    int c = op1.precedence.CompareTo(op2.precedence);\n                    if (c < 0 || !op1.rightAssociative && c <= 0) {\n                        output.Add(stack.Pop());\n                    } else {\n                        break;\n                    }\n                }\n                stack.Push(token);\n                Print(token);\n            } else if (token == \"(\") {\n                stack.Push(token);\n                Print(token);\n            } else if (token == \")\") {\n                string top = \"\";\n                while (stack.Count > 0 && (top = stack.Pop()) != \"(\") {\n                    output.Add(top);\n                }\n                if (top != \"(\") throw new ArgumentException(\"No matching left parenthesis.\");\n                Print(token);\n            }\n        }\n        while (stack.Count > 0) {\n            var top = stack.Pop();\n            if (!operators.ContainsKey(top)) throw new ArgumentException(\"No matching right parenthesis.\");\n            output.Add(top);\n        }\n        Print(\"pop\");\n        return string.Join(\" \", output);\n        \n        \n        void Print(string action) => Console.WriteLine($\"{action + \":\",-4} {$\"stack[ {string.Join(\" \", stack.Reverse())} ]\",-18} {$\"out[ {string.Join(\" \", output)} ]\"}\");\n        \n        void Print(string action) => Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {string.Join(\" \", stack.Reverse())} ]\", $\"out[ {string.Join(\" \", output)} ]\");\n    }\n}\n"}
{"id": 60037, "name": "Middle three digits", "Python": ">>> def middle_three_digits(i):\n\ts = str(abs(i))\n\tlength = len(s)\n\tassert length >= 3 and length % 2 == 1, \"Need odd and >= 3 digits\"\n\tmid = length // 2\n\treturn s[mid-1:mid+2]\n\n>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\n>>> failing = [1, 2, -1, -10, 2002, -2002, 0]\n>>> for x in passing + failing:\n\ttry:\n\t\tanswer = middle_three_digits(x)\n\texcept AssertionError as error:\n\t\tanswer = error\n\tprint(\"middle_three_digits(%s) returned: %r\" % (x, answer))\n\n\t\nmiddle_three_digits(123) returned: '123'\nmiddle_three_digits(12345) returned: '234'\nmiddle_three_digits(1234567) returned: '345'\nmiddle_three_digits(987654321) returned: '654'\nmiddle_three_digits(10001) returned: '000'\nmiddle_three_digits(-10001) returned: '000'\nmiddle_three_digits(-123) returned: '123'\nmiddle_three_digits(-100) returned: '100'\nmiddle_three_digits(100) returned: '100'\nmiddle_three_digits(-12345) returned: '234'\nmiddle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)\nmiddle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)\n>>>\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();\n            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? \"Error\" : text.Substring((text.Length - 3) / 2, 3));\n        }\n    }\n}\n"}
{"id": 60038, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 60039, "name": "Stern-Brocot sequence", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\n    \n\n    sb, i = [1, 1], 0\n    while predicate(sb):\n        sb += [sum(sb[i:i + 2]), sb[i + 1]]\n        i += 1\n    return sb\n\n\nif __name__ == '__main__':\n    from fractions import gcd\n\n    n_first = 15\n    print('The first %i values:\\n  ' % n_first,\n          stern_brocot(lambda series: len(series) < n_first)[:n_first])\n    print()\n    n_max = 10\n    for n_occur in list(range(1, n_max + 1)) + [100]:\n        print('1-based index of the first occurrence of %3i in the series:' % n_occur,\n              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)\n              \n              \n\n    print()\n    n_gcd = 1000\n    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]\n    assert all(gcd(prev, this) == 1\n               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nstatic class Program {\n    static List<int> l = new List<int>() { 1, 1 };\n\n    static int gcd(int a, int b) {\n        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }\n\n    static void Main(string[] args) {\n        int max = 1000; int take = 15; int i = 1;\n        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };\n        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }\n        while (l.Count < max || l[l.Count - 2] != selection.Last());\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take);\n        Console.WriteLine(\"{0}\\n\", string.Join(\", \", l.Take(take)));\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\");\n        foreach (int ii in selection) {\n            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine(\"{0,3}: {1:n0}\", ii, j); }\n        Console.WriteLine(); bool good = true;\n        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" + \n                          \" series up to the {0}th item is {1}always one.\", max, good ? \"\" : \"not \");\n    }\n}\n"}
{"id": 60040, "name": "Documentation", "Python": "class Doc(object):\n   \n   def method(self, num):\n      \n      pass\n", "C#": "\n\n\npublic static class XMLSystem\n{\n    static XMLSystem()\n    {\n        \n    }\n\n    \n    \n    \n    \n    \n    public static XmlDocument GetXML(string name) \n    {\n        return null;\n    }\n}\n"}
{"id": 60041, "name": "Problem of Apollonius", "Python": "from collections import namedtuple\nimport math\n\nCircle = namedtuple('Circle', 'x, y, r')\n \ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n    \n    x1, y1, r1 = c1\n    x2, y2, r2 = c2\n    x3, y3, r3 = c3\n\n    v11 = 2*x2 - 2*x1\n    v12 = 2*y2 - 2*y1\n    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n    v14 = 2*s2*r2 - 2*s1*r1\n \n    v21 = 2*x3 - 2*x2\n    v22 = 2*y3 - 2*y2\n    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n    v24 = 2*s3*r3 - 2*s2*r2\n \n    w12 = v12/v11\n    w13 = v13/v11\n    w14 = v14/v11\n \n    w22 = v22/v21-w12\n    w23 = v23/v21-w13\n    w24 = v24/v21-w14\n \n    P = -w23/w22\n    Q = w24/w22\n    M = -w12*P-w13\n    N = w14 - w12*Q\n \n    a = N*N + Q*Q - 1\n    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n    \n    D = b*b-4*a*c\n    rs = (-b-math.sqrt(D))/(2*a)\n \n    xs = M+N*rs\n    ys = P+Q*rs\n \n    return Circle(xs, ys, rs)\n\nif __name__ == '__main__':\n    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)\n    print(solveApollonius(c1, c2, c3, 1, 1, 1))    \n    print(solveApollonius(c1, c2, c3, -1, -1, -1)) \n", "C#": "using System;\n\nnamespace ApolloniusProblemCalc\n{\n    class Program\n    {\n        static float rs = 0;\n        static float xs = 0;\n        static float ys = 0;\n\n        public static void Main(string[] args)\n        {\n            float gx1;\n            float gy1;\n            float gr1;\n            float gx2;\n            float gy2;\n            float gr2;\n            float gx3;\n            float gy3;\n            float gr3;\n\n            \n            gx1 = 0;\n            gy1 = 0;\n            gr1 = 1;\n            gx2 = 4;\n            gy2 = 0;\n            gr2 = 1;\n            gx3 = 2;\n            gy3 = 4;\n            gr3 = 2;\n            \n\n            for (int i = 1; i <= 8; i++)\n            {\n                SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);\n\n\n                if (i == 1)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"st solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"st solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"st Solution circle's radius: \" + rs.ToString());\n                }\n                else if (i == 2)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"ed solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"ed solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"ed Solution circle's radius: \" + rs.ToString());\n                }\n                else if(i == 3)\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"rd solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"rd solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"rd Solution circle's radius: \" + rs.ToString());\n                }\n                else\n                {\n                    Console.WriteLine(\"X of point of the \" + i + \"th solution: \" + xs.ToString());\n                    Console.WriteLine(\"Y of point of the \" + i + \"th solution: \" + ys.ToString());\n                    Console.WriteLine(i + \"th Solution circle's radius: \" + rs.ToString());\n                }\n\n                Console.WriteLine();\n            }\n\n\n            Console.ReadKey(true);\n        }\n\n        private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)\n        {\n            float s1 = 1;\n            float s2 = 1;\n            float s3 = 1;\n\n            if (calcCounter == 2)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 3)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = -1;\n            }\n            else if (calcCounter == 4)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 5)\n            {\n                s1 = -1;\n                s2 = -1;\n                s3 = 1;\n            }\n            else if (calcCounter == 6)\n            {\n                s1 = 1;\n                s2 = 1;\n                s3 = -1;\n            }\n            else if (calcCounter == 7)\n            {\n                s1 = -1;\n                s2 = 1;\n                s3 = 1;\n            }\n            else if (calcCounter == 8)\n            {\n                s1 = 1;\n                s2 = -1;\n                s3 = 1;\n            }\n\n            \n            float v11 = 2 * x2 - 2 * x1;\n            float v12 = 2 * y2 - 2 * y1;\n            float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;\n            float v14 = 2 * s2 * r2 - 2 * s1 * r1;\n\n            float v21 = 2 * x3 - 2 * x2;\n            float v22 = 2 * y3 - 2 * y2;\n            float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;\n            float v24 = 2 * s3 * r3 - 2 * s2 * r2;\n\n            float w12 = v12 / v11;\n            float w13 = v13 / v11;\n            float w14 = v14 / v11;\n\n            float w22 = v22 / v21 - w12;\n            float w23 = v23 / v21 - w13;\n            float w24 = v24 / v21 - w14;\n\n            float P = -w23 / w22;\n            float Q = w24 / w22;\n            float M = -w12 * P - w13;\n            float N = w14 - w12 * Q;\n\n            float a = N * N + Q * Q - 1;\n            float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;\n            float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;\n\n            float D = b * b - 4 * a * c;\n\n            rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));\n            xs = M + N * rs;\n            ys = P + Q * rs;\n        }\n    }\n}\n"}
{"id": 60042, "name": "Chat server", "Python": "\n\nimport socket\nimport thread\nimport time\n\nHOST = \"\"\nPORT = 4004\n\ndef accept(conn):\n    \n    def threaded():\n        while True:\n            conn.send(\"Please enter your name: \")\n            try:\n                name = conn.recv(1024).strip()\n            except socket.error:\n                continue\n            if name in users:\n                conn.send(\"Name entered is already in use.\\n\")\n            elif name:\n                conn.setblocking(False)\n                users[name] = conn\n                broadcast(name, \"+++ %s arrived +++\" % name)\n                break\n    thread.start_new_thread(threaded, ())\n\ndef broadcast(name, message):\n    \n    print message\n    for to_name, conn in users.items():\n        if to_name != name:\n            try:\n                conn.send(message + \"\\n\")\n            except socket.error:\n                pass\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.setblocking(False)\nserver.bind((HOST, PORT))\nserver.listen(1)\nprint \"Listening on %s\" % (\"%s:%s\" % server.getsockname())\n\n\nusers = {}\nwhile True:\n    try:\n        \n        while True:\n            try:\n                conn, addr = server.accept()\n            except socket.error:\n                break\n            accept(conn)\n        \n        for name, conn in users.items():\n            try:\n                message = conn.recv(1024)\n            except socket.error:\n                continue\n            if not message:\n                \n                del users[name]\n                broadcast(name, \"--- %s leaves ---\" % name)\n            else:\n                broadcast(name, \"%s> %s\" % (name, message.strip()))\n        time.sleep(.1)\n    except (SystemExit, KeyboardInterrupt):\n        break\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace ChatServer {\n    class State {\n        private TcpClient client;\n        private StringBuilder sb = new StringBuilder();\n\n        public string Name { get; }\n\n        public State(string name, TcpClient client) {\n            Name = name;\n            this.client = client;\n        }\n\n        public void Add(byte b) {\n            sb.Append((char)b);\n        }\n\n        public void Send(string text) {\n            var bytes = Encoding.ASCII.GetBytes(string.Format(\"{0}\\r\\n\", text));\n            client.GetStream().Write(bytes, 0, bytes.Length);\n        }\n    }\n\n    class Program {\n        static TcpListener listen;\n        static Thread serverthread;\n        static Dictionary<int, State> connections = new Dictionary<int, State>();\n\n        static void Main(string[] args) {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 4004);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen() {\n            \n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true) {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client) {\n            \n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            byte[] bytes = Encoding.ASCII.GetBytes(\"Enter name: \");\n            tClient.GetStream().Write(bytes, 0, bytes.Length);\n\n            string name = string.Empty;\n            bool done = false;\n            do {\n                if (!tClient.Connected) {\n                    Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \n                }\n\n                name = Receive(tClient);\n                done = true;\n\n                if (done) {\n                    foreach (var cl in connections) {\n                        var state = cl.Value;\n                        if (state.Name == name) {\n                            bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \");\n                            tClient.GetStream().Write(bytes, 0, bytes.Length);\n                            done = false;\n                        }\n                    }\n                }\n            } while (!done);\n\n            connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));\n            Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n            Broadcast(string.Format(\"+++ {0} arrived +++\", name));\n\n            do {\n                string text = Receive(tClient);\n                if (text == \"/quit\") {\n                    Broadcast(string.Format(\"Connection from {0} closed.\", name));\n                    connections.Remove(Thread.CurrentThread.ManagedThreadId);\n                    Console.WriteLine(\"\\tTotal connections: {0}\", connections.Count);\n                    break;\n                }\n\n                if (!tClient.Connected) {\n                    break;\n                }\n                Broadcast(string.Format(\"{0}> {1}\", name, text));\n            } while (true);\n\n            Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId);\n            tClient.Close();\n            Thread.CurrentThread.Abort();\n        }\n\n        private static string Receive(TcpClient client) {\n            StringBuilder sb = new StringBuilder();\n            do {\n                if (client.Available > 0) {\n                    while (client.Available > 0) {\n                        char ch = (char)client.GetStream().ReadByte();\n                        if (ch == '\\r') {\n                            \n                            continue;\n                        }\n                        if (ch == '\\n') {\n                            return sb.ToString();\n                        }\n                        sb.Append(ch);\n                    }\n                }\n\n                \n                Thread.Sleep(100);\n            } while (true);\n        }\n\n        private static void Broadcast(string text) {\n            Console.WriteLine(text);\n            foreach (var oClient in connections) {\n                if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {\n                    State state = oClient.Value;\n                    state.Send(text);\n                }\n            }\n        }\n    }\n}\n"}
{"id": 60043, "name": "FASTA format", "Python": "import io\n\nFASTA=\n\ninfile = io.StringIO(FASTA)\n\ndef fasta_parse(infile):\n    key = ''\n    for line in infile:\n        if line.startswith('>'):\n            if key:\n                yield key, val\n            key, val = line[1:].rstrip().split()[0], ''\n        elif key:\n            val += line.rstrip()\n    if key:\n        yield key, val\n\nprint('\\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nclass Program\n{\n    public class FastaEntry\n    {\n        public string Name { get; set; }\n        public StringBuilder Sequence { get; set; }\n    }\n\n    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)\n    {\n        FastaEntry f = null;\n        string line;\n        while ((line = fastaFile.ReadLine()) != null)\n        {\n            \n            if (line.StartsWith(\";\"))\n                continue;\n\n            if (line.StartsWith(\">\"))\n            {\n                if (f != null)\n                    yield return f;\n                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };\n            }\n            else if (f != null)\n                f.Sequence.Append(line);\n        }\n        yield return f;\n    }\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (var fastaFile = new StreamReader(\"fasta.txt\"))\n            {\n                foreach (FastaEntry f in ParseFasta(fastaFile))\n                    Console.WriteLine(\"{0}: {1}\", f.Name, f.Sequence);\n            }\n        }\n        catch (FileNotFoundException e)\n        {\n            Console.WriteLine(e);\n        }\n        Console.ReadLine();\n    }\n}\n"}
{"id": 60044, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 60045, "name": "Find palindromic numbers in both binary and ternary bases", "Python": "from itertools import islice\n\ndigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\ndef baseN(num,b):\n  if num == 0: return \"0\"\n  result = \"\"\n  while num != 0:\n    num, d = divmod(num, b)\n    result += digits[d]\n  return result[::-1] \n\ndef pal2(num):\n    if num == 0 or num == 1: return True\n    based = bin(num)[2:]\n    return based == based[::-1]\n\ndef pal_23():\n    yield 0\n    yield 1\n    n = 1\n    while True:\n        n += 1\n        b = baseN(n, 3)\n        revb = b[::-1]\n        \n        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),\n                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):\n            t = int(trial, 3)\n            if pal2(t):\n                yield t\n\nfor pal23 in islice(pal_23(), 6):\n    print(pal23, baseN(pal23, 3), baseN(pal23, 2))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class FindPalindromicNumbers\n{\n    static void Main(string[] args)\n    {\n        var query =\n            PalindromicTernaries()\n            .Where(IsPalindromicBinary)\n            .Take(6);\n        foreach (var x in query) {\n            Console.WriteLine(\"Decimal: \" + x);\n            Console.WriteLine(\"Ternary: \" + ToTernary(x));\n            Console.WriteLine(\"Binary: \" + Convert.ToString(x, 2));\n            Console.WriteLine();\n        }\n    }\n\n    public static IEnumerable<long> PalindromicTernaries() {\n        yield return 0;\n        yield return 1;\n        yield return 13;\n        yield return 23;\n\n        var f = new List<long> {0};\n        long fMiddle = 9;\n        while (true) {\n            for (long edge = 1; edge < 3; edge++) {\n                int i;\n                do {\n                    \n                    long result = fMiddle;\n                    long fLeft = fMiddle * 3;\n                    long fRight = fMiddle / 3;\n                    for (int j = f.Count - 1; j >= 0; j--) {\n                        result += (fLeft + fRight) * f[j];\n                        fLeft *= 3;\n                        fRight /= 3;\n                    }\n                    result += (fLeft + fRight) * edge;\n                    yield return result;\n\n                    \n                    for (i = f.Count - 1; i >= 0; i--) {\n                        if (f[i] == 2) {\n                            f[i] = 0;\n                        } else {\n                            f[i]++;\n                            break;\n                        }\n                    }\n                } while (i >= 0);\n            }\n            f.Add(0);\n            fMiddle *= 3;\n        }\n    }\n\n    public static bool IsPalindromicBinary(long number) {\n        long n = number;\n        long reverse = 0;\n        while (n != 0) {\n            reverse <<= 1;\n            if ((n & 1) == 1) reverse++;\n            n >>= 1;\n        }\n        return reverse == number;\n    }\n\n    public static string ToTernary(long n)\n    {\n        if (n == 0) return \"0\";\n        string result = \"\";\n        while (n > 0) {        {\n            result = (n % 3) + result;\n            n /= 3;\n        }\n        return result;\n    }\n\n}\n"}
{"id": 60046, "name": "Terminal control_Dimensions", "Python": "import os\n\ndef get_windows_terminal():\n    from ctypes import windll, create_string_buffer\n    h = windll.kernel32.GetStdHandle(-12)\n    csbi = create_string_buffer(22)\n    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n    \n    if not res: return 80, 25 \n\n    import struct\n    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\\\n    = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n    width = right - left + 1\n    height = bottom - top + 1\n\n    return width, height\n\ndef get_linux_terminal():\n    width = os.popen('tput cols', 'r').readline()\n    height = os.popen('tput lines', 'r').readline()\n\n    return int(width), int(height)\n\nprint get_linux_terminal() if os.name == 'posix' else get_windows_terminal()\n", "C#": "static void Main(string[] args)\n{\n    int bufferHeight = Console.BufferHeight;\n    int bufferWidth = Console.BufferWidth;\n    int windowHeight = Console.WindowHeight;\n    int windowWidth = Console.WindowWidth;\n\n    Console.Write(\"Buffer Height: \");\n    Console.WriteLine(bufferHeight);\n    Console.Write(\"Buffer Width: \");\n    Console.WriteLine(bufferWidth);\n    Console.Write(\"Window Height: \");\n    Console.WriteLine(windowHeight);\n    Console.Write(\"Window Width: \");\n    Console.WriteLine(windowWidth);\n    Console.ReadLine();\n}\n"}
{"id": 60047, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 60048, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 60049, "name": "Cipolla's algorithm", "Python": "\n\ndef convertToBase(n, b):\n\tif(n < 2):\n\t\treturn [n];\n\ttemp = n;\n\tans = [];\n\twhile(temp != 0):\n\t\tans = [temp % b]+ ans;\n\t\ttemp /= b;\n\treturn ans;\n\n\n\n\ndef cipolla(n,p):\n\tn %= p\n\tif(n == 0 or n == 1):\n\t\treturn (n,-n%p)\n\tphi = p - 1\n\tif(pow(n, phi/2, p) != 1):\n\t\treturn ()\n\tif(p%4 == 3):\n\t\tans = pow(n,(p+1)/4,p)\n\t\treturn (ans,-ans%p)\n\taa = 0\n\tfor i in xrange(1,p):\n\t\ttemp = pow((i*i-n)%p,phi/2,p)\n\t\tif(temp == phi):\n\t\t\taa = i\n\t\t\tbreak;\n\texponent = convertToBase((p+1)/2,2)\n\tdef cipollaMult((a,b),(c,d),w,p):\n\t\treturn ((a*c+b*d*w)%p,(a*d+b*c)%p)\n\tx1 = (aa,1)\n\tx2 = cipollaMult(x1,x1,aa*aa-n,p)\n\tfor i in xrange(1,len(exponent)):\n\t\tif(exponent[i] == 0):\n\t\t\tx2 = cipollaMult(x2,x1,aa*aa-n,p)\n\t\t\tx1 = cipollaMult(x1,x1,aa*aa-n,p)\n\t\telse:\n\t\t\tx1 = cipollaMult(x1,x2,aa*aa-n,p)\n\t\t\tx2 = cipollaMult(x2,x2,aa*aa-n,p)\n\treturn (x1[0],-x1[0]%p)\n\nprint \"Roots of 2 mod 7: \" +str(cipolla(2,7))\nprint \"Roots of 8218 mod 10007: \" +str(cipolla(8218,10007))\nprint \"Roots of 56 mod 101: \" +str(cipolla(56,101))\nprint \"Roots of 1 mod 11: \" +str(cipolla(1,11))\nprint \"Roots of 8219 mod 10007: \" +str(cipolla(8219,10007))\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace CipollaAlgorithm {\n    class Program {\n        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;\n\n        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {\n            BigInteger n = BigInteger.Parse(ns);\n            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;\n\n            \n            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);\n\n            \n            if (ls(n) != 1) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            BigInteger a = 0;\n            BigInteger omega2;\n            while (true) {\n                omega2 = (a * a + p - n) % p;\n                if (ls(omega2) == p - 1) {\n                    break;\n                }\n                a += 1;\n            }\n\n            \n            BigInteger finalOmega = omega2;\n            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {\n                return new Tuple<BigInteger, BigInteger>(\n                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,\n                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p\n                );\n            }\n\n            \n            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);\n            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);\n            BigInteger nn = ((p + 1) >> 1) % p;\n            while (nn > 0) {\n                if ((nn & 1) == 1) {\n                    r = mul(r, s);\n                }\n                s = mul(s, s);\n                nn >>= 1;\n            }\n\n            \n            if (r.Item2 != 0) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            if (r.Item1 * r.Item1 % p != n) {\n                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);\n            }\n\n            \n            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(C(\"10\", \"13\"));\n            Console.WriteLine(C(\"56\", \"101\"));\n            Console.WriteLine(C(\"8218\", \"10007\"));\n            Console.WriteLine(C(\"8219\", \"10007\"));\n            Console.WriteLine(C(\"331575\", \"1000003\"));\n            Console.WriteLine(C(\"665165880\", \"1000000007\"));\n            Console.WriteLine(C(\"881398088036\", \"1000000000039\"));\n            Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"));\n        }\n    }\n}\n"}
{"id": 60050, "name": "Literals_String", "Python": "'c' == \"c\" \n'text' == \"text\"\n' \" '\n\" ' \"\n'\\x20' == ' '\nu'unicode string'\nu'\\u05d0' \n", "C#": "string path = @\"C:\\Windows\\System32\";\nstring multiline = @\"Line 1.\nLine 2.\nLine 3.\";\n"}
{"id": 60051, "name": "GUI_Maximum window dimensions", "Python": "\n\nimport tkinter as tk \n\nroot = tk.Tk() \nroot.state('zoomed') \nroot.update_idletasks() \ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() \nroot.mainloop()\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n"}
{"id": 60052, "name": "Enumerations", "Python": ">>> from enum import Enum\n>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')\n>>> Contact.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))\n>>> \n>>> \n>>> class Contact2(Enum):\n\tFIRST_NAME = 1\n\tLAST_NAME = 2\n\tPHONE = 3\n\n\t\n>>> Contact2.__members__\nmappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))\n>>>\n", "C#": "enum fruits { apple, banana, cherry }\n\nenum fruits { apple = 0, banana = 1, cherry = 2 }\n\nenum fruits : int { apple = 0, banana = 1, cherry = 2 }\n\n[FlagsAttribute]\nenum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }\n"}
{"id": 60053, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 60054, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 60055, "name": "A_ search algorithm", "Python": "from __future__ import print_function\nimport matplotlib.pyplot as plt\n\nclass AStarGraph(object):\n\t\n\n\tdef __init__(self):\n\t\tself.barriers = []\n\t\tself.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])\n\n\tdef heuristic(self, start, goal):\n\t\t\n\t\t\n\t\tD = 1\n\t\tD2 = 1\n\t\tdx = abs(start[0] - goal[0])\n\t\tdy = abs(start[1] - goal[1])\n\t\treturn D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\n\tdef get_vertex_neighbours(self, pos):\n\t\tn = []\n\t\t\n\t\tfor dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:\n\t\t\tx2 = pos[0] + dx\n\t\t\ty2 = pos[1] + dy\n\t\t\tif x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:\n\t\t\t\tcontinue\n\t\t\tn.append((x2, y2))\n\t\treturn n\n\n\tdef move_cost(self, a, b):\n\t\tfor barrier in self.barriers:\n\t\t\tif b in barrier:\n\t\t\t\treturn 100 \n\t\treturn 1 \n\ndef AStarSearch(start, end, graph):\n\n\tG = {} \n\tF = {} \n\n\t\n\tG[start] = 0\n\tF[start] = graph.heuristic(start, end)\n\n\tclosedVertices = set()\n\topenVertices = set([start])\n\tcameFrom = {}\n\n\twhile len(openVertices) > 0:\n\t\t\n\t\tcurrent = None\n\t\tcurrentFscore = None\n\t\tfor pos in openVertices:\n\t\t\tif current is None or F[pos] < currentFscore:\n\t\t\t\tcurrentFscore = F[pos]\n\t\t\t\tcurrent = pos\n\n\t\t\n\t\tif current == end:\n\t\t\t\n\t\t\tpath = [current]\n\t\t\twhile current in cameFrom:\n\t\t\t\tcurrent = cameFrom[current]\n\t\t\t\tpath.append(current)\n\t\t\tpath.reverse()\n\t\t\treturn path, F[end] \n\n\t\t\n\t\topenVertices.remove(current)\n\t\tclosedVertices.add(current)\n\n\t\t\n\t\tfor neighbour in graph.get_vertex_neighbours(current):\n\t\t\tif neighbour in closedVertices:\n\t\t\t\tcontinue \n\t\t\tcandidateG = G[current] + graph.move_cost(current, neighbour)\n\n\t\t\tif neighbour not in openVertices:\n\t\t\t\topenVertices.add(neighbour) \n\t\t\telif candidateG >= G[neighbour]:\n\t\t\t\tcontinue \n\n\t\t\t\n\t\t\tcameFrom[neighbour] = current\n\t\t\tG[neighbour] = candidateG\n\t\t\tH = graph.heuristic(neighbour, end)\n\t\t\tF[neighbour] = G[neighbour] + H\n\n\traise RuntimeError(\"A* failed to find a solution\")\n\nif __name__==\"__main__\":\n\tgraph = AStarGraph()\n\tresult, cost = AStarSearch((0,0), (7,7), graph)\n\tprint (\"route\", result)\n\tprint (\"cost\", cost)\n\tplt.plot([v[0] for v in result], [v[1] for v in result])\n\tfor barrier in graph.barriers:\n\t\tplt.plot([v[0] for v in barrier], [v[1] for v in barrier])\n\tplt.xlim(-1,8)\n\tplt.ylim(-1,8)\n\tplt.show()\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace A_star\n{\n    class A_star\n    {\n        \n        public class Coordinates : IEquatable<Coordinates>\n        {\n            public int row;\n            public int col;\n\n            public Coordinates() { this.row = -1; this.col = -1; }\n            public Coordinates(int row, int col) { this.row = row; this.col = col; }\n\n            public Boolean Equals(Coordinates c)\n            {\n                if (this.row == c.row && this.col == c.col)\n                    return true;\n                else\n                    return false;\n            }\n        }\n\n        \n        \n        public class Cell\n        {\n            public int cost;\n            public int g;\n            public int f;\n            public Coordinates parent;\n        }\n\n        \n        public class Astar\n        {\n            \n            public Cell[,] cells = new Cell[8, 8];\n            \n            public List<Coordinates> path = new List<Coordinates>();\n            \n            public List<Coordinates> opened = new List<Coordinates>();\n            \n            public List<Coordinates> closed = new List<Coordinates>();\n            \n            public Coordinates startCell = new Coordinates(0, 0);\n            \n            public Coordinates finishCell = new Coordinates(7, 7);\n\n            \n            public Astar()\n            {\n                \n                for (int i = 0; i < 8; i++)\n                    for (int j = 0; j < 8; j++)\n                    {\n                        cells[i, j] = new Cell();\n                        cells[i, j].parent = new Coordinates();\n                        if (IsAWall(i, j))\n                            cells[i, j].cost = 100;\n                        else\n                            cells[i, j].cost = 1;\n                    }\n\n                \n                opened.Add(startCell);\n\n                \n                Boolean pathFound = false;\n\n                \n                do\n                {\n                    List<Coordinates> neighbors = new List<Coordinates>();\n                    \n                    Coordinates currentCell = ShorterExpectedPath();\n                    \n                    neighbors = neighborsCells(currentCell);\n                    foreach (Coordinates newCell in neighbors)\n                    {\n                        \n                        if (newCell.row == finishCell.row && newCell.col == finishCell.col)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            pathFound = true;\n                            break;\n                        }\n\n                        \n                        else if (!opened.Contains(newCell) && !closed.Contains(newCell))\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                        }\n\n                        \n                        \n                        else if (cells[newCell.row, newCell.col].g > cells[currentCell.row,\n                            currentCell.col].g + cells[newCell.row, newCell.col].cost)\n                        {\n                            cells[newCell.row, newCell.col].g = cells[currentCell.row,\n                                currentCell.col].g + cells[newCell.row, newCell.col].cost;\n                            cells[newCell.row, newCell.col].f =\n                                cells[newCell.row, newCell.col].g + Heuristic(newCell);\n                            cells[newCell.row, newCell.col].parent.row = currentCell.row;\n                            cells[newCell.row, newCell.col].parent.col = currentCell.col;\n                            SetCell(newCell, opened);\n                            ResetCell(newCell, closed);\n                        }\n                    }\n                    SetCell(currentCell, closed);\n                    ResetCell(currentCell, opened);\n                } while (opened.Count > 0 && pathFound == false);\n\n                if (pathFound)\n                {\n                    path.Add(finishCell);\n                    Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col);\n                    \n                    while (cells[currentCell.row, currentCell.col].parent.row >= 0)\n                    {\n                        path.Add(cells[currentCell.row, currentCell.col].parent);\n                        int tmp_row = cells[currentCell.row, currentCell.col].parent.row;\n                        currentCell.col = cells[currentCell.row, currentCell.col].parent.col;\n                        currentCell.row = tmp_row;\n                    }\n\n                    \n                    for (int i = 0; i < 8; i++)\n                    {\n                        for (int j = 0; j < 8; j++)\n                        {\n                            \n                            \n                            char gr = '.';\n                            \n                            if (path.Contains(new Coordinates(i, j))) { gr = 'X'; }\n                            \n                            else if (cells[i, j].cost > 1) { gr = '\\u2588'; }\n                            System.Console.Write(gr);\n                        }\n                        System.Console.WriteLine();\n                    }\n\n                    \n                    System.Console.Write(\"\\nPath: \");\n                    for (int i = path.Count - 1; i >= 0; i--)\n                    {\n                        System.Console.Write(\"({0},{1})\", path[i].row, path[i].col);\n                    }\n\n                    \n                    System.Console.WriteLine(\"\\nPath cost: {0}\", path.Count - 1);\n\n                    \n                    String wt = System.Console.ReadLine();\n                }\n            }\n\n            \n            \n            public Coordinates ShorterExpectedPath()\n            {\n                int sep = 0;\n                if (opened.Count > 1)\n                {\n                    for (int i = 1; i < opened.Count; i++)\n                    {\n                        if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row,\n                            opened[sep].col].f)\n                        {\n                            sep = i;\n                        }\n                    }\n                }\n                return opened[sep];\n            }\n\n            \n            public List<Coordinates> neighborsCells(Coordinates c)\n            {\n                List<Coordinates> lc = new List<Coordinates>();\n                for (int i = -1; i <= 1; i++)\n                    for (int j = -1; j <= 1; j++)\n                        if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 &&\n                            (i != 0 || j != 0))\n                        {\n                            lc.Add(new Coordinates(c.row + i, c.col + j));\n                        }\n                return lc;\n            }\n\n            \n            public bool IsAWall(int row, int col)\n            {\n                int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 },\n                    { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } };\n                bool found = false;\n                for (int i = 0; i < walls.GetLength(0); i++)\n                    if (walls[i,0] == row && walls[i,1] == col)\n                        found = true;\n                return found;\n            }\n\n            \n            \n            public int Heuristic(Coordinates cell)\n            {\n                int dRow = Math.Abs(finishCell.row - cell.row);\n                int dCol = Math.Abs(finishCell.col - cell.col);\n                return Math.Max(dRow, dCol);\n            }\n\n            \n            public void SetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell) == false)\n                {\n                    coordinatesList.Add(cell);\n                }\n            }\n\n            \n            public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList)\n            {\n                if (coordinatesList.Contains(cell))\n                {\n                    coordinatesList.Remove(cell);\n                }\n            }\n        }\n\n        \n        static void Main(string[] args)\n        {\n            Astar astar = new Astar();\n        }\n    }\n}\n"}
{"id": 60056, "name": "Range extraction", "Python": "def range_extract(lst):\n    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'\n    lenlst = len(lst)\n    i = 0\n    while i< lenlst:\n        low = lst[i]\n        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1\n        hi = lst[i]\n        if   hi - low >= 2:\n            yield (low, hi)\n        elif hi - low == 1:\n            yield (low,)\n            yield (hi,)\n        else:\n            yield (low,)\n        i += 1\n\ndef printr(ranges):\n    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)\n                     for r in ranges ) )\n\nif __name__ == '__main__':\n    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,\n                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],\n                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:\n        \n        printr(range_extract(lst))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass RangeExtraction\n{\n    static void Main()\n    {\n        const string testString = \"0,  1,  2,  4,  6,  7,  8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39\";\n        var result = String.Join(\",\", RangesToStrings(GetRanges(testString)));\n        Console.Out.WriteLine(result);\n    }\n\n    public static IEnumerable<IEnumerable<int>> GetRanges(string testString)\n    {\n        var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));\n        var current = new List<int>();\n        foreach (var n in numbers)\n        {\n            if (current.Count == 0)\n            {\n                current.Add(n);\n            }\n            else\n            {\n                if (current.Max() + 1 == n)\n                {\n                    current.Add(n);\n                }\n                else\n                {\n                    yield return current;\n                    current = new List<int> { n };\n                }\n            }\n        }\n        yield return current;\n    }\n\n    public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)\n    {\n        foreach (var range in ranges)\n        {\n            if (range.Count() == 1)\n            {\n                yield return range.Single().ToString();\n            }\n            else if (range.Count() == 2)\n            {\n                yield return range.Min() + \",\" + range.Max();\n            }\n            else\n            {\n                yield return range.Min() + \"-\" + range.Max();\n            }\n        }\n    }\n}\n"}
{"id": 60057, "name": "Maximum triangle path sum", "Python": "fun maxpathsum(t): \n    let a = val t\n    for i in a.length-1..-1..1, c in linearindices a[r]:\n        a[r, c] += max(a[r+1, c], a[r=1, c+1])\n    return a[1, 1]\n\nlet test = [\n    [55],\n    [94, 48],\n    [95, 30, 96],\n    [77, 71, 26, 67],\n    [97, 13, 76, 38, 45],\n    [07, 36, 79, 16, 37, 68],\n    [48, 07, 09, 18, 70, 26, 06],\n    [18, 72, 79, 46, 59, 79, 29, 90],\n    [20, 76, 87, 11, 32, 07, 07, 49, 18],\n    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n]\n\n@print maxpathsum test\n", "C#": "using System;\n\nnamespace RosetaCode\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint[,] list = new int[18,19];\n\t\t\tstring input = @\"55\n\t                        94 48\n\t                       95 30 96\n\t                     77 71 26 67\n\t                    97 13 76 38 45\n\t                  07 36 79 16 37 68\n\t                 48 07 09 18 70 26 06\n\t               18 72 79 46 59 79 29 90\n\t              20 76 87 11 32 07 07 49 18\n\t            27 83 58 35 71 11 25 57 29 85\n\t           14 64 36 96 27 11 58 56 92 18 55\n\t         02 90 03 60 48 49 41 46 33 36 47 23\n\t        92 50 48 02 36 59 42 79 72 20 82 77 42\n\t      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n\t   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n\t  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n\t27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\";\n\t\t\tvar charArray = input.Split ('\\n');\n\n\t\t\tfor (int i=0; i < charArray.Length; i++) {\n\t\t\t\tvar numArr = charArray[i].Trim().Split(' ');\n\n\t\t\t\tfor (int j = 0; j<numArr.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tint number = Convert.ToInt32 (numArr[j]);\n\t\t\t\t\tlist [i, j] = number;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 16; i >= 0; i--) {\n\t\t\t\tfor (int j = 0; j < 18; j++) {\n\t\t\t\t\tlist[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tConsole.WriteLine (string.Format(\"Maximum total: {0}\", list [0, 0]));\n\t\t}\n\t}\n}\n"}
{"id": 60058, "name": "Terminal control_Cursor movement", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n"}
{"id": 60059, "name": "Terminal control_Cursor movement", "Python": "import curses\n\nscr = curses.initscr()\n\ndef move_left():\n\ty,x = curses.getyx()\n\tcurses.move(y,x-1)\n\t\n\ndef move_right():\n\ty,x = curses.getyx()\n\tcurses.move(y,x+1)\n\t\n\ndef move_up():\n\ty,x = curses.getyx()\n\tcurses.move(y-1,x)\n\t\n\ndef move_down():\n\ty,x = curses.getyx()\n\tcurses.move(y+1,x)\n\n\ndef move_line_home()\t\n\ty,x = curses.getyx()\n\tcurses.move(y,0)\n\n\ndef move_line_end()\t\n\ty,x = curses.getyx()\n\tmaxy,maxx = scr.getmaxyx()\n\tcurses.move(y,maxx)\n\n\ndef move_page_home():\n\tcurses.move(0,0)\n\t\n\ndef move_page_end():\n\ty,x = scr.getmaxyx()\n\tcurses.move(y,x)\n", "C#": "static void Main(string[] args)\n{\n    \n    Console.Write(\"\\n\\n\\n\\n     Cursor is here -->   \");\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft - 1; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.CursorLeft + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop - 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorTop = Console.CursorTop + 1;\n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = 0; \n    System.Threading.Thread.Sleep(3000);\n    Console.CursorLeft = Console.BufferWidth - 1;\n     \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(0,0); \n    System.Threading.Thread.Sleep(3000);\n    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); \n    System.Threading.Thread.Sleep(3000);\n}\n"}
{"id": 60060, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 60061, "name": "Four bit adder", "Python": "\n\nfrom myhdl import *\n\n\n\n@block\ndef NOTgate( a,  q ):   \n   \n   @always_comb   \n   def NOTgateLogic():\n      q.next = not a\n\n   return NOTgateLogic   \n\n\n@block\ndef ANDgate( a, b,  q ):\n   \n   @always_comb \n   def ANDgateLogic():\n      q.next = a and b\n\n   return ANDgateLogic\n\n\n@block\ndef ORgate( a, b,  q ):\n      \n   @always_comb  \n   def ORgateLogic():\n      q.next = a or b\n\n   return ORgateLogic\n\n\n\n\n@block\ndef XORgate( a, b,  q ):\n      \n   \n   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]\n   \n   inv0 = NOTgate( a,  nota )\n   inv1 = NOTgate( b,  notb )\n   and2a = ANDgate( a, notb,  annotb )\n   and2b = ANDgate( b, nota,  bnnota )\n   or2a = ORgate( annotb, bnnota,  q )\n\n   return inv0, inv1, and2a, and2b, or2a\n\n\n@block\ndef HalfAdder( in_a, in_b,  summ, carry ):\n    \n   and2a =  ANDgate(in_a, in_b,  carry)\n   xor2a =  XORgate(in_a, in_b,  summ)\n\n   return and2a, xor2a\n\n\n@block\ndef FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):\n   \n\n   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]\n\n   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )\n   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )\n   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)\n\n   return HalfAdder01, HalfAdder02, or2a\n\n\n@block\ndef Adder4b( ina, inb,  cOut, sum4):\n    \n\n   cl = [Signal(bool()) for i in range(0,4)]  \n   sl = [Signal(bool()) for i in range(4)]  \n\n   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )\n   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] ) \n   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] ) \n   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut ) \n\n   sc = ConcatSignal(*reversed(sl))  \n\n   @always_comb\n   def list2intbv():\n      sum4.next = sc  \n\n   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv\n\n\n\nt_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]\nina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]\n\nfrom random import randrange \n\n@block\ndef Test_Adder4b():\n   \n   dut = Adder4b( ina4, inb4,  t_co, sum4 )\n\n   @instance\n   def check():\n      print( \"\\n      b   a   |  c1    s   \\n     -------------------\" )\n      for i in range(15):\n         ina4.next, inb4.next = randrange(2**4), randrange(2**4)\n         yield delay(5)\n         print( \"     %2d  %2d   |  %2d   %2d     \" \\\n                % (ina4,inb4, t_co,sum4) )\n         assert t_co * 16 + sum4 == ina4 + inb4  \n      print()\n\n   return dut, check\n\n\n\n\ndef main():\n   simInst = Test_Adder4b()\n   simInst.name = \"mySimInst\"\n   simInst.config_sim(trace=True)  \n   simInst.run_sim(duration=None)\n\n   inst = Adder4b( ina4, inb4,  t_co, sum4 )  \n   inst.convert(hdl='VHDL')  \n   inst.convert(hdl='Verilog')  \n\n    \nif __name__ == '__main__':\n   main()\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks.FourBitAdder\n{\n\tpublic struct BitAdderOutput\n\t{\n\t\tpublic bool S { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn \"S\" + ( S ? \"1\" : \"0\" ) + \"C\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct Nibble\n\t{\n\t\tpublic bool _1 { get; set; }\n\t\tpublic bool _2 { get; set; }\n\t\tpublic bool _3 { get; set; }\n\t\tpublic bool _4 { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn ( _4 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _3 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _2 ? \"1\" : \"0\" )\n\t\t\t\t+ ( _1 ? \"1\" : \"0\" );\n\t\t}\n\t}\n\tpublic struct FourBitAdderOutput\n\t{\n\t\tpublic Nibble N { get; set; }\n\t\tpublic bool C { get; set; }\n\t\tpublic override string ToString ( )\n\t\t{\n\t\t\treturn N.ToString ( ) + \"c\" + ( C ? \"1\" : \"0\" );\n\t\t}\n\t}\n\n\tpublic static class LogicGates\n\t{\n\t\t\n\t\tpublic static bool Not ( bool A ) { return !A; }\n\t\tpublic static bool And ( bool A, bool B ) { return A && B; }\n\t\tpublic static bool Or ( bool A, bool B ) { return A || B; }\n\n\t\t\n\t\tpublic static bool Xor ( bool A, bool B ) {\treturn Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }\n\t}\n\n\tpublic static class ConstructiveBlocks\n\t{\n\t\tpublic static BitAdderOutput HalfAdder ( bool A, bool B )\n\t\t{\n\t\t\treturn new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };\n\t\t}\n\n\t\tpublic static BitAdderOutput FullAdder ( bool A, bool B, bool CI )\n\t\t{\n\t\t\tBitAdderOutput HA1 = HalfAdder ( CI, A );\n\t\t\tBitAdderOutput HA2 = HalfAdder ( HA1.S, B );\n\n\t\t\treturn new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };\n\t\t}\n\n\t\tpublic static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )\n\t\t{\n\n\t\t\tBitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );\n\t\t\tBitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );\n\t\t\tBitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );\n\t\t\tBitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );\n\n\t\t\treturn new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };\n\t\t}\n\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Four Bit Adder\" );\n\n\t\t\tfor ( int i = 0; i < 256; i++ )\n\t\t\t{\n\t\t\t\tNibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tNibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };\n\t\t\t\tif ( (i & 1) == 1)\n\t\t\t\t{\n\t\t\t\t\tA._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 2 ) == 2 )\n\t\t\t\t{\n\t\t\t\t\tA._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 4 ) == 4 )\n\t\t\t\t{\n\t\t\t\t\tA._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 8 ) == 8 )\n\t\t\t\t{\n\t\t\t\t\tA._4 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 16 ) == 16 )\n\t\t\t\t{\n\t\t\t\t\tB._1 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 32 ) == 32)\n\t\t\t\t{\n\t\t\t\t\tB._2 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 64 ) == 64 )\n\t\t\t\t{\n\t\t\t\t\tB._3 = true;\n\t\t\t\t}\n\t\t\t\tif ( ( i & 128 ) == 128 )\n\t\t\t\t{\n\t\t\t\t\tB._4 = true;\n\t\t\t\t}\n\n\t\t\t\tConsole.WriteLine ( \"{0} + {1} = {2}\", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );\n\n\t\t\t}\n\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t}\n}\n"}
{"id": 60062, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 60063, "name": "Unix_ls", "Python": ">>> import os\n>>> print('\\n'.join(sorted(os.listdir('.'))))\nDLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nREADME.txt\nScripts\nTools\ninclude\nlibs\npython.exe\npythonw.exe\ntcl\n>>>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Unix_ls\n{\n    public class UnixLS\n    {\n        public static void Main(string[] args)\n        {\n            UnixLS ls = new UnixLS();\n            ls.list(args.Length.Equals(0) ? \".\" : args[0]);\n        }\n\n        private void list(string folder)\n        {\n            foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos(\"*\", SearchOption.TopDirectoryOnly))\n            {\n                Console.WriteLine(fileSystemInfo.Name);\n            }\n        }\n    }\n}\n"}
{"id": 60064, "name": "UTF-8 encode and decode", "Python": "\nfrom unicodedata import name\n\n\ndef unicode_code(ch):\n    return 'U+{:04x}'.format(ord(ch))\n\n\ndef utf8hex(ch):\n    return \" \".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()\n\n\nif __name__ == \"__main__\":\n    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))\n    chars = ['A', 'ö', 'Ж', '€', '𝄞']\n    for char in chars:\n        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))\n", "C#": "using System;\nusing System.Text;\n\nnamespace Rosetta\n{\n    class Program\n    {\n        static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));\n        static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);\n        static void Main(string[] args)\n        {\n            Console.OutputEncoding = Encoding.UTF8;  \n            foreach (int unicodePoint in new int[] {  0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})\n            {\n                byte[] asUtf8bytes = MyEncoder(unicodePoint);\n                string theCharacter = MyDecoder(asUtf8bytes);\n                Console.WriteLine(\"{0,8} {1,5}     {2,-15}\", unicodePoint.ToString(\"X4\"), theCharacter, BitConverter.ToString(asUtf8bytes));\n            }\n        }\n    }\n}\n\n"}
{"id": 60065, "name": "Magic squares of doubly even order", "Python": "def MagicSquareDoublyEven(order):\n    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]\n    n1 = order/4\n    for r in range(n1):\n        r1 = sq[r][n1:-n1]\n        r2 = sq[order -r - 1][n1:-n1]\n        r1.reverse()\n        r2.reverse()\n        sq[r][n1:-n1] = r2\n        sq[order -r - 1][n1:-n1] = r1\n    for r in range(n1, order-n1):\n        r1 = sq[r][:n1]\n        r2 = sq[order -r - 1][order-n1:]\n        r1.reverse()\n        r2.reverse()\n        sq[r][:n1] = r2\n        sq[order -r - 1][order-n1:] = r1\n    return sq\n\ndef printsq(s):\n    n = len(s)\n    bl = len(str(n**2))+1\n    for i in range(n):\n        print ''.join( [ (\"%\"+str(bl)+\"s\")%(str(x)) for x in s[i]] )\n    print \"\\nMagic constant = %d\"%sum(s[0])\n\nprintsq(MagicSquareDoublyEven(8))\n", "C#": "using System;\n\nnamespace MagicSquareDoublyEven\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = 8;\n            var result = MagicSquareDoublyEven(n);\n            for (int i = 0; i < result.GetLength(0); i++)\n            {\n                for (int j = 0; j < result.GetLength(1); j++)\n                    Console.Write(\"{0,2} \", result[i, j]);\n                Console.WriteLine();\n            }\n            Console.WriteLine(\"\\nMagic constant: {0} \", (n * n + 1) * n / 2);\n            Console.ReadLine();\n        }\n\n        private static int[,] MagicSquareDoublyEven(int n)\n        {\n            if (n < 4 || n % 4 != 0)\n                throw new ArgumentException(\"base must be a positive \"\n                        + \"multiple of 4\");\n\n            \n            int bits = 0b1001_0110_0110_1001;\n            int size = n * n;\n            int mult = n / 4;  \n\n            int[,] result = new int[n, n];\n\n            for (int r = 0, i = 0; r < n; r++)\n            {\n                for (int c = 0; c < n; c++, i++)\n                {\n                    int bitPos = c / mult + (r / mult) * 4;\n                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n                }\n            }\n            return result;\n        }\n    }\n}\n"}
{"id": 60066, "name": "Same fringe", "Python": "try:\n    from itertools import zip_longest as izip_longest \nexcept:\n    from itertools import izip_longest                \n\ndef fringe(tree):\n    \n    for node1 in tree:\n        if isinstance(node1, tuple):\n            for node2 in fringe(node1):\n                yield node2\n        else:\n            yield node1\n\ndef same_fringe(tree1, tree2):\n    return all(node1 == node2 for node1, node2 in\n               izip_longest(fringe(tree1), fringe(tree2)))\n\nif __name__ == '__main__':\n    a = 1, 2, 3, 4, 5, 6, 7, 8\n    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))\n    c = (((1, 2), 3), 4), 5, 6, 7, 8\n\n    x = 1, 2, 3, 4, 5, 6, 7, 8, 9\n    y = 0, 2, 3, 4, 5, 6, 7, 8\n    z = 1, 2, (4, 3), 5, 6, 7, 8\n\n    assert same_fringe(a, a)\n    assert same_fringe(a, b)\n    assert same_fringe(a, c)\n\n    assert not same_fringe(a, x)\n    assert not same_fringe(a, y)\n    assert not same_fringe(a, z)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Same_Fringe\n{\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar rnd = new Random(110456);\n\t\t\tvar randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();\n\t\t\tvar bt1 = new BinTree<int>(randList);\n\t\t\t\n\t\t\tShuffle(randList, 428);\n\t\t\tvar bt2 = new BinTree<int>(randList);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"True compare worked\" : \"True compare failed\");\n\t\t\t\n\t\t\tbt1.Insert(0);\n\t\t\tConsole.WriteLine(bt1.CompareTo(bt2) ? \"False compare failed\" : \"False compare worked\");\n\t\t}\n\n\t\tstatic void Shuffle<T>(List<T> values, int seed)\n\t\t{\n\t\t\tvar rnd = new Random(seed);\n\n\t\t\tfor (var i = 0; i < values.Count - 2; i++)\n\t\t\t{\n\t\t\t\tvar iSwap = rnd.Next(values.Count - i) + i;\n\t\t\t\tvar tmp = values[iSwap];\n\t\t\t\tvalues[iSwap] = values[i];\n\t\t\t\tvalues[i] = tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tclass BinTree<T> where T:IComparable\n\t{\n\t\tprivate BinTree<T> _left;\n\t\tprivate BinTree<T> _right;\n\t\tprivate T _value;\n\n\t\tprivate BinTree<T> Left\n\t\t{\n\t\t\tget { return _left; }\n\t\t}\n\n\t\tprivate BinTree<T> Right\n\t\t{\n\t\t\tget { return _right; }\n\t\t}\n\n\t\t\n\t\t\n\t\tprivate T Value\n\t\t{\n\t\t\tget { return _value; }\n\t\t}\n\n\t\tpublic bool IsLeaf { get { return Left == null; } }\n\n\t\tprivate BinTree(BinTree<T> left, BinTree<T> right, T value)\n\t\t{\n\t\t\t_left = left;\n\t\t\t_right = right;\n\t\t\t_value = value;\n\t\t}\n\n\t\tpublic BinTree(T value) : this(null, null, value) { }\n\n\t\tpublic BinTree(IEnumerable<T> values)\n\t\t{\n\t\t\t\n\t\t\t_value = values.First();\n\t\t\tforeach (var value in values.Skip(1))\n\t\t\t{\n\t\t\t\tInsert(value);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic void Insert(T value)\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(value);\n\t\t\t\t\t_right = new BinTree<T>(Value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_left = new BinTree<T>(Value);\n\t\t\t\t\t_right = new BinTree<T>(value);\n\t\t\t\t\t_value = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (value.CompareTo(Value) < 0)\n\t\t\t\t{\n\t\t\t\t\tLeft.Insert(value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRight.Insert(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<T> GetLeaves()\n\t\t{\n\t\t\tif (IsLeaf)\n\t\t\t{\n\t\t\t\tyield return Value;\n\t\t\t\tyield break;\n\t\t\t}\n\t\t\tforeach (var val in Left.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t\tforeach (var val in Right.GetLeaves())\n\t\t\t{\n\t\t\t\tyield return val;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool CompareTo(BinTree<T> other)\n\t\t{\n\t\t\treturn other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);\n\t\t}\n\t}\n}\n"}
{"id": 60067, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n"}
{"id": 60068, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Python": "[print(\"( \" + \"1\"*i + \"3 ) ^ 2 = \" + str(int(\"1\"*i + \"3\")**2)) for i in range(0,8)]\n", "C#": "using System; using BI = System.Numerics.BigInteger;\nclass Program { static void Main(string[] args) {\n    for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3)\n      Console.WriteLine(\"{1,43} {0,-20}\", x, x * x); } }\n"}
{"id": 60069, "name": "Peaceful chess queen armies", "Python": "from itertools import combinations, product, count\nfrom functools import lru_cache, reduce\n\n\n_bbullet, _wbullet = '\\u2022\\u25E6'\n_or = set.__or__\n\ndef place(m, n):\n    \"Place m black and white queens, peacefully, on an n-by-n board\"\n    board = set(product(range(n), repeat=2))  \n    placements = {frozenset(c) for c in combinations(board, m)}\n    for blacks in placements:\n        black_attacks = reduce(_or, \n                               (queen_attacks_from(pos, n) for pos in blacks), \n                               set())\n        for whites in {frozenset(c)     \n                       for c in combinations(board - black_attacks, m)}:\n            if not black_attacks & whites:\n                return blacks, whites\n    return set(), set()\n\n@lru_cache(maxsize=None)\ndef queen_attacks_from(pos, n):\n    x0, y0 = pos\n    a = set([pos])    \n    a.update((x, y0) for x in range(n))    \n    a.update((x0, y) for y in range(n))    \n    \n    for x1 in range(n):\n        \n        y1 = y0 -x0 +x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n        \n        y1 = y0 +x0 -x1\n        if 0 <= y1 < n: \n            a.add((x1, y1))\n    return a\n\ndef pboard(black_white, n):\n    \"Print board\"\n    if black_white is None: \n        blk, wht = set(), set()\n    else:\n        blk, wht = black_white\n    print(f\"\n          f\"on a {n}-by-{n} board:\", end='')\n    for x, y in product(range(n), repeat=2):\n        if y == 0:\n            print()\n        xy = (x, y)\n        ch = ('?' if xy in blk and xy in wht \n              else 'B' if xy in blk\n              else 'W' if xy in wht\n              else _bbullet if (x + y)%2 else _wbullet)\n        print('%s' % ch, end='')\n    print()\n\nif __name__ == '__main__':\n    n=2\n    for n in range(2, 7):\n        print()\n        for m in count(1):\n            ans = place(m, n)\n            if ans[0]:\n                pboard(ans, n)\n            else:\n                print (f\"\n                break\n    \n    print('\\n')\n    m, n = 5, 7\n    ans = place(m, n)\n    pboard(ans, n)\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace PeacefulChessQueenArmies {\n    using Position = Tuple<int, int>;\n\n    enum Piece {\n        Empty,\n        Black,\n        White\n    }\n\n    class Program {\n        static bool IsAttacking(Position queen, Position pos) {\n            return queen.Item1 == pos.Item1\n                || queen.Item2 == pos.Item2\n                || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);\n        }\n\n        static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {\n            if (m == 0) {\n                return true;\n            }\n            bool placingBlack = true;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    var pos = new Position(i, j);\n                    foreach (var queen in pBlackQueens) {\n                        if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    foreach (var queen in pWhiteQueens) {\n                        if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {\n                            goto inner;\n                        }\n                    }\n                    if (placingBlack) {\n                        pBlackQueens.Add(pos);\n                        placingBlack = false;\n                    } else {\n                        pWhiteQueens.Add(pos);\n                        if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                            return true;\n                        }\n                        pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n                        pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);\n                        placingBlack = true;\n                    }\n                inner: { }\n                }\n            }\n            if (!placingBlack) {\n                pBlackQueens.RemoveAt(pBlackQueens.Count - 1);\n            }\n            return false;\n        }\n\n        static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {\n            var board = new Piece[n * n];\n\n            foreach (var queen in blackQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.Black;\n            }\n            foreach (var queen in whiteQueens) {\n                board[queen.Item1 * n + queen.Item2] = Piece.White;\n            }\n\n            for (int i = 0; i < board.Length; i++) {\n                if (i != 0 && i % n == 0) {\n                    Console.WriteLine();\n                }\n                switch (board[i]) {\n                    case Piece.Black:\n                        Console.Write(\"B \");\n                        break;\n                    case Piece.White:\n                        Console.Write(\"W \");\n                        break;\n                    case Piece.Empty:\n                        int j = i / n;\n                        int k = i - j * n;\n                        if (j % 2 == k % 2) {\n                            Console.Write(\"  \");\n                        } else {\n                            Console.Write(\"# \");\n                        }\n                        break;\n                }\n            }\n\n            Console.WriteLine(\"\\n\");\n        }\n\n        static void Main() {\n            var nms = new int[,] {\n                {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n                {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n                {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n                {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n            };\n            for (int i = 0; i < nms.GetLength(0); i++) {\n                Console.WriteLine(\"{0} black and {0} white queens on a {1} x {1} board:\", nms[i, 1], nms[i, 0]);\n                List<Position> blackQueens = new List<Position>();\n                List<Position> whiteQueens = new List<Position>();\n                if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {\n                    PrintBoard(nms[i, 0], blackQueens, whiteQueens);\n                } else {\n                    Console.WriteLine(\"No solution exists.\\n\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 60070, "name": "Move-to-front algorithm", "Python": "from __future__ import print_function\nfrom string import ascii_lowercase\n\nSYMBOLTABLE = list(ascii_lowercase)\n\ndef move2front_encode(strng, symboltable):\n    sequence, pad = [], symboltable[::]\n    for char in strng:\n        indx = pad.index(char)\n        sequence.append(indx)\n        pad = [pad.pop(indx)] + pad\n    return sequence\n\ndef move2front_decode(sequence, symboltable):\n    chars, pad = [], symboltable[::]\n    for indx in sequence:\n        char = pad[indx]\n        chars.append(char)\n        pad = [pad.pop(indx)] + pad\n    return ''.join(chars)\n\nif __name__ == '__main__':\n    for s in ['broood', 'bananaaa', 'hiphophiphop']:\n        encode = move2front_encode(s, SYMBOLTABLE)\n        print('%14r encodes to %r' % (s, encode), end=', ')\n        decode = move2front_decode(encode, SYMBOLTABLE)\n        print('which decodes back to %r' % decode)\n        assert s == decode, 'Whoops!'\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace MoveToFront\n{\n    class Program\n    {\n        private static char[] symbolTable;\n        private static void setSymbolTable()\n        {\n            symbolTable = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\n        }\n\n        private static void moveToFront(int charIndex)\n        {\n            char toFront = symbolTable[charIndex];\n            for (int j = charIndex; j > 0; j--)\n            {\n                symbolTable[j] = symbolTable[j - 1];\n            }\n            symbolTable[0] = toFront;\n        }\n\n        public static int[] Encode(string input)\n        {\n            setSymbolTable();\n            var output = new List<int>();\n            foreach (char c in input)\n            {\n                for (int i = 0; i < 26; i++)\n                {\n                    if (symbolTable[i] == c)\n                    {\n                        output.Add(i);\n                        moveToFront(i);\n                        break;\n                    }\n                }\n            }         \n            return output.ToArray();\n        }\n\n        public static string Decode(int[] input)\n        {\n            setSymbolTable();\n            var output = new StringBuilder(input.Length);\n            foreach (int n in input)\n            {\n                output.Append(symbolTable[n]);\n                moveToFront(n);\n            }\n            return output.ToString();\n        }\n\n        static void Main(string[] args)\n        {\n            string[] testInputs = new string[] { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n            int[] encoding;\n            foreach (string s in testInputs) \n            {\n                Console.WriteLine($\"Encoding for '{s}':\");\n                encoding = Encode(s);\n                foreach (int i in encoding)\n                {\n                    Console.Write($\"{i} \");\n                }\n                Console.WriteLine($\"\\nDecoding for '{s}':\");\n                Console.WriteLine($\"{Decode(encoding)}\\n\");\n            }\n        }\n    }\n}\n"}
{"id": 60071, "name": "Sum of first n cubes", "Python": "def main():\n    fila = 0\n    lenCubos = 51\n\n    print(\"Suma de N cubos para n = [0..49]\\n\")\n\n    for n in range(1, lenCubos):\n        sumCubos = 0\n        for m in range(1, n):\n            sumCubos = sumCubos + (m ** 3)\n            \n        fila += 1\n        print(f'{sumCubos:7} ', end='')\n        if fila % 5 == 0:\n            print(\" \")\n\n    print(f\"\\nEncontrados {fila} cubos.\")\n\nif __name__ == '__main__': main()\n", "C#": "using System; using static System.Console;\nclass Program { static void Main(string[] args) {\n    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)\n      Write(\"{0,-7}{1}\",s, (i+=i==3?-4:1)==0?\"\\n\":\" \"); } }\n"}
{"id": 60072, "name": "Execute a system command", "Python": "import os\nexit_code = os.system('ls')       \noutput    = os.popen('ls').read() \n", "C#": "using System.Diagnostics;\n\nnamespace Execute\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process.Start(\"cmd.exe\", \"/c dir\");\n        }\n    }\n}\n"}
{"id": 60073, "name": "XML validation", "Python": "\nfrom __future__ import print_function\nimport lxml\nfrom lxml import etree\n\nif __name__==\"__main__\":\n\n\tparser = etree.XMLParser(dtd_validation=True)\n\tschema_root = etree.XML()\n\tschema = etree.XMLSchema(schema_root)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5</a>\", parser)\n\t\tprint (\"Finished validating good xml\")\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n\n\t\n\tparser = etree.XMLParser(schema = schema)\n\ttry:\n\t\troot = etree.fromstring(\"<a>5<b>foobar</b></a>\", parser)\n\texcept lxml.etree.XMLSyntaxError as err:\n\t\tprint (err)\n", "C#": "using System;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.IO;\n\npublic class Test\n{\n\tpublic static void Main()\n\t{\n\t\t\n\t\tXmlSchemaSet sc = new XmlSchemaSet();\n\t\tsc.Add(null, \"http:\n\t\tXmlReaderSettings settings = new XmlReaderSettings();\n\t\tsettings.ValidationType = ValidationType.Schema;\n\t\tsettings.Schemas = sc;\n\t\tsettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\t\t\n\t\tXmlReader reader = XmlReader.Create(\"http:\n\t\t\n\t\twhile (reader.Read()); \n\t\t\n\t\tConsole.WriteLine(\"The XML file is valid for the given xsd file\");\n\t}\n\t\n\t\n\tprivate static void ValidationCallBack(object sender, ValidationEventArgs e) {\n\t\tConsole.WriteLine(\"Validation Error: {0}\", e.Message);\n\t}\n}\n"}
{"id": 60074, "name": "Longest increasing subsequence", "Python": "def longest_increasing_subsequence(X):\n    \n    N = len(X)\n    P = [0] * N\n    M = [0] * (N+1)\n    L = 0\n    for i in range(N):\n       lo = 1\n       hi = L\n       while lo <= hi:\n           mid = (lo+hi)//2\n           if (X[M[mid]] < X[i]):\n               lo = mid+1\n           else:\n               hi = mid-1\n    \n       newL = lo\n       P[i] = M[newL-1]\n       M[newL] = i\n    \n       if (newL > L):\n           L = newL\n    \n    S = []\n    k = M[L]\n    for i in range(L-1, -1, -1):\n        S.append(X[k])\n        k = P[k]\n    return S[::-1]\n\nif __name__ == '__main__':\n    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:\n        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class LIS\n{\n    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>\n        values == null ? throw new ArgumentNullException() :\n            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();\n\n    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {\n        if (index == values.Count) return current;\n        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)\n            return FindRecImpl(values, current, index + 1, comparer);\n        return Max(\n            FindRecImpl(values, current, index + 1, comparer),\n            FindRecImpl(values, current + values[index], index + 1, comparer)\n        );\n    }\n\n    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;\n\n    class Sequence<T> : IEnumerable<T>\n    {\n        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);\n\n        public Sequence(T value, Sequence<T> tail)\n        {\n            Value = value;\n            Tail = tail;\n            Length = tail == null ? 0 : tail.Length + 1;\n        }\n\n        public T Value { get; }\n        public Sequence<T> Tail { get; }\n        public int Length { get; }\n\n        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;\n        }\n\n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n    }\n}\n"}
{"id": 60075, "name": "Scope modifiers", "Python": ">>> x=\"From global scope\"\n>>> def outerfunc():\n    x = \"From scope at outerfunc\"\n\n    def scoped_local():\n        x = \"scope local\"\n        return \"scoped_local scope gives x = \" + x\n    print(scoped_local())\n\n    def scoped_nonlocal():\n        nonlocal x\n        return \"scoped_nonlocal scope gives x = \" + x\n    print(scoped_nonlocal())\n\n    def scoped_global():\n        global x\n        return \"scoped_global scope gives x = \" + x\n    print(scoped_global())\n\n    def scoped_notdefinedlocally():\n        return \"scoped_notdefinedlocally scope gives x = \" + x\n    print(scoped_notdefinedlocally())\n\n    \n>>> outerfunc()\nscoped_local scope gives x = scope local\nscoped_nonlocal scope gives x = From scope at outerfunc\nscoped_global scope gives x = From global scope\nscoped_notdefinedlocally scope gives x = From global scope\n>>>\n", "C#": "public \nprotected \ninternal \nprotected internal \nprivate \n\nprivate protected \n\n\n\n\n\n\n\n\n\n\n\n"}
{"id": 60076, "name": "Brace expansion", "Python": "def getitem(s, depth=0):\n    out = [\"\"]\n    while s:\n        c = s[0]\n        if depth and (c == ',' or c == '}'):\n            return out,s\n        if c == '{':\n            x = getgroup(s[1:], depth+1)\n            if x:\n                out,s = [a+b for a in out for b in x[0]], x[1]\n                continue\n        if c == '\\\\' and len(s) > 1:\n            s, c = s[1:], c + s[1]\n\n        out, s = [a+c for a in out], s[1:]\n\n    return out,s\n\ndef getgroup(s, depth):\n    out, comma = [], False\n    while s:\n        g,s = getitem(s, depth)\n        if not s: break\n        out += g\n\n        if s[0] == '}':\n            if comma: return out, s[1:]\n            return ['{' + a + '}' for a in out], s[1:]\n\n        if s[0] == ',':\n            comma,s = True, s[1:]\n\n    return None\n\n\nfor s in .split('\\n'):\n    print \"\\n\\t\".join([s] + getitem(s)[0]) + \"\\n\"\n", "C#": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic static class BraceExpansion\n{\n    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }\n    const char L = '{', R = '}', S = ',';\n    \n    public static void Main() {\n        string[] input = {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            @\"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            @\"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        };\n        foreach (string text in input) Expand(text);\n    }\n    \n    static void Expand(string input) {\n        Token token = Tokenize(input);\n        foreach (string value in token) Console.WriteLine(value);\n        Console.WriteLine();\n    }\n    \n    static Token Tokenize(string input) {\n        var tokens = new List<Token>();\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        int level = 0;\n        \n        foreach (char c in input) {\n            (escaping, level, tokens, buffer) = c switch {\n                _ when escaping => (false, level, tokens, buffer.Append(c)),\n                '\\\\' => (true, level, tokens, buffer.Append(c)),\n                L => (escaping, level + 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),\n                S when level > 0 => (escaping, level,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),\n                R when level > 0 => (escaping, level - 1,\n                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),\n                _ => (escaping, level, tokens, buffer.Append(c))\n            };\n        }\n        if (buffer.Length > 0) tokens.Add(buffer.Flush());\n        for (int i = 0; i < tokens.Count; i++) {\n            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {\n                tokens[i] = tokens[i].Value; \n            }\n        }\n        return new Token(tokens, TokenType.Concat);\n    }\n    \n    static List<Token> Merge(this List<Token> list) {\n        int separators = 0;\n        int last = list.Count - 1;\n        for (int i = list.Count - 3; i >= 0; i--) {\n            if (list[i].Type == TokenType.Separator) {\n                separators++;\n                Concat(list, i + 1, last);\n                list.RemoveAt(i);\n                last = i;\n            } else if (list[i].Type == TokenType.OpenBrace) {\n                Concat(list, i + 1, last);\n                if (separators > 0) {\n                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);\n                    list.RemoveRange(i+1, list.Count - i - 1);\n                } else {\n                    list[i] = L.ToString();\n                    list[^1] = R.ToString();\n                    Concat(list, i, list.Count);\n                }\n                break;\n            }\n        }\n        return list;\n    }\n    \n    static void Concat(List<Token> list, int s, int e) {\n        for (int i = e - 2; i >= s; i--) {\n            (Token a, Token b) = (list[i], list[i+1]);\n            switch (a.Type, b.Type) {\n                case (TokenType.Text, TokenType.Text):\n                    list[i] = a.Value + b.Value;\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Concat):\n                    a.SubTokens.AddRange(b.SubTokens);\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Concat, TokenType.Text) when b.Value == \"\":\n                    list.RemoveAt(i+1);\n                    break;\n                case (TokenType.Text, TokenType.Concat) when a.Value == \"\":\n                    list.RemoveAt(i);\n                    break;\n                default:\n                    list[i] = new Token(new [] { a, b }, TokenType.Concat);\n                    list.RemoveAt(i+1);\n                    break;\n            }\n        }\n    }\n    \n    private struct Token : IEnumerable<string>\n    {\n        private List<Token>? _subTokens;\n        \n        public string Value { get; }\n        public TokenType Type { get; }\n        public List<Token> SubTokens => _subTokens ??= new List<Token>();\n        \n        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);\n        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = (\"\", type, subTokens.ToList());\n        \n        public static implicit operator Token(string value) => new Token(value, TokenType.Text);\n        \n        public IEnumerator<string> GetEnumerator() => (Type switch\n        {\n            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join(\"\", p)),\n            TokenType.Alternate => from t in SubTokens from s in t select s,\n            _ => Repeat(Value, 1)\n        }).GetEnumerator();\n        \n        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        \n    }\n    \n    \n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { 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    static List<Token> With(this List<Token> list, Token token) {\n        list.Add(token);\n        return list;\n    }\n    \n    static IEnumerable<Token> Range(this List<Token> list, Range range) {\n        int start = range.Start.GetOffset(list.Count);\n        int end = range.End.GetOffset(list.Count);\n        for (int i = start; i < end; i++) yield return list[i];\n    }\n    \n    static string Flush(this StringBuilder builder) {\n        string result = builder.ToString();\n        builder.Clear();\n        return result;\n    }\n}\n"}
{"id": 60077, "name": "GUI component interaction", "Python": "import random, tkMessageBox\nfrom Tkinter import *\nwindow = Tk()\nwindow.geometry(\"300x50+100+100\")\noptions = { \"padx\":5, \"pady\":5}\ns=StringVar()\ns.set(1)\ndef increase():\n    s.set(int(s.get())+1)\ndef rand():\n    if tkMessageBox.askyesno(\"Confirmation\", \"Reset to random value ?\"):\n        s.set(random.randrange(0,5000))\ndef update(e):\n    if not e.char.isdigit():\n        tkMessageBox.showerror('Error', 'Invalid input !') \n        return \"break\"\ne = Entry(text=s)\ne.grid(column=0, row=0, **options)\ne.bind('<Key>', update)\nb1 = Button(text=\"Increase\", command=increase, **options )\nb1.grid(column=1, row=0, **options)\nb2 = Button(text=\"Random\", command=rand, **options)\nb2.grid(column=2, row=0, **options)\nmainloop()\n", "C#": "using System; \nusing System.ComponentModel; \nusing System.Windows.Forms; \n\nclass RosettaInteractionForm : Form\n{    \n    \n    \n    class NumberModel: INotifyPropertyChanged\n    {\n\n        Random rnd = new Random();\n\n        \n        public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n        int _value;\n        public int Value\n        {\n            get { return _value; }\n            set \n            { \n                _value = value;\n                \n                PropertyChanged(this, new PropertyChangedEventArgs(\"Value\"));\n            }\n        }\n\n        public void ResetToRandom(){\n            Value = rnd.Next(5000);\n        }\n    }\n\n    NumberModel model = new NumberModel{ Value = 0};\n    \n    RosettaInteractionForm()    \n    {\n        \n        var tbNumber = new MaskedTextBox\n                        { \n                            Mask=\"0000\",            \n                            ResetOnSpace = false,   \n                            Dock = DockStyle.Top    \n                        };\n        \n        tbNumber.DataBindings.Add(\"Text\", model, \"Value\");\n\n        var btIncrement = new Button{Text = \"Increment\", Dock = DockStyle.Bottom};\n        btIncrement.Click += delegate\n                        {\n                            model.Value++;\n                        };\n        var btDecrement = new Button{Text = \"Decrement\", Dock = DockStyle.Bottom};\n        btDecrement.Click += delegate\n                        {\n                            model.Value--;\n                        };\n        var btRandom = new Button{ Text=\"Reset to Random\", Dock = DockStyle.Bottom };\n        btRandom.Click += delegate\n                        {\n                            if (MessageBox.Show(\"Are you sure?\", \"Are you sure?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n                                model.ResetToRandom();\n                        };\n        Controls.Add(tbNumber);\n        Controls.Add(btIncrement);\n        Controls.Add(btDecrement);\n        Controls.Add(btRandom);\n    }\n    static void Main()\n    {\n        Application.Run(new RosettaInteractionForm());\n    }\n}\n"}
{"id": 60078, "name": "One of n lines in a file", "Python": "from random import randrange\ntry:\n    range = xrange\nexcept: pass\n\ndef one_of_n(lines): \n    choice = None\n    for i, line in enumerate(lines):\n        if randrange(i+1) == 0:\n            choice = line\n    return choice\n            \ndef one_of_n_test(n=10, trials=1000000):\n    bins = [0] * n\n    if n:\n        for i in range(trials):\n            bins[one_of_n(range(n))] += 1\n    return bins\n\nprint(one_of_n_test())\n", "C#": "    class Program\n    {\n        private static Random rnd = new Random();\n        public static int one_of_n(int n)\n        {\n            int currentChoice = 1;\n            for (int i = 2; i <= n; i++)\n            {\n                double outerLimit = 1D / (double)i;\n                if (rnd.NextDouble() < outerLimit)\n                    currentChoice = i;\n            }\n            return currentChoice;\n        }\n\n        static void Main(string[] args)\n        {\n            Dictionary<int, int> results = new Dictionary<int, int>();\n            for (int i = 1; i < 11; i++)\n                results.Add(i, 0);\n\n            for (int i = 0; i < 1000000; i++)\n            {\n                int result = one_of_n(10);\n                results[result] = results[result] + 1;\n            }\n\n            for (int i = 1; i < 11; i++)\n                Console.WriteLine(\"{0}\\t{1}\", i, results[i]);\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 60079, "name": "Addition chains", "Python": "def prepend(n, seq):\n    return [n] + seq\n\ndef check_seq(pos, seq, n, min_len):\n    if pos > min_len or seq[0] > n:\n        return min_len, 0\n    if seq[0] == n:\n        return pos, 1\n    if pos < min_len:\n        return try_perm(0, pos, seq, n, min_len)\n    return min_len, 0\n\ndef try_perm(i, pos, seq, n, min_len):\n    if i > pos:\n        return min_len, 0\n\n    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)\n    res2 = try_perm(i + 1, pos, seq, n, res1[0])\n\n    if res2[0] < res1[0]:\n        return res2\n    if res2[0] == res1[0]:\n        return res2[0], res1[1] + res2[1]\n    raise Exception(\"try_perm exception\")\n\ndef init_try_perm(x):\n    return try_perm(0, 0, [1], x, 12)\n\ndef find_brauer(num):\n    res = init_try_perm(num)\n    print\n    print \"N = \", num\n    print \"Minimum length of chains: L(n) = \", res[0]\n    print \"Number of minimum length Brauer chains: \", res[1]\n\n\nnums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\nfor i in nums:\n    find_brauer(i)\n", "C#": "using System;\n\nnamespace AdditionChains {\n    class Program {\n        static int[] Prepend(int n, int[] seq) {\n            int[] result = new int[seq.Length + 1];\n            Array.Copy(seq, 0, result, 1, seq.Length);\n            result[0] = n;\n            return result;\n        }\n\n        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {\n            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);\n            if (seq[0] == n) return new Tuple<int, int>(pos, 1);\n            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);\n            return new Tuple<int, int>(min_len, 0);\n        }\n\n        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {\n            if (i > pos) return new Tuple<int, int>(min_len, 0);\n\n            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);\n            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);\n\n            if (res2.Item1 < res1.Item1) return res2;\n            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);\n\n            throw new Exception(\"TryPerm exception\");\n        }\n\n        static Tuple<int, int> InitTryPerm(int x) {\n            return TryPerm(0, 0, new int[] { 1 }, x, 12);\n        }\n\n        static void FindBrauer(int num) {\n            Tuple<int, int> res = InitTryPerm(num);\n            Console.WriteLine();\n            Console.WriteLine(\"N = {0}\", num);\n            Console.WriteLine(\"Minimum length of chains: L(n)= {0}\", res.Item1);\n            Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2);\n        }\n\n        static void Main(string[] args) {\n            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };\n            Array.ForEach(nums, n => FindBrauer(n));\n        }\n    }\n}\n"}
{"id": 60080, "name": "Repeat", "Python": "\ndef repeat(f,n):\n  for i in range(n):\n    f();\n\ndef procedure():\n  print(\"Example\");\n\nrepeat(procedure,3); \n", "C#": "using System;\n\nnamespace Repeat {\n    class Program {\n        static void Repeat(int count, Action<int> fn) {\n            if (null == fn) {\n                throw new ArgumentNullException(\"fn\");\n            }\n            for (int i = 0; i < count; i++) {\n                fn.Invoke(i + 1);\n            }\n        }\n\n        static void Main(string[] args) {\n            Repeat(3, x => Console.WriteLine(\"Example {0}\", x));\n        }\n    }\n}\n"}
{"id": 60081, "name": "Modular inverse", "Python": ">>> def extended_gcd(aa, bb):\n    lastremainder, remainder = abs(aa), abs(bb)\n    x, lastx, y, lasty = 0, 1, 1, 0\n    while remainder:\n        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n        x, lastx = lastx - quotient*x, x\n        y, lasty = lasty - quotient*y, y\n    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n\n>>> def modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise ValueError\n\treturn x % m\n\n>>> modinv(42, 2017)\n1969\n>>>\n", "C#": "public class Program\n{\n    static void Main()\n    {\n        System.Console.WriteLine(42.ModInverse(2017));\n    }\n}\n\npublic static class IntExtensions\n{\n    public static int ModInverse(this int a, int m)\n    {\n        if (m == 1) return 0;\n        int m0 = m;\n        (int x, int y) = (1, 0);\n\n        while (a > 1) {\n            int q = a / m;\n            (a, m) = (m, a % m);\n            (x, y) = (y, x - q * y);\n        }\n        return x < 0 ? x + m0 : x;\n    }\n}\n"}
{"id": 60082, "name": "Hello world_Web server", "Python": "from wsgiref.simple_server import make_server\n\ndef app(environ, start_response):\n    start_response('200 OK', [('Content-Type','text/html')])\n    yield b\"<h1>Goodbye, World!</h1>\"\n\nserver = make_server('127.0.0.1', 8080, app)\nserver.serve_forever()\n", "C#": "using System.Text;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace WebServer\n{\n    class GoodByeWorld\n    {        \n        static void Main(string[] args)\n        {\n            const string msg = \"<html>\\n<body>\\nGoodbye, world!\\n</body>\\n</html>\\n\";        \n            const int port = 8080;\n            bool serverRunning = true;\n\n            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);\n            tcpListener.Start();\n\n            while (serverRunning)\n            {\n                Socket socketConnection = tcpListener.AcceptSocket();\n                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);\n                socketConnection.Send(bMsg);\n                socketConnection.Disconnect(true);\n            }\n        }\n    }\n}\n"}
{"id": 60083, "name": "The sieve of Sundaram", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n"}
{"id": 60084, "name": "The sieve of Sundaram", "Python": "from numpy import log\n\ndef sieve_of_Sundaram(nth, print_all=True):\n    \n    assert nth > 0, \"nth must be a positive integer\"\n    k = int((2.4 * nth * log(nth)) // 2)  \n    integers_list = [True] * k\n    for i in range(1, k):\n        j = i\n        while i + j + 2 * i * j < k:\n            integers_list[i + j + 2 * i * j] = False\n            j += 1\n    pcount = 0\n    for i in range(1, k + 1):\n        if integers_list[i]:\n            pcount += 1\n            if print_all:\n                print(f\"{2 * i + 1:4}\", end=' ')\n                if pcount % 10 == 0:\n                    print()\n\n            if pcount == nth:\n                print(f\"\\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\\n\")\n                break\n\n\n\nsieve_of_Sundaram(100, True)\n\nsieve_of_Sundaram(1000000, False)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nclass Program\n{\n    static string fmt(int[] a)\n    {\n        var sb = new System.Text.StringBuilder();\n        for (int i = 0; i < a.Length; i++)\n            sb.Append(string.Format(\"{0,5}{1}\",\n              a[i], i % 10 == 9 ? \"\\n\" : \" \"));\n        return sb.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();\n        sw.Stop();\n        Write(\"The first 100 odd prime numbers:\\n{0}\\n\",\n          fmt(pr.Take(100).ToArray()));\n        Write(\"The millionth odd prime number: {0}\", pr.Last());\n        Write(\"\\n{0} ms\", sw.Elapsed.TotalMilliseconds);\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<int> Sundaram(int n)\n    {\n        \n        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;\n        var comps = new bool[k + 1];\n        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)\n            while ((t += d + 2) < k)\n                comps[t] = true;\n        for (; v < k; v++)\n            if (!comps[v])\n                yield return (v << 1) + 1;\n    }\n}\n"}
{"id": 60085, "name": "Chemical calculator", "Python": "assert   1.008 == molar_mass('H')                  \nassert   2.016 == molar_mass('H2')                 \nassert  18.015 == molar_mass('H2O')                \nassert  34.014 == molar_mass('H2O2')               \nassert  34.014 == molar_mass('(HO)2')              \nassert 142.036 == molar_mass('Na2SO4')             \nassert  84.162 == molar_mass('C6H12')              \nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  \nassert 176.124 == molar_mass('C6H4O2(OH)4')        \nassert 386.664 == molar_mass('C27H46O')            \nassert 315     == molar_mass('Uue')                \n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ChemicalCalculator {\n    class Program {\n        static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {\n            {\"H\",     1.008 },\n            {\"He\",    4.002602},\n            {\"Li\",    6.94},\n            {\"Be\",    9.0121831},\n            {\"B\",    10.81},\n            {\"C\",    12.011},\n            {\"N\",    14.007},\n            {\"O\",    15.999},\n            {\"F\",    18.998403163},\n            {\"Ne\",   20.1797},\n            {\"Na\",   22.98976928},\n            {\"Mg\",   24.305},\n            {\"Al\",   26.9815385},\n            {\"Si\",   28.085},\n            {\"P\",    30.973761998},\n            {\"S\",    32.06},\n            {\"Cl\",   35.45},\n            {\"Ar\",   39.948},\n            {\"K\",    39.0983},\n            {\"Ca\",   40.078},\n            {\"Sc\",   44.955908},\n            {\"Ti\",   47.867},\n            {\"V\",    50.9415},\n            {\"Cr\",   51.9961},\n            {\"Mn\",   54.938044},\n            {\"Fe\",   55.845},\n            {\"Co\",   58.933194},\n            {\"Ni\",   58.6934},\n            {\"Cu\",   63.546},\n            {\"Zn\",   65.38},\n            {\"Ga\",   69.723},\n            {\"Ge\",   72.630},\n            {\"As\",   74.921595},\n            {\"Se\",   78.971},\n            {\"Br\",   79.904},\n            {\"Kr\",   83.798},\n            {\"Rb\",   85.4678},\n            {\"Sr\",   87.62},\n            {\"Y\",    88.90584},\n            {\"Zr\",   91.224},\n            {\"Nb\",   92.90637},\n            {\"Mo\",   95.95},\n            {\"Ru\",  101.07},\n            {\"Rh\",  102.90550},\n            {\"Pd\",  106.42},\n            {\"Ag\",  107.8682},\n            {\"Cd\",  112.414},\n            {\"In\",  114.818},\n            {\"Sn\",  118.710},\n            {\"Sb\",  121.760},\n            {\"Te\",  127.60},\n            {\"I\",   126.90447},\n            {\"Xe\",  131.293},\n            {\"Cs\",  132.90545196},\n            {\"Ba\",  137.327},\n            {\"La\",  138.90547},\n            {\"Ce\",  140.116},\n            {\"Pr\",  140.90766},\n            {\"Nd\",  144.242},\n            {\"Pm\",  145},\n            {\"Sm\",  150.36},\n            {\"Eu\",  151.964},\n            {\"Gd\",  157.25},\n            {\"Tb\",  158.92535},\n            {\"Dy\",  162.500},\n            {\"Ho\",  164.93033},\n            {\"Er\",  167.259},\n            {\"Tm\",  168.93422},\n            {\"Yb\",  173.054},\n            {\"Lu\",  174.9668},\n            {\"Hf\",  178.49},\n            {\"Ta\",  180.94788},\n            {\"W\",   183.84},\n            {\"Re\",  186.207},\n            {\"Os\",  190.23},\n            {\"Ir\",  192.217},\n            {\"Pt\",  195.084},\n            {\"Au\",  196.966569},\n            {\"Hg\",  200.592},\n            {\"Tl\",  204.38},\n            {\"Pb\",  207.2},\n            {\"Bi\",  208.98040},\n            {\"Po\",  209},\n            {\"At\",  210},\n            {\"Rn\",  222},\n            {\"Fr\",  223},\n            {\"Ra\",  226},\n            {\"Ac\",  227},\n            {\"Th\",  232.0377},\n            {\"Pa\",  231.03588},\n            {\"U\",   238.02891},\n            {\"Np\",  237},\n            {\"Pu\",  244},\n            {\"Am\",  243},\n            {\"Cm\",  247},\n            {\"Bk\",  247},\n            {\"Cf\",  251},\n            {\"Es\",  252},\n            {\"Fm\",  257},\n            {\"Uue\", 315},\n            {\"Ubn\", 299},\n        };\n\n        static double Evaluate(string s) {\n            s += \"[\";\n            double sum = 0.0;\n            string symbol = \"\";\n            string number = \"\";\n            for (int i = 0; i < s.Length; ++i) {\n                var c = s[i];\n                if ('@' <= c && c <= '[') {\n                    \n                    int n = 1;\n                    if (number != \"\") {\n                        n = int.Parse(number);\n                    }\n                    if (symbol != \"\") {\n                        sum += atomicMass[symbol] * n;\n                    }\n                    if (c == '[') {\n                        break;\n                    }\n                    symbol = c.ToString();\n                    number = \"\";\n                } else if ('a' <= c && c <= 'z') {\n                    symbol += c;\n                } else if ('0' <= c && c <= '9') {\n                    number += c;\n                } else {\n                    throw new Exception(string.Format(\"Unexpected symbol {0} in molecule\", c));\n                }\n            }\n            return sum;\n        }\n\n        \n        static string ReplaceFirst(string text, string search, string replace) {\n            int pos = text.IndexOf(search);\n            if (pos < 0) {\n                return text;\n            }\n            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n        }\n\n        static string ReplaceParens(string s) {\n            char letter = 's';\n            while (true) {\n                var start = s.IndexOf('(');\n                if (start == -1) {\n                    break;\n                }\n\n                for (int i = start + 1; i < s.Length; ++i) {\n                    if (s[i] == ')') {\n                        var expr = s.Substring(start + 1, i - start - 1);\n                        var symbol = string.Format(\"@{0}\", letter);\n                        s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);\n                        atomicMass[symbol] = Evaluate(expr);\n                        letter++;\n                        break;\n                    }\n                    if (s[i] == '(') {\n                        start = i;\n                        continue;\n                    }\n                }\n            }\n            return s;\n        }\n\n        static void Main() {\n            var molecules = new string[]{\n                \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n                \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n            };\n            foreach (var molecule in molecules) {\n                var mass = Evaluate(ReplaceParens(molecule));\n                Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass);\n            }\n        }\n    }\n}\n"}
{"id": 60086, "name": "Active Directory_Connect", "Python": "import ldap\n\nl = ldap.initialize(\"ldap://ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n", "C#": "\nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\n"}
{"id": 60087, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 60088, "name": "Pythagorean quadruples", "Python": "def quad(top=2200):\n    r = [False] * top\n    ab = [False] * (top * 2)**2\n    for a in range(1, top):\n        for b in range(a, top):\n            ab[a * a + b * b] = True\n    s = 3\n    for c in range(1, top):\n        s1, s, s2 = s, s + 2, s + 2\n        for d in range(c + 1, top):\n            if ab[s1]:\n                r[d] = True\n            s1 += s2\n            s2 += 2\n    return [i for i, val in enumerate(r) if not val and i]\n    \nif __name__ == '__main__':\n    n = 2200\n    print(f\"Those values of d in 1..{n} that can't be represented: {quad(n)}\")\n", "C#": "using System;\n\nnamespace PythagoreanQuadruples {\n    class Program {\n        const int MAX = 2200;\n        const int MAX2 = MAX * MAX * 2;\n\n        static void Main(string[] args) {\n            bool[] found = new bool[MAX + 1]; \n            bool[] a2b2 = new bool[MAX2 + 1]; \n            int s = 3;\n\n            for(int a = 1; a <= MAX; a++) {\n                int a2 = a * a;\n                for (int b=a; b<=MAX; b++) {\n                    a2b2[a2 + b * b] = true;\n                }\n            }\n\n            for (int c = 1; c <= MAX; c++) {\n                int s1 = s;\n                s += 2;\n                int s2 = s;\n                for (int d = c + 1; d <= MAX; d++) {\n                    if (a2b2[s1]) found[d] = true;\n                    s1 += s2;\n                    s2 += 2;\n                }\n            }\n\n            Console.WriteLine(\"The values of d <= {0} which can't be represented:\", MAX);\n            for (int d = 1; d < MAX; d++) {\n                if (!found[d]) Console.Write(\"{0}  \", d);\n            }\n            Console.WriteLine();\n        }\n    }\n}\n"}
{"id": 60089, "name": "Zebra puzzle", "Python": "from logpy import *\nfrom logpy.core import lall\nimport time\n\ndef lefto(q, p, list):\n\t\n\t\n\t\n\treturn membero((q,p), zip(list, list[1:]))\n\ndef nexto(q, p, list):\n\t\n\t\n\t\n\treturn conde([lefto(q, p, list)], [lefto(p, q, list)])\n\nhouses = var()\n\nzebraRules = lall(\n\t\n\t(eq, \t\t(var(), var(), var(), var(), var()), houses),\n\t\n\t(membero,\t('Englishman', var(), var(), var(), 'red'), houses),\n\t\n\t(membero,\t('Swede', var(), var(), 'dog', var()), houses),\n\t\n\t(membero,\t('Dane', var(), 'tea', var(), var()), houses),\n\t\n\t(lefto,\t\t(var(), var(), var(), var(), 'green'),\n\t\t\t\t(var(), var(), var(), var(), 'white'), houses),\n\t\n\t(membero,\t(var(), var(), 'coffee', var(), 'green'), houses),\n\t\n\t(membero,\t(var(), 'Pall Mall', var(), 'birds', var()), houses),\n\t\n\t(membero,\t(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n\t\n\t(eq,\t\t(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n\t\n\t(eq,\t\t(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'cats', var()), houses),\n\t\n\t(nexto,\t\t(var(), 'Dunhill', var(), var(), var()),\n\t\t\t\t(var(), var(), var(), 'horse', var()), houses),\n\t\n\t(membero,\t(var(), 'Blue Master', 'beer', var(), var()), houses),\n\t\n\t(membero,\t('German', 'Prince', var(), var(), var()), houses),\n\t\n\t(nexto,\t\t('Norwegian', var(), var(), var(), var()),\n\t\t\t\t(var(), var(), var(), var(), 'blue'), houses),\n\t\n\t(nexto,\t\t(var(), 'Blend', var(), var(), var()),\n\t\t\t\t(var(), var(), 'water', var(), var()), houses),\n\t\n\t(membero,\t(var(), var(), var(), 'zebra', var()), houses)\n)\n\nt0 = time.time()\nsolutions = run(0, houses, zebraRules)\nt1 = time.time()\ndur = t1-t0\n\ncount = len(solutions)\nzebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]\n\nprint \"%i solutions in %.2f seconds\" % (count, dur)\nprint \"The %s is the owner of the zebra\" % zebraOwner\nprint \"Here are all the houses:\"\nfor line in solutions[0]:\n\tprint str(line)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\n\npublic enum Colour { Red, Green, White, Yellow, Blue }\npublic enum Nationality { Englishman, Swede, Dane, Norwegian,German }\npublic enum Pet { Dog, Birds, Cats, Horse, Zebra }\npublic enum Drink { Coffee, Tea, Milk, Beer, Water }\npublic enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}\n\npublic static class ZebraPuzzle\n{\n    private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;\n\n    static ZebraPuzzle()\n    {\n        var solve = from colours in Permute<Colour>()  \n                    where (colours,Colour.White).IsRightOf(colours, Colour.Green) \n                    from nations in Permute<Nationality>()\n                    where nations[0] == Nationality.Norwegian \n                    where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) \n                    where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) \n                    from drinks in Permute<Drink>()\n                    where drinks[2] == Drink.Milk \n                    where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) \n                    where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) \n                    from pets in Permute<Pet>()\n                    where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) \n                    from smokes in Permute<Smoke>()\n                    where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) \n                    where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) \n                    where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) \n                    where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) \n                    where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) \n                    where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) \n                    where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) \n                    select (colours, drinks, smokes, pets, nations);\n\n        _solved = solve.First();\n    }\n    \n    private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);\n\n    private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;\n\n    private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);\n\n    private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a,  U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);\n\n    \n    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n    {\n        if (values.Count() == 1)\n            return values.ToSingleton();\n\n        return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));\n    }\n\n    public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());\n\n    private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }\n\n    private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();\n\n    public static new String ToString()\n    {\n        var sb = new StringBuilder();\n        sb.AppendLine(\"House Colour Drink    Nationality Smokes     Pet\");\n        sb.AppendLine(\"───── ────── ──────── ─────────── ────────── ─────\");\n        var (colours, drinks, smokes, pets, nations) = _solved;\n        for (var i = 0; i < 5; i++)\n            sb.AppendLine($\"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}\");\n        return sb.ToString();\n    }\n\n    public static void Main(string[] arguments)\n    {\n        var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];\n        WriteLine($\"The zebra owner is {owner}\");\n        Write(ToString());\n        Read();\n    }\n}\n"}
{"id": 60090, "name": "Rosetta Code_Find unimplemented tasks", "Python": "\nfrom operator import attrgetter\nfrom typing import Iterator\n\nimport mwclient\n\nURL = 'www.rosettacode.org'\nAPI_PATH = '/mw/'\n\n\ndef unimplemented_tasks(language: str,\n                        *,\n                        url: str,\n                        api_path: str) -> Iterator[str]:\n    \n    site = mwclient.Site(url, path=api_path)\n    all_tasks = site.categories['Programming Tasks']\n    language_tasks = site.categories[language]\n    name = attrgetter('name')\n    all_tasks_names = map(name, all_tasks)\n    language_tasks_names = set(map(name, language_tasks))\n    for task in all_tasks_names:\n        if task not in language_tasks_names:\n            yield task\n\n\nif __name__ == '__main__':\n    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)\n    print(*tasks, sep='\\n')\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Net;\n\nclass Program {\n    static List<string> GetTitlesFromCategory(string category) {\n        string searchQueryFormat = \"http:\n        List<string> results = new List<string>();\n        string cmcontinue = string.Empty;\n\n        do {\n            string cmContinueKeyValue;\n\n            \n            if (cmcontinue.Length > 0)\n                cmContinueKeyValue = String.Format(\"&cmcontinue={0}\", cmcontinue);\n            else\n                cmContinueKeyValue = String.Empty;\n\n            \n            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);\n            string content = new WebClient().DownloadString(query);\n\n            results.AddRange(new Regex(\"\\\"title\\\":\\\"(.+?)\\\"\").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));\n\n            \n            cmcontinue = Regex.Match(content, @\"{\"\"cmcontinue\"\":\"\"([^\"\"]+)\"\"}\", RegexOptions.IgnoreCase).Groups[\"1\"].Value;                \n        } while (cmcontinue.Length > 0);\n\n        return results;\n    }\n\n    static string[] GetUnimplementedTasksFromLanguage(string language) {\n        List<string> alltasks = GetTitlesFromCategory(\"Programming_Tasks\");\n        List<string> lang = GetTitlesFromCategory(language);\n\n        return alltasks.Where(x => !lang.Contains(x)).ToArray();\n    }\n\n    static void Main(string[] args) {\n        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);\n\n        foreach (string i in unimpl) Console.WriteLine(i);\n    }\n}\n"}
{"id": 60091, "name": "First-class functions_Use numbers analogously", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 60092, "name": "First-class functions_Use numbers analogously", "Python": "IDLE 2.6.1      \n>>> \n>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25\n>>> \n>>> z  = x + y\n>>> zi = 1.0 / (x + y)\n>>> \n>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\n>>> \n>>> numlist = [x, y, z]\n>>> numlisti = [xi, yi, zi]\n>>> \n>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\n[0.5, 0.5, 0.5]\n>>>\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        double x, xi, y, yi, z, zi;\n        x = 2.0;\n        xi = 0.5;\n        y = 4.0;\n        yi = 0.25;\n        z = x + y;\n        zi = 1.0 / (x + y);\n\n        var numlist = new[] { x, y, z };\n        var numlisti = new[] { xi, yi, zi };\n        var multiplied = numlist.Zip(numlisti, (n1, n2) =>\n                       {\n                           Func<double, double> multiplier = m => n1 * n2 * m;\n                           return multiplier;\n                       });\n\n        foreach (var multiplier in multiplied)\n            Console.WriteLine(multiplier(0.5));\n    }\n}\n"}
{"id": 60093, "name": "Sokoban", "Python": "from array import array\nfrom collections import deque\nimport psyco\n\ndata = []\nnrows = 0\npx = py = 0\nsdata = \"\"\nddata = \"\"\n\ndef init(board):\n    global data, nrows, sdata, ddata, px, py\n    data = filter(None, board.splitlines())\n    nrows = max(len(r) for r in data)\n\n    maps = {' ':' ', '.': '.', '@':' ', '\n    mapd = {' ':' ', '.': ' ', '@':'@', '\n\n    for r, row in enumerate(data):\n        for c, ch in enumerate(row):\n            sdata += maps[ch]\n            ddata += mapd[ch]\n            if ch == '@':\n                px = c\n                py = r\n\ndef push(x, y, dx, dy, data):\n    if sdata[(y+2*dy) * nrows + x+2*dx] == '\n       data[(y+2*dy) * nrows + x+2*dx] != ' ':\n        return None\n\n    data2 = array(\"c\", data)\n    data2[y * nrows + x] = ' '\n    data2[(y+dy) * nrows + x+dx] = '@'\n    data2[(y+2*dy) * nrows + x+2*dx] = '*'\n    return data2.tostring()\n\ndef is_solved(data):\n    for i in xrange(len(data)):\n        if (sdata[i] == '.') != (data[i] == '*'):\n            return False\n    return True\n\ndef solve():\n    open = deque([(ddata, \"\", px, py)])\n    visited = set([ddata])\n    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),\n            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))\n\n    lnrows = nrows\n    while open:\n        cur, csol, x, y = open.popleft()\n\n        for di in dirs:\n            temp = cur\n            dx, dy = di[0], di[1]\n\n            if temp[(y+dy) * lnrows + x+dx] == '*':\n                temp = push(x, y, dx, dy, temp)\n                if temp and temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[3]\n                    open.append((temp, csol + di[3], x+dx, y+dy))\n                    visited.add(temp)\n            else:\n                if sdata[(y+dy) * lnrows + x+dx] == '\n                   temp[(y+dy) * lnrows + x+dx] != ' ':\n                    continue\n\n                data2 = array(\"c\", temp)\n                data2[y * lnrows + x] = ' '\n                data2[(y+dy) * lnrows + x+dx] = '@'\n                temp = data2.tostring()\n\n                if temp not in visited:\n                    if is_solved(temp):\n                        return csol + di[2]\n                    open.append((temp, csol + di[2], x+dx, y+dy))\n                    visited.add(temp)\n\n    return \"No solution\"\n\n\nlevel = \"\"\"\\\n\n\n\n\n\n\n\n\n\npsyco.full()\ninit(level)\nprint level, \"\\n\\n\", solve()\n", "C#": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SokobanSolver\n{\n    public class SokobanSolver\n    {\n        private class Board\n        {\n            public string Cur { get; internal set; }\n            public string Sol { get; internal set; }\n            public int X { get; internal set; }\n            public int Y { get; internal set; }\n\n            public Board(string cur, string sol, int x, int y)\n            {\n                Cur = cur;\n                Sol = sol;\n                X = x;\n                Y = y;\n            }\n        }\n\n        private string destBoard, currBoard;\n        private int playerX, playerY, nCols;\n\n        SokobanSolver(string[] board)\n        {\n            nCols = board[0].Length;\n            StringBuilder destBuf = new StringBuilder();\n            StringBuilder currBuf = new StringBuilder();\n\n            for (int r = 0; r < board.Length; r++)\n            {\n                for (int c = 0; c < nCols; c++)\n                {\n\n                    char ch = board[r][c];\n\n                    destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');\n                    currBuf.Append(ch != '.' ? ch : ' ');\n\n                    if (ch == '@')\n                    {\n                        this.playerX = c;\n                        this.playerY = r;\n                    }\n                }\n            }\n            destBoard = destBuf.ToString();\n            currBoard = currBuf.ToString();\n        }\n\n        private string Move(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newPlayerPos = (y + dy) * nCols + x + dx;\n\n            if (trialBoard[newPlayerPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[newPlayerPos] = '@';\n\n            return new string(trial);\n        }\n\n        private string Push(int x, int y, int dx, int dy, string trialBoard)\n        {\n\n            int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;\n\n            if (trialBoard[newBoxPos] != ' ')\n                return null;\n\n            char[] trial = trialBoard.ToCharArray();\n            trial[y * nCols + x] = ' ';\n            trial[(y + dy) * nCols + x + dx] = '@';\n            trial[newBoxPos] = '$';\n\n            return new string(trial);\n        }\n\n        private bool IsSolved(string trialBoard)\n        {\n            for (int i = 0; i < trialBoard.Length; i++)\n                if ((destBoard[i] == '.')\n                        != (trialBoard[i] == '$'))\n                    return false;\n            return true;\n        }\n\n        private string Solve()\n        {\n            char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };\n            int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };\n            ISet<string> history = new HashSet<string>();\n            LinkedList<Board> open = new LinkedList<Board>();\n\n            history.Add(currBoard);\n            open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));\n\n            while (!open.Count.Equals(0))\n            {\n                Board item = open.First();\n                open.RemoveFirst();\n                string cur = item.Cur;\n                string sol = item.Sol;\n                int x = item.X;\n                int y = item.Y;\n\n                for (int i = 0; i < dirs.GetLength(0); i++)\n                {\n                    string trial = cur;\n                    int dx = dirs[i, 0];\n                    int dy = dirs[i, 1];\n\n                    \n                    if (trial[(y + dy) * nCols + x + dx] == '$')\n                    {\n                        \n                        if ((trial = Push(x, y, dx, dy, trial)) != null)\n                        {\n                            \n                            if (!history.Contains(trial))\n                            {\n\n                                string newSol = sol + dirLabels[i, 1];\n\n                                if (IsSolved(trial))\n                                    return newSol;\n\n                                open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                                history.Add(trial);\n                            }\n                        }\n                        \n                    }\n                    else if ((trial = Move(x, y, dx, dy, trial)) != null)\n                    {\n                        if (!history.Contains(trial))\n                        {\n                            string newSol = sol + dirLabels[i, 0];\n                            open.AddLast(new Board(trial, newSol, x + dx, y + dy));\n                            history.Add(trial);\n                        }\n                    }\n                }\n            }\n            return \"No solution\";\n        }\n\n        public static void Main(string[] a)\n        {\n            string level = \"#######,\" +\n                           \"#     #,\" +\n                           \"#     #,\" +\n                           \"#. #  #,\" +\n                           \"#. $$ #,\" +\n                           \"#.$$  #,\" +\n                           \"#.#  @#,\" +\n                           \"#######\";\n            System.Console.WriteLine(\"Level:\\n\");\n            foreach (string line in level.Split(','))\n            {\n                System.Console.WriteLine(line);\n            }\n            System.Console.WriteLine(\"\\nSolution:\\n\");\n            System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());\n        }\n    }\n}\n"}
{"id": 60094, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 60095, "name": "Almkvist-Giullera formula for pi", "Python": "import mpmath as mp\n\nwith mp.workdps(72):\n\n    def integer_term(n):\n        p = 532 * n * n + 126 * n + 9\n        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n    def exponent_term(n):\n        return -(mp.mpf(\"6.0\") * n + 3)\n\n    def nthterm(n):\n        return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n    for n in range(10):\n        print(\"Term \", n, '  ', int(integer_term(n)))\n\n\n    def almkvist_guillera(floatprecision):\n        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n        for n in range(100000000):\n            nextadd = summed + nthterm(n)\n            if abs(nextadd - summed) < 10.0**(-floatprecision):\n                break\n\n            summed = nextadd\n\n        return nextadd\n\n\n    print('\\nπ to 70 digits is ', end='')\n    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n    print('mpmath π is       ', end='')\n    mp.nprint(mp.pi, 71)\n", "C#": "using System;\nusing BI = System.Numerics.BigInteger;\nusing static System.Console;\n\nclass Program {\n\n  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {\n    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }\n\n  static string dump(int digs, bool show = false) {\n    int gb = 1, dg = ++digs + gb, z;\n    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,\n       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;\n    for (BI n = 0; n < dg; n++) {\n      if (n > 0) t3 *= BI.Pow(n, 6);\n      te = t1 * t2 / t3;\n      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);\n      else te /= BI.Pow (10, -z);\n      if (show && n < 10)\n        WriteLine(\"{0,2} {1,62}\", n, te * 32 / 3 / t);\n      su += te; if (te < 10) {\n        if (show) WriteLine(\"\\n{0} iterations required for {1} digits \" +\n        \"after the decimal point.\\n\", n, --digs); break; }\n      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;\n      t2 += 126 + 532 * (d += 2);\n    }\n    string s = string.Format(\"{0}\", isqrt(BI.Pow(10, dg * 2 + 3) /\n      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));\n    return s[0] + \".\" + s.Substring(1, digs); }\n\n  static void Main(string[] args) {\n    WriteLine(dump(70, true)); }\n}\n"}
{"id": 60096, "name": "Practical numbers", "Python": "from itertools import chain, cycle, accumulate, combinations\nfrom typing import List, Tuple\n\n\n\ndef factors5(n: int) -> List[int]:\n    \n    def prime_powers(n):\n        \n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n//c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r[:-1]\n\n\n\ndef powerset(s: List[int]) -> List[Tuple[int, ...]]:\n    \n    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))\n\n\n\ndef is_practical(x: int) -> bool:\n    \n    if x == 1:\n        return True\n    if x %2:\n        return False  \n    f = factors5(x)\n    ps = powerset(f)\n    found = {y for y in {sum(i) for i in ps}\n             if 1 <= y < x}\n    return len(found) == x - 1\n\n\nif __name__ == '__main__':\n    n = 333\n    p = [x for x in range(1, n + 1) if is_practical(x)]\n    print(f\"There are {len(p)} Practical numbers from 1 to {n}:\")\n    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])\n    x = 666\n    print(f\"\\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.\")\n", "C#": "using System.Collections.Generic; using System.Linq; using static System.Console;\n\nclass Program {\n\n    static bool soas(int n, IEnumerable<int> f) {\n        if (n <= 0) return false; if (f.Contains(n)) return true;\n        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;\n            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);\n                return soas(d, rf) || soas(n, rf); } return true; }\n\n    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();\n        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }\n\n    static void Main() {\n        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)\n            if (ip(i) || i == 1) Write(\"{0,3} {1}\", i, ++c % 10 == 0 ? \"\\n\" : \"\"); \n        Write(\"\\nFound {0} practical numbers between 1 and {1} inclusive.\\n\", c, m);\n        do Write(\"\\n{0,5} is a{1}practical number.\",\n            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? \" \" : \"n im\"); while (m < 1e4); } }\n"}
{"id": 60097, "name": "Consecutive primes with ascending or descending differences", "Python": "from sympy import sieve\n\nprimelist = list(sieve.primerange(2,1000000))\n\nlistlen = len(primelist)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff > old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n\n\n\npindex = 1\nold_diff = -1\ncurr_list=[primelist[0]]\nlongest_list=[]\n\nwhile pindex < listlen:\n\n    diff = primelist[pindex] - primelist[pindex-1]\n    if diff < old_diff:\n        curr_list.append(primelist[pindex])\n        if len(curr_list) > len(longest_list):\n            longest_list = curr_list\n    else:\n        curr_list = [primelist[pindex-1],primelist[pindex]]\n        \n    old_diff = diff\n    pindex += 1\n    \nprint(longest_list)\n", "C#": "using System.Linq;\nusing System.Collections.Generic;\nusing TG = System.Tuple<int, int>;\nusing static System.Console;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        const int mil = (int)1e6;\n        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })\n        {\n            int lmt = mil * amt, lg = 0, ng, d, ld = 0;\n            var desc = new string[] { \"A\", \"\", \"De\" };\n            int[] mx = new int[] { 0, 0, 0 },\n                  bi = new int[] { 0, 0, 0 },\n                   c = new int[] { 2, 2, 2 };\n            WriteLine(\"For primes up to {0:n0}:\", lmt);\n            var pr = PG.Primes(lmt).ToArray();\n            for (int i = 0; i < pr.Length; i++)\n            {\n                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;\n                if (ld == d)\n                    c[2 - d]++;\n                else\n                {\n                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }\n                    c[d] = 2;\n                }\n                ld = d; lg = ng;\n            }\n            for (int r = 0; r <= 2; r += 2)\n            {\n                Write(\"{0}scending, found run of {1} consecutive primes:\\n  {2} \",\n                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);\n                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))\n                    Write(\"({0}) {1} \", itm.Item2, itm.Item1); WriteLine(r == 0 ? \"\" : \"\\n\");\n            }\n        }\n    }\n}\n\nclass PG\n{\n    public static IEnumerable<TG> Primes(int lim)\n    {\n        bool[] flags = new bool[lim + 1];\n        int j = 3, lj = 2;\n        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;\n            }\n        for (; j <= lim; j += 2)\n            if (!flags[j])\n            {\n                yield return new TG(j, j - lj);\n                lj = j;\n            }\n    }\n}\n"}
{"id": 60098, "name": "Literals_Floating point", "Python": "2.3    \n.3     \n.3e4   \n.3e+34 \n.3e-34 \n2.e34  \n", "C#": "double d = 1;\nd = 1d;\nd = 1D;\nd = 1.2; \nd = 1.2d; \nd = .2;\nd = 12e-12;\nd = 12E-12;\nd = 1_234e-1_2; \nfloat f = 1;\nf = 1f;\nf = 1F;\nf = 1.2f;\nf = .2f;\nf = 12e-12f;\nf = 12E-12f;\nf = 1_234e-1_2f;\ndecimal m = 1;\nm = 1m;\nm = 1m;\nm = 1.2m;\nm = .2m;\nm = 12e-12m;\nm = 12E-12m;\nm = 1_234e-1_2m;\n"}
{"id": 60099, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 60100, "name": "Solve a Numbrix puzzle", "Python": "from sys import stdout\nneighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nexists = []\nlastNumber = 0\nwid = 0\nhei = 0\n\n\ndef find_next(pa, x, y, z):\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == z:\n                return a, b\n\n    return -1, -1\n\n\ndef find_solution(pa, x, y, z):\n    if z > lastNumber:\n        return 1\n    if exists[z] == 1:\n        s = find_next(pa, x, y, z)\n        if s[0] < 0:\n            return 0\n        return find_solution(pa, s[0], s[1], z + 1)\n\n    for i in range(4):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if wid > a > -1 and hei > b > -1:\n            if pa[a][b] == 0:\n                pa[a][b] = z\n                r = find_solution(pa, a, b, z + 1)\n                if r == 1:\n                    return 1\n                pa[a][b] = 0\n\n    return 0\n\n\ndef solve(pz, w, h):\n    global lastNumber, wid, hei, exists\n\n    lastNumber = w * h\n    wid = w\n    hei = h\n    exists = [0 for j in range(lastNumber + 1)]\n\n    pa = [[0 for j in range(h)] for i in range(w)]\n    st = pz.split()\n    idx = 0\n    for j in range(h):\n        for i in range(w):\n            if st[idx] == \".\":\n                idx += 1\n            else:\n                pa[i][j] = int(st[idx])\n                exists[pa[i][j]] = 1\n                idx += 1\n\n    x = 0\n    y = 0\n    t = w * h + 1\n    for j in range(h):\n        for i in range(w):\n            if pa[i][j] != 0 and pa[i][j] < t:\n                t = pa[i][j]\n                x = i\n                y = j\n\n    return find_solution(pa, x, y, t + 1), pa\n\n\ndef show_result(r):\n    if r[0] == 1:\n        for j in range(hei):\n            for i in range(wid):\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n            print()\n    else:\n        stdout.write(\"No Solution!\\n\")\n\n    print()\n\n\nr = solve(\". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17\"\n          \" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37\"\n          \" .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\", 9, 9)\nshow_result(r)\n\nr = solve(\"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55\"\n          \" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\", 9, 9)\nshow_result(r)\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var numbrixSolver = new Solver(numbrixMoves);\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0,  0, 46, 45,  0, 55, 74,  0,  0 },\n            {  0, 38,  0,  0, 43,  0,  0, 78,  0 },\n            {  0, 35,  0,  0,  0,  0,  0, 71,  0 },\n            {  0,  0, 33,  0,  0,  0, 59,  0,  0 },\n            {  0, 17,  0,  0,  0,  0,  0, 67,  0 },\n            {  0, 18,  0,  0, 11,  0,  0, 64,  0 },\n            {  0,  0, 24, 21,  0,  1,  2,  0,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n\n        Print(numbrixSolver.Solve(false, new [,] {\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n            {  0, 11, 12, 15, 18, 21, 62, 61,  0 },\n            {  0,  6,  0,  0,  0,  0,  0, 60,  0 },\n            {  0, 33,  0,  0,  0,  0,  0, 57,  0 },\n            {  0, 32,  0,  0,  0,  0,  0, 56,  0 },\n            {  0, 37,  0,  1,  0,  0,  0, 73,  0 },\n            {  0, 38,  0,  0,  0,  0,  0, 72,  0 },\n            {  0, 43, 44, 47, 48, 51, 76, 77,  0 },\n            {  0,  0,  0,  0,  0,  0,  0,  0,  0 },\n        }));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 60101, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 60102, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 60103, "name": "Church numerals", "Python": "\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n\n\ndef churchZero():\n    \n    return lambda f: identity\n\n\ndef churchSucc(cn):\n    \n    return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n    \n    return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n    \n    return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n    \n    return lambda n: n(m)\n\n\ndef churchFromInt(n):\n    \n    return lambda f: (\n        foldl\n        (compose)\n        (identity)\n        (replicate(n)(f))\n    )\n\n\n\ndef churchFromInt_(n):\n    \n    if 0 == n:\n        return churchZero()\n    else:\n        return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n    \n    return cn(succ)(0)\n\n\n\n\ndef main():\n    'Tests'\n\n    cThree = churchFromInt(3)\n    cFour = churchFromInt(4)\n\n    print(list(map(intFromChurch, [\n        churchAdd(cThree)(cFour),\n        churchMult(cThree)(cFour),\n        churchExp(cFour)(cThree),\n        churchExp(cThree)(cFour),\n    ])))\n\n\n\n\n\ndef compose(f):\n    \n    return lambda g: lambda x: g(f(x))\n\n\n\ndef foldl(f):\n    \n    def go(acc, xs):\n        return reduce(lambda a, x: f(a)(x), xs, acc)\n    return lambda acc: lambda xs: go(acc, xs)\n\n\n\ndef identity(x):\n    \n    return x\n\n\n\ndef replicate(n):\n    \n    return lambda x: repeat(x, n)\n\n\n\ndef succ(x):\n    \n    return 1 + x if isinstance(x, int) else (\n        chr(1 + ord(x))\n    )\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System;\n \npublic delegate Church Church(Church f);\n \npublic static class ChurchNumeral\n{\n    public static readonly Church ChurchZero = _ => x => x;\n    public static readonly Church ChurchOne = f => f;\n \n    public static Church Successor(this Church n) => f => x => f(n(f)(x));\n    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));\n    public static Church Multiply(this Church m, Church n) => f => m(n(f));\n    public static Church Exponent(this Church m, Church n) => n(m);\n    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);\n    public static Church Predecessor(this Church n) =>\n      f => x => n(g => h => h(g(f)))(_ => x)(a => a);\n    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);\n    static Church looper(this Church v, Church d) =>\n        v(_ => v.divr(d).Successor())(ChurchZero);\n    static Church divr(this Church n, Church d) =>\n        n.Subtract(d).looper(d);\n    public static Church Divide(this Church dvdnd, Church dvsr) =>\n        (dvdnd.Successor()).divr(dvsr);\n \n    public static Church FromInt(int i) =>\n      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));\n \n    public static int ToInt(this Church ch) {\n        int count = 0;\n        ch(x => { count++; return x; })(null);\n        return count;\n    }\n \n    public static void Main() {\n        Church c3 = FromInt(3);\n        Church c4 = c3.Successor();\n        Church c11 = FromInt(11);\n        Church c12 = c11.Successor();\n        int sum = c3.Add(c4).ToInt();\n        int product = c3.Multiply(c4).ToInt();\n        int exp43 = c4.Exponent(c3).ToInt();\n        int exp34 = c3.Exponent(c4).ToInt();\n        int tst0 = ChurchZero.IsZero().ToInt();\n        int pred4 = c4.Predecessor().ToInt();\n        int sub43 = c4.Subtract(c3).ToInt();\n        int div11by3 = c11.Divide(c3).ToInt();\n        int div12by3 = c12.Divide(c3).ToInt();\n        Console.Write($\"{sum} {product} {exp43} {exp34} {tst0} \");\n        Console.WriteLine($\"{pred4} {sub43} {div11by3} {div12by3}\");\n    } \n}\n"}
{"id": 60104, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 60105, "name": "Solve a Hopido puzzle", "Python": "from sys import stdout\n\nneighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]\ncnt = 0\npWid = 0\npHei = 0\n\n\ndef is_valid(a, b):\n    return -1 < a < pWid and -1 < b < pHei\n\n\ndef iterate(pa, x, y, v):\n    if v > cnt:\n        return 1\n\n    for i in range(len(neighbours)):\n        a = x + neighbours[i][0]\n        b = y + neighbours[i][1]\n        if is_valid(a, b) and pa[a][b] == 0:\n            pa[a][b] = v\n            r = iterate(pa, a, b, v + 1)\n            if r == 1:\n                return r\n            pa[a][b] = 0\n    return 0\n\n\ndef solve(pz, w, h):\n    global cnt, pWid, pHei\n\n    pa = [[-1 for j in range(h)] for i in range(w)]\n    f = 0\n    pWid = w\n    pHei = h\n    for j in range(h):\n        for i in range(w):\n            if pz[f] == \"1\":\n                pa[i][j] = 0\n                cnt += 1\n            f += 1\n\n    for y in range(h):\n        for x in range(w):\n            if pa[x][y] == 0:\n                pa[x][y] = 1\n                if 1 == iterate(pa, x, y, 2):\n                    return 1, pa\n                pa[x][y] = 0\n\n    return 0, pa\n\nr = solve(\"011011011111111111111011111000111000001000\", 7, 6)\nif r[0] == 1:\n    for j in range(6):\n        for i in range(7):\n            if r[1][i][j] == -1:\n                stdout.write(\"   \")\n            else:\n                stdout.write(\" {:0{}d}\".format(r[1][i][j], 2))\n        print()\nelse:\n    stdout.write(\"No solution!\")\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        Print(new Solver(hopidoMoves).Solve(false,\n            \".00.00.\",\n            \"0000000\",\n            \"0000000\",\n            \".00000.\",\n            \"..000..\",\n            \"...0...\"\n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 60106, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 60107, "name": "Nonogram solver", "Python": "from itertools import izip\n\ndef gen_row(w, s):\n    \n    def gen_seg(o, sp):\n        if not o:\n            return [[2] * sp]\n        return [[2] * x + o[0] + tail\n                for x in xrange(1, sp - len(o) + 2)\n                for tail in gen_seg(o[1:], sp - x)]\n\n    return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]\n\n\ndef deduce(hr, vr):\n    \n    def allowable(row):\n        return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)\n\n    def fits(a, b):\n        return all(x & y for x, y in izip(a, b))\n\n    def fix_col(n):\n        \n        c = [x[n] for x in can_do]\n        cols[n] = [x for x in cols[n] if fits(x, c)]\n        for i, x in enumerate(allowable(cols[n])):\n            if x != can_do[i][n]:\n                mod_rows.add(i)\n                can_do[i][n] &= x\n\n    def fix_row(n):\n        \n        c = can_do[n]\n        rows[n] = [x for x in rows[n] if fits(x, c)]\n        for i, x in enumerate(allowable(rows[n])):\n            if x != can_do[n][i]:\n                mod_cols.add(i)\n                can_do[n][i] &= x\n\n    def show_gram(m):\n        \n        \n        for x in m:\n            print \" \".join(\"x\n        print\n\n    w, h = len(vr), len(hr)\n    rows = [gen_row(w, x) for x in hr]\n    cols = [gen_row(h, x) for x in vr]\n    can_do = map(allowable, rows)\n\n    \n    mod_rows, mod_cols = set(), set(xrange(w))\n\n    while mod_cols:\n        for i in mod_cols:\n            fix_col(i)\n        mod_cols = set()\n        for i in mod_rows:\n            fix_row(i)\n        mod_rows = set()\n\n    if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):\n        print \"Solution would be unique\" \n    else:\n        print \"Solution may not be unique, doing exhaustive search:\"\n\n    \n    \n    \n    out = [0] * h\n\n    def try_all(n = 0):\n        if n >= h:\n            for j in xrange(w):\n                if [x[j] for x in out] not in cols[j]:\n                    return 0\n            show_gram(out)\n            return 1\n        sol = 0\n        for x in rows[n]:\n            out[n] = x\n            sol += try_all(n + 1)\n        return sol\n\n    n = try_all()\n    if not n:\n        print \"No solution.\"\n    elif n == 1:\n        print \"Unique solution.\"\n    else:\n        print n, \"solutions.\"\n    print\n\n\ndef solve(p, show_runs=True):\n    s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]\n         for l in p.splitlines()]\n    if show_runs:\n        print \"Horizontal runs:\", s[0]\n        print \"Vertical runs:\", s[1]\n    deduce(s[0], s[1])\n\n\ndef main():\n    \n    fn = \"nonogram_problems.txt\"\n    for p in (x for x in open(fn).read().split(\"\\n\\n\") if x):\n        solve(p)\n\n    print \"Extra example not solvable by deduction alone:\"\n    solve(\"B B A A\\nB B A A\")\n\n    print \"Extra example where there is no solution:\"\n    solve(\"B A A\\nA A A\")\n\nmain()\n", "C#": "using System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class NonogramSolver\n{\n    public static void Main2() {\n        foreach (var (x, y) in new [] {\n            (\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"),\n            (\"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n                \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"),\n            (\"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n                \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\"),\n            (\"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n                \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\")\n            })\n        {\n            Solve(x, y);\n            Console.WriteLine();\n        }\n    }\n\n    static void Solve(string rowLetters, string columnLetters) {\n        var r = rowLetters.Split(\" \").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        var c = columnLetters.Split(\" \").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();\n        Solve(r, c);\n    }\n\n    static void Solve(int[][] rowRuns, int[][] columnRuns) {\n        int len = columnRuns.Length;\n        var rows = rowRuns.Select(row => Generate(len, row)).ToList();\n        var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();\n        Reduce(rows, columns);\n        foreach (var list in rows) {\n            if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());\n            else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());\n        }\n    }\n\n    static List<BitSet> Generate(int length, params int[] runs) {\n        var list = new List<BitSet>();\n        BitSet initial = BitSet.Empty;\n        int[] sums = new int[runs.Length];\n        sums[0] = 0;\n        for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;\n        for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);\n        Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);\n        return list;\n    }\n\n    static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {\n        if (index == runs.Length) {\n            result.Add(current);\n            return;\n        }\n        while (current.Value < max.Value) {\n            Generate(result, max, runs, sums, current, index + 1, shift);\n            current = current.ShiftLeftAt(sums[index] + shift);\n            shift++;\n        }\n    }\n\n    static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {\n        for (int count = 1; count > 0; ) {\n            foreach (var (rowIndex, row) in rows.WithIndex()) {\n                var allOn  = row.Aggregate((a, b) => a & b);\n                var allOff = row.Aggregate((a, b) => a | b);\n                foreach (var (columnIndex, column) in columns.WithIndex()) {\n                    count  = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));\n                    count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));\n                }\n            }\n            foreach (var (columnIndex, column) in columns.WithIndex()) {\n                var allOn  = column.Aggregate((a, b) => a & b);\n                var allOff = column.Aggregate((a, b) => a | b);\n                foreach (var (rowIndex, row) in rows.WithIndex()) {\n                    count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));\n                    count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));\n                }\n            }\n        }\n    }\n\n    static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {\n        int i = 0;\n        foreach (T element in source) {\n            yield return (i++, element);\n        }\n    }\n\n    static string Reverse(this string s) {\n        char[] array = s.ToCharArray();\n        Array.Reverse(array);\n        return new string(array);\n    }\n\n    static string Spaced(this IEnumerable<char> s) => string.Join(\" \", s);\n\n    struct BitSet \n    {\n        public static BitSet Empty => default;\n        private readonly int bits;\n        public int Value => bits;\n\n        private BitSet(int bits) => this.bits = bits;\n\n        public BitSet Add(int item) => new BitSet(bits | (1 << item));\n        public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));\n        public bool Contains(int item) => (bits & (1 << item)) != 0;\n        public BitSet ShiftLeftAt(int index)  => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));\n        public override string ToString() => Convert.ToString(bits, 2);\n\n        public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);\n        public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);\n    }\n\n}\n"}
{"id": 60108, "name": "Word search", "Python": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n    def __init__(self):\n        self.num_attempts = 0\n        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n        self.solutions = []\n\n\ndef read_words(filename):\n    max_len = max(n_rows, n_cols)\n\n    words = []\n    with open(filename, \"r\") as file:\n        for line in file:\n            s = line.strip().lower()\n            if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n                words.append(s)\n\n    return words\n\n\ndef place_message(grid, msg):\n    msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n    message_len = len(msg)\n    if 0 < message_len < grid_size:\n        gap_size = grid_size // message_len\n\n        for i in range(0, message_len):\n            pos = i * gap_size + randint(0, gap_size)\n            grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n        return message_len\n\n    return 0\n\n\ndef try_location(grid, word, direction, pos):\n    r = pos // n_cols\n    c = pos % n_cols\n    length = len(word)\n\n    \n    if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n       (dirs[direction][0] == -1 and (length - 1) > c) or \\\n       (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n       (dirs[direction][1] == -1 and (length - 1) > r):\n        return 0\n\n    rr = r\n    cc = c\n    i = 0\n    overlaps = 0\n\n    \n    while i < length:\n        if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n            return 0\n        cc += dirs[direction][0]\n        rr += dirs[direction][1]\n        i += 1\n\n    rr = r\n    cc = c\n    i = 0\n    \n    while i < length:\n        if grid.cells[rr][cc] == word[i]:\n            overlaps += 1\n        else:\n            grid.cells[rr][cc] = word[i]\n\n        if i < length - 1:\n            cc += dirs[direction][0]\n            rr += dirs[direction][1]\n\n        i += 1\n\n    letters_placed = length - overlaps\n    if letters_placed > 0:\n        grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n    return letters_placed\n\n\ndef try_place_word(grid, word):\n    rand_dir = randint(0, len(dirs))\n    rand_pos = randint(0, grid_size)\n\n    for direction in range(0, len(dirs)):\n        direction = (direction + rand_dir) % len(dirs)\n\n        for pos in range(0, grid_size):\n            pos = (pos + rand_pos) % grid_size\n\n            letters_placed = try_location(grid, word, direction, pos)\n            if letters_placed > 0:\n                return letters_placed\n\n    return 0\n\n\ndef create_word_search(words):\n    grid = None\n    num_attempts = 0\n\n    while num_attempts < 100:\n        num_attempts += 1\n        shuffle(words)\n\n        grid = Grid()\n        message_len = place_message(grid, \"Rosetta Code\")\n        target = grid_size - message_len\n\n        cells_filled = 0\n        for word in words:\n            cells_filled += try_place_word(grid, word)\n            if cells_filled == target:\n                if len(grid.solutions) >= min_words:\n                    grid.num_attempts = num_attempts\n                    return grid\n                else:\n                    break \n\n    return grid\n\n\ndef print_result(grid):\n    if grid is None or grid.num_attempts == 0:\n        print(\"No grid to display\")\n        return\n\n    size = len(grid.solutions)\n\n    print(\"Attempts: {0}\".format(grid.num_attempts))\n    print(\"Number of words: {0}\".format(size))\n\n    print(\"\\n     0  1  2  3  4  5  6  7  8  9\\n\")\n    for r in range(0, n_rows):\n        print(\"{0}   \".format(r), end='')\n        for c in range(0, n_cols):\n            print(\" %c \" % grid.cells[r][c], end='')\n        print()\n    print()\n\n    for i in range(0, size - 1, 2):\n        print(\"{0}   {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n    if size % 2 == 1:\n        print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n    print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n    static class Program\n    {\n        readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n            {0, -1}, {-1, -1}, {-1, 1}};\n\n        class Grid\n        {\n            public char[,] Cells = new char[nRows, nCols];\n            public List<string> Solutions = new List<string>();\n            public int NumAttempts;\n        }\n\n        readonly static int nRows = 10;\n        readonly static int nCols = 10;\n        readonly static int gridSize = nRows * nCols;\n        readonly static int minWords = 25;\n\n        readonly static Random rand = new Random();\n\n        static void Main(string[] args)\n        {\n            PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n        }\n\n        private static List<string> ReadWords(string filename)\n        {\n            int maxLen = Math.Max(nRows, nCols);\n\n            return System.IO.File.ReadAllLines(filename)\n                .Select(s => s.Trim().ToLower())\n                .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n                .ToList();\n        }\n\n        private static Grid CreateWordSearch(List<string> words)\n        {\n            int numAttempts = 0;\n\n            while (++numAttempts < 100)\n            {\n                words.Shuffle();\n\n                var grid = new Grid();\n                int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n                int target = gridSize - messageLen;\n\n                int cellsFilled = 0;\n                foreach (var word in words)\n                {\n                    cellsFilled += TryPlaceWord(grid, word);\n                    if (cellsFilled == target)\n                    {\n                        if (grid.Solutions.Count >= minWords)\n                        {\n                            grid.NumAttempts = numAttempts;\n                            return grid;\n                        }\n                        else break; \n                    }\n                }\n            }\n            return null;\n        }\n\n        private static int TryPlaceWord(Grid grid, string word)\n        {\n            int randDir = rand.Next(dirs.GetLength(0));\n            int randPos = rand.Next(gridSize);\n\n            for (int dir = 0; dir < dirs.GetLength(0); dir++)\n            {\n                dir = (dir + randDir) % dirs.GetLength(0);\n\n                for (int pos = 0; pos < gridSize; pos++)\n                {\n                    pos = (pos + randPos) % gridSize;\n\n                    int lettersPlaced = TryLocation(grid, word, dir, pos);\n                    if (lettersPlaced > 0)\n                        return lettersPlaced;\n                }\n            }\n            return 0;\n        }\n\n        private static int TryLocation(Grid grid, string word, int dir, int pos)\n        {\n            int r = pos / nCols;\n            int c = pos % nCols;\n            int len = word.Length;\n\n            \n            if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n                    || (dirs[dir, 0] == -1 && (len - 1) > c)\n                    || (dirs[dir, 1] == 1 && (len + r) > nRows)\n                    || (dirs[dir, 1] == -1 && (len - 1) > r))\n                return 0;\n\n            int rr, cc, i, overlaps = 0;\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n                {\n                    return 0;\n                }\n\n                cc += dirs[dir, 0];\n                rr += dirs[dir, 1];\n            }\n\n            \n            for (i = 0, rr = r, cc = c; i < len; i++)\n            {\n                if (grid.Cells[rr, cc] == word[i])\n                    overlaps++;\n                else\n                    grid.Cells[rr, cc] = word[i];\n\n                if (i < len - 1)\n                {\n                    cc += dirs[dir, 0];\n                    rr += dirs[dir, 1];\n                }\n            }\n\n            int lettersPlaced = len - overlaps;\n            if (lettersPlaced > 0)\n            {\n                grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n            }\n\n            return lettersPlaced;\n        }\n\n        private static int PlaceMessage(Grid grid, string msg)\n        {\n            msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n            int messageLen = msg.Length;\n            if (messageLen > 0 && messageLen < gridSize)\n            {\n                int gapSize = gridSize / messageLen;\n\n                for (int i = 0; i < messageLen; i++)\n                {\n                    int pos = i * gapSize + rand.Next(gapSize);\n                    grid.Cells[pos / nCols, pos % nCols] = msg[i];\n                }\n                return messageLen;\n            }\n            return 0;\n        }\n\n        public static void Shuffle<T>(this IList<T> list)\n        {\n            int n = list.Count;\n            while (n > 1)\n            {\n                n--;\n                int k = rand.Next(n + 1);\n                T value = list[k];\n                list[k] = list[n];\n                list[n] = value;\n            }\n        }\n\n        private static void PrintResult(Grid grid)\n        {\n            if (grid == null || grid.NumAttempts == 0)\n            {\n                Console.WriteLine(\"No grid to display\");\n                return;\n            }\n            int size = grid.Solutions.Count;\n\n            Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n            Console.WriteLine(\"Number of words: \" + size);\n\n            Console.WriteLine(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n            for (int r = 0; r < nRows; r++)\n            {\n                Console.Write(\"\\n{0}   \", r);\n                for (int c = 0; c < nCols; c++)\n                    Console.Write(\" {0} \", grid.Cells[r, c]);\n            }\n\n            Console.WriteLine(\"\\n\");\n\n            for (int i = 0; i < size - 1; i += 2)\n            {\n                Console.WriteLine(\"{0}   {1}\", grid.Solutions[i],\n                        grid.Solutions[i + 1]);\n            }\n            if (size % 2 == 1)\n                Console.WriteLine(grid.Solutions[size - 1]);\n\n            Console.ReadLine();\n        }        \n    }\n}\n"}
{"id": 60109, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 60110, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 60111, "name": "Break OO privacy", "Python": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n  File \"<pyshell\n    mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>>\n", "C#": "using System;\nusing System.Reflection;\n\npublic class MyClass\n{\n    private int answer = 42;\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var myInstance = new MyClass();\n        var fieldInfo = typeof(MyClass).GetField(\"answer\", BindingFlags.NonPublic | BindingFlags.Instance);\n        var answer = fieldInfo.GetValue(myInstance);\n        Console.WriteLine(answer);\n    }\n}\n"}
{"id": 60112, "name": "Object serialization", "Python": "\n\n\n\n\nimport pickle\n\nclass Entity:\n\tdef __init__(self):\n\t\tself.name = \"Entity\"\n\tdef printName(self):\n\t\tprint self.name\n\nclass Person(Entity): \n\tdef __init__(self): \n\t\tself.name = \"Cletus\" \n\ninstance1 = Person()\ninstance1.printName()\n\ninstance2 = Entity()\ninstance2.printName()\n\ntarget = file(\"objects.dat\", \"w\") \n\n\npickle.dump((instance1, instance2), target) \ntarget.close() \nprint \"Serialized...\"\n\n\ntarget = file(\"objects.dat\") \ni1, i2 = pickle.load(target)\nprint \"Unserialized...\"\n\ni1.printName()\ni2.printName()\n", "C#": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization.Formatters.Binary;\n\nnamespace Object_serialization\n{\n  [Serializable] public class Being\n  {\n    public bool Alive { get; set; }\n  }\n\n  [Serializable] public class Animal: Being\n  {\n    public Animal() { }\n\n    public Animal(long id, string name, bool alive = true)\n    {\n      Id = id;\n      Name = name;\n      Alive = alive;\n    }\n\n    public long Id { get; set; }\n    public string Name { get; set; }\n\n    public void Print() { Console.WriteLine(\"{0}, id={1} is {2}\",\n      Name, Id, Alive ? \"alive\" : \"dead\"); }\n  }\n\n\n  internal class Program\n  {\n    private static void Main()\n    {\n      string path = \n        Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+\"\\\\objects.dat\";\n\n      var n = new List<Animal>\n              {\n                new Animal(1, \"Fido\"),\n                new Animal(2, \"Lupo\"),\n                new Animal(7, \"Wanda\"),\n                new Animal(3, \"Kiki\", alive: false)\n              };\n\n      foreach(Animal animal in n)\n        animal.Print();\n\n      using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))\n        new BinaryFormatter().Serialize(stream, n);\n\n      n.Clear();\n      Console.WriteLine(\"---------------\");\n      List<Animal> m;\n\n      using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n        m = (List<Animal>) new BinaryFormatter().Deserialize(stream);\n\n      foreach(Animal animal in m)\n        animal.Print();\n    }\n  }\n}\n"}
{"id": 60113, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 60114, "name": "Eertree", "Python": "\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} \n\t\tself.link = None \n\t\tself.len = 0 \n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t\n\t\tself.rto = Node() \n\t\tself.rte = Node() \n\n\t\t\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] \n\t\tself.maxSufT = self.rte \n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t\n\t\t\n\t\t\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) \n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t\n\t\t\tQ.edges[a] = P\n\n\t\t\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t\n\t\t\n\n\t\t\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] \n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): \n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): \n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: \n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) \n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) \n\tprint (\"Sub-palindromes:\", result)\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Eertree {\n    class Node {\n        public Node(int length) {\n            this.Length = length;\n            \n            this.Edges = new Dictionary<char, int>();\n        }\n\n        public Node(int length, Dictionary<char, int> edges, int suffix) {\n            this.Length = length;\n            this.Edges = edges;\n            this.Suffix = suffix;\n        }\n\n        public int Length { get; set; }\n        public Dictionary<char, int> Edges { get; set; }\n        public int Suffix { get; set; }\n    }\n\n    class Program {\n        const int EVEN_ROOT = 0;\n        const int ODD_ROOT = 1;\n\n        static List<Node> Eertree(string s) {\n            List<Node> tree = new List<Node> {\n                \n                new Node(0, new Dictionary<char, int>(), ODD_ROOT),\n                \n                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)\n            };\n            int suffix = ODD_ROOT;\n            int n, k;\n            for (int i = 0; i < s.Length; i++) {\n                char c = s[i];\n                for (n = suffix; ; n = tree[n].Suffix) {\n                    k = tree[n].Length;\n                    int b = i - k - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                if (tree[n].Edges.ContainsKey(c)) {\n                    suffix = tree[n].Edges[c];\n                    continue;\n                }\n                suffix = tree.Count;\n                tree.Add(new Node(k + 2));\n                tree[n].Edges[c] = suffix;\n                if (tree[suffix].Length == 1) {\n                    tree[suffix].Suffix = 0;\n                    continue;\n                }\n                while (true) {\n                    n = tree[n].Suffix;\n                    int b = i - tree[n].Length - 1;\n                    if (b >= 0 && s[b] == c) {\n                        break;\n                    }\n                }\n                tree[suffix].Suffix = tree[n].Edges[c];\n            }\n            return tree;\n        }\n\n        static List<string> SubPalindromes(List<Node> tree) {\n            List<string> s = new List<string>();\n            SubPalindromes_children(0, \"\", tree, s);\n            foreach (var c in tree[1].Edges.Keys) {\n                int m = tree[1].Edges[c];\n                string ct = c.ToString();\n                s.Add(ct);\n                SubPalindromes_children(m, ct, tree, s);\n            }\n            return s;\n        }\n\n        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {\n            foreach (var c in tree[n].Edges.Keys) {\n                int m = tree[n].Edges[c];\n                string p1 = c + p + c;\n                s.Add(p1);\n                SubPalindromes_children(m, p1, tree, s);\n            }\n        }\n\n        static void Main(string[] args) {\n            List<Node> tree = Eertree(\"eertree\");\n            List<string> result = SubPalindromes(tree);\n            string listStr = string.Join(\", \", result);\n            Console.WriteLine(\"[{0}]\", listStr);\n        }\n    }\n}\n"}
{"id": 60115, "name": "Long year", "Python": "\n\nfrom datetime import date\n\n\n\ndef longYear(y):\n    \n    return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n\n\ndef main():\n    \n    for year in [\n            x for x in range(2000, 1 + 2100)\n            if longYear(x)\n    ]:\n        print(year)\n\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using static System.Console;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Globalization;\n\npublic static class Program\n{\n    public static void Main()\n    {\n        WriteLine(\"Long years in the 21st century:\");\n        WriteLine(string.Join(\" \", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));\n    }\n    \n    public static IEnumerable<int> To(this int start, int end) {\n        for (int i = start; i < end; i++) yield return i;\n    }\n    \n}\n"}
{"id": 60116, "name": "Zumkeller numbers", "Python": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n    d = divisors(n)\n    s = sum(d)\n    if not s % 2 and max(d) <= s/2:\n        for x in range(1, 2**len(d)):\n            if sum(Subset.unrank_binary(x, d).subset) == s/2:\n                return True\n\n    return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n    nprinted = 0\n    for n in range(1, 10**5):\n        if (oddonly == False or n % 2) and isZumkeller(n):\n            print(f'{n:>8}', end='')\n            nprinted += 1\n            if nprinted % 10 == 0:\n                print()\n            if nprinted >= N:\n                return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n    class Program {\n        static List<int> GetDivisors(int n) {\n            List<int> divs = new List<int> {\n                1, n\n            };\n            for (int i = 2; i * i <= n; i++) {\n                if (n % i == 0) {\n                    int j = n / i;\n                    divs.Add(i);\n                    if (i != j) {\n                        divs.Add(j);\n                    }\n                }\n            }\n            return divs;\n        }\n\n        static bool IsPartSum(List<int> divs, int sum) {\n            if (sum == 0) {\n                return true;\n            }\n            var le = divs.Count;\n            if (le == 0) {\n                return false;\n            }\n            var last = divs[le - 1];\n            List<int> newDivs = new List<int>();\n            for (int i = 0; i < le - 1; i++) {\n                newDivs.Add(divs[i]);\n            }\n            if (last > sum) {\n                return IsPartSum(newDivs, sum);\n            }\n            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n        }\n\n        static bool IsZumkeller(int n) {\n            var divs = GetDivisors(n);\n            var sum = divs.Sum();\n            \n            if (sum % 2 == 1) {\n                return false;\n            }\n            \n            if (n % 2 == 1) {\n                var abundance = sum - 2 * n;\n                return abundance > 0 && abundance % 2 == 0;\n            }\n            \n            return IsPartSum(divs, sum / 2);\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n            int i = 2;\n            for (int count = 0; count < 220; i++) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,3} \", i);\n                    count++;\n                    if (count % 20 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (IsZumkeller(i)) {\n                    Console.Write(\"{0,5} \", i);\n                    count++;\n                    if (count % 10 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n\n            Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n            i = 3;\n            for (int count = 0; count < 40; i += 2) {\n                if (i % 10 != 5 && IsZumkeller(i)) {\n                    Console.Write(\"{0,7} \", i);\n                    count++;\n                    if (count % 8 == 0) {\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 60117, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 60118, "name": "Associative array_Merging", "Python": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        var baseData = new Dictionary<string, object> {\n            [\"name\"] = \"Rocket Skates\",\n            [\"price\"] = 12.75,\n            [\"color\"] = \"yellow\"\n        };\n        var updateData = new Dictionary<string, object> {\n            [\"price\"] = 15.25,\n            [\"color\"] = \"red\",\n            [\"year\"] = 1974\n        };\n        var mergedData = new Dictionary<string, object>();\n        foreach (var entry in baseData.Concat(updateData)) {\n            mergedData[entry.Key] = entry.Value;\n        }\n        foreach (var entry in mergedData) {\n            Console.WriteLine(entry);\n        }\n   }\n}\n"}
{"id": 60119, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 60120, "name": "Metallic ratios", "Python": "from itertools import count, islice\nfrom _pydecimal import getcontext, Decimal\n\ndef metallic_ratio(b):\n    m, n = 1, 1\n    while True:\n        yield m, n\n        m, n = m*b + n, m\n\ndef stable(b, prec):\n    def to_decimal(b):\n        for m,n in metallic_ratio(b):\n            yield Decimal(m)/Decimal(n)\n\n    getcontext().prec = prec\n    last = 0\n    for i,x in zip(count(), to_decimal(b)):\n        if x == last:\n            print(f'after {i} iterations:\\n\\t{x}')\n            break\n        last = x\n\nfor b in range(4):\n    coefs = [n for _,n in islice(metallic_ratio(b), 15)]\n    print(f'\\nb = {b}: {coefs}')\n    stable(b, 32)\n\nprint(f'\\nb = 1 with 256 digits:')\nstable(1, 256)\n", "C#": "using static System.Math;\nusing static System.Console;\nusing BI = System.Numerics.BigInteger;\n \nclass Program {\n \n    static BI IntSqRoot(BI v, BI res) { \n        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;\n            dl = d; d = term - res; } return term; }\n \n    static string doOne(int b, int digs) { \n        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),\n            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);\n        bs += b * BI.Parse('1' + new string('0', digs));\n        bs >>= 1; bs += 4; string st = bs.ToString();\n        return string.Format(\"{0}.{1}\", st[0], st.Substring(1, --digs)); }\n \n    static string divIt(BI a, BI b, int digs) { \n        int al = a.ToString().Length, bl = b.ToString().Length;\n        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);\n        string s = (a / b + 5).ToString(); return s[0] + \".\" + s.Substring(1, --digs); }\n \n    \n    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};\n        string res = \"\"; for (int i = 0; i < x.Length; i++) res += \n            string.Format(\"{0,\" + (-wids[i]).ToString() + \"} \", x[i]); return res; }\n \n    static void Main(string[] args) { \n        WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\");\n        int k; string lt, t = \"\"; BI n, nm1, on; for (int b = 0; b < 10; b++) {\n            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;\n            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];\n            \n            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {\n                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;\n                on = n; n = b * n + nm1; nm1 = on; }\n            WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\\n{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\"\n                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), \"\", joined(lst)); }\n        \n        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {\n            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;\n                on = n; n += nm1; nm1 = on; }\n        WriteLine(\"\\nAu to 256 digits:\"); WriteLine(t);\n        WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t == doOne(1, 256)); }\n}\n"}
{"id": 60121, "name": "Markov chain text generator", "Python": "import random, sys\n\ndef makerule(data, context):\n    \n    rule = {}\n    words = data.split(' ')\n    index = context\n    \n    for word in words[index:]:\n        key = ' '.join(words[index-context:index])\n        if key in rule:\n            rule[key].append(word)\n        else:\n            rule[key] = [word]\n        index += 1\n\n    return rule\n\n\ndef makestring(rule, length):    \n    \n    oldwords = random.choice(list(rule.keys())).split(' ') \n    string = ' '.join(oldwords) + ' '\n    \n    for i in range(length):\n        try:\n            key = ' '.join(oldwords)\n            newword = random.choice(rule[key])\n            string += newword + ' '\n\n            for word in range(len(oldwords)):\n                oldwords[word] = oldwords[(word + 1) % len(oldwords)]\n            oldwords[-1] = newword\n\n        except KeyError:\n            return string\n    return string\n\n\nif __name__ == '__main__':\n    with open(sys.argv[1], encoding='utf8') as f:\n        data = f.read()\n    rule = makerule(data, int(sys.argv[2]))\n    string = makestring(rule, int(sys.argv[3]))\n    print(string)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace MarkovChainTextGenerator {\n    class Program {\n        static string Join(string a, string b) {\n            return a + \" \" + b;\n        }\n\n        static string Markov(string filePath, int keySize, int outputSize) {\n            if (keySize < 1) throw new ArgumentException(\"Key size can't be less than 1\");\n\n            string body;\n            using (StreamReader sr = new StreamReader(filePath)) {\n                body = sr.ReadToEnd();\n            }\n            var words = body.Split();\n            if (outputSize < keySize || words.Length < outputSize) {\n                throw new ArgumentException(\"Output size is out of range\");\n            }\n\n            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n            for (int i = 0; i < words.Length - keySize; i++) {\n                var key = words.Skip(i).Take(keySize).Aggregate(Join);\n                string value;\n                if (i + keySize < words.Length) {\n                    value = words[i + keySize];\n                } else {\n                    value = \"\";\n                }\n\n                if (dict.ContainsKey(key)) {\n                    dict[key].Add(value);\n                } else {\n                    dict.Add(key, new List<string>() { value });\n                }\n            }\n\n            Random rand = new Random();\n            List<string> output = new List<string>();\n            int n = 0;\n            int rn = rand.Next(dict.Count);\n            string prefix = dict.Keys.Skip(rn).Take(1).Single();\n            output.AddRange(prefix.Split());\n\n            while (true) {\n                var suffix = dict[prefix];\n                if (suffix.Count == 1) {\n                    if (suffix[0] == \"\") {\n                        return output.Aggregate(Join);\n                    }\n                    output.Add(suffix[0]);\n                } else {\n                    rn = rand.Next(suffix.Count);\n                    output.Add(suffix[rn]);\n                }\n                if (output.Count >= outputSize) {\n                    return output.Take(outputSize).Aggregate(Join);\n                }\n                n++;\n                prefix = output.Skip(n).Take(keySize).Aggregate(Join);\n            }\n        }\n\n        static void Main(string[] args) {\n            Console.WriteLine(Markov(\"alice_oz.txt\", 3, 200));\n        }\n    }\n}\n"}
{"id": 60122, "name": "Dijkstra's algorithm", "Python": "from collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        \n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        \n \n        while q:\n            \n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  \n                    dist[v] = alt\n                    previous[v] = u\n        \n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n", "C#": "using static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i / 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n"}
{"id": 60123, "name": "Geometric algebra", "Python": "import copy, random\n\ndef bitcount(n):\n    return bin(n).count(\"1\")\n\ndef reoderingSign(i, j):\n    k = i >> 1\n    sum = 0\n    while k != 0:\n        sum += bitcount(k & j)\n        k = k >> 1\n    return 1.0 if ((sum & 1) == 0) else -1.0\n\nclass Vector:\n    def __init__(self, da):\n        self.dims = da\n\n    def dot(self, other):\n        return (self * other + other * self) * 0.5\n\n    def __getitem__(self, i):\n        return self.dims[i]\n\n    def __setitem__(self, i, v):\n        self.dims[i] = v\n\n    def __neg__(self):\n        return self * -1.0\n\n    def __add__(self, other):\n        result = copy.copy(other.dims)\n        for i in xrange(0, len(self.dims)):\n            result[i] += self.dims[i]\n        return Vector(result)\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):\n            result = [0.0] * 32\n            for i in xrange(0, len(self.dims)):\n                if self.dims[i] != 0.0:\n                    for j in xrange(0, len(self.dims)):\n                        if other.dims[j] != 0.0:\n                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]\n                            k = i ^ j\n                            result[k] += s\n            return Vector(result)\n        else:\n            result = copy.copy(self.dims)\n            for i in xrange(0, len(self.dims)):\n                self.dims[i] *= other\n            return Vector(result)\n\n    def __str__(self):\n        return str(self.dims)\n\ndef e(n):\n    assert n <= 4, \"n must be less than 5\"\n    result = Vector([0.0] * 32)\n    result[1 << n] = 1.0\n    return result\n\ndef randomVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 5):\n        result += Vector([random.uniform(0, 1)]) * e(i)\n    return result\n\ndef randomMultiVector():\n    result = Vector([0.0] * 32)\n    for i in xrange(0, 32):\n        result[i] = random.uniform(0, 1)\n    return result\n\ndef main():\n    for i in xrange(0, 5):\n        for j in xrange(0, 5):\n            if i < j:\n                if e(i).dot(e(j))[0] != 0.0:\n                    print \"Unexpected non-null scalar product\"\n                    return\n                elif i == j:\n                    if e(i).dot(e(j))[0] == 0.0:\n                        print \"Unexpected non-null scalar product\"\n\n    a = randomMultiVector()\n    b = randomMultiVector()\n    c = randomMultiVector()\n    x = randomVector()\n\n    \n    print (a * b) * c\n    print a * (b * c)\n    print\n\n    \n    print a * (b + c)\n    print a * b + a * c\n    print\n\n    \n    print (a + b) * c\n    print a * c + b * c\n    print\n\n    \n    print x * x\n\nmain()\n", "C#": "using System;\nusing System.Text;\n\nnamespace GeometricAlgebra {\n    struct Vector {\n        private readonly double[] dims;\n\n        public Vector(double[] da) {\n            dims = da;\n        }\n\n        public static Vector operator -(Vector v) {\n            return v * -1.0;\n        }\n\n        public static Vector operator +(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length);\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = lhs[i] + rhs[i];\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector lhs, Vector rhs) {\n            var result = new double[32];\n            for (int i = 0; i < lhs.Length; i++) {\n                if (lhs[i] != 0.0) {\n                    for (int j = 0; j < lhs.Length; j++) {\n                        if (rhs[j] != 0.0) {\n                            var s = ReorderingSign(i, j) * lhs[i] * rhs[j];\n                            var k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public static Vector operator *(Vector v, double scale) {\n            var result = (double[])v.dims.Clone();\n            for (int i = 0; i < result.Length; i++) {\n                result[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        public double this[int key] {\n            get {\n                return dims[key];\n            }\n\n            set {\n                dims[key] = value;\n            }\n        }\n\n        public int Length {\n            get {\n                return dims.Length;\n            }\n        }\n\n        public Vector Dot(Vector rhs) {\n            return (this * rhs + rhs * this) * 0.5;\n        }\n\n        private static int BitCount(int i) {\n            i -= ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            i = (i + (i >> 4)) & 0x0F0F0F0F;\n            i += (i >> 8);\n            i += (i >> 16);\n            return i & 0x0000003F;\n        }\n\n        private static double ReorderingSign(int i, int j) {\n            int k = i >> 1;\n            int sum = 0;\n            while (k != 0) {\n                sum += BitCount(k & j);\n                k >>= 1;\n            }\n            return ((sum & 1) == 0) ? 1.0 : -1.0;\n        }\n\n        public override string ToString() {\n            var it = dims.GetEnumerator();\n\n            StringBuilder sb = new StringBuilder(\"[\");\n            if (it.MoveNext()) {\n                sb.Append(it.Current);\n            }\n            while (it.MoveNext()) {\n                sb.Append(\", \");\n                sb.Append(it.Current);\n            }\n\n            sb.Append(']');\n            return sb.ToString();\n        }\n    }\n\n    class Program {\n        static double[] DoubleArray(uint size) {\n            double[] result = new double[size];\n            for (int i = 0; i < size; i++) {\n                result[i] = 0.0;\n            }\n            return result;\n        }\n\n        static Vector E(int n) {\n            if (n > 4) {\n                throw new ArgumentException(\"n must be less than 5\");\n            }\n\n            var result = new Vector(DoubleArray(32));\n            result[1 << n] = 1.0;\n            return result;\n        }\n\n        static readonly Random r = new Random();\n\n        static Vector RandomVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < 5; i++) {\n                var singleton = new double[] { r.NextDouble() };\n                result += new Vector(singleton) * E(i);\n            }\n            return result;\n        }\n\n        static Vector RandomMultiVector() {\n            var result = new Vector(DoubleArray(32));\n            for (int i = 0; i < result.Length; i++) {\n                result[i] = r.NextDouble();\n            }\n            return result;\n        }\n\n        static void Main() {\n            for (int i = 0; i < 5; i++) {\n                for (int j = 0; j < 5; j++) {\n                    if (i < j) {\n                        if (E(i).Dot(E(j))[0] != 0.0) {\n                            Console.WriteLine(\"Unexpected non-null sclar product.\");\n                            return;\n                        }\n                    } else if (i == j) {\n                        if ((E(i).Dot(E(j)))[0] == 0.0) {\n                            Console.WriteLine(\"Unexpected null sclar product.\");\n                        }\n                    }\n                }\n            }\n\n            var a = RandomMultiVector();\n            var b = RandomMultiVector();\n            var c = RandomMultiVector();\n            var x = RandomVector();\n\n            \n            Console.WriteLine((a * b) * c);\n            Console.WriteLine(a * (b * c));\n            Console.WriteLine();\n\n            \n            Console.WriteLine(a * (b + c));\n            Console.WriteLine(a * b + a * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine((a + b) * c);\n            Console.WriteLine(a * c + b * c);\n            Console.WriteLine();\n\n            \n            Console.WriteLine(x * x);\n        }\n    }\n}\n"}
{"id": 60124, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 60125, "name": "Suffix tree", "Python": "class Node:\n    def __init__(self, sub=\"\", children=None):\n        self.sub = sub\n        self.ch = children or []\n\nclass SuffixTree:\n    def __init__(self, str):\n        self.nodes = [Node()]\n        for i in range(len(str)):\n            self.addSuffix(str[i:])\n\n    def addSuffix(self, suf):\n        n = 0\n        i = 0\n        while i < len(suf):\n            b = suf[i]\n            x2 = 0\n            while True:\n                children = self.nodes[n].ch\n                if x2 == len(children):\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(suf[i:], []))\n                    self.nodes[n].ch.append(n2)\n                    return\n                n2 = children[x2]\n                if self.nodes[n2].sub[0] == b:\n                    break\n                x2 = x2 + 1\n\n            \n            sub2 = self.nodes[n2].sub\n            j = 0\n            while j < len(sub2):\n                if suf[i + j] != sub2[j]:\n                    \n                    n3 = n2\n                    \n                    n2 = len(self.nodes)\n                    self.nodes.append(Node(sub2[:j], [n3]))\n                    self.nodes[n3].sub = sub2[j:] \n                    self.nodes[n].ch[x2] = n2\n                    break \n                j = j + 1\n            i = i + j   \n            n = n2      \n\n    def visualize(self):\n        if len(self.nodes) == 0:\n            print \"<empty>\"\n            return\n\n        def f(n, pre):\n            children = self.nodes[n].ch\n            if len(children) == 0:\n                print \"--\", self.nodes[n].sub\n                return\n            print \"+-\", self.nodes[n].sub\n            for c in children[:-1]:\n                print pre, \"+-\",\n                f(c, pre + \" | \")\n            print pre, \"+-\",\n            f(children[-1], pre + \"  \")\n\n        f(0, \"\")\n\nSuffixTree(\"banana$\").visualize()\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace SuffixTree {\n    class Node {\n        public string sub;                     \n        public List<int> ch = new List<int>(); \n\n        public Node() {\n            sub = \"\";\n        }\n\n        public Node(string sub, params int[] children) {\n            this.sub = sub;\n            ch.AddRange(children);\n        }\n    }\n\n    class SuffixTree {\n        readonly List<Node> nodes = new List<Node>();\n\n        public SuffixTree(string str) {\n            nodes.Add(new Node());\n            for (int i = 0; i < str.Length; i++) {\n                AddSuffix(str.Substring(i));\n            }\n        }\n\n        public void Visualize() {\n            if (nodes.Count == 0) {\n                Console.WriteLine(\"<empty>\");\n                return;\n            }\n\n            void f(int n, string pre) {\n                var children = nodes[n].ch;\n                if (children.Count == 0) {\n                    Console.WriteLine(\"- {0}\", nodes[n].sub);\n                    return;\n                }\n                Console.WriteLine(\"+ {0}\", nodes[n].sub);\n\n                var it = children.GetEnumerator();\n                if (it.MoveNext()) {\n                    do {\n                        var cit = it;\n                        if (!cit.MoveNext()) break;\n\n                        Console.Write(\"{0}+-\", pre);\n                        f(it.Current, pre + \"| \");\n                    } while (it.MoveNext());\n                }\n\n                Console.Write(\"{0}+-\", pre);\n                f(children[children.Count-1], pre+\"  \");\n            }\n\n            f(0, \"\");\n        }\n\n        private void AddSuffix(string suf) {\n            int n = 0;\n            int i = 0;\n            while (i < suf.Length) {\n                char b = suf[i];\n                int x2 = 0;\n                int n2;\n                while (true) {\n                    var children = nodes[n].ch;\n                    if (x2 == children.Count) {\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(suf.Substring(i)));\n                        nodes[n].ch.Add(n2);\n                        return;\n                    }\n                    n2 = children[x2];\n                    if (nodes[n2].sub[0] == b) {\n                        break;\n                    }\n                    x2++;\n                }\n                \n                var sub2 = nodes[n2].sub;\n                int j = 0;\n                while (j < sub2.Length) {\n                    if (suf[i + j] != sub2[j]) {\n                        \n                        var n3 = n2;\n                        \n                        n2 = nodes.Count;\n                        nodes.Add(new Node(sub2.Substring(0, j), n3));\n                        nodes[n3].sub = sub2.Substring(j); \n                        nodes[n].ch[x2] = n2;\n                        break; \n                    }\n                    j++;\n                }\n                i += j; \n                n = n2; \n            }\n        }\n    }\n\n    class Program {\n        static void Main() {\n            new SuffixTree(\"banana$\").Visualize();\n        }\n    }\n}\n"}
{"id": 60126, "name": "Associative array_Iteration", "Python": "myDict = { \"hello\": 13,\n\t   \"world\": 31,\n\t   \"!\"    : 71 }\n\n\nfor key, value in myDict.items():\n    print (\"key = %s, value = %s\" % (key, value))\n\n\nfor key in myDict:\n    print (\"key = %s\" % key)\n\nfor key in myDict.keys():\n    print (\"key = %s\" % key)\n\n\nfor value in myDict.values():\n    print (\"value = %s\" % value)\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace AssocArrays\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            Dictionary<string,int> assocArray = new Dictionary<string,int>();\n\n            assocArray[\"Hello\"] = 1;\n            assocArray.Add(\"World\", 2);\n            assocArray[\"!\"] = 3;\n\n            foreach (KeyValuePair<string, int> kvp in assocArray)\n            {\n                Console.WriteLine(kvp.Key + \" : \" + kvp.Value);\n            }\n\n            foreach (string key in assocArray.Keys)\n            {\n                Console.WriteLine(key);\n            }\n\n            foreach (int val in assocArray.Values)\n            {\n                Console.WriteLine(val.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 60127, "name": "Define a primitive data type", "Python": ">>> class num(int):\n    def __init__(self, b):\n        if 1 <= b <= 10:\n            return int.__init__(self+0)\n        else:\n            raise ValueError,\"Value %s should be >=0 and <= 10\" % b\n\n        \n>>> x = num(3)\n>>> x = num(11)\n\nTraceback (most recent call last):\n  File \"<pyshell\n    x = num(11)\n  File \"<pyshell\n    raise ValueError,\"Value %s should be >=0 and <= 10\" % b\nValueError: Value 11 should be >=0 and <= 10\n>>> x\n3\n>>> type(x)\n<class '__main__.num'>\n>>>\n", "C#": "using System;\nusing System.Globalization;\n\nstruct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable\n{\n    const int MIN_VALUE = 1;\n    const int MAX_VALUE = 10;\n\n    public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);\n    public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);\n\n    static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;\n\n    readonly int _value;\n    public int Value => this._value == 0 ? MIN_VALUE : this._value; \n\n    public LimitedInt(int value)\n    {\n        if (!IsValidValue(value))\n            throw new ArgumentOutOfRangeException(nameof(value), value, $\"Value must be between {MIN_VALUE} and {MAX_VALUE}.\");\n        this._value = value;\n    }\n\n    #region IComparable\n    public int CompareTo(object obj)\n    {\n        if (obj is LimitedInt l) return this.Value.CompareTo(l);\n        throw new ArgumentException(\"Object must be of type \" + nameof(LimitedInt), nameof(obj));\n    }\n    #endregion\n\n    #region IComparable<LimitedInt>\n    public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);\n    #endregion\n\n    #region IConvertible\n    public TypeCode GetTypeCode() => this.Value.GetTypeCode();\n    bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);\n    byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);\n    char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);\n    DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);\n    decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);\n    double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);\n    short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);\n    int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);\n    long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);\n    sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);\n    float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);\n    string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);\n    object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);\n    ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);\n    uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);\n    ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);\n    #endregion\n\n    #region IEquatable<LimitedInt>\n    public bool Equals(LimitedInt other) => this == other;\n    #endregion\n\n    #region IFormattable\n    public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);\n    #endregion\n\n    #region operators\n    public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;\n    public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;\n    public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;\n    public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;\n    public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;\n    public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;\n\n    public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);\n    public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);\n\n    public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);\n    public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);\n    public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);\n    public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);\n    public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);\n\n    public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);\n    public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);\n    public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);\n    public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;\n\n    public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);\n    public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);\n\n    public static implicit operator int(LimitedInt value) => value.Value;\n    public static explicit operator LimitedInt(int value)\n    {\n        if (!IsValidValue(value)) throw new OverflowException();\n        return new LimitedInt(value);\n    }\n    #endregion\n\n    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)\n        => this.Value.TryFormat(destination, out charsWritten, format, provider);\n\n    public override int GetHashCode() => this.Value.GetHashCode();\n    public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);\n    public override string ToString() => this.Value.ToString();\n\n    #region static methods\n    public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);\n    public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);\n    public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);\n    public static int Parse(string s) => int.Parse(s);\n    public static int Parse(string s, NumberStyles style) => int.Parse(s, style);\n    public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);\n    public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);\n    #endregion\n}\n"}
{"id": 60128, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 60129, "name": "Solve a Holy Knight's tour", "Python": "from sys import stdout\nmoves = [\n    [-1, -2], [1, -2], [-1, 2], [1, 2],\n    [-2, -1], [-2, 1], [2, -1], [2, 1]\n]\n\n\ndef solve(pz, sz, sx, sy, idx, cnt):\n    if idx > cnt:\n        return 1\n\n    for i in range(len(moves)):\n        x = sx + moves[i][0]\n        y = sy + moves[i][1]\n        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:\n            pz[x][y] = idx\n            if 1 == solve(pz, sz, x, y, idx + 1, cnt):\n                return 1\n            pz[x][y] = 0\n\n    return 0\n\n\ndef find_solution(pz, sz):\n    p = [[-1 for j in range(sz)] for i in range(sz)]\n    idx = x = y = cnt = 0\n    for j in range(sz):\n        for i in range(sz):\n            if pz[idx] == \"x\":\n                p[i][j] = 0\n                cnt += 1\n            elif pz[idx] == \"s\":\n                p[i][j] = 1\n                cnt += 1\n                x = i\n                y = j\n            idx += 1\n\n    if 1 == solve(p, sz, x, y, 2, cnt):\n        for j in range(sz):\n            for i in range(sz):\n                if p[i][j] != -1:\n                    stdout.write(\" {:0{}d}\".format(p[i][j], 2))\n                else:\n                    stdout.write(\"   \")\n            print()\n    else:\n        print(\"Cannot solve this puzzle!\")\n\n\n\nfind_solution(\".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8)\nprint()\nfind_solution(\".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13)\n", "C#": "using System.Collections;\nusing System.Collections.Generic;\nusing static System.Console;\nusing static System.Math;\nusing static System.Linq.Enumerable;\n\npublic class Solver\n{\n    private static readonly (int dx, int dy)[]\n        \n        knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};\n\n    private (int dx, int dy)[] moves;\n        \n    public static void Main()\n    {\n        var knightSolver = new Solver(knightMoves);\n        Print(knightSolver.Solve(true,\n            \".000....\",\n            \".0.00...\",\n            \".0000000\",\n            \"000..0.0\",\n            \"0.0..000\",\n            \"1000000.\",\n            \"..00.0..\",\n            \"...000..\"));\n\n        Print(knightSolver.Solve(true,\n            \".....0.0.....\",\n            \".....0.0.....\",\n            \"....00000....\",\n            \".....000.....\",\n            \"..0..0.0..0..\",\n            \"00000...00000\",\n            \"..00.....00..\",\n            \"00000...00000\",\n            \"..0..0.0..0..\",\n            \".....000.....\",\n            \"....00000....\",\n            \".....0.0.....\",\n            \".....0.0.....\" \n        ));\n    }\n\n    public Solver(params (int dx, int dy)[] moves) => this.moves = moves;\n\n    public int[,] Solve(bool circular, params string[] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    public int[,] Solve(bool circular, int[,] puzzle)\n    {\n        var (board, given, count) = Parse(puzzle);\n        return Solve(board, given, count, circular);\n    }\n\n    private int[,] Solve(int[,] board, BitArray given, int count, bool circular)\n    {\n        var (height, width) = (board.GetLength(0), board.GetLength(1));\n        bool solved = false;\n        for (int x = 0; x < height && !solved; x++) {\n            solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));\n            if (solved) return board;\n        }\n        return null;\n    }\n\n    private bool Solve(int[,] board, BitArray given, bool circular,\n        (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)\n    {\n        var (x, y) = current;\n        if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;\n        if (board[x, y] < 0) return false;\n        if (given[n - 1]) {\n            if (board[x, y] != n) return false;\n        } else if (board[x, y] > 0) return false;\n        board[x, y] = n;\n        if (n == last) {\n            if (!circular || AreNeighbors(start, current)) return true;\n        }\n        for (int i = 0; i < moves.Length; i++) {\n            var move = moves[i];\n            if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;\n        }\n        if (!given[n - 1]) board[x, y] = 0;\n        return false;\n\n        bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(string[] input)\n    {\n        (int height, int width) = (input.Length, input[0].Length);\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++) {\n            string line = input[x];\n            for (int y = 0; y < width; y++) {\n                board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;\n                if (board[x, y] >= 0) count++;\n            }\n        }\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static (int[,] board, BitArray given, int count) Parse(int[,] input)\n    {\n        (int height, int width) = (input.GetLength(0), input.GetLength(1));\n        int[,] board = new int[height, width];\n        int count = 0;\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if ((board[x, y] = input[x, y]) >= 0) count++;\n        BitArray given = Scan(board, count, height, width);\n        return (board, given, count);\n    }\n\n    private static BitArray Scan(int[,] board, int count, int height, int width)\n    {\n        var given = new BitArray(count + 1);\n        for (int x = 0; x < height; x++)\n            for (int y = 0; y < width; y++)\n                if (board[x, y] > 0) given[board[x, y] - 1] = true;\n        return given;\n    }\n\n    private static void Print(int[,] board)\n    {\n        if (board == null) {\n            WriteLine(\"No solution\");\n        } else {\n            int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;\n            string e = new string('-', w);\n            foreach (int x in Range(0, board.GetLength(0)))\n                WriteLine(string.Join(\" \", Range(0, board.GetLength(1))\n                    .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));\n        }\n        WriteLine();\n    }\n\n}\n"}
{"id": 60130, "name": "Hash join", "Python": "from collections import defaultdict\n\ndef hashJoin(table1, index1, table2, index2):\n    h = defaultdict(list)\n    \n    for s in table1:\n        h[s[index1]].append(s)\n    \n    return [(s, r) for r in table2 for s in h[r[index2]]]\n\ntable1 = [(27, \"Jonah\"),\n          (18, \"Alan\"),\n          (28, \"Glory\"),\n          (18, \"Popeye\"),\n          (28, \"Alan\")]\ntable2 = [(\"Jonah\", \"Whales\"),\n          (\"Jonah\", \"Spiders\"),\n          (\"Alan\", \"Ghosts\"),\n          (\"Alan\", \"Zombies\"),\n          (\"Glory\", \"Buffy\")]\n\nfor row in hashJoin(table1, 1, table2, 0):\n    print(row)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HashJoin\n{\n    public class AgeName\n    {\n        public AgeName(byte age, string name)\n        {\n            Age = age;\n            Name = name;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n    }\n\n    public class NameNemesis\n    {\n        public NameNemesis(string name, string nemesis)\n        {\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    public class DataContext\n    {\n        public DataContext()\n        {\n            AgeName = new List<AgeName>();\n            NameNemesis = new List<NameNemesis>();\n        }\n        public List<AgeName> AgeName { get; set; }\n        public List<NameNemesis> NameNemesis { get; set; }\n    }\n\n    public class AgeNameNemesis\n    {\n        public AgeNameNemesis(byte age, string name, string nemesis)\n        {\n            Age = age;\n            Name = name;\n            Nemesis = nemesis;\n        }\n        public byte Age { get; private set; }\n        public string Name { get; private set; }\n        public string Nemesis { get; private set; }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var data = GetData();\n            var result = ExecuteHashJoin(data);\n            WriteResultToConsole(result);\n        }\n\n        private static void WriteResultToConsole(List<AgeNameNemesis> result)\n        {\n            result.ForEach(ageNameNemesis => Console.WriteLine(\"Age: {0}, Name: {1}, Nemesis: {2}\",\n                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));\n        }\n\n        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)\n        {\n            return (data.AgeName.Join(data.NameNemesis, \n                ageName => ageName.Name, nameNemesis => nameNemesis.Name,\n                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))\n                .ToList();\n        }\n\n        private static DataContext GetData()\n        {\n            var context = new DataContext();\n\n            context.AgeName.AddRange(new [] {\n                    new AgeName(27, \"Jonah\"), \n                    new AgeName(18, \"Alan\"), \n                    new AgeName(28, \"Glory\"), \n                    new AgeName(18, \"Popeye\"), \n                    new AgeName(28, \"Alan\")\n                });\n\n            context.NameNemesis.AddRange(new[]\n            {\n                new NameNemesis(\"Jonah\", \"Whales\"),\n                new NameNemesis(\"Jonah\", \"Spiders\"),\n                new NameNemesis(\"Alan\", \"Ghosts\"),\n                new NameNemesis(\"Alan\", \"Zombies\"),\n                new NameNemesis(\"Glory\", \"Buffy\")\n            });\n\n            return context;\n        }\n    }\n}\n"}
{"id": 60131, "name": "Odd squarefree semiprimes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 60132, "name": "Odd squarefree semiprimes", "Python": "\n\ndef isPrime(n):\n    for i in range(2, int(n**0.5) + 1):\n        if n % i == 0:\n            return False        \n    return True\n\n\nif __name__ == '__main__':\n    for p in range(3, 999):\n        if not isPrime(p):            \n            continue\n        for q in range(p+1, 1000//p):\n            if not isPrime(q):\n                continue\n            print(p*q, end = \" \");\n", "C#": "using System; using static System.Console; using System.Collections;\nusing System.Linq; using System.Collections.Generic;\n\nclass Program { static void Main(string[] args) {\n    int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();\n    var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();\n    lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)\n      res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))\n        Write(\"{0,4} {1}\", item, ++c % 20 == 0 ? \"\\n\" : \"\");\n    Write(\"\\n\\nCounted {0} odd squarefree semiprimes under {1}\", c, lmt); } }\n\nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 60133, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 60134, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 60135, "name": "Polynomial synthetic division", "Python": "from __future__ import print_function\nfrom __future__ import division\n\n\n\n\ndef extended_synthetic_division(dividend, divisor):\n    \n    \n\n    out = list(dividend) \n    normalizer = divisor[0]\n    for i in xrange(len(dividend)-(len(divisor)-1)):\n        out[i] /= normalizer \n                                 \n        coef = out[i]\n        if coef != 0: \n            for j in xrange(1, len(divisor)): \n                                              \n                out[i + j] += -divisor[j] * coef\n\n    \n    \n    \n    separator = -(len(divisor)-1)\n    return out[:separator], out[separator:] \n\nif __name__ == '__main__':\n    print(\"POLYNOMIAL SYNTHETIC DIVISION\")\n    N = [1, -12, 0, -42]\n    D = [1, -3]\n    print(\"  %s / %s  =\" % (N,D), \" %s remainder %s\" % extended_synthetic_division(N, D))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SyntheticDivision\n{\n    class Program\n    {\n        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)\n        {\n            List<int> output = dividend.ToList();\n            int normalizer = divisor[0];\n\n            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)\n            {\n                output[i] /= normalizer;\n\n                int coef = output[i];\n                if (coef != 0)\n                {\n                    for (int j = 1; j < divisor.Count(); j++)\n                        output[i + j] += -divisor[j] * coef;\n                }\n            }\n\n            int separator = output.Count() - (divisor.Count() - 1);\n\n            return (\n                output.GetRange(0, separator),\n                output.GetRange(separator, output.Count() - separator)\n            );\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> N = new List<int>{ 1, -12, 0, -42 };\n            List<int> D = new List<int> { 1, -3 };\n\n            var (quotient, remainder) = extendedSyntheticDivision(N, D);\n            Console.WriteLine(\"[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]\" ,\n                string.Join(\",\", N),\n                string.Join(\",\", D),\n                string.Join(\",\", quotient),\n                string.Join(\",\", remainder)\n            );\n        }\n    }\n}\n"}
{"id": 60136, "name": "Respond to an unknown method call", "Python": "class Example(object):\n    def foo(self):\n        print(\"this is foo\")\n    def bar(self):\n        print(\"this is bar\")\n    def __getattr__(self, name):\n        def method(*args):\n            print(\"tried to handle unknown method \" + name)\n            if args:\n                print(\"it had arguments: \" + str(args))\n        return method\n\nexample = Example()\n\nexample.foo()        \nexample.bar()        \nexample.grill()      \nexample.ding(\"dong\") \n                     \n", "C#": "using System;\nusing System.Dynamic;\n\nclass Example : DynamicObject\n{\n    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n    {\n        result = null;\n\n        Console.WriteLine(\"This is {0}.\", binder.Name);\n        return true;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic ex = new Example();\n\n        ex.Foo();\n        ex.Bar();\n    }\n}\n"}
{"id": 60137, "name": "Latin Squares in reduced form", "Python": "def dList(n, start):\n    start -= 1 \n    a = range(n)\n    a[start] = a[0]\n    a[0] = start\n    a[1:] = sorted(a[1:])\n    first = a[1]\n    \n    r = []\n    def recurse(last):\n        if (last == first):\n            \n            \n            \n            for j,v in enumerate(a[1:]):\n                if j + 1 == v:\n                    return \n            b = [x + 1 for x in a]\n            r.append(b)\n            return\n        for i in xrange(last, 0, -1):\n            a[i], a[last] = a[last], a[i]\n            recurse(last - 1)\n            a[i], a[last] = a[last], a[i]\n    recurse(n - 1)\n    return r\n\ndef printSquare(latin,n):\n    for row in latin:\n        print row\n    print\n\ndef reducedLatinSquares(n,echo):\n    if n <= 0:\n        if echo:\n            print []\n        return 0\n    elif n == 1:\n        if echo:\n            print [1]\n        return 1\n\n    rlatin = [None] * n\n    for i in xrange(n):\n        rlatin[i] = [None] * n\n    \n    for j in xrange(0, n):\n        rlatin[0][j] = j + 1\n\n    class OuterScope:\n        count = 0\n    def recurse(i):\n        rows = dList(n, i)\n\n        for r in xrange(len(rows)):\n            rlatin[i - 1] = rows[r]\n            justContinue = False\n            k = 0\n            while not justContinue and k < i - 1:\n                for j in xrange(1, n):\n                    if rlatin[k][j] == rlatin[i - 1][j]:\n                        if r < len(rows) - 1:\n                            justContinue = True\n                            break\n                        if i > 2:\n                            return\n                k += 1\n            if not justContinue:\n                if i < n:\n                    recurse(i + 1)\n                else:\n                    OuterScope.count += 1\n                    if echo:\n                        printSquare(rlatin, n)\n\n    \n    recurse(2)\n    return OuterScope.count\n\ndef factorial(n):\n    if n == 0:\n        return 1\n    prod = 1\n    for i in xrange(2, n + 1):\n        prod *= i\n    return prod\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4,True)\n\nprint \"The size of the set of reduced latin squares for the following orders\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in xrange(1, 7):\n    size = reducedLatinSquares(n, False)\n    f = factorial(n - 1)\n    f *= f * n * size\n    print \"Order %d: Size %-4d x %d! x %d! => Total %d\" % (n, size, n, n - 1, f)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LatinSquares {\n    using matrix = List<List<int>>;\n\n    class Program {\n        static void Swap<T>(ref T a, ref T b) {\n            var t = a;\n            a = b;\n            b = t;\n        }\n\n        static matrix DList(int n, int start) {\n            start--; \n            var a = Enumerable.Range(0, n).ToArray();\n            a[start] = a[0];\n            a[0] = start;\n            Array.Sort(a, 1, a.Length - 1);\n            var first = a[1];\n            \n            matrix r = new matrix();\n            void recurse(int last) {\n                if (last == first) {\n                    \n                    \n                    for (int j = 1; j < a.Length; j++) {\n                        var v = a[j];\n                        if (j == v) {\n                            return; \n                        }\n                    }\n                    \n                    var b = a.Select(v => v + 1).ToArray();\n                    r.Add(b.ToList());\n                    return;\n                }\n                for (int i = last; i >= 1; i--) {\n                    Swap(ref a[i], ref a[last]);\n                    recurse(last - 1);\n                    Swap(ref a[i], ref a[last]);\n                }\n            }\n            recurse(n - 1);\n            return r;\n        }\n\n        static ulong ReducedLatinSquares(int n, bool echo) {\n            if (n <= 0) {\n                if (echo) {\n                    Console.WriteLine(\"[]\\n\");\n                }\n                return 0;\n            } else if (n == 1) {\n                if (echo) {\n                    Console.WriteLine(\"[1]\\n\");\n                }\n                return 1;\n            }\n\n            matrix rlatin = new matrix();\n            for (int i = 0; i < n; i++) {\n                rlatin.Add(new List<int>());\n                for (int j = 0; j < n; j++) {\n                    rlatin[i].Add(0);\n                }\n            }\n            \n            for (int j = 0; j < n; j++) {\n                rlatin[0][j] = j + 1;\n            }\n\n            ulong count = 0;\n            void recurse(int i) {\n                var rows = DList(n, i);\n\n                for (int r = 0; r < rows.Count; r++) {\n                    rlatin[i - 1] = rows[r];\n                    for (int k = 0; k < i - 1; k++) {\n                        for (int j = 1; j < n; j++) {\n                            if (rlatin[k][j] == rlatin[i - 1][j]) {\n                                if (r < rows.Count - 1) {\n                                    goto outer;\n                                }\n                                if (i > 2) {\n                                    return;\n                                }\n                            }\n                        }\n                    }\n                    if (i < n) {\n                        recurse(i + 1);\n                    } else {\n                        count++;\n                        if (echo) {\n                            PrintSquare(rlatin, n);\n                        }\n                    }\n                outer: { }\n                }\n            }\n\n            \n            recurse(2);\n            return count;\n        }\n\n        static void PrintSquare(matrix latin, int n) {\n            foreach (var row in latin) {\n                var it = row.GetEnumerator();\n                Console.Write(\"[\");\n                if (it.MoveNext()) {\n                    Console.Write(it.Current);\n                }\n                while (it.MoveNext()) {\n                    Console.Write(\", {0}\", it.Current);\n                }\n                Console.WriteLine(\"]\");\n            }\n            Console.WriteLine();\n        }\n\n        static ulong Factorial(ulong n) {\n            if (n <= 0) {\n                return 1;\n            }\n            ulong prod = 1;\n            for (ulong i = 2; i < n + 1; i++) {\n                prod *= i;\n            }\n            return prod;\n        }\n\n        static void Main() {\n            Console.WriteLine(\"The four reduced latin squares of order 4 are:\\n\");\n            ReducedLatinSquares(4, true);\n\n            Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\");\n            Console.WriteLine(\"and hence the total number of latin squares of these orders are:\\n\");\n            for (int n = 1; n < 7; n++) {\n                ulong nu = (ulong)n;\n\n                var size = ReducedLatinSquares(n, false);\n                var f = Factorial(nu - 1);\n                f *= f * nu * size;\n                Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f);\n            }\n        }\n    }\n}\n"}
{"id": 60138, "name": "Closest-pair problem", "Python": "\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints/2]\n    Pr = xP[numPoints/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    \n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        \n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    \n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n", "C#": "class Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n"}
{"id": 60139, "name": "Address of a variable", "Python": "var num = 12\nvar pointer = ptr(num) \n\nprint pointer \n\n@unsafe \npointer.addr = 0xFFFE \n", "C#": "int i = 5;\nint* p = &i;\n"}
{"id": 60140, "name": "Inheritance_Single", "Python": "class Animal:\n  pass \n\nclass Dog(Animal):\n  pass \n\nclass Cat(Animal):\n  pass \n\nclass Lab(Dog):\n  pass \n\nclass Collie(Dog):\n  pass \n", "C#": "class Animal\n{ \n   \n  \n}\n\nclass Dog : Animal\n{ \n   \n  \n}\n\nclass Lab : Dog\n{ \n   \n  \n}\n\nclass Collie : Dog\n{ \n  \n  \n}\n\nclass Cat : Animal\n{ \n  \n  \n}\n"}
{"id": 60141, "name": "Associative array_Creation", "Python": "hash = dict()  \nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n", "C#": "System.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n"}
{"id": 60142, "name": "Color wheel", "Python": "size(300, 300)\nbackground(0)\nradius = min(width, height) / 2.0\ncx, cy = width / 2, width / 2\nfor x in range(width):\n        for y in range(height):\n            rx = x - cx\n            ry = y - cy\n            s = sqrt(rx ** 2 + ry ** 2) / radius\n            if s <= 1.0:\n                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0\n                colorMode(HSB)\n                c = color(int(h * 255), int(s * 255), 255)\n                set(x, y, c) \n", "C#": "\n\npublic MainWindow()\n{\n    InitializeComponent();\n    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);\n    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);\n    \n    DrawHue(100);\n}\n\nvoid DrawHue(int saturation)\n{\n    var bmp = (WriteableBitmap)imgMain.Source;\n\n    int centerX = (int)bmp.Width / 2;\n    int centerY = (int)bmp.Height / 2;\n    int radius = Math.Min(centerX, centerY);\n    int radius2 = radius - 40;\n\n    bmp.Lock();\n    unsafe{\n        var buf = bmp.BackBuffer;\n        IntPtr pixLineStart;\n        for(int y=0; y < bmp.Height; y++){\n            pixLineStart = buf + bmp.BackBufferStride * y;\n            double dy = (y - centerY);\n            for(int x=0; x < bmp.Width; x++){\n                double dx = (x - centerX);\n                double dist = Math.Sqrt(dx * dx + dy * dy);\n                if (radius2 <= dist && dist <= radius) {\n                    double theta = Math.Atan2(dy, dx);\n                    double hue = (theta + Math.PI) / (2.0 * Math.PI);\n                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);\n                }\n            }\n        }\n    }\n    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));\n    bmp.Unlock();\n}\n\nstatic int HSB_to_RGB(int h, int s, int v)\n{\n    var rgb = new int[3];\n\n    var baseColor = (h + 60) % 360 / 120;\n    var shift = (h + 60) % 360 - (120 * baseColor + 60 );\n    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;\n\n    \n    rgb[baseColor] = 255;\n    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));\n\n    \n    for (var i = 0; i < 3; i++)\n        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);\n\n    return RGB2int(rgb[0], rgb[1], rgb[2]);\n}\n\npublic static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;\n"}
{"id": 60143, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 60144, "name": "Polymorphism", "Python": "class Point(object):\n    def __init__(self, x=0.0, y=0.0):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)\n\nclass Circle(object):\n    def __init__(self, center=None, radius=1.0):\n        self.center = center or Point()\n        self.radius = radius\n    def __repr__(self):\n        return '<Circle 0x%x x: %f y: %f radius: %f>' % (\n            id(self), self.center.x, self.center.y, self.radius)\n", "C#": "using System;\nclass Point\n{\n  protected int x, y;\n  public Point() : this(0) {}\n  public Point(int x) : this(x,0) {}\n  public Point(int x, int y) { this.x = x; this.y = y; }\n  public int X { get { return x; } set { x = value; } }\n  public int Y { get { return y; } set { y = value; } }\n  public virtual void print() { System.Console.WriteLine(\"Point\"); }\n}\n\npublic class Circle : Point\n{\n  private int r;\n  public Circle(Point p) : this(p,0) { }\n  public Circle(Point p, int r) : base(p) { this.r = r; }\n  public Circle() : this(0) { }\n  public Circle(int x) : this(x,0) { }\n  public Circle(int x, int y) : this(x,y,0) { }\n  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }\n  public int R { get { return r; } set { r = value; } }\n  public override void print() { System.Console.WriteLine(\"Circle\"); }\n \n  public static void main(String args[])\n  {\n    Point p = new Point();\n    Point c = new Circle();\n    p.print();\n    c.print();\n  }\n}\n"}
{"id": 60145, "name": "Rare numbers", "Python": "\n\n\n\nfrom math import floor, sqrt\nfrom datetime import datetime\n\ndef main():\n\tstart = datetime.now()\n\tfor i in xrange(1, 10 ** 11):\n\t\tif rare(i):\n\t\t\tprint \"found a rare:\", i\n\tend = datetime.now()\n\tprint \"time elapsed:\", end - start\n\ndef is_square(n):\n\ts = floor(sqrt(n + 0.5))\n\treturn s * s == n\n\ndef reverse(n):\n\treturn int(str(n)[::-1])\n\ndef is_palindrome(n):\n\treturn n == reverse(n)\n\ndef rare(n):\n\tr = reverse(n)\n\treturn ( \n\t\tnot is_palindrome(n) and \n\t\tn > r and\n\t\tis_square(n+r) and is_square(n-r)\n\t)\n\nif __name__ == '__main__':\n\tmain()\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nusing UI = System.UInt64;\nusing LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;\nusing Lst = System.Collections.Generic.List<sbyte>;\nusing DT = System.DateTime;\n\nclass Program {\n\n    const sbyte MxD = 19;\n\n    public struct term { public UI coeff; public sbyte a, b;\n        public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } }\n\n    static int[] digs;   static List<UI> res;   static sbyte count = 0;\n    static DT st; static List<List<term>> tLst; static List<LST> lists;\n    static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il;\n    static bool odd; static int nd, nd2; static LST ixs;\n    static int[] cnd, di; static LST dis; static UI Dif;\n\n    \n    static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++)\n            r = r * 10 + (uint)digs[i]; return r; }\n    \n    \n    static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--)\n            r = r * 10 + (uint)digs[i]; return Dif + (r << 1); }\n\n    \n    static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0)\n        { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; }\n\n    \n    static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst();\n        for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; }\n\n    \n    static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0];\n            digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1;\n            if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) {\n                digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; }\n            if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine(\"{0,16:n0}{1,4}   ({2:n0})\",\n                (DT.Now - st).TotalMilliseconds, ++count, res.Last()); }\n        else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } }\n\n    \n    static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0;\n            foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]);\n                else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return;\n            dis = new LST { Seq(0, fml[cnd[0]].Count - 1) };\n            foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1));\n            if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0);\n        } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } }\n\n    static void init() { UI pow = 1;\n        \n        tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) {\n            List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1;\n            for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) {\n                terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; }\n            tLst.Add(terms); }\n        \n        fml = new Dictionary<int, LST> {\n            [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } },\n            [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } },\n            [4] = new LST { new Lst { 4, 0 } },\n            [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } };\n        \n        dmd = new Dictionary<int, LST>();\n        for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) {\n                if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j });\n                else dmd[d] = new LST { new Lst { i, j } }; }\n        dl = Seq(-9, 9);    \n        zl = Seq( 0, 0);    \n        el = Seq(-8, 8, 2); \n        ol = Seq(-9, 9, 2); \n        il = Seq( 0, 9); lists = new List<LST>();\n        foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); }\n\n    static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0;\n        WriteLine(\"{0,5}{1,12}{2,4}{3,14}\", \"digs\", \"elapsed(ms)\", \"R/N\", \"Unordered Rare Numbers\");\n        for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd];\n            if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); }\n            else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl);\n            ixs = new LST(); \n            foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b });\n            foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); }\n            WriteLine(\"  {0,2}  {1,10:n0}\", nd, (DT.Now - st).TotalMilliseconds); }\n        res.Sort();\n        WriteLine(\"\\nThe {0} rare numbers with up to {1} digits are:\", res.Count, MxD);\n        count = 0; foreach (var rare in res) WriteLine(\"{0,2}:{1,27:n0}\", ++count, rare);\n        if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }\n}\n"}
{"id": 60146, "name": "Minesweeper game", "Python": "\n\n\ngridsize  = (6, 4)\nminerange = (0.2, 0.6)\n\n\ntry:\n    raw_input\nexcept:\n    raw_input = input\n    \nimport random\nfrom itertools import product\nfrom pprint import pprint as pp\n\n\ndef gridandmines(gridsize=gridsize, minerange=minerange):\n    xgrid, ygrid = gridsize\n    minmines, maxmines = minerange\n    minecount = xgrid * ygrid    \n    minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))\n    grid = set(product(range(xgrid), range(ygrid)))\n    mines = set(random.sample(grid, minecount))\n    show = {xy:'.' for xy in grid}\n    return grid, mines, show\n\ndef printgrid(show, gridsize=gridsize):\n    xgrid, ygrid = gridsize\n    grid = '\\n'.join(''.join(show[(x,y)] for x in range(xgrid))\n                     for y in range(ygrid))\n    print( grid )\n\ndef resign(showgrid, mines, markedmines):\n    for m in mines:\n        showgrid[m] = 'Y' if m in markedmines else 'N'\n\ndef clear(x,y, showgrid, grid, mines, markedmines):\n    if showgrid[(x, y)] == '.':\n        xychar = str(sum(1\n                         for xx in (x-1, x, x+1)\n                         for yy in (y-1, y, y+1)\n                         if (xx, yy) in mines ))\n        if xychar == '0': xychar = '.'\n        showgrid[(x,y)] = xychar\n        for xx in (x-1, x, x+1):\n            for yy in (y-1, y, y+1):\n                xxyy = (xx, yy)\n                if ( xxyy != (x, y)\n                     and xxyy in grid\n                     and xxyy not in mines | markedmines ):\n                    clear(xx, yy, showgrid, grid, mines, markedmines)\n\nif __name__ == '__main__':\n    grid, mines, showgrid = gridandmines()\n    markedmines = set([])\n    print( __doc__ )\n    print( '\\nThere are %i true mines of fixed position in the grid\\n' % len(mines) )\n    printgrid(showgrid)\n    while markedmines != mines:\n        inp = raw_input('m x y/c x y/p/r: ').strip().split()\n        if inp:\n            if inp[0] == 'm':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in markedmines:\n                    markedmines.remove((x,y))\n                    showgrid[(x,y)] = '.'\n                else:\n                    markedmines.add((x,y))\n                    showgrid[(x,y)] = '?'\n            elif inp[0] == 'p':\n                printgrid(showgrid)\n            elif inp[0] == 'c':\n                x, y = [int(i)-1 for i in inp[1:3]]\n                if (x,y) in mines | markedmines:\n                    print( '\\nKLABOOM!! You hit a mine.\\n' )\n                    resign(showgrid, mines, markedmines)\n                    printgrid(showgrid)\n                    break\n                clear(x,y, showgrid, grid, mines, markedmines)\n                printgrid(showgrid)\n            elif inp[0] == 'r':\n                print( '\\nResigning!\\n' )\n                resign(showgrid, mines, markedmines)\n                printgrid(showgrid)\n                break\n    \n    print( '\\nYou got %i and missed %i of the %i mines'\n           % (len(mines.intersection(markedmines)),\n              len(markedmines.difference(mines)),\n              len(mines)) )\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MineFieldModel\n{\n    public int RemainingMinesCount{\n        get{\n            var count = 0;\n            ForEachCell((i,j)=>{\n                if (Mines[i,j] && !Marked[i,j])\n                    count++;\n            });\n            return count;\n        }\n    }\n\n    public bool[,] Mines{get; private set;}\n    public bool[,] Opened{get;private set;}\n    public bool[,] Marked{get; private set;}\n    public int[,] Values{get;private set; }\n    public int Width{ get{return Mines.GetLength(1);} } \n    public int Height{ get{return Mines.GetLength(0);} }\n\n    public MineFieldModel(bool[,] mines)\n    {\n        this.Mines = mines;\n        this.Opened = new bool[Height, Width]; \n        this.Marked = new bool[Height, Width];\n        this.Values = CalculateValues();\n    }\n    \n    private int[,] CalculateValues()\n    {\n        int[,] values = new int[Height, Width];\n        ForEachCell((i,j) =>{\n            var value = 0;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (Mines[i1,j1])\n                    value++;\n            });\n            values[i,j] = value;\n        });\n        return values;\n    }\n\n    \n    public void ForEachCell(Action<int,int> action)\n    {\n        for (var i = 0; i < Height; i++)\n        for (var j = 0; j < Width; j++)\n            action(i,j);\n    }\n\n    \n    public void ForEachNeighbor(int i, int j, Action<int,int> action)\n    {\n        for (var i1 = i-1; i1 <= i+1; i1++)\n        for (var j1 = j-1; j1 <= j+1; j1++)               \n            if (InBounds(j1, i1) && !(i1==i && j1 ==j))\n                action(i1, j1);\n    }\n\n    private bool InBounds(int x, int y)\n    {\n        return y >= 0 && y < Height && x >=0 && x < Width;\n    }\n\n    public event Action Exploded = delegate{};\n    public event Action Win = delegate{};\n    public event Action Updated = delegate{};\n\n    public void OpenCell(int i, int j){\n        if(!Opened[i,j]){\n            if (Mines[i,j])\n                Exploded();\n            else{\n                OpenCellsStartingFrom(i,j);\n                Updated();\n                CheckForVictory();\n            }\n        }\n    }\n\n    void OpenCellsStartingFrom(int i, int j)\n    {\n            Opened[i,j] = true;\n            ForEachNeighbor(i,j, (i1,j1)=>{\n                if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1])\n                    OpenCellsStartingFrom(i1, j1);\n            });\n    }\n    \n    void CheckForVictory(){\n        int notMarked = 0;\n        int wrongMarked = 0;\n        ForEachCell((i,j)=>{\n            if (Mines[i,j] && !Marked[i,j])\n                notMarked++;\n            if (!Mines[i,j] && Marked[i,j])\n                wrongMarked++;\n        }); \n        if (notMarked == 0 && wrongMarked == 0)\n            Win();\n    }\n\n    public void Mark(int i, int j){\n        if (!Opened[i,j])\n            Marked[i,j] = true;\n            Updated();\n            CheckForVictory();\n    }\n}\n\nclass MineFieldView: UserControl{\n    public const int CellSize = 40;\n\n    MineFieldModel _model;\n    public MineFieldModel Model{\n        get{ return _model; }\n        set\n        { \n            _model = value; \n            this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2);\n        }\n    }\n    \n    public MineFieldView(){\n        \n        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true);\n        this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);\n\n        this.MouseUp += (o,e)=>{\n            Point cellCoords = GetCell(e.Location);\n            if (Model != null)\n            {\n                if (e.Button == MouseButtons.Left)\n                    Model.OpenCell(cellCoords.Y, cellCoords.X);\n                else if (e.Button == MouseButtons.Right)\n                    Model.Mark(cellCoords.Y, cellCoords.X);\n            }\n        };\n    }\n\n    Point GetCell(Point coords)\n    {\n        var rgn = ClientRectangle;\n        var x = (coords.X - rgn.X)/CellSize;\n        var y = (coords.Y - rgn.Y)/CellSize;\n        return new Point(x,y);\n    }\n         \n    static readonly Brush MarkBrush = new SolidBrush(Color.Blue);\n    static readonly Brush ValueBrush = new SolidBrush(Color.Black);\n    static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control);\n    static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark);\n\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        var g = e.Graphics;\n        if (Model != null)\n        {\n            Model.ForEachCell((i,j)=>\n            {\n                var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize);\n                if (Model.Opened[i,j])\n                {\n                    g.FillRectangle(OpenBrush, bounds);\n                    if (Model.Values[i,j] > 0)\n                    {\n                        DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds);\n                    }\n                } \n                else \n                {\n                    g.FillRectangle(UnexploredBrush, bounds);\n                    if (Model.Marked[i,j])\n                    {\n                        DrawStringInCenter(g, \"?\", MarkBrush, bounds);\n                    }\n                    var outlineOffset = 1;\n                    var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset);\n                    g.DrawRectangle(Pens.Gray, outline);\n                }\n                g.DrawRectangle(Pens.Black, bounds);\n            });\n        }\n\n    }\n\n    static readonly StringFormat FormatCenter = new StringFormat\n                            {\n                                LineAlignment = StringAlignment.Center,\n                                Alignment=StringAlignment.Center\n                            };\n\n    void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds)\n    {\n        PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2);\n        g.DrawString(s, this.Font, brush, center, FormatCenter);\n    }\n\n}\n\nclass MineSweepForm: Form\n{\n\n    MineFieldModel CreateField(int width, int height)\n{\n        var field = new bool[height, width];\n        int mineCount = (int)(0.2 * height * width);\n        var rnd = new Random();\n        while(mineCount > 0)\n        {\n            var x = rnd.Next(width);\n            var y = rnd.Next(height);\n            if (!field[y,x])\n            {\n                field[y,x] = true;\n                mineCount--;\n            }\n        }\n        return new MineFieldModel(field);\n    }\n\n    public MineSweepForm()\n    {\n        var model = CreateField(6, 4);\n        var counter = new Label{ };\n        counter.Text = model.RemainingMinesCount.ToString();\n        var view = new MineFieldView\n                        { \n                            Model = model, BorderStyle = BorderStyle.FixedSingle,\n                        };\n        var stackPanel = new FlowLayoutPanel\n                        {\n                            Dock = DockStyle.Fill,\n                            FlowDirection = FlowDirection.TopDown,\n                            Controls = {counter, view}\n                        };\n        this.Controls.Add(stackPanel);\n        model.Updated += delegate{\n            view.Invalidate();\n            counter.Text = model.RemainingMinesCount.ToString();\n        };\n        model.Exploded += delegate {\n            MessageBox.Show(\"FAIL!\");\n            Close();\n        };\n        model.Win += delegate {\n            MessageBox.Show(\"WIN!\");\n            view.Enabled = false;\n        };\n\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Application.Run(new MineSweepForm());\n    }\n}\n"}
{"id": 60147, "name": "Primes with digits in nondecreasing order", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 60148, "name": "Primes with digits in nondecreasing order", "Python": "\n\nfrom operator import le\nfrom itertools import takewhile\n\n\n\ndef monotonicDigits(base):\n    \n    def go(n):\n        return monotonic(le)(\n            showIntAtBase(base)(digitFromInt)(n)('')\n        )\n    return go\n\n\n\ndef monotonic(op):\n    \n    def go(xs):\n        return all(map(op, xs, xs[1:]))\n    return go\n\n\n\n\ndef main():\n    \n    xs = [\n        str(n) for n in takewhile(\n            lambda n: 1000 > n,\n            filter(monotonicDigits(10), primes())\n        )\n    ]\n    w = len(xs[-1])\n    print(f'{len(xs)} matches for base 10:\\n')\n    print('\\n'.join(\n        ' '.join(row) for row in chunksOf(10)([\n            x.rjust(w, ' ') for x in xs\n        ])\n    ))\n\n\n\n\n\ndef chunksOf(n):\n    \n    def go(xs):\n        return (\n            xs[i:n + i] for i in range(0, len(xs), n)\n        ) if 0 < n else None\n    return go\n\n\n\ndef digitFromInt(n):\n    \n    return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (\n        0 <= n < 36\n    ) else '?'\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\n\ndef showIntAtBase(base):\n    \n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0 != n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;\n \nclass Program {\n\n  static int ba; static string chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  \n  static string from10(int b) { string res = \"\"; int re; while (b > 0) {\n    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }\n\n  \n  static int to10(string s) { int res = 0; foreach (char i in s)\n    res = res * ba + chars.IndexOf(i); return res; }\n\n  \n  static bool nd(string s) { if (s.Length < 2) return true;\n    char l = s[0]; for (int i = 1; i < s.Length; i++)\n      if (chars.IndexOf(l) > chars.IndexOf(s[i]))\n        return false; else l = s[i] ; return true; }\n\n  static void Main(string[] args) { int c, lim = 1000; string s;\n    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {\n      ba = b; c = 0; foreach (var a in PG.Primes(lim))\n        if (nd(s = from10(a))) Write(\"{0,4} {1}\", s, ++c % 20 == 0 ? \"\\n\" : \"\");\n    WriteLine(\"\\nBase {0}: found {1} non-decreasing primes under {2:n0}\\n\", b, c, from10(lim)); } } } \n \nclass PG { public static IEnumerable<int> Primes(int lim) {\n    var flags = new bool[lim + 1]; int j; yield return 2;\n    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;\n    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)\n      if (!flags[j]) { yield return j;\n        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }\n    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }\n"}
{"id": 60149, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n"}
{"id": 60150, "name": "Reflection_List properties", "Python": "class Parent(object):\n    __priv = 'private'\n    \n    def __init__(self, name):\n        self.name = name\n    \n    def __repr__(self):\n        return '%s(%s)' % (type(self).__name__, self.name)\n    \n    def doNothing(self):\n        pass\n\nimport re\n\nclass Child(Parent):\n    \n    __rePrivate = re.compile('^_(Child|Parent)__')\n    \n    __reBleh = re.compile('\\Wbleh$')\n    @property\n    def reBleh(self):\n        return self.__reBleh\n    \n    def __init__(self, name, *args):\n        super(Child, self).__init__(name)\n        self.args = args\n    \n    def __dir__(self):\n        myDir = filter(\n            \n            lambda p: not self.__rePrivate.match(p),\n            list(set( \\\n                sum([dir(base) for base in type(self).__bases__], []) \\\n                + type(self).__dict__.keys() \\\n                + self.__dict__.keys() \\\n            )))\n        return myDir + map(\n            \n            lambda p: p + '_bleh',\n            filter(\n                \n                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),\n                myDir))\n    \n    def __getattr__(self, name):\n        if name[-5:] == '_bleh':\n            \n            return str(getattr(self, name[:-5])) + ' bleh'\n        if hasattr(super(Child, chld), '__getattr__'):\n            return super(Child, self).__getattr__(name)\n        raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n    \n    def __setattr__(self, name, value):\n        if name[-5:] == '_bleh':\n            \n            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):\n                setattr(self, name[:-5], self.reBleh.sub('', value))\n        elif hasattr(super(Child, self), '__setattr__'):\n            super(Child, self).__setattr__(name, value)\n        elif hasattr(self, '__dict__'):\n            self.__dict__[name] = value\n    \n    def __repr__(self):\n        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))\n    \n    def doStuff(self):\n        return (1+1.0/1e6) ** 1e6\n\npar = Parent('par')\npar.parent = True\ndir(par)\n\ninspect.getmembers(par)\n\n\nchld = Child('chld', 0, 'I', 'two')\nchld.own = \"chld's own\"\ndir(chld)\n\ninspect.getmembers(chld)\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\npublic static class Reflection\n{\n    public static void Main() {\n        var t = new TestClass();\n        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n        foreach (var prop in GetPropertyValues(t, flags)) {\n            Console.WriteLine(prop);\n        }\n        foreach (var field in GetFieldValues(t, flags)) {\n            Console.WriteLine(field);\n        }\n    }\n\n    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>\n        from p in typeof(T).GetProperties(flags)\n        where p.GetIndexParameters().Length == 0 \n        select (p.Name, p.GetValue(obj, null));\n    \n    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>\n        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));\n    \n    class TestClass\n    {\n        private int privateField = 7;\n        public int PublicNumber { get; } = 4;\n        private int PrivateNumber { get; } = 2;\n    }\n\n}\n"}
{"id": 60151, "name": "Minimal steps down to 1", "Python": "from functools import lru_cache\n\n\n\n\nDIVS = {2, 3}\nSUBS = {1}\n\nclass Minrec():\n    \"Recursive, memoised minimised steps to 1\"\n\n    def __init__(self, divs=DIVS, subs=SUBS):\n        self.divs, self.subs = divs, subs\n\n    @lru_cache(maxsize=None)\n    def _minrec(self, n):\n        \"Recursive, memoised\"\n        if n == 1:\n            return 0, ['=1']\n        possibles = {}\n        for d in self.divs:\n            if n % d == 0:\n                possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)\n        for s in self.subs:\n            if n > s:\n                possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)\n        thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])\n        ret = 1 + count, [thiskind] + otherkinds\n        return ret\n\n    def __call__(self, n):\n        \"Recursive, memoised\"\n        ans = self._minrec(n)[1][:-1]\n        return len(ans), ans\n\n\nif __name__ == '__main__':\n    for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:\n        minrec = Minrec(DIVS, SUBS)\n        print('\\nMINIMUM STEPS TO 1: Recursive algorithm')\n        print('  Possible divisors:  ', DIVS)\n        print('  Possible decrements:', SUBS)\n        for n in range(1, 11):\n            steps, how = minrec(n)\n            print(f'    minrec({n:2}) in {steps:2} by: ', ', '.join(how))\n\n        upto = 2000\n        print(f'\\n    Those numbers up to {upto} that take the maximum, \"minimal steps down to 1\":')\n        stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))\n        mx = stepn[-1][0]\n        ans = [x[1] for x in stepn if x[0] == mx]\n        print('      Taking', mx, f'steps is/are the {len(ans)} numbers:',\n              ', '.join(str(n) for n in sorted(ans)))\n        \n        print()\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class MinimalSteps\n{\n    public static void Main() {\n        var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });\n        var lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n        Console.WriteLine();\n\n        subtractors = new [] { 2 };\n        lookup = CreateLookup(2_000, divisors, subtractors);\n        Console.WriteLine($\"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]\");\n        PrintRange(lookup, 10);\n        PrintMaxMins(lookup);\n        lookup = CreateLookup(20_000, divisors, subtractors);\n        PrintMaxMins(lookup);\n    }\n\n    private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {\n        for (int goal = 1; goal <= limit; goal++) {\n            var x = lookup[goal];\n            if (x.param == 0) {\n                Console.WriteLine($\"{goal} cannot be reached with these numbers.\");\n                continue;\n            }\n            Console.Write($\"{goal} takes {x.steps} {(x.steps == 1 ? \"step\" : \"steps\")}: \");\n            for (int n = goal; n > 1; ) {\n                Console.Write($\"{n},{x.op}{x.param}=> \");\n                n = x.op == '/' ? n / x.param : n - x.param;\n                x = lookup[n];\n            }\n            Console.WriteLine(\"1\");\n        }\n    }\n\n    private static void PrintMaxMins((char op, int param, int steps)[] lookup) {\n        var maxSteps = lookup.Max(x => x.steps);\n        var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();\n        Console.WriteLine(items.Count == 1\n            ? $\"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}\"\n            : $\"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}\"\n        );\n    }\n\n    private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)\n    {\n        var lookup = new (char op, int param, int steps)[goal+1];\n        lookup[1] = ('/', 1, 0);\n        for (int n = 1; n < lookup.Length; n++) {\n            var ln = lookup[n];\n            if (ln.param == 0) continue;\n            for (int d = 0; d < divisors.Length; d++) {\n                int target = n * divisors[d];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);\n            }\n            for (int s = 0; s < subtractors.Length; s++) {\n                int target = n + subtractors[s];\n                if (target > goal) break;\n                if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);\n            }\n        }\n        return lookup;\n    }\n\n    private static string Delimit<T>(this IEnumerable<T> source) => string.Join(\", \", source);\n}\n"}
{"id": 60152, "name": "Align columns", "Python": "from itertools import zip_longest\n\ntxt = \n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n", "C#": "using System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) / 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n"}
{"id": 60153, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 60154, "name": "URL parser", "Python": "import urllib.parse as up \n\nurl = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1\n\nprint('url.scheme = ', url.scheme)\nprint('url.netloc = ', url.netloc)\nprint('url.hostname = ', url.hostname)\nprint('url.port = ', url.port)\nprint('url.path = ', url.path)\nprint('url.params = ', url.params)\nprint('url.query = ', url.query)\nprint('url.fragment = ', url.fragment)\nprint('url.username = ', url.username)\nprint('url.password = ', url.password)\n", "C#": "using System;\n\nnamespace RosettaUrlParse\n{\n    class Program\n    {\n        static void ParseUrl(string url)\n        {\n            var u = new Uri(url);\n            Console.WriteLine(\"URL:         {0}\", u.AbsoluteUri);\n            Console.WriteLine(\"Scheme:      {0}\", u.Scheme);\n            Console.WriteLine(\"Host:        {0}\", u.DnsSafeHost);\n            Console.WriteLine(\"Port:        {0}\", u.Port);\n            Console.WriteLine(\"Path:        {0}\", u.LocalPath);\n            Console.WriteLine(\"Query:       {0}\", u.Query);\n            Console.WriteLine(\"Fragment:    {0}\", u.Fragment);\n            Console.WriteLine();\n        }\n        static void Main(string[] args)\n        {\n            ParseUrl(\"foo:\n            ParseUrl(\"urn:example:animal:ferret:nose\");\n            ParseUrl(\"jdbc:mysql:\n            ParseUrl(\"ftp:\n            ParseUrl(\"http:\n            ParseUrl(\"ldap:\n            ParseUrl(\"mailto:John.Doe@example.com\");\n            ParseUrl(\"news:comp.infosystems.www.servers.unix\");\n            ParseUrl(\"tel:+1-816-555-1212\");\n            ParseUrl(\"telnet:\n            ParseUrl(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\");\n        }\n    }\n}\n"}
{"id": 60155, "name": "Idoneal numbers", "Python": "\n\n\ndef is_idoneal(num):\n    \n    for a in range(1, num):\n        for b in range(a + 1, num):\n            if a * b + a + b > num:\n                break\n            for c in range(b + 1, num):\n                sum3 = a * b + b * c + a * c\n                if sum3 == num:\n                    return False\n                if sum3 > num:\n                    break\n    return True\n\n\nrow = 0\nfor n in range(1, 2000):\n    if is_idoneal(n):\n        row += 1\n        print(f'{n:5}', end='\\n' if row % 13 == 0 else '')\n", "C#": "using System;\n\nclass Program {\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int a, b, c, i, n, s3, ab; var res = new int[65];\n    for (n = 1, i = 0; n < 1850; n++) {\n      bool found = true;\n      for (a = 1; a < n; a++)\n         for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {\n            if (ab > n) break;\n            for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {\n                if (s3 == n) found = false;\n                if (s3 >= n) break;\n            }\n         }\n      if (found) res[i++] = n;\n    }\n    sw.Stop();\n    Console.WriteLine(\"The 65 known Idoneal numbers:\");\n    for (i = 0; i < res.Length; i++)\n      Console.Write(\"{0,5}{1}\", res[i], i % 13 == 12 ? \"\\n\" : \"\");\n    Console.Write(\"Calculations took {0} ms\", sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 60156, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 60157, "name": "Base58Check encoding", "Python": "ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef convertToBase58(num):\n    sb = ''\n    while (num > 0):\n        r = num % 58\n        sb = sb + ALPHABET[r]\n        num = num // 58;\n    return sb[::-1]\n\ns = 25420294593250030202636073700053352635053786165627414518\nb = convertToBase58(s)\nprint(\"%-56d -> %s\" % (s, b))\n\nhash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]\nfor num in hash_arr:\n    b = convertToBase58(num)\n    print(\"0x%-54x -> %s\" % (num, b))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Numerics;\nusing System.Text;\n\nnamespace Base58CheckEncoding {\n    class Program {\n        const string ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n        static BigInteger ToBigInteger(string value, int @base) {\n            const string HEX = \"0123456789ABCDEF\";\n            if (@base < 1 || @base > HEX.Length) {\n                throw new ArgumentException(\"Base is out of range.\");\n            }\n\n            BigInteger bi = BigInteger.Zero;\n            foreach (char c in value) {\n                char c2 = Char.ToUpper(c);\n                int idx = HEX.IndexOf(c2);\n                if (idx == -1 || idx >= @base) {\n                    throw new ArgumentOutOfRangeException(\"Illegal character encountered.\");\n                }\n                bi = bi * @base + idx;\n            }\n\n            return bi;\n        }\n\n        static string ConvertToBase58(string hash, int @base = 16) {\n            BigInteger x;\n            if (@base == 16 && hash.Substring(0, 2) == \"0x\") {\n                x = ToBigInteger(hash.Substring(2), @base);\n            } else {\n                x = ToBigInteger(hash, @base);\n            }\n\n            StringBuilder sb = new StringBuilder();\n            while (x > 0) {\n                BigInteger r = x % 58;\n                sb.Append(ALPHABET[(int)r]);\n                x = x / 58;\n            }\n\n            char[] ca = sb.ToString().ToCharArray();\n            Array.Reverse(ca);\n            return new string(ca);\n        }\n\n        static void Main(string[] args) {\n            string s = \"25420294593250030202636073700053352635053786165627414518\";\n            string b = ConvertToBase58(s, 10);\n            Console.WriteLine(\"{0} -> {1}\", s, b);\n\n            List<string> hashes = new List<string>() {\n                \"0x61\",\n                \"0x626262\",\n                \"0x636363\",\n                \"0x73696d706c792061206c6f6e6720737472696e67\",\n                \"0x516b6fcd0f\",\n                \"0xbf4f89001e670274dd\",\n                \"0x572e4794\",\n                \"0xecac89cad93923c02321\",\n                \"0x10c8511e\",\n            };\n            foreach (string hash in hashes) {\n                string b58 = ConvertToBase58(hash);\n                Console.WriteLine(\"{0,-56} -> {1}\", hash, b58);\n            }\n        }\n    }\n}\n"}
{"id": 60158, "name": "Dynamic variable names", "Python": ">>> name = raw_input(\"Enter a variable name: \")\nEnter a variable name: X\n>>> globals()[name] = 42\n>>> X\n42\n", "C#": "using System;\nusing System.Dynamic;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string varname = Console.ReadLine();\n        \n        dynamic expando = new ExpandoObject();\n        var map = expando as IDictionary<string, object>;\n        map.Add(varname, \"Hello world!\");\n \n        Console.WriteLine(expando.foo);\n    }\n}\n"}
{"id": 60159, "name": "Fibonacci matrix-exponentiation", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n"}
{"id": 60160, "name": "Fibonacci matrix-exponentiation", "Python": "class Head():\n    def __init__(self, lo, hi=None, shift=0):\n        if hi is None: hi = lo\n\n        d = hi - lo\n        ds, ls, hs = str(d), str(lo), str(hi)\n\n        if d and len(ls) > len(ds):\n            assert(len(ls) - len(ds) + 1 > 21)\n            lo = int(str(lo)[:len(ls) - len(ds) + 1])\n            hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1\n            shift += len(ds) - 1\n        elif len(ls) > 100:\n            lo = int(str(ls)[:100])\n            hi = lo + 1\n            shift = len(ls) - 100\n\n        self.lo, self.hi, self.shift = lo, hi, shift\n\n    def __mul__(self, other):\n        lo = self.lo*other.lo\n        hi = self.hi*other.hi\n        shift = self.shift + other.shift\n\n        return Head(lo, hi, shift)\n\n    def __add__(self, other):\n        if self.shift < other.shift:\n            return other + self\n\n        sh = self.shift - other.shift\n        if sh >= len(str(other.hi)):\n            return Head(self.lo, self.hi, self.shift)\n\n        ls = str(other.lo)\n        hs = str(other.hi)\n\n        lo = self.lo + int(ls[:len(ls)-sh])\n        hi = self.hi + int(hs[:len(hs)-sh])\n\n        return Head(lo, hi, self.shift)\n\n    def __repr__(self):\n        return str(self.hi)[:20]\n\nclass Tail():\n    def __init__(self, v):\n        self.v = int(f'{v:020d}'[-20:])\n\n    def __add__(self, other):\n        return Tail(self.v + other.v)\n\n    def __mul__(self, other):\n        return Tail(self.v*other.v)\n\n    def __repr__(self):\n        return f'{self.v:020d}'[-20:]\n        \ndef mul(a, b):\n    return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]\n\ndef fibo(n, cls):\n    n -= 1\n    zero, one = cls(0), cls(1)\n    m = (one, one, zero)\n    e = (one, zero, one)\n\n    while n:\n        if n&1: e = mul(m, e)\n        m = mul(m, m)\n        n >>= 1\n\n    return f'{e[0]}'\n\nfor i in range(2, 10):\n    n = 10**i\n    print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))\n\nfor i in range(3, 8):\n    n = 2**i\n    s = f'2^{n}'\n    print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))\n", "C#": "using System;\nusing System.IO;\nusing System.Numerics;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace Fibonacci {\n    class Program\n    {\n        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };\n        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = \"_\" };\n        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)\n        {\n            if (A.GetLength(1) != B.GetLength(0))\n            {\n                throw new ArgumentException(\"Illegal matrix dimensions for multiplication.\");\n            }\n            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < B.GetLength(1); ++j)\n                {\n                    for (int k = 0; k < A.GetLength(1); ++k)\n                    {\n                        C[i, j] +=  A[i, k] * B[k, j];\n                    }\n                }\n            }\n            return C;\n        }\n        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)\n        {\n            if (A.GetLength(1) != A.GetLength(0))\n            {\n                throw new ArgumentException(\"Not a square matrix.\");\n            }\n            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                C[i, i] = BigInteger.One;\n            }\n            if (0 == n) return C;\n            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];\n            for (int i = 0; i < A.GetLength(0); ++i)\n            {\n                for (int j = 0; j < A.GetLength(1); ++j)\n                {\n                    S[i, j] = A[i, j];\n                }\n            }\n            while (0 < n)\n            {\n                if (1 == n % 2) C = Multiply(C, S);\n                S = Multiply(S,S);\n                n /= 2;\n            }\n            return C;\n        }\n        public static BigInteger Fib(in ulong n)\n        {\n            var C = Power(F, n);\n            return C[0, 1];\n        }\n        public static void Task(in ulong p)\n        {\n            var ans = Fib(p).ToString();\n            var sp = p.ToString(\"N0\", nfi);\n            if (ans.Length <= 40)\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1}\", sp, ans);\n            }\n            else\n            {\n                Console.WriteLine(\"Fibonacci({0}) = {1} ... {2}\", sp, ans[0..19], ans[^20..]);\n            }\n        }\n        public static void Main()\n        {\n            Stopwatch stopWatch = new Stopwatch();\n            stopWatch.Start();\n            for (ulong p = 10; p <= 10_000_000; p *= 10) {\n                Task(p);\n            }\n            stopWatch.Stop();\n            TimeSpan ts = stopWatch.Elapsed;\n            string elapsedTime = String.Format(\"{0:00}:{1:00}:{2:00}.{3:00}\",\n                ts.Hours, ts.Minutes, ts.Seconds,\n                ts.Milliseconds / 10);\n            Console.WriteLine(\"Took \" + elapsedTime);\n        }\n    }\n}\n"}
{"id": 60161, "name": "Largest palindrome product", "Python": "\n\nT=[set([(0, 0)])]\n\ndef double(it):\n    for a, b in it:\n        yield a, b\n        yield b, a\n\ndef tails(n):\n    \n    if len(T)<=n:\n        l = set()\n        for i in range(10):\n            for j in range(i, 10):\n                I = i*10**(n-1)\n                J = j*10**(n-1)\n                it = tails(n-1)\n                if I!=J: it = double(it)\n                for t1, t2 in it:\n                    if ((I+t1)*(J+t2)+1)%10**n == 0:\n                        l.add((I+t1, J+t2))\n        T.append(l)\n    return T[n]\n\ndef largestPalindrome(n):\n    \n    m, tail = 0, n // 2\n    head = n - tail\n    up = 10**head\n    for L in range(1, 9*10**(head-1)+1):\n        \n        m = 0\n        sol = None\n        for i in range(1, L + 1):\n            lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)\n            hi = int(up - (up - L)**2 / (up - i))\n            for j in range(lo, hi + 1):\n                I = (up-i) * 10**tail\n                J = (up-j) * 10**tail\n                it = tails(tail)\n                if I!=J: it = double(it)\n                    for t1, t2 in it:\n                        val = (I + t1)*(J + t2)\n                        s = str(val)\n                        if s == s[::-1] and val>m:\n                            sol = (I + t1, J + t2)\n                            m = val\n\n        if m:\n            print(\"{:2d}\\t{:4d}\".format(n, m % 1337), sol, sol[0] * sol[1])\n            return m % 1337\n    return 0\n\nif __name__ == \"__main__\":\n    for k in range(1, 14):\n        largestPalindrome(k)\n", "C#": "using System;\nclass Program {\n\n  static bool isPal(int n) {\n    int rev = 0, lr = -1, rem;\n    while (n > rev) {\n      n = Math.DivRem(n, 10, out rem);\n      if (lr < 0 && rem == 0) return false;\n      lr = rev; rev = 10 * rev + rem;\n      if (n == rev || n == lr) return true;\n    } return false; }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew();\n    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;\n    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = \"\";\n    y /= 11;\n    if ((y & 1) == 0) y--;\n    if (y % 5 == 0) y -= 2;\n    y *= 11;\n    while (y <= max) {\n      c = 0;\n      y10 = y * 10;\n      z = max9 + a[ld = y % 10];\n      p = y * z;\n      while (p >= bp) {\n        if (isPal(p)) {\n          if (p > bp) bp = p;\n          bs = string.Format(\"{0} x {1} = {2}\", y, z - c, bp);\n        }\n        p -= y10; c += 10;\n      }\n      y += ld == 3 ? 44 : 22;\n    }\n    sw.Stop();\n    Console.Write(\"{0} {1} μs\", bs, sw.Elapsed.TotalMilliseconds * 1000.0);\n  }\n}\n"}
{"id": 60162, "name": "Commatizing numbers", "Python": "import re as RegEx\n\n\ndef Commatize( _string, _startPos=0, _periodLen=3, _separator=\",\" ):\n\toutString = \"\"\n\tstrPos = 0\n\tmatches = RegEx.findall( \"[0-9]*\", _string )\n\n\tfor match in matches[:-1]:\n\t\tif not match:\n\t\t\toutString += _string[ strPos ]\n\t\t\tstrPos += 1\n\t\telse:\n\t\t\tif len(match) > _periodLen:\n\t\t\t\tleadIn = match[:_startPos]\n\t\t\t\tperiods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]\n\t\t\t\toutString += leadIn + _separator.join( periods )\n\t\t\telse:\n\t\t\t\toutString += match\n\n\t\t\tstrPos += len( match )\n\n\treturn outString\n\n\n\nprint ( Commatize( \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", 0, 5, \" \" ) )\nprint ( Commatize( \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", 0, 3, \".\" ))\nprint ( Commatize( \"\\\"-in Aus$+1411.8millions\\\"\" ))\nprint ( Commatize( \"===US$0017440 millions=== (in 2000 dollars)\" ))\nprint ( Commatize( \"123.e8000 is pretty big.\" ))\nprint ( Commatize( \"The land area of the earth is 57268900(29% of the surface) square miles.\" ))\nprint ( Commatize( \"Ain't no numbers in this here words, nohow, no way, Jose.\" ))\nprint ( Commatize( \"James was never known as 0000000007\" ))\nprint ( Commatize( \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\" ))\nprint ( Commatize( \"␢␢␢$-140000±100 millions.\" ))\nprint ( Commatize( \"6/9/1946 was a good year for some.\" ))\n", "C#": "static string[] inputs = {\n\t\"pi=3.14159265358979323846264338327950288419716939937510582097494459231\",\n\t\"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\",\n\t\"\\\"-in Aus$+1411.8millions\\\"\",\n\t\"===US$0017440 millions=== (in 2000 dollars)\"\n};\n\nvoid Main()\n{\n\tinputs.Select(s => Commatize(s, 0, 3, \",\"))\n              .ToList()\n              .ForEach(Console.WriteLine);\n}\n\nstring Commatize(string text, int startPosition, int interval, string separator)\n{\n\tvar matches = Regex.Matches(text.Substring(startPosition), \"[0-9]*\");\n\tvar x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();\n\treturn string.Join(\"\", x);\n}\n\n\nstring Commatize(Match match, int interval, string separator, string original)\n{\n\tif (match.Length <= interval)\n\t\treturn original.Substring(match.Index, \n                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));\n\t\n\treturn string.Join(separator, match.Value.Split(interval));\n}\n\npublic static class Extension\n{\n\tpublic static string[] Split(this string source, int interval)\n\t{\n\t\treturn SplitImpl(source, interval).ToArray();\n\t}\n\t\n\tstatic IEnumerable<string>SplitImpl(string source, int interval)\n\t{\n\t\tfor\t(int i = 1; i < source.Length; i++)\n\t\t{\n\t\t\tif (i % interval != 0) continue;\n\t\t\t\n\t\t\tyield return source.Substring(i - interval, interval);\n\t\t}\n\t}\n}\n"}
{"id": 60163, "name": "Arithmetic coding_As a generalized change of radix", "Python": "from collections import Counter\n\ndef cumulative_freq(freq):\n    cf = {}\n    total = 0\n    for b in range(256):\n        if b in freq:\n            cf[b] = total\n            total += freq[b]\n    return cf\n\ndef arithmethic_coding(bytes, radix):\n\n    \n    freq = Counter(bytes)\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    base = len(bytes)\n\n    \n    lower = 0\n\n    \n    pf = 1\n\n    \n    \n    for b in bytes:\n        lower = lower*base + cf[b]*pf\n        pf *= freq[b]\n\n    \n    upper = lower+pf\n\n    pow = 0\n    while True:\n        pf //= radix\n        if pf==0: break\n        pow += 1\n\n    enc = (upper-1) // radix**pow\n    return enc, pow, freq\n\ndef arithmethic_decoding(enc, radix, pow, freq):\n\n    \n    enc *= radix**pow;\n\n    \n    base = sum(freq.values())\n\n    \n    cf = cumulative_freq(freq)\n\n    \n    dict = {}\n    for k,v in cf.items():\n        dict[v] = k\n\n    \n    lchar = None\n    for i in range(base):\n        if i in dict:\n            lchar = dict[i]\n        elif lchar is not None:\n            dict[i] = lchar\n\n    \n    decoded = bytearray()\n    for i in range(base-1, -1, -1):\n        pow = base**i\n        div = enc//pow\n\n        c  = dict[div]\n        fv = freq[c]\n        cv = cf[c]\n\n        rem = (enc - pow*cv) // fv\n\n        enc = rem\n        decoded.append(c)\n\n    \n    return bytes(decoded)\n\nradix = 10      \n\nfor str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():\n    enc, pow, freq = arithmethic_coding(str, radix)\n    dec = arithmethic_decoding(enc, radix, pow, freq)\n\n    print(\"%-25s=> %19s * %d^%s\" % (str, enc, radix, pow))\n\n    if str != dec:\n    \traise Exception(\"\\tHowever that is incorrect!\")\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\n\nnamespace AruthmeticCoding {\n    using Freq = Dictionary<char, long>;\n    using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;\n\n    class Program {\n        static Freq CumulativeFreq(Freq freq) {\n            long total = 0;\n            Freq cf = new Freq();\n            for (int i = 0; i < 256; i++) {\n                char c = (char)i;\n                if (freq.ContainsKey(c)) {\n                    long v = freq[c];\n                    cf[c] = total;\n                    total += v;\n                }\n            }\n            return cf;\n        }\n\n        static Triple ArithmeticCoding(string str, long radix) {\n            \n            Freq freq = new Freq();\n            foreach (char c in str) {\n                if (freq.ContainsKey(c)) {\n                    freq[c] += 1;\n                } else {\n                    freq[c] = 1;\n                }\n            }\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            BigInteger @base = str.Length;\n\n            \n            BigInteger lower = 0;\n\n            \n            BigInteger pf = 1;\n\n            \n            \n            foreach (char c in str) {\n                BigInteger x = cf[c];\n                lower = lower * @base + x * pf;\n                pf = pf * freq[c];\n            }\n\n            \n            BigInteger upper = lower + pf;\n\n            int powr = 0;\n            BigInteger bigRadix = radix;\n\n            while (true) {\n                pf = pf / bigRadix;\n                if (pf == 0) break;\n                powr++;\n            }\n\n            BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));\n            return new Triple(diff, powr, freq);\n        }\n\n        static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n            BigInteger powr = radix;\n            BigInteger enc = num * BigInteger.Pow(powr, pwr);\n            long @base = freq.Values.Sum();\n\n            \n            Freq cf = CumulativeFreq(freq);\n\n            \n            Dictionary<long, char> dict = new Dictionary<long, char>();\n            foreach (char key in cf.Keys) {\n                long value = cf[key];\n                dict[value] = key;\n            }\n\n            \n            long lchar = -1;\n            for (long i = 0; i < @base; i++) {\n                if (dict.ContainsKey(i)) {\n                    lchar = dict[i];\n                } else if (lchar != -1) {\n                    dict[i] = (char)lchar;\n                }\n            }\n\n            \n            StringBuilder decoded = new StringBuilder((int)@base);\n            BigInteger bigBase = @base;\n            for (long i = @base - 1; i >= 0; --i) {\n                BigInteger pow = BigInteger.Pow(bigBase, (int)i);\n                BigInteger div = enc / pow;\n                char c = dict[(long)div];\n                BigInteger fv = freq[c];\n                BigInteger cv = cf[c];\n                BigInteger diff = enc - pow * cv;\n                enc = diff / fv;\n                decoded.Append(c);\n            }\n\n            \n            return decoded.ToString();\n        }\n\n        static void Main(string[] args) {\n            long radix = 10;\n            string[] strings = { \"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\" };\n            foreach (string str in strings) {\n                Triple encoded = ArithmeticCoding(str, radix);\n                string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);\n                Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", str, encoded.Item1, radix, encoded.Item2);\n                if (str != dec) {\n                    throw new Exception(\"\\tHowever that is incorrect!\");\n                }\n            }\n        }\n    }\n}\n"}
{"id": 60164, "name": "Kosaraju", "Python": "def kosaraju(g):\n    class nonlocal: pass\n\n    \n    size = len(g)\n\n    vis = [False]*size \n    l = [0]*size\n    nonlocal.x = size\n    t = [[]]*size   \n\n    def visit(u):\n        if not vis[u]:\n            vis[u] = True\n            for v in g[u]:\n                visit(v)\n                t[v] = t[v] + [u]\n            nonlocal.x = nonlocal.x - 1\n            l[nonlocal.x] = u\n\n    \n    for u in range(len(g)):\n        visit(u)\n    c = [0]*size\n\n    def assign(u, root):\n        if vis[u]:\n            vis[u] = False\n            c[u] = root\n            for v in t[u]:\n                assign(v, root)\n\n    \n    for u in l:\n        assign(u, u)\n\n    return c\n\ng = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]\nprint kosaraju(g)\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Node\n{\n\tpublic enum Colors\n\t{\n\t\tBlack, White, Gray\n\t}\n\n\tpublic Colors color { get; set; }\n\tpublic int N { get; }\n\t\n\tpublic Node(int n)\n\t{\n\t\tN = n;\n\t\tcolor = Colors.White;\n\t}\n}\n\nclass Graph\n{\n\tpublic HashSet<Node> V { get; }\n\tpublic Dictionary<Node, HashSet<Node>> Adj { get; }\n\n\t\n\t\n\t\n\tpublic void Kosaraju()\n\t{\n\t\tvar L = new HashSet<Node>();\n\n\t\tAction<Node> Visit = null;\n\t\tVisit = (u) =>\n\t\t{\n\t\t\tif (u.color == Node.Colors.White)\n\t\t\t{\n\t\t\t\tu.color = Node.Colors.Gray;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tVisit(v);\n\n\t\t\t\tL.Add(u);\n\t\t\t}\n\t\t};\n\n\t\tAction<Node, Node> Assign = null;\n\t\tAssign = (u, root) =>\n\t\t{\n\t\t\tif (u.color != Node.Colors.Black)\n\t\t\t{\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.Write(\"SCC: \");\n\n\t\t\t\tConsole.Write(u.N + \" \");\n\t\t\t\tu.color = Node.Colors.Black;\n\n\t\t\t\tforeach (var v in Adj[u])\n\t\t\t\t\tAssign(v, root);\n\n\t\t\t\tif (u == root)\n\t\t\t\t\tConsole.WriteLine();\n\t\t\t}\n\t\t};\n\n\t\tforeach (var u in V)\n\t\t\tVisit(u);\n\n\t\tforeach (var u in L)\n\t\t\tAssign(u, u);\n\t}\n}\n"}
{"id": 60165, "name": "Reflection_List methods", "Python": "import inspect\n\n\nclass Super(object):\n  def __init__(self, name):\n    self.name = name\n  \n  def __str__(self):\n    return \"Super(%s)\" % (self.name,)\n  \n  def doSup(self):\n    return 'did super stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in sup)'\n  \n  @classmethod\n  def supCls(cls):\n    return 'Super method'\n  \n  @staticmethod\n  def supStatic():\n    return 'static method'\n\nclass Other(object):\n  def otherMethod(self):\n    return 'other method'\n\nclass Sub(Other, Super):\n  def __init__(self, name, *args):\n    super(Sub, self).__init__(name);\n    self.rest = args;\n    self.methods = {}\n  \n  def __dir__(self):\n    return list(set( \\\n        sum([dir(base) for base in type(self).__bases__], []) \\\n        + type(self).__dict__.keys() \\\n        + self.__dict__.keys() \\\n        + self.methods.keys() \\\n      ))\n  \n  def __getattr__(self, name):\n    if name in self.methods:\n      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:\n        if self.methods[name].__code__.co_varnames[0] == 'self':\n          return self.methods[name].__get__(self, type(self))\n        if self.methods[name].__code__.co_varnames[0] == 'cls':\n          return self.methods[name].__get__(type(self), type)\n      return self.methods[name]\n    raise AttributeError(\"'%s' object has no attribute '%s'\" % (type(self).__name__, name))\n  \n  def __str__(self):\n    return \"Sub(%s)\" % self.name\n  \n  def doSub():\n    return 'did sub stuff'\n  \n  @classmethod\n  def cls(cls):\n    return 'cls method (in Sub)'\n  \n  @classmethod\n  def subCls(cls):\n    return 'Sub method'\n  \n  @staticmethod\n  def subStatic():\n    return 'Sub method'\n\nsup = Super('sup')\nsub = Sub('sub', 0, 'I', 'two')\nsub.methods['incr'] = lambda x: x+1\nsub.methods['strs'] = lambda self, x: str(self) * x\n\n\n[method for method in dir(sub) if callable(getattr(sub, method))]\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]\n\n\n[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]\n\n\n\ninspect.getmembers(sub, predicate=inspect.ismethod)\n\nmap(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))\n\n", "C#": "using System;\nusing System.Reflection;\n\npublic class Rosetta\n{\n    public static void Main()\n    {\n        \n        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static\n            | BindingFlags.Public | BindingFlags.NonPublic\n            | BindingFlags.DeclaredOnly;\n\n        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))\n            Console.WriteLine(method);\n    }\n    \n    class TestForMethodReflection\n    {\n        public void MyPublicMethod() {}\n        private void MyPrivateMethod() {}\n        \n        public static void MyPublicStaticMethod() {}\n        private static void MyPrivateStaticMethod() {}\n    }\n    \n}\n"}
{"id": 60166, "name": "Comments", "Python": "\n\nvar x = 0 \n\nvar y = 0 \n\n\nThere are also multi-line comments\nEverything inside of \n]\n\n\n\ndiscard \n", "C#": "\n\n\n\n\n\n"}
{"id": 60167, "name": "Pentomino tiling", "Python": "from itertools import product\n\nminos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),\n        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),\n        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),\n        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),\n        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),\n        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),\n        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),\n        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),\n        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),\n        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),\n        ((4311810305, 8, 4), (31, 4, 8)),\n        ((132866, 6, 6),))\n\nboxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'\nboxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]\n\n\npatterns = boxchar_single_width\n\ntiles = []\nfor row in reversed(minos):\n    tiles.append([])\n    for n, x, y in row:\n        for shift in (b*8 + a for a, b in product(range(x), range(y))):\n            tiles[-1].append(n << shift)\n\ndef img(seq):\n    b = [[0]*10 for _ in range(10)]\n\n    for i, s in enumerate(seq):\n        for j, k in product(range(8), range(8)):\n            if s & (1<<(j*8 + k)):\n                b[j + 1][k + 1] = i + 1\n\n    idices = [[0]*9 for _ in range(9)]\n    for i, j in product(range(9), range(9)):\n        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])\n        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))\n\n    return '\\n'.join(''.join(patterns[i] for i in row) for row in idices)\n\ndef tile(board=0, seq=tuple(), tiles=tiles):\n    if not tiles:\n        yield img(seq)\n        return\n\n    for c in tiles[0]:\n        b = board | c\n\n        tnext = [] \n        for t in tiles[1:]:\n            tnext.append(tuple(n for n in t if not n&b))\n            if not tnext[-1]: break \n        else:\n            yield from tile(b, seq + (c,), tnext)\n\nfor x in tile():\n    print(x)\n", "C#": "using System;\nusing System.Linq;\n\nnamespace PentominoTiling\n{\n    class Program\n    {\n        static readonly char[] symbols = \"FILNPTUVWXYZ-\".ToCharArray();\n\n        static readonly int nRows = 8;\n        static readonly int nCols = 8;\n        static readonly int target = 12;\n        static readonly int blank = 12;\n\n        static int[][] grid = new int[nRows][];\n        static bool[] placed = new bool[target];\n\n        static void Main(string[] args)\n        {\n            var rand = new Random();\n\n            for (int r = 0; r < nRows; r++)\n                grid[r] = Enumerable.Repeat(-1, nCols).ToArray();\n\n            for (int i = 0; i < 4; i++)\n            {\n                int randRow, randCol;\n                do\n                {\n                    randRow = rand.Next(nRows);\n                    randCol = rand.Next(nCols);\n                } \n                while (grid[randRow][randCol] == blank);\n\n                grid[randRow][randCol] = blank;\n            }\n\n            if (Solve(0, 0))\n            {\n                PrintResult();\n            }\n            else\n            {\n                Console.WriteLine(\"no solution\");\n            }\n\n            Console.ReadKey();\n        }\n\n        private static void PrintResult()\n        {\n            foreach (int[] r in grid)\n            {\n                foreach (int i in r)\n                    Console.Write(\"{0} \", symbols[i]);\n                Console.WriteLine();\n            }\n        }\n\n        private static bool Solve(int pos, int numPlaced)\n        {\n            if (numPlaced == target)\n                return true;\n\n            int row = pos / nCols;\n            int col = pos % nCols;\n\n            if (grid[row][col] != -1)\n                return Solve(pos + 1, numPlaced);\n\n            for (int i = 0; i < shapes.Length; i++)\n            {\n                if (!placed[i])\n                {\n                    foreach (int[] orientation in shapes[i])\n                    {\n                        if (!TryPlaceOrientation(orientation, row, col, i))\n                            continue;\n\n                        placed[i] = true;\n\n                        if (Solve(pos + 1, numPlaced + 1))\n                            return true;\n\n                        RemoveOrientation(orientation, row, col);\n                        placed[i] = false;\n                    }\n                }\n            }\n            return false;\n        }\n\n        private static void RemoveOrientation(int[] orientation, int row, int col)\n        {\n            grid[row][col] = -1;\n            for (int i = 0; i < orientation.Length; i += 2)\n                grid[row + orientation[i]][col + orientation[i + 1]] = -1;\n        }\n\n        private static bool TryPlaceOrientation(int[] orientation, int row, int col, int shapeIndex)\n        {\n            for (int i = 0; i < orientation.Length; i += 2)\n            {\n                int x = col + orientation[i + 1];\n                int y = row + orientation[i];\n                if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                    return false;\n            }\n\n            grid[row][col] = shapeIndex;\n            for (int i = 0; i < orientation.Length; i += 2)\n                grid[row + orientation[i]][col + orientation[i + 1]] = shapeIndex;\n\n            return true;\n        }\n\n        \n        static readonly int[][] F = {\n            new int[] {1, -1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 2, 0},\n            new int[] {1, 0, 1, 1, 1, 2, 2, 1}, new int[] {1, 0, 1, 1, 2, -1, 2, 0},\n            new int[] {1, -2, 1, -1, 1, 0, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 1},\n            new int[] {1, -1, 1, 0, 1, 1, 2, -1}, new int[] {1, -1, 1, 0, 2, 0, 2, 1}};\n\n        static readonly int[][] I = {\n            new int[] { 0, 1, 0, 2, 0, 3, 0, 4 }, new int[] { 1, 0, 2, 0, 3, 0, 4, 0 } };\n\n        static readonly int[][] L = {\n            new int[] {1, 0, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, 0, 3, -1, 3, 0},\n            new int[] {0, 1, 0, 2, 0, 3, 1, 3}, new int[] {0, 1, 1, 0, 2, 0, 3, 0},\n            new int[] {0, 1, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 0, 3, 1, 0},\n            new int[] {1, 0, 2, 0, 3, 0, 3, 1}, new int[] {1, -3, 1, -2, 1, -1, 1, 0}};\n\n        static readonly int[][] N = {\n            new int[] {0, 1, 1, -2, 1, -1, 1, 0}, new int[] {1, 0, 1, 1, 2, 1, 3, 1},\n            new int[]  {0, 1, 0, 2, 1, -1, 1, 0}, new int[] {1, 0, 2, 0, 2, 1, 3, 1},\n            new int[] {0, 1, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, -1, 2, 0, 3, -1},\n            new int[] {0, 1, 0, 2, 1, 2, 1, 3}, new int[] {1, -1, 1, 0, 2, -1, 3, -1}};\n\n        static readonly int[][] P = {\n            new int[] {0, 1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 0, 2, 1, 0, 1, 1},\n            new int[] {1, 0, 1, 1, 2, 0, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 1, 1},\n            new int[] {0, 1, 1, 0, 1, 1, 1, 2}, new int[] {1, -1, 1, 0, 2, -1, 2, 0},\n            new int[] {0, 1, 0, 2, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 1, 1, 2, 0}};\n\n        static readonly int[][] T = {\n            new int[] {0, 1, 0, 2, 1, 1, 2, 1}, new int[] {1, -2, 1, -1, 1, 0, 2, 0},\n            new int[] {1, 0, 2, -1, 2, 0, 2, 1}, new int[] {1, 0, 1, 1, 1, 2, 2, 0}};\n\n        static readonly int[][] U = {\n            new int[] {0, 1, 0, 2, 1, 0, 1, 2}, new int[] {0, 1, 1, 1, 2, 0, 2, 1},\n            new int[]  {0, 2, 1, 0, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 2, 0, 2, 1}};\n\n        static readonly int[][] V = {\n            new int[] {1, 0, 2, 0, 2, 1, 2, 2}, new int[] {0, 1, 0, 2, 1, 0, 2, 0},\n            new int[] {1, 0, 2, -2, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 2, 2, 2}};\n\n        static readonly int[][] W = {\n            new int[] {1, 0, 1, 1, 2, 1, 2, 2}, new int[] {1, -1, 1, 0, 2, -2, 2, -1},\n            new int[] {0, 1, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, -1, 1, 0, 2, -1}};\n\n        static readonly int[][] X = { new int[] { 1, -1, 1, 0, 1, 1, 2, 0 } };\n\n        static readonly int[][] Y = {\n            new int[] {1, -2, 1, -1, 1, 0, 1, 1}, new int[] {1, -1, 1, 0, 2, 0, 3, 0},\n            new int[] {0, 1, 0, 2, 0, 3, 1, 1}, new int[] {1, 0, 2, 0, 2, 1, 3, 0},\n            new int[] {0, 1, 0, 2, 0, 3, 1, 2}, new int[] {1, 0, 1, 1, 2, 0, 3, 0},\n            new int[] {1, -1, 1, 0, 1, 1, 1, 2}, new int[] {1, 0, 2, -1, 2, 0, 3, 0}};\n\n        static readonly int[][] Z = {\n            new int[] {0, 1, 1, 0, 2, -1, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 2},\n            new int[] {0, 1, 1, 1, 2, 1, 2, 2}, new int[] {1, -2, 1, -1, 1, 0, 2, -2}};\n\n        static readonly int[][][] shapes = { F, I, L, N, P, T, U, V, W, X, Y, Z };\n    }\n}\n"}
{"id": 60168, "name": "Send an unknown method call", "Python": "class Example(object):\n     def foo(self, x):\n             return 42 + x\n\nname = \"foo\"\ngetattr(Example(), name)(5)      \n", "C#": "using System;\n\nclass Example\n{\n    public int foo(int x)\n    {\n        return 42 + x;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var example = new Example();\n        var method = \"foo\";\n        \n        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });\n        Console.WriteLine(\"{0}(5) = {1}\", method, result);\n    }\n}\n"}
{"id": 60169, "name": "Variables", "Python": "\nexample1 = 3\nexample2 = 3.0\nexample3 = True\nexample4 = \"hello\"\n\n\nexample1 = \"goodbye\"\n", "C#": "int j;\n"}
{"id": 60170, "name": "Sieve of Pritchard", "Python": "\n\nfrom numpy import ndarray\nfrom math import isqrt\n\n\ndef pritchard(limit):\n    \n    members = ndarray(limit + 1, dtype=bool)\n    members.fill(False)\n    members[1] = True\n    steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2\n    primes = []\n    while prime <= rtlim:\n        if steplength < limit:\n            for w in range(1, len(members)):\n                if members[w]:\n                    n = w + steplength\n                    while n <= nlimit:\n                        members[n] = True\n                        n += steplength\n            steplength = nlimit\n\n        np = 5\n        mcpy = members.copy()\n        for w in range(1, len(members)):\n            if mcpy[w]:\n                if np == 5 and w > prime:\n                    np = w\n                n = prime * w\n                if n > nlimit:\n                    break  \n                members[n] = False  \n\n        if np < prime:\n            break\n        primes.append(prime)\n        prime = 3 if prime == 2 else np\n        nlimit = min(steplength * prime, limit)  \n\n    newprimes = [i for i in range(2, len(members)) if members[i]]\n    return sorted(primes + newprimes)\n\n\nprint(pritchard(150))\nprint('Number of primes up to 1,000,000:', len(pritchard(1000000)))\n", "C#": "using System;\nusing System.Collections.Generic;\n\nclass Program {\n\n    \n    static List<int> PrimesUpTo(int limit, bool verbose = false) {\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        var members = new SortedSet<int>{ 1 };\n        int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1;\n        List<int> primes = new List<int>(), tl = new List<int>();\n        while (prime < rtlim) {\n            nl = Math.Min(prime * stp, limit);\n            if (stp < limit) {\n                tl.Clear(); \n                foreach (var w in members)\n                    for (n = w + stp; n <= nl; n += stp) tl.Add(n);\n                members.UnionWith(tl); ac += tl.Count;\n            }\n            stp = nl; \n            nxtpr = 5; \n            tl.Clear();\n            foreach (var w in members) {\n                if (nxtpr == 5 && w > prime) nxtpr = w;\n                if ((n = prime * w) > nl) break; else tl.Add(n);\n            }\n            foreach (var itm in tl) members.Remove(itm); rc += tl.Count;\n            primes.Add(prime);\n            prime = prime == 2 ? 3 : nxtpr;\n        }\n        members.Remove(1); primes.AddRange(members); sw.Stop();\n        if (verbose) Console.WriteLine(\"Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms\", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds);\n        return primes;\n    }\n\n    static void Main(string[] args) {\n        Console.WriteLine(\"[{0}]\", string.Join(\", \", PrimesUpTo(150, true)));\n        PrimesUpTo(1000000, true);\n    }\n}\n"}
{"id": 60171, "name": "Particle swarm optimization", "Python": "import math\nimport random\n\nINFINITY = 1 << 127\nMAX_INT = 1 << 31\n\nclass Parameters:\n    def __init__(self, omega, phip, phig):\n        self.omega = omega\n        self.phip = phip\n        self.phig = phig\n\nclass State:\n    def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):\n        self.iter = iter\n        self.gbpos = gbpos\n        self.gbval = gbval\n        self.min = min\n        self.max = max\n        self.parameters = parameters\n        self.pos = pos\n        self.vel = vel\n        self.bpos = bpos\n        self.bval = bval\n        self.nParticles = nParticles\n        self.nDims = nDims\n\n    def report(self, testfunc):\n        print \"Test Function :\", testfunc\n        print \"Iterations    :\", self.iter\n        print \"Global Best Position :\", self.gbpos\n        print \"Global Best Value    : %.16f\" % self.gbval\n\ndef uniform01():\n    v = random.random()\n    assert 0.0 <= v and v < 1.0\n    return v\n\ndef psoInit(min, max, parameters, nParticles):\n    nDims = len(min)\n    pos = [min[:]] * nParticles\n    vel = [[0.0] * nDims] * nParticles\n    bpos = [min[:]] * nParticles\n    bval = [INFINITY] * nParticles\n    iter = 0\n    gbpos = [INFINITY] * nDims\n    gbval = INFINITY\n    return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n\ndef pso(fn, y):\n    p = y.parameters\n    v = [0.0] * (y.nParticles)\n    bpos = [y.min[:]] * (y.nParticles)\n    bval = [0.0] * (y.nParticles)\n    gbpos = [0.0] * (y.nDims)\n    gbval = INFINITY\n    for j in xrange(0, y.nParticles):\n        \n        v[j] = fn(y.pos[j])\n        \n        if v[j] < y.bval[j]:\n            bpos[j] = y.pos[j][:]\n            bval[j] = v[j]\n        else:\n            bpos[j] = y.bpos[j][:]\n            bval[j] = y.bval[j]\n        if bval[j] < gbval:\n            gbval = bval[j]\n            gbpos = bpos[j][:]\n    rg = uniform01()\n    pos = [[None] * (y.nDims)] * (y.nParticles)\n    vel = [[None] * (y.nDims)] * (y.nParticles)\n    for j in xrange(0, y.nParticles):\n        \n        rp = uniform01()\n        ok = True\n        vel[j] = [0.0] * (len(vel[j]))\n        pos[j] = [0.0] * (len(pos[j]))\n        for k in xrange(0, y.nDims):\n            vel[j][k] = p.omega * y.vel[j][k] \\\n                      + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \\\n                      + p.phig * rg * (gbpos[k] - y.pos[j][k])\n            pos[j][k] = y.pos[j][k] + vel[j][k]\n            ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]\n        if not ok:\n            for k in xrange(0, y.nDims):\n                pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()\n    iter = 1 + y.iter\n    return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n\ndef iterate(fn, n, y):\n    r = y\n    old = y\n    if n == MAX_INT:\n        while True:\n            r = pso(fn, r)\n            if r == old:\n                break\n            old = r\n    else:\n        for _ in xrange(0, n):\n            r = pso(fn, r)\n    return r\n\ndef mccormick(x):\n    (a, b) = x\n    return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a\n\ndef michalewicz(x):\n    m = 10\n    d = len(x)\n    sum = 0.0\n    for i in xrange(1, d):\n        j = x[i - 1]\n        k = math.sin(i * j * j / math.pi)\n        sum += math.sin(j) * k ** (2.0 * m)\n    return -sum\n\ndef main():\n    state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)\n    state = iterate(mccormick, 40, state)\n    state.report(\"McCormick\")\n    print \"f(-.54719, -1.54719) : %.16f\" % (mccormick([-.54719, -1.54719]))\n\n    print\n\n    state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)\n    state = iterate(michalewicz, 30, state)\n    state.report(\"Michalewicz (2D)\")\n    print \"f(2.20, 1.57)        : %.16f\" % (michalewicz([2.2, 1.57]))\n\nmain()\n", "C#": "using System;\n\nnamespace ParticleSwarmOptimization {\n    public struct Parameters {\n        public double omega, phip, phig;\n\n        public Parameters(double omega, double phip, double phig) : this() {\n            this.omega = omega;\n            this.phip = phip;\n            this.phig = phig;\n        }\n    }\n\n    public struct State {\n        public int iter;\n        public double[] gbpos;\n        public double gbval;\n        public double[] min;\n        public double[] max;\n        public Parameters parameters;\n        public double[][] pos;\n        public double[][] vel;\n        public double[][] bpos;\n        public double[] bval;\n        public int nParticles;\n        public int nDims;\n\n        public State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) : this() {\n            this.iter = iter;\n            this.gbpos = gbpos;\n            this.gbval = gbval;\n            this.min = min;\n            this.max = max;\n            this.parameters = parameters;\n            this.pos = pos;\n            this.vel = vel;\n            this.bpos = bpos;\n            this.bval = bval;\n            this.nParticles = nParticles;\n            this.nDims = nDims;\n        }\n\n        public void Report(string testfunc) {\n            Console.WriteLine(\"Test Function        : {0}\", testfunc);\n            Console.WriteLine(\"Iterations           : {0}\", iter);\n            Console.WriteLine(\"Global Best Position : {0}\", string.Join(\", \", gbpos));\n            Console.WriteLine(\"Global Best Value    : {0}\", gbval);\n        }\n    }\n\n    class Program {\n        public static State PsoInit(double[] min, double[] max, Parameters parameters, int nParticles) {\n            var nDims = min.Length;\n            double[][] pos = new double[nParticles][];\n            for (int i = 0; i < nParticles; i++) {\n                pos[i] = new double[min.Length];\n                min.CopyTo(pos[i], 0);\n            }\n            double[][] vel = new double[nParticles][];\n            for (int i = 0; i < nParticles; i++) {\n                vel[i] = new double[nDims];\n            }\n            double[][] bpos = new double[nParticles][];\n            for (int i = 0; i < nParticles; i++) {\n                bpos[i] = new double[min.Length];\n                min.CopyTo(bpos[i], 0);\n            }\n            double[] bval = new double[nParticles];\n            for (int i = 0; i < nParticles; i++) {\n                bval[i] = double.PositiveInfinity;\n            }\n            int iter = 0;\n            double[] gbpos = new double[nDims];\n            for (int i = 0; i < nDims; i++) {\n                gbpos[i] = double.PositiveInfinity;\n            }\n            double gbval = double.PositiveInfinity;\n\n            return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);\n        }\n\n        static Random r = new Random();\n\n        public static State Pso(Func<double[], double> fn, State y) {\n            var p = y.parameters;\n            double[] v = new double[y.nParticles];\n            double[][] bpos = new double[y.nParticles][];\n            for (int i = 0; i < y.nParticles; i++) {\n                bpos[i] = new double[y.min.Length];\n                y.min.CopyTo(bpos[i], 0);\n            }\n            double[] bval = new double[y.nParticles];\n            double[] gbpos = new double[y.nDims];\n            double gbval = double.PositiveInfinity;\n            for (int j = 0; j < y.nParticles; j++) {\n                \n                v[j] = fn.Invoke(y.pos[j]);\n                \n                if (v[j] < y.bval[j]) {\n                    y.pos[j].CopyTo(bpos[j], 0);\n                    bval[j] = v[j];\n                }\n                else {\n                    y.bpos[j].CopyTo(bpos[j], 0);\n                    bval[j] = y.bval[j];\n                }\n                if (bval[j] < gbval) {\n                    gbval = bval[j];\n                    bpos[j].CopyTo(gbpos, 0);\n                }\n            }\n            double rg = r.NextDouble();\n            double[][] pos = new double[y.nParticles][];\n            double[][] vel = new double[y.nParticles][];\n            for (int i = 0; i < y.nParticles; i++) {\n                pos[i] = new double[y.nDims];\n                vel[i] = new double[y.nDims];\n            }\n            for (int j = 0; j < y.nParticles; j++) {\n                \n                double rp = r.NextDouble();\n                bool ok = true;\n                for (int k = 0; k < y.nDims; k++) {\n                    vel[j][k] = 0.0;\n                    pos[j][k] = 0.0;\n                }\n                for (int k = 0; k < y.nDims; k++) {\n                    vel[j][k] = p.omega * y.vel[j][k] +\n                                p.phip * rp * (bpos[j][k] - y.pos[j][k]) +\n                                p.phig * rg * (gbpos[k] - y.pos[j][k]);\n                    pos[j][k] = y.pos[j][k] + vel[j][k];\n                    ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];\n                }\n                if (!ok) {\n                    for (int k = 0; k < y.nDims; k++) {\n                        pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.NextDouble();\n                    }\n                }\n            }\n            var iter = 1 + y.iter;\n            return new State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);\n        }\n\n        public static State Iterate(Func<double[], double> fn, int n, State y) {\n            State r = y;\n            if (n == int.MaxValue) {\n                State old = y;\n                while (true) {\n                    r = Pso(fn, r);\n                    if (r.Equals(old)) break;\n                    old = r;\n                }\n            }\n            else {\n                for (int i = 0; i < n; i++) {\n                    r = Pso(fn, r);\n                }\n            }\n            return r;\n        }\n\n        public static double Mccormick(double[] x) {\n            var a = x[0];\n            var b = x[1];\n            return Math.Sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;\n        }\n\n        public static double Michalewicz(double[] x) {\n            int m = 10;\n            int d = x.Length;\n            double sum = 0.0;\n            for (int i = 1; i < d; i++) {\n                var j = x[i - 1];\n                var k = Math.Sin(i * j * j / Math.PI);\n                sum += Math.Sin(j) * Math.Pow(k, 2.0 * m);\n            }\n            return -sum;\n        }\n\n        static void Main(string[] args) {\n            var state = PsoInit(\n                new double[] { -1.5, -3.0 },\n                new double[] { 4.0, 4.0 },\n                new Parameters(0.0, 0.6, 0.3),\n                100\n                );\n            state = Iterate(Mccormick, 40, state);\n            state.Report(\"McCormick\");\n            Console.WriteLine(\"f(-.54719, -1.54719) : {0}\", Mccormick(new double[] { -.54719, -1.54719 }));\n            Console.WriteLine();\n\n            state = PsoInit(\n                new double[] { -0.0, -0.0 },\n                new double[] { Math.PI, Math.PI },\n                new Parameters(0.3, 0.3, 0.3),\n                1000\n                );\n            state = Iterate(Michalewicz, 30, state);\n            state.Report(\"Michalewicz (2D)\");\n            Console.WriteLine(\"f(2.20, 1.57)        : {0}\", Michalewicz(new double[] { 2.20, 1.57 }));\n        }\n    }\n}\n"}
{"id": 60172, "name": "Twelve statements", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n"}
{"id": 60173, "name": "Twelve statements", "Python": "from itertools import product\n\n\nconstraintinfo = (  \n  (lambda st: len(st) == 12                 ,(1, 'This is a numbered list of twelve statements')),\n  (lambda st: sum(st[-6:]) == 3             ,(2, 'Exactly 3 of the last 6 statements are true')),\n  (lambda st: sum(st[1::2]) == 2            ,(3, 'Exactly 2 of the even-numbered statements are true')),\n  (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),\n  (lambda st: sum(st[1:4]) == 0             ,(5, 'The 3 preceding statements are all false')),\n  (lambda st: sum(st[0::2]) == 4            ,(6, 'Exactly 4 of the odd-numbered statements are true')),\n  (lambda st: sum(st[1:3]) == 1             ,(7, 'Either statement 2 or 3 is true, but not both')),\n  (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),\n  (lambda st: sum(st[:6]) == 3              ,(9, 'Exactly 3 of the first 6 statements are true')),\n  (lambda st: (st[10]&st[11])               ,(10, 'The next two statements are both true')),\n  (lambda st: sum(st[6:9]) == 1             ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),\n  (lambda st: sum(st[0:11]) == 4            ,(12, 'Exactly 4 of the preceding statements are true')),\n)  \n\ndef printer(st, matches):\n    if False in matches:\n        print('Missed by one statement: %i, %s' % docs[matches.index(False)])\n    else:\n        print('Full match:')\n    print('  ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))\n\nfuncs, docs = zip(*constraintinfo)\n\nfull, partial = [], []\n\nfor st in product( *([(False, True)] * 12) ):\n    truths = [bool(func(st)) for func in funcs]\n    matches = [s == t for s,t in zip(st, truths)]\n    mcount = sum(matches)\n    if mcount == 12:\n        full.append((st, matches))\n    elif mcount == 11:\n        partial.append((st, matches))\n\nfor stm in full + partial:\n    printer(*stm)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n    \npublic static class TwelveStatements\n{\n    public static void Main() {\n        Func<Statements, bool>[] checks = {\n            st => st[1],\n            st => st[2] == (7.To(12).Count(i => st[i]) == 3),\n            st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),\n            st => st[4] == st[5].Implies(st[6] && st[7]),\n            st => st[5] == (!st[2] && !st[3] && !st[4]),\n            st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),\n            st => st[7] == (st[2] != st[3]),\n            st => st[8] == st[7].Implies(st[5] && st[6]),\n            st => st[9] == (1.To(6).Count(i => st[i]) == 3),\n            st => st[10] == (st[11] && st[12]),\n            st => st[11] == (7.To(9).Count(i => st[i]) == 1),\n            st => st[12] == (1.To(11).Count(i => st[i]) == 4)\n        };\n        \n        for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {\n            int count = 0;\n            int falseIndex = 0;\n            for (int i = 0; i < checks.Length; i++) {\n                if (checks[i](statements)) count++;\n                else falseIndex = i;\n            }\n            if (count == 0) Console.WriteLine($\"{\"All wrong:\", -13}{statements}\");\n            else if (count == 11) Console.WriteLine($\"{$\"Wrong at {falseIndex + 1}:\", -13}{statements}\");\n            else if (count == 12) Console.WriteLine($\"{\"All correct:\", -13}{statements}\");\n        }\n    }\n    \n    struct Statements\n    {    \n        public Statements(int value) : this() { Value = value; }\n        \n        public int Value { get; }\n                \n        public bool this[int index] => (Value & (1 << index - 1)) != 0;\n        \n        public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);\n        \n        public override string ToString() {\n            Statements copy = this; \n            return string.Join(\" \", from i in 1.To(12) select copy[i] ? \"T\" : \"F\");\n        }\n        \n    }\n    \n    \n    static bool Implies(this bool x, bool y) => !x || y;\n    \n    static IEnumerable<int> To(this int start, int end, int by = 1) {\n        while (start <= end) {\n            yield return start;\n            start += by;\n        }\n    }\n\n}\n"}
{"id": 60174, "name": "Add a variable to a class instance at runtime", "Python": "class empty(object):\n    pass\ne = empty()\n", "C#": "\n\n\n\n\n\n\n\nusing System;\nusing System.Dynamic;\n\nnamespace DynamicClassVariable\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            \n            \n            dynamic sampleObj = new ExpandoObject();\n            \n            sampleObj.bar = 1;\n            Console.WriteLine( \"sampleObj.bar = {0}\", sampleObj.bar );\n\n            \n            \n            \n            \n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 60175, "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": 60176, "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", "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": 60177, "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", "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": 60178, "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", "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": 60179, "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", "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": 60180, "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", "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": 60181, "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", "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": 60182, "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", "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": 60183, "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", "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": 60184, "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", "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": 60185, "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", "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": 60186, "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", "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": 60187, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 60188, "name": "Integer sequence", "VB": "    For i As Integer = 0 To Integer.MaxValue\n      Console.WriteLine(i)\n    Next\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": 60189, "name": "DNS query", "VB": "Function dns_query(url,ver)\n\tSet r = New RegExp\n\tr.Pattern = \"Pinging.+?\\[(.+?)\\].+\"\n\tSet objshell = CreateObject(\"WScript.Shell\")\n\tSet objexec = objshell.Exec(\"%comspec% /c \" & \"ping -\" & ver & \" \" & url)\n\tWScript.StdOut.WriteLine \"URL: \" & url\n\tDo Until objexec.StdOut.AtEndOfStream\n\t\tline = objexec.StdOut.ReadLine\n\t\tIf r.Test(line) Then\n\t\t\tWScript.StdOut.WriteLine \"IP Version \" &_\n\t\t\t\tver & \": \" & r.Replace(line,\"$1\")\n\t\tEnd If\n\tLoop\nEnd Function\n\nCall dns_query(WScript.Arguments(0),WScript.Arguments(1))\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": 60190, "name": "Peano curve", "VB": "Const WIDTH = 243 \nDim n As Long\nDim points() As Single\nDim flag As Boolean\n\n\n\n\n\n\n\n\n\n\n\n\nPrivate Sub lineto(x As Integer, y As Integer)\n    If flag Then\n        points(n, 1) = x\n        points(n, 2) = y\n    End If\n    n = n + 1\nEnd Sub\nPrivate Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _\n    ByVal i1 As Integer, ByVal i2 As Integer)\n    If (lg = 1) Then\n        Call lineto(x * 3, y * 3)\n        Exit Sub\n    End If\n    lg = lg / 3\n    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)\n    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)\n    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)\n    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)\n    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)\n    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)\n    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)\n    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)\nEnd Sub\nSub main()\n    n = 1: flag = False\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ReDim points(1 To n - 1, 1 To 2)\n    n = 1: flag = True\n    Call Peano(0, 0, WIDTH, 0, 0) \n    ActiveSheet.Shapes.AddPolyline points \nEnd Sub\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": 60191, "name": "Seven-sided dice from five-sided dice", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; Format(ChiSquared, \"0.0000\"); \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPrivate Function Dice5() As Integer\n    Dice5 = Int(5 * Rnd + 1)\nEnd Function\nPrivate Function Dice7() As Integer\n    Dim i As Integer\n    Do\n        i = 5 * (Dice5 - 1) + Dice5\n    Loop While i > 21\n    Dice7 = i Mod 7 + 1\nEnd Function\nSub TestDice7()\n    Dim i As Long, roll As Integer\n    Dim Bins(1 To 7) As Variant\n    For i = 1 To 1000000\n        roll = Dice7\n        Bins(roll) = Bins(roll) + 1\n    Next i\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(Bins, 0.05); \"\"\"\"\nEnd Sub\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": 60192, "name": "Magnanimous numbers", "VB": "Imports System, System.Console\n\nModule Module1\n\n    Dim np As Boolean()\n\n    Sub ms(ByVal lmt As Long)\n        np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True\n        Dim n As Integer = 2, j As Integer = 1 : While n < lmt\n            If Not np(n) Then\n                Dim k As Long = CLng(n) * n\n                While k < lmt : np(CInt(k)) = True : k += n : End While\n            End If : n += j : j = 2 : End While\n    End Sub\n\n    Function is_Mag(ByVal n As Integer) As Boolean\n        Dim res, rm As Integer, p As Integer = 10\n        While n >= p\n            res = Math.DivRem(n, p, rm)\n            If np(res + rm) Then Return False\n            p = p * 10 : End While : Return True\n    End Function\n\n    Sub Main(ByVal args As String())\n        ms(100_009) : Dim mn As String = \" magnanimous numbers:\"\n        WriteLine(\"First 45{0}\", mn) : Dim l As Integer = 0, c As Integer = 0\n        While c < 400 : If is_Mag(l) Then\n            c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, \"{0,4} \", \"{0,8:n0} \"), l)\n            If c < 45 AndAlso c Mod 15 = 0 Then WriteLine()\n            If c = 240 Then WriteLine(vbLf & vbLf & \"241st through 250th{0}\", mn)\n            If c = 390 Then WriteLine(vbLf & vbLf & \"391st through 400th{0}\", mn)\n        End If : l += 1 : End While\n    End Sub\nEnd Module\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": 60193, "name": "Extensible prime generator", "VB": "Option Explicit\n\nSub Main()\nDim Primes() As Long, n As Long, temp$\nDim t As Single\n    t = Timer\n    \n    n = 133218295 \n    Primes = ListPrimes(n)\n    Debug.Print \"For N = \" & Format(n, \"#,##0\") & \", execution time : \" & _\n        Format(Timer - t, \"0.000 s\") & \", \" & _\n        Format(UBound(Primes) + 1, \"#,##0\") & \" primes numbers.\"\n    \n    \n    For n = 0 To 19\n        temp = temp & \", \" & Primes(n)\n    Next\n    Debug.Print \"First twenty primes : \"; Mid(temp, 3)\n    \n    n = 0: temp = vbNullString\n    Do While Primes(n) < 100\n        n = n + 1\n    Loop\n    Do While Primes(n) < 150\n        temp = temp & \", \" & Primes(n)\n        n = n + 1\n    Loop\n    Debug.Print \"Primes between 100 and 150 : \" & Mid(temp, 3)\n    \n    Dim ccount As Long\n    n = 0\n    Do While Primes(n) < 7700\n        n = n + 1\n    Loop\n    Do While Primes(n) < 8000\n        ccount = ccount + 1\n        n = n + 1\n    Loop\n    Debug.Print \"Number of primes between 7,700 and 8,000 : \" & ccount\n    \n    n = 1\n    Do While n <= 100000\n        n = n * 10\n        Debug.Print \"The \" & n & \"th prime: \"; Format(Primes(n - 1), \"#,##0\")\n    Loop\n    Debug.Print \"VBA has a limit in array\n    Debug.Print \"With my computer, the limit for an array of Long is : 133 218 295\"\n    Debug.Print \"The last prime I could find is the : \" & _\n        Format(UBound(Primes), \"#,##0\") & \"th, Value : \" & _\n        Format(Primes(UBound(Primes)), \"#,##0\")\nEnd Sub\n\nFunction ListPrimes(MAX As Long) As Long()\nDim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long\n    ReDim t(2 To MAX)\n    ReDim L(MAX \\ 2)\n    s = Sqr(MAX)\n    For i = 3 To s Step 2\n        If t(i) = False Then\n            For j = i * i To MAX Step i\n                t(j) = True\n            Next\n        End If\n    Next i\n    L(0) = 2\n    For i = 3 To MAX Step 2\n        If t(i) = False Then\n            c = c + 1\n            L(c) = i\n        End If\n    Next i\n    ReDim Preserve L(c)\n    ListPrimes = L\nEnd Function\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": 60194, "name": "Create a two-dimensional array at runtime", "VB": "Module Program\n    Sub Main()\n        Console.WriteLine(\"Enter two space-delimited integers:\")\n        Dim input = Console.ReadLine().Split()\n        Dim rows = Integer.Parse(input(0))\n        Dim cols = Integer.Parse(input(1))\n\n        \n        Dim arr(rows - 1, cols - 1) As Integer\n\n        arr(0, 0) = 2\n        Console.WriteLine(arr(0, 0))\n    End Sub\nEnd Module\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": 60195, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 60196, "name": "Chinese remainder theorem", "VB": "Private Function chinese_remainder(n As Variant, a As Variant) As Variant\n    Dim p As Long, prod As Long, tot As Long\n    prod = 1: tot = 0\n    For i = 1 To UBound(n)\n        prod = prod * n(i)\n    Next i\n    Dim m As Variant\n    For i = 1 To UBound(n)\n        p = prod / n(i)\n        m = mul_inv(p, n(i))\n        If WorksheetFunction.IsText(m) Then\n            chinese_remainder = \"fail\"\n            Exit Function\n        End If\n        tot = tot + a(i) * m * p\n    Next i\n    chinese_remainder = tot Mod prod\nEnd Function\nPublic Sub re()\n    Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])\n    Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])\n    Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])\n    Debug.Print chinese_remainder([{100,23}], [{19,0}])\nEnd Sub\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": 60197, "name": "Pi", "VB": "Option Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print \n    End If\n  Next n\nEnd Sub\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": 60198, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 60199, "name": "Hofstadter Q sequence", "VB": "Public Q(100000) As Long\nPublic Sub HofstadterQ()\n    Dim n As Long, smaller As Long\n    Q(1) = 1\n    Q(2) = 1\n    For n = 3 To 100000\n        Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))\n        If Q(n) < Q(n - 1) Then smaller = smaller + 1\n    Next n\n    Debug.Print \"First ten terms:\"\n    For i = 1 To 10\n        Debug.Print Q(i);\n    Next i\n    Debug.print\n    Debug.Print \"The 1000th term is:\"; Q(1000)\n    Debug.Print \"Number of times smaller:\"; smaller\nEnd Sub\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": 60200, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 60201, "name": "Y combinator", "VB": "Private Function call_fn(f As String, n As Long) As Long\n    call_fn = Application.Run(f, f, n)\nEnd Function\n \nPrivate Function Y(f As String) As String\n    Y = f\nEnd Function\n \nPrivate Function fac(self As String, n As Long) As Long\n    If n > 1 Then\n        fac = n * call_fn(self, n - 1)\n    Else\n        fac = 1\n    End If\nEnd Function\n \nPrivate Function fib(self As String, n As Long) As Long\n    If n > 1 Then\n        fib = call_fn(self, n - 1) + call_fn(self, n - 2)\n    Else\n        fib = n\n    End If\nEnd Function\n \nPrivate Sub test(name As String)\n    Dim f As String: f = Y(name)\n    Dim i As Long\n    Debug.Print name\n    For i = 1 To 10\n        Debug.Print call_fn(f, i);\n    Next i\n    Debug.Print\nEnd Sub\n\nPublic Sub main()\n    test \"fac\"\n    test \"fib\"\nEnd Sub\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": 60202, "name": "Return multiple values", "VB": "Type Contact\n    Name As String\n    firstname As String\n    Age As Byte\nEnd Type\n\nFunction SetContact(N As String, Fn As String, A As Byte) As Contact\n    SetContact.Name = N\n    SetContact.firstname = Fn\n    SetContact.Age = A\nEnd Function\n\n\nSub Test_SetContact()\nDim Cont As Contact\n\n    Cont = SetContact(\"SMITH\", \"John\", 23)\n    Debug.Print Cont.Name & \" \" & Cont.firstname & \", \" & Cont.Age & \" years old.\"\nEnd Sub\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": 60203, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 60204, "name": "Van Eck sequence", "VB": "Imports System.Linq\nModule Module1\n    Dim h() As Integer\n    Sub sho(i As Integer)\n        Console.WriteLine(String.Join(\" \", h.Skip(i).Take(10)))\n    End Sub\n    Sub Main()\n        Dim a, b, c, d, f, g As Integer : g = 1000\n        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g\n            f = h(b) : For d = a To 0 Step -1\n                If f = h(d) Then h(c) = b - d: Exit For\n            Next : a = b : b = c : Next : sho(0) : sho(990)\n    End Sub\nEnd Module\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": 60205, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 60206, "name": "24 game", "VB": "Sub Rosetta_24game()\n\nDim Digit(4) As Integer, i As Integer, iDigitCount As Integer\nDim stUserExpression As String\nDim stFailMessage As String, stFailDigits As String\nDim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean\nDim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant\n\n\nGenerateNewDigits:\n    For i = 1 To 4\n        Digit(i) = [randbetween(1,9)]\n    Next i\n\n\nGetUserExpression:\n    bValidExpression = True\n    stFailMessage = \"\"\n    stFailDigits = \"\"\n    stUserExpression = InputBox(\"Enter a mathematical expression which results in 24, using the following digits: \" & _\n        Digit(1) & \", \" & Digit(2) & \", \" & Digit(3) & \" and \" & Digit(4), \"Rosetta Code | 24 Game\")\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To 4\n        If InStr(stUserExpression, Digit(i)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Digit(i)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = \"Your expression excluded the following required digits: \" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 1 To Len(stUserExpression)\n        If InStr(\"0123456789+-*/()\", Mid(stUserExpression, i, 1)) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid characters:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    iDigitCount = 0\n    For i = 1 To Len(stUserExpression)\n        If Not InStr(\"0123456789\", Mid(stUserExpression, i, 1)) = 0 Then\n            iDigitCount = iDigitCount + 1\n            If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then\n                bValidDigits = False\n                stFailDigits = stFailDigits & \" \" & Mid(stUserExpression, i, 1)\n            End If\n        End If\n    Next i\n    If iDigitCount > 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained more than 4 digits\" & vbCr & vbCr\n    End If\n        If iDigitCount < 4 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained less than 4 digits\" & vbCr & vbCr\n    End If\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid digits:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    bValidDigits = True\n    stFailDigits = \"\"\n    For i = 11 To 99\n        If Not InStr(stUserExpression, i) = 0 Then\n            bValidDigits = False\n            stFailDigits = stFailDigits & \" \" & i\n        End If\n    Next i\n    If bValidDigits = False Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression contained invalid numbers:\" & stFailDigits & vbCr & vbCr\n    End If\n\n\n    On Error GoTo EvalFail\n    vResult = Evaluate(stUserExpression)\n    If Not vResult = 24 Then\n        bValidExpression = False\n        stFailMessage = stFailMessage & \"Your expression did not result in 24. It returned: \" & vResult\n    End If\n\n\n    If bValidExpression = False Then\n        vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & \"Would you like to try again?\", vbCritical + vbRetryCancel, \"Rosetta Code | 24 Game | FAILED\")\n            If vTryAgain = vbRetry Then\n                vSameDigits = MsgBox(\"Do you want to use the same numbers?\", vbQuestion + vbYesNo, \"Rosetta Code | 24 Game | RETRY\")\n                If vSameDigits = vbYes Then\n                    GoTo GetUserExpression\n                Else\n                    GoTo GenerateNewDigits\n                End If\n            End If\n    Else\n        vTryAgain = MsgBox(\"You entered: \" & stUserExpression & vbCr & vbCr & \"which resulted in: \" & vResult, _\n            vbInformation + vbRetryCancel, \"Rosetta Code | 24 Game | SUCCESS\")\n        If vTryAgain = vbRetry Then\n            GoTo GenerateNewDigits\n        End If\n    End If\n    Exit Sub\nEvalFail:\n    bValidExpression = False\n    vResult = Err.Description\n    Resume\nEnd Sub\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": 60207, "name": "Loops_Continue", "VB": "For i = 1 To 10\n    Console.Write(i)\n    If i Mod 5 = 0 Then\n        Console.WriteLine()\n    Else\n        Console.Write(\", \")\n    End If\nNext\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": 60208, "name": "LU decomposition", "VB": "Option Base 1\nPrivate Function pivotize(m As Variant) As Variant\n    Dim n As Integer: n = UBound(m)\n    Dim im() As Double\n    ReDim im(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            im(i, j) = 0\n        Next j\n        im(i, i) = 1\n    Next i\n    For i = 1 To n\n        mx = Abs(m(i, i))\n        row_ = i\n        For j = i To n\n            If Abs(m(j, i)) > mx Then\n                mx = Abs(m(j, i))\n                row_ = j\n            End If\n        Next j\n        If i <> Row Then\n            For j = 1 To n\n                tmp = im(i, j)\n                im(i, j) = im(row_, j)\n                im(row_, j) = tmp\n            Next j\n        End If\n    Next i\n    pivotize = im\nEnd Function\n \nPrivate Function lu(a As Variant) As Variant\n    Dim n As Integer: n = UBound(a)\n    Dim l() As Double\n    ReDim l(n, n)\n    For i = 1 To n\n        For j = 1 To n\n            l(i, j) = 0\n        Next j\n    Next i\n    u = l\n    p = pivotize(a)\n    a2 = WorksheetFunction.MMult(p, a)\n    For j = 1 To n\n        l(j, j) = 1#\n        For i = 1 To j\n            sum1 = 0#\n            For k = 1 To i\n                sum1 = sum1 + u(k, j) * l(i, k)\n            Next k\n            u(i, j) = a2(i, j) - sum1\n        Next i\n        For i = j + 1 To n\n            sum2 = 0#\n            For k = 1 To j\n                sum2 = sum2 + u(k, j) * l(i, k)\n            Next k\n            l(i, j) = (a2(i, j) - sum2) / u(j, j)\n        Next i\n    Next j\n    Dim res(4) As Variant\n    res(1) = a\n    res(2) = l\n    res(3) = u\n    res(4) = p\n    lu = res\nEnd Function\n \nPublic Sub main()\n    \n    a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print result(i)(j, k),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\n    a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]\n    Debug.Print \"== a,l,u,p: ==\"\n    result = lu(a)\n    For i = 1 To 4\n        For j = 1 To UBound(result(1))\n            For k = 1 To UBound(result(1), 2)\n                Debug.Print Format(result(i)(j, k), \"0.#####\"),\n            Next k\n            Debug.Print\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\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": 60209, "name": "General FizzBuzz", "VB": "Option Explicit\n\nPrivate Type Choice\n    Number As Integer\n    Name As String\nEnd Type\n\nPrivate MaxNumber As Integer\n\nSub Main()\nDim U(1 To 3) As Choice, i As Integer, j As Integer, t$\n\n    MaxNumber = Application.InputBox(\"Enter the max number : \", \"Integer please\", Type:=1)\n    For i = 1 To 3\n        U(i) = UserChoice\n    Next\n    For i = 1 To MaxNumber\n        t = vbNullString\n        For j = 1 To 3\n            If i Mod U(j).Number = 0 Then t = t & U(j).Name\n        Next\n        Debug.Print IIf(t = vbNullString, i, t)\n    Next i\nEnd Sub\n\nPrivate Function UserChoice() As Choice\nDim ok As Boolean\n\n    Do While Not ok\n        UserChoice.Number = Application.InputBox(\"Enter the factors to be calculated : \", \"Integer please\", Type:=1)\n        UserChoice.Name = InputBox(\"Enter the corresponding word : \")\n        If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True\n    Loop\nEnd Function\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": 60210, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 60211, "name": "Read a specific line from a file", "VB": "Function read_line(filepath,n)\n\tSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\tSet objFile = objFSO.OpenTextFile(filepath,1)\n\tarrLines = Split(objFile.ReadAll,vbCrLf)\n\tIf UBound(arrLines) >= n-1 Then\n\t\tIf arrLines(n-1) <> \"\" Then\n\t\t\tread_line = arrLines(n-1)\n\t\tElse\n\t\t\tread_line = \"Line \" & n & \" is null.\"\n\t\tEnd If\n\tElse\n\t\tread_line = \"Line \" & n & \" does not exist.\"\n\tEnd If\n\tobjFile.Close\n\tSet objFSO = Nothing\nEnd Function\n\nWScript.Echo read_line(\"c:\\temp\\input.txt\",7)\n", "Java": "package linenbr7;\n\nimport java.io.*;\n\npublic class LineNbr7 {\n\n    public static void main(String[] args) throws Exception {\n        File f = new File(args[0]);\n        if (!f.isFile() || !f.canRead())\n            throw new IOException(\"can't read \" + args[0]);\n\n        BufferedReader br = new BufferedReader(new FileReader(f));\n        try (LineNumberReader lnr = new LineNumberReader(br)) {\n            String line = null;\n            int lnum = 0;\n            while ((line = lnr.readLine()) != null\n                    && (lnum = lnr.getLineNumber()) < 7) {\n            }\n\n            switch (lnum) {\n                case 0:\n                    System.out.println(\"the file has zero length\");\n                    break;\n                case 7:\n                    boolean empty = \"\".equals(line);\n                    System.out.println(\"line 7: \" + (empty ? \"empty\" : line));\n                    break;\n                default:\n                    System.out.println(\"the file has only \" + lnum + \" line(s)\");\n            }\n        }\n    }\n}\n"}
{"id": 60212, "name": "Variable-length quantity", "VB": "Module Module1\n\n    Function ToVlq(v As ULong) As ULong\n        Dim array(8) As Byte\n        Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray\n        buffer.CopyTo(array, 0)\n        Return BitConverter.ToUInt64(array, 0)\n    End Function\n\n    Function FromVlq(v As ULong) As ULong\n        Dim collection = BitConverter.GetBytes(v).Reverse()\n        Return FromVlqCollection(collection)\n    End Function\n\n    Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)\n        If v > Math.Pow(2, 56) Then\n            Throw New OverflowException(\"Integer exceeds max value.\")\n        End If\n\n        Dim index = 7\n        Dim significantBitReached = False\n        Dim mask = &H7FUL << (index * 7)\n        While index >= 0\n            Dim buffer = mask And v\n            If buffer > 0 OrElse significantBitReached Then\n                significantBitReached = True\n                buffer >>= index * 7\n                If index > 0 Then\n                    buffer = buffer Or &H80\n                End If\n                Yield buffer\n            End If\n            mask >>= 7\n            index -= 1\n        End While\n    End Function\n\n    Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong\n        Dim v = 0UL\n        Dim significantBitReached = False\n\n        Using enumerator = vlq.GetEnumerator\n            Dim index = 0\n            While enumerator.MoveNext\n                Dim buffer = enumerator.Current\n                If buffer > 0 OrElse significantBitReached Then\n                    significantBitReached = True\n                    v <<= 7\n                    v = v Or (buffer And &H7FUL)\n                End If\n\n                index += 1\n                If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then\n                    Exit While\n                End If\n            End While\n        End Using\n\n        Return v\n    End Function\n\n    Sub Main()\n        Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}\n        For Each original In values\n            Console.WriteLine(\"Original: 0x{0:X}\", original)\n\n            REM collection\n            Dim seq = ToVlqCollection(original)\n            Console.WriteLine(\"Sequence: 0x{0}\", seq.Select(Function(b) b.ToString(\"X2\")).Aggregate(Function(a, b) String.Concat(a, b)))\n\n            Dim decoded = FromVlqCollection(seq)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            REM ints\n            Dim encoded = ToVlq(original)\n            Console.WriteLine(\"Encoded: 0x{0:X}\", encoded)\n\n            decoded = FromVlq(encoded)\n            Console.WriteLine(\"Decoded: 0x{0:X}\", decoded)\n\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Java": "public class VLQCode\n{\n  public static byte[] encode(long n)\n  {\n    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n    int numBytes = (numRelevantBits + 6) / 7;\n    if (numBytes == 0)\n      numBytes = 1;\n    byte[] output = new byte[numBytes];\n    for (int i = numBytes - 1; i >= 0; i--)\n    {\n      int curByte = (int)(n & 0x7F);\n      if (i != (numBytes - 1))\n        curByte |= 0x80;\n      output[i] = (byte)curByte;\n      n >>>= 7;\n    }\n    return output;\n  }\n  \n  public static long decode(byte[] b)\n  {\n    long n = 0;\n    for (int i = 0; i < b.length; i++)\n    {\n      int curByte = b[i] & 0xFF;\n      n = (n << 7) | (curByte & 0x7F);\n      if ((curByte & 0x80) == 0)\n        break;\n    }\n    return n;\n  }\n  \n  public static String byteArrayToString(byte[] b)\n  {\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < b.length; i++)\n    {\n      if (i > 0)\n        sb.append(\", \");\n      String s = Integer.toHexString(b[i] & 0xFF);\n      if (s.length() < 2)\n        s = \"0\" + s;\n      sb.append(s);\n    }\n    return sb.toString();\n  }\n  \n  public static void main(String[] args)\n  {\n    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n    for (long n : testNumbers)\n    {\n      byte[] encoded = encode(n);\n      long decoded = decode(encoded);\n      System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n    }\n  }\n}\n"}
{"id": 60213, "name": "String case", "VB": "Sub Main()\nConst TESTSTRING As String = \"alphaBETA\"\nDebug.Print \"initial   =                                      \" _\n   & TESTSTRING\nDebug.Print \"uppercase =                                      \" _\n   & UCase(TESTSTRING)\nDebug.Print \"lowercase =                                      \" _\n   & LCase(TESTSTRING)\nDebug.Print \"first letter capitalized =                       \" _\n   & StrConv(TESTSTRING, vbProperCase)\nDebug.Print \"length (in characters) =                         \" _\n   & CStr(Len(TESTSTRING))\nDebug.Print \"length (in bytes) =                              \" _\n   & CStr(LenB(TESTSTRING))\nDebug.Print \"reversed =                                       \" _\n   & StrReverse(TESTSTRING)\nDebug.Print \"first position of letter A (case-sensitive) =    \" _\n   & InStr(1, TESTSTRING, \"A\", vbBinaryCompare)\nDebug.Print \"first position of letter A (case-insensitive) =  \" _\n   & InStr(1, TESTSTRING, \"A\", vbTextCompare)\nDebug.Print \"concatenated with \n   & TESTSTRING & \"123\"\nEnd Sub\n", "Java": "String str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\nSystem.out.println(\"äàâáçñßæεбế\".toUpperCase());\nSystem.out.println(\"ÄÀÂÁÇÑSSÆΕБẾ\".toLowerCase()); \n"}
{"id": 60214, "name": "Text processing_1", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\t\t\"\\data.txt\",1)\n\nbad_readings_total = 0\ngood_readings_total = 0\ndata_gap = 0\nstart_date = \"\"\nend_date = \"\"\ntmp_datax_gap = 0\ntmp_start_date = \"\"\n\nDo Until objFile.AtEndOfStream\n\tbad_readings = 0\n\tgood_readings = 0\n\tline_total = 0\n\tline = objFile.ReadLine\n\ttoken = Split(line,vbTab)\n\tn = 1\n\tDo While n <= UBound(token)\n\t\tIf n + 1 <= UBound(token) Then\n\t\t\tIf CInt(token(n+1)) < 1 Then\n\t\t\t\tbad_readings = bad_readings + 1\n\t\t\t\tbad_readings_total = bad_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf tmp_start_date = \"\" Then\n\t\t\t\t\ttmp_start_date = token(0)\n\t\t\t\tEnd If\n\t\t\t\ttmp_data_gap = tmp_data_gap + 1\n\t\t\tElse\n\t\t\t\tgood_readings = good_readings + 1\n\t\t\t\tline_total = line_total + CInt(token(n))\n\t\t\t\tgood_readings_total = good_readings_total + 1\n\t\t\t\t\n\t\t\t\tIf (tmp_start_date <> \"\") And (tmp_data_gap > data_gap) Then\n\t\t\t\t\tstart_date = tmp_start_date\n\t\t\t\t\tend_date = token(0)\n\t\t\t\t\tdata_gap = tmp_data_gap\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tElse\n\t\t\t\t\ttmp_start_date = \"\"\n\t\t\t\t\ttmp_data_gap = 0\n\t\t\t\tEnd If\n\t\t\tEnd If\t\n\t\tEnd If\n\t\tn = n + 2\n\tLoop\n\tline_avg = line_total/good_readings\n\tWScript.StdOut.Write \"Date: \" & token(0) & vbTab &_\n\t\t\"Bad Reads: \" & bad_readings & vbTab &_\n\t\t\"Good Reads: \" & good_readings & vbTab &_\n\t\t\"Line Total: \" & FormatNumber(line_total,3) & vbTab &_\n\t\t\"Line Avg: \" & FormatNumber(line_avg,3)\n\tWScript.StdOut.WriteLine\nLoop\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Maximum run of \" & data_gap &_ \n\t\" consecutive bad readings from \" & start_date & \" to \" &_\n\tend_date & \".\"\nWScript.StdOut.WriteLine\nobjFile.Close\nSet objFSO = Nothing\n", "Java": "import java.io.File;\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class TextProcessing1 {\n\n    public static void main(String[] args) throws Exception {\n        Locale.setDefault(new Locale(\"en\", \"US\"));\n        Metrics metrics = new Metrics();\n\n        int dataGap = 0;\n        String gapBeginDate = null;\n        try (Scanner lines = new Scanner(new File(\"readings.txt\"))) {\n            while (lines.hasNextLine()) {\n\n                double lineTotal = 0.0;\n                int linePairs = 0;\n                int lineInvalid = 0;\n                String lineDate;\n\n                try (Scanner line = new Scanner(lines.nextLine())) {\n\n                    lineDate = line.next();\n\n                    while (line.hasNext()) {\n                        final double value = line.nextDouble();\n                        if (line.nextInt() <= 0) {\n                            if (dataGap == 0)\n                                gapBeginDate = lineDate;\n                            dataGap++;\n                            lineInvalid++;\n                            continue;\n                        }\n                        lineTotal += value;\n                        linePairs++;\n\n                        metrics.addDataGap(dataGap, gapBeginDate, lineDate);\n                        dataGap = 0;\n                    }\n                }\n                metrics.addLine(lineTotal, linePairs);\n                metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);\n            }\n            metrics.report();\n        }\n    }\n\n    private static class Metrics {\n        private List<String[]> gapDates;\n        private int maxDataGap = -1;\n        private double total;\n        private int pairs;\n        private int lineResultCount;\n\n        void addLine(double tot, double prs) {\n            total += tot;\n            pairs += prs;\n        }\n\n        void addDataGap(int gap, String begin, String end) {\n            if (gap > 0 && gap >= maxDataGap) {\n                if (gap > maxDataGap) {\n                    maxDataGap = gap;\n                    gapDates = new ArrayList<>();\n                }\n                gapDates.add(new String[]{begin, end});\n            }\n        }\n\n        void lineResult(String date, int invalid, int prs, double tot) {\n            if (lineResultCount >= 3)\n                return;\n            out.printf(\"%10s  out: %2d  in: %2d  tot: %10.3f  avg: %10.3f%n\",\n                    date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);\n            lineResultCount++;\n        }\n\n        void report() {\n            out.printf(\"%ntotal    = %10.3f%n\", total);\n            out.printf(\"readings = %6d%n\", pairs);\n            out.printf(\"average  = %010.3f%n\", total / pairs);\n            out.printf(\"%nmaximum run(s) of %d invalid measurements: %n\",\n                    maxDataGap);\n            for (String[] dates : gapDates)\n                out.printf(\"begins at %s and ends at %s%n\", dates[0], dates[1]);\n\n        }\n    }\n}\n"}
{"id": 60215, "name": "MD5", "VB": "Imports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n    Sub Main(args As String())\n        Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n    End Sub\n\n    Private Function GetMD5(plainText As String) As String\n        Dim hash As String = \"\"\n\n        Using hashObject As MD5 = MD5.Create()\n            Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n            Dim hashBuilder As New StringBuilder\n\n            For i As Integer = 0 To ptBytes.Length - 1\n                hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n            Next\n            hash = hashBuilder.ToString\n        End Using\n\n        Return hash\n    End Function\n\nEnd Module\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n    public static void main(String[] args) {\n        System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n    }\n\n    static String hexDigest(String str, String digestName) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(digestName);\n            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n            char[] hex = new char[digest.length * 2];\n            for (int i = 0; i < digest.length; i++) {\n                hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n                hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n            }\n            return new String(hex);\n        } catch (NoSuchAlgorithmException e) {\n            throw new IllegalStateException(e);\n        }\n    }\n}\n"}
{"id": 60216, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 60217, "name": "Aliquot sequence classifications", "VB": "Option Explicit\n\nPrivate Type Aliquot\n   Sequence() As Double\n   Classification As String\nEnd Type\n\nSub Main()\nDim result As Aliquot, i As Long, j As Double, temp As String\n\n   For j = 1 To 10\n      result = Aliq(j)\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & j & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next j\n\nDim a\n   \n   a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)\n   For j = LBound(a) To UBound(a)\n      result = Aliq(CDbl(a(j)))\n      temp = vbNullString\n      For i = 0 To UBound(result.Sequence)\n         temp = temp & result.Sequence(i) & \", \"\n      Next i\n      Debug.Print \"Aliquot seq of \" & a(j) & \" : \" & result.Classification & \"   \" & Left(temp, Len(temp) - 2)\n   Next\nEnd Sub\n\nPrivate Function Aliq(Nb As Double) As Aliquot\nDim s() As Double, i As Long, temp, j As Long, cpt As Long\n   temp = Array(\"non-terminating\", \"Terminate\", \"Perfect\", \"Amicable\", \"Sociable\", \"Aspiring\", \"Cyclic\")\n   ReDim s(0)\n   s(0) = Nb\n   For i = 1 To 15\n      cpt = cpt + 1\n      ReDim Preserve s(cpt)\n      s(i) = SumPDiv(s(i - 1))\n      If s(i) > 140737488355328# Then Exit For\n      If s(i) = 0 Then j = 1\n      If s(1) = s(0) Then j = 2\n      If s(i) = s(0) And i > 1 And i <> 2 Then j = 4\n      If s(i) = s(i - 1) And i > 1 Then j = 5\n      If i >= 2 Then\n         If s(2) = s(0) Then j = 3\n         If s(i) = s(i - 2) And i <> 2 Then j = 6\n      End If\n      If j > 0 Then Exit For\n   Next\n   Aliq.Classification = temp(j)\n   Aliq.Sequence = s\nEnd Function\n\nPrivate Function SumPDiv(n As Double) As Double\n\nDim j As Long, t As Long\n    If n > 1 Then\n        For j = 1 To n \\ 2\n            If n Mod j = 0 Then t = t + j\n        Next\n    End If\n    SumPDiv = t\nEnd Function\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n    private static Long properDivsSum(long n) {\n        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n    }\n\n    static boolean aliquot(long n, int maxLen, long maxTerm) {\n        List<Long> s = new ArrayList<>(maxLen);\n        s.add(n);\n        long newN = n;\n\n        while (s.size() <= maxLen && newN < maxTerm) {\n\n            newN = properDivsSum(s.get(s.size() - 1));\n\n            if (s.contains(newN)) {\n\n                if (s.get(0) == newN) {\n\n                    switch (s.size()) {\n                        case 1:\n                            return report(\"Perfect\", s);\n                        case 2:\n                            return report(\"Amicable\", s);\n                        default:\n                            return report(\"Sociable of length \" + s.size(), s);\n                    }\n\n                } else if (s.get(s.size() - 1) == newN) {\n                    return report(\"Aspiring\", s);\n\n                } else\n                    return report(\"Cyclic back to \" + newN, s);\n\n            } else {\n                s.add(newN);\n                if (newN == 0)\n                    return report(\"Terminating\", s);\n            }\n        }\n\n        return report(\"Non-terminating\", s);\n    }\n\n    static boolean report(String msg, List<Long> result) {\n        System.out.println(msg + \": \" + result);\n        return false;\n    }\n\n    public static void main(String[] args) {\n        long[] arr = {\n                11, 12, 28, 496, 220, 1184, 12496, 1264460,\n                790, 909, 562, 1064, 1488};\n\n        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n        System.out.println();\n        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n    }\n}\n"}
{"id": 60218, "name": "Sorting algorithms_Sleep sort", "VB": "Imports System.Threading\n\nModule Module1\n\n    Sub SleepSort(items As IEnumerable(Of Integer))\n        For Each item In items\n            Task.Factory.StartNew(Sub()\n                                      Thread.Sleep(1000 * item)\n                                      Console.WriteLine(item)\n                                  End Sub)\n        Next\n    End Sub\n\n    Sub Main()\n        SleepSort({1, 5, 2, 1, 8, 10, 3})\n        Console.ReadKey()\n    End Sub\n\nEnd Module\n", "Java": "import java.util.concurrent.CountDownLatch;\n\npublic class SleepSort {\n\tpublic static void sleepSortAndPrint(int[] nums) {\n\t\tfinal CountDownLatch doneSignal = new CountDownLatch(nums.length);\n\t\tfor (final int num : nums) {\n\t\t\tnew Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tdoneSignal.countDown();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdoneSignal.await();\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tThread.sleep(num * 1000);\n\t\t\t\t\t\tSystem.out.println(num);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}).start();\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] nums = new int[args.length];\n\t\tfor (int i = 0; i < args.length; i++)\n\t\t\tnums[i] = Integer.parseInt(args[i]);\n\t\tsleepSortAndPrint(nums);\n\t}\n}\n"}
{"id": 60219, "name": "Loops_Nested", "VB": "Public Sub LoopsNested()\n    Dim a(1 To 10, 1 To 10) As Integer\n    Randomize\n    For i = 1 To 10\n        For j = 1 To 10\n            a(i, j) = Int(20 * Rnd) + 1\n        Next j\n    Next i\n    For i = 1 To 10\n        For j = 1 To 10\n            If a(i, j) <> 20 Then\n                Debug.Print a(i, j),\n            Else\n                i = 10 \n                Exit For \n            End If\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "Java": "import java.util.Random;\n\npublic class NestedLoopTest {\n    public static final Random gen = new Random();\n    public static void main(String[] args) {\n        int[][] a = new int[10][10];\n        for (int i = 0; i < a.length; i++)\n            for (int j = 0; j < a[i].length; j++)\n                a[i][j] = gen.nextInt(20) + 1;\n\n        Outer:for (int i = 0; i < a.length; i++) {\n            for (int j = 0; j < a[i].length; j++) {\n                System.out.print(\" \" + a[i][j]);\n                if (a[i][j] == 20)\n                    break Outer; \n            }\n            System.out.println();\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 60220, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 60221, "name": "Pythagorean triples", "VB": "Dim total As Variant, prim As Variant, maxPeri As Variant\nPrivate Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)\n    Dim p As Variant\n    p = CDec(s0) + CDec(s1) + CDec(s2)\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2\n        newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2\n        newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2\n      End If\nEnd Sub\nPublic Sub Program_PythagoreanTriples()\n    maxPeri = CDec(100)\n    Do While maxPeri <= 10000000#\n        prim = CDec(0)\n        total = CDec(0)\n        newTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n", "Java": "import java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n    public static void main(String[] args){\n        long tripCount = 0, primCount = 0;\n\n        \n        BigInteger periLimit = BigInteger.valueOf(100),\n                peri2 = periLimit.divide(BigInteger.valueOf(2)),\n                peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n            BigInteger aa = a.multiply(a);\n            \n            for(BigInteger b = a.add(ONE);\n                    b.compareTo(peri2) < 0; b = b.add(ONE)){\n                BigInteger bb = b.multiply(b);\n                BigInteger ab = a.add(b);\n                BigInteger aabb = aa.add(bb);\n                \n                for(BigInteger c = b.add(ONE);\n                        c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n                    int compare = aabb.compareTo(c.multiply(c));\n                    \n                    if(ab.add(c).compareTo(periLimit) > 0){\n                        break;\n                    }\n                    \n                    if(compare < 0){\n                        break;\n                    }else if (compare == 0){\n                        tripCount++;\n                        System.out.print(a + \", \" + b + \", \" + c);\n\n                        \n                        if(a.gcd(b).equals(ONE)){\n                            System.out.print(\" primitive\");\n                            primCount++;\n                        }\n                        System.out.println();\n                    }\n                }\n            }\n        }\n        System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n                + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n    }\n}\n"}
{"id": 60222, "name": "Remove duplicate elements", "VB": "Option Explicit\n\nSub Main()\nDim myArr() As Variant, i As Long\n\n    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, \"Alpha\", 1, 235, 4, 1.25, 1.25, \"Beta\", 1.23456789101112E+16, \"Delta\", \"Alpha\", \"Charlie\", 1, 2, \"Foxtrot\", \"Foxtrot\", \"Alpha\", 235))\n\n    For i = LBound(myArr) To UBound(myArr)\n        Debug.Print myArr(i)\n    Next\nEnd Sub\n\nPrivate Function Remove_Duplicate(Arr As Variant) As Variant()\nDim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long\n\n    ReDim Temp(UBound(Arr))\n    For i = LBound(Arr) To UBound(Arr)\n        On Error Resume Next\n        myColl.Add CStr(Arr(i)), CStr(Arr(i))\n        If Err.Number > 0 Then\n            On Error GoTo 0\n        Else\n            Temp(cpt) = Arr(i)\n            cpt = cpt + 1\n        End If\n    Next i\n    ReDim Preserve Temp(cpt - 1)\n    Remove_Duplicate = Temp\nEnd Function\n", "Java": "module RetainUniqueValues\n    {\n    @Inject Console console;\n    void run()\n        {\n        Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];\n        array = array.distinct().toArray();\n        console.print($\"result={array}\");\n        }\n    }\n"}
{"id": 60223, "name": "Look-and-say sequence", "VB": "function looksay( n )\n\tdim i\n\tdim accum\n\tdim res\n\tdim c\n\tres = vbnullstring\n\tdo\n\t\tif n = vbnullstring then exit do\n\t\taccum = 0\n\t\tc = left( n,1 )\n\t\tdo while left( n, 1 ) = c\n\t\t\taccum = accum + 1\n\t\t\tn = mid(n,2)\n\t\tloop\n\t\tif accum > 0 then \n\t\t\tres = res & accum & c\n\t\tend if\n\tloop\n\tlooksay = res\nend function\n", "Java": "public static String lookandsay(String number){\n\tStringBuilder result= new StringBuilder();\n\n\tchar repeat= number.charAt(0);\n\tnumber= number.substring(1) + \" \";\n\tint times= 1;\n\n\tfor(char actual: number.toCharArray()){\n\t\tif(actual != repeat){\n\t\t\tresult.append(times + \"\" + repeat);\n\t\t\ttimes= 1;\n\t\t\trepeat= actual;\n\t\t}else{\n\t\t\ttimes+= 1;\n\t\t}\n\t}\n\treturn result.toString();\n}\n"}
{"id": 60224, "name": "Stack", "VB": "\n\n\n\n\n\nPrivate myStack()\nPrivate myStackHeight As Integer\n\n\nPublic Function Push(aValue)\n  \n  myStackHeight = myStackHeight + 1\n  ReDim Preserve myStack(myStackHeight)\n  myStack(myStackHeight) = aValue\nEnd Function\n\n\nPublic Function Pop()\n  \n  If myStackHeight > 0 Then\n    Pop = myStack(myStackHeight)\n    myStackHeight = myStackHeight - 1\n  Else\n    MsgBox \"Pop: stack is empty!\"\n  End If\nEnd Function\n\n\nPublic Function IsEmpty() As Boolean\n  IsEmpty = (myStackHeight = 0)\nEnd Function\n\n\nProperty Get Size() As Integer\n  Size = myStackHeight\nEnd Property\n", "Java": "import java.util.Stack;\n\npublic class StackTest {\n    public static void main( final String[] args ) {\n        final Stack<String> stack = new Stack<String>();\n\n        System.out.println( \"New stack empty? \" + stack.empty() );\n\n        stack.push( \"There can be only one\" );\n        System.out.println( \"Pushed stack empty? \" + stack.empty() );\n        System.out.println( \"Popped single entry: \" + stack.pop() );\n\n        stack.push( \"First\" );\n        stack.push( \"Second\" );\n        System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n        \n        stack.pop();\n        stack.pop();\n    }\n}\n"}
{"id": 60225, "name": "Totient function", "VB": "Private Function totient(ByVal n As Long) As Long\n    Dim tot As Long: tot = n\n    Dim i As Long: i = 2\n    Do While i * i <= n\n        If n Mod i = 0 Then\n            Do While True\n                n = n \\ i\n                If n Mod i <> 0 Then Exit Do\n            Loop\n            tot = tot - tot \\ i\n        End If\n        i = i + IIf(i = 2, 1, 2)\n    Loop\n    If n > 1 Then\n        tot = tot - tot \\ n\n    End If\n    totient = tot\nEnd Function\n\nPublic Sub main()\n    Debug.Print \" n  phi   prime\"\n    Debug.Print \" --------------\"\n    Dim count As Long\n    Dim tot As Integer, n As Long\n    For n = 1 To 25\n        tot = totient(n)\n        prime = (n - 1 = tot)\n        count = count - prime\n        Debug.Print Format(n, \"@@\"); Format(tot, \"@@@@@\"); Format(prime, \"@@@@@@@@\")\n    Next n\n    Debug.Print\n    Debug.Print \"Number of primes up to 25     = \"; Format(count, \"@@@@\")\n    For n = 26 To 100000\n        count = count - (totient(n) = n - 1)\n        Select Case n\n            Case 100, 1000, 10000, 100000\n                Debug.Print \"Number of primes up to\"; n; String$(6 - Len(CStr(n)), \" \"); \"=\"; Format(count, \"@@@@@\")\n            Case Else\n        End Select\n    Next n\nEnd Sub\n", "Java": "public class TotientFunction {\n\n    public static void main(String[] args) {\n        computePhi();\n        System.out.println(\"Compute and display phi for the first 25 integers.\");\n        System.out.printf(\"n  Phi  IsPrime%n\");\n        for ( int n = 1 ; n <= 25 ; n++ ) {\n            System.out.printf(\"%2d  %2d  %b%n\", n, phi[n], (phi[n] == n-1));\n        }\n        for ( int i = 2 ; i < 8 ; i++ ) {\n            int max = (int) Math.pow(10, i);\n            System.out.printf(\"The count of the primes up to %,10d = %d%n\", max, countPrimes(1, max));\n        }\n    }\n    \n    private static int countPrimes(int min, int max) {\n        int count = 0;\n        for ( int i = min ; i <= max ; i++ ) {\n            if ( phi[i] == i-1 ) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private static final int max = 10000000;\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": 60226, "name": "Conditional structures", "VB": "Sub C_S_If()\nDim A$, B$\n\n    A = \"Hello\"\n    B = \"World\"\n    \n    If A = B Then Debug.Print A & \" = \" & B\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else\n        Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then\n        Debug.Print A & \" = \" & B\n    Else: Debug.Print A & \" and \" & B & \" are differents.\"\n    End If\n    \n    If A = B Then Debug.Print A & \" = \" & B _\n    Else Debug.Print A & \" and \" & B & \" are differents.\"    \n    \n    If A = B Then Debug.Print A & \" = \" & B Else Debug.Print A & \" and \" & B & \" are differents.\"\n    If A = B Then Debug.Print A & \" = \" & B Else: Debug.Print A & \" and \" & B & \" are differents.\"\nEnd Sub\n", "Java": "if (s == 'Hello World') {\n    foo();\n} else if (s == 'Bye World') {\n    bar();\n} else {\n    deusEx();\n}\n"}
{"id": 60227, "name": "Fractran", "VB": "Option Base 1\nPublic prime As Variant\nPublic nf As New Collection\nPublic df As New Collection\nConst halt = 20\nPrivate Sub init()\n    prime = [{2,3,5,7,11,13,17,19,23,29,31}]\nEnd Sub\nPrivate Function factor(f As Long) As Variant\n    Dim result(10) As Integer\n    Dim i As Integer: i = 1\n    Do While f > 1\n        Do While f Mod prime(i) = 0\n            f = f \\ prime(i)\n            result(i) = result(i) + 1\n        Loop\n        i = i + 1\n    Loop\n    factor = result\nEnd Function\nPrivate Function decrement(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) - b(i)\n    Next i\n    decrement = a\nEnd Function\nPrivate Function increment(ByVal a As Variant, b As Variant) As Variant\n    For i = LBound(a) To UBound(a)\n        a(i) = a(i) + b(i)\n    Next i\n    increment = a\nEnd Function\nPrivate Function test(a As Variant, b As Variant)\n    flag = True\n    For i = LBound(a) To UBound(a)\n        If a(i) < b(i) Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    test = flag\nEnd Function\nPrivate Function unfactor(x As Variant) As Long\n    result = 1\n    For i = LBound(x) To UBound(x)\n        result = result * prime(i) ^ x(i)\n    Next i\n    unfactor = result\nEnd Function\nPrivate Sub compile(program As String)\n    program = Replace(program, \" \", \"\")\n    programlist = Split(program, \",\")\n    For Each instruction In programlist\n        parts = Split(instruction, \"/\")\n        nf.Add factor(Val(parts(0)))\n        df.Add factor(Val(parts(1)))\n    Next instruction\nEnd Sub\nPrivate Function run(x As Long) As Variant\n    n = factor(x)\n    counter = 0\n    Do While True\n        For i = 1 To df.Count\n            If test(n, df(i)) Then\n                n = increment(decrement(n, df(i)), nf(i))\n                Exit For\n            End If\n        Next i\n        Debug.Print unfactor(n);\n        counter = counter + 1\n        If num = 31 Or counter >= halt Then Exit Do\n    Loop\n    Debug.Print\n    run = n\nEnd Function\nPrivate Function steps(x As Variant) As Variant\n    \n    For i = 1 To df.Count\n        If test(x, df(i)) Then\n            x = increment(decrement(x, df(i)), nf(i))\n            Exit For\n        End If\n    Next i\n    steps = x\nEnd Function\nPrivate Function is_power_of_2(x As Variant) As Boolean\n    flag = True\n    For i = LBound(x) + 1 To UBound(x)\n        If x(i) > 0 Then\n            flag = False\n            Exit For\n        End If\n    Next i\n    is_power_of_2 = flag\nEnd Function\nPrivate Function filter_primes(x As Long, max As Integer) As Long\n    n = factor(x)\n    i = 0: iterations = 0\n    Do While i < max\n        If is_power_of_2(steps(n)) Then\n            Debug.Print n(1);\n            i = i + 1\n        End If\n        iterations = iterations + 1\n    Loop\n    Debug.Print\n    filter_primes = iterations\nEnd Function\nPublic Sub main()\n    init\n    compile (\"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14,  15/2, 55/1\")\n    Debug.Print \"First 20 results:\"\n    output = run(2)\n    Debug.Print \"First 30 primes:\"\n    Debug.Print \"after\"; filter_primes(2, 30); \"iterations.\"\nEnd Sub\n", "Java": "import java.util.Vector;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Fractran{\n\n   public static void main(String []args){ \n\n       new Fractran(\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1\", 2);\n   }\n   final int limit = 15;\n   \n\n   Vector<Integer> num = new Vector<>(); \n   Vector<Integer> den = new Vector<>(); \n   public Fractran(String prog, Integer val){\n      compile(prog);\n      dump();\n      exec(2);\n    }\n\n\n   void compile(String prog){\n      Pattern regexp = Pattern.compile(\"\\\\s*(\\\\d*)\\\\s*\\\\/\\\\s*(\\\\d*)\\\\s*(.*)\");\n      Matcher matcher = regexp.matcher(prog);\n      while(matcher.find()){\n         num.add(Integer.parseInt(matcher.group(1)));\n         den.add(Integer.parseInt(matcher.group(2)));\n         matcher = regexp.matcher(matcher.group(3));\n      }\n   }\n\n   void exec(Integer val){\n       int n = 0;\n       while(val != null && n<limit){\n           System.out.println(n+\": \"+val);\n           val = step(val);\n           n++;\n       }\n   }\n   Integer step(int val){\n       int i=0; \n       while(i<den.size() && val%den.get(i) != 0) i++;\n       if(i<den.size())\n           return num.get(i)*val/den.get(i);\n       return null;\n   }\n\n   void dump(){\n       for(int i=0; i<den.size(); i++)\n           System.out.print(num.get(i)+\"/\"+den.get(i)+\" \");\n       System.out.println();\n   }\n}\n"}
{"id": 60228, "name": "Read a configuration file", "VB": "type TSettings extends QObject\n    FullName as string\n    FavouriteFruit as string\n    NeedSpelling as integer\n    SeedsRemoved as integer\n    OtherFamily as QStringlist\n    \n    Constructor\n        FullName = \"\"\n        FavouriteFruit = \"\"\n        NeedSpelling = 0\n        SeedsRemoved = 0\n        OtherFamily.clear\n    end constructor\nend type\n\nDim Settings as TSettings\ndim ConfigList as QStringList\ndim x as integer\ndim StrLine as string\ndim StrPara as string\ndim StrData as string\n\nfunction Trim$(Expr as string) as string\n    Result = Rtrim$(Ltrim$(Expr))\nend function\n\nSub ConfigOption(PData as string)\n    dim x as integer\n    for x = 1 to tally(PData, \",\") +1\n        Settings.OtherFamily.AddItems Trim$(field$(PData, \",\" ,x))\n    next\nend sub \n\nFunction ConfigBoolean(PData as string) as integer\n    PData = Trim$(PData)\n    Result = iif(lcase$(PData)=\"true\" or PData=\"1\" or PData=\"\", 1, 0)\nend function\n\nsub ReadSettings\n    ConfigList.LoadFromFile(\"Rosetta.cfg\")\n    ConfigList.text = REPLACESUBSTR$(ConfigList.text,\"=\",\" \")\n\n    for x = 0 to ConfigList.ItemCount -1\n        StrLine = Trim$(ConfigList.item(x))\n        StrPara = Trim$(field$(StrLine,\" \",1))\n        StrData = Trim$(lTrim$(StrLine - StrPara))  \n    \n        Select case UCase$(StrPara)\n        case \"FULLNAME\"       : Settings.FullName = StrData \n        case \"FAVOURITEFRUIT\" : Settings.FavouriteFruit = StrData \n        case \"NEEDSPEELING\"   : Settings.NeedSpelling = ConfigBoolean(StrData)\n        case \"SEEDSREMOVED\"   : Settings.SeedsRemoved = ConfigBoolean(StrData)\n        case \"OTHERFAMILY\"    : Call ConfigOption(StrData)\n        end select\n    next\nend sub\n\nCall ReadSettings\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n    private static final Pattern             LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n    private static final Map<String, Object> DEFAULTS     = new HashMap<String, Object>() {{\n        put( \"needspeeling\", false );\n        put( \"seedsremoved\", false );\n    }};\n\n    public static void main( final String[] args ) {\n        System.out.println( parseFile( args[ 0 ] ) );\n    }\n\n    public static Map<String, Object> parseFile( final String fileName ) {\n        final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );\n         BufferedReader      reader = null;\n\n        try {\n            reader = new BufferedReader( new FileReader( fileName ) );\n            for ( String line; null != ( line = reader.readLine() );  ) {\n                parseLine( line, result );\n            }\n        } catch ( final IOException x ) {\n            throw new RuntimeException( \"Oops: \" + x, x );\n        } finally {\n            if ( null != reader ) try {\n                reader.close();\n            } catch ( final IOException x2 ) {\n                System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n            }\n        }\n\n        return result;\n    }\n\n    private static void parseLine( final String line, final Map<String, Object> map ) {\n        if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n            return;\n\n        final Matcher matcher = LINE_PATTERN.matcher( line );\n\n        if ( ! matcher.matches() ) {\n            System.err.println( \"Bad config line: \" + line );\n            return;\n        }\n\n        final String key   = matcher.group( 1 ).trim().toLowerCase();\n        final String value = matcher.group( 2 ).trim();\n\n        if ( \"\".equals( value ) ) {\n            map.put( key, true );\n        } else if ( -1 == value.indexOf( ',' ) ) {\n            map.put( key, value );\n        } else {\n            final String[] values = value.split( \",\" );\n\n            for ( int i = 0; i < values.length; i++ ) {\n                values[ i ] = values[ i ].trim();\n            }\n            map.put( key, Arrays.asList( values ) );\n        }\n    }\n}\n"}
{"id": 60229, "name": "Sort using a custom comparator", "VB": "Imports System\n\nModule Sorting_Using_a_Custom_Comparator\n    Function CustomComparator(ByVal x As String, ByVal y As String) As Integer\n        Dim result As Integer\n        result = y.Length - x.Length\n        If result = 0 Then\n            result = String.Compare(x, y, True)\n        End If\n        Return result\n    End Function\n\n    Sub Main()\n        Dim strings As String() = {\"test\", \"Zoom\", \"strings\", \"a\"}\n\n        Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))\n    End Sub\nEnd Module\n", "Java": "import java.util.Comparator;\nimport java.util.Arrays;\n\npublic class Test {\n  public static void main(String[] args) {\n    String[] strings = {\"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\"};\n\n    Arrays.sort(strings, new Comparator<String>() {\n      public int compare(String s1, String s2) {\n        int c = s2.length() - s1.length();\n        if (c == 0)\n          c = s1.compareToIgnoreCase(s2);\n        return c;\n      }\n    });\n\n    for (String s: strings)\n      System.out.print(s + \" \");\n  }\n}\n"}
{"id": 60230, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 60231, "name": "Animation", "VB": "VERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  \n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n", "Java": "import java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n    private static class State {\n        private final String text = \"Hello World! \";\n        private int startIndex = 0;\n        private boolean rotateRight = true;\n    }\n\n    public static void main(String[] args) {\n        State state = new State();\n\n        JLabel label = new JLabel(state.text);\n        label.addMouseListener(new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent event) {\n                state.rotateRight = !state.rotateRight;\n            }\n        });\n\n        TimerTask task = new TimerTask() {\n            public void run() {\n                int delta = state.rotateRight ? 1 : -1;\n                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n                label.setText(rotate(state.text, state.startIndex));\n            }\n        };\n        Timer timer = new Timer(false);\n        timer.schedule(task, 0, 500);\n\n        JFrame rot = new JFrame();\n        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n        rot.add(label);\n        rot.pack();\n        rot.setLocationRelativeTo(null);\n        rot.addWindowListener(new WindowAdapter() {\n            @Override\n            public void windowClosed(WindowEvent e) {\n                timer.cancel();\n            }\n        });\n        rot.setVisible(true);\n    }\n\n    private static String rotate(String text, int startIdx) {\n        char[] rotated = new char[text.length()];\n        for (int i = 0; i < text.length(); i++) {\n            rotated[i] = text.charAt((i + startIdx) % text.length());\n        }\n        return String.valueOf(rotated);\n    }\n}\n"}
{"id": 60232, "name": "List comprehensions", "VB": "Module ListComp\n    Sub Main()\n        Dim ts = From a In Enumerable.Range(1, 20) _\n                 From b In Enumerable.Range(a, 21 - a) _\n                 From c In Enumerable.Range(b, 21 - b) _\n                 Where a * a + b * b = c * c _\n                 Select New With { a, b, c }\n        \n        For Each t In ts\n            System.Console.WriteLine(\"{0}, {1}, {2}\", t.a, t.b, t.c)\n        Next\n    End Sub\nEnd Module\n", "Java": "\nimport java.util.Arrays;\nimport java.util.List;\nimport static java.util.function.Function.identity;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\npublic interface PythagComp{\n    static void main(String... args){\n        System.out.println(run(20));\n    }\n\n    static List<List<Integer>> run(int n){\n        return\n            \n            \n            range(1, n).mapToObj(\n                x -> range(x, n).mapToObj(\n                    y -> range(y, n).mapToObj(\n                        z -> new Integer[]{x, y, z}\n                    )\n                )\n            )\n                .flatMap(identity())\n                .flatMap(identity())\n                \n                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])\n                \n                .map(Arrays::asList)\n                \n                .collect(toList())\n        ;\n    }\n}\n"}
{"id": 60233, "name": "Sorting algorithms_Selection sort", "VB": "Function Selection_Sort(s)\n\tarr = Split(s,\",\")\n\tFor i = 0 To UBound(arr)\n\t\tFor j = i To UBound(arr)\n\t\t\ttemp = arr(i)\n\t\t\tIf arr(j) < arr(i) Then\n\t\t\t\tarr(i) = arr(j)\n\t\t\t\tarr(j) = temp\n\t\t\tEnd If\n\t\tNext\n\tNext\n\tSelection_Sort = (Join(arr,\",\"))\nEnd Function\n\nWScript.StdOut.Write \"Pre-Sort\" & vbTab & \"Sorted\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"3,2,5,4,1\" & vbTab & Selection_Sort(\"3,2,5,4,1\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"c,e,b,a,d\" & vbTab & Selection_Sort(\"c,e,b,a,d\")\n", "Java": "public static void sort(int[] nums){\n\tfor(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){\n\t\tint smallest = Integer.MAX_VALUE;\n\t\tint smallestAt = currentPlace+1;\n\t\tfor(int check = currentPlace; check<nums.length;check++){\n\t\t\tif(nums[check]<smallest){\n\t\t\t\tsmallestAt = check;\n\t\t\t\tsmallest = nums[check];\n\t\t\t}\n\t\t}\n\t\tint temp = nums[currentPlace];\n\t\tnums[currentPlace] = nums[smallestAt];\n\t\tnums[smallestAt] = temp;\n\t}\n}\n"}
{"id": 60234, "name": "Apply a callback to an array", "VB": "Option Explicit\n\nSub Main()\nDim arr, i\n    \n    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n\n    \n    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next\n    \n    \n    Debug.Print Join(arr, \", \")\nEnd Sub\n\nPrivate Function Fibonacci(N) As Variant\n    If N <= 1 Then\n        Fibonacci = N\n    Else\n        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)\n    End If\nEnd Function\n", "Java": "public class ArrayCallback7 {\n\n    interface IntConsumer {\n        void run(int x);\n    }\n\n    interface IntToInt {\n        int run(int x);\n    }\n\n    static void forEach(int[] arr, IntConsumer consumer) {\n        for (int i : arr) {\n            consumer.run(i);\n        }\n    }\n\n    static void update(int[] arr, IntToInt mapper) {\n        for (int i = 0; i < arr.length; i++) {\n            arr[i] = mapper.run(arr[i]);\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n\n        update(numbers, new IntToInt() {\n            @Override\n            public int run(int x) {\n                return x * x;\n            }\n        });\n\n        forEach(numbers, new IntConsumer() {\n            public void run(int x) {\n                System.out.println(x);\n            }\n        });\n    }\n}\n"}
{"id": 60235, "name": "Case-sensitivity of identifiers", "VB": "Public Sub case_sensitivity()\n    \n    \n    \n    Dim DOG As String\n    DOG = \"Benjamin\"\n    DOG = \"Samba\"\n    DOG = \"Bernie\"\n    Debug.Print \"There is just one dog named \" & DOG\nEnd Sub\n", "Java": "String dog = \"Benjamin\"; \nString Dog = \"Samba\";    \nString DOG = \"Bernie\";   \n@Inject Console console;\nconsole.print($\"There are three dogs named {dog}, {Dog}, and {DOG}\");\n"}
{"id": 60236, "name": "Loops_Downward for", "VB": "For i = 10 To 0 Step -1\n   Debug.Print i\nNext i\n", "Java": "for (int i = 10; i >= 0; i--) {\n    System.out.println(i);\n}\n"}
{"id": 60237, "name": "Write entire file", "VB": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n           \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n           \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n    Print #1, Text\nClose #Nb\nEnd Sub\n", "Java": "import java.io.*;\n\npublic class Test {\n\n    public static void main(String[] args) throws IOException {\n        try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n            bw.write(\"abc\");\n        }\n    }\n}\n"}
{"id": 60238, "name": "Loops_For", "VB": "Public OutConsole As Scripting.TextStream\nFor i = 0 To 4\n    For j = 0 To i\n        OutConsole.Write \"*\"\n    Next j \n    OutConsole.WriteLine\nNext i\n", "Java": "for (Integer i = 0; i < 5; i++) {\n    String line = '';\n\n    for (Integer j = 0; j < i; j++) {\n        line += '*';\n    }\n\n    System.debug(line);\n}\n\nList<String> lines = new List<String> {\n    '*',\n    '**',\n    '***',\n    '****',\n    '*****'\n};\n\nfor (String line : lines) {\n    System.debug(line);\n}\n"}
{"id": 60239, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 60240, "name": "Sierpinski triangle_Graphical", "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\n\nsub sier(lev,lgth)\n   dim i\n   \n   if lev=1 then  \n     for i=1 to 3\n       x.fw lgth \n       x.lt 2\n     next  \n   else\n      sier lev-1,lgth\\2\n      x.fw lgth\\2\n      sier lev-1,lgth\\2\n      x.bw lgth\\2\n      x.lt 1\n      x.fw lgth\\2\n      x.rt 1\n      sier lev-1,lgth\\2 \n      x.lt 1\n      x.bw lgth\\2\n      x.rt 1\n    end if  \nend sub\n     \ndim x\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=10\nx.x=100:x.y=100\n\nsier 7,64\nset x=nothing \n", "Java": "import javax.swing.*;\nimport java.awt.*;\n\n \n\nclass SierpinskyTriangle {\n\n\tpublic static void main(String[] args) {\n\t\tint i = 3;\t\t\n\t\tif(args.length >= 1) {\n\t\t\ttry {\n\t\t\t\ti = Integer.parseInt(args[0]);\n\t\t\t}\n\t\t\tcatch(NumberFormatException e) {\n\t\t\t\tSystem.out.println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to \"+i);\n\t\t\t}\n\t\t}\n\t\tfinal int level = i;\n\n\t\tJFrame frame = new JFrame(\"Sierpinsky Triangle - Java\");\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tJPanel panel = new JPanel() {\n\t\t\t@Override\n\t\t\tpublic void paintComponent(Graphics g) {\n\t\t\t\tg.setColor(Color.BLACK);\n\t\t\t\tdrawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);\n\t\t\t}\n\t\t};\n\n\t\tpanel.setPreferredSize(new Dimension(400, 400));\n\n\t\tframe.add(panel);\n\t\tframe.pack();\n\t\tframe.setResizable(false);\n\t\tframe.setLocationRelativeTo(null);\n\t\tframe.setVisible(true);\n\t}\n\n\tprivate static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {\n\t\tif(level <= 0) return;\n\n\t\tg.drawLine(x, y, x+size, y);\n\t\tg.drawLine(x, y, x, y+size);\n\t\tg.drawLine(x+size, y, x, y+size);\n\n\t\tdrawSierpinskyTriangle(level-1, x, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);\n\t\tdrawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);\n\t}\n}\n"}
{"id": 60241, "name": "Non-continuous subsequences", "VB": "\n\nFunction noncontsubseq(l)\n    Dim  i, j, g, n, r, s, w, m\n    Dim  a, b, c\n    n = Ubound(l)\n    For s = 0 To n-2\n        For g = s+1 To n-1\n            a = \"[\"\n            For i = s To g-1\n                a = a & l(i) & \", \"\n            Next \n            For w = 1 To n-g\n                r = n+1-g-w\n                For i = 1 To 2^r-1 Step 2\n                    b = a\n                    For j = 0 To r-1\n                        If i And 2^j Then b=b & l(g+w+j) & \", \"\n                    Next \n                    c = (Left(b, Len(b)-1))\n                    WScript.Echo Left(c, Len(c)-1) & \"]\"\n\t\t\t\t\tm = m+1\n                Next \n            Next \n        Next \n    Next \n    noncontsubseq = m\nEnd Function \n\nlist = Array(\"1\", \"2\", \"3\", \"4\")\nWScript.Echo \"List: [\" & Join(list, \", \") & \"]\"\nnn = noncontsubseq(list)\nWScript.Echo nn & \" non-continuous subsequences\"\n", "Java": "public class NonContinuousSubsequences {\n\n    public static void main(String args[]) {\n        seqR(\"1234\", \"\", 0, 0);\n    }\n\n    private static void seqR(String s, String c, int i, int added) {\n        if (i == s.length()) {\n            if (c.trim().length() > added)\n                System.out.println(c);\n        } else {\n            seqR(s, c + s.charAt(i), i + 1, added + 1);\n            seqR(s, c + ' ', i + 1, added);\n        }\n    }\n}\n"}
{"id": 60242, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 60243, "name": "Twin primes", "VB": "Function IsPrime(x As Long) As Boolean\n    Dim i As Long\n    If x Mod 2 = 0 Then\n        Exit Function\n    Else\n        For i = 3 To Int(Sqr(x)) Step 2\n            If x Mod i = 0 Then Exit Function\n        Next i\n    End If\n    IsPrime = True\nEnd Function\n\nFunction TwinPrimePairs(max As Long) As Long\n    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long\n    p2 = True\n    For i = 5 To max Step 2\n        p1 = p2\n        p2 = IsPrime(i)\n        If p1 And p2 Then count = count + 1\n    Next i\n    TwinPrimePairs = count\nEnd Function\n\nSub Test(x As Long)\n    Debug.Print \"Twin prime pairs below\" + Str(x) + \":\" + Str(TwinPrimePairs(x))\nEnd Sub\n\nSub Main()\n    Test 10\n    Test 100\n    Test 1000\n    Test 10000\n    Test 100000\n    Test 1000000\n    Test 10000000\nEnd Sub\n", "Java": "import java.math.BigInteger;\nimport java.util.Scanner;\n\npublic class twinPrimes {\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        System.out.println(\"Search Size: \");\n        BigInteger max = input.nextBigInteger();\n        int counter = 0;\n        for(BigInteger x = new BigInteger(\"3\"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){\n            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);\n            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {\n                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;\n            }\n        }\n        System.out.println(counter + \" twin prime pairs.\");\n    }\n    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){\n        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){\n            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"}
{"id": 60244, "name": "Roots of unity", "VB": "Public Sub roots_of_unity()\n    For n = 2 To 9\n        Debug.Print n; \"th roots of 1:\"\n        For r00t = 0 To n - 1\n            Debug.Print \"   Root \"; r00t & \": \"; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _\n                Sin(2 * WorksheetFunction.Pi() * r00t / n))\n        Next r00t\n        Debug.Print\n    Next n\nEnd Sub\n", "Java": "import java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] a) {\n        for (int n = 2; n < 6; n++)\n            unity(n);\n    }\n\n    public static void unity(int n) {\n        System.out.printf(\"%n%d: \", n);\n\n        \n        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {\n\n            double real = Math.cos(angle); \n\n            if (Math.abs(real) < 1.0E-3)\n                real = 0.0; \n\n            double imag = Math.sin(angle); \n\n            if (Math.abs(imag) < 1.0E-3)\n                imag = 0.0;\n\n            System.out.printf(Locale.US, \"(%9f,%9f) \", real, imag);\n        }\n    }\n}\n"}
{"id": 60245, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 60246, "name": "Long multiplication", "VB": "Imports System\nImports System.Console\nImports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D\n\n    \n    Structure bd\n        Public hi, lo As Decimal\n    End Structure\n\n    \n    Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String\n        Dim r As String = If(a.hi = 0, String.Format(\"{0:0}\", a.lo),\n                                       String.Format(\"{0:0}{1:\" & New String(\"0\"c, 28) & \"}\", a.hi, a.lo))\n        If Not comma Then Return r \n        Dim rc As String = \"\"\n        For i As Integer = r.Length - 3 To 0 Step -3\n            rc = \",\" & r.Substring(i, 3) & rc : Next\n        toStr = r.Substring(0, r.Length Mod 3) & rc\n            toStr = toStr.Substring(If(toStr.Chars(0) = \",\" , 1, 0))\n    End Function\n\n    \n    Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal\n        If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _\n        Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas\n    End Function\n\n    Sub Main(ByVal args As String())\n         For p As UInteger = 64 To 95 - 1 Step 30                 \n            Dim y As bd, x As bd : a = Pow_dec(2D, p)             \n            WriteLine(\"The square of (2^{0}):                    {1,38:n0}\", p, a)\n            x.hi = Math.Floor(a / hm) : x.lo = a Mod hm           \n            Dim BS As BI = BI.Pow(CType(a, BI), 2)                \n            y.lo = x.lo * x.lo : y.hi = x.hi * x.hi               \n            a = x.hi * x.lo * 2D                                  \n            y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm  \n            While y.lo > mx : y.lo -= mx : y.hi += 1 : End While  \n            WriteLine(\" is {0,75} (which {1} match the BigInteger computation)\" & vbLf,\n                toStr(y, True), If(BS.ToString() = toStr(y), \"does\", \"fails to\"))\n        Next\n    End Sub\n\nEnd Module\n", "Java": "public class LongMult {\n\n\tprivate static byte[] stringToDigits(String num) {\n\t\tbyte[] result = new byte[num.length()];\n\t\tfor (int i = 0; i < num.length(); i++) {\n\t\t\tchar c = num.charAt(i);\n\t\t\tif (c < '0' || c > '9') {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid digit \" + c\n\t\t\t\t\t\t+ \" found at position \" + i);\n\t\t\t}\n\t\t\tresult[num.length() - 1 - i] = (byte) (c - '0');\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String longMult(String num1, String num2) {\n\t\tbyte[] left = stringToDigits(num1);\n\t\tbyte[] right = stringToDigits(num2);\n\t\tbyte[] result = new byte[left.length + right.length];\n\t\tfor (int rightPos = 0; rightPos < right.length; rightPos++) {\n\t\t\tbyte rightDigit = right[rightPos];\n\t\t\tbyte temp = 0;\n\t\t\tfor (int leftPos = 0; leftPos < left.length; leftPos++) {\n\t\t\t\ttemp += result[leftPos + rightPos];\n\t\t\t\ttemp += rightDigit * left[leftPos];\n\t\t\t\tresult[leftPos + rightPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t}\n\t\t\tint destPos = rightPos + left.length;\n\t\t\twhile (temp != 0) {\n\t\t\t\ttemp += result[destPos] & 0xFFFFFFFFL;\n\t\t\t\tresult[destPos] = (byte) (temp % 10);\n\t\t\t\ttemp /= 10;\n\t\t\t\tdestPos++;\n\t\t\t}\n\t\t}\n\t\tStringBuilder stringResultBuilder = new StringBuilder(result.length);\n\t\tfor (int i = result.length - 1; i >= 0; i--) {\n\t\t\tbyte digit = result[i];\n\t\t\tif (digit != 0 || stringResultBuilder.length() > 0) {\n\t\t\t\tstringResultBuilder.append((char) (digit + '0'));\n\t\t\t}\n\t\t}\n\t\treturn stringResultBuilder.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(longMult(\"18446744073709551616\",\n\t\t\t\t\"18446744073709551616\"));\n\t}\n}\n"}
{"id": 60247, "name": "Pell's equation", "VB": "Imports System.Numerics\n\nModule Module1\n    Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)\n        Dim t As BigInteger = a : a = b : b = b * c + t\n    End Sub\n\n    Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)\n        Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,\n            e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1\n        While True\n            y = r * z - y : z = (n - y * y) / z : r = (x + y) / z\n            Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)\n            If a * a - n * b * b = 1 Then Exit Sub\n        End While\n    End Sub\n\n    Sub Main()\n        Dim x As BigInteger, y As BigInteger\n        For Each n As Integer In {61, 109, 181, 277}\n            SolvePell(n, x, y)\n            Console.WriteLine(\"x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}\", n, x, y)\n        Next\n    End Sub\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PellsEquation {\n\n    public static void main(String[] args) {\n        NumberFormat format = NumberFormat.getInstance();\n        for ( int n : new int[] {61, 109, 181, 277, 8941} ) {\n            BigInteger[] pell = pellsEquation(n);\n            System.out.printf(\"x^2 - %3d * y^2 = 1 for:%n    x = %s%n    y = %s%n%n\", n,  format.format(pell[0]),  format.format(pell[1]));\n        }\n    }\n\n    private static final BigInteger[] pellsEquation(int n) {\n        int a0 = (int) Math.sqrt(n);\n        if ( a0*a0 == n ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid n = \" + n);\n        }\n        List<Integer> continuedFrac = continuedFraction(n);\n        int count = 0;\n        BigInteger ajm2 = BigInteger.ONE;\n        BigInteger ajm1 = new BigInteger(a0 + \"\");\n        BigInteger bjm2 = BigInteger.ZERO;\n        BigInteger bjm1 = BigInteger.ONE;\n        boolean stop = (continuedFrac.size() % 2 == 1);\n        if ( continuedFrac.size() == 2 ) {\n            stop = true;\n        }\n        while ( true ) {\n            count++;\n            BigInteger bn = new BigInteger(continuedFrac.get(count) + \"\");\n            BigInteger aj = bn.multiply(ajm1).add(ajm2);\n            BigInteger bj = bn.multiply(bjm1).add(bjm2);\n            if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {\n                return new BigInteger[] {aj, bj};\n            }\n            else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {\n                stop = true;\n            }\n            if ( count == continuedFrac.size()-1 ) {\n                count = 0;\n            }\n            ajm2 = ajm1;\n            ajm1 = aj;\n            bjm2 = bjm1;\n            bjm1 = bj;\n        }\n    }\n\n    private static final List<Integer> continuedFraction(int n) {\n        List<Integer> answer = new ArrayList<Integer>();\n        int a0 = (int) Math.sqrt(n);\n        answer.add(a0);\n        int a = -a0;\n        int aStart = a;\n        int b = 1;\n        int bStart = b;\n\n        while ( true ) {\n            \n            int[] values = iterateFrac(n, a, b);\n            answer.add(values[0]);\n            a = values[1];\n            b = values[2];\n            if (a == aStart && b == bStart) break;\n        }\n        return answer;\n    }\n    \n    \n    \n    \n    private static final int[] iterateFrac(int n, int a, int b) {\n        int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a));\n        int[] answer = new int[3];\n        answer[0] = x;\n        answer[1] = -(b * a + x *(n - a * a)) / b;\n        answer[2] = (n - a * a) / b;\n        return answer;\n    }\n\n\n}\n"}
{"id": 60248, "name": "Bulls and cows", "VB": "Option Explicit\n\nSub Main_Bulls_and_cows()\nDim strNumber As String, strInput As String, strMsg As String, strTemp As String\nDim boolEnd As Boolean\nDim lngCpt As Long\nDim i As Byte, bytCow As Byte, bytBull As Byte\nConst NUMBER_OF_DIGITS As Byte = 4\nConst MAX_LOOPS As Byte = 25 \n\n    strNumber = Create_Number(NUMBER_OF_DIGITS)\n    Do\n        bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1\n        If lngCpt > MAX_LOOPS Then strMsg = \"Max of loops... Sorry you loose!\": Exit Do\n        strInput = AskToUser(NUMBER_OF_DIGITS)\n        If strInput = \"Exit Game\" Then strMsg = \"User abort\": Exit Do\n        For i = 1 To Len(strNumber)\n            If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then\n                bytBull = bytBull + 1\n            ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then\n                bytCow = bytCow + 1\n            End If\n        Next i\n        If bytBull = Len(strNumber) Then\n            boolEnd = True: strMsg = \"You win in \" & lngCpt & \" loops!\"\n        Else\n            strTemp = strTemp & vbCrLf & \"With : \" & strInput & \" ,you have : \" & bytBull & \" bulls,\" & bytCow & \" cows.\"\n            MsgBox strTemp\n        End If\n    Loop While Not boolEnd\n    MsgBox strMsg\nEnd Sub\n\nFunction Create_Number(NbDigits As Byte) As String\nDim myColl As New Collection\nDim strTemp As String\nDim bytAlea As Byte\n\n    Randomize\n    Do\n        bytAlea = Int((Rnd * 9) + 1)\n        On Error Resume Next\n        myColl.Add CStr(bytAlea), CStr(bytAlea)\n        If Err <> 0 Then\n            On Error GoTo 0\n        Else\n            strTemp = strTemp & CStr(bytAlea)\n        End If\n    Loop While Len(strTemp) < NbDigits\n    Create_Number = strTemp\nEnd Function\n\nFunction AskToUser(NbDigits As Byte) As String\nDim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte\n\n    Do While Not boolGood\n        strIn = InputBox(\"Enter your number (\" & NbDigits & \" digits)\", \"Number\")\n        If StrPtr(strIn) = 0 Then strIn = \"Exit Game\": Exit Do\n        If strIn <> \"\" Then\n            If Len(strIn) = NbDigits Then\n                NbDiff = 0\n                For i = 1 To Len(strIn)\n                    If Len(Replace(strIn, Mid(strIn, i, 1), \"\")) < NbDigits - 1 Then\n                        NbDiff = 1\n                        Exit For\n                    End If\n                Next i\n                If NbDiff = 0 Then boolGood = True\n            End If\n        End If\n    Loop\n    AskToUser = strIn\nEnd Function\n", "Java": "import java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n"}
{"id": 60249, "name": "Sorting algorithms_Bubble sort", "VB": "  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n  sortable.Shuffle() \n  Dim swapped As Boolean\n  Do\n    Dim index, bound As Integer\n    bound = sortable.Ubound\n\n    While index < bound\n      If sortable(index) > sortable(index + 1) Then\n        Dim s As Integer = sortable(index)\n        sortable.Remove(index)\n        sortable.Insert(index + 1, s)\n        swapped = True\n      End If\n      index = index + 1\n    Wend\n    \n  Loop Until Not swapped\n\n", "Java": "public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {\n    boolean changed = false;\n    do {\n        changed = false;\n        for (int a = 0; a < comparable.length - 1; a++) {\n            if (comparable[a].compareTo(comparable[a + 1]) > 0) {\n                E tmp = comparable[a];\n                comparable[a] = comparable[a + 1];\n                comparable[a + 1] = tmp;\n                changed = true;\n            }\n        }\n    } while (changed);\n}\n"}
{"id": 60250, "name": "File input_output", "VB": "Sub WriteToFile(input As FolderItem, output As FolderItem)\n  Dim tis As TextInputStream\n  Dim tos As TextOutputStream\n  tis = tis.Open(input)\n  tos = tos.Create(output)\n  While Not tis.EOF\n    tos.WriteLine(tis.ReadLine)\n  Wend\n  tis.Close\n  tos.Close\nEnd Sub\n", "Java": "import java.io.*;\n\npublic class FileIODemo {\n  public static void main(String[] args) {\n    try {\n      FileInputStream in = new FileInputStream(\"input.txt\");\n      FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n      int c;\n      while ((c = in.read()) != -1) {\n        out.write(c);\n      }\n    } catch (FileNotFoundException e) {\n      e.printStackTrace();\n    } catch (IOException e){\n      e.printStackTrace();\n    }\n  }\n}\n"}
{"id": 60251, "name": "Arithmetic_Integer", "VB": "START:\nINPUT \"Enter two integers (a,b):\"; a!, b!\nIF a = 0 THEN END\nIF b = 0 THEN\n    PRINT \"Second integer is zero. Zero not allowed for Quotient or Remainder.\"\n    GOTO START\nEND IF\nPRINT\nPRINT \"             Sum = \"; a + b\nPRINT \"      Difference = \"; a - b\nPRINT \"         Product = \"; a * b\n\nPRINT \"Integer Quotient = \"; a \\ b, , \"* Rounds toward 0.\"\nPRINT \"       Remainder = \"; a MOD b, , \"* Sign matches first operand.\"\nPRINT \"  Exponentiation = \"; a ^ b\nPRINT\nINPUT \"Again? (y/N)\"; a$\nIF UCASE$(a$) = \"Y\" THEN CLS: GOTO START\nCLS\nEND\n", "Java": "import java.util.Scanner;\n\npublic class IntegerArithmetic {\n    public static void main(String[] args) {\n        \n        Scanner sc = new Scanner(System.in);\n        int a = sc.nextInt();\n        int b = sc.nextInt();\n\n        int sum = a + b;        \n        int difference = a - b; \n        int product = a * b;    \n        int division = a / b;   \n        int remainder = a % b;  \n\n        System.out.println(\"a + b = \" + sum);\n        System.out.println(\"a - b = \" + difference);\n        System.out.println(\"a * b = \" + product);\n        System.out.println(\"quotient of a / b = \" + division);   \n        System.out.println(\"remainder of a / b = \" + remainder);   \n    }\n}\n"}
{"id": 60252, "name": "Matrix transposition", "VB": "Function transpose(m As Variant) As Variant\n    transpose = WorksheetFunction.transpose(m)\nEnd Function\n", "Java": "import java.util.Arrays;\npublic class Transpose{\n       public static void main(String[] args){\n               double[][] 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}};\n               double[][] ans = new double[m[0].length][m.length];\n               for(int rows = 0; rows < m.length; rows++){\n                       for(int cols = 0; cols < m[0].length; cols++){\n                               ans[cols][rows] = m[rows][cols];\n                       }\n               }\n               for(double[] i:ans){\n                       System.out.println(Arrays.toString(i));\n               }\n       }\n}\n"}
{"id": 60253, "name": "Short-circuit evaluation", "VB": "Private Function a(i As Variant) As Boolean\n    Debug.Print \"a:  \"; i = 1,\n    a = i\nEnd Function\nPrivate Function b(j As Variant) As Boolean\n    Debug.Print \"b: \"; j = 1;\n    b = j\nEnd Function\nPublic Sub short_circuit()\n    Dim x As Boolean, y As Boolean\n    \n    Debug.Print \"=====AND=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print \"======OR=====\" & vbCrLf\n    For p = 0 To 1\n        For q = 0 To 1\n            If Not a(p) Then\n                x = b(q)\n            End If\n            Debug.Print \" = x\"\n        Next q\n        Debug.Print\n    Next p\n    Debug.Print\nEnd Sub\n", "Java": "module test\n    {\n    @Inject Console console;\n\n    static Boolean show(String name, Boolean value)\n        {\n        console.print($\"{name}()={value}\");\n        return value;\n        }\n\n    void run()\n        {\n        val a = show(\"a\", _);\n        val b = show(\"b\", _);\n\n        for (Boolean v1 : False..True)\n            {\n            for (Boolean v2 : False..True)\n                {\n                console.print($\"a({v1}) && b({v2}) == {a(v1) && b(v2)}\");\n                console.print();\n                console.print($\"a({v1}) || b({v2}) == {a(v1) || b(v2)}\");\n                console.print();\n                }\n            }\n        }\n    }\n"}
{"id": 60254, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 60255, "name": "Find limit of recursion", "VB": "Option Explicit\n\nSub Main()\n    Debug.Print \"The limit is : \" & Limite_Recursivite(0)\nEnd Sub\n\nFunction Limite_Recursivite(Cpt As Long) As Long\n    Cpt = Cpt + 1               \n    On Error Resume Next\n    Limite_Recursivite Cpt      \n    On Error GoTo 0\n    Limite_Recursivite = Cpt    \nEnd Function\n", "Java": "public class RecursionTest {\n\t\n    private static void recurse(int i) {\n        try {\n\t    recurse(i+1);\n\t} catch (StackOverflowError e) {\n\t    System.out.print(\"Recursion depth on this system is \" + i + \".\");\n\t}\n    }\n\t\n    public static void main(String[] args) {\n        recurse(0);\n    }\n}\n"}
{"id": 60256, "name": "Image noise", "VB": "Imports System.Drawing.Imaging\n\nPublic Class frmSnowExercise\n    Dim bRunning As Boolean = True\n\n    Private Sub Form1_Load(ByVal sender As System.Object,\n                           ByVal e As System.EventArgs) Handles MyBase.Load\n\n        \n        \n        \n        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _\n            Or ControlStyles.OptimizedDoubleBuffer, True)\n        UpdateStyles()\n\n        \n        \n        FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n        MaximizeBox = False\n\n        \n        \n        \n        \n        Width = 320 + Size.Width - ClientSize.Width\n        Height = 240 + Size.Height - ClientSize.Height\n\n        \n        \n        Show()\n        Activate()\n        Application.DoEvents()\n\n        \n        RenderLoop()\n\n        \n        Close()\n\n    End Sub\n\n    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n        \n        If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False\n    End Sub\n\n    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _\n            System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing\n        \n        \n        e.Cancel = bRunning\n        bRunning = False\n    End Sub\n\n    Private Sub RenderLoop()\n\n        Const cfPadding As Single = 5.0F\n\n        Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,\n                            PixelFormat.Format32bppArgb)\n        Dim g As Graphics = Graphics.FromImage(b)\n        Dim r As New Random(Now.Millisecond)\n        Dim oBMPData As BitmapData = Nothing\n        Dim oPixels() As Integer = Nothing\n        Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}\n        Dim oStopwatch As New Stopwatch\n        Dim fElapsed As Single = 0.0F\n        Dim iLoops As Integer = 0\n        Dim sFPS As String = \"0.0 FPS\"\n        Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)\n        Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -\n                      oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n\n        \n        g.Clear(Color.Black)\n\n        \n        oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n        \n        \n        \n        Array.Resize(oPixels, b.Width * b.Height)\n        Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,\n                                             oPixels, 0, oPixels.Length)\n        b.UnlockBits(oBMPData)\n        \n        Do\n            \n            \n            fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F\n            oStopwatch.Reset() : oStopwatch.Start()\n            \n            iLoops += 1\n            If fElapsed >= 1.0F Then\n                \n                \n                \n                \n                \n                \n                \n                sFPS = (iLoops / fElapsed).ToString(\"0.0\") & \" FPS\"\n                oFPSSize = g.MeasureString(sFPS, Font)\n                oFPSBG = New RectangleF(ClientSize.Width - cfPadding -\n                    oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)\n                \n                \n                fElapsed -= 1.0F\n                iLoops = 0\n            End If\n\n            \n            For i As Integer = 0 To oPixels.GetUpperBound(0)\n                oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))\n            Next\n\n            \n            oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),\n                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n            \n            Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,\n                                                 oPixels.Length)\n            b.UnlockBits(oBMPData)\n\n            \n            g.FillRectangle(Brushes.Black, oFPSBG)\n            \n            g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)\n\n            \n            BackgroundImage = b\n            Invalidate(ClientRectangle)\n\n            \n            Application.DoEvents()\n        Loop While bRunning\n\n    End Sub\nEnd Class\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.image.*;\nimport java.util.Arrays;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class ImageNoise {\n    int framecount = 0;\n    int fps = 0;\n    BufferedImage image;\n    Kernel kernel;\n    ConvolveOp cop;\n    JFrame frame = new JFrame(\"Java Image Noise\");\n\n    JPanel panel = new JPanel() {\n        private int show_fps = 0; \n        private MouseAdapter ma = new MouseAdapter() {\n            @Override\n            public void mouseClicked(MouseEvent e) {\n                show_fps = (show_fps + 1) % 3;\n            }\n        };\n        {addMouseListener(ma);}\n\n        @Override\n        public Dimension getPreferredSize() {\n            return new Dimension(320, 240);\n        }\n\n        @Override\n        @SuppressWarnings(\"fallthrough\")\n        public void paintComponent(Graphics g1) {\n            Graphics2D g = (Graphics2D) g1;\n            drawNoise();\n            g.drawImage(image, 0, 0, null);\n\n            switch (show_fps) {\n            case 0: \n                \n                int xblur = getWidth() - 130, yblur = getHeight() - 32;\n                BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32);\n                BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(),\n                                                     BufferedImage.TYPE_BYTE_GRAY);\n                cop.filter(bc, bs);\n                g.drawImage(bs, xblur, yblur , null);\n            case 1: \n                \n                g.setColor(Color.RED);\n                g.setFont(new Font(\"Monospaced\", Font.BOLD, 20));\n                g.drawString(\"FPS: \" + fps, getWidth() - 120, getHeight() - 10);\n            }\n            framecount++;\n        }\n    };\n    \n    \n    Timer repainter = new Timer(1, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            panel.repaint();\n        }\n    });\n    \n    \n    Timer framerateChecker = new Timer(1000, new ActionListener() {\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            fps = framecount;\n            framecount = 0;\n        }\n    });\n    \n    public ImageNoise() {\n        \n        float[] vals = new float[121];\n        Arrays.fill(vals, 1/121f);\n        kernel = new Kernel(11, 11, vals);\n        cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);\n        \n        \n        frame.add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setVisible(true);\n        repainter.start();\n        framerateChecker.start();\n    }\n\n    void drawNoise() {\n        int w = panel.getWidth(), h = panel.getHeight();\n        \n        \n        if (null == image || image.getWidth() != w || image.getHeight() != h) {\n            image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);\n        }\n        Random rand = new Random();\n        int[] data = new int[w * h];\n        \n        for (int x = 0; x < w * h / 32; x++) {\n            int r = rand.nextInt();\n            for (int i = 0; i < 32; i++) {\n                data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE;\n                r >>>= 1;\n            }\n        }\n        \n        image.getRaster().setPixels(0, 0, w, h, data);\n    }\n    \n    public static void main(String[] args) {\n        \n        SwingUtilities.invokeLater(new Runnable() {\n            @Override\n            public void run() {\n                ImageNoise i = new ImageNoise();\n            }\n        });\n    }\n}\n"}
{"id": 60257, "name": "Perfect numbers", "VB": "Private Function Factors(x As Long) As String\n    Application.Volatile\n    Dim i As Long\n    Dim cooresponding_factors As String\n    Factors = 1\n    corresponding_factors = x\n    For i = 2 To Sqr(x)\n        If x Mod i = 0 Then\n            Factors = Factors & \", \" & i\n            If i <> x / i Then corresponding_factors = x / i & \", \" & corresponding_factors\n        End If\n    Next i\n    If x <> 1 Then Factors = Factors & \", \" & corresponding_factors\nEnd Function\nPrivate Function is_perfect(n As Long)\n    fs = Split(Factors(n), \", \")\n    Dim f() As Long\n    ReDim f(UBound(fs))\n    For i = 0 To UBound(fs)\n        f(i) = Val(fs(i))\n    Next i\n    is_perfect = WorksheetFunction.Sum(f) - n = n\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    For i = 2 To 100000\n        If is_perfect(i) Then Debug.Print i\n    Next i\nEnd Sub\n", "Java": "public static boolean perf(int n){\n\tint sum= 0;\n\tfor(int i= 1;i < n;i++){\n\t\tif(n % i == 0){\n\t\t\tsum+= i;\n\t\t}\n\t}\n\treturn sum == n;\n}\n"}
{"id": 60258, "name": "Sorting algorithms_Bead sort", "VB": "Option Base 1\n\nPrivate Function sq_add(arr As Variant, x As Double) As Variant\n    Dim res() As Variant\n    ReDim res(UBound(arr))\n    For i = 1 To UBound(arr)\n        res(i) = arr(i) + x\n    Next i\n    sq_add = res\nEnd Function\n\nPrivate Function beadsort(ByVal a As Variant) As Variant\n    Dim poles() As Variant\n    ReDim poles(WorksheetFunction.Max(a))\n    For i = 1 To UBound(a)\n        For j = 1 To a(i)\n            poles(j) = poles(j) + 1\n        Next j\n    Next i\n    For j = 1 To UBound(a)\n        a(j) = 0\n    Next j\n    For i = 1 To UBound(poles)\n        For j = 1 To poles(i)\n            a(j) = a(j) + 1\n        Next j\n    Next i\n    beadsort = a\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), \", \")\nEnd Sub\n", "Java": "public class BeadSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tBeadSort now=new BeadSort();\n\t\tint[] arr=new int[(int)(Math.random()*11)+5];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tarr[i]=(int)(Math.random()*10);\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tint[] sort=now.beadSort(arr);\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(sort);\n\t}\n\tint[] beadSort(int[] arr)\n\t{\n\t\tint max=a[0];\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t\n\t\t\n\t\tchar[][] grid=new char[arr.length][max];\n\t\tint[] levelcount=new int[max];\n\t\tfor(int i=0;i<max;i++)\n\t\t{\n\t\t\tlevelcount[i]=0;\n\t\t\tfor(int j=0;j<arr.length;j++)\n\t\t\t\tgrid[j][i]='_';\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint num=arr[i];\n\t\t\tfor(int j=0;num>0;j++)\n\t\t\t{\n\t\t\t\tgrid[levelcount[j]++][j]='*';\n\t\t\t\tnum--;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t\tdisplay2D(grid);\n\t\t\n\t\tint[] sorted=new int[arr.length];\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tint putt=0;\n\t\t\tfor(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)\n\t\t\t\tputt++;\n\t\t\tsorted[i]=putt;\n\t\t}\n\t\t\n\t\treturn sorted;\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\tvoid display1D(char[] 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\tvoid display2D(char[][] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tdisplay1D(arr[i]);\n\t\tSystem.out.println();\n\t}\n}\n"}
{"id": 60259, "name": "Arbitrary-precision integers (included)", "VB": "Imports System.Console\nImports BI = System.Numerics.BigInteger \n\nModule Module1\n\n    Dim Implems() As String = {\"Built-In\", \"Recursive\", \"Iterative\"},\n        powers() As Integer = {5, 4, 3, 2}\n\n    Function intPowR(val As BI, exp As BI) As BI\n        If exp = 0 Then Return 1\n        Dim ne As BI, vs As BI = val * val\n        If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)\n        ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val\n    End Function\n\n    Function intPowI(val As BI, exp As BI) As BI\n        intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val\n            val *= val : exp >>= 1 : End While\n    End Function\n\n    Sub DoOne(title As String, p() As Integer)\n        Dim st As DateTime = DateTime.Now, res As BI, resStr As String\n        Select Case (Array.IndexOf(Implems, title))\n            Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))\n            Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))\n            Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))\n        End Select : resStr = res.ToString()\n        Dim et As TimeSpan = DateTime.Now - st\n        Debug.Assert(resStr.Length = 183231)\n        Debug.Assert(resStr.StartsWith(\"62060698786608744707\"))\n        Debug.Assert(resStr.EndsWith(\"92256259918212890625\"))\n        WriteLine(\"n = {0}\", String.Join(\"^\", powers))\n        WriteLine(\"n = {0}...{1}\", resStr.Substring(0, 20),  resStr.Substring(resStr.Length - 20, 20))\n        WriteLine(\"n digits = {0}\", resStr.Length)\n        WriteLine(\"{0} elasped: {1} milliseconds.\" & vblf, title, et.TotalMilliseconds)\n    End Sub\n\n    Sub Main()\n        For Each itm As String in Implems : DoOne(itm, powers) : Next\n        If Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\n\nclass IntegerPower {\n    public static void main(String[] args) {\n        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());\n        String str = power.toString();\n        int len = str.length();\n        System.out.printf(\"5**4**3**2 = %s...%s and has %d digits%n\",\n                str.substring(0, 20), str.substring(len - 20), len);\n    }\n}\n"}
{"id": 60260, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 60261, "name": "Draw a sphere", "VB": "shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n\n\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j / 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n", "Java": "using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] /= len;\n            v[1] /= len;\n            v[2] /= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 60262, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 60263, "name": "Least common multiple", "VB": "Function gcd(u As Long, v As Long) As Long\n    Dim t As Long\n    Do While v\n        t = u\n        u = v\n        v = t Mod v\n    Loop\n    gcd = u\nEnd Function\nFunction lcm(m As Long, n As Long) As Long\n    lcm = Abs(m * n) / gcd(m, n)\nEnd Function\n", "Java": "import java.util.Scanner;\n\npublic class LCM{\n   public static void main(String[] args){\n      Scanner aScanner = new Scanner(System.in);\n   \n      \n      System.out.print(\"Enter the value of m:\");\n      int m = aScanner.nextInt();\n      System.out.print(\"Enter the value of n:\");\n      int n = aScanner.nextInt();\n      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n      \n      if (lcm == 0) {\n         int mm = m, nn = n;\n         while (mm != nn) {\n             while (mm < nn) { mm += m; }\n             while (nn < mm) { nn += n; }\n         }  \n         lcm = mm;\n      }\n      System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n   }\n}\n"}
{"id": 60264, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 60265, "name": "Loops_Break", "VB": "Public Sub LoopsBreak()\n    Dim value As Integer\n    Randomize\n    Do While True\n        value = Int(20 * Rnd)\n        Debug.Print value\n        If value = 10 Then Exit Do\n        Debug.Print Int(20 * Rnd)\n    Loop\nEnd Sub\n", "Java": "import java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n    int a = rand.nextInt(20);\n    System.out.println(a);\n    if(a == 10) break;\n    int b = rand.nextInt(20);\n    System.out.println(b);\n}\n"}
{"id": 60266, "name": "Water collected between towers", "VB": "\nModule Module1\n    Sub Main(Args() As String)\n        Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1  \n        Dim wta As Integer()() = {                       \n            New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n            New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n        Dim blk As String,                   \n            lf As String = vbLf,      \n            tb = \"██\", wr = \"≈≈\", mt = \"  \"    \n        For i As Integer = 0 To wta.Length - 1\n            Dim bpf As Integer                    \n            blk = \"\"\n            Do\n                bpf = 0 : Dim floor As String = \"\"  \n                For j As Integer = 0 To wta(i).Length - 1\n                    If wta(i)(j) > 0 Then      \n                        floor &= tb : wta(i)(j) -= 1 : bpf += 1    \n                    Else  \n                        floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n                    End If\n                Next\n                If bpf > 0 Then blk = floor & lf & blk \n            Loop Until bpf = 0                       \n            \n            While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n            While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n            \n            If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n            \n            Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n                                     (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n        Next\n    End Sub\nEnd Module\n", "Java": "public class WaterBetweenTowers {\n    public static void main(String[] args) {\n        int i = 1;\n        int[][] tba = new int[][]{\n            new int[]{1, 5, 3, 7, 2},\n            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n            new int[]{5, 5, 5, 5},\n            new int[]{5, 6, 7, 8},\n            new int[]{8, 7, 7, 6},\n            new int[]{6, 7, 10, 7, 6}\n        };\n\n        for (int[] tea : tba) {\n            int rht, wu = 0, bof;\n            do {\n                for (rht = tea.length - 1; rht >= 0; rht--) {\n                    if (tea[rht] > 0) {\n                        break;\n                    }\n                }\n\n                if (rht < 0) {\n                    break;\n                }\n\n                bof = 0;\n                for (int col = 0; col <= rht; col++) {\n                    if (tea[col] > 0) {\n                        tea[col]--;\n                        bof += 1;\n                    } else if (bof > 0) {\n                        wu++;\n                    }\n                }\n                if (bof < 2) {\n                    break;\n                }\n            } while (true);\n\n            System.out.printf(\"Block %d\", i++);\n            if (wu == 0) {\n                System.out.print(\" does not hold any\");\n            } else {\n                System.out.printf(\" holds %d\", wu);\n            }\n            System.out.println(\" water units.\");\n        }\n    }\n}\n"}
{"id": 60267, "name": "Square-free integers", "VB": "Module Module1\n\n    Function Sieve(limit As Long) As List(Of Long)\n        Dim primes As New List(Of Long) From {2}\n        Dim c(limit + 1) As Boolean\n        Dim p = 3L\n        While True\n            Dim p2 = p * p\n            If p2 > limit Then\n                Exit While\n            End If\n            For i = p2 To limit Step 2 * p\n                c(i) = True\n            Next\n            While True\n                p += 2\n                If Not c(p) Then\n                    Exit While\n                End If\n            End While\n        End While\n        For i = 3 To limit Step 2\n            If Not c(i) Then\n                primes.Add(i)\n            End If\n        Next\n        Return primes\n    End Function\n\n    Function SquareFree(from As Long, to_ As Long) As List(Of Long)\n        Dim limit = CType(Math.Sqrt(to_), Long)\n        Dim primes = Sieve(limit)\n        Dim results As New List(Of Long)\n\n        Dim i = from\n        While i <= to_\n            For Each p In primes\n                Dim p2 = p * p\n                If p2 > i Then\n                    Exit For\n                End If\n                If (i Mod p2) = 0 Then\n                    i += 1\n                    Continue While\n                End If\n            Next\n            results.Add(i)\n            i += 1\n        End While\n\n        Return results\n    End Function\n\n    ReadOnly TRILLION As Long = 1_000_000_000_000\n\n    Sub Main()\n        Console.WriteLine(\"Square-free integers from 1 to 145:\")\n        Dim sf = SquareFree(1, 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 20) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,4}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Square-free integers from {0} to {1}:\", TRILLION, TRILLION + 145)\n        sf = SquareFree(TRILLION, TRILLION + 145)\n        For index = 0 To sf.Count - 1\n            Dim v = sf(index)\n            If index > 1 AndAlso (index Mod 5) = 0 Then\n                Console.WriteLine()\n            End If\n            Console.Write(\"{0,14}\", v)\n        Next\n        Console.WriteLine()\n        Console.WriteLine()\n\n        Console.WriteLine(\"Number of square-free integers:\")\n        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}\n            Console.WriteLine(\"   from 1 to {0} = {1}\", to_, SquareFree(1, to_).Count)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SquareFree\n{\n    private static List<Long> sieve(long limit) {\n        List<Long> primes = new ArrayList<Long>();\n        primes.add(2L);\n        boolean[] c = new boolean[(int)limit + 1]; \n        \n        long p = 3;\n        for (;;) {\n            long p2 = p * p;\n            if (p2 > limit) break;\n            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;\n            for (;;) {\n                p += 2;\n                if (!c[(int)p]) break;\n            }\n        }\n        for (long i = 3; i <= limit; i += 2) {\n            if (!c[(int)i]) primes.add(i);\n        }\n        return primes;\n    }\n\n    private static List<Long> squareFree(long from, long to) {\n        long limit = (long)Math.sqrt((double)to);\n        List<Long> primes = sieve(limit);\n        List<Long> results = new ArrayList<Long>();\n\n        outer: for (long i = from; i <= to; i++) {\n            for (long p : primes) {\n                long p2 = p * p;\n                if (p2 > i) break;\n                if (i % p2 == 0) continue outer;\n            }\n            results.add(i);\n        }\n        return results;\n    }\n\n    private final static long TRILLION = 1000000000000L;\n\n    public static void main(String[] args) {\n        System.out.println(\"Square-free integers from 1 to 145:\");\n        List<Long> sf = squareFree(1, 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 20 == 0) {\n                System.out.println();\n            }\n            System.out.printf(\"%4d\", sf.get(i));\n        }\n\n        System.out.print(\"\\n\\nSquare-free integers\");\n        System.out.printf(\" from %d to %d:\\n\", TRILLION, TRILLION + 145);\n        sf = squareFree(TRILLION, TRILLION + 145);\n        for (int i = 0; i < sf.size(); i++) {\n            if (i > 0 && i % 5 == 0) System.out.println();\n            System.out.printf(\"%14d\", sf.get(i));\n        }\n\n        System.out.println(\"\\n\\nNumber of square-free integers:\\n\");\n        long[] tos = {100, 1000, 10000, 100000, 1000000};\n        for (long to : tos) {\n            System.out.printf(\"  from %d to %d = %d\\n\", 1, to, squareFree(1, to).size());\n        }\n    }\n}\n"}
{"id": 60268, "name": "Jaro similarity", "VB": "Option Explicit\n\nFunction JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double\nDim dummyChar, match1, match2 As String\nDim i, f, t, j, m, l, s1, s2, limit As Integer\n\ni = 1\nDo\n    dummyChar = Chr(i)\n    i = i + 1\nLoop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0\n\ns1 = Len(text1)\ns2 = Len(text2)\nlimit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)\nmatch1 = String(s1, dummyChar)\nmatch2 = String(s2, dummyChar)\n\nFor l = 1 To WorksheetFunction.Min(4, s1, s2)\n    If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For\nNext l\nl = l - 1\n\nFor i = 1 To s1\n    f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)\n    t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)\n    j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)\n    If j > 0 Then\n        m = m + 1\n        text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)\n        match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)\n        match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)\n    End If\nNext i\nmatch1 = Replace(match1, dummyChar, \"\", 1, -1, vbTextCompare)\nmatch2 = Replace(match2, dummyChar, \"\", 1, -1, vbTextCompare)\nt = 0\nFor i = 1 To m\n    If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1\nNext i\n\nJaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3\nJaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)\nEnd Function\n", "Java": "public class JaroDistance {\n    public static double jaro(String s, String t) {\n        int s_len = s.length();\n        int t_len = t.length();\n\n        if (s_len == 0 && t_len == 0) return 1;\n\n        int match_distance = Integer.max(s_len, t_len) / 2 - 1;\n\n        boolean[] s_matches = new boolean[s_len];\n        boolean[] t_matches = new boolean[t_len];\n\n        int matches = 0;\n        int transpositions = 0;\n\n        for (int i = 0; i < s_len; i++) {\n            int start = Integer.max(0, i-match_distance);\n            int end = Integer.min(i+match_distance+1, t_len);\n\n            for (int j = start; j < end; j++) {\n                if (t_matches[j]) continue;\n                if (s.charAt(i) != t.charAt(j)) continue;\n                s_matches[i] = true;\n                t_matches[j] = true;\n                matches++;\n                break;\n            }\n        }\n\n        if (matches == 0) return 0;\n\n        int k = 0;\n        for (int i = 0; i < s_len; i++) {\n            if (!s_matches[i]) continue;\n            while (!t_matches[k]) k++;\n            if (s.charAt(i) != t.charAt(k)) transpositions++;\n            k++;\n        }\n\n        return (((double)matches / s_len) +\n                ((double)matches / t_len) +\n                (((double)matches - transpositions/2.0) / matches)) / 3.0;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(jaro(   \"MARTHA\",      \"MARHTA\"));\n        System.out.println(jaro(    \"DIXON\",    \"DICKSONX\"));\n        System.out.println(jaro(\"JELLYFISH\",  \"SMELLYFISH\"));\n    }\n}\n"}
{"id": 60269, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 60270, "name": "Fairshare between two and more", "VB": "Module Module1\n\n    Function Turn(base As Integer, n As Integer) As Integer\n        Dim sum = 0\n        While n <> 0\n            Dim re = n Mod base\n            n \\= base\n            sum += re\n        End While\n        Return sum Mod base\n    End Function\n\n    Sub Fairshare(base As Integer, count As Integer)\n        Console.Write(\"Base {0,2}:\", base)\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            Console.Write(\" {0,2}\", t)\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Sub TurnCount(base As Integer, count As Integer)\n        Dim cnt(base) As Integer\n        For i = 1 To base\n            cnt(i - 1) = 0\n        Next\n\n        For i = 1 To count\n            Dim t = Turn(base, i - 1)\n            cnt(t) += 1\n        Next\n\n        Dim minTurn = Integer.MaxValue\n        Dim maxTurn = Integer.MinValue\n        Dim portion = 0\n        For i = 1 To base\n            Dim num = cnt(i - 1)\n            If num > 0 Then\n                portion += 1\n            End If\n            If num < minTurn Then\n                minTurn = num\n            End If\n            If num > maxTurn Then\n                maxTurn = num\n            End If\n        Next\n\n        Console.Write(\"  With {0} people: \", base)\n        If 0 = minTurn Then\n            Console.WriteLine(\"Only {0} have a turn\", portion)\n        ElseIf minTurn = maxTurn Then\n            Console.WriteLine(minTurn)\n        Else\n            Console.WriteLine(\"{0} or {1}\", minTurn, maxTurn)\n        End If\n    End Sub\n\n    Sub Main()\n        Fairshare(2, 25)\n        Fairshare(3, 25)\n        Fairshare(5, 25)\n        Fairshare(11, 25)\n\n        Console.WriteLine(\"How many times does each get a turn in 50000 iterations?\")\n        TurnCount(191, 50000)\n        TurnCount(1377, 50000)\n        TurnCount(49999, 50000)\n        TurnCount(50000, 50000)\n        TurnCount(50001, 50000)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class FairshareBetweenTwoAndMore {\n\n    public static void main(String[] args) {\n        for ( int base : Arrays.asList(2, 3, 5, 11) ) {\n            System.out.printf(\"Base %d = %s%n\", base, thueMorseSequence(25, base));\n        }\n    }\n    \n    private static List<Integer> thueMorseSequence(int terms, int base) {\n        List<Integer> sequence = new ArrayList<Integer>();\n        for ( int i = 0 ; i < terms ; i++ ) {\n            int sum = 0;\n            int n = i;\n            while ( n > 0 ) {\n                \n                sum += n % base;\n                n /= base;\n            }\n            \n            sequence.add(sum % base);\n        }\n        return sequence;\n    }\n\n}\n"}
{"id": 60271, "name": "Parsing_Shunting-yard algorithm", "VB": "Module Module1\n    Class SymbolType\n        Public ReadOnly symbol As String\n        Public ReadOnly precedence As Integer\n        Public ReadOnly rightAssociative As Boolean\n\n        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)\n            Me.symbol = symbol\n            Me.precedence = precedence\n            Me.rightAssociative = rightAssociative\n        End Sub\n    End Class\n\n    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From\n    {\n        {\"^\", New SymbolType(\"^\", 4, True)},\n        {\"*\", New SymbolType(\"*\", 3, False)},\n        {\"/\", New SymbolType(\"/\", 3, False)},\n        {\"+\", New SymbolType(\"+\", 2, False)},\n        {\"-\", New SymbolType(\"-\", 2, False)}\n    }\n\n    Function ToPostfix(infix As String) As String\n        Dim tokens = infix.Split(\" \")\n        Dim stack As New Stack(Of String)\n        Dim output As New List(Of String)\n\n        Dim Print = Sub(action As String) Console.WriteLine(\"{0,-4} {1,-18} {2}\", action + \":\", $\"stack[ {String.Join(\" \", stack.Reverse())} ]\", $\"out[ {String.Join(\" \", output)} ]\")\n\n        For Each token In tokens\n            Dim iv As Integer\n            Dim op1 As SymbolType\n            Dim op2 As SymbolType\n            If Integer.TryParse(token, iv) Then\n                output.Add(token)\n                Print(token)\n            ElseIf Operators.TryGetValue(token, op1) Then\n                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)\n                    Dim c = op1.precedence.CompareTo(op2.precedence)\n                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then\n                        output.Add(stack.Pop())\n                    Else\n                        Exit While\n                    End If\n                End While\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \"(\" Then\n                stack.Push(token)\n                Print(token)\n            ElseIf token = \")\" Then\n                Dim top = \"\"\n                While stack.Count > 0\n                    top = stack.Pop()\n                    If top <> \"(\" Then\n                        output.Add(top)\n                    Else\n                        Exit While\n                    End If\n                End While\n                If top <> \"(\" Then\n                    Throw New ArgumentException(\"No matching left parenthesis.\")\n                End If\n                Print(token)\n            End If\n        Next\n        While stack.Count > 0\n            Dim top = stack.Pop()\n            If Not Operators.ContainsKey(top) Then\n                Throw New ArgumentException(\"No matching right parenthesis.\")\n            End If\n            output.Add(top)\n        End While\n        Print(\"pop\")\n        Return String.Join(\" \", output)\n    End Function\n\n    Sub Main()\n        Dim infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n        Console.WriteLine(ToPostfix(infix))\n    End Sub\n\nEnd Module\n", "Java": "import java.util.Stack;\n\npublic class ShuntingYard {\n\n    public static void main(String[] args) {\n        String infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n        System.out.printf(\"infix:   %s%n\", infix);\n        System.out.printf(\"postfix: %s%n\", infixToPostfix(infix));\n    }\n\n    static String infixToPostfix(String infix) {\n        \n        final String ops = \"-+/*^\";\n\n        StringBuilder sb = new StringBuilder();\n        Stack<Integer> s = new Stack<>();\n\n        for (String token : infix.split(\"\\\\s\")) {\n            if (token.isEmpty())\n                continue;\n            char c = token.charAt(0);\n            int idx = ops.indexOf(c);\n\n            \n            if (idx != -1) {\n                if (s.isEmpty())\n                    s.push(idx);\n          \n                else {\n                    while (!s.isEmpty()) {\n                        int prec2 = s.peek() / 2;\n                        int prec1 = idx / 2;\n                        if (prec2 > prec1 || (prec2 == prec1 && c != '^'))\n                            sb.append(ops.charAt(s.pop())).append(' ');\n                        else break;\n                    }\n                    s.push(idx);\n                }\n            } \n            else if (c == '(') {\n                s.push(-2); \n            } \n            else if (c == ')') {\n                \n                while (s.peek() != -2)\n                    sb.append(ops.charAt(s.pop())).append(' ');\n                s.pop();\n            }\n            else {\n                sb.append(token).append(' ');\n            }\n        }\n        while (!s.isEmpty())\n            sb.append(ops.charAt(s.pop())).append(' ');\n        return sb.toString();\n    }\n}\n"}
{"id": 60272, "name": "Prime triangle", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\n\nModule vMain\n\n    Public Const maxNumber As Integer = 20 \n    Dim prime(2 * maxNumber) As Boolean    \n\n    \n    Public Function countArrangements(ByVal n As Integer) As Integer\n        If n < 2 Then \n            Return 0\n        ElseIf n < 4 Then \n            \n            For i As Integer = 1 To n\n                Console.Out.Write(i.ToString.PadLeft(3))\n            Next i\n            Console.Out.WriteLine()\n            Return 1\n        Else\n            \n            Dim printSolution As Boolean = true\n            Dim used(n) As Boolean\n            Dim number(n) As Integer\n            \n            \n            For i As Integer = 0 To n - 1\n                number(i) = i Mod 2\n            Next i\n            used(1) = True\n            number(n) = n\n            used(n) = True\n            \n            Dim count As Integer = 0\n            Dim p As Integer = 2\n            Do While p > 0\n                Dim p1 As Integer = number(p - 1)\n                Dim current As Integer = number(p)\n                Dim [next] As Integer = current + 2\n                Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))\n                    [next] += 2\n                Loop\n                If [next] >= n Then\n                    [next] = 0\n                End If\n                If p = n - 1 Then\n                    \n                    \n                    If [next] <> 0 Then\n                        \n                        If prime([next] + n) Then\n                            \n                            count += 1\n                            If printSolution Then\n                                For i As Integer = 1 To n - 2\n                                     Console.Out.Write(number(i).ToString.PadLeft(3))\n                                Next i\n                                Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))\n                                printSolution = False\n                            End If\n                        End If\n                        [next] = 0\n                    End If\n                    \n                    p -= 1\n                    \n                End If\n                If [next] <> 0 Then\n                    \n                    used(current) = False\n                    used([next]) = True\n                    number(p) = [next]\n                    \n                    p += 1\n                ElseIf p <= 2 Then\n                    \n                    p = 0\n                Else\n                    \n                    used(number(p)) = False\n                    number(p) = p Mod 2\n                    p -= 1\n                End If\n            Loop\n            Return count\n        End If\n    End Function\n\n    Public Sub Main\n        prime(2) = True\n        For i As Integer = 3 To UBound(prime) Step  2\n            prime(i) = True\n        Next i\n        For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2\n            If prime(i) Then\n                For s As Integer = i * i To Ubound(prime) Step i + i\n                    prime(s) = False\n                Next s\n            End If\n        Next i\n\n        Dim  arrangements(maxNumber) As Integer\n        For n As Integer = 2 To UBound(arrangements)\n            arrangements(n) = countArrangements(n)\n        Next n\n        For n As Integer = 2 To UBound(arrangements)\n            Console.Out.Write(\" \" & arrangements(n))\n        Next n\n        Console.Out.WriteLine()\n\n    End Sub\n\nEnd Module\n", "Java": "public class PrimeTriangle {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (findRow(a, 0, i))\n                printRow(a);                \n        }\n        System.out.println();\n        StringBuilder s = new StringBuilder();\n        for (int i = 2; i <= 20; ++i) {\n            int[] a = new int[i];\n            for (int j = 0; j < i; ++j)\n                a[j] = j + 1;\n            if (i > 2)\n                s.append(\" \");\n            s.append(countRows(a, 0, i));\n        }\n        System.out.println(s);\n        long finish = System.currentTimeMillis();\n        System.out.printf(\"\\nElapsed time: %d milliseconds\\n\", finish - start);\n    }\n\n    private static void printRow(int[] a) {\n        for (int i = 0; i < a.length; ++i) {\n            if (i != 0)\n                System.out.print(\" \");\n            System.out.printf(\"%2d\", a[i]);\n        }\n        System.out.println();\n    }\n\n    private static boolean findRow(int[] a, int start, int length) {\n        if (length == 2)\n            return isPrime(a[start] + a[start + 1]);\n        for (int i = 1; i + 1 < length; i += 2) {\n            if (isPrime(a[start] + a[start + i])) {\n                swap(a, start + i, start + 1);\n                if (findRow(a, start + 1, length - 1))\n                    return true;\n                swap(a, start + i, start + 1);\n            }\n        }\n        return false;\n    }\n\n    private static int countRows(int[] a, int start, int length) {\n        int count = 0;\n        if (length == 2) {\n            if (isPrime(a[start] + a[start + 1]))\n                ++count;\n        } else {\n            for (int i = 1; i + 1 < length; i += 2) {\n                if (isPrime(a[start] + a[start + i])) {\n                    swap(a, start + i, start + 1);\n                    count += countRows(a, start + 1, length - 1);\n                    swap(a, start + i, start + 1);\n                }\n            }\n        }\n        return count;\n    }\n\n    private static void swap(int[] a, int i, int j) {\n        int tmp = a[i];\n        a[i] = a[j];\n        a[j] = tmp;\n    }\n\n    private static boolean isPrime(int n) {\n        return ((1L << n) & 0x28208a20a08a28acL) != 0;\n    }\n}\n"}
{"id": 60273, "name": "Trabb Pardo–Knuth algorithm", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 60274, "name": "Trabb Pardo–Knuth algorithm", "VB": "Function tpk(s)\n\tarr = Split(s,\" \")\n\tFor i = UBound(arr) To 0 Step -1\n\t\tn = fx(CDbl(arr(i)))\n\t\tIf  n > 400 Then\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = OVERFLOW\"\n\t\tElse\n\t\t\tWScript.StdOut.WriteLine arr(i) & \" = \" & n\n\t\tEnd If\n\tNext\nEnd Function\n\nFunction fx(x)\n\tfx = Sqr(Abs(x))+5*x^3\nEnd Function\n\n\nWScript.StdOut.Write \"Please enter a series of numbers:\"\nlist = WScript.StdIn.ReadLine\ntpk(list)\n", "Java": "\nimport java.util.*;\nimport java.io.*; \n\npublic class TPKA {\n\tpublic static void main(String... args) {\n\t\tdouble[] input = new double[11];\n\t\tdouble userInput = 0.0;\n\t\tScanner in = new Scanner(System.in);\n\t\tfor(int i = 0; i < 11; i++) {\n\t\t\tSystem.out.print(\"Please enter a number: \");\n\t\t\tString s = in.nextLine();\n\t\t\ttry {\n\t\t\t\tuserInput = Double.parseDouble(s);\n\t\t\t} catch (NumberFormatException e) { \n\t\t\t\tSystem.out.println(\"You entered invalid input, exiting\");\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t\tinput[i] = userInput;\n\t\t}\n\t\tfor(int j = 10; j >= 0; j--) {\n\t\t\tdouble x = input[j]; double y = f(x);\n\t\t\tif( y < 400.0) {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %.2f\\n\", x, y);\n\t\t\t} else {\n\t\t\t\tSystem.out.printf(\"f( %.2f ) = %s\\n\", x, \"TOO LARGE\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static double f(double x) {\n\t\treturn Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));\n\t}\n}\n"}
{"id": 60275, "name": "Middle three digits", "VB": "Option Explicit\n\nSub Main_Middle_three_digits()\nDim Numbers, i&\n    Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _\n    100, -12345, 1, 2, -1, -10, 2002, -2002, 0)\n    For i = 0 To 16\n        Debug.Print Numbers(i) & \" Return : \" & Middle3digits(CStr(Numbers(i)))\n    Next\nEnd Sub\n\nFunction Middle3digits(strNb As String) As String\n    If Left(strNb, 1) = \"-\" Then strNb = Right(strNb, Len(strNb) - 1)\n    If Len(strNb) < 3 Then\n        Middle3digits = \"Error ! Number of digits must be >= 3\"\n    ElseIf Len(strNb) Mod 2 = 0 Then\n        Middle3digits = \"Error ! Number of digits must be odd\"\n    Else\n        Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)\n    End If\nEnd Function\n", "Java": "public class MiddleThreeDigits {\n\n    public static void main(String[] args) {\n        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,\n            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};\n\n        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,\n            Integer.MAX_VALUE};\n\n        for (long n : passing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n\n        for (int n : failing)\n            System.out.printf(\"middleThreeDigits(%s): %s\\n\", n, middleThreeDigits(n));\n    }\n\n    public static <T> String middleThreeDigits(T n) {\n        String s = String.valueOf(n);\n        if (s.charAt(0) == '-')\n            s = s.substring(1);\n        int len = s.length();\n        if (len < 3 || len % 2 == 0)\n            return \"Need odd and >= 3 digits\";\n        int mid = len / 2;\n        return s.substring(mid - 1, mid + 2);\n    }\n}\n"}
{"id": 60276, "name": "Odd word problem", "VB": "Private Function OddWordFirst(W As String) As String\nDim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String\n   count = 1\n   Do\n      flag = Not flag\n      l = FindNextPunct(i, W) - count + 1\n      If flag Then\n         temp = temp & ExtractWord(W, count, l)\n      Else\n         temp = temp & ReverseWord(W, count, l)\n      End If\n   Loop While count < Len(W)\n   OddWordFirst = temp\nEnd Function\n\nPrivate Function FindNextPunct(d As Integer, W As String) As Integer\nConst PUNCT As String = \",;:.\"\n   Do\n      d = d + 1\n   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0\n   FindNextPunct = d\nEnd Function\n\nPrivate Function ExtractWord(W As String, c As Integer, i As Integer) As String\n   ExtractWord = Mid(W, c, i)\n   c = c + Len(ExtractWord)\nEnd Function\n\nPrivate Function ReverseWord(W As String, c As Integer, i As Integer) As String\nDim temp As String, sep As String\n   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)\n   sep = Right(Mid(W, c, i), 1)\n   ReverseWord = StrReverse(temp) & sep\n   c = c + Len(ReverseWord)\nEnd Function\n", "Java": "public class OddWord {\n    interface CharHandler {\n\tCharHandler handle(char c) throws Exception;\n    }\n    final CharHandler fwd = new CharHandler() {\n\tpublic CharHandler handle(char c) {\n\t    System.out.print(c);\n\t    return (Character.isLetter(c) ? fwd : rev);\n\t}\n    };\n    class Reverser extends Thread implements CharHandler {\n\tReverser() {\n\t    setDaemon(true);\n\t    start();\n\t}\n\tprivate Character ch; \n\tprivate char recur() throws Exception {\n\t    notify();\n\t    while (ch == null) wait();\n\t    char c = ch, ret = c;\n\t    ch = null;\n\t    if (Character.isLetter(c)) {\n\t\tret = recur();\n\t\tSystem.out.print(c);\n\t    }\n\t    return ret;\n\t}\n\tpublic synchronized void run() {\n\t    try {\n\t\twhile (true) {\n\t\t    System.out.print(recur());\n\t\t    notify();\n\t\t}\n\t    } catch (Exception e) {}\n\t}\n\tpublic synchronized CharHandler handle(char c) throws Exception {\n\t    while (ch != null) wait();\n\t    ch = c;\n\t    notify();\n\t    while (ch != null) wait();\n\t    return (Character.isLetter(c) ? rev : fwd);\n\t}\n    }\n    final CharHandler rev = new Reverser();\n\n    public void loop() throws Exception {\n\tCharHandler handler = fwd;\n\tint c;\n\twhile ((c = System.in.read()) >= 0) {\n\t    handler = handler.handle((char) c);\n\t}\n    }\n\n    public static void main(String[] args) throws Exception {\n\tnew OddWord().loop();\n    }\n}\n"}
{"id": 60277, "name": "Stern-Brocot sequence", "VB": "Imports System\nImports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n    Dim l As List(Of Integer) = {1, 1}.ToList()\n\n    Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer\n        Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,\n            selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}\n        Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1\n        Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()\n        Console.Write(\"The first {0} items In the Stern-Brocot sequence: \", take)\n        Console.WriteLine(\"{0}\" & vbLf, String.Join(\", \", l.Take(take)))\n        Console.WriteLine(\"The locations of where the selected numbers (1-to-10, & 100) first appear:\")\n        For Each ii As Integer In selection\n            Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1\n            Console.WriteLine(\"{0,3}: {1:n0}\", ii, j)\n        Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max\n            If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For\n        Next\n        Console.WriteLine(\"The greatest common divisor of all the two consecutive items of the\" &\n                          \" series up to the {0}th item is {1}always one.\", max, If(good, \"\", \"not \"))\n    End Sub\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.LinkedList;\n\npublic class SternBrocot {\n\tstatic LinkedList<Integer> sequence = new LinkedList<Integer>(){{\n\t\tadd(1); add(1);\n\t}};\n\t\n\tprivate static void genSeq(int n){\n\t\tfor(int conIdx = 1; sequence.size() < n; conIdx++){\n\t\t\tint consider = sequence.get(conIdx);\n\t\t\tint pre = sequence.get(conIdx - 1);\n\t\t\tsequence.add(consider + pre);\n\t\t\tsequence.add(consider);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tgenSeq(1200);\n\t\tSystem.out.println(\"The first 15 elements are: \" + sequence.subList(0, 15));\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"First occurrence of \" + i + \" is at \" + (sequence.indexOf(i) + 1));\n\t\t}\n\t\t\n\t\tSystem.out.println(\"First occurrence of 100 is at \" + (sequence.indexOf(100) + 1));\n\t\t\n\t\tboolean failure = false;\n\t\tfor(int i = 0; i < 999; i++){\n\t\t\tfailure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);\n\t\t}\n\t\tSystem.out.println(\"All GCDs are\" + (failure ? \" not\" : \"\") + \" 1\");\n\t}\n}\n"}
{"id": 60278, "name": "Soundex", "VB": "\n    tt=array( _\n      \"Ashcraft\",\"Ashcroft\",\"Gauss\",\"Ghosh\",\"Hilbert\",\"Heilbronn\",\"Lee\",\"Lloyd\", _\n      \"Moses\",\"Pfister\",\"Robert\",\"Rupert\",\"Rubin\",\"Tymczak\",\"Soundex\",\"Example\")\n    tv=array( _\n      \"A261\",\"A261\",\"G200\",\"G200\",\"H416\",\"H416\",\"L000\",\"L300\", _\n      \"M220\",\"P236\",\"R163\",\"R163\",\"R150\",\"T522\",\"S532\",\"E251\")\n    For i=lbound(tt) To ubound(tt)\n        ts=soundex(tt(i))\n        If ts<>tv(i) Then ok=\" KO \"& tv(i) Else ok=\"\"\n        Wscript.echo right(\" \"& i ,2) & \" \" & left( tt(i) &space(12),12) & \" \" & ts & ok\n    Next \n    \nFunction getCode(c)\n    Select Case c\n        Case \"B\", \"F\", \"P\", \"V\"\n            getCode = \"1\"\n        Case \"C\", \"G\", \"J\", \"K\", \"Q\", \"S\", \"X\", \"Z\"\n            getCode = \"2\"\n        Case \"D\", \"T\"\n            getCode = \"3\"\n        Case \"L\"\n            getCode = \"4\"\n        Case \"M\", \"N\"\n            getCode = \"5\"\n        Case \"R\"\n            getCode = \"6\"\n        Case \"W\",\"H\"\n            getCode = \"-\"\n    End Select\nEnd Function \n \nFunction soundex(s)\n    Dim code, previous, i\n    code = UCase(Mid(s, 1, 1))\n    previous = getCode(UCase(Mid(s, 1, 1)))\n    For i = 2 To Len(s)\n        current = getCode(UCase(Mid(s, i, 1)))\n        If current <> \"\" And current <> \"-\" And current <> previous Then code = code & current\n        If current <> \"-\" Then previous = current\n    Next \n    soundex = Mid(code & \"000\", 1, 4)\nEnd Function \n", "Java": "public static void main(String[] args){\n    System.out.println(soundex(\"Soundex\"));\n    System.out.println(soundex(\"Example\"));\n    System.out.println(soundex(\"Sownteks\"));\n    System.out.println(soundex(\"Ekzampul\"));\n  }\n\nprivate static String getCode(char c){\n  switch(c){\n    case 'B': case 'F': case 'P': case 'V':\n      return \"1\";\n    case 'C': case 'G': case 'J': case 'K':\n    case 'Q': case 'S': case 'X': case 'Z':\n      return \"2\";\n    case 'D': case 'T':\n      return \"3\";\n    case 'L':\n      return \"4\";\n    case 'M': case 'N':\n      return \"5\";\n    case 'R':\n      return \"6\";\n    default:\n      return \"\";\n  }\n}\n\npublic static String soundex(String s){\n  String code, previous, soundex;\n  code = s.toUpperCase().charAt(0) + \"\";\n\n  \n  previous = getCode(s.toUpperCase().charAt(0));\n\n  for(int i = 1;i < s.length();i++){\n    String current = getCode(s.toUpperCase().charAt(i));\n    if(current.length() > 0 && !current.equals(previous)){\n      code = code + current;\n    }\n    previous = current;\n  }\n  soundex = (code + \"0000\").substring(0, 4);\n  return soundex;\n}\n"}
{"id": 60279, "name": "Chat server", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 60280, "name": "Chat server", "VB": "Imports System.Net.Sockets\nImports System.Text\nImports System.Threading\n\nModule Module1\n\n    Class State\n        Private ReadOnly client As TcpClient\n        Private ReadOnly sb As New StringBuilder\n\n        Public Sub New(name As String, client As TcpClient)\n            Me.Name = name\n            Me.client = client\n        End Sub\n\n        Public ReadOnly Property Name As String\n\n        Public Sub Send(text As String)\n            Dim bytes = Encoding.ASCII.GetBytes(String.Format(\"{0}\" & vbCrLf, text))\n            client.GetStream().Write(bytes, 0, bytes.Length)\n        End Sub\n    End Class\n\n    ReadOnly connections As New Dictionary(Of Integer, State)\n    Dim listen As TcpListener\n    Dim serverThread As Thread\n\n    Sub Main()\n        listen = New TcpListener(Net.IPAddress.Parse(\"127.0.0.1\"), 4004)\n        serverThread = New Thread(New ThreadStart(AddressOf DoListen))\n        serverThread.Start()\n    End Sub\n\n    Private Sub DoListen()\n        listen.Start()\n        Console.WriteLine(\"Server: Started server\")\n\n        Do\n            Console.Write(\"Server: Waiting...\")\n            Dim client = listen.AcceptTcpClient()\n            Console.WriteLine(\" Connected\")\n\n            \n            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))\n\n            clientThread.Start(client)\n        Loop\n    End Sub\n\n    Private Sub DoClient(client As TcpClient)\n        Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId)\n        Dim bytes = Encoding.ASCII.GetBytes(\"Enter name: \")\n        client.GetStream().Write(bytes, 0, bytes.Length)\n\n        Dim done As Boolean\n        Dim name As String\n        Do\n            If Not client.Connected Then\n                Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n                client.Close()\n                Thread.CurrentThread.Abort() \n            End If\n\n            name = Receive(client)\n            done = True\n\n            For Each cl In connections\n                Dim state = cl.Value\n                If state.Name = name Then\n                    bytes = Encoding.ASCII.GetBytes(\"Name already registered. Please enter your name: \")\n                    client.GetStream().Write(bytes, 0, bytes.Length)\n                    done = False\n                End If\n            Next\n        Loop While Not done\n\n        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))\n        Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n        Broadcast(String.Format(\"+++ {0} arrived +++\", name))\n\n        Do\n            Dim text = Receive(client)\n            If text = \"/quit\" Then\n                Broadcast(String.Format(\"Connection from {0} closed.\", name))\n                connections.Remove(Thread.CurrentThread.ManagedThreadId)\n                Console.WriteLine(vbTab & \"Total connections: {0}\", connections.Count)\n                Exit Do\n            End If\n\n            If Not client.Connected Then\n                Exit Do\n            End If\n\n            Broadcast(String.Format(\"{0}> {1}\", name, text))\n        Loop\n\n        Console.WriteLine(\"Client (Thread: {0}): Terminated!\", Thread.CurrentThread.ManagedThreadId)\n        client.Close()\n        Thread.CurrentThread.Abort()\n    End Sub\n\n    Private Function Receive(client As TcpClient) As String\n        Dim sb As New StringBuilder\n        Do\n            If client.Available > 0 Then\n                While client.Available > 0\n                    Dim ch = Chr(client.GetStream.ReadByte())\n                    If ch = vbCr Then\n                        \n                        Continue While\n                    End If\n                    If ch = vbLf Then\n                        Return sb.ToString()\n                    End If\n                    sb.Append(ch)\n                End While\n\n                \n                Thread.Sleep(100)\n            End If\n        Loop\n    End Function\n\n    Private Sub Broadcast(text As String)\n        Console.WriteLine(text)\n        For Each client In connections\n            If client.Key <> Thread.CurrentThread.ManagedThreadId Then\n                Dim state = client.Value\n                state.Send(text)\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class ChatServer implements Runnable\n{\n  private int port = 0;\n  private List<Client> clients = new ArrayList<Client>();\n  \n  public ChatServer(int port)\n  {  this.port = port;  }\n  \n  public void run()\n  {\n    try\n    {\n      ServerSocket ss = new ServerSocket(port);\n      while (true)\n      {\n        Socket s = ss.accept();\n        new Thread(new Client(s)).start();\n      }\n    }\n    catch (Exception e)\n    {  e.printStackTrace();  }\n  }\n\n  private synchronized boolean registerClient(Client client)\n  {\n    for (Client otherClient : clients)\n      if (otherClient.clientName.equalsIgnoreCase(client.clientName))\n        return false;\n    clients.add(client);\n    return true;\n  }\n\n  private void deregisterClient(Client client)\n  {\n    boolean wasRegistered = false;\n    synchronized (this)\n    {  wasRegistered = clients.remove(client);  }\n    if (wasRegistered)\n      broadcast(client, \"--- \" + client.clientName + \" left ---\");\n  }\n  \n  private synchronized String getOnlineListCSV()\n  {\n    StringBuilder sb = new StringBuilder();\n    sb.append(clients.size()).append(\" user(s) online: \");\n    for (int i = 0; i < clients.size(); i++)\n      sb.append((i > 0) ? \", \" : \"\").append(clients.get(i).clientName);\n    return sb.toString();\n  }\n  \n  private void broadcast(Client fromClient, String msg)\n  {\n    \n    List<Client> clients = null;\n    synchronized (this)\n    {  clients = new ArrayList<Client>(this.clients);  }\n    for (Client client : clients)\n    {\n      if (client.equals(fromClient))\n        continue;\n      try\n      {  client.write(msg + \"\\r\\n\");  }\n      catch (Exception e)\n      {  }\n    }\n  }\n\n  public class Client implements Runnable\n  {\n    private Socket socket = null;\n    private Writer output = null;\n    private String clientName = null;\n    \n    public Client(Socket socket)\n    {\n      this.socket = socket;\n    }\n    \n    public void run()\n    {\n      try\n      {\n        socket.setSendBufferSize(16384);\n        socket.setTcpNoDelay(true);\n        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n        output = new OutputStreamWriter(socket.getOutputStream());\n        write(\"Please enter your name: \");\n        String line = null;\n        while ((line = input.readLine()) != null)\n        {\n          if (clientName == null)\n          {\n            line = line.trim();\n            if (line.isEmpty())\n            {\n              write(\"A name is required. Please enter your name: \");\n              continue;\n            }\n            clientName = line;\n            if (!registerClient(this))\n            {\n              clientName = null;\n              write(\"Name already registered. Please enter your name: \");\n              continue;\n            }\n            write(getOnlineListCSV() + \"\\r\\n\");\n            broadcast(this, \"+++ \" + clientName + \" arrived +++\");\n            continue;\n          }\n          if (line.equalsIgnoreCase(\"/quit\"))\n            return;\n          broadcast(this, clientName + \"> \" + line);\n        }\n      }\n      catch (Exception e)\n      {  }\n      finally\n      {\n        deregisterClient(this);\n        output = null;\n        try\n        {  socket.close();  }\n        catch (Exception e)\n        {  }\n        socket = null;\n      }\n    }\n    \n    public void write(String msg) throws IOException\n    {\n      output.write(msg);\n      output.flush();\n    }\n    \n    public boolean equals(Client client)\n    {\n      return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName);\n    }\n  }\n  \n  public static void main(String[] args)\n  {\n    int port = 4004;\n    if (args.length > 0)\n      port = Integer.parseInt(args[0]);\n    new ChatServer(port).run();\n  }\n}\n"}
{"id": 60281, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 60282, "name": "Truncate a file", "VB": "Sub truncate(fpath,n)\n\t\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tIf objfso.FileExists(fpath) = False Then\n\t\tWScript.Echo fpath & \" does not exist\"\n\t\tExit Sub\n\tEnd If\n\tcontent = \"\"\n\t\n\tSet objinstream = CreateObject(\"Adodb.Stream\")\n\tWith objinstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.LoadFromFile(fpath)\n\t\t\n\t\tIf n <= .Size Then\n\t\t\tcontent = .Read(n)\n\t\tElse\n\t\t\tWScript.Echo \"The specified size is larger than the file content\"\n\t\t\tExit Sub\n\t\tEnd If\n\t\t.Close\n\tEnd With\n\t\n\tSet objoutstream = CreateObject(\"Adodb.Stream\")\n\tWith objoutstream\n\t\t.Type = 1\n\t\t.Open\n\t\t.Write content\n\t\t.SaveToFile fpath,2\n\t\t.Close\n\tEnd With\n\tSet objinstream = Nothing\n\tSet objoutstream = Nothing\n\tSet objfso = Nothing\nEnd Sub\n\n\nCall truncate(\"C:\\temp\\test.txt\",30)\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class TruncFile {\n\tpublic static void main(String[] args) throws IOException{\n\t\tif(args.length < 2){\n\t\t\tSystem.out.println(\"Usage: java TruncFile fileName newSize\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tFileChannel outChan = new FileOutputStream(args[0], true).getChannel();\n\t\tlong newSize = Long.parseLong(args[1]);\n\t\toutChan.truncate(newSize);\n\t\toutChan.close();\n\t}\n}\n"}
{"id": 60283, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 60284, "name": "Find palindromic numbers in both binary and ternary bases", "VB": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\n\n\nPrivate Function DecimalToBinary(DecimalNum As Long) As String\n    Dim tmp As String\n    Dim n As Long\n    \n    n = DecimalNum\n    \n    tmp = Trim(CStr(n Mod 2))\n    n = n \\ 2\n    \n    Do While n <> 0\n    tmp = Trim(CStr(n Mod 2)) & tmp\n    n = n \\ 2\n    Loop\n    \n    DecimalToBinary = tmp\nEnd Function\nFunction Dec2Bin(ByVal DecimalIn As Variant, _\n              Optional NumberOfBits As Variant) As String\n    Dec2Bin = \"\"\n    DecimalIn = Int(CDec(DecimalIn))\n    Do While DecimalIn <> 0\n        Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin\n        DecimalIn = Int(DecimalIn / 2)\n    Loop\n    If Not IsMissing(NumberOfBits) Then\n       If Len(Dec2Bin) > NumberOfBits Then\n          Dec2Bin = \"Error - Number exceeds specified bit size\"\n       Else\n          Dec2Bin = Right$(String$(NumberOfBits, _\n                    \"0\") & Dec2Bin, NumberOfBits)\n       End If\n    End If\nEnd Function\nPublic Sub base()\n    \n    \n    \n    Time1 = GetTickCount\n    Dim n As Long\n    Dim three(19) As Integer\n    Dim pow3(19) As Variant\n    Dim full3 As Variant\n    Dim trail As Variant\n    Dim check As Long\n    Dim len3 As Integer\n    Dim carry As Boolean\n    Dim i As Integer, j As Integer\n    Dim s As String\n    Dim t As String\n    pow3(0) = CDec(1)\n    For i = 1 To 19\n        pow3(i) = 3 * pow3(i - 1)\n    Next i\n    Debug.Print String$(5, \" \"); \"iter\"; String$(7, \" \"); \"decimal\"; String$(18, \" \"); \"binary\";\n    Debug.Print String$(30, \" \"); \"ternary\"\n    n = 0: full3 = 0: t = \"0\": s = \"0\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    n = 0: full3 = 1: t = \"1\": s = \"1\"\n    Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n    Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n    Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n    number = 0\n    n = 1\n    len3 = 0\n    full3 = 3\n    Do \n        three(0) = three(0) + 1\n        carry = False\n        If three(0) = 3 Then\n            three(0) = 0\n            carry = True\n            j = 1\n            Do While carry\n                three(j) = three(j) + 1\n                If three(j) = 3 Then\n                    three(j) = 0\n                    j = j + 1\n                Else\n                    carry = False\n                End If\n            Loop\n            If len3 < j Then\n                trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)\n                len3 = j\n                full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + 1 \n            Else\n                full3 = full3 + pow3(len3 + 2)\n                For i = 0 To j - 1\n                    full3 = full3 - 2 * pow3(len3 - i)\n                Next i\n                full3 = full3 + pow3(len3 - j)\n            End If\n        Else\n            full3 = full3 + pow3(len3 + 2) + pow3(len3)\n        End If\n        s = \"\"\n        For i = 0 To len3\n            s = s & CStr(three(i))\n        Next i\n        \n        t = Dec2Bin(full3) \n        If t = StrReverse(t) Then\n            \n            number = number + 1\n            s = StrReverse(s) & \"1\" & s\n            If n < 200000 Then\n                Debug.Print String$(8 - Len(CStr(n)), \" \"); n; String$(12 - Len(CStr(full3)), \" \");\n                Debug.Print full3; String$((41 - Len(t)) / 2, \" \"); t; String$((41 - Len(t)) / 2, \" \");\n                Debug.Print String$((31 - Len(s)) / 2, \" \"); s\n                If number = 4 Then\n                    Debug.Print \"Completed in\"; (GetTickCount - Time1) / 1000; \"seconds\"\n                    Time2 = GetTickCount\n                    Application.ScreenUpdating = False\n                End If\n            Else\n                Debug.Print n, full3, Len(t), t, Len(s), s\n                Debug.Print \"Completed in\"; (Time2 - Time1) / 1000; \"seconds\";\n                Time3 = GetTickCount\n            End If\n        End If\n        n = n + 1\n    Loop Until number = 5 \n    Debug.Print \"Completed in\"; (Time3 - Time1) / 1000; \"seconds\"\n    Application.ScreenUpdating = True\nEnd Sub\n", "Java": "public class Pali23 {\n\tpublic static boolean isPali(String x){\n\t\treturn x.equals(new StringBuilder(x).reverse().toString());\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\t\n\t\tfor(long i = 0, count = 0; count < 6;i++){\n\t\t\tif((i & 1) == 0 && (i != 0)) continue; \n\t\t\t\n\t\t\t\n\t\t\tif(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){\n\t\t\t\tSystem.out.println(i + \", \" + Long.toBinaryString(i) + \", \" + Long.toString(i, 3));\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 60285, "name": "Finite state machine", "VB": "Enum states\n    READY\n    WAITING\n    DISPENSE\n    REFUND\n    QU1T\nEnd Enum \nPublic Sub finite_state_machine()\n    Dim state As Integer: state = READY: ch = \" \"\n    Do While True\n        Debug.Print ch\n        Select Case state\n            Case READY:     Debug.Print \"Machine is READY. (D)eposit or (Q)uit :\"\n                            Do While True\n                                If ch = \"D\" Then\n                                    state = WAITING\n                                    Exit Do\n                                End If\n                                If ch = \"Q\" Then\n                                    state = QU1T\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Machine is READY. (D)eposit or (Q)uit :\")\n                            Loop\n            Case WAITING:   Debug.Print \"(S)elect product or choose to (R)efund :\"\n                            Do While True\n                                If ch = \"S\" Then\n                                    state = DISPENSE\n                                    Exit Do\n                                End If\n                                If ch = \"R\" Then\n                                    state = REFUND\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"(S)elect product or choose to (R)efund :\")\n                            Loop\n            Case DISPENSE:  Debug.Print \"Dispensing product...\"\n                            Do While True\n                                If ch = \"C\" Then\n                                    state = READY\n                                    Exit Do\n                                End If\n                                ch = InputBox(\"Please (C)ollect product. :\")\n                            Loop\n            Case REFUND:    Debug.Print \"Please collect refund.\"\n                            state = READY\n                            ch = \" \"\n            Case QU1T:      Debug.Print \"Thank you, shutting down now.\"\n                            Exit Sub\n        End Select\n    Loop\nEnd Sub\n", "Java": "import java.util.*;\n\npublic class FiniteStateMachine {\n\n    private enum State {\n        Ready(true, \"Deposit\", \"Quit\"),\n        Waiting(true, \"Select\", \"Refund\"),\n        Dispensing(true, \"Remove\"),\n        Refunding(false, \"Refunding\"),\n        Exiting(false, \"Quiting\");\n\n        State(boolean exp, String... in) {\n            inputs = Arrays.asList(in);\n            explicit = exp;\n        }\n\n        State nextState(String input, State current) {\n            if (inputs.contains(input)) {\n                return map.getOrDefault(input, current);\n            }\n            return current;\n        }\n\n        final List<String> inputs;\n        final static Map<String, State> map = new HashMap<>();\n        final boolean explicit;\n\n        static {\n            map.put(\"Deposit\", State.Waiting);\n            map.put(\"Quit\", State.Exiting);\n            map.put(\"Select\", State.Dispensing);\n            map.put(\"Refund\", State.Refunding);\n            map.put(\"Remove\", State.Ready);\n            map.put(\"Refunding\", State.Ready);\n        }\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        State state = State.Ready;\n\n        while (state != State.Exiting) {\n            System.out.println(state.inputs);\n            if (state.explicit){\n                System.out.print(\"> \");\n                state = state.nextState(sc.nextLine().trim(), state);\n            } else {\n                state = state.nextState(state.inputs.get(0), state);\n            }\n        }\n    }\n}\n"}
{"id": 60286, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 60287, "name": "Cipolla's algorithm", "VB": "Imports System.Numerics\n\nModule Module1\n\n    ReadOnly BIG = BigInteger.Pow(10, 50) + 151\n\n    Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)\n        Dim n = BigInteger.Parse(ns)\n        Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)\n\n        \n        Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)\n\n        \n        If ls(n) <> 1 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Dim a = BigInteger.Zero\n        Dim omega2 As BigInteger\n        Do\n            omega2 = (a * a + p - n) Mod p\n            If ls(omega2) = p - 1 Then\n                Exit Do\n            End If\n            a += 1\n        Loop\n\n        \n        Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))\n                      Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)\n                  End Function\n\n        \n        Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)\n        Dim s = Tuple.Create(a, BigInteger.One)\n        Dim nn = ((p + 1) >> 1) Mod p\n        While nn > 0\n            If nn Mod 2 = 1 Then\n                r = mul(r, s)\n            End If\n            s = mul(s, s)\n            nn >>= 1\n        End While\n\n        \n        If r.Item2 <> 0 Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        If r.Item1 * r.Item1 Mod p <> n Then\n            Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)\n        End If\n\n        \n        Return Tuple.Create(r.Item1, p - r.Item1, True)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(C(\"10\", \"13\"))\n        Console.WriteLine(C(\"56\", \"101\"))\n        Console.WriteLine(C(\"8218\", \"10007\"))\n        Console.WriteLine(C(\"8219\", \"10007\"))\n        Console.WriteLine(C(\"331575\", \"1000003\"))\n        Console.WriteLine(C(\"665165880\", \"1000000007\"))\n        Console.WriteLine(C(\"881398088036\", \"1000000000039\"))\n        Console.WriteLine(C(\"34035243914635549601583369544560650254325084643201\", \"\"))\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class CipollasAlgorithm {\n    private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));\n    private static final BigInteger BIG_TWO = BigInteger.valueOf(2);\n\n    private static class Point {\n        BigInteger x;\n        BigInteger y;\n\n        Point(BigInteger x, BigInteger y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s)\", this.x, this.y);\n        }\n    }\n\n    private static class Triple {\n        BigInteger x;\n        BigInteger y;\n        boolean b;\n\n        Triple(BigInteger x, BigInteger y, boolean b) {\n            this.x = x;\n            this.y = y;\n            this.b = b;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%s, %s, %s)\", this.x, this.y, this.b);\n        }\n    }\n\n    private static Triple c(String ns, String ps) {\n        BigInteger n = new BigInteger(ns);\n        BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;\n\n        \n        Function<BigInteger, BigInteger> ls = (BigInteger a)\n            -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);\n\n        \n        if (!ls.apply(n).equals(BigInteger.ONE)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        BigInteger a = BigInteger.ZERO;\n        BigInteger omega2;\n        while (true) {\n            omega2 = a.multiply(a).add(p).subtract(n).mod(p);\n            if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {\n                break;\n            }\n            a = a.add(BigInteger.ONE);\n        }\n\n        \n        BigInteger finalOmega = omega2;\n        BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(\n            aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),\n            aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)\n        );\n\n        \n        Point r = new Point(BigInteger.ONE, BigInteger.ZERO);\n        Point s = new Point(a, BigInteger.ONE);\n        BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);\n        while (nn.compareTo(BigInteger.ZERO) > 0) {\n            if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {\n                r = mul.apply(r, s);\n            }\n            s = mul.apply(s, s);\n            nn = nn.shiftRight(1);\n        }\n\n        \n        if (!r.y.equals(BigInteger.ZERO)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        if (!r.x.multiply(r.x).mod(p).equals(n)) {\n            return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);\n        }\n\n        \n        return new Triple(r.x, p.subtract(r.x), true);\n    }\n\n    public static void main(String[] args) {\n        System.out.println(c(\"10\", \"13\"));\n        System.out.println(c(\"56\", \"101\"));\n        System.out.println(c(\"8218\", \"10007\"));\n        System.out.println(c(\"8219\", \"10007\"));\n        System.out.println(c(\"331575\", \"1000003\"));\n        System.out.println(c(\"665165880\", \"1000000007\"));\n        System.out.println(c(\"881398088036\", \"1000000000039\"));\n        System.out.println(c(\"34035243914635549601583369544560650254325084643201\", \"\"));\n    }\n}\n"}
{"id": 60288, "name": "Sierpinski pentagon", "VB": "Private Sub sierpinski(Order_ As Integer, Side As Double)\n    Dim Circumradius As Double, Inradius As Double\n    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double\n    Dim Pi As Double, p(5) As String, Shp As Shape\n    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10\n    Inradius = Sqr(25 + 10 * Sqr(5)) / 10\n    Height = Circumradius + Inradius\n    Diagonal = (1 + Sqr(5)) / 2\n    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4\n    Pi = WorksheetFunction.Pi\n    Ratio = Height / (2 * Height + HeightDiagonal)\n    \n    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _\n        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)\n    p(0) = Shp.Name\n    Shp.Rotation = 180\n    Shp.Line.Weight = 0\n    For j = 1 To Order_\n        \n        For i = 0 To 4\n            \n            Set Shp = Shp.Duplicate\n            p(i + 1) = Shp.Name\n            If i = 0 Then Shp.Rotation = 0\n            \n            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)\n            Shp.Visible = msoTrue\n        Next i\n        \n        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group\n        p(0) = Shp.Name\n        If j < Order_ Then\n            \n            Shp.ScaleHeight Ratio, False\n            Shp.ScaleWidth Ratio, False\n            \n            Shp.Rotation = 180\n            Shp.Left = 2 * Side\n            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side\n        End If\n    Next j\nEnd Sub\n\nPublic Sub main()\n    sierpinski Order_:=5, Side:=200\nEnd Sub\n", "Java": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.geom.Path2D;\nimport static java.lang.Math.*;\nimport java.util.Random;\nimport javax.swing.*;\n\npublic class SierpinskiPentagon extends JPanel {\n    \n    final double degrees072 = toRadians(72);\n\n    \n    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);\n\n    final int margin = 20;\n    int limit = 0;\n    Random r = new Random();\n\n    public SierpinskiPentagon() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n\n        new Timer(3000, (ActionEvent e) -> {\n            limit++;\n            if (limit >= 5)\n                limit = 0;\n            repaint();\n        }).start();\n    }\n\n    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {\n        double angle = 3 * degrees072; \n\n        if (depth == 0) {\n\n            Path2D p = new Path2D.Double();\n            p.moveTo(x, y);\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * side;\n                y = y - sin(angle) * side;\n                p.lineTo(x, y);\n                angle += degrees072;\n            }\n\n            g.setColor(RandomHue.next());\n            g.fill(p);\n\n        } else {\n\n            side *= scaleFactor;\n\n            \n            double distance = side + side * cos(degrees072) * 2;\n\n            \n            for (int i = 0; i < 5; i++) {\n                x = x + cos(angle) * distance;\n                y = y - sin(angle) * distance;\n                drawPentagon(g, x, y, side, depth - 1);\n                angle += degrees072;\n            }\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        int w = getWidth();\n        double radius = w / 2 - 2 * margin;\n        double side = radius * sin(PI / 5) * 2;\n\n        drawPentagon(g, w / 2, 3 * margin, side, limit);\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(\"Sierpinski Pentagon\");\n            f.setResizable(true);\n            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n\nclass RandomHue {\n    \n    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;\n    private static double hue = Math.random();\n\n    static Color next() {\n        hue = (hue + goldenRatioConjugate) % 1;\n        return Color.getHSBColor((float) hue, 1, 1);\n    }\n}\n"}
{"id": 60289, "name": "Rep-string", "VB": "Function rep_string(s)\n\tmax_len = Int(Len(s)/2)\n\ttmp = \"\"\n\tIf max_len = 0 Then\n\t\trep_string = \"No Repeating String\"\n\t\tExit Function\n\tEnd If\n\tFor i = 1 To max_len\n\t\tIf InStr(i+1,s,tmp & Mid(s,i,1))Then\n\t\t\ttmp = tmp & Mid(s,i,1)\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tDo While Len(tmp) > 0\n\t\tIf Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then\n\t\t\trep_string = tmp\n\t\t\tExit Do\n\t\tElse\n\t\t\ttmp = Mid(tmp,1,Len(tmp)-1)\n\t\tEnd If\n\tLoop\n\tIf Len(tmp) > 0 Then\n\t\trep_string = tmp\n\tElse\n\t\trep_string = \"No Repeating String\"\n\tEnd If\nEnd Function\n\n\narr = Array(\"1001110011\",\"1110111011\",\"0010010010\",\"1010101010\",_\n\t\t\"1111111111\",\"0100101101\",\"0100100\",\"101\",\"11\",\"00\",\"1\")\n\nFor n = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(n) & \": \" & rep_string(arr(n))\n\tWScript.StdOut.WriteLine\nNext\n", "Java": "public class RepString {\n\n    static final String[] input = {\"1001110011\", \"1110111011\", \"0010010010\",\n        \"1010101010\", \"1111111111\", \"0100101101\", \"0100100\", \"101\", \"11\",\n        \"00\", \"1\", \"0100101\"};\n\n    public static void main(String[] args) {\n        for (String s : input)\n            System.out.printf(\"%s : %s%n\", s, repString(s));\n    }\n\n    static String repString(String s) {\n        int len = s.length();\n        outer:\n        for (int part = len / 2; part > 0; part--) {\n            int tail = len % part;\n            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))\n                continue;\n            for (int j = 0; j < len / part - 1; j++) {\n                int a = j * part;\n                int b = (j + 1) * part;\n                int c = (j + 2) * part;\n                if (!s.substring(a, b).equals(s.substring(b, c)))\n                    continue outer;\n            }\n            return s.substring(0, part);\n        }\n        return \"none\";\n    }\n}\n"}
{"id": 60290, "name": "Literals_String", "VB": "  Debug.Print \"Tom said, \"\"The fox ran away.\"\"\"\n  Debug.Print \"Tom said, \n", "Java": "  char a = 'a';  \n  String b = \"abc\";  \n  char doubleQuote = '\"';  \n  char singleQuote = '\\'';  \n  String singleQuotes = \"''\";  \n  String doubleQuotes = \"\\\"\\\"\";  \n"}
{"id": 60291, "name": "GUI_Maximum window dimensions", "VB": "TYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n\n\nsyswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY\n\n\n", "Java": "import java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n    public static void main(String[] args) {\n        new Test();\n    }\n\n    Test() {\n        Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n        Dimension screenSize = toolkit.getScreenSize();\n        System.out.println(\"Physical screen size: \" + screenSize);\n\n        Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n        System.out.println(\"Insets: \" + insets);\n\n        screenSize.width -= (insets.left + insets.right);\n        screenSize.height -= (insets.top + insets.bottom);\n        System.out.println(\"Max available: \" + screenSize);\n    }\n}\n"}
{"id": 60292, "name": "Enumerations", "VB": "\nEnum fruits\n  apple\n  banana\n  cherry\nEnd Enum\n \n\nEnum fruits2\n  pear = 5\n  mango = 10\n  kiwi = 20\n  pineapple = 20\nEnd Enum\n\n\nSub test()\nDim f As fruits\n  f = apple\n  Debug.Print \"apple equals \"; f\n  Debug.Print \"kiwi equals \"; kiwi\n  Debug.Print \"cherry plus kiwi plus pineapple equals \"; cherry + kiwi + pineapple\nEnd Sub\n", "Java": "enum Fruits{\n   APPLE, BANANA, CHERRY\n}\n"}
{"id": 60293, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 60294, "name": "Pentagram", "VB": "Sub pentagram()\n    With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)\n        .Fill.ForeColor.RGB = RGB(255, 0, 0)\n        .Line.Weight = 3\n        .Line.ForeColor.RGB = RGB(0, 0, 255)\n    End With\nEnd Sub\n", "Java": "import java.awt.*;\nimport java.awt.geom.Path2D;\nimport javax.swing.*;\n\npublic class Pentagram extends JPanel {\n\n    final double degrees144 = Math.toRadians(144);\n\n    public Pentagram() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n    }\n\n    private void drawPentagram(Graphics2D g, int len, int x, int y,\n            Color fill, Color stroke) {\n        double angle = 0;\n\n        Path2D p = new Path2D.Float();\n        p.moveTo(x, y);\n\n        for (int i = 0; i < 5; i++) {\n            int x2 = x + (int) (Math.cos(angle) * len);\n            int y2 = y + (int) (Math.sin(-angle) * len);\n            p.lineTo(x2, y2);\n            x = x2;\n            y = y2;\n            angle -= degrees144;\n        }\n        p.closePath();\n\n        g.setColor(fill);\n        g.fill(p);\n\n        g.setColor(stroke);\n        g.draw(p);\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));\n\n        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);\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(\"Pentagram\");\n            f.setResizable(false);\n            f.add(new Pentagram(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 60295, "name": "Parse an IP Address", "VB": "Function parse_ip(addr)\n    \n    Set ipv4_pattern = New RegExp\n    ipv4_pattern.Global = True\n    ipv4_pattern.Pattern = \"(\\d{1,3}\\.){3}\\d{1,3}\"\n    \n    Set ipv6_pattern = New RegExp\n    ipv6_pattern.Global = True\n    ipv6_pattern.Pattern = \"([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}\"\n    \n    If ipv4_pattern.Test(addr) Then\n        port = Split(addr,\":\")\n        octet = Split(port(0),\".\")\n        ipv4_hex = \"\"\n        For i = 0 To UBound(octet)\n            If octet(i) <= 255 And octet(i) >= 0 Then\n                ipv4_hex = ipv4_hex & Right(\"0\" & Hex(octet(i)),2)\n            Else\n                ipv4_hex = \"Erroneous Address\"\n                Exit For\n            End If \n        Next\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: \" & ipv4_hex & vbCrLf\n        If UBound(port) = 1 Then\n            If port(1) <= 65535 And port(1) >= 0 Then\n                parse_ip = parse_ip & \"Port: \" & port(1) & vbCrLf\n            Else\n                parse_ip = parse_ip & \"Port: Invalid\" & vbCrLf\n            End If\n        End If\n    End If\n    \n    If ipv6_pattern.Test(addr) Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf\n        port_v6 = \"Port: \"\n        ipv6_hex = \"\"\n        \n        If InStr(1,addr,\"[\") Then\n            \n            port_v6 = port_v6 & Mid(addr,InStrRev(addr,\"]\")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,\"]\")+1)))\n            \n            addr = Mid(addr,InStrRev(addr,\"[\")+1,InStrRev(addr,\"]\")-(InStrRev(addr,\"[\")+1))\n        End If\n        word = Split(addr,\":\")\n        word_count = 0\n        For i = 0 To UBound(word)\n            If word(i) = \"\" Then\n                If i < UBound(word) Then\n                    If Int((7-(i+1))/2) = 1 Then\n                        k = 1\n                    ElseIf UBound(word) < 6 Then\n                        k = Int((7-(i+1))/2)\n                    ElseIf UBound(word) >= 6 Then\n                        k = Int((7-(i+1))/2)-1\n                    End If\n                    For j = 0 To k\n                        ipv6_hex = ipv6_hex & \"0000\"\n                        word_count = word_count + 1\n                    Next\n                Else\n                    For j = 0 To (7-word_count)\n                        ipv6_hex = ipv6_hex & \"0000\"\n                    Next\n                End If\n            Else\n                ipv6_hex = ipv6_hex & Right(\"0000\" & word(i),4)\n                word_count = word_count + 1\n            End If\n        Next\n        parse_ip = parse_ip & \"Address: \" & ipv6_hex &_\n                vbCrLf & port_v6 & vbCrLf\n    End If\n    \n    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then\n        parse_ip = \"Test Case: \" & addr & vbCrLf &_\n                   \"Address: Invalid Address\" & vbCrLf\n    End If\nEnd Function\n\n\nip_arr = Array(\"127.0.0.1\",\"127.0.0.1:80\",\"::1\",_\n    \"[::1]:80\",\"2605:2700:0:3::4713:93e3\",\"[2605:2700:0:3::4713:93e3]:80\",\"RosettaCode\")\n\nFor n = 0 To UBound(ip_arr)\n    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf\nNext\n", "Java": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ParseIPAddress {\n\n    public static void main(String[] args) {\n        String [] tests = new String[] {\"192.168.0.1\", \"127.0.0.1\", \"256.0.0.1\", \"127.0.0.1:80\", \"::1\", \"[::1]:80\", \"[32e::12f]:80\", \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\", \"2001:db8:85a3:0:0:8a2e:370:7334\"};\n        System.out.printf(\"%-40s %-32s   %s%n\", \"Test Case\", \"Hex Address\", \"Port\");\n        for ( String ip : tests ) {\n            try {\n                String [] parsed = parseIP(ip);\n                System.out.printf(\"%-40s %-32s   %s%n\", ip, parsed[0], parsed[1]);\n            }\n            catch (IllegalArgumentException e) {\n                System.out.printf(\"%-40s Invalid address:  %s%n\", ip, e.getMessage());\n            }\n        }\n    }\n    \n    private static final Pattern IPV4_PAT = Pattern.compile(\"^(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?::(\\\\d+)){0,1}$\");\n    private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile(\"^\\\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\\\]:(\\\\d+)){0,1}$\");\n    private static String ipv6Pattern;\n    static {\n        ipv6Pattern = \"^\\\\[{0,1}\";\n        for ( int i = 1 ; i <= 7 ; i ++ ) {\n            ipv6Pattern += \"([0-9a-f]+):\";\n        }\n        ipv6Pattern += \"([0-9a-f]+)(?:\\\\]:(\\\\d+)){0,1}$\";\n    }\n    private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);\n    \n    private static String[] parseIP(String ip) {\n        String hex = \"\";\n        String port = \"\";\n        \n        \n        Matcher ipv4Matcher = IPV4_PAT.matcher(ip);\n        if ( ipv4Matcher.matches() ) {\n            for ( int i = 1 ; i <= 4 ; i++ ) {\n                hex += toHex4(ipv4Matcher.group(i));\n            }\n            if ( ipv4Matcher.group(5) != null ) {\n                port = ipv4Matcher.group(5);\n            }\n            return new String[] {hex, port};\n        }\n        \n        \n        Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);\n        if ( ipv6DoubleColonMatcher.matches() ) {\n            String p1 = ipv6DoubleColonMatcher.group(1);\n            if ( p1.isEmpty() ) {\n                p1 = \"0\";\n            }\n            String p2 = ipv6DoubleColonMatcher.group(2);\n            if ( p2.isEmpty() ) {\n                p2 = \"0\";\n            }\n            ip =  p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;\n            if ( ipv6DoubleColonMatcher.group(3) != null ) {\n                ip = \"[\" + ip + \"]:\" + ipv6DoubleColonMatcher.group(3);\n            }\n        }\n        \n        \n        Matcher ipv6Matcher = IPV6_PAT.matcher(ip);\n        if ( ipv6Matcher.matches() ) {\n            for ( int i = 1 ; i <= 8 ; i++ ) {\n                hex += String.format(\"%4s\", toHex6(ipv6Matcher.group(i))).replace(\" \", \"0\");\n            }\n            if ( ipv6Matcher.group(9) != null ) {\n                port = ipv6Matcher.group(9);\n            }\n            return new String[] {hex, port};\n        }\n        \n        throw new IllegalArgumentException(\"ERROR 103: Unknown address: \" + ip);\n    }\n    \n    private static int numCount(String s) {\n        return s.split(\":\").length;\n    }\n    \n    private static String getZero(int count) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        while ( count > 0 ) {\n            sb.append(\"0:\");\n            count--;\n        }\n        return sb.toString();\n    }\n\n    private static String toHex4(String s) {\n        int val = Integer.parseInt(s);\n        if ( val < 0 || val > 255 ) {\n            throw new IllegalArgumentException(\"ERROR 101:  Invalid value : \" + s);\n        }\n        return String.format(\"%2s\", Integer.toHexString(val)).replace(\" \", \"0\");\n    }\n\n    private static String toHex6(String s) {\n        int val = Integer.parseInt(s, 16);\n        if ( val < 0 || val > 65536 ) {\n            throw new IllegalArgumentException(\"ERROR 102:  Invalid hex value : \" + s);\n        }\n        return s;\n    }\n\n}\n"}
{"id": 60296, "name": "Knapsack problem_Unbounded", "VB": "Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function \n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) \n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))\n    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))\n      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S \n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n", "Java": "package hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n    protected Item []  items = {\n                               new Item(\"panacea\", 3000,  0.3, 0.025),\n                               new Item(\"ichor\"  , 1800,  0.2, 0.015),\n                               new Item(\"gold\"   , 2500,  2.0, 0.002)\n                               };\n    protected final int    n = items.length; \n    protected Item      sack = new Item(\"sack\"   ,    0, 25.0, 0.250);\n    protected Item      best = new Item(\"best\"   ,    0,  0.0, 0.000);\n    protected int  []  maxIt = new int [n];  \n    protected int  []    iIt = new int [n];  \n    protected int  [] bestAm = new int [n];  \n\n    public UnboundedKnapsack() {\n        \n        for (int i = 0; i < n; i++) {\n            maxIt [i] = Math.min(\n                           (int)(sack.getWeight() / items[i].getWeight()),\n                           (int)(sack.getVolume() / items[i].getVolume())\n                        );\n        } \n\n        \n        calcWithRecursion(0);\n\n        \n        NumberFormat nf = NumberFormat.getInstance();\n        System.out.println(\"Maximum value achievable is: \" + best.getValue());\n        System.out.print(\"This is achieved by carrying (one solution): \");\n        for (int i = 0; i < n; i++) {\n            System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n        }\n        System.out.println();\n        System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n                           \"   and the volume used is: \" + nf.format(best.getVolume())\n                          );\n\n    }\n\n    \n    \n    public void calcWithRecursion(int item) {\n        for (int i = 0; i <= maxIt[item]; i++) {\n            iIt[item] = i;\n            if (item < n-1) {\n                calcWithRecursion(item+1);\n            } else {\n                int    currVal = 0;   \n                double currWei = 0.0; \n                double currVol = 0.0; \n                for (int j = 0; j < n; j++) {\n                    currVal += iIt[j] * items[j].getValue();\n                    currWei += iIt[j] * items[j].getWeight();\n                    currVol += iIt[j] * items[j].getVolume();\n                }\n\n                if (currVal > best.getValue()\n                    &&\n                    currWei <= sack.getWeight()\n                    &&\n                    currVol <= sack.getVolume()\n                )\n                {\n                    best.setValue (currVal);\n                    best.setWeight(currWei);\n                    best.setVolume(currVol);\n                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n                } \n            } \n        } \n    } \n\n    \n    public static void main(String[] args) {\n        new UnboundedKnapsack();\n    } \n\n} \n"}
{"id": 60297, "name": "Textonyms", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\unixdict.txt\",1)\nSet objKeyMap = CreateObject(\"Scripting.Dictionary\")\n\tWith objKeyMap\n\t\t.Add \"ABC\", \"2\" : .Add \"DEF\", \"3\" : .Add \"GHI\", \"4\" : .Add \"JKL\", \"5\"\n\t\t.Add \"MNO\", \"6\" : .Add \"PQRS\", \"7\" : .Add \"TUV\", \"8\" : .Add \"WXYZ\", \"9\"\n\tEnd With\n\n\nTotalWords = 0\nUniqueCombinations = 0\nSet objUniqueWords = CreateObject(\"Scripting.Dictionary\")\nSet objMoreThanOneWord = CreateObject(\"Scripting.Dictionary\")\n\nDo Until objInFile.AtEndOfStream\n\tWord = objInFile.ReadLine\n\tc = 0\n\tNum = \"\"\n\tIf Word <> \"\" Then\n\t\tFor i = 1 To Len(Word)\n\t\t\tFor Each Key In objKeyMap.Keys\n\t\t\t\tIf InStr(1,Key,Mid(Word,i,1),1) > 0 Then\n\t\t\t\t\tNum = Num & objKeyMap.Item(Key)\n\t\t\t\t\tc = c + 1\n\t\t\t\tEnd If\n\t\t\tNext\n\t\tNext\n\t\tIf c = Len(Word) Then\n\t\t\tTotalWords = TotalWords + 1\n\t\t\tIf objUniqueWords.Exists(Num) = False Then\n\t\t\t\tobjUniqueWords.Add Num, \"\"\n\t\t\t\tUniqueCombinations = UniqueCombinations + 1\n\t\t\tElse\n\t\t\t\tIf objMoreThanOneWord.Exists(Num) = False Then\n\t\t\t\t\tobjMoreThanOneWord.Add Num, \"\"\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tEnd If\n\tEnd If\nLoop\t\n\nWScript.Echo \"There are \" & TotalWords & \" words in \"\"unixdict.txt\"\" which can be represented by the digit key mapping.\" & vbCrLf &_\n\t\t\t \"They require \" & UniqueCombinations & \" digit combinations to represent them.\" & vbCrLf &_\n                         objMoreThanOneWord.Count &  \" digit combinations represent Textonyms.\"\n\nobjInFile.Close\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Vector;\n\npublic class RTextonyms {\n\n  private static final Map<Character, Character> mapping;\n  private int total, elements, textonyms, max_found;\n  private String filename, mappingResult;\n  private Vector<String> max_strings;\n  private Map<String, Vector<String>> values;\n\n  static {\n    mapping = new HashMap<Character, Character>();\n    mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');\n    mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');\n    mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');\n    mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');\n    mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');\n    mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');\n    mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');\n    mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');\n  }\n\n  public RTextonyms(String filename) {\n\n    this.filename = filename;\n    this.total = this.elements = this.textonyms = this.max_found = 0;\n    this.values = new HashMap<String, Vector<String>>();\n    this.max_strings = new Vector<String>();\n\n    return;\n  }\n\n  public void add(String line) {\n\n    String mapping = \"\";\n    total++;\n    if (!get_mapping(line)) {\n      return;\n    }\n    mapping = mappingResult;\n\n    if (values.get(mapping) == null) {\n      values.put(mapping, new Vector<String>());\n    }\n\n    int num_strings;\n    num_strings = values.get(mapping).size();\n    textonyms += num_strings == 1 ? 1 : 0;\n    elements++;\n\n    if (num_strings > max_found) {\n      max_strings.clear();\n      max_strings.add(mapping);\n      max_found = num_strings;\n    }\n    else if (num_strings == max_found) {\n      max_strings.add(mapping);\n    }\n\n    values.get(mapping).add(line);\n\n    return;\n  }\n\n  public void results() {\n\n    System.out.printf(\"Read %,d words from %s%n%n\", total, filename);\n    System.out.printf(\"There are %,d words in %s which can be represented by the digit key mapping.%n\", elements,\n        filename);\n    System.out.printf(\"They require %,d digit combinations to represent them.%n\", values.size());\n    System.out.printf(\"%,d digit combinations represent Textonyms.%n\", textonyms);\n    System.out.printf(\"The numbers mapping to the most words map to %,d words each:%n\", max_found + 1);\n    for (String key : max_strings) {\n      System.out.printf(\"%16s maps to: %s%n\", key, values.get(key).toString());\n    }\n    System.out.println();\n\n    return;\n  }\n\n  public void match(String key) {\n\n    Vector<String> match;\n    match = values.get(key);\n    if (match == null) {\n      System.out.printf(\"Key %s not found%n\", key);\n    }\n    else {\n      System.out.printf(\"Key %s matches: %s%n\", key, match.toString());\n    }\n\n    return;\n  }\n\n  private boolean get_mapping(String line) {\n\n    mappingResult = line;\n    StringBuilder mappingBuilder = new StringBuilder();\n    for (char cc : line.toCharArray()) {\n      if (Character.isAlphabetic(cc)) {\n        mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));\n      }\n      else if (Character.isDigit(cc)) {\n        mappingBuilder.append(cc);\n      }\n      else {\n        return false;\n      }\n    }\n    mappingResult = mappingBuilder.toString();\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n\n    String filename;\n    if (args.length > 0) {\n      filename = args[0];\n    }\n    else {\n      filename = \"./unixdict.txt\";\n    }\n    RTextonyms tc;\n    tc = new RTextonyms(filename);\n    Path fp = Paths.get(filename);\n    try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {\n      while (fs.hasNextLine()) {\n        tc.add(fs.nextLine());\n      }\n    }\n    catch (IOException ex) {\n      ex.printStackTrace();\n    }\n\n    List<String> numbers = Arrays.asList(\n        \"001\", \"228\", \"27484247\", \"7244967473642\",\n        \".\"\n        );\n\n    tc.results();\n    for (String number : numbers) {\n      if (number.equals(\".\")) {\n        System.out.println();\n      }\n      else {\n        tc.match(number);\n      }\n    }\n\n    return;\n  }\n}\n"}
{"id": 60298, "name": "Range extraction", "VB": "Public Function RangeExtraction(AList) As String\n\nConst RangeDelim = \"-\"          \nDim result As String\nDim InRange As Boolean\nDim Posn, ub, lb, rangestart, rangelen As Integer\n\nresult = \"\"\n\nub = UBound(AList)\nlb = LBound(AList)\nPosn = lb\nWhile Posn < ub\n  rangestart = Posn\n  rangelen = 0\n  InRange = True\n  \n  While InRange\n    rangelen = rangelen + 1\n    If Posn = ub Then\n      InRange = False\n    Else\n      InRange = (AList(Posn + 1) = AList(Posn) + 1)\n      Posn = Posn + 1\n    End If\n  Wend\n  If rangelen > 2 Then \n    result = result & \",\" & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))\n  Else \n    For i = rangestart To rangestart + rangelen - 1\n      result = result & \",\" & Format$(AList(i))\n    Next\n  End If\n  Posn = rangestart + rangelen\nWend\nRangeExtraction = Mid$(result, 2) \nEnd Function\n\n\nPublic Sub RangeTest()\n\n\nDim MyList As Variant\nMyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)\nDebug.Print \"a) \"; RangeExtraction(MyList)\n\n\nDim MyOtherList(1 To 20) As Integer\nMyOtherList(1) = -6\nMyOtherList(2) = -3\nMyOtherList(3) = -2\nMyOtherList(4) = -1\nMyOtherList(5) = 0\nMyOtherList(6) = 1\nMyOtherList(7) = 3\nMyOtherList(8) = 4\nMyOtherList(9) = 5\nMyOtherList(10) = 7\nMyOtherList(11) = 8\nMyOtherList(12) = 9\nMyOtherList(13) = 10\nMyOtherList(14) = 11\nMyOtherList(15) = 14\nMyOtherList(16) = 15\nMyOtherList(17) = 17\nMyOtherList(18) = 18\nMyOtherList(19) = 19\nMyOtherList(20) = 20\nDebug.Print \"b) \"; RangeExtraction(MyOtherList)\nEnd Sub\n", "Java": "public class RangeExtraction {\n\n    public static void main(String[] args) {\n        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n            37, 38, 39};\n\n        int len = arr.length;\n        int idx = 0, idx2 = 0;\n        while (idx < len) {\n            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);\n            if (idx2 - idx > 2) {\n                System.out.printf(\"%s-%s,\", arr[idx], arr[idx2 - 1]);\n                idx = idx2;\n            } else {\n                for (; idx < idx2; idx++)\n                    System.out.printf(\"%s,\", arr[idx]);\n            }\n        }\n    }\n}\n"}
{"id": 60299, "name": "Type detection", "VB": "Public Sub main()\n    Dim c(1) As Currency\n    Dim d(1) As Double\n    Dim dt(1) As Date\n    Dim a(1) As Integer\n    Dim l(1) As Long\n    Dim s(1) As Single\n    Dim e As Variant\n    Dim o As Object\n    Set o = New Application\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1 = 1)\n    Debug.Print TypeName(CByte(1))\n    Set o = New Collection\n    Debug.Print TypeName(o)\n    Debug.Print TypeName(1@)\n    Debug.Print TypeName(c)\n    Debug.Print TypeName(CDate(1))\n    Debug.Print TypeName(dt)\n    Debug.Print TypeName(CDec(1))\n    Debug.Print TypeName(1#)\n    Debug.Print TypeName(d)\n    Debug.Print TypeName(e)\n    Debug.Print TypeName(CVErr(1))\n    Debug.Print TypeName(1)\n    Debug.Print TypeName(a)\n    Debug.Print TypeName(1&)\n    Debug.Print TypeName(l)\n    Set o = Nothing\n    Debug.Print TypeName(o)\n    Debug.Print TypeName([A1])\n    Debug.Print TypeName(1!)\n    Debug.Print TypeName(s)\n    Debug.Print TypeName(CStr(1))\n    Debug.Print TypeName(Worksheets(1))\nEnd Sub\n", "Java": "public class TypeDetection {\n    private static void showType(Object a) {\n        if (a instanceof Integer) {\n            System.out.printf(\"'%s' is an integer\\n\", a);\n        } else if (a instanceof Double) {\n            System.out.printf(\"'%s' is a double\\n\", a);\n        } else if (a instanceof Character) {\n            System.out.printf(\"'%s' is a character\\n\", a);\n        } else {\n            System.out.printf(\"'%s' is some other type\\n\", a);\n        }\n    }\n\n    public static void main(String[] args) {\n        showType(5);\n        showType(7.5);\n        showType('d');\n        showType(true);\n    }\n}\n"}
{"id": 60300, "name": "Maximum triangle path sum", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\triangle.txt\",1,False)\n\t\nrow = Split(objinfile.ReadAll,vbCrLf)\n\nFor i = UBound(row) To 0 Step -1\n\trow(i) = Split(row(i),\" \")\n\tIf i < UBound(row) Then\n\t\tFor j = 0 To UBound(row(i))\n\t\t\tIf (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))\n\t\t\tElse\n\t\t\t\trow(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))\n\t\t\tEnd If\n\t\tNext\n\tEnd If\t\nNext\n\nWScript.Echo row(0)(0)\n\nobjinfile.Close\nSet objfso = Nothing\n", "Java": "import java.nio.file.*;\nimport static java.util.Arrays.stream;\n\npublic class MaxPathSum {\n\n    public static void main(String[] args) throws Exception {\n        int[][] data = Files.lines(Paths.get(\"triangle.txt\"))\n                .map(s -> stream(s.trim().split(\"\\\\s+\"))\n                        .mapToInt(Integer::parseInt)\n                        .toArray())\n                .toArray(int[][]::new);\n\n        for (int r = data.length - 1; r > 0; r--)\n            for (int c = 0; c < data[r].length - 1; c++)\n                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);\n\n        System.out.println(data[0][0]);\n    }\n}\n"}
{"id": 60301, "name": "Zhang-Suen thinning algorithm", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n"}
{"id": 60302, "name": "Zhang-Suen thinning algorithm", "VB": "Public n As Variant\nPrivate Sub init()\n    n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]\nEnd Sub\n\nPrivate Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim prev As String: prev = \"#\"\n    Dim next_ As String\n    Dim p2468 As String\n    For i = 1 To UBound(n)\n        next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)\n        wtb = wtb - (prev = \".\" And next_ <= \"#\")\n        bn = bn - (i > 1 And next_ <= \"#\")\n        If (i And 1) = 0 Then p2468 = p2468 & prev\n        prev = next_\n    Next i\n    If step = 2 Then \n        p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)\n        \n    End If\n    Dim ret(2) As Variant\n    ret(0) = wtb\n    ret(1) = bn\n    ret(2) = p2468\n    AB = ret\nEnd Function\n \nPrivate Sub Zhang_Suen(text As Variant)\n    Dim wtb As Integer\n    Dim bn As Integer\n    Dim changed As Boolean, changes As Boolean\n    Dim p2468 As String     \n    Dim x As Integer, y As Integer, step As Integer\n    Do While True\n        changed = False\n        For step = 1 To 2\n            changes = False\n            For y = 1 To UBound(text) - 1\n                For x = 2 To Len(text(y)) - 1\n                    If Mid(text(y), x, 1) = \"#\" Then\n                        ret = AB(text, y, x, step)\n                        wtb = ret(0)\n                        bn = ret(1)\n                        p2468 = ret(2)\n                        If wtb = 1 _\n                            And bn >= 2 And bn <= 6 _\n                            And InStr(1, Mid(p2468, 1, 3), \".\") _\n                            And InStr(1, Mid(p2468, 2, 3), \".\") Then\n                            changes = True\n                            text(y) = Left(text(y), x - 1) & \"!\" & Right(text(y), Len(text(y)) - x)\n                        End If\n                    End If\n                Next x\n            Next y\n            If changes Then\n                For y = 1 To UBound(text) - 1\n                    text(y) = Replace(text(y), \"!\", \".\")\n                Next y\n                changed = True\n            End If\n        Next step\n        If Not changed Then Exit Do\n    Loop\n    Debug.Print Join(text, vbCrLf)\nEnd Sub\n\nPublic Sub main()\n    init\n    Dim Small_rc(9) As String\n    Small_rc(0) = \"................................\"\n    Small_rc(1) = \".#########.......########.......\"\n    Small_rc(2) = \".###...####.....####..####......\"\n    Small_rc(3) = \".###....###.....###....###......\"\n    Small_rc(4) = \".###...####.....###.............\"\n    Small_rc(5) = \".#########......###.............\"\n    Small_rc(6) = \".###.####.......###....###......\"\n    Small_rc(7) = \".###..####..###.####..####.###..\"\n    Small_rc(8) = \".###...####.###..########..###..\"\n    Small_rc(9) = \"................................\"\n    Zhang_Suen (Small_rc)\nEnd Sub\n", "Java": "import java.awt.Point;\nimport java.util.*;\n\npublic class ZhangSuen {\n\n    final static String[] image = {\n        \"                                                          \",\n        \" #################                   #############        \",\n        \" ##################               ################        \",\n        \" ###################            ##################        \",\n        \" ########     #######          ###################        \",\n        \"   ######     #######         #######       ######        \",\n        \"   ######     #######        #######                      \",\n        \"   #################         #######                      \",\n        \"   ################          #######                      \",\n        \"   #################         #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######        #######                      \",\n        \"   ######     #######         #######       ######        \",\n        \" ########     #######          ###################        \",\n        \" ########     ####### ######    ################## ###### \",\n        \" ########     ####### ######      ################ ###### \",\n        \" ########     ####### ######         ############# ###### \",\n        \"                                                          \"};\n\n    final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},\n        {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};\n\n    final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},\n        {0, 4, 6}}};\n\n    static List<Point> toWhite = new ArrayList<>();\n    static char[][] grid;\n\n    public static void main(String[] args) {\n        grid = new char[image.length][];\n        for (int r = 0; r < image.length; r++)\n            grid[r] = image[r].toCharArray();\n\n        thinImage();\n    }\n\n    static void thinImage() {\n        boolean firstStep = false;\n        boolean hasChanged;\n\n        do {\n            hasChanged = false;\n            firstStep = !firstStep;\n\n            for (int r = 1; r < grid.length - 1; r++) {\n                for (int c = 1; c < grid[0].length - 1; c++) {\n\n                    if (grid[r][c] != '#')\n                        continue;\n\n                    int nn = numNeighbors(r, c);\n                    if (nn < 2 || nn > 6)\n                        continue;\n\n                    if (numTransitions(r, c) != 1)\n                        continue;\n\n                    if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n                        continue;\n\n                    toWhite.add(new Point(c, r));\n                    hasChanged = true;\n                }\n            }\n\n            for (Point p : toWhite)\n                grid[p.y][p.x] = ' ';\n            toWhite.clear();\n\n        } while (firstStep || hasChanged);\n\n        printResult();\n    }\n\n    static int numNeighbors(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')\n                count++;\n        return count;\n    }\n\n    static int numTransitions(int r, int c) {\n        int count = 0;\n        for (int i = 0; i < nbrs.length - 1; i++)\n            if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n                if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')\n                    count++;\n            }\n        return count;\n    }\n\n    static boolean atLeastOneIsWhite(int r, int c, int step) {\n        int count = 0;\n        int[][] group = nbrGroups[step];\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < group[i].length; j++) {\n                int[] nbr = nbrs[group[i][j]];\n                if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n                    count++;\n                    break;\n                }\n            }\n        return count > 1;\n    }\n\n    static void printResult() {\n        for (char[] row : grid)\n            System.out.println(row);\n    }\n}\n"}
{"id": 60303, "name": "Variable declaration reset", "VB": "Option Strict On\nOption Explicit On\n\nImports System.IO\n\nModule vMain\n\n    Public Sub Main\n        Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}\n        For i As Integer = 0 To Ubound(s)\n            Dim curr As Integer = s(i)\n            Dim prev As Integer\n            If i > 1 AndAlso curr = prev Then\n                  Console.Out.WriteLine(i)\n            End If\n            prev = curr\n        Next i\n    End Sub\n\nEnd Module\n", "Java": "public class VariableDeclarationReset {\n    public static void main(String[] args) {\n        int[] s = {1, 2, 2, 3, 4, 4, 5};\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            int prev = 0;\n\n            if (i > 0 && curr == prev) System.out.println(i);\n            prev = curr;\n        }\n\n        int gprev = 0;\n\n        \n        \n        for (int i = 0; i < s.length; ++i) {\n            int curr = s[i];\n            if (i > 0 && curr == gprev) System.out.println(i);\n            gprev = curr;\n        }\n    }\n}\n"}
{"id": 60304, "name": "Koch 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     if ori<0 then ori = ori+pi*2\n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     if ori>(pi*2) then ori=ori-pi*2\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   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      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 koch (n,le)\n  if n=0 then x.fw le :exit sub\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\n  x.rt 2\n  koch n-1, le/3\n  x.lt 1\n  koch n-1, le/3\nend sub\n\n dim x,i\nset x=new turtle\nx.iangle=60\nx.orient=0\nx.incr=3\nx.x=100:x.y=300\nfor i=0 to 3\n  koch 7,100\n  x.rt 2\nnext  \nset x=nothing  \n", "Java": "int l = 300;\n\nvoid setup() {\n  size(400, 400);\n  background(0, 0, 255);\n  stroke(255);\n  \n  translate(width/2.0, height/2.0);\n  \n  translate(-l/2.0, l*sqrt(3)/6.0);\n  for (int i = 1; i <= 3; i++) {\n    kcurve(0, l);\n    rotate(radians(120));\n    translate(-l, 0);\n  }\n}\n\nvoid kcurve(float x1, float x2) {\n  float s = (x2-x1)/3;\n  if (s < 5) {\n    pushMatrix();\n    translate(x1, 0);\n    line(0, 0, s, 0);\n    line(2*s, 0, 3*s, 0);\n    translate(s, 0);\n    rotate(radians(60));\n    line(0, 0, s, 0);\n    translate(s, 0);\n    rotate(radians(-120));\n    line(0, 0, s, 0);\n    popMatrix();\n    return;\n  }\n  pushMatrix();\n  translate(x1, 0);\n  kcurve(0, s);\n  kcurve(2*s, 3*s);\n  translate(s, 0);\n  rotate(radians(60));\n  kcurve(0, s);\n  translate(s, 0);\n  rotate(radians(-120));\n  kcurve(0, s);\n  popMatrix();\n}\n"}
{"id": 60305, "name": "Draw a pixel", "VB": "Sub draw()\n    Dim sh As Shape, sl As Shape\n    Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)\n    Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)\n    sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)\nEnd Sub\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n"}
{"id": 60306, "name": "Words from neighbour ones", "VB": "with createobject(\"ADODB.Stream\")\n  .charset =\"UTF-8\"\n  .open\n  .loadfromfile(\"unixdict.txt\")\n  s=.readtext\nend with  \na=split (s,vblf)\nset d=createobject(\"scripting.dictionary\")\nredim b(ubound(a))\ni=0\nfor each x in a\n  s=trim(x)\n  if len(s)>=9 then \n    if len(s)= 9 then d.add s,\"\"\n    b(i)=s\n    i=i+1   \n  end if\nnext\nredim preserve b(i-1)\nwscript.echo i\nj=1\nfor i=0 to ubound(b)-9\n  s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_\n  mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)\n  \n  if d.exists(s9) then \n    wscript.echo j,s9\n    d.remove(s9)\n    j=j+1\n  end if \nnext\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class NeighbourWords {\n    public static void main(String[] args) {\n        try {\n            int minLength = 9;\n            List<String> words = new ArrayList<>();\n            try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    if (line.length() >= minLength)\n                        words.add(line);\n                }\n            }\n            Collections.sort(words);\n            String previousWord = null;\n            int count = 0;\n            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {\n                StringBuilder sb = new StringBuilder(minLength);\n                for (int j = 0; j < minLength; ++j)\n                    sb.append(words.get(i + j).charAt(j));\n                String word = sb.toString();\n                if (word.equals(previousWord))\n                    continue;\n                if (Collections.binarySearch(words, word) >= 0)\n                    System.out.printf(\"%2d. %s\\n\", ++count, word);\n                previousWord = word;\n            }\n        } catch (Exception e)  {\n            e.printStackTrace();\n        }\n    }\n}\n"}
{"id": 60307, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 60308, "name": "Execute Brain____", "VB": "\n\n\n\nFunction BFInpt(s, sp, d, dp, i, ip, o)\n    While sp < Len(s)\n        Select Case Mid(s, sp + 1, 1)\n            Case \"+\"\n                newd = Asc(d(dp)) + 1\n                If newd > 255 Then newd = newd Mod 256    \n                d(dp) = Chr(newd)\n            Case \"-\"\n                newd = Asc(d(dp)) - 1\n                If newd < 0 Then newd = (newd Mod 256) + 256    \n                d(dp) = Chr(newd)\n            Case \">\"\n                dp = dp + 1\n                If dp > UBound(d) Then\n                    ReDim Preserve d(UBound(d) + 1)\n                    d(dp) = Chr(0)\n                End If\n            Case \"<\"\n                dp = dp - 1\n            Case \".\"\n                o = o & d(dp)\n            Case \",\"\n                If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)\n            Case \"[\"\n                If Asc(d(dp)) = 0 Then\n                    bracket = 1\n                    While bracket And sp < Len(s)\n                        sp = sp + 1\n                        If Mid(s, sp + 1, 1) = \"[\" Then\n                            bracket = bracket + 1\n                        ElseIf Mid(s, sp + 1, 1) = \"]\" Then\n                            bracket = bracket - 1\n                        End If\n                    WEnd\n                Else\n                    pos = sp - 1\n                    sp = sp + 1\n                    If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos\n                End If\n            Case \"]\"\n                BFInpt = Asc(d(dp)) <> 0\n                Exit Function\n        End Select\n        sp = sp + 1\n    WEnd\nEnd Function\n\n\nFunction BFuck(source, input)\n    Dim data() : ReDim data(0)\n    data(0)  = Chr(0)\n    DataPtr  = 0\n    SrcPtr   = 0\n    InputPtr = 0\n    output   = \"\"\n\n    BFInpt source , SrcPtr   , _\n           data   , DataPtr  , _\n           input  , InputPtr , _\n           output\n    BFuck = output\nEnd Function\n\n\n\n\n\n\ncode   = \">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>\" & _\n         \">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.\"\ninpstr = \"\"\nWScript.StdOut.Write BFuck(code, inpstr)\n", "Java": "import java.io.IOException;\n\npublic class Interpreter {\n\n    public final static int MEMORY_SIZE = 65536;\n\n    private final char[] memory = new char[MEMORY_SIZE];\n    private int dp;\n    private int ip;\n    private int border;\n\n    private void reset() {\n\n        for (int i = 0; i < MEMORY_SIZE; i++) {\n            memory[i] = 0;\n        }\n        ip = 0;\n        dp = 0;\n    }\n\n    private void load(String program) {\n\n        if (program.length() > MEMORY_SIZE - 2) {\n            throw new RuntimeException(\"Not enough memory.\");\n        }\n\n        reset();\n\n        for (; dp < program.length(); dp++) {\n            memory[dp] = program.charAt(dp);\n        }\n\n        \n        \n        border = dp;\n\n        dp += 1;\n    }\n\n    public void execute(String program) {\n\n        load(program);\n        char instruction = memory[ip];\n\n        while (instruction != 0) {\n\n            switch (instruction) {\n                case '>':\n                    dp++;\n                    if (dp == MEMORY_SIZE) {\n                        throw new RuntimeException(\"Out of memory.\");\n                    }\n                    break;\n                case '<':\n                    dp--;\n                    if (dp == border) {\n                        throw new RuntimeException(\"Invalid data pointer.\");\n                    }\n                    break;\n                case '+':\n                    memory[dp]++;\n                    break;\n                case '-':\n                    memory[dp]--;\n                    break;\n                case '.':\n                    System.out.print(memory[dp]);\n                    break;\n                case ',':\n                    try {\n                        \n                        memory[dp] = (char) System.in.read();\n                    } catch (IOException e) {\n                        throw new RuntimeException(e);\n                    }\n                    break;\n                case '[':\n                    if (memory[dp] == 0) {\n                        skipLoop();\n                    }\n                    break;\n                case ']':\n                    if (memory[dp] != 0) {\n                        loop();\n                    }\n                    break;\n                default:\n                    throw new RuntimeException(\"Unknown instruction.\");\n            }\n\n            instruction = memory[++ip];\n        }\n    }\n\n    private void skipLoop() {\n\n        int loopCount = 0;\n\n        while (memory[ip] != 0) {\n            if (memory[ip] == '[') {\n                loopCount++;\n            } else if (memory[ip] == ']') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip++;\n        }\n\n        if (memory[ip] == 0) {\n            throw new RuntimeException(\"Unable to find a matching ']'.\");\n        }\n    }\n\n    private void loop() {\n\n        int loopCount = 0;\n\n        while (ip >= 0) {\n            if (memory[ip] == ']') {\n                loopCount++;\n            } else if (memory[ip] == '[') {\n                loopCount--;\n                if (loopCount == 0) {\n                    return;\n                }\n            }\n            ip--;\n        }\n\n        if (ip == -1) {\n            throw new RuntimeException(\"Unable to find a matching '['.\");\n        }\n    }\n\n    public static void main(String[] args) {\n\n        Interpreter interpreter = new Interpreter();\n        interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n    }\n}\n"}
{"id": 60309, "name": "UTF-8 encode and decode", "VB": "Private Function unicode_2_utf8(x As Long) As Byte()\n    Dim y() As Byte\n    Dim r As Long\n    Select Case x\n        Case 0 To &H7F\n            ReDim y(0)\n            y(0) = x\n        Case &H80 To &H7FF\n            ReDim y(1)\n            y(0) = 192 + x \\ 64\n            y(1) = 128 + x Mod 64\n        Case &H800 To &H7FFF\n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case 32768 To 65535 \n            ReDim y(2)\n            y(2) = 128 + x Mod 64\n            r = x \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 224 + r \\ 64\n        Case &H10000 To &H10FFFF\n            ReDim y(3)\n            y(3) = 128 + x Mod 64\n            r = x \\ 64\n            y(2) = 128 + r Mod 64\n            r = r \\ 64\n            y(1) = 128 + r Mod 64\n            y(0) = 240 + r \\ 64\n        Case Else\n            MsgBox \"what else?\" & x & \" \" & Hex(x)\n    End Select\n    unicode_2_utf8 = y\nEnd Function\nPrivate Function utf8_2_unicode(x() As Byte) As Long\n    Dim first As Long, second As Long, third As Long, fourth As Long\n    Dim total As Long\n    Select Case UBound(x) - LBound(x)\n        Case 0 \n            If x(0) < 128 Then\n                total = x(0)\n            Else\n                MsgBox \"highest bit set error\"\n            End If\n        Case 1 \n            If x(0) \\ 32 = 6 Then\n                first = x(0) Mod 32\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                Else\n                    MsgBox \"mask error\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n            total = 64 * first + second\n        Case 2 \n            If x(0) \\ 16 = 14 Then\n                first = x(0) Mod 16\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                    Else\n                        MsgBox \"mask error last byte\"\n                    End If\n                Else\n                    MsgBox \"mask error middle byte\"\n                End If\n            Else\n                MsgBox \"leading byte error\"\n            End If\n                total = 4096 * first + 64 * second + third\n        Case 3 \n            If x(0) \\ 8 = 30 Then\n                first = x(0) Mod 8\n                If x(1) \\ 64 = 2 Then\n                    second = x(1) Mod 64\n                    If x(2) \\ 64 = 2 Then\n                        third = x(2) Mod 64\n                        If x(3) \\ 64 = 2 Then\n                            fourth = x(3) Mod 64\n                        Else\n                            MsgBox \"mask error last byte\"\n                        End If\n                    Else\n                        MsgBox \"mask error third byte\"\n                    End If\n                Else\n                    MsgBox \"mask error second byte\"\n                End If\n            Else\n                MsgBox \"mask error leading byte\"\n            End If\n            total = CLng(262144 * first + 4096 * second + 64 * third + fourth)\n        Case Else\n            MsgBox \"more bytes than expected\"\n        End Select\n        utf8_2_unicode = total\nEnd Function\nPublic Sub program()\n    Dim cp As Variant\n    Dim r() As Byte, s As String\n    cp = [{65, 246, 1046, 8364, 119070}] \n    Debug.Print \"ch  unicode  UTF-8 encoded  decoded\"\n    For Each cpi In cp\n        r = unicode_2_utf8(CLng(cpi))\n        On Error Resume Next\n        s = CStr(Hex(cpi))\n        Debug.Print ChrW(cpi); String$(10 - Len(s), \" \"); s,\n        If Err.Number = 5 Then Debug.Print \"?\"; String$(10 - Len(s), \" \"); s,\n        s = \"\"\n        For Each yz In r\n            s = s & CStr(Hex(yz)) & \" \"\n        Next yz\n        Debug.Print String$(13 - Len(s), \" \"); s;\n        s = CStr(Hex(utf8_2_unicode(r)))\n        Debug.Print String$(8 - Len(s), \" \"); s\n    Next cpi\nEnd Sub\n", "Java": "import java.nio.charset.StandardCharsets;\nimport java.util.Formatter;\n\npublic class UTF8EncodeDecode {\n\n    public static byte[] utf8encode(int codepoint) {\n        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);\n    }\n\n    public static int utf8decode(byte[] bytes) {\n        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);\n    }\n\n    public static void main(String[] args) {\n        System.out.printf(\"%-7s %-43s %7s\\t%s\\t%7s%n\",\n                \"Char\", \"Name\", \"Unicode\", \"UTF-8 encoded\", \"Decoded\");\n\n        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {\n            byte[] encoded = utf8encode(codepoint);\n            Formatter formatter = new Formatter();\n            for (byte b : encoded) {\n                formatter.format(\"%02X \", b);\n            }\n            String encodedHex = formatter.toString();\n            int decoded = utf8decode(encoded);\n            System.out.printf(\"%-7c %-43s U+%04X\\t%-12s\\tU+%04X%n\",\n                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);\n        }\n    }\n}\n"}
{"id": 60310, "name": "Magic squares of doubly even order", "VB": "\nn=8  \npattern=\"1001011001101001\"\nsize=n*n: w=len(size)\nmult=n\\4  \nwscript.echo \"Magic square : \" & n & \" x \" & n\ni=0\nFor r=0 To n-1\n\tl=\"\"\n\tFor c=0 To n-1\n\t\tbit=Mid(pattern, c\\mult+(r\\mult)*4+1, 1)\n\t\tIf bit=\"1\" Then t=i+1 Else t=size-i\n\t\tl=l & Right(Space(w) & t, w) & \" \"\n\t\ti=i+1\n\tNext \n\twscript.echo l\nNext \nwscript.echo \"Magic constant=\" & (n*n+1)*n/2\n", "Java": "public class MagicSquareDoublyEven {\n\n    public static void main(String[] args) {\n        int n = 8;\n        for (int[] row : magicSquareDoublyEven(n)) {\n            for (int x : row)\n                System.out.printf(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    static int[][] magicSquareDoublyEven(final int n) {\n        if (n < 4 || n % 4 != 0)\n            throw new IllegalArgumentException(\"base must be a positive \"\n                    + \"multiple of 4\");\n\n        \n        int bits = 0b1001_0110_0110_1001;\n        int size = n * n;\n        int mult = n / 4;  \n\n        int[][] result = new int[n][n];\n\n        for (int r = 0, i = 0; r < n; r++) {\n            for (int c = 0; c < n; c++, i++) {\n                int bitPos = c / mult + (r / mult) * 4;\n                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n            }\n        }\n        return result;\n    }\n}\n"}
{"id": 60311, "name": "Move-to-front algorithm", "VB": "Function mtf_encode(s)\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 1 To Len(s)\n\t\tchar = Mid(s,i,1)\n\t\tIf i = Len(s) Then\n\t\t\toutput = output & symbol_table.IndexOf(char,0)\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tElse\n\t\t\toutput = output & symbol_table.IndexOf(char,0) & \" \"\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_encode = output\nEnd Function\n\nFunction mtf_decode(s)\n\t\n\tcode = Split(s,\" \")\n\t\n\tSet symbol_table = CreateObject(\"System.Collections.ArrayList\")\n\tFor j = 97 To 122 \n\t\tsymbol_table.Add Chr(j)\n\tNext\n\toutput = \"\"\n\tFor i = 0 To UBound(code)\n\t\tchar = symbol_table(code(i))\n\t\toutput = output & char\n\t\tIf code(i) <> 0 Then\n\t\t\tsymbol_table.RemoveAt(symbol_table.LastIndexOf(char))\n\t\t\tsymbol_table.Insert 0,char\n\t\tEnd If\n\tNext\n\tmtf_decode = output\t\nEnd Function\n\n\nwordlist = Array(\"broood\",\"bananaaa\",\"hiphophiphop\")\nFor Each word In wordlist\n\tWScript.StdOut.Write word & \" encodes as \" & mtf_encode(word) & \" and decodes as \" &_\n\t\tmtf_decode(mtf_encode(word)) & \".\"\n\tWScript.StdOut.WriteBlankLines(1)\nNext\n", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class MTF{\n\tpublic static List<Integer> encode(String msg, String symTable){\n\t\tList<Integer> output = new LinkedList<Integer>();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(char c : msg.toCharArray()){\n\t\t\tint idx = s.indexOf(\"\" + c);\n\t\t\toutput.add(idx);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output;\n\t}\n\t\n\tpublic static String decode(List<Integer> idxs, String symTable){\n\t\tStringBuilder output = new StringBuilder();\n\t\tStringBuilder s = new StringBuilder(symTable);\n\t\tfor(int idx : idxs){\n\t\t\tchar c = s.charAt(idx);\n\t\t\toutput = output.append(c);\n\t\t\ts = s.deleteCharAt(idx).insert(0, c);\n\t\t}\n\t\treturn output.toString();\n\t}\n\t\n\tprivate static void test(String toEncode, String symTable){\n\t\tList<Integer> encoded = encode(toEncode, symTable);\n\t\tSystem.out.println(toEncode + \": \" + encoded);\n\t\tString decoded = decode(encoded, symTable);\n\t\tSystem.out.println((toEncode.equals(decoded) ? \"\" : \"in\") + \"correctly decoded to \" + decoded);\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString symTable = \"abcdefghijklmnopqrstuvwxyz\";\n\t\ttest(\"broood\", symTable);\n\t\ttest(\"bananaaa\", symTable);\n\t\ttest(\"hiphophiphop\", symTable);\n\t}\n}\n"}
{"id": 60312, "name": "Execute a system command", "VB": "Set objShell = CreateObject(\"WScript.Shell\")\nobjShell.Run \"%comspec% /K dir\",3,True\n", "Java": "import java.util.Scanner;\nimport java.io.*;\n\npublic class Program {\n    public static void main(String[] args) {    \t\n    \ttry {\n    \t\tProcess p = Runtime.getRuntime().exec(\"cmd /C dir\");\n    \t\tScanner sc = new Scanner(p.getInputStream());    \t\t\n    \t\twhile (sc.hasNext()) System.out.println(sc.nextLine());\n    \t}\n    \tcatch (IOException e) {\n    \t\tSystem.out.println(e.getMessage());\n    \t}\n    }\n}\n"}
{"id": 60313, "name": "XML validation", "VB": "Option explicit\n\nFunction fileexists(fn) \n  fileexists= CreateObject(\"Scripting.FileSystemObject\").FileExists(fn)\nEnd Function\n\nFunction xmlvalid(strfilename)\n  Dim xmldoc,xmldoc2,objSchemas \n  Set xmlDoc = CreateObject(\"Msxml2.DOMDocument.6.0\")\n  \n  If fileexists(Replace(strfilename,\".xml\",\".dtd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", False\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n  ElseIf fileexists(Replace(strfilename,\".xml\",\".xsd\")) Then\n    xmlDoc.setProperty \"ProhibitDTD\", True\n    xmlDoc.setProperty \"ResolveExternals\", True \n    xmlDoc.validateOnParse = True\n    xmlDoc.async = False\n    xmlDoc.load(strFileName)\n    \n    \n    Set xmlDoc2 = CreateObject(\"Msxml2.DOMDocument.6.0\")\n    xmlDoc2.validateOnParse = True\n    xmlDoc2.async = False\n    xmlDoc2.load(Replace (strfilename,\".xml\",\".xsd\"))\n    \n    \n    Set objSchemas = CreateObject(\"MSXML2.XMLSchemaCache.6.0\")\n    objSchemas.Add \"\", xmlDoc2\n  Else \n    Set xmlvalid= Nothing:Exit Function\n  End If\n  \n  Set xmlvalid=xmldoc.parseError \nEnd Function\n\n\n\nSub displayerror (parserr) \n  Dim strresult\n  If parserr is Nothing Then \n    strresult= \"could not find dtd or xsd for \" & strFileName\n  Else   \n    With parserr\n     Select Case .errorcode\n      Case 0 \n        strResult = \"Valid: \" & strFileName & vbCr\n      Case Else\n        strResult = vbCrLf & \"ERROR! Failed to validate \" & _\n        strFileName & vbCrLf &.reason & vbCr & _\n        \"Error code: \" & .errorCode & \", Line: \" & _\n        .line & \", Character: \" & _\n        .linepos & \", Source: \"\"\" & _\n        .srcText &  \"\"\" - \" & vbCrLf \n \n      End Select\n    End With\n  End If\n  WScript.Echo strresult\nEnd Sub\n\n\nDim strfilename\n\n\n\n\n\n\nstrfilename=\"shiporder.xml\"\ndisplayerror xmlvalid (strfilename)\n", "Java": "import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\nimport javax.xml.ws.Holder;\n\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\npublic class XmlValidation {\n\tpublic static void main(String... args) throws MalformedURLException {\n\t\tURL schemaLocation = new URL(\"http:\n\t\tURL documentLocation = new URL(\"http:\n\t\tif (validate(schemaLocation, documentLocation)) {\n\t\t\tSystem.out.println(\"document is valid\");\n\t\t} else {\n\t\t\tSystem.out.println(\"document is invalid\");\n\t\t}\n\t}\n\n\t\n\tpublic static boolean minimalValidate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\n\tpublic static boolean validate(URL schemaLocation, URL documentLocation) {\n\t\tSchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);\n\t\tfinal Holder<Boolean> valid = new Holder<>(true);\n\t\ttry {\n\t\t\tValidator validator = factory.newSchema(schemaLocation).newValidator();\n\t\t\t\n\t\t\tvalidator.setErrorHandler(new ErrorHandler(){\n\t\t\t\t@Override\n\t\t\t\tpublic void warning(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"warning: \" + exception.getMessage());\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void error(SAXParseException exception) {\n\t\t\t\t\tSystem.out.println(\"error: \" + exception.getMessage());\n\t\t\t\t\tvalid.value = false;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void fatalError(SAXParseException exception) throws SAXException {\n\t\t\t\t\tSystem.out.println(\"fatal error: \" + exception.getMessage());\n\t\t\t\t\tthrow exception;\n\t\t\t\t}});\n\t\t\tvalidator.validate(new StreamSource(documentLocation.toString()));\n\t\t\treturn valid.value;\n\t\t} catch (SAXException e) {\n\t\t\t\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\tSystem.err.println(e);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"}
{"id": 60314, "name": "Longest increasing subsequence", "VB": "Function LIS(arr)\n\tn = UBound(arr)\n\tDim p()\n\tReDim p(n)\n\tDim m()\n\tReDim m(n)\n\tl = 0\n\tFor i = 0 To n\n\t\tlo = 1\n\t\thi = l\n\t\tDo While lo <= hi\n\t\t\tmiddle = Int((lo+hi)/2)\n\t\t\tIf arr(m(middle)) < arr(i) Then\n\t\t\t\tlo = middle + 1\n\t\t\tElse\n\t\t\t\thi = middle - 1\n\t\t\tEnd If\n\t\tLoop\n\t\tnewl = lo\n\t\tp(i) = m(newl-1)\n\t\tm(newl) = i\n\t\tIf newL > l Then\n\t\t\tl = newl\n\t\tEnd If\n\tNext\n\tDim s()\n\tReDim s(l)\n\tk = m(l)\n\tFor i = l-1 To 0 Step - 1\n\t\ts(i) = arr(k)\n\t\tk = p(k)\n\tNext\n\tLIS = Join(s,\",\")\nEnd Function\n\nWScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))\nWScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))\n", "Java": "import java.util.*;\n\npublic class LIS {\n    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {\n        List<Node<E>> pileTops = new ArrayList<Node<E>>();\n        \n        for (E x : n) {\n\t    Node<E> node = new Node<E>();\n\t    node.value = x;\n            int i = Collections.binarySearch(pileTops, node);\n            if (i < 0) i = ~i;\n\t    if (i != 0)\n\t\tnode.pointer = pileTops.get(i-1);\n            if (i != pileTops.size())\n                pileTops.set(i, node);\n            else\n                pileTops.add(node);\n        }\n\t\n\tList<E> result = new ArrayList<E>();\n\tfor (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);\n                node != null; node = node.pointer)\n\t    result.add(node.value);\n\tCollections.reverse(result);\n\treturn result;\n    }\n\n    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {\n\tpublic E value;\n\tpublic Node<E> pointer;\n        public int compareTo(Node<E> y) { return value.compareTo(y.value); }\n    }\n\n    public static void main(String[] args) {\n\tList<Integer> d = Arrays.asList(3,2,6,4,5,1);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);\n\tSystem.out.printf(\"an L.I.S. of %s is %s\\n\", d, lis(d));\n    }\n}\n"}
{"id": 60315, "name": "Death Star", "VB": "\n\noption explicit               \n\nconst x_=0\nconst y_=1\nconst z_=2\nconst r_=3\n\nfunction clamp(x,b,t) \n  if x<b then \n     clamp=b \n  elseif x>t then\n    clamp =t \n  else \n    clamp=x \n  end if \nend function\n\nfunction dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function\n\nfunction normal (byval v) \n    dim ilen:ilen=1/sqr(dot(v,v)): \n    v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:\n    normal=v:\nend function\n\nfunction hittest(s,x,y)\n   dim z\n   z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2\n   if z>=0  then\n     z=sqr(z)\n     hittest=array(s(z_)-z,s(z_)+z)\n   else\n     hittest=0\n  end if\nend function\n            \nsub deathstar(pos, neg, sun, k, amb)\n  dim x,y,shades,result,shade,hp,hn,xx,b \n  shades=array(\" \",\".\",\":\",\"!\",\"*\",\"o\",\"e\",\"&\",\"#\",\"%\",\"@\")\n  for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 \n    for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5\n      hp=hittest (pos, x, y)\n      hn=hittest(neg,x,y)\n      if not  isarray(hp) then\n         result=0\n      elseif not isarray(hn) then\n        result=1\n      elseif hn(0)>hp(0)  then\n        result=1        \n      elseif  hn(1)>hp(1) then\n        result=0\n      elseif hn(1)>hp(0) then\n        result=2\n      else\n        result=1\n      end if\n\n      shade=-1\n      select case result\n      case 0\n        shade=0        \n      case 1\n        xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))\n        \n      case 2\n        xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))\n        \n      end select\n      if shade <>0 then\n        b=dot(sun,xx)^k+amb\n        shade=clamp((1-b) *ubound(shades),1,ubound(shades))        \n      end if       \n      wscript.stdout.write string(2,shades(shade))\n    next\n    wscript.stdout.write vbcrlf\n  next\nend sub\n\ndeathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1\n", "Java": "import javafx.application.Application;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Point3D;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyCode;\nimport javafx.scene.input.KeyEvent;\nimport javafx.scene.shape.MeshView;\nimport javafx.scene.shape.TriangleMesh;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class DeathStar extends Application {\n\n\tprivate static final int DIVISION = 200;\n\tfloat radius = 300;\n\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tPoint3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);\n\t\tfinal TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);\n\t\tMeshView a = new MeshView(triangleMesh);\n\n\t\ta.setTranslateY(radius);\n\t\ta.setTranslateX(radius);\n\t\ta.setRotationAxis(Rotate.Y_AXIS);\n\t\tScene scene = new Scene(new Group(a));\n\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\tprimaryStage.setScene(scene);\n\t\tprimaryStage.show();\n\t}\n\n\tstatic TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {\n\t\tRotate rotate = new Rotate(180, centerOtherSphere);\n\t\tfinal int div2 = division / 2;\n\n\t\tfinal int nPoints = division * (div2 - 1) + 2;\n\t\tfinal int nTPoints = (division + 1) * (div2 - 1) + division * 2;\n\t\tfinal int nFaces = division * (div2 - 2) * 2 + division * 2;\n\n\t\tfinal float rDiv = 1.f / division;\n\n\t\tfloat points[] = new float[nPoints * 3];\n\t\tfloat tPoints[] = new float[nTPoints * 2];\n\t\tint faces[] = new int[nFaces * 6];\n\n\t\tint pPos = 0, tPos = 0;\n\n\t\tfor (int y = 0; y < div2 - 1; ++y) {\n\t\t\tfloat va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;\n\t\t\tfloat sin_va = (float) Math.sin(va);\n\t\t\tfloat cos_va = (float) Math.cos(va);\n\n\t\t\tfloat ty = 0.5f + sin_va * 0.5f;\n\t\t\tfor (int i = 0; i < division; ++i) {\n\t\t\t\tdouble a = rDiv * i * 2 * (float) Math.PI;\n\t\t\t\tfloat hSin = (float) Math.sin(a);\n\t\t\t\tfloat hCos = (float) Math.cos(a);\n\t\t\t\tpoints[pPos + 0] = hSin * cos_va * radius;\n\t\t\t\tpoints[pPos + 2] = hCos * cos_va * radius;\n\t\t\t\tpoints[pPos + 1] = sin_va * radius;\n\n\t\t\t\tfinal Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);\n\t\t\t\tdouble distance = centerOtherSphere.distance(point3D);\n\t\t\t\tif (distance <= radius) {\n\t\t\t\t\tPoint3D subtract = centerOtherSphere.subtract(point3D);\n\t\t\t\t\tPoint3D transform = rotate.transform(subtract);\n\t\t\t\t\tpoints[pPos + 0] = (float) transform.getX();\n\t\t\t\t\tpoints[pPos + 1] = (float) transform.getY();\n\t\t\t\t\tpoints[pPos + 2] = (float) transform.getZ();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\ttPoints[tPos + 0] = 1 - rDiv * i;\n\t\t\t\ttPoints[tPos + 1] = ty;\n\t\t\t\tpPos += 3;\n\t\t\t\ttPos += 2;\n\t\t\t}\n\t\t\ttPoints[tPos + 0] = 0;\n\t\t\ttPoints[tPos + 1] = ty;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tpoints[pPos + 0] = 0;\n\t\tpoints[pPos + 1] = -radius;\n\t\tpoints[pPos + 2] = 0;\n\t\tpoints[pPos + 3] = 0;\n\t\tpoints[pPos + 4] = radius;\n\t\tpoints[pPos + 5] = 0;\n\t\tpPos += 6;\n\n\t\tint pS = (div2 - 1) * division;\n\n\t\tfloat textureDelta = 1.f / 256;\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tfor (int i = 0; i < division; ++i) {\n\t\t\ttPoints[tPos + 0] = rDiv * (0.5f + i);\n\t\t\ttPoints[tPos + 1] = 1 - textureDelta;\n\t\t\ttPos += 2;\n\t\t}\n\n\t\tint fIndex = 0;\n\t\tfor (int y = 0; y < div2 - 2; ++y) {\n\t\t\tfor (int x = 0; x < division; ++x) {\n\t\t\t\tint p0 = y * division + x;\n\t\t\t\tint p1 = p0 + 1;\n\t\t\t\tint p2 = p0 + division;\n\t\t\t\tint p3 = p1 + division;\n\n\t\t\t\tint t0 = p0 + y;\n\t\t\t\tint t1 = t0 + 1;\n\t\t\t\tint t2 = t0 + division + 1;\n\t\t\t\tint t3 = t1 + division + 1;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p0;\n\t\t\t\tfaces[fIndex + 1] = t0;\n\t\t\t\tfaces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 3] = t1;\n\t\t\t\tfaces[fIndex + 4] = p2;\n\t\t\t\tfaces[fIndex + 5] = t2;\n\t\t\t\tfIndex += 6;\n\n\t\t\t\t\n\t\t\t\tfaces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;\n\t\t\t\tfaces[fIndex + 1] = t3;\n\t\t\t\tfaces[fIndex + 2] = p2;\n\t\t\t\tfaces[fIndex + 3] = t2;\n\t\t\t\tfaces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;\n\t\t\t\tfaces[fIndex + 5] = t1;\n\t\t\t\tfIndex += 6;\n\t\t\t}\n\t\t}\n\n\t\tint p0 = pS;\n\t\tint tB = (div2 - 1) * (division + 1);\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p2 = x, p1 = x + 1, t0 = tB + x;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1 == division ? 0 : p1;\n\t\t\tfaces[fIndex + 3] = p1;\n\t\t\tfaces[fIndex + 4] = p2;\n\t\t\tfaces[fIndex + 5] = p2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tp0 = p0 + 1;\n\t\ttB = tB + division;\n\t\tint pB = (div2 - 2) * division;\n\n\t\tfor (int x = 0; x < division; ++x) {\n\t\t\tint p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;\n\t\t\tint t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;\n\t\t\tfaces[fIndex + 0] = p0;\n\t\t\tfaces[fIndex + 1] = t0;\n\t\t\tfaces[fIndex + 2] = p1;\n\t\t\tfaces[fIndex + 3] = t1;\n\t\t\tfaces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;\n\t\t\tfaces[fIndex + 5] = t2;\n\t\t\tfIndex += 6;\n\t\t}\n\n\t\tTriangleMesh m = new TriangleMesh();\n\t\tm.getPoints().setAll(points);\n\t\tm.getTexCoords().setAll(tPoints);\n\t\tm.getFaces().setAll(faces);\n\n\t\treturn m;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tlaunch(args);\n\t}\n\n}\n"}
{"id": 60316, "name": "Verify distribution uniformity_Chi-squared test", "VB": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n    \n    Dim Total As Long, Ei As Long, i As Integer\n    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n    Debug.Print \"[1] \"\"Data set:\"\" \";\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        Total = Total + ObservationFrequencies(i)\n        Debug.Print ObservationFrequencies(i); \" \";\n    Next i\n    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n    \n    Ei = Total / (DegreesOfFreedom + 1)\n    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n    Next i\n    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n    Debug.Print\n    Debug.Print \"   Chi-squared test for given frequencies\"\n    Debug.Print \"X-squared =\"; ChiSquared; \", \";\n    Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n    Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n    Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n    Dim O() As Variant\n    O = [{199809,200665,199607,200270,199649}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n    O = [{522573,244456,139979,71531,21461}]\n    Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n", "Java": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n    static double x2Dist(double[] data) {\n        double avg = stream(data).sum() / data.length;\n        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n        return sqs / avg;\n    }\n\n    static double x2Prob(double dof, double distance) {\n        return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n    }\n\n    static boolean x2IsUniform(double[] data, double significance) {\n        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n    }\n\n    public static void main(String[] a) {\n        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461}};\n\n        System.out.printf(\" %4s %12s  %12s %8s   %s%n\",\n                \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n        for (double[] ds : dataSets) {\n            int dof = ds.length - 1;\n            double dist = x2Dist(ds);\n            double prob = x2Prob(dof, dist);\n            System.out.printf(\"%4d %12.3f  %12.8f    %5s    %6s%n\",\n                    dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n                    Arrays.toString(ds));\n        }\n    }\n}\n"}
{"id": 60317, "name": "Brace expansion", "VB": "Module Module1\n\n    Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String)\n        Dim comma = False\n        While Not String.IsNullOrEmpty(s)\n            Dim gs = GetItem(s, depth)\n            Dim g = gs.Item1\n            s = gs.Item2\n            If String.IsNullOrEmpty(s) Then\n                Exit While\n            End If\n            out.AddRange(g)\n\n            If s(0) = \"}\" Then\n                If comma Then\n                    Return Tuple.Create(out, s.Substring(1))\n                End If\n                Return Tuple.Create(out.Select(Function(a) \"{\" + a + \"}\").ToList(), s.Substring(1))\n            End If\n\n            If s(0) = \",\" Then\n                comma = True\n                s = s.Substring(1)\n            End If\n        End While\n        Return Nothing\n    End Function\n\n    Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)\n        Dim out As New List(Of String) From {\"\"}\n        While Not String.IsNullOrEmpty(s)\n            Dim c = s(0)\n            If depth > 0 AndAlso (c = \",\" OrElse c = \"}\") Then\n                Return Tuple.Create(out, s)\n            End If\n            If c = \"{\" Then\n                Dim x = GetGroup(s.Substring(1), depth + 1)\n                If Not IsNothing(x) Then\n                    Dim tout As New List(Of String)\n                    For Each a In out\n                        For Each b In x.Item1\n                            tout.Add(a + b)\n                        Next\n                    Next\n                    out = tout\n                    s = x.Item2\n                    Continue While\n                End If\n            End If\n            If c = \"\\\" AndAlso s.Length > 1 Then\n                c += s(1)\n                s = s.Substring(1)\n            End If\n            out = out.Select(Function(a) a + c).ToList()\n            s = s.Substring(1)\n        End While\n        Return Tuple.Create(out, s)\n    End Function\n\n    Sub Main()\n        For Each s In {\n            \"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\, again\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}\"\n        }\n            Dim fmt = \"{0}\" + vbNewLine + vbTab + \"{1}\"\n            Dim parts = GetItem(s)\n            Dim res = String.Join(vbNewLine + vbTab, parts.Item1)\n            Console.WriteLine(fmt, s, res)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "public class BraceExpansion {\n\n    public static void main(String[] args) {\n        for (String s : new String[]{\"It{{em,alic}iz,erat}e{d,}, please.\",\n            \"~/{Downloads,Pictures}/*.{jpg,gif,png}\",\n            \"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\",\n            \"{}} some }{,{\\\\\\\\{ edge, edge} \\\\,}{ cases, {here} \\\\\\\\\\\\\\\\\\\\}\"}) {\n            System.out.println();\n            expand(s);\n        }\n    }\n\n    public static void expand(String s) {\n        expandR(\"\", s, \"\");\n    }\n\n    private static void expandR(String pre, String s, String suf) {\n        int i1 = -1, i2 = 0;\n        String noEscape = s.replaceAll(\"([\\\\\\\\]{2}|[\\\\\\\\][,}{])\", \"  \");\n        StringBuilder sb = null;\n\n        outer:\n        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {\n            i2 = i1 + 1;\n            sb = new StringBuilder(s);\n            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {\n                char c = noEscape.charAt(i2);\n                depth = (c == '{') ? ++depth : depth;\n                depth = (c == '}') ? --depth : depth;\n                if (c == ',' && depth == 1) {\n                    sb.setCharAt(i2, '\\u0000');\n                } else if (c == '}' && depth == 0 && sb.indexOf(\"\\u0000\") != -1)\n                    break outer;\n            }\n        }\n        if (i1 == -1) {\n            if (suf.length() > 0)\n                expandR(pre + s, suf, \"\");\n            else\n                System.out.printf(\"%s%s%s%n\", pre, s, suf);\n        } else {\n            for (String m : sb.substring(i1 + 1, i2).split(\"\\u0000\", -1))\n                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);\n        }\n    }\n}\n"}
{"id": 60318, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 60319, "name": "Call a function", "VB": "\n\n\nFunction no_arguments() As String\n    no_arguments = \"ok\"\nEnd Function\n\n\nFunction fixed_number(argument1 As Integer, argument2 As Integer)\n    fixed_number = argument1 + argument2\nEnd Function\n\n\nFunction optional_parameter(Optional argument1 = 1) As Integer\n    \n    optional_parameter = argument1\nEnd Function\n\n\nFunction variable_number(arguments As Variant) As Integer\n    variable_number = UBound(arguments)\nEnd Function\n\n\nFunction named_arguments(argument1 As Integer, argument2 As Integer) As Integer\n    named_arguments = argument1 + argument2\nEnd Function\n\n\nFunction statement() As String\n    Debug.Print \"function called as statement\"\n    statement = \"ok\"\nEnd Function\n\n\n\n\n\nFunction return_value() As String\n    return_value = \"ok\"\nEnd Function\n\n\n\n\n\n\nSub foo()\n    Debug.Print \"subroutine\",\nEnd Sub\n\nFunction bar() As String\n    bar = \"function\"\nEnd Function\n\n\nFunction passed_by_value(ByVal s As String) As String\n    s = \"written over\"\n    passed_by_value = \"passed by value\"\nEnd Function\n\nFunction passed_by_reference(ByRef s As String) As String\n    s = \"written over\"\n    passed_by_reference = \"passed by reference\"\nEnd Function\n\n\n\n\n\nSub no_parentheses(myargument As String)\n    Debug.Print myargument,\nEnd Sub\n\n\nPublic Sub calling_a_function()\n    \n    Debug.Print \"no arguments\", , no_arguments\n    Debug.Print \"no arguments\", , no_arguments()\n    \n    \n    \n    Debug.Print \"fixed_number\", , fixed_number(1, 1)\n    \n    \n    Debug.Print \"optional parameter\", optional_parameter\n    Debug.Print \"optional parameter\", optional_parameter(2)\n    \n    \n    Debug.Print \"variable number\", variable_number([{\"hello\", \"there\"}])\n    \n    \n    \n    Debug.Print \"named arguments\", named_arguments(argument2:=1, argument1:=1)\n    \n    \n    statement\n    \n    \n    s = \"no_arguments\"\n    Debug.Print \"first-class context\", Application.Run(s)\n    \n    \n    \n    returnvalue = return_value\n    Debug.Print \"obtained return value\", returnvalue\n    \n    \n    \n    \n    foo\n    Debug.Print , bar\n    \n    \n    Dim t As String\n    t = \"unaltered\"\n    Debug.Print passed_by_value(t), t\n    Debug.Print passed_by_reference(t), t\n    \n    \n    \n    \n    \n    no_parentheses \"calling a subroutine\"\n    Debug.Print \"does not require parentheses\"\n    Call no_parentheses(\"deprecated use\")\n    Debug.Print \"of parentheses\"\n    \nEnd Sub\n", "Java": "foo();             \nInt x = bar();     \n"}
{"id": 60320, "name": "GUI component interaction", "VB": "VERSION 5.00\nBegin VB.Form Form1 \n   Caption         =   \"Form1\"\n   ClientHeight    =   2265\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   2175\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2265\n   ScaleWidth      =   2175\n   StartUpPosition =   3  \n   Begin VB.CommandButton cmdRnd \n      Caption         =   \"Random\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   2\n      Top             =   1680\n      Width           =   1215\n   End\n   Begin VB.CommandButton cmdInc \n      Caption         =   \"Increment\"\n      Height          =   495\n      Left            =   120\n      TabIndex        =   1\n      Top             =   1080\n      Width           =   1215\n   End\n   Begin VB.TextBox txtValue \n      Height          =   495\n      Left            =   120\n      TabIndex        =   0\n      Text            =   \"0\"\n      Top             =   240\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n\nPrivate Sub Form_Load()\n    Randomize Timer\nEnd Sub\n\nPrivate Sub cmdRnd_Click()\n    If MsgBox(\"Random?\", vbYesNo) Then txtValue.Text = Int(Rnd * 11)\nEnd Sub\n\nPrivate Sub cmdInc_Click()\n    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1\nEnd Sub\n\nPrivate Sub txtValue_KeyPress(KeyAscii As Integer)\n    Select Case KeyAscii\n        Case 8, 43, 45, 48 To 57\n            \n        Case Else\n            KeyAscii = 0\n    End Select\nEnd Sub\n", "Java": "import java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class Interact extends JFrame{\n\tfinal JTextField numberField;\n\tfinal JButton incButton, randButton;\n\t\n\tpublic Interact(){\n\t\t\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); \n\t\t\n\t\tnumberField = new JTextField();\n\t\tincButton = new JButton(\"Increment\");\n\t\trandButton = new JButton(\"Random\");\n\t\t\n\t\tnumberField.setText(\"0\");\n\t\t\n\t\t\n\t\tnumberField.addKeyListener(new KeyListener(){\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\t\t\n\t\t\t\tif(!Character.isDigit(e.getKeyChar())){\n\t\t\t\t\t\n\t\t\t\t\te.consume();\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e){}\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e){}\n\t\t});\n\t\t\n\t\t\n\t\tincButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tString text = numberField.getText();\n\t\t\t\tif(text.isEmpty()){\n\t\t\t\t\tnumberField.setText(\"1\");\n\t\t\t\t}else{\n\t\t\t\t\tnumberField.setText((Long.valueOf(text) + 1) + \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\trandButton.addActionListener(new ActionListener(){\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\n\t\t\t\tif(JOptionPane.showConfirmDialog(null, \"Are you sure?\") ==\n\t\t\t\t\tJOptionPane.YES_OPTION){\n\t\t\t\t\t\n\t\t\t\t\tnumberField.setText(Long.toString((long)(Math.random() \n\t\t\t\t\t\t\t* Long.MAX_VALUE)));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\tsetLayout(new GridLayout(2, 1));\n\t\t\n\t\t\n\t\tJPanel buttonPanel = new JPanel();\n\t\t\n\t\t\n\t\tbuttonPanel.setLayout(new GridLayout(1, 2));\n\t\t\n\t\tbuttonPanel.add(incButton);\n\t\tbuttonPanel.add(randButton);\n\t\t\n\t\t\n\t\tadd(numberField);\n\t\tadd(buttonPanel);\n\t\t\n\t\tpack();\n\t\t\n\t}\n\n\tpublic static void main(String[] args){\n\t\tnew Interact().setVisible(true);\n\t}\n}\n"}
{"id": 60321, "name": "One of n lines in a file", "VB": "Dim chosen(10)\n\nFor j = 1 To 1000000\n\tc = one_of_n(10)\n\tchosen(c) = chosen(c) + 1\nNext\n\nFor k = 1 To 10\n\tWScript.StdOut.WriteLine k & \". \" & chosen(k)\nNext \n\nFunction one_of_n(n)\n\tRandomize\n\tFor i = 1 To n\n\t\tIf Rnd(1) < 1/i Then\n\t\t\tone_of_n = i\n\t\tEnd If\n\tNext\nEnd Function\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class OneOfNLines {\n\n\tstatic Random rand;\n\t\n\tpublic static int oneOfN(int n) {\n\t\tint choice = 0;\n\t\t\n\t\tfor(int i = 1; i < n; i++) {\n\t\t\tif(rand.nextInt(i+1) == 0)\n\t\t\t\tchoice = i;\n\t\t}\n\t\t\n\t\treturn choice;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10;\n\t\tint trials = 1000000;\n\t\tint[] bins = new int[n];\n\t\trand = new Random();\n\t\t\n\t\tfor(int i = 0; i < trials; i++)\n\t\t\tbins[oneOfN(n)]++;\n\t\t\n\t\t\n\t\tSystem.out.println(Arrays.toString(bins));\n\t}\n}\n"}
{"id": 60322, "name": "Spelling of ordinal numbers", "VB": "Private Function ordinal(s As String) As String\n    Dim irregs As New Collection\n    irregs.Add \"first\", \"one\"\n    irregs.Add \"second\", \"two\"\n    irregs.Add \"third\", \"three\"\n    irregs.Add \"fifth\", \"five\"\n    irregs.Add \"eighth\", \"eight\"\n    irregs.Add \"ninth\", \"nine\"\n    irregs.Add \"twelfth\", \"twelve\"\n    Dim i As Integer\n    For i = Len(s) To 1 Step -1\n        ch = Mid(s, i, 1)\n        If ch = \" \" Or ch = \"-\" Then Exit For\n    Next i\n    On Error GoTo 1\n    ord = irregs(Right(s, Len(s) - i))\n    ordinal = Left(s, i) & ord\n    Exit Function\n1:\n    If Right(s, 1) = \"y\" Then\n        s = Left(s, Len(s) - 1) & \"ieth\"\n    Else\n        s = s & \"th\"\n    End If\n    ordinal = s\nEnd Function\nPublic Sub ordinals()\n    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]\n    init\n    For i = 1 To UBound(tests)\n        Debug.Print ordinal(spell(tests(i)))\n    Next i\nEnd Sub\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class SpellingOfOrdinalNumbers {\n\n    public static void main(String[] args) {\n        for ( long test : new long[] {1,  2,  3,  4,  5,  11,  65,  100,  101,  272,  23456,  8007006005004003L} ) {\n            System.out.printf(\"%d = %s%n\", test, toOrdinal(test));\n        }\n    }\n\n    private static Map<String,String> ordinalMap = new HashMap<>();\n    static {\n        ordinalMap.put(\"one\", \"first\");\n        ordinalMap.put(\"two\", \"second\");\n        ordinalMap.put(\"three\", \"third\");\n        ordinalMap.put(\"five\", \"fifth\");\n        ordinalMap.put(\"eight\", \"eighth\");\n        ordinalMap.put(\"nine\", \"ninth\");\n        ordinalMap.put(\"twelve\", \"twelfth\");\n    }\n    \n    private static String toOrdinal(long n) {\n        String spelling = numToString(n);\n        String[] split = spelling.split(\" \");\n        String last = split[split.length - 1];\n        String replace = \"\";\n        if ( last.contains(\"-\") ) {\n            String[] lastSplit = last.split(\"-\");\n            String lastWithDash = lastSplit[1];\n            String lastReplace = \"\";\n            if ( ordinalMap.containsKey(lastWithDash) ) {\n                lastReplace = ordinalMap.get(lastWithDash);\n            }\n            else if ( lastWithDash.endsWith(\"y\") ) {\n                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + \"ieth\";\n            }\n            else {\n                lastReplace = lastWithDash + \"th\";\n            }\n            replace = lastSplit[0] + \"-\" + lastReplace;\n        }\n        else {\n            if ( ordinalMap.containsKey(last) ) {\n                replace = ordinalMap.get(last);\n            }\n            else if ( last.endsWith(\"y\") ) {\n                replace = last.substring(0, last.length() - 1) + \"ieth\";\n            }\n            else {\n                replace = last + \"th\";\n            }\n        }\n        split[split.length - 1] = replace;\n        return String.join(\" \", split);\n    }\n\n    private static final String[] nums = new String[] {\n            \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \n            \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    \n    private static final String[] tens = new String[] {\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\n    private static final String numToString(long n) {\n        return numToStringHelper(n);\n    }\n    \n    private static final String numToStringHelper(long n) {\n        if ( n < 0 ) {\n            return \"negative \" + numToStringHelper(-n);\n        }\n        int index = (int) n;\n        if ( n <= 19 ) {\n            return nums[index];\n        }\n        if ( n <= 99 ) {\n            return tens[index/10] + (n % 10 > 0 ? \"-\" + numToStringHelper(n % 10) : \"\");\n        }\n        String label = null;\n        long factor = 0;\n        if ( n <= 999 ) {\n            label = \"hundred\";\n            factor = 100;\n        }\n        else if ( n <= 999999) {\n            label = \"thousand\";\n            factor = 1000;\n        }\n        else if ( n <= 999999999) {\n            label = \"million\";\n            factor = 1000000;\n        }\n        else if ( n <= 999999999999L) {\n            label = \"billion\";\n            factor = 1000000000;\n        }\n        else if ( n <= 999999999999999L) {\n            label = \"trillion\";\n            factor = 1000000000000L;\n        }\n        else if ( n <= 999999999999999999L) {\n            label = \"quadrillion\";\n            factor = 1000000000000000L;\n        }\n        else {\n            label = \"quintillion\";\n            factor = 1000000000000000000L;\n        }\n        return numToStringHelper(n / factor) + \" \" + label + (n % factor > 0 ? \" \" + numToStringHelper(n % factor ) : \"\");\n    }\n\n}\n"}
{"id": 60323, "name": "Self-describing numbers", "VB": "Function IsSelfDescribing(n)\n\tIsSelfDescribing = False\n\tSet digit = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 1 To Len(n)\n\t\tk = Mid(n,i,1)\n\t\tIf digit.Exists(k) Then\n\t\t\tdigit.Item(k) = digit.Item(k) + 1\n\t\tElse\n\t\t\tdigit.Add k,1\n\t\tEnd If\t\n\tNext\n\tc = 0\n\tFor j = 0 To Len(n)-1\n\t\tl = Mid(n,j+1,1)\n\t\tIf digit.Exists(CStr(j)) Then\n\t\t\tIf digit.Item(CStr(j)) = CInt(l) Then\n\t\t\t\tc = c + 1\n\t\t\tEnd If\n\t\tElseIf l = 0 Then\n\t\t\tc = c + 1\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\n\tIf c = Len(n) Then\n\t\tIsSelfDescribing = True\n\tEnd If\nEnd Function\n\n\nstart_time = Now\ns = \"\"\nFor m = 1 To 100000000\n\tIf \tIsSelfDescribing(m) Then\n\t\tWScript.StdOut.WriteLine m\n\tEnd If\nNext\nend_time = Now\nWScript.StdOut.WriteLine \"Elapse Time: \" & DateDiff(\"s\",start_time,end_time) & \" seconds\"\n", "Java": "public class SelfDescribingNumbers{\n    public static boolean isSelfDescribing(int a){\n        String s = Integer.toString(a);\n        for(int i = 0; i < s.length(); i++){\n            String s0 = s.charAt(i) + \"\";\n            int b = Integer.parseInt(s0); \n            int count = 0;\n            for(int j = 0; j < s.length(); j++){\n                int temp = Integer.parseInt(s.charAt(j) + \"\");\n                if(temp == i){\n                    count++;\n                }\n                if (count > b) return false;\n            }\n            if(count != b) return false;\n        }\n        return true;\n    }\n\n    public static void main(String[] args){\n        for(int i = 0; i < 100000000; i++){\n            if(isSelfDescribing(i)){\n                System.out.println(i);\n             }\n        }\n    }\n}\n"}
{"id": 60324, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 60325, "name": "Addition chains", "VB": "Module Module1\n\n    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)\n        Dim result As New List(Of Integer) From {\n            n\n        }\n        result.AddRange(seq)\n        Return result\n    End Function\n\n    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If pos > min_len OrElse seq(0) > n Then\n            Return Tuple.Create(min_len, 0)\n        End If\n        If seq(0) = n Then\n            Return Tuple.Create(pos, 1)\n        End If\n        If pos < min_len Then\n            Return TryPerm(0, pos, seq, n, min_len)\n        End If\n        Return Tuple.Create(min_len, 0)\n    End Function\n\n    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)\n        If i > pos Then\n            Return Tuple.Create(min_len, 0)\n        End If\n\n        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)\n        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)\n\n        If res2.Item1 < res1.Item1 Then\n            Return res2\n        End If\n        If res2.Item1 = res1.Item1 Then\n            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)\n        End If\n\n        Throw New Exception(\"TryPerm exception\")\n    End Function\n\n    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)\n        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)\n    End Function\n\n    Sub FindBrauer(num As Integer)\n        Dim res = InitTryPerm(num)\n        Console.WriteLine(\"N = {0}\", num)\n        Console.WriteLine(\"Minimum length of chains: L(n) = {0}\", res.Item1)\n        Console.WriteLine(\"Number of minimum length Brauer chains: {0}\", res.Item2)\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n        Array.ForEach(nums, Sub(n) FindBrauer(n))\n    End Sub\n\nEnd Module\n", "Java": "public class AdditionChains {\n    private static class Pair {\n        int f, s;\n\n        Pair(int f, int s) {\n            this.f = f;\n            this.s = s;\n        }\n    }\n\n    private static int[] prepend(int n, int[] seq) {\n        int[] result = new int[seq.length + 1];\n        result[0] = n;\n        System.arraycopy(seq, 0, result, 1, seq.length);\n        return result;\n    }\n\n    private static Pair check_seq(int pos, int[] seq, int n, int min_len) {\n        if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);\n        else if (seq[0] == n) return new Pair(pos, 1);\n        else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);\n        else return new Pair(min_len, 0);\n    }\n\n    private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {\n        if (i > pos) return new Pair(min_len, 0);\n\n        Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);\n        Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);\n\n        if (res2.f < res1.f) return res2;\n        else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);\n        else throw new RuntimeException(\"Try_perm exception\");\n    }\n\n    private static Pair init_try_perm(int x) {\n        return try_perm(0, 0, new int[]{1}, x, 12);\n    }\n\n    private static void find_brauer(int num) {\n        Pair res = init_try_perm(num);\n        System.out.println();\n        System.out.println(\"N = \" + num);\n        System.out.println(\"Minimum length of chains: L(n)= \" + res.f);\n        System.out.println(\"Number of minimum length Brauer chains: \" + res.s);\n    }\n\n    public static void main(String[] args) {\n        int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n        for (int i : nums) {\n            find_brauer(i);\n        }\n    }\n}\n"}
{"id": 60326, "name": "Repeat", "VB": "Private Sub Repeat(rid As String, n As Integer)\n    For i = 1 To n\n        Application.Run rid\n    Next i\nEnd Sub\n \nPrivate Sub Hello()\n    Debug.Print \"Hello\"\nEnd Sub\n \nPublic Sub main()\n    Repeat \"Hello\", 5\nEnd Sub\n", "Java": "import java.util.function.Consumer;\nimport java.util.stream.IntStream;\n\npublic class Repeat {\n\n    public static void main(String[] args) {\n        repeat(3, (x) -> System.out.println(\"Example \" + x));\n    }\n\n    static void repeat (int n, Consumer<Integer> fun) {\n        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));\n    }\n}\n"}
{"id": 60327, "name": "Sparkline in unicode", "VB": "\n\nsub ensure_cscript()\nif instrrev(ucase(WScript.FullName),\"WSCRIPT.EXE\")then\n   createobject(\"wscript.shell\").run \"CSCRIPT //nologo \"\"\" &_\n     WScript.ScriptFullName &\"\"\"\" ,,0\n   wscript.quit\n end if\nend sub \n\nclass bargraph\n  private bar,mn,mx,nn,cnt\n\n  Private sub class_initialize()\n     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_\n     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)\n     nn=8\n  end sub\n\n\n  public function bg (s)\n    a=split(replace(replace(s,\",\",\" \"),\"  \",\" \"),\" \")\n\n    mn=999999:mx=-999999:cnt=ubound(a)+1\n    for i=0 to ubound(a)\n       a(i)=cdbl(trim(a(i)))\n       if a(i)>mx then mx=a(i) \n       if a(i)<mn then mn=a(i) \n    next\n   \n    ss=\"Data:    \"\n    for i=0 to ubound(a) :ss=ss & right (\"     \"& a(i),6) :next\n    \n    ss=ss+vbcrlf + \"sparkline: \"  \n    \n    for i=0 to ubound(a)\n       x=scale(a(i))\n       \n       ss=ss & string(6,mid(bar,x,1))\n    next\n    bg=ss &vbcrlf & \"min: \"&mn & \"  max: \"& mx & _\n      \" cnt: \"& ubound(a)+1 &vbcrlf\n  end function   \n\n  private function scale(x)\n    if x=<mn then \n      scale=1\n    elseif x>=mx then\n      scale=nn\n    else\n      scale=int(nn* (x-mn)/(mx-mn)+1)\n    end if  \n  end function    \n\nend class\n\nensure_cscript\n\nset b=new bargraph\nwscript.stdout.writeblanklines 2\nwscript.echo b.bg(\"1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1\")\nwscript.echo b.bg(\"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\")\nwscript.echo b.bg(\"0, 1, 19, 20\")\nwscript.echo b.bg(\"0, 999, 4000, 4999, 7000, 7999\")\nset b=nothing\n\nwscript.echo \"If bars don\n\"font to DejaVu Sans Mono or any other that has the bargrph characters\" & _\nvbcrlf\n\nwscript.stdout.write \"Press any key..\" : wscript.stdin.read 1\n", "Java": "public class Sparkline \n{\n\tString bars=\"▁▂▃▄▅▆▇█\";\n\tpublic static void main(String[] args)\n\t{\n\t\tSparkline now=new Sparkline();\n\t\tfloat[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};\n\t\tnow.display1D(arr);\n\t\tSystem.out.println(now.getSparkline(arr));\n\t\tfloat[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};\n\t\tnow.display1D(arr1);\n\t\tSystem.out.println(now.getSparkline(arr1));\n\t}\n\tpublic void display1D(float[] 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\tpublic String getSparkline(float[] arr)\n\t{\n\t\tfloat min=Integer.MAX_VALUE;\n\t\tfloat max=Integer.MIN_VALUE;\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\tif(arr[i]<min)\n\t\t\t\tmin=arr[i];\n\t\t\tif(arr[i]>max)\n\t\t\t\tmax=arr[i];\n\t\t}\n\t\tfloat range=max-min;\n\t\tint num=bars.length()-1;\n\t\tString line=\"\";\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t{\n\t\t\t\n\t\t\tline+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));\n\t\t}\n\t\treturn line;\n\t}\n}\n"}
{"id": 60328, "name": "Modular inverse", "VB": "Private Function mul_inv(a As Long, n As Long) As Variant\n    If n < 0 Then n = -n\n    If a < 0 Then a = n - ((-a) Mod n)\n    Dim t As Long: t = 0\n    Dim nt As Long: nt = 1\n    Dim r As Long: r = n\n    Dim nr As Long: nr = a\n    Dim q As Long\n    Do While nr <> 0\n        q = r \\ nr\n        tmp = t\n        t = nt\n        nt = tmp - q * nt\n        tmp = r\n        r = nr\n        nr = tmp - q * nr\n    Loop\n    If r > 1 Then\n        mul_inv = \"a is not invertible\"\n    Else\n        If t < 0 Then t = t + n\n        mul_inv = t\n    End If\nEnd Function\nPublic Sub mi()\n    Debug.Print mul_inv(42, 2017)\n    Debug.Print mul_inv(40, 1)\n    Debug.Print mul_inv(52, -217) \n    Debug.Print mul_inv(-486, 217)\n    Debug.Print mul_inv(40, 2018)\nEnd Sub\n", "Java": "System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));\n"}
{"id": 60329, "name": "Hello world_Web server", "VB": "Class HTTPSock\nInherits TCPSocket\n  Event Sub DataAvailable()\n    Dim headers As New InternetHeaders\n    headers.AppendHeader(\"Content-Length\", Str(LenB(\"Goodbye, World!\")))\n    headers.AppendHeader(\"Content-Type\", \"text/plain\")\n    headers.AppendHeader(\"Content-Encoding\", \"identity\")\n    headers.AppendHeader(\"Connection\", \"close\")\n    Dim data As String = \"HTTP/1.1 200 OK\" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + \"Goodbye, World!\"\n    Me.Write(data)\n    Me.Close\n  End Sub\nEnd Class\n\nClass HTTPServ\nInherits ServerSocket\n  Event Sub AddSocket() As TCPSocket\n    Return New HTTPSock\n  End Sub\nEnd Class\n\nClass App\nInherits Application\n  Event Sub Run(Args() As String)\n    Dim sock As New HTTPServ\n    sock.Port = 8080\n    sock.Listen()\n    While True\n      App.DoEvents\n    Wend\n  End Sub\nEnd Class\n", "Java": "import java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class HelloWorld{\n  public static void main(String[] args) throws IOException{\n    ServerSocket listener = new ServerSocket(8080);\n    while(true){\n      Socket sock = listener.accept();\n      new PrintWriter(sock.getOutputStream(), true).\n                println(\"Goodbye, World!\");\n      sock.close();\n    }\n  }\n}\n"}
{"id": 60330, "name": "Terminal control_Clear the screen", "VB": "System.Console.Clear()\n", "Java": "public class Clear\n{\n    public static void main (String[] args)\n    {\n        System.out.print(\"\\033[2J\");\n    }\n}\n"}
{"id": 60331, "name": "Sorting algorithms_Pancake sort", "VB": "\n\n\nPublic Sub printarray(A)\n  For i = LBound(A) To UBound(A)\n    Debug.Print A(i),\n  Next\n  Debug.Print\nEnd Sub\n\nPublic Sub Flip(ByRef A, p1, p2, trace)\n\n If trace Then Debug.Print \"we\n Cut = Int((p2 - p1 + 1) / 2)\n For i = 0 To Cut - 1\n   \n   temp = A(i)\n   A(i) = A(p2 - i)\n   A(p2 - i) = temp\n Next\nEnd Sub\n\nPublic Sub pancakesort(ByRef A(), Optional trace As Boolean = False)\n\n\nlb = LBound(A)\nub = UBound(A)\nLength = ub - lb + 1\nIf Length <= 1 Then \n  Exit Sub\nEnd If\n\nFor i = ub To lb + 1 Step -1\n  \n  P = lb\n  Maximum = A(P)\n  For j = lb + 1 To i\n    If A(j) > Maximum Then\n      P = j\n      Maximum = A(j)\n    End If\n  Next j\n  \n  If P < i Then\n    \n    If P > 1 Then\n      Flip A, lb, P, trace\n      If trace Then printarray A\n    End If\n    \n    Flip A, lb, i, trace\n    If trace Then printarray A\n  End If\nNext i\nEnd Sub\n\n\nPublic Sub TestPancake(Optional trace As Boolean = False)\nDim A()\nA = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)\nDebug.Print \"Initial array:\"\nprintarray A\npancakesort A, trace\nDebug.Print \"Final array:\"\nprintarray A\nEnd Sub\n", "Java": "public class PancakeSort\n{\n   int[] heap;\n\n   public String toString() {\n      String info = \"\";\n      for (int x: heap)\n         info += x + \" \";\n      return info;\n   }\n    \n   public void flip(int n) {\n      for (int i = 0; i < (n+1) / 2; ++i) {\n         int tmp = heap[i];\n         heap[i] = heap[n-i];\n         heap[n-i] = tmp;\n      }      \n      System.out.println(\"flip(0..\" + n + \"): \" + toString());\n   }\n   \n   public int[] minmax(int n) {\n      int xm, xM;\n      xm = xM = heap[0];\n      int posm = 0, posM = 0;\n      \n      for (int i = 1; i < n; ++i) {\n         if (heap[i] < xm) {\n            xm = heap[i];\n            posm = i;\n         }\n         else if (heap[i] > xM) {\n            xM = heap[i];\n            posM = i;\n         }\n      }\n      return new int[] {posm, posM};\n   }\n   \n   public void sort(int n, int dir) {\n      if (n == 0) return;\n         \n      int[] mM = minmax(n);\n      int bestXPos = mM[dir];\n      int altXPos = mM[1-dir];\n      boolean flipped = false;\n      \n      if (bestXPos == n-1) {\n         --n;\n      }\n      else if (bestXPos == 0) {\n         flip(n-1);\n         --n;\n      }\n      else if (altXPos == n-1) {\n         dir = 1-dir;\n         --n;\n         flipped = true;\n      }\n      else {\n         flip(bestXPos);\n      }\n      sort(n, dir);\n\n      if (flipped) {\n         flip(n);\n      }\n   }\n   \n   PancakeSort(int[] numbers) {\n      heap = numbers;\n      sort(numbers.length, 1);\n   } \n \n   public static void main(String[] args) {\n      int[] numbers = new int[args.length];\n      for (int i = 0; i < args.length; ++i)\n         numbers[i] = Integer.valueOf(args[i]);\n\n      PancakeSort pancakes = new PancakeSort(numbers);\n      System.out.println(pancakes);\n   }\n}\n"}
{"id": 60332, "name": "Chemical calculator", "VB": "Module Module1\n\n    Dim atomicMass As New Dictionary(Of String, Double) From {\n        {\"H\", 1.008},\n        {\"He\", 4.002602},\n        {\"Li\", 6.94},\n        {\"Be\", 9.0121831},\n        {\"B\", 10.81},\n        {\"C\", 12.011},\n        {\"N\", 14.007},\n        {\"O\", 15.999},\n        {\"F\", 18.998403163},\n        {\"Ne\", 20.1797},\n        {\"Na\", 22.98976928},\n        {\"Mg\", 24.305},\n        {\"Al\", 26.9815385},\n        {\"Si\", 28.085},\n        {\"P\", 30.973761998},\n        {\"S\", 32.06},\n        {\"Cl\", 35.45},\n        {\"Ar\", 39.948},\n        {\"K\", 39.0983},\n        {\"Ca\", 40.078},\n        {\"Sc\", 44.955908},\n        {\"Ti\", 47.867},\n        {\"V\", 50.9415},\n        {\"Cr\", 51.9961},\n        {\"Mn\", 54.938044},\n        {\"Fe\", 55.845},\n        {\"Co\", 58.933194},\n        {\"Ni\", 58.6934},\n        {\"Cu\", 63.546},\n        {\"Zn\", 65.38},\n        {\"Ga\", 69.723},\n        {\"Ge\", 72.63},\n        {\"As\", 74.921595},\n        {\"Se\", 78.971},\n        {\"Br\", 79.904},\n        {\"Kr\", 83.798},\n        {\"Rb\", 85.4678},\n        {\"Sr\", 87.62},\n        {\"Y\", 88.90584},\n        {\"Zr\", 91.224},\n        {\"Nb\", 92.90637},\n        {\"Mo\", 95.95},\n        {\"Ru\", 101.07},\n        {\"Rh\", 102.9055},\n        {\"Pd\", 106.42},\n        {\"Ag\", 107.8682},\n        {\"Cd\", 112.414},\n        {\"In\", 114.818},\n        {\"Sn\", 118.71},\n        {\"Sb\", 121.76},\n        {\"Te\", 127.6},\n        {\"I\", 126.90447},\n        {\"Xe\", 131.293},\n        {\"Cs\", 132.90545196},\n        {\"Ba\", 137.327},\n        {\"La\", 138.90547},\n        {\"Ce\", 140.116},\n        {\"Pr\", 140.90766},\n        {\"Nd\", 144.242},\n        {\"Pm\", 145},\n        {\"Sm\", 150.36},\n        {\"Eu\", 151.964},\n        {\"Gd\", 157.25},\n        {\"Tb\", 158.92535},\n        {\"Dy\", 162.5},\n        {\"Ho\", 164.93033},\n        {\"Er\", 167.259},\n        {\"Tm\", 168.93422},\n        {\"Yb\", 173.054},\n        {\"Lu\", 174.9668},\n        {\"Hf\", 178.49},\n        {\"Ta\", 180.94788},\n        {\"W\", 183.84},\n        {\"Re\", 186.207},\n        {\"Os\", 190.23},\n        {\"Ir\", 192.217},\n        {\"Pt\", 195.084},\n        {\"Au\", 196.966569},\n        {\"Hg\", 200.592},\n        {\"Tl\", 204.38},\n        {\"Pb\", 207.2},\n        {\"Bi\", 208.9804},\n        {\"Po\", 209},\n        {\"At\", 210},\n        {\"Rn\", 222},\n        {\"Fr\", 223},\n        {\"Ra\", 226},\n        {\"Ac\", 227},\n        {\"Th\", 232.0377},\n        {\"Pa\", 231.03588},\n        {\"U\", 238.02891},\n        {\"Np\", 237},\n        {\"Pu\", 244},\n        {\"Am\", 243},\n        {\"Cm\", 247},\n        {\"Bk\", 247},\n        {\"Cf\", 251},\n        {\"Es\", 252},\n        {\"Fm\", 257},\n        {\"Uue\", 315},\n        {\"Ubn\", 299}\n    }\n\n    Function Evaluate(s As String) As Double\n        s += \"[\"\n        Dim sum = 0.0\n        Dim symbol = \"\"\n        Dim number = \"\"\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            If \"@\" <= c AndAlso c <= \"[\" Then\n                \n                Dim n = 1\n                If number <> \"\" Then\n                    n = Integer.Parse(number)\n                End If\n                If symbol <> \"\" Then\n                    sum += atomicMass(symbol) * n\n                End If\n                If c = \"[\" Then\n                    Exit For\n                End If\n                symbol = c.ToString\n                number = \"\"\n            ElseIf \"a\" <= c AndAlso c <= \"z\" Then\n                symbol += c\n            ElseIf \"0\" <= c AndAlso c <= \"9\" Then\n                number += c\n            Else\n                Throw New Exception(String.Format(\"Unexpected symbol {0} in molecule\", c))\n            End If\n        Next\n        Return sum\n    End Function\n\n    Function ReplaceFirst(text As String, search As String, replace As String) As String\n        Dim pos = text.IndexOf(search)\n        If pos < 0 Then\n            Return text\n        Else\n            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n        End If\n    End Function\n\n    Function ReplaceParens(s As String) As String\n        Dim letter = \"s\"c\n        While True\n            Dim start = s.IndexOf(\"(\")\n            If start = -1 Then\n                Exit While\n            End If\n\n            For i = start + 1 To s.Length - 1\n                If s(i) = \")\" Then\n                    Dim expr = s.Substring(start + 1, i - start - 1)\n                    Dim symbol = String.Format(\"@{0}\", letter)\n                    s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)\n                    atomicMass(symbol) = Evaluate(expr)\n                    letter = Chr(Asc(letter) + 1)\n                    Exit For\n                End If\n                If s(i) = \"(\" Then\n                    start = i\n                    Continue For\n                End If\n            Next\n        End While\n        Return s\n    End Function\n\n    Sub Main()\n        Dim molecules() As String = {\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        }\n        For Each molecule In molecules\n            Dim mass = Evaluate(ReplaceParens(molecule))\n            Console.WriteLine(\"{0,17} -> {1,7:0.000}\", molecule, mass)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\npublic class ChemicalCalculator {\n    private static final Map<String, Double> atomicMass = new HashMap<>();\n\n    static {\n        atomicMass.put(\"H\", 1.008);\n        atomicMass.put(\"He\", 4.002602);\n        atomicMass.put(\"Li\", 6.94);\n        atomicMass.put(\"Be\", 9.0121831);\n        atomicMass.put(\"B\", 10.81);\n        atomicMass.put(\"C\", 12.011);\n        atomicMass.put(\"N\", 14.007);\n        atomicMass.put(\"O\", 15.999);\n        atomicMass.put(\"F\", 18.998403163);\n        atomicMass.put(\"Ne\", 20.1797);\n        atomicMass.put(\"Na\", 22.98976928);\n        atomicMass.put(\"Mg\", 24.305);\n        atomicMass.put(\"Al\", 26.9815385);\n        atomicMass.put(\"Si\", 28.085);\n        atomicMass.put(\"P\", 30.973761998);\n        atomicMass.put(\"S\", 32.06);\n        atomicMass.put(\"Cl\", 35.45);\n        atomicMass.put(\"Ar\", 39.948);\n        atomicMass.put(\"K\", 39.0983);\n        atomicMass.put(\"Ca\", 40.078);\n        atomicMass.put(\"Sc\", 44.955908);\n        atomicMass.put(\"Ti\", 47.867);\n        atomicMass.put(\"V\", 50.9415);\n        atomicMass.put(\"Cr\", 51.9961);\n        atomicMass.put(\"Mn\", 54.938044);\n        atomicMass.put(\"Fe\", 55.845);\n        atomicMass.put(\"Co\", 58.933194);\n        atomicMass.put(\"Ni\", 58.6934);\n        atomicMass.put(\"Cu\", 63.546);\n        atomicMass.put(\"Zn\", 65.38);\n        atomicMass.put(\"Ga\", 69.723);\n        atomicMass.put(\"Ge\", 72.630);\n        atomicMass.put(\"As\", 74.921595);\n        atomicMass.put(\"Se\", 78.971);\n        atomicMass.put(\"Br\", 79.904);\n        atomicMass.put(\"Kr\", 83.798);\n        atomicMass.put(\"Rb\", 85.4678);\n        atomicMass.put(\"Sr\", 87.62);\n        atomicMass.put(\"Y\", 88.90584);\n        atomicMass.put(\"Zr\", 91.224);\n        atomicMass.put(\"Nb\", 92.90637);\n        atomicMass.put(\"Mo\", 95.95);\n        atomicMass.put(\"Ru\", 101.07);\n        atomicMass.put(\"Rh\", 102.90550);\n        atomicMass.put(\"Pd\", 106.42);\n        atomicMass.put(\"Ag\", 107.8682);\n        atomicMass.put(\"Cd\", 112.414);\n        atomicMass.put(\"In\", 114.818);\n        atomicMass.put(\"Sn\", 118.710);\n        atomicMass.put(\"Sb\", 121.760);\n        atomicMass.put(\"Te\", 127.60);\n        atomicMass.put(\"I\", 126.90447);\n        atomicMass.put(\"Xe\", 131.293);\n        atomicMass.put(\"Cs\", 132.90545196);\n        atomicMass.put(\"Ba\", 137.327);\n        atomicMass.put(\"La\", 138.90547);\n        atomicMass.put(\"Ce\", 140.116);\n        atomicMass.put(\"Pr\", 140.90766);\n        atomicMass.put(\"Nd\", 144.242);\n        atomicMass.put(\"Pm\", 145.0);\n        atomicMass.put(\"Sm\", 150.36);\n        atomicMass.put(\"Eu\", 151.964);\n        atomicMass.put(\"Gd\", 157.25);\n        atomicMass.put(\"Tb\", 158.92535);\n        atomicMass.put(\"Dy\", 162.500);\n        atomicMass.put(\"Ho\", 164.93033);\n        atomicMass.put(\"Er\", 167.259);\n        atomicMass.put(\"Tm\", 168.93422);\n        atomicMass.put(\"Yb\", 173.054);\n        atomicMass.put(\"Lu\", 174.9668);\n        atomicMass.put(\"Hf\", 178.49);\n        atomicMass.put(\"Ta\", 180.94788);\n        atomicMass.put(\"W\", 183.84);\n        atomicMass.put(\"Re\", 186.207);\n        atomicMass.put(\"Os\", 190.23);\n        atomicMass.put(\"Ir\", 192.217);\n        atomicMass.put(\"Pt\", 195.084);\n        atomicMass.put(\"Au\", 196.966569);\n        atomicMass.put(\"Hg\", 200.592);\n        atomicMass.put(\"Tl\", 204.38);\n        atomicMass.put(\"Pb\", 207.2);\n        atomicMass.put(\"Bi\", 208.98040);\n        atomicMass.put(\"Po\", 209.0);\n        atomicMass.put(\"At\", 210.0);\n        atomicMass.put(\"Rn\", 222.0);\n        atomicMass.put(\"Fr\", 223.0);\n        atomicMass.put(\"Ra\", 226.0);\n        atomicMass.put(\"Ac\", 227.0);\n        atomicMass.put(\"Th\", 232.0377);\n        atomicMass.put(\"Pa\", 231.03588);\n        atomicMass.put(\"U\", 238.02891);\n        atomicMass.put(\"Np\", 237.0);\n        atomicMass.put(\"Pu\", 244.0);\n        atomicMass.put(\"Am\", 243.0);\n        atomicMass.put(\"Cm\", 247.0);\n        atomicMass.put(\"Bk\", 247.0);\n        atomicMass.put(\"Cf\", 251.0);\n        atomicMass.put(\"Es\", 252.0);\n        atomicMass.put(\"Fm\", 257.0);\n        atomicMass.put(\"Uue\", 315.0);\n        atomicMass.put(\"Ubn\", 299.0);\n    }\n\n    private static double evaluate(String s) {\n        String sym = s + \"[\";\n        double sum = 0.0;\n        StringBuilder symbol = new StringBuilder();\n        String number = \"\";\n        for (int i = 0; i < sym.length(); ++i) {\n            char c = sym.charAt(i);\n            if ('@' <= c && c <= '[') {\n                \n                int n = 1;\n                if (!number.isEmpty()) {\n                    n = Integer.parseInt(number);\n                }\n                if (symbol.length() > 0) {\n                    sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;\n                }\n                if (c == '[') {\n                    break;\n                }\n                symbol = new StringBuilder(String.valueOf(c));\n                number = \"\";\n            } else if ('a' <= c && c <= 'z') {\n                symbol.append(c);\n            } else if ('0' <= c && c <= '9') {\n                number += c;\n            } else {\n                throw new RuntimeException(\"Unexpected symbol \" + c + \" in molecule\");\n            }\n        }\n        return sum;\n    }\n\n    private static String replaceParens(String s) {\n        char letter = 'a';\n        String si = s;\n        while (true) {\n            int start = si.indexOf('(');\n            if (start == -1) {\n                break;\n            }\n\n            for (int i = start + 1; i < si.length(); ++i) {\n                if (si.charAt(i) == ')') {\n                    String expr = si.substring(start + 1, i);\n                    String symbol = \"@\" + letter;\n                    String pattern = Pattern.quote(si.substring(start, i + 1));\n                    si = si.replaceFirst(pattern, symbol);\n                    atomicMass.put(symbol, evaluate(expr));\n                    letter++;\n                    break;\n                }\n                if (si.charAt(i) == '(') {\n                    start = i;\n                }\n            }\n        }\n        return si;\n    }\n\n    public static void main(String[] args) {\n        List<String> molecules = List.of(\n            \"H\", \"H2\", \"H2O\", \"H2O2\", \"(HO)2\", \"Na2SO4\", \"C6H12\",\n            \"COOH(C(CH3)2)3CH3\", \"C6H4O2(OH)4\", \"C27H46O\", \"Uue\"\n        );\n        for (String molecule : molecules) {\n            double mass = evaluate(replaceParens(molecule));\n            System.out.printf(\"%17s -> %7.3f\\n\", molecule, mass);\n        }\n    }\n}\n"}
{"id": 60333, "name": "Pythagorean quadruples", "VB": "Const n = 2200\nPublic Sub pq()\n    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3\n    Dim l(n) As Boolean, l_add(9680000) As Boolean \n    For x = 1 To n\n        x2 = x * x\n        For y = x To n\n            l_add(x2 + y * y) = True\n        Next y\n    Next x\n    For x = 1 To n\n        s1 = s\n        s = s + 2\n        s2 = s\n        For y = x + 1 To n\n            If l_add(s1) Then l(y) = True\n            s1 = s1 + s2\n            s2 = s2 + 2\n        Next\n    Next\n    For x = 1 To n\n        If Not l(x) Then Debug.Print x;\n    Next\n    Debug.Print\nEnd Sub\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PythagoreanQuadruples {\n\n    public static void main(String[] args) {\n        long d = 2200;\n        System.out.printf(\"Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n\", d, getPythagoreanQuadruples(d));\n    }\n\n    \n    private static List<Long> getPythagoreanQuadruples(long max) {\n        List<Long> list = new ArrayList<>();\n        long n = -1;\n        long m = -1;\n        while ( true ) {\n            long nTest = (long) Math.pow(2, n+1);\n            long mTest = (long) (5L * Math.pow(2, m+1));\n            long test = 0;\n            if ( nTest > mTest ) {\n                test = mTest;\n                m++;\n            }\n            else {\n                test = nTest;\n                n++;\n            }\n            if ( test < max ) {\n                list.add(test);\n            }\n            else {\n                break;\n            }\n        }\n        return list;\n    }\n\n}\n"}
{"id": 60334, "name": "Update a configuration file", "VB": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\n\nSet objParamLookup = CreateObject(\"Scripting.Dictionary\")\nWith objParamLookup\n\t.Add \"FAVOURITEFRUIT\", \"banana\"\n\t.Add \"NEEDSPEELING\", \"\"\n\t.Add \"SEEDSREMOVED\", \"\"\n\t.Add \"NUMBEROFBANANAS\", \"1024\"\n\t.Add \"NUMBEROFSTRAWBERRIES\", \"62000\"\nEnd With \n\n\nSet objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\IN_config.txt\",1)\n\nOutput = \"\"\t\nIsnumberofstrawberries = False\nWith objInFile\n\tDo Until .AtEndOfStream\n\t\tline = .ReadLine\n\t\tIf Left(line,1) = \"#\" Or line = \"\" Then\n\t\t\tOutput = Output & line & vbCrLf\n\t\tElseIf Left(line,1) = \" \" And InStr(line,\"#\") Then\n\t\t\tOutput = Output & Mid(line,InStr(1,line,\"#\"),1000) & vbCrLf\n\t\tElseIf Replace(Replace(line,\";\",\"\"),\" \",\"\") <> \"\" Then\n\t\t\tIf InStr(1,line,\"FAVOURITEFRUIT\",1) Then\n\t\t\t\tOutput = Output & \"FAVOURITEFRUIT\" & \" \" & objParamLookup.Item(\"FAVOURITEFRUIT\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NEEDSPEELING\",1) Then\n\t\t\t\tOutput = Output & \"; \" & \"NEEDSPEELING\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"SEEDSREMOVED\",1) Then\n\t\t\t\tOutput = Output & \"SEEDSREMOVED\" & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFBANANAS\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFBANANAS\" & \" \" & objParamLookup.Item(\"NUMBEROFBANANAS\") & vbCrLf\n\t\t\tElseIf InStr(1,line,\"NUMBEROFSTRAWBERRIES\",1) Then\n\t\t\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\t\t\tIsnumberofstrawberries = True\n\t\t\tEnd If\n\t\tEnd If\n\tLoop\n\tIf Isnumberofstrawberries = False Then\n\t\tOutput = Output & \"NUMBEROFSTRAWBERRIES\" & \" \" & objParamLookup.Item(\"NUMBEROFSTRAWBERRIES\") & vbCrLf\n\t\tIsnumberofstrawberries = True\n\tEnd If\n\t.Close\nEnd With\n\t\n\nSet objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\OUT_config.txt\",2,True)\nWith objOutFile\n\t.Write Output\n\t.Close\nEnd With\n\nSet objFSO = Nothing\nSet objParamLookup = Nothing\n", "Java": "import java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class UpdateConfig {\n\n    public static void main(String[] args) {\n        if (args[0] == null) {\n            System.out.println(\"filename required\");\n\n        } else if (readConfig(args[0])) {\n            enableOption(\"seedsremoved\");\n            disableOption(\"needspeeling\");\n            setOption(\"numberofbananas\", \"1024\");\n            addOption(\"numberofstrawberries\", \"62000\");\n            store();\n        }\n    }\n\n    private enum EntryType {\n        EMPTY, ENABLED, DISABLED, COMMENT\n    }\n\n    private static class Entry {\n        EntryType type;\n        String name, value;\n\n        Entry(EntryType t, String n, String v) {\n            type = t;\n            name = n;\n            value = v;\n        }\n    }\n\n    private static Map<String, Entry> entries = new LinkedHashMap<>();\n    private static String path;\n\n    private static boolean readConfig(String p) {\n        path = p;\n\n        File f = new File(path);\n        if (!f.exists() || f.isDirectory())\n            return false;\n\n        String regexString = \"^(;*)\\\\s*([A-Za-z0-9]+)\\\\s*([A-Za-z0-9]*)\";\n        Pattern regex = Pattern.compile(regexString);\n\n        try (Scanner sc = new Scanner(new FileReader(f))){\n            int emptyLines = 0;\n            String line;\n            while (sc.hasNext()) {\n                line = sc.nextLine().trim();\n\n                if (line.isEmpty()) {\n                    addOption(\"\" + emptyLines++, null, EntryType.EMPTY);\n\n                } else if (line.charAt(0) == '#') {\n                    entries.put(line, new Entry(EntryType.COMMENT, line, null));\n\n                } else {\n                    line = line.replaceAll(\"[^a-zA-Z0-9\\\\x20;]\", \"\");\n                    Matcher m = regex.matcher(line);\n\n                    if (m.find() && !m.group(2).isEmpty()) {\n\n                        EntryType t = EntryType.ENABLED;\n                        if (!m.group(1).isEmpty())\n                            t = EntryType.DISABLED;\n\n                        addOption(m.group(2), m.group(3), t);\n                    }\n                }\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n        return true;\n    }\n\n    private static void addOption(String name, String value) {\n        addOption(name, value, EntryType.ENABLED);\n    }\n\n    private static void addOption(String name, String value, EntryType t) {\n        name = name.toUpperCase();\n        entries.put(name, new Entry(t, name, value));\n    }\n\n    private static void enableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.ENABLED;\n    }\n\n    private static void disableOption(String name) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.type = EntryType.DISABLED;\n    }\n\n    private static void setOption(String name, String value) {\n        Entry e = entries.get(name.toUpperCase());\n        if (e != null)\n            e.value = value;\n    }\n\n    private static void store() {\n        try (PrintWriter pw = new PrintWriter(path)) {\n            for (Entry e : entries.values()) {\n                switch (e.type) {\n                    case EMPTY:\n                        pw.println();\n                        break;\n                    case ENABLED:\n                        pw.format(\"%s %s%n\", e.name, e.value);\n                        break;\n                    case DISABLED:\n                        pw.format(\"; %s %s%n\", e.name, e.value);\n                        break;\n                    case COMMENT:\n                        pw.println(e.name);\n                        break;\n                    default:\n                        break;\n                }\n            }\n            if (pw.checkError()) {\n                throw new IOException(\"writing to file failed\");\n            }\n        } catch (IOException e) {\n            System.out.println(e);\n        }\n    }\n}\n"}
{"id": 60335, "name": "Practical numbers", "VB": "Imports System.Collections.Generic, System.Linq, System.Console\n\nModule Module1\n    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean\n        If n <= 0 Then Return False Else If f.Contains(n) Then Return True\n        Select Case n.CompareTo(f.Sum())\n            Case 1 : Return False : Case 0 : Return True\n            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) \n                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)\n        End Select : Return true\n    End Function\n\n    Function ip(ByVal n As Integer) As Boolean\n        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()\n        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))\n    End Function\n\n    Sub Main()\n        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m\n            If ip(i) OrElse i = 1 Then c += 1 : Write(\"{0,3} {1}\", i, If(c Mod 10 = 0, vbLf, \"\"))\n            i += If(i = 1, 1, 2) : End While\n        Write(vbLf & \"Found {0} practical numbers between 1 and {1} inclusive.\" & vbLf, c, m)\n        Do : m = If(m < 500, m << 1, m * 10 + 6)\n            Write(vbLf & \"{0,5} is a{1}practical number.\", m, If(ip(m), \" \", \"n im\")) : Loop While m < 1e4\n    End Sub\nEnd Module\n", "Java": "import java.util.*;\n\npublic class PracticalNumbers {\n    public static void main(String[] args) {\n        final int from = 1;\n        final int to = 333;\n        List<Integer> practical = new ArrayList<>();\n        for (int i = from; i <= to; ++i) {\n            if (isPractical(i))\n                practical.add(i);\n        }\n        System.out.printf(\"Found %d practical numbers between %d and %d:\\n%s\\n\",\n                practical.size(), from, to, shorten(practical, 10));\n\n        printPractical(666);\n        printPractical(6666);\n        printPractical(66666);\n        printPractical(672);\n        printPractical(720);\n        printPractical(222222);\n    }\n\n    private static void printPractical(int n) {\n        if (isPractical(n))\n            System.out.printf(\"%d is a practical number.\\n\", n);\n        else\n            System.out.printf(\"%d is not a practical number.\\n\", n);\n    }\n\n    private static boolean isPractical(int n) {\n        int[] divisors = properDivisors(n);\n        for (int i = 1; i < n; ++i) {\n            if (!sumOfAnySubset(i, divisors, divisors.length))\n                return false;\n        }\n        return true;\n    }\n\n    private static boolean sumOfAnySubset(int n, int[] f, int len) {\n        if (len == 0)\n            return false;\n        int total = 0;\n        for (int i = 0; i < len; ++i) {\n            if (n == f[i])\n                return true;\n            total += f[i];\n        }\n        if (n == total)\n            return true;\n        if (n > total)\n            return false;\n        --len;\n        int d = n - f[len];\n        return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);\n    }\n\n    private static int[] properDivisors(int n) {\n        List<Integer> divisors = new ArrayList<>();\n        divisors.add(1);\n        for (int i = 2;; ++i) {\n            int i2 = i * i;\n            if (i2 > n)\n                break;\n            if (n % i == 0) {\n                divisors.add(i);\n                if (i2 != n)\n                    divisors.add(n / i);\n            }\n        }\n        int[] result = new int[divisors.size()];\n        for (int i = 0; i < result.length; ++i)\n            result[i] = divisors.get(i);\n        Arrays.sort(result);\n        return result;\n    }\n\n    private static String shorten(List<Integer> list, int n) {\n        StringBuilder str = new StringBuilder();\n        int len = list.size(), i = 0;\n        if (n > 0 && len > 0)\n            str.append(list.get(i++));\n        for (; i < n && i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        if (len > i + n) {\n            if (n > 0)\n                str.append(\", ...\");\n            i = len - n;\n        }\n        for (; i < len; ++i) {\n            str.append(\", \");\n            str.append(list.get(i));\n        }\n        return str.toString();\n    }\n}\n"}
{"id": 60336, "name": "Literals_Floating point", "VB": "Sub Main()\nDim d As Double \nDim s As Single \n  d = -12.3456\n  d = 1000#\n  d = 0.00001\n  d = 67#\n  d = 8.9\n  d = 0.33\n  d = 0#\n  d = 2# * 10 ^ 3\n  d = 2E+50\n  d = 2E-50\n  s = -12.3456!\n  s = 1000!\n  s = 0.00001!\n  s = 67!\n  s = 8.9!\n  s = 0.33!\n  s = 0!\n  s = 2! * 10 ^ 3\nEnd Sub\n", "Java": "1. \n1.0 \n2432311.7567374 \n1.234E-10 \n1.234e-10 \n758832d \n728832f \n1.0f \n758832D \n728832F \n1.0F \n1 / 2. \n1 / 2 \n"}
{"id": 60337, "name": "Word search", "VB": "Module Module1\n\n    ReadOnly Dirs As Integer(,) = {\n        {1, 0}, {0, 1}, {1, 1},\n        {1, -1}, {-1, 0},\n        {0, -1}, {-1, -1}, {-1, 1}\n    }\n\n    Const RowCount = 10\n    Const ColCount = 10\n    Const GridSize = RowCount * ColCount\n    Const MinWords = 25\n\n    Class Grid\n        Public cells(RowCount - 1, ColCount - 1) As Char\n        Public solutions As New List(Of String)\n        Public numAttempts As Integer\n\n        Sub New()\n            For i = 0 To RowCount - 1\n                For j = 0 To ColCount - 1\n                    cells(i, j) = ControlChars.NullChar\n                Next\n            Next\n        End Sub\n    End Class\n\n    Dim Rand As New Random()\n\n    Sub Main()\n        PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n    End Sub\n\n    Function ReadWords(filename As String) As List(Of String)\n        Dim maxlen = Math.Max(RowCount, ColCount)\n        Dim words As New List(Of String)\n\n        Dim objReader As New IO.StreamReader(filename)\n        Dim line As String\n        Do While objReader.Peek() <> -1\n            line = objReader.ReadLine()\n            If line.Length > 3 And line.Length < maxlen Then\n                If line.All(Function(c) Char.IsLetter(c)) Then\n                    words.Add(line)\n                End If\n            End If\n        Loop\n\n        Return words\n    End Function\n\n    Function CreateWordSearch(words As List(Of String)) As Grid\n        For numAttempts = 1 To 1000\n            Shuffle(words)\n\n            Dim grid As New Grid()\n            Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n            Dim target = GridSize - messageLen\n\n            Dim cellsFilled = 0\n            For Each word In words\n                cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n                If cellsFilled = target Then\n                    If grid.solutions.Count >= MinWords Then\n                        grid.numAttempts = numAttempts\n                        Return grid\n                    Else\n                        \n                        Exit For\n                    End If\n                End If\n            Next\n        Next\n\n        Return Nothing\n    End Function\n\n    Function PlaceMessage(grid As Grid, msg As String) As Integer\n        msg = msg.ToUpper()\n        msg = msg.Replace(\" \", \"\")\n\n        If msg.Length > 0 And msg.Length < GridSize Then\n            Dim gapSize As Integer = GridSize / msg.Length\n\n            Dim pos = 0\n            Dim lastPos = -1\n            For i = 0 To msg.Length - 1\n                If i = 0 Then\n                    pos = pos + Rand.Next(gapSize - 1)\n                Else\n                    pos = pos + Rand.Next(2, gapSize - 1)\n                End If\n                Dim r As Integer = Math.Floor(pos / ColCount)\n                Dim c = pos Mod ColCount\n\n                grid.cells(r, c) = msg(i)\n\n                lastPos = pos\n            Next\n            Return msg.Length\n        End If\n\n        Return 0\n    End Function\n\n    Function TryPlaceWord(grid As Grid, word As String) As Integer\n        Dim randDir = Rand.Next(Dirs.GetLength(0))\n        Dim randPos = Rand.Next(GridSize)\n\n        For d = 0 To Dirs.GetLength(0) - 1\n            Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n            For p = 0 To GridSize - 1\n                Dim pp = (p + randPos) Mod GridSize\n\n                Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n                If lettersPLaced > 0 Then\n                    Return lettersPLaced\n                End If\n            Next\n        Next\n\n        Return 0\n    End Function\n\n    Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n        Dim r As Integer = pos / ColCount\n        Dim c = pos Mod ColCount\n        Dim len = word.Length\n\n        \n        If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n            Return 0\n        End If\n        If r = RowCount OrElse c = ColCount Then\n            Return 0\n        End If\n\n        Dim rr = r\n        Dim cc = c\n\n        \n        For i = 0 To len - 1\n            If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n                Return 0\n            End If\n\n            cc = cc + Dirs(dir, 0)\n            rr = rr + Dirs(dir, 1)\n        Next\n\n        \n        Dim overlaps = 0\n        rr = r\n        cc = c\n        For i = 0 To len - 1\n            If grid.cells(rr, cc) = word(i) Then\n                overlaps = overlaps + 1\n            Else\n                grid.cells(rr, cc) = word(i)\n            End If\n\n            If i < len - 1 Then\n                cc = cc + Dirs(dir, 0)\n                rr = rr + Dirs(dir, 1)\n            End If\n        Next\n\n        Dim lettersPlaced = len - overlaps\n        If lettersPlaced > 0 Then\n            grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n        End If\n\n        Return lettersPlaced\n    End Function\n\n    Sub PrintResult(grid As Grid)\n        If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n            Console.WriteLine(\"No grid to display\")\n            Return\n        End If\n\n        Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n        Console.WriteLine(\"Number of words: {0}\", GridSize)\n        Console.WriteLine()\n\n        Console.WriteLine(\"     0  1  2  3  4  5  6  7  8  9\")\n        For r = 0 To RowCount - 1\n            Console.WriteLine()\n            Console.Write(\"{0}   \", r)\n            For c = 0 To ColCount - 1\n                Console.Write(\" {0} \", grid.cells(r, c))\n            Next\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine()\n\n        For i = 0 To grid.solutions.Count - 1\n            If i Mod 2 = 0 Then\n                Console.Write(\"{0}\", grid.solutions(i))\n            Else\n                Console.WriteLine(\"   {0}\", grid.solutions(i))\n            End If\n        Next\n\n        Console.WriteLine()\n    End Sub\n\n    \n    Sub Shuffle(Of T)(list As IList(Of T))\n        Dim r As Random = New Random()\n        For i = 0 To list.Count - 1\n            Dim index As Integer = r.Next(i, list.Count)\n            If i <> index Then\n                \n                Dim temp As T = list(i)\n                list(i) = list(index)\n                list(index) = temp\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n    static class Grid {\n        int numAttempts;\n        char[][] cells = new char[nRows][nCols];\n        List<String> solutions = new ArrayList<>();\n    }\n\n    final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n    {0, -1}, {-1, -1}, {-1, 1}};\n\n    final static int nRows = 10;\n    final static int nCols = 10;\n    final static int gridSize = nRows * nCols;\n    final static int minWords = 25;\n\n    final static Random rand = new Random();\n\n    public static void main(String[] args) {\n        printResult(createWordSearch(readWords(\"unixdict.txt\")));\n    }\n\n    static List<String> readWords(String filename) {\n        int maxLen = Math.max(nRows, nCols);\n\n        List<String> words = new ArrayList<>();\n        try (Scanner sc = new Scanner(new FileReader(filename))) {\n            while (sc.hasNext()) {\n                String s = sc.next().trim().toLowerCase();\n                if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n                    words.add(s);\n            }\n        } catch (FileNotFoundException e) {\n            System.out.println(e);\n        }\n        return words;\n    }\n\n    static Grid createWordSearch(List<String> words) {\n        Grid grid = null;\n        int numAttempts = 0;\n\n        outer:\n        while (++numAttempts < 100) {\n            Collections.shuffle(words);\n\n            grid = new Grid();\n            int messageLen = placeMessage(grid, \"Rosetta Code\");\n            int target = gridSize - messageLen;\n\n            int cellsFilled = 0;\n            for (String word : words) {\n                cellsFilled += tryPlaceWord(grid, word);\n                if (cellsFilled == target) {\n                    if (grid.solutions.size() >= minWords) {\n                        grid.numAttempts = numAttempts;\n                        break outer;\n                    } else break; \n                }\n            }\n        }\n\n        return grid;\n    }\n\n    static int placeMessage(Grid grid, String msg) {\n        msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n        int messageLen = msg.length();\n        if (messageLen > 0 && messageLen < gridSize) {\n            int gapSize = gridSize / messageLen;\n\n            for (int i = 0; i < messageLen; i++) {\n                int pos = i * gapSize + rand.nextInt(gapSize);\n                grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n            }\n            return messageLen;\n        }\n        return 0;\n    }\n\n    static int tryPlaceWord(Grid grid, String word) {\n        int randDir = rand.nextInt(dirs.length);\n        int randPos = rand.nextInt(gridSize);\n\n        for (int dir = 0; dir < dirs.length; dir++) {\n            dir = (dir + randDir) % dirs.length;\n\n            for (int pos = 0; pos < gridSize; pos++) {\n                pos = (pos + randPos) % gridSize;\n\n                int lettersPlaced = tryLocation(grid, word, dir, pos);\n                if (lettersPlaced > 0)\n                    return lettersPlaced;\n            }\n        }\n        return 0;\n    }\n\n    static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n        int r = pos / nCols;\n        int c = pos % nCols;\n        int len = word.length();\n\n        \n        if ((dirs[dir][0] == 1 && (len + c) > nCols)\n                || (dirs[dir][0] == -1 && (len - 1) > c)\n                || (dirs[dir][1] == 1 && (len + r) > nRows)\n                || (dirs[dir][1] == -1 && (len - 1) > r))\n            return 0;\n\n        int rr, cc, i, overlaps = 0;\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n                return 0;\n            cc += dirs[dir][0];\n            rr += dirs[dir][1];\n        }\n\n        \n        for (i = 0, rr = r, cc = c; i < len; i++) {\n            if (grid.cells[rr][cc] == word.charAt(i))\n                overlaps++;\n            else\n                grid.cells[rr][cc] = word.charAt(i);\n\n            if (i < len - 1) {\n                cc += dirs[dir][0];\n                rr += dirs[dir][1];\n            }\n        }\n\n        int lettersPlaced = len - overlaps;\n        if (lettersPlaced > 0) {\n            grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n        }\n\n        return lettersPlaced;\n    }\n\n    static void printResult(Grid grid) {\n        if (grid == null || grid.numAttempts == 0) {\n            System.out.println(\"No grid to display\");\n            return;\n        }\n        int size = grid.solutions.size();\n\n        System.out.println(\"Attempts: \" + grid.numAttempts);\n        System.out.println(\"Number of words: \" + size);\n\n        System.out.println(\"\\n     0  1  2  3  4  5  6  7  8  9\");\n        for (int r = 0; r < nRows; r++) {\n            System.out.printf(\"%n%d   \", r);\n            for (int c = 0; c < nCols; c++)\n                System.out.printf(\" %c \", grid.cells[r][c]);\n        }\n\n        System.out.println(\"\\n\");\n\n        for (int i = 0; i < size - 1; i += 2) {\n            System.out.printf(\"%s   %s%n\", grid.solutions.get(i),\n                    grid.solutions.get(i + 1));\n        }\n        if (size % 2 == 1)\n            System.out.println(grid.solutions.get(size - 1));\n    }\n}\n"}
{"id": 60338, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 60339, "name": "Break OO privacy", "VB": "Imports System.Reflection\n\n\nPublic Class MyClazz\n    Private answer As Integer = 42\nEnd Class\n\nPublic Class Program\n    Public Shared Sub Main()\n        Dim myInstance = New MyClazz()\n        Dim fieldInfo = GetType(MyClazz).GetField(\"answer\", BindingFlags.NonPublic Or BindingFlags.Instance)\n        Dim answer = fieldInfo.GetValue(myInstance)\n        Console.WriteLine(answer)\n    End Sub\nEnd Class\n", "Java": "module BreakOO\n    {\n    \n    class Exposed\n        {\n        public    String pub = \"public\";\n        protected String pro = \"protected\";\n        private   String pri = \"private\";\n\n        @Override\n        String toString()\n            {\n            return $\"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}\";\n            }\n        }\n\n    void run()\n        {\n        @Inject Console console;\n\n        Exposed expo = new Exposed();\n        console.print($\"before: {expo}\");\n\n        \n        expo.pub = $\"this was {expo.pub}\";\n     \n     \n\n        \n        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));\n        expoPro.pro = $\"this was {expoPro.pro}\";\n     \n\n        \n        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));\n        expoPri.pri = $\"this was {expoPri.pri}\";\n\n        \n        \n        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));\n        expoStr.pub = $\"{expoStr.pub}!!!\";\n        expoStr.pro = $\"{expoStr.pro}!!!\";\n        expoStr.pri = $\"{expoStr.pri}!!!\";\n\n        console.print($\"after: {expo}\");\n        }\n    }\n"}
{"id": 60340, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 60341, "name": "Eertree", "VB": "Module Module1\n\n    Class Node\n        Public Sub New(Len As Integer)\n            Length = Len\n            Edges = New Dictionary(Of Char, Integer)\n        End Sub\n\n        Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)\n            Length = len\n            Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)\n            Suffix = suf\n        End Sub\n\n        Property Edges As Dictionary(Of Char, Integer)\n        Property Length As Integer\n        Property Suffix As Integer\n    End Class\n\n    ReadOnly EVEN_ROOT As Integer = 0\n    ReadOnly ODD_ROOT As Integer = 1\n\n    Function Eertree(s As String) As List(Of Node)\n        Dim tree As New List(Of Node) From {\n            New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),\n            New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)\n        }\n        Dim suffix = ODD_ROOT\n        Dim n As Integer\n        Dim k As Integer\n\n        For i = 1 To s.Length\n            Dim c = s(i - 1)\n            n = suffix\n            While True\n                k = tree(n).Length\n                Dim b = i - k - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n                n = tree(n).Suffix\n            End While\n            If tree(n).Edges.ContainsKey(c) Then\n                suffix = tree(n).Edges(c)\n                Continue For\n            End If\n            suffix = tree.Count\n            tree.Add(New Node(k + 2))\n            tree(n).Edges(c) = suffix\n            If tree(suffix).Length = 1 Then\n                tree(suffix).Suffix = 0\n                Continue For\n            End If\n            While True\n                n = tree(n).Suffix\n                Dim b = i - tree(n).Length - 2\n                If b >= 0 AndAlso s(b) = c Then\n                    Exit While\n                End If\n            End While\n            Dim a = tree(n)\n            Dim d = a.Edges(c)\n            Dim e = tree(suffix)\n            e.Suffix = d\n        Next\n\n        Return tree\n    End Function\n\n    Function SubPalindromes(tree As List(Of Node)) As List(Of String)\n        Dim s As New List(Of String)\n        Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)\n                                                         For Each c In tree(n).Edges.Keys\n                                                             Dim m = tree(n).Edges(c)\n                                                             Dim p1 = c + p + c\n                                                             s.Add(p1)\n                                                             children(m, p1)\n                                                         Next\n                                                     End Sub\n        children(0, \"\")\n        For Each c In tree(1).Edges.Keys\n            Dim m = tree(1).Edges(c)\n            Dim ct = c.ToString()\n            s.Add(ct)\n            children(m, ct)\n        Next\n        Return s\n    End Function\n\n    Sub Main()\n        Dim tree = Eertree(\"eertree\")\n        Dim result = SubPalindromes(tree)\n        Dim listStr = String.Join(\", \", result)\n        Console.WriteLine(\"[{0}]\", listStr)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n    public static void main(String[] args) {\n        List<Node> tree = eertree(\"eertree\");\n        List<String> result = subPalindromes(tree);\n        System.out.println(result);\n    }\n\n    private static class Node {\n        int length;\n        Map<Character, Integer> edges = new HashMap<>();\n        int suffix;\n\n        public Node(int length) {\n            this.length = length;\n        }\n\n        public Node(int length, Map<Character, Integer> edges, int suffix) {\n            this.length = length;\n            this.edges = edges != null ? edges : new HashMap<>();\n            this.suffix = suffix;\n        }\n    }\n\n    private static final int EVEN_ROOT = 0;\n    private static final int ODD_ROOT = 1;\n\n    private static List<Node> eertree(String s) {\n        List<Node> tree = new ArrayList<>();\n        tree.add(new Node(0, null, ODD_ROOT));\n        tree.add(new Node(-1, null, ODD_ROOT));\n        int suffix = ODD_ROOT;\n        int n, k;\n        for (int i = 0; i < s.length(); ++i) {\n            char c = s.charAt(i);\n            for (n = suffix; ; n = tree.get(n).suffix) {\n                k = tree.get(n).length;\n                int b = i - k - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            if (tree.get(n).edges.containsKey(c)) {\n                suffix = tree.get(n).edges.get(c);\n                continue;\n            }\n            suffix = tree.size();\n            tree.add(new Node(k + 2));\n            tree.get(n).edges.put(c, suffix);\n            if (tree.get(suffix).length == 1) {\n                tree.get(suffix).suffix = 0;\n                continue;\n            }\n            while (true) {\n                n = tree.get(n).suffix;\n                int b = i - tree.get(n).length - 1;\n                if (b >= 0 && s.charAt(b) == c) {\n                    break;\n                }\n            }\n            tree.get(suffix).suffix = tree.get(n).edges.get(c);\n        }\n        return tree;\n    }\n\n    private static List<String> subPalindromes(List<Node> tree) {\n        List<String> s = new ArrayList<>();\n        subPalindromes_children(0, \"\", tree, s);\n        for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {\n            String ct = String.valueOf(cm.getKey());\n            s.add(ct);\n            subPalindromes_children(cm.getValue(), ct, tree, s);\n        }\n        return s;\n    }\n\n    \n    private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {\n        for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {\n            Character c = cm.getKey();\n            Integer m = cm.getValue();\n            String pl = c + p + c;\n            s.add(pl);\n            subPalindromes_children(m, pl, tree, s);\n        }\n    }\n}\n"}
{"id": 60342, "name": "Long year", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 60343, "name": "Long year", "VB": "DEFINT A-Z\n\nDECLARE FUNCTION p% (Yr AS INTEGER)\nDECLARE FUNCTION LongYear% (Yr AS INTEGER)\n\nDIM iYi, iYf, i\n\nCLS\nPRINT \"This program calculates which are 53-week years in a range.\"\nPRINT\nINPUT \"Initial year\"; iYi\nINPUT \"Final year (could be the same)\"; iYf\nIF iYf >= iYi THEN\n  FOR i = iYi TO iYf\n    IF LongYear(i) THEN\n      PRINT i; \" \";\n    END IF\n  NEXT i\nEND IF\nPRINT\nPRINT\nPRINT \"End of program.\"\nEND\n\nFUNCTION LongYear% (Yr AS INTEGER)\n  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)\nEND FUNCTION\n\nFUNCTION p% (Yr AS INTEGER)\n  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7\nEND FUNCTION\n", "Java": "import java.time.LocalDate;\nimport java.time.temporal.WeekFields;\n\npublic class LongYear {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Long years this century:%n\");\n        for (int year = 2000 ; year < 2100 ; year++ ) {\n            if ( longYear(year) ) {\n                System.out.print(year + \"  \");\n            }\n        }\n    }\n    \n    private static boolean longYear(int year) {\n        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;\n    }\n\n}\n"}
{"id": 60344, "name": "Zumkeller numbers", "VB": "Module Module1\n    Function GetDivisors(n As Integer) As List(Of Integer)\n        Dim divs As New List(Of Integer) From {\n            1, n\n        }\n        Dim i = 2\n        While i * i <= n\n            If n Mod i = 0 Then\n                Dim j = n \\ i\n                divs.Add(i)\n                If i <> j Then\n                    divs.Add(j)\n                End If\n            End If\n            i += 1\n        End While\n        Return divs\n    End Function\n\n    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n        If sum = 0 Then\n            Return True\n        End If\n        Dim le = divs.Count\n        If le = 0 Then\n            Return False\n        End If\n        Dim last = divs(le - 1)\n        Dim newDivs As New List(Of Integer)\n        For i = 1 To le - 1\n            newDivs.Add(divs(i - 1))\n        Next\n        If last > sum Then\n            Return IsPartSum(newDivs, sum)\n        End If\n        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n    End Function\n\n    Function IsZumkeller(n As Integer) As Boolean\n        Dim divs = GetDivisors(n)\n        Dim sum = divs.Sum()\n        REM if sum is odd can\n        If sum Mod 2 = 1 Then\n            Return False\n        End If\n        REM if n is odd use \n        If n Mod 2 = 1 Then\n            Dim abundance = sum - 2 * n\n            Return abundance > 0 AndAlso abundance Mod 2 = 0\n        End If\n        REM if n and sum are both even check if there\n        Return IsPartSum(divs, sum \\ 2)\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n        Dim i = 2\n        Dim count = 0\n        While count < 220\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,3} \", i)\n                count += 1\n                If count Mod 20 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 1\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n        i = 3\n        count = 0\n        While count < 40\n            If IsZumkeller(i) Then\n                Console.Write(\"{0,5} \", i)\n                count += 1\n                If count Mod 10 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n        Console.WriteLine()\n\n        Console.WriteLine(\"The first 40 odd Zumkeller numbers which don\n        i = 3\n        count = 0\n        While count < 40\n            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n                Console.Write(\"{0,7} \", i)\n                count += 1\n                If count Mod 8 = 0 Then\n                    Console.WriteLine()\n                End If\n            End If\n            i += 2\n        End While\n    End Sub\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n    public static void main(String[] args) {\n        int n = 1;\n        System.out.printf(\"First 220 Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 220 ; n += 1 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%3d  \", n);\n                if ( count % 20 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( isZumkeller(n) ) {\n                System.out.printf(\"%6d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n        \n        n = 1;\n        System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n        for ( int count = 1 ; count <= 40 ; n += 2 ) {\n            if ( n % 5 != 0 && isZumkeller(n) ) {\n                System.out.printf(\"%8d\", n);\n                if ( count % 10 == 0 ) {\n                    System.out.printf(\"%n\");\n                }\n                count++;\n            }\n        }\n\n    }\n    \n    private static boolean isZumkeller(int n) {\n        \n        if ( n % 18 == 6 || n % 18 == 12 ) {\n            return true;\n        }\n        \n        List<Integer> divisors = getDivisors(n);        \n        int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n        \n        \n        if ( divisorSum % 2 == 1 ) {\n            return false;\n        }\n        \n        \n        int abundance = divisorSum - 2 * n;\n        if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n            return true;\n        }\n        \n        Collections.sort(divisors);\n        int j = divisors.size() - 1;\n        int sum = divisorSum/2;\n        \n        \n        if ( divisors.get(j) > sum ) {\n            return false;\n        }\n        \n        return canPartition(j, divisors, sum, new int[2]);\n    }\n    \n    private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n        if ( j < 0 ) {\n            return true;\n        }\n        for ( int i = 0 ; i < 2 ; i++ ) {\n            if ( buckets[i] + divisors.get(j) <= sum ) {\n                buckets[i] += divisors.get(j);\n                if ( canPartition(j-1, divisors, sum, buckets) ) {\n                    return true;\n                }\n                buckets[i] -= divisors.get(j);\n            }\n            if( buckets[i] == 0 ) {\n                break;\n            }\n        }\n        return false;\n    }\n    \n    private static final List<Integer> getDivisors(int number) {\n        List<Integer> divisors = new ArrayList<Integer>();\n        long sqrt = (long) Math.sqrt(number);\n        for ( int i = 1 ; i <= sqrt ; i++ ) {\n            if ( number % i == 0 ) {\n                divisors.add(i);\n                int div = number / i;\n                if ( div != i ) {\n                    divisors.add(div);\n                }\n            }\n        }\n        return divisors;\n    }\n\n}\n"}
{"id": 60345, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 60346, "name": "Associative array_Merging", "VB": "Private Type Associative\n    Key As String\n    Value As Variant\nEnd Type\nSub Main_Array_Associative()\nDim BaseArray(2) As Associative, UpdateArray(2) As Associative\n    FillArrays BaseArray, UpdateArray\n    ReDim Result(UBound(BaseArray)) As Associative\n    MergeArray Result, BaseArray, UpdateArray\n    PrintOut Result\nEnd Sub\nPrivate Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)\nDim i As Long, Respons As Long\n    Res = Base\n    For i = LBound(Update) To UBound(Update)\n        If Exist(Respons, Base, Update(i).Key) Then\n            Res(Respons).Value = Update(i).Value\n        Else\n            ReDim Preserve Res(UBound(Res) + 1)\n            Res(UBound(Res)).Key = Update(i).Key\n            Res(UBound(Res)).Value = Update(i).Value\n        End If\n    Next\nEnd Sub\nPrivate Function Exist(R As Long, B() As Associative, K As String) As Boolean\nDim i As Long\n    Do\n        If B(i).Key = K Then\n            Exist = True\n            R = i\n        End If\n        i = i + 1\n    Loop While i <= UBound(B) And Not Exist\nEnd Function\nPrivate Sub FillArrays(B() As Associative, U() As Associative)\n    B(0).Key = \"name\"\n    B(0).Value = \"Rocket Skates\"\n    B(1).Key = \"price\"\n    B(1).Value = 12.75\n    B(2).Key = \"color\"\n    B(2).Value = \"yellow\"\n    U(0).Key = \"price\"\n    U(0).Value = 15.25\n    U(1).Key = \"color\"\n    U(1).Value = \"red\"\n    U(2).Key = \"year\"\n    U(2).Value = 1974\nEnd Sub\nPrivate Sub PrintOut(A() As Associative)\nDim i As Long\n    Debug.Print \"Key\", \"Value\"\n    For i = LBound(A) To UBound(A)\n        Debug.Print A(i).Key, A(i).Value\n    Next i\n    Debug.Print \"-----------------------------\"\nEnd Sub\n", "Java": "import java.util.*;\n\nclass MergeMaps {\n    public static void main(String[] args) {\n        Map<String, Object> base = new HashMap<>();\n        base.put(\"name\", \"Rocket Skates\");\n        base.put(\"price\", 12.75);\n        base.put(\"color\", \"yellow\");\n        Map<String, Object> update = new HashMap<>();\n        update.put(\"price\", 15.25);\n        update.put(\"color\", \"red\");\n        update.put(\"year\", 1974);\n\n        Map<String, Object> result = new HashMap<>(base);\n        result.putAll(update);\n\n        System.out.println(result);\n    }\n}\n"}
{"id": 60347, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 60348, "name": "Metallic ratios", "VB": "Imports BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Function IntSqRoot(v As BI, res As BI) As BI\n        REM res is the initial guess\n        Dim term As BI = 0\n        Dim d As BI = 0\n        Dim dl As BI = 1\n        While dl <> d\n            term = v / res\n            res = (res + term) >> 1\n            dl = d\n            d = term - res\n        End While\n        Return term\n    End Function\n\n    Function DoOne(b As Integer, digs As Integer) As String\n        REM calculates result via square root, not iterations\n        Dim s = b * b + 4\n        digs += 1\n        Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))\n        Dim bs = IntSqRoot(s * BI.Parse(\"1\" + New String(\"0\", digs << 1)), g)\n        bs += b * BI.Parse(\"1\" + New String(\"0\", digs))\n        bs >>= 1\n        bs += 4\n        Dim st = bs.ToString\n        digs -= 1\n        Return String.Format(\"{0}.{1}\", st(0), st.Substring(1, digs))\n    End Function\n\n    Function DivIt(a As BI, b As BI, digs As Integer) As String\n        REM performs division\n        Dim al = a.ToString.Length\n        Dim bl = b.ToString.Length\n        digs += 1\n        a *= BI.Pow(10, digs << 1)\n        b *= BI.Pow(10, digs)\n        Dim s = (a / b + 5).ToString\n        digs -= 1\n        Return s(0) + \".\" + s.Substring(1, digs)\n    End Function\n\n    REM custom formatting\n    Function Joined(x() As BI) As String\n        Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}\n        Dim res = \"\"\n        For i = 0 To x.Length - 1\n            res += String.Format(\"{0,\" + (-wids(i)).ToString + \"} \", x(i))\n        Next\n        Return res\n    End Function\n\n    Sub Main()\n        REM calculates and checks each \"metal\"\n        Console.WriteLine(\"Metal B Sq.Rt Iters /---- 32 decimal place value ----\\\\  Matches Sq.Rt Calc\")\n        Dim t = \"\"\n        Dim n As BI\n        Dim nm1 As BI\n        Dim k As Integer\n        Dim j As Integer\n        For b = 0 To 9\n            Dim lst(14) As BI\n            lst(0) = 1\n            lst(1) = 1\n            For i = 2 To 14\n                lst(i) = b * lst(i - 1) + lst(i - 2)\n            Next\n            REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15\n            n = lst(14)\n            nm1 = lst(13)\n            k = 0\n            j = 13\n            While k = 0\n                Dim lt = t\n                t = DivIt(n, nm1, 32)\n                If lt = t Then\n                    k = If(b = 0, 1, j)\n                End If\n                Dim onn = n\n                n = b * n + nm1\n                nm1 = onn\n\n                j += 1\n            End While\n            Console.WriteLine(\"{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\" + vbNewLine + \"{6,19} {7}\", \"Pt Au Ag CuSn Cu Ni Al Fe Sn Pb\".Split(\" \")(b), b, b * b + 4, k, t, t = DoOne(b, 32), \"\", Joined(lst))\n        Next\n        REM now calculate and check big one\n        n = 1\n        nm1 = 1\n        k = 0\n        j = 1\n        While k = 0\n            Dim lt = t\n            t = DivIt(n, nm1, 256)\n            If lt = t Then\n                k = j\n            End If\n            Dim onn = n\n            n += nm1\n            nm1 = onn\n\n            j += 1\n        End While\n        Console.WriteLine()\n        Console.WriteLine(\"Au to 256 digits:\")\n        Console.WriteLine(t)\n        Console.WriteLine(\"Iteration count: {0}  Matched Sq.Rt Calc: {1}\", k, t = DoOne(1, 256))\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.math.MathContext;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MetallicRatios {\n\n    private static String[] ratioDescription = new String[] {\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminum\", \"Iron\", \"Tin\", \"Lead\"};\n    \n    public static void main(String[] args) {\n        int elements = 15;\n        for ( int b = 0 ; b < 10 ; b++ ) {\n            System.out.printf(\"Lucas sequence for %s ratio, where b = %d:%n\", ratioDescription[b], b);\n            System.out.printf(\"First %d elements: %s%n\", elements, lucasSequence(1, 1, b, elements));\n            int decimalPlaces = 32;\n            BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n            System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n            System.out.printf(\"%n\");\n        }\n        int b = 1;\n        int decimalPlaces = 256;\n        System.out.printf(\"%s ratio, where b = %d:%n\", ratioDescription[b], b);\n        BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);\n        System.out.printf(\"Value to %d decimal places after %s iterations : %s%n\", decimalPlaces, ratio[1], ratio[0]);\n    }\n    \n    private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {\n        BigDecimal x0Bi = BigDecimal.valueOf(x0);\n        BigDecimal x1Bi = BigDecimal.valueOf(x1);\n        BigDecimal bBi = BigDecimal.valueOf(b);\n        MathContext mc = new MathContext(digits);\n        BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);\n        int iterations = 0;\n        while ( true ) {\n            iterations++;\n            BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);\n            BigDecimal fractionCurrent = x.divide(x1Bi, mc);\n            if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {\n                break;\n            }\n            x0Bi = x1Bi;\n            x1Bi = x;\n            fractionPrior = fractionCurrent;\n        }\n        return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};\n    }\n\n    private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {\n        List<BigInteger> list = new ArrayList<>();\n        BigInteger x0Bi = BigInteger.valueOf(x0);\n        BigInteger x1Bi = BigInteger.valueOf(x1);\n        BigInteger bBi = BigInteger.valueOf(b);\n        if ( n > 0 ) {\n            list.add(x0Bi);\n        }\n        if ( n > 1 ) {\n            list.add(x1Bi);\n        }\n        while ( n > 2 ) {\n            BigInteger x = bBi.multiply(x1Bi).add(x0Bi);\n            list.add(x);\n            n--;\n            x0Bi = x1Bi;\n            x1Bi = x;\n        }\n        return list;\n    }\n    \n}\n"}
{"id": 60349, "name": "Dijkstra's algorithm", "VB": "Class Branch\nPublic from As Node \nPublic towards As Node\nPublic length As Integer \nPublic distance As Integer \nPublic key As String\nClass Node\nPublic key As String\nPublic correspondingBranch As Branch\nConst INFINITY = 32767\nPrivate Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Dim a As New Collection \n    \n    \n    \n    Dim b As New Collection \n    \n    Dim c As New Collection \n    \n    \n    \n    Dim I As New Collection \n    \n    \n    Dim II As New Collection \n    \n    Dim III As New Collection \n    Dim u As Node, R_ As Node, dist As Integer\n    \n    \n    \n    For Each n In Nodes\n        c.Add n, n.key\n    Next n\n    For Each e In Branches\n        III.Add e, e.key\n    Next e\n    a.Add P, P.key\n    c.Remove P.key\n    Set u = P\n    Do\n        \n        \n        \n        \n        \n        \n        \n        \n        For Each r In III\n            If r.from Is u Then\n                Set R_ = r.towards\n                If Belongs(R_, c) Then\n                    c.Remove R_.key\n                    b.Add R_, R_.key\n                    Set R_.correspondingBranch = r\n                    If u.correspondingBranch Is Nothing Then\n                        R_.correspondingBranch.distance = r.length\n                    Else\n                        R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length\n                    End If\n                    III.Remove r.key \n                    II.Add r, r.key\n                Else\n                    If Belongs(R_, b) Then \n                        If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then\n                            II.Remove R_.correspondingBranch.key\n                            II.Add r, r.key\n                            Set R_.correspondingBranch = r \n                            R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length \n                        End If\n                    End If\n                End If\n            End If\n        Next r\n        \n        \n        \n        \n        \n        \n        dist = INFINITY\n        Set u = Nothing\n        For Each n In b\n            If dist > n.correspondingBranch.distance Then\n                dist = n.correspondingBranch.distance\n                Set u = n\n            End If\n        Next n\n        b.Remove u.key\n        a.Add u, u.key\n        II.Remove u.correspondingBranch.key\n        I.Add u.correspondingBranch, u.correspondingBranch.key\n    Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)\n    If Not Q Is Nothing Then GetPath Q\nEnd Sub\nPrivate Function Belongs(n As Node, col As Collection) As Boolean\n    Dim obj As Node\n    On Error GoTo err\n        Belongs = True\n        Set obj = col(n.key)\n        Exit Function\nerr:\n        Belongs = False\nEnd Function\nPrivate Sub GetPath(Target As Node)\n    Dim path As String\n    If Target.correspondingBranch Is Nothing Then\n        path = \"no path\"\n    Else\n        path = Target.key\n        Set u = Target\n        Do While Not u.correspondingBranch Is Nothing\n            path = u.correspondingBranch.from.key & \" \" & path\n            Set u = u.correspondingBranch.from\n        Loop\n        Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path\n    End If\nEnd Sub\nPublic Sub test()\n    Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node\n    Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch\n    Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch\n    Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = \"ab\": ab.distance = INFINITY\n    Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = \"ac\": ac.distance = INFINITY\n    Set af.from = a: Set af.towards = f: af.length = 14: af.key = \"af\": af.distance = INFINITY\n    Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = \"bc\": bc.distance = INFINITY\n    Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = \"bd\": bd.distance = INFINITY\n    Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = \"cd\": cd.distance = INFINITY\n    Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = \"cf\": cf.distance = INFINITY\n    Set de.from = d: Set de.towards = e: de.length = 6: de.key = \"de\": de.distance = INFINITY\n    Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = \"ef\": ef.distance = INFINITY\n    a.key = \"a\"\n    b.key = \"b\"\n    c.key = \"c\"\n    d.key = \"d\"\n    e.key = \"e\"\n    f.key = \"f\"\n    Dim testNodes As New Collection\n    Dim testBranches As New Collection\n    testNodes.Add a, \"a\"\n    testNodes.Add b, \"b\"\n    testNodes.Add c, \"c\"\n    testNodes.Add d, \"d\"\n    testNodes.Add e, \"e\"\n    testNodes.Add f, \"f\"\n    testBranches.Add ab, \"ab\"\n    testBranches.Add ac, \"ac\"\n    testBranches.Add af, \"af\"\n    testBranches.Add bc, \"bc\"\n    testBranches.Add bd, \"bd\"\n    testBranches.Add cd, \"cd\"\n    testBranches.Add cf, \"cf\"\n    testBranches.Add de, \"de\"\n    testBranches.Add ef, \"ef\"\n    Debug.Print \"From\", \"To\", \"Distance\", \"Path\"\n    \n    Dijkstra testNodes, testBranches, a, e\n    \n    Dijkstra testNodes, testBranches, a\n    GetPath f\nEnd Sub\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n   private static final Graph.Edge[] GRAPH = {\n      new Graph.Edge(\"a\", \"b\", 7),\n      new Graph.Edge(\"a\", \"c\", 9),\n      new Graph.Edge(\"a\", \"f\", 14),\n      new Graph.Edge(\"b\", \"c\", 10),\n      new Graph.Edge(\"b\", \"d\", 15),\n      new Graph.Edge(\"c\", \"d\", 11),\n      new Graph.Edge(\"c\", \"f\", 2),\n      new Graph.Edge(\"d\", \"e\", 6),\n      new Graph.Edge(\"e\", \"f\", 9),\n   };\n   private static final String START = \"a\";\n   private static final String END = \"e\";\n   \n   public static void main(String[] args) {\n      Graph g = new Graph(GRAPH);\n      g.dijkstra(START);\n      g.printPath(END);\n      \n   }\n}\n\nclass Graph {\n   private final Map<String, Vertex> graph; \n   \n   \n   public static class Edge {\n      public final String v1, v2;\n      public final int dist;\n      public Edge(String v1, String v2, int dist) {\n         this.v1 = v1;\n         this.v2 = v2;\n         this.dist = dist;\n      }\n   }\n   \n   \n  public static class Vertex implements Comparable<Vertex>{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \n\tpublic Vertex previous = null;\n\tpublic final Map<Vertex, Integer> neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n   \n   \n   public Graph(Edge[] edges) {\n      graph = new HashMap<>(edges.length);\n      \n      \n      for (Edge e : edges) {\n         if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n         if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n      }\n      \n      \n      for (Edge e : edges) {\n         graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n         \n      }\n   }\n   \n    \n   public void dijkstra(String startName) {\n      if (!graph.containsKey(startName)) {\n         System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n         return;\n      }\n      final Vertex source = graph.get(startName);\n      NavigableSet<Vertex> q = new TreeSet<>();\n      \n      \n      for (Vertex v : graph.values()) {\n         v.previous = v == source ? source : null;\n         v.dist = v == source ? 0 : Integer.MAX_VALUE;\n         q.add(v);\n      }\n      \n      dijkstra(q);\n   }\n   \n   \n   private void dijkstra(final NavigableSet<Vertex> q) {      \n      Vertex u, v;\n      while (!q.isEmpty()) {\n         \n         u = q.pollFirst(); \n         if (u.dist == Integer.MAX_VALUE) break; \n         \n         \n         for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {\n            v = a.getKey(); \n            \n            final int alternateDist = u.dist + a.getValue();\n            if (alternateDist < v.dist) { \n               q.remove(v);\n               v.dist = alternateDist;\n               v.previous = u;\n               q.add(v);\n            } \n         }\n      }\n   }\n   \n   \n   public void printPath(String endName) {\n      if (!graph.containsKey(endName)) {\n         System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n         return;\n      }\n      \n      graph.get(endName).printPath();\n      System.out.println();\n   }\n   \n   public void printAllPaths() {\n      for (Vertex v : graph.values()) {\n         v.printPath();\n         System.out.println();\n      }\n   }\n}\n"}
{"id": 60350, "name": "Geometric algebra", "VB": "Option Strict On\n\nImports System.Text\n\nModule Module1\n\n    Structure Vector\n        Private ReadOnly dims() As Double\n\n        Public Sub New(da() As Double)\n            dims = da\n        End Sub\n\n        Public Shared Operator -(v As Vector) As Vector\n            Return v * -1.0\n        End Operator\n\n        Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            Array.Copy(lhs.dims, 0, result, 0, lhs.Length)\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) = lhs(i2) + rhs(i2)\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector\n            Dim result(31) As Double\n            For i = 1 To lhs.Length\n                Dim i2 = i - 1\n                If lhs(i2) <> 0.0 Then\n                    For j = 1 To lhs.Length\n                        Dim j2 = j - 1\n                        If rhs(j2) <> 0.0 Then\n                            Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)\n                            Dim k = i2 Xor j2\n                            result(k) += s\n                        End If\n                    Next\n                End If\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Public Shared Operator *(v As Vector, scale As Double) As Vector\n            Dim result = CType(v.dims.Clone, Double())\n            For i = 1 To result.Length\n                Dim i2 = i - 1\n                result(i2) *= scale\n            Next\n            Return New Vector(result)\n        End Operator\n\n        Default Public Property Index(key As Integer) As Double\n            Get\n                Return dims(key)\n            End Get\n            Set(value As Double)\n                dims(key) = value\n            End Set\n        End Property\n\n        Public ReadOnly Property Length As Integer\n            Get\n                Return dims.Length\n            End Get\n        End Property\n\n        Public Function Dot(rhs As Vector) As Vector\n            Return (Me * rhs + rhs * Me) * 0.5\n        End Function\n\n        Private Shared Function BitCount(i As Integer) As Integer\n            i -= ((i >> 1) And &H55555555)\n            i = (i And &H33333333) + ((i >> 2) And &H33333333)\n            i = (i + (i >> 4)) And &HF0F0F0F\n            i += (i >> 8)\n            i += (i >> 16)\n            Return i And &H3F\n        End Function\n\n        Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double\n            Dim k = i >> 1\n            Dim sum = 0\n            While k <> 0\n                sum += BitCount(k And j)\n                k >>= 1\n            End While\n            Return If((sum And 1) = 0, 1.0, -1.0)\n        End Function\n\n        Public Overrides Function ToString() As String\n            Dim it = dims.GetEnumerator\n\n            Dim sb As New StringBuilder(\"[\")\n            If it.MoveNext() Then\n                sb.Append(it.Current)\n            End If\n            While it.MoveNext\n                sb.Append(\", \")\n                sb.Append(it.Current)\n            End While\n            sb.Append(\"]\")\n            Return sb.ToString\n        End Function\n    End Structure\n\n    Function DoubleArray(size As Integer) As Double()\n        Dim result(size - 1) As Double\n        For i = 1 To size\n            Dim i2 = i - 1\n            result(i2) = 0.0\n        Next\n        Return result\n    End Function\n\n    Function E(n As Integer) As Vector\n        If n > 4 Then\n            Throw New ArgumentException(\"n must be less than 5\")\n        End If\n\n        Dim result As New Vector(DoubleArray(32))\n        result(1 << n) = 1.0\n        Return result\n    End Function\n\n    ReadOnly r As New Random()\n\n    Function RandomVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To 5\n            Dim i2 = i - 1\n            Dim singleton() As Double = {r.NextDouble()}\n            result += New Vector(singleton) * E(i2)\n        Next\n        Return result\n    End Function\n\n    Function RandomMultiVector() As Vector\n        Dim result As New Vector(DoubleArray(32))\n        For i = 1 To result.Length\n            Dim i2 = i - 1\n            result(i2) = r.NextDouble()\n        Next\n        Return result\n    End Function\n\n    Sub Main()\n        For i = 1 To 5\n            Dim i2 = i - 1\n            For j = 1 To 5\n                Dim j2 = j - 1\n                If i2 < j2 Then\n                    If E(i2).Dot(E(j2))(0) <> 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected non-null scalar product\")\n                        Return\n                    End If\n                ElseIf i2 = j2 Then\n                    If E(i2).Dot(E(j2))(0) = 0.0 Then\n                        Console.Error.WriteLine(\"Unexpected null scalar product\")\n                        Return\n                    End If\n                End If\n            Next\n        Next\n\n        Dim a = RandomMultiVector()\n        Dim b = RandomMultiVector()\n        Dim c = RandomMultiVector()\n        Dim x = RandomVector()\n\n        \n        Console.WriteLine((a * b) * c)\n        Console.WriteLine(a * (b * c))\n        Console.WriteLine()\n\n        \n        Console.WriteLine(a * (b + c))\n        Console.WriteLine(a * b + a * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine((a + b) * c)\n        Console.WriteLine(a * c + b * c)\n        Console.WriteLine()\n\n        \n        Console.WriteLine(x * x)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class GeometricAlgebra {\n    private static int bitCount(int i) {\n        i -= ((i >> 1) & 0x55555555);\n        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n        i = (i + (i >> 4)) & 0x0F0F0F0F;\n        i += (i >> 8);\n        i += (i >> 16);\n        return i & 0x0000003F;\n    }\n\n    private static double reorderingSign(int i, int j) {\n        int k = i >> 1;\n        int sum = 0;\n        while (k != 0) {\n            sum += bitCount(k & j);\n            k = k >> 1;\n        }\n        return ((sum & 1) == 0) ? 1.0 : -1.0;\n    }\n\n    static class Vector {\n        private double[] dims;\n\n        public Vector(double[] dims) {\n            this.dims = dims;\n        }\n\n        public Vector dot(Vector rhs) {\n            return times(rhs).plus(rhs.times(this)).times(0.5);\n        }\n\n        public Vector unaryMinus() {\n            return times(-1.0);\n        }\n\n        public Vector plus(Vector rhs) {\n            double[] result = Arrays.copyOf(dims, 32);\n            for (int i = 0; i < rhs.dims.length; ++i) {\n                result[i] += rhs.get(i);\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(Vector rhs) {\n            double[] result = new double[32];\n            for (int i = 0; i < dims.length; ++i) {\n                if (dims[i] != 0.0) {\n                    for (int j = 0; j < rhs.dims.length; ++j) {\n                        if (rhs.get(j) != 0.0) {\n                            double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];\n                            int k = i ^ j;\n                            result[k] += s;\n                        }\n                    }\n                }\n            }\n            return new Vector(result);\n        }\n\n        public Vector times(double scale) {\n            double[] result = dims.clone();\n            for (int i = 0; i < 5; ++i) {\n                dims[i] *= scale;\n            }\n            return new Vector(result);\n        }\n\n        double get(int index) {\n            return dims[index];\n        }\n\n        void set(int index, double value) {\n            dims[index] = value;\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder(\"(\");\n            boolean first = true;\n            for (double value : dims) {\n                if (first) {\n                    first = false;\n                } else {\n                    sb.append(\", \");\n                }\n                sb.append(value);\n            }\n            return sb.append(\")\").toString();\n        }\n    }\n\n    private static Vector e(int n) {\n        if (n > 4) {\n            throw new IllegalArgumentException(\"n must be less than 5\");\n        }\n        Vector result = new Vector(new double[32]);\n        result.set(1 << n, 1.0);\n        return result;\n    }\n\n    private static final Random rand = new Random();\n\n    private static Vector randomVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 5; ++i) {\n            Vector temp = new Vector(new double[]{rand.nextDouble()});\n            result = result.plus(temp.times(e(i)));\n        }\n        return result;\n    }\n\n    private static Vector randomMultiVector() {\n        Vector result = new Vector(new double[32]);\n        for (int i = 0; i < 32; ++i) {\n            result.set(i, rand.nextDouble());\n        }\n        return result;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 5; ++j) {\n                if (i < j) {\n                    if (e(i).dot(e(j)).get(0) != 0.0) {\n                        System.out.println(\"Unexpected non-null scalar product.\");\n                        return;\n                    }\n                }\n            }\n        }\n\n        Vector a = randomMultiVector();\n        Vector b = randomMultiVector();\n        Vector c = randomMultiVector();\n        Vector x = randomVector();\n\n        \n        System.out.println(a.times(b).times(c));\n        System.out.println(a.times(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.times(b.plus(c)));\n        System.out.println(a.times(b).plus(a.times(c)));\n        System.out.println();\n\n        \n        System.out.println(a.plus(b).times(c));\n        System.out.println(a.times(c).plus(b.times(c)));\n        System.out.println();\n\n        \n        System.out.println(x.times(x));\n    }\n}\n"}
{"id": 60351, "name": "Associative array_Iteration", "VB": "Option Explicit\nSub Test()\n    Dim h As Object, i As Long, u, v, s\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n\n    \n    For Each s In h.Keys\n        Debug.Print s\n    Next\n\n    \n    For Each s In h.Items\n        Debug.Print s\n    Next\n\n    \n    u = h.Keys\n    v = h.Items\n    For i = 0 To h.Count - 1\n        Debug.Print u(i), v(i)\n    Next\nEnd Sub\n", "Java": "Map<String, Integer> map = new HashMap<String, Integer>();\nmap.put(\"hello\", 1);\nmap.put(\"world\", 2);\nmap.put(\"!\", 3);\n\n\nfor (Map.Entry<String, Integer> e : map.entrySet()) {\n    String key = e.getKey();\n    Integer value = e.getValue();\n    System.out.println(\"key = \" + key + \", value = \" + value);\n}\n\n\nfor (String key : map.keySet()) {\n    System.out.println(\"key = \" + key);\n}\n\n\nfor (Integer value : map.values()) {\n    System.out.println(\"value = \" + value);\n}\n"}
{"id": 60352, "name": "Define a primitive data type", "VB": "Private mvarValue As Integer\n\nPublic Property Let Value(ByVal vData As Integer)\n    If (vData > 10) Or (vData < 1) Then\n        Error 380   \n    Else\n        mvarValue = vData\n    End If\nEnd Property\n\nPublic Property Get Value() As Integer\n    Value = mvarValue\nEnd Property\n\nPrivate Sub Class_Initialize()\n    \n    mvarValue = 1\nEnd Sub\n", "Java": "class BoundedIntOutOfBoundsException extends Exception\n{\n  public BoundedIntOutOfBoundsException(int v, int l, int u) {\n    super(\"value \" + v + \" is out of bounds [\" + l + \",\" + u + \"]\");\n  }\n}\n\nclass BoundedInt {\n  private int value;\n  private int lower;\n  private int upper;\n\n  public BoundedInt(int l, int u) {\n    lower = Math.min(l, u);\n    upper = Math.max(l, u);\n  }\n\n  private boolean checkBounds(int v) {\n    return (v >= this.lower) && (v <= this.upper);\n  }\n\n  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{\n    assign(i.value()); \n  }\n\n  public void assign(int v) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(v) ) {\n      this.value = v;\n    } else {\n      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);\n    }\n  }\n\n  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {\n    return add(i.value());\n  }\n\n  public int add(int i) throws BoundedIntOutOfBoundsException {\n    if ( checkBounds(this.value + i) ) {\n      this.value += i;\n    }  else {\n      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);\n    }\n    return this.value;\n  }\n\n  public int value() {\n    return this.value;\n  }\n}\n\n\npublic class Bounded {\n  public static void main(String[] args) throws BoundedIntOutOfBoundsException {\n    BoundedInt a = new BoundedInt(1, 10);\n    BoundedInt b = new BoundedInt(1, 10);\n\n    a.assign(6);\n    try {\n      b.assign(12);\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n    b.assign(9);\n    try {\n      a.add(b.value());\n    } catch (Exception e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n"}
{"id": 60353, "name": "Hash join", "VB": "Dim t_age(4,1)\nt_age(0,0) = 27 : t_age(0,1) = \"Jonah\"\nt_age(1,0) = 18 : t_age(1,1) = \"Alan\"\nt_age(2,0) = 28 : t_age(2,1) = \"Glory\"\nt_age(3,0) = 18 : t_age(3,1) = \"Popeye\"\nt_age(4,0) = 28 : t_age(4,1) = \"Alan\"\n\nDim t_nemesis(4,1)\nt_nemesis(0,0) = \"Jonah\" : t_nemesis(0,1) = \"Whales\"\nt_nemesis(1,0) = \"Jonah\" : t_nemesis(1,1) = \"Spiders\"\nt_nemesis(2,0) = \"Alan\" : t_nemesis(2,1) = \"Ghosts\"\nt_nemesis(3,0) = \"Alan\" : t_nemesis(3,1) = \"Zombies\"\nt_nemesis(4,0) = \"Glory\" : t_nemesis(4,1) = \"Buffy\"\n\nCall hash_join(t_age,1,t_nemesis,0)\n\nSub hash_join(table_1,index_1,table_2,index_2)\n\tSet hash = CreateObject(\"Scripting.Dictionary\")\n\tFor i = 0 To UBound(table_1)\n\t\thash.Add i,Array(table_1(i,0),table_1(i,1))\n\tNext\n\tFor j = 0 To UBound(table_2)\n\t\tFor Each key In hash.Keys\n\t\t\tIf hash(key)(index_1) = table_2(j,index_2) Then\n\t\t\t\tWScript.StdOut.WriteLine hash(key)(0) & \",\" & hash(key)(1) &_\n\t\t\t\t\t\" = \" & table_2(j,0) & \",\" & table_2(j,1)\n\t\t\tEnd If\n\t\tNext\n\tNext\nEnd Sub\n", "Java": "import java.util.*;\n\npublic class HashJoin {\n\n    public static void main(String[] args) {\n        String[][] table1 = {{\"27\", \"Jonah\"}, {\"18\", \"Alan\"}, {\"28\", \"Glory\"},\n        {\"18\", \"Popeye\"}, {\"28\", \"Alan\"}};\n\n        String[][] table2 = {{\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n        {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n        {\"Bob\", \"foo\"}};\n\n        hashJoin(table1, 1, table2, 0).stream()\n                .forEach(r -> System.out.println(Arrays.deepToString(r)));\n    }\n\n    static List<String[][]> hashJoin(String[][] records1, int idx1,\n            String[][] records2, int idx2) {\n\n        List<String[][]> result = new ArrayList<>();\n        Map<String, List<String[]>> map = new HashMap<>();\n\n        for (String[] record : records1) {\n            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());\n            v.add(record);\n            map.put(record[idx1], v);\n        }\n\n        for (String[] record : records2) {\n            List<String[]> lst = map.get(record[idx2]);\n            if (lst != null) {\n                lst.stream().forEach(r -> {\n                    result.add(new String[][]{r, record});\n                });\n            }\n        }\n\n        return result;\n    }\n}\n"}
{"id": 60354, "name": "Sierpinski square 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n"}
{"id": 60355, "name": "Sierpinski square 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst raiz2=1.4142135623730950488016887242097\nsub media_sierp (niv,sz)\n   if niv=0 then x.fw sz: exit sub \n   media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1\n    media_sierp niv-1,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n  media_sierp niv-1,sz\n   x.lt 1\n   x.fw sz*raiz2\n   x.lt 1 \n    media_sierp niv-1,sz\nend sub    \n\n\n\n\n\n\n\n\n\n\n\n\nsub sierp(niv,sz)\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\n   media_sierp niv,sz\n   x.rt 2\n   x.fw sz\n   x.rt 2\nend sub   \n     \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=0\nx.incr=1\nx.x=100:x.y=270\n\nsierp 5,4\nset x=nothing\n", "Java": "import java.io.*;\n\npublic class SierpinskiSquareCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"sierpinski_square.svg\"))) {\n            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);\n            int size = 635, length = 5;\n            s.currentAngle = 0;\n            s.currentX = (size - length)/2;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(size);\n            s.execute(rewrite(5));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private SierpinskiSquareCurve(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 = AXIOM;\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 == 'X')\n                    sb.append(PRODUCTION);\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\n    private static final String AXIOM = \"F+XF+F+XF\";\n    private static final String PRODUCTION = \"XF-F+F-XF+F+XF-F+F-X\";\n    private static final int ANGLE = 90;\n}\n"}
{"id": 60356, "name": "Word break problem", "VB": "Module Module1\n\n    Structure Node\n        Private ReadOnly m_val As String\n        Private ReadOnly m_parsed As List(Of String)\n\n        Sub New(initial As String)\n            m_val = initial\n            m_parsed = New List(Of String)\n        End Sub\n\n        Sub New(s As String, p As List(Of String))\n            m_val = s\n            m_parsed = p\n        End Sub\n\n        Public Function Value() As String\n            Return m_val\n        End Function\n\n        Public Function Parsed() As List(Of String)\n            Return m_parsed\n        End Function\n    End Structure\n\n    Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))\n        Dim matches As New List(Of List(Of String))\n        Dim q As New Queue(Of Node)\n        q.Enqueue(New Node(s))\n        While q.Count > 0\n            Dim node = q.Dequeue()\n            REM check if fully parsed\n            If node.Value.Length = 0 Then\n                matches.Add(node.Parsed)\n            Else\n                For Each word In dictionary\n                    REM check for match\n                    If node.Value.StartsWith(word) Then\n                        Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)\n                        Dim parsedNew As New List(Of String)\n                        parsedNew.AddRange(node.Parsed)\n                        parsedNew.Add(word)\n                        q.Enqueue(New Node(valNew, parsedNew))\n                    End If\n                Next\n            End If\n        End While\n        Return matches\n    End Function\n\n    Sub Main()\n        Dim dict As New List(Of String) From {\"a\", \"aa\", \"b\", \"ab\", \"aab\"}\n        For Each testString In {\"aab\", \"aa b\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n\n        dict = New List(Of String) From {\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\"}\n        For Each testString In {\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"}\n            Dim matches = WordBreak(testString, dict)\n            Console.WriteLine(\"String = {0}, Dictionary = {1}. Solutions = {2}\", testString, dict, matches.Count)\n            For Each match In matches\n                Console.WriteLine(\" Word Break = [{0}]\", String.Join(\", \", match))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class WordBreak {\n\n    public static void main(String[] args) {\n        List<String> dict = Arrays.asList(\"a\", \"aa\", \"b\", \"ab\", \"aab\");\n        for ( String testString : Arrays.asList(\"aab\", \"aa b\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n        dict = Arrays.asList(\"abc\", \"a\", \"ac\", \"b\", \"c\", \"cb\", \"d\");\n        for ( String testString : Arrays.asList(\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\") ) {\n            List<List<String>> matches = wordBreak(testString, dict);\n            System.out.printf(\"String = %s, Dictionary = %s.  Solutions = %d:%n\", testString, dict, matches.size());\n            for ( List<String> match : matches ) {\n                System.out.printf(\" Word Break = %s%n\", match);\n            }\n            System.out.printf(\"%n\");\n        }\n    }\n    \n    private static List<List<String>> wordBreak(String s, List<String> dictionary) {\n        List<List<String>> matches = new ArrayList<>();\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(s));\n        while ( ! queue.isEmpty() ) {\n            Node node = queue.remove();\n            \n            if ( node.val.length() == 0 ) {\n                matches.add(node.parsed);\n            }\n            else {\n                for ( String word : dictionary ) {\n                    \n                    if ( node.val.startsWith(word) ) {\n                        String valNew = node.val.substring(word.length(), node.val.length());\n                        List<String> parsedNew = new ArrayList<>();\n                        parsedNew.addAll(node.parsed);\n                        parsedNew.add(word);\n                        queue.add(new Node(valNew, parsedNew));\n                    }\n                }\n            }\n        }\n        return matches;\n    }\n    \n    private static class Node {\n        private String val;  \n        private List<String> parsed;  \n        public Node(String initial) {\n            val = initial;\n            parsed = new ArrayList<>();\n        }\n        public Node(String s, List<String> p) {\n            val = s;\n            parsed = p;\n        }\n    }\n\n}\n"}
{"id": 60357, "name": "Latin Squares in reduced form", "VB": "Option Strict On\n\nImports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))\n\nModule Module1\n\n    Sub Swap(Of T)(ByRef a As T, ByRef b As T)\n        Dim u = a\n        a = b\n        b = u\n    End Sub\n\n    Sub PrintSquare(latin As Matrix)\n        For Each row In latin\n            Dim it = row.GetEnumerator\n            Console.Write(\"[\")\n            If it.MoveNext Then\n                Console.Write(it.Current)\n            End If\n            While it.MoveNext\n                Console.Write(\", \")\n                Console.Write(it.Current)\n            End While\n            Console.WriteLine(\"]\")\n        Next\n        Console.WriteLine()\n    End Sub\n\n    Function DList(n As Integer, start As Integer) As Matrix\n        start -= 1 REM use 0 based indexes\n        Dim a = Enumerable.Range(0, n).ToArray\n        a(start) = a(0)\n        a(0) = start\n        Array.Sort(a, 1, a.Length - 1)\n        Dim first = a(1)\n        REM recursive closure permutes a[1:]\n        Dim r As New Matrix\n\n        Dim Recurse As Action(Of Integer) = Sub(last As Integer)\n                                                If last = first Then\n                                                    REM bottom of recursion. you get here once for each permutation\n                                                    REM test if permutation is deranged.\n                                                    For j = 1 To a.Length - 1\n                                                        Dim v = a(j)\n                                                        If j = v Then\n                                                            Return REM no, ignore it\n                                                        End If\n                                                    Next\n                                                    REM yes, save a copy with 1 based indexing\n                                                    Dim b = a.Select(Function(v) v + 1).ToArray\n                                                    r.Add(b.ToList)\n                                                    Return\n                                                End If\n                                                For i = last To 1 Step -1\n                                                    Swap(a(i), a(last))\n                                                    Recurse(last - 1)\n                                                    Swap(a(i), a(last))\n                                                Next\n                                            End Sub\n        Recurse(n - 1)\n        Return r\n    End Function\n\n    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong\n        If n <= 0 Then\n            If echo Then\n                Console.WriteLine(\"[]\")\n                Console.WriteLine()\n            End If\n            Return 0\n        End If\n        If n = 1 Then\n            If echo Then\n                Console.WriteLine(\"[1]\")\n                Console.WriteLine()\n            End If\n            Return 1\n        End If\n\n        Dim rlatin As New Matrix\n        For i = 0 To n - 1\n            rlatin.Add(New List(Of Integer))\n            For j = 0 To n - 1\n                rlatin(i).Add(0)\n            Next\n        Next\n        REM first row\n        For j = 0 To n - 1\n            rlatin(0)(j) = j + 1\n        Next\n\n        Dim count As ULong = 0\n        Dim Recurse As Action(Of Integer) = Sub(i As Integer)\n                                                Dim rows = DList(n, i)\n\n                                                For r = 0 To rows.Count - 1\n                                                    rlatin(i - 1) = rows(r)\n                                                    For k = 0 To i - 2\n                                                        For j = 1 To n - 1\n                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then\n                                                                If r < rows.Count - 1 Then\n                                                                    GoTo outer\n                                                                End If\n                                                                If i > 2 Then\n                                                                    Return\n                                                                End If\n                                                            End If\n                                                        Next\n                                                    Next\n                                                    If i < n Then\n                                                        Recurse(i + 1)\n                                                    Else\n                                                        count += 1UL\n                                                        If echo Then\n                                                            PrintSquare(rlatin)\n                                                        End If\n                                                    End If\nouter:\n                                                    While False\n                                                        REM empty\n                                                    End While\n                                                Next\n                                            End Sub\n\n        REM remiain rows\n        Recurse(2)\n        Return count\n    End Function\n\n    Function Factorial(n As ULong) As ULong\n        If n <= 0 Then\n            Return 1\n        End If\n        Dim prod = 1UL\n        For i = 2UL To n\n            prod *= i\n        Next\n        Return prod\n    End Function\n\n    Sub Main()\n        Console.WriteLine(\"The four reduced latin squares of order 4 are:\")\n        Console.WriteLine()\n        ReducedLatinSquares(4, True)\n\n        Console.WriteLine(\"The size of the set of reduced latin squares for the following orders\")\n        Console.WriteLine(\"and hence the total number of latin squares of these orders are:\")\n        Console.WriteLine()\n        For n = 1 To 6\n            Dim nu As ULong = CULng(n)\n\n            Dim size = ReducedLatinSquares(n, False)\n            Dim f = Factorial(nu - 1UL)\n            f *= f * nu * size\n            Console.WriteLine(\"Order {0}: Size {1} x {2}! x {3}! => Total {4}\", n, size, n, n - 1, f)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class LatinSquaresInReducedForm {\n\n    public static void main(String[] args) {\n        System.out.printf(\"Reduced latin squares of order 4:%n\");\n        for ( LatinSquare square : getReducedLatinSquares(4) ) {\n            System.out.printf(\"%s%n\", square);\n        }\n        \n        System.out.printf(\"Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n\");\n        for ( int n = 1 ; n <= 6 ; n++ ) {\n            List<LatinSquare> list = getReducedLatinSquares(n);\n            System.out.printf(\"Size = %d, %d * %d * %d = %,d%n\", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));\n        }\n    }\n    \n    private static long fact(int n) {\n        if ( n == 0 ) {\n            return 1;\n        }\n        int prod = 1;\n        for ( int i = 1 ; i <= n ; i++ ) {\n            prod *= i;\n        }\n        return prod;\n    }\n    \n    private static List<LatinSquare> getReducedLatinSquares(int n) {\n        List<LatinSquare> squares = new ArrayList<>();\n        \n        squares.add(new LatinSquare(n));\n        PermutationGenerator permGen = new PermutationGenerator(n);\n        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {\n            List<LatinSquare> squaresNext = new ArrayList<>();\n            for ( LatinSquare square : squares ) {\n                while ( permGen.hasMore() ) {\n                    int[] perm = permGen.getNext();\n                    \n                    \n                    if ( (perm[0]+1) != (fillRow+1) ) {\n                        continue;\n                    }\n                    \n                    \n                    boolean permOk = true;\n                    done:\n                    for ( int row = 0 ; row < fillRow ; row++ ) {\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            if ( square.get(row, col) == (perm[col]+1) ) {\n                                permOk = false;\n                                break done;\n                            }\n                        }\n                    }\n                    if ( permOk ) {\n                        LatinSquare newSquare = new LatinSquare(square);\n                        for ( int col = 0 ; col < n ; col++ ) {\n                            newSquare.set(fillRow, col, perm[col]+1);\n                        }\n                        squaresNext.add(newSquare);\n                    }\n                }\n                permGen.reset();\n            }\n            squares = squaresNext;\n        }\n        \n        return squares;\n    }\n    \n    @SuppressWarnings(\"unused\")\n    private static int[] display(int[] in) {\n        int [] out = new int[in.length];\n        for ( int i = 0 ; i < in.length ; i++ ) {\n            out[i] = in[i] + 1;\n        }\n        return out;\n    }\n    \n    private static class LatinSquare {\n        \n        int[][] square;\n        int size;\n        \n        public LatinSquare(int n) {\n            square = new int[n][n];\n            size = n;\n            for ( int col = 0 ; col < n ; col++ ) {\n                set(0, col, col + 1);\n            }\n        }\n        \n        public LatinSquare(LatinSquare ls) {\n            int n = ls.size;\n            square = new int[n][n];\n            size = n;\n            for ( int row = 0 ; row < n ; row++ ) {\n                for ( int col = 0 ; col < n ; col++ ) {\n                    set(row, col, ls.get(row, col));\n                }\n            }\n        }\n        \n        public void set(int row, int col, int value) {\n            square[row][col] = value;\n        }\n\n        public int get(int row, int col) {\n            return square[row][col];\n        }\n\n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            for ( int row = 0 ; row < size ; row++ ) {\n                sb.append(Arrays.toString(square[row]));\n                sb.append(\"\\n\");\n            }\n            return sb.toString();\n        }\n        \n        \n    }\n\n    private static class PermutationGenerator {\n\n        private int[] a;\n        private BigInteger numLeft;\n        private BigInteger total;\n\n        public PermutationGenerator (int n) {\n            if (n < 1) {\n                throw new IllegalArgumentException (\"Min 1\");\n            }\n            a = new int[n];\n            total = getFactorial(n);\n            reset();\n        }\n\n        private void reset () {\n            for ( int i = 0 ; i < a.length ; i++ ) {\n                a[i] = i;\n            }\n            numLeft = new BigInteger(total.toString());\n        }\n\n        public boolean hasMore() {\n            return numLeft.compareTo(BigInteger.ZERO) == 1;\n        }\n\n        private static BigInteger getFactorial (int n) {\n            BigInteger fact = BigInteger.ONE;\n            for ( int i = n ; i > 1 ; i-- ) {\n                fact = fact.multiply(new BigInteger(Integer.toString(i)));\n            }\n            return fact;\n        }\n\n        \n        public int[] getNext() {\n            if ( numLeft.equals(total) ) {\n                numLeft = numLeft.subtract (BigInteger.ONE);\n                return a;\n            }\n\n            \n            int j = a.length - 2;\n            while ( a[j] > a[j+1] ) {\n                j--;\n            }\n\n            \n            int k = a.length - 1;\n            while ( a[j] > a[k] ) {\n                k--;\n            }\n\n            \n            int temp = a[k];\n            a[k] = a[j];\n            a[j] = temp;\n\n            \n            int r = a.length - 1;\n            int s = j + 1;\n            while (r > s) {\n                int temp2 = a[s];\n                a[s] = a[r];\n                a[r] = temp2;\n                r--;\n                s++;\n            }\n\n            numLeft = numLeft.subtract(BigInteger.ONE);\n            return a;\n        }\n    }\n\n}\n"}
{"id": 60358, "name": "UPC", "VB": "\n\nOption Explicit\nConst m_limit =\"# #\"\nConst m_middle=\" # # \"\nDim a,bnum,i,check,odic\na=array(\"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",_\n         \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",_\n        \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",_\n          \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",_\n        \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",_\n       \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",_\n        \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",_\n         \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",_\n        \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",_\n         \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \")\n\n\nbnum=Array(\"0001101\",\"0011001\",\"0010011\",\"0111101\",\"0100011\",\" 0110001\",\"0101111\",\"0111011\",\"0110111\",\"0001011\")\n\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=0 To 9: \n  odic.Add bin2dec(bnum(i),Asc(\"1\")),i+1 \n  odic.Add bin2dec(bnum(i),Asc(\"0\")),-i-1  \nNext\n\nFor i=0 To UBound(a) : print pad(i+1,-2) & \": \"& upc(a(i)) :Next\n  WScript.Quit(1)\n  \n  Function bin2dec(ByVal B,a) \n    Dim n\n    While len(b)\n      n =n *2 - (asc(b)=a)  \n      b=mid(b,2) \n    Wend\n    bin2dec= n And 127\n  End Function\n  \n  Sub 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\n  End Sub\n  function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else  pad= left(s& space(n),n) end if :end function\n   \n  Function iif(t,a,b)  If t Then iif=a Else iif=b End If :End Function\n  \n  Function getnum(s,r) \n    Dim n,s1,r1 \n    \n    s1=Left(s,7)\n    s=Mid(s,8)\n    r1=r\n    Do\n      If r Then s1=StrReverse(s1) \n      n=bin2dec(s1,asc(\"#\"))\n      If odic.exists(n) Then\n        getnum=odic(n)\n        Exit Function\n      Else\n        If r1<>r Then getnum=0:Exit Function\n        r=Not r\n      End If\n    Loop \n  End Function          \n  \n  Function getmarker(s,m) \n    getmarker= (InStr(s,m)= 1)\n    s=Mid(s,Len(m)+1)\n  End Function\n  \n  Function checksum(ByVal s)\n    Dim n,i : n=0\n    do\n       n=n+(Asc(s)-48)*3\n       s=Mid(s,2)\n       n=n+(Asc(s)-48)*1\n       s=Mid(s,2)\n    Loop until Len(s)=0\n    checksum= ((n mod 10)=0)\n  End function      \n      \n  Function upc(ByVal s1)\n    Dim i,n,s,out,rev,j \n    \n    \n    s=Trim(s1)\n    If getmarker(s,m_limit)=False  Then upc= \"bad start marker \":Exit function\n    rev=False\n    out=\"\"\n    For j= 0 To 1\n      For i=0 To 5\n        n=getnum(s,rev)\n        If n=0 Then upc= pad(out,16) & pad (\"bad code\",-10) & pad(\"pos \"& i+j*6+1,-11): Exit Function\n        out=out & Abs(n)-1\n      Next\n      If j=0 Then If getmarker(s,m_middle)=False  Then upc= \"bad middle marker \" & out :Exit Function\n    Next  \n    If getmarker(s,m_limit)=False  Then upc= \"bad end marker \"  :Exit function\n    If rev Then out=strreverse(out)\n    upc= pad(out,16) &  pad(iif (checksum(out),\"valid\",\"not valid\"),-10)&  pad(iif(rev,\"reversed\",\"\"),-11)\n  End Function\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class UPC {\n    private static final int SEVEN = 7;\n\n    private static final Map<String, Integer> LEFT_DIGITS = Map.of(\n        \"   ## #\", 0,\n        \"  ##  #\", 1,\n        \"  #  ##\", 2,\n        \" #### #\", 3,\n        \" #   ##\", 4,\n        \" ##   #\", 5,\n        \" # ####\", 6,\n        \" ### ##\", 7,\n        \" ## ###\", 8,\n        \"   # ##\", 9\n    );\n\n    private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()\n        .stream()\n        .collect(Collectors.toMap(\n            entry -> entry.getKey()\n                .replace(' ', 's')\n                .replace('#', ' ')\n                .replace('s', '#'),\n            Map.Entry::getValue\n        ));\n\n    private static final String END_SENTINEL = \"# #\";\n    private static final String MID_SENTINEL = \" # # \";\n\n    private static void decodeUPC(String input) {\n        Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {\n            int pos = 0;\n            var part = candidate.substring(pos, pos + END_SENTINEL.length());\n\n            List<Integer> output = new ArrayList<>();\n            if (END_SENTINEL.equals(part)) {\n                pos += END_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (LEFT_DIGITS.containsKey(part)) {\n                    output.add(LEFT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + MID_SENTINEL.length());\n            if (MID_SENTINEL.equals(part)) {\n                pos += MID_SENTINEL.length();\n            } else {\n                return Map.entry(false, output);\n            }\n\n            for (int i = 1; i < SEVEN; i++) {\n                part = candidate.substring(pos, pos + SEVEN);\n                pos += SEVEN;\n\n                if (RIGHT_DIGITS.containsKey(part)) {\n                    output.add(RIGHT_DIGITS.get(part));\n                } else {\n                    return Map.entry(false, output);\n                }\n            }\n\n            part = candidate.substring(pos, pos + END_SENTINEL.length());\n            if (!END_SENTINEL.equals(part)) {\n                return Map.entry(false, output);\n            }\n\n            int sum = 0;\n            for (int i = 0; i < output.size(); i++) {\n                if (i % 2 == 0) {\n                    sum += 3 * output.get(i);\n                } else {\n                    sum += output.get(i);\n                }\n            }\n            return Map.entry(sum % 10 == 0, output);\n        };\n\n        Consumer<List<Integer>> printList = list -> {\n            var it = list.iterator();\n            System.out.print('[');\n            if (it.hasNext()) {\n                System.out.print(it.next());\n            }\n            while (it.hasNext()) {\n                System.out.print(\", \");\n                System.out.print(it.next());\n            }\n            System.out.print(']');\n        };\n\n        var candidate = input.trim();\n        var out = decode.apply(candidate);\n        if (out.getKey()) {\n            printList.accept(out.getValue());\n            System.out.println();\n        } else {\n            StringBuilder builder = new StringBuilder(candidate);\n            builder.reverse();\n            out = decode.apply(builder.toString());\n            if (out.getKey()) {\n                printList.accept(out.getValue());\n                System.out.println(\" Upside down\");\n            } else if (out.getValue().size() == 12) {\n                System.out.println(\"Invalid checksum\");\n            } else {\n                System.out.println(\"Invalid digit(s)\");\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        var barcodes = List.of(\n            \"         # #   # ##  #  ## #   ## ### ## ### ## #### # # # ## ##  #   #  ##  ## ###  # ##  ## ### #  # #       \",\n            \"        # # #   ##   ## # #### #   # ## #   ## #   ## # # # ###  # ###  ##  ## ###  # #  ### ###  # # #         \",\n            \"         # #    # # #  ###  #   #    # #  #   #    # # # # ## #   ## #   ## #   ##   # # #### ### ## # #         \",\n            \"       # # ##  ## ##  ##   #  #   #  # ###  # ##  ## # # #   ## ##  #  ### ## ## #   # #### ## #   # #        \",\n            \"         # # ### ## #   ## ## ###  ##  # ##   #   # ## # # ### #  ## ##  #    # ### #  ## ##  #      # #          \",\n            \"          # #  #   # ##  ##  #   #   #  # ##  ##  #   # # # # #### #  ##  # #### #### # #  ##  # #### # #         \",\n            \"         # #  #  ##  ##  # #   ## ##   # ### ## ##   # # # #  #   #   #  #  ### # #    ###  # #  #   # #        \",\n            \"        # # #    # ##  ##   #  # ##  ##  ### #   #  # # # ### ## ## ### ## ### ### ## #  ##  ### ## # #         \",\n            \"         # # ### ##   ## # # #### #   ## # #### # #### # # #   #  # ###  #    # ###  # #    # ###  # # #       \",\n            \"        # # # #### ##   # #### # #   ## ## ### #### # # # #  ### # ###  ###  # # ###  #    # #  ### # #         \"\n        );\n        barcodes.forEach(UPC::decodeUPC);\n    }\n}\n"}
{"id": 60359, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 60360, "name": "Playfair cipher", "VB": "Option Explicit\n\nPrivate Type Adress\n   Row As Integer\n   Column As Integer\nEnd Type\n\nPrivate myTable() As String\n\nSub Main()\nDim keyw As String, boolQ As Boolean, text As String, test As Long\nDim res As String\n   keyw = InputBox(\"Enter your keyword : \", \"KeyWord\", \"Playfair example\")\n   If keyw = \"\" Then GoTo ErrorHand\n   Debug.Print \"Enter your keyword : \" & keyw\n   boolQ = MsgBox(\"Ignore Q when buiding table  y/n : \", vbYesNo) = vbYes\n   Debug.Print \"Ignore Q when buiding table  y/n : \" & IIf(boolQ, \"Y\", \"N\")\n   Debug.Print \"\"\n   Debug.Print \"Table : \"\n   myTable = CreateTable(keyw, boolQ)\n   On Error GoTo ErrorHand\n   test = UBound(myTable)\n   On Error GoTo 0\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TRRE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   text = InputBox(\"Enter your text\", \"Encode\", \"hide the gold in the TREE stump\")\n   If text = \"\" Then GoTo ErrorHand\n   Debug.Print \"\"\n   Debug.Print \"Text to encode : \" & text\n   Debug.Print \"-------------------------------------------------\"\n   res = Encode(text)\n   Debug.Print \"Encoded text is : \" & res\n   res = Decode(res)\n   Debug.Print \"Decoded text is : \" & res\n   Exit Sub\nErrorHand:\n   Debug.Print \"error\"\nEnd Sub\n\nPrivate Function CreateTable(strKeyword As String, Q As Boolean) As String()\nDim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer\nDim strT As String, coll As New Collection\nDim s As String\n\n   strKeyword = UCase(Replace(strKeyword, \" \", \"\"))\n   If Q Then\n      If InStr(strKeyword, \"J\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   Else\n      If InStr(strKeyword, \"Q\") > 0 Then\n         Debug.Print \"Your keyword isn\n         Exit Function\n      End If\n   End If\n   strT = IIf(Not Q, \"ABCDEFGHIKLMNOPQRSTUVWXYZ\", \"ABCDEFGHIJKLMNOPRSTUVWXYZ\")\n   t = Split(StrConv(strKeyword, vbUnicode), Chr(0))\n   For c = LBound(t) To UBound(t) - 1\n      strT = Replace(strT, t(c), \"\")\n      On Error Resume Next\n      coll.Add t(c), t(c)\n      On Error GoTo 0\n   Next\n   strKeyword = vbNullString\n   For c = 1 To coll.Count\n      strKeyword = strKeyword & coll(c)\n   Next\n   t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0))\n   c = 1: r = 1\n   For cpt = LBound(t) To UBound(t) - 1\n      temp(r, c) = t(cpt)\n      s = s & \" \" & t(cpt)\n      c = c + 1\n      If c = 6 Then c = 1: r = r + 1: Debug.Print \"   \" & s: s = \"\"\n   Next\n   CreateTable = temp\nEnd Function\n\nPrivate Function Encode(s As String) As String\nDim i&, t() As String, cpt&\n   s = UCase(Replace(s, \" \", \"\"))\n   \n   For i = 1 To Len(s) - 1\n      If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & \"X\" & Right(s, Len(s) - i)\n   Next\n   \n   For i = 1 To Len(s) Step 2\n      ReDim Preserve t(cpt)\n      t(cpt) = Mid(s, i, 2)\n      cpt = cpt + 1\n   Next i\n   If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & \"X\"\n   Debug.Print \"[the pairs : \" & Join(t, \" \") & \"]\"\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsEncoding(t(i))\n   Next\n   Encode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsEncoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1)\n         resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1)\n         SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1)\n         resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1)\n         SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n\nPrivate Function Decode(s As String) As String\nDim t, i&, j&, e&\n   t = Split(s, \" \")\n   e = UBound(t) - 1\n   \n   For i = LBound(t) To UBound(t)\n      t(i) = SwapPairsDecoding(CStr(t(i)))\n   Next\n   \n   For i = LBound(t) To e\n      If Right(t(i), 1) = \"X\" And Left(t(i), 1) = Left(t(i + 1), 1) Then\n         t(i) = Left(t(i), 1) & Left(t(i + 1), 1)\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      ElseIf Left(t(i + 1), 1) = \"X\" And Right(t(i), 1) = Right(t(i + 1), 1) Then\n         For j = i + 1 To UBound(t) - 1\n            t(j) = Right(t(j), 1) & Left(t(j + 1), 1)\n         Next j\n         If Right(t(j), 1) = \"X\" Then\n            ReDim Preserve t(j - 1)\n         Else\n            t(j) = Right(t(j), 1) & \"X\"\n         End If\n      End If\n   Next\n   Decode = Join(t, \" \")\nEnd Function\n\nPrivate Function SwapPairsDecoding(s As String) As String\nDim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean\nDim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress\n   d1 = Left(s, 1): d2 = Right(s, 1)\n   For r = 1 To 5\n      For c = 1 To 5\n         If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c\n         If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c\n         If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For\n      Next\n      If Flag Then Exit For\n   Next\n   Select Case True\n      Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1)\n         resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1)\n         SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column\n         \n         resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1)\n         resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1)\n         SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column)\n      Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column\n         \n         resD1.Row = addD1.Row\n         resD2.Row = addD2.Row\n         resD1.Column = addD2.Column\n         resD2.Column = addD1.Column\n         SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)\n   End Select\nEnd Function\n", "Java": "import java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n    private static char[][] charTable;\n    private static Point[] positions;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n        String txt = prompt(\"Enter the message: \", sc, 1);\n        String jti = prompt(\"Replace J with I? y/n: \", sc, 1);\n\n        boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n        createTable(key, changeJtoI);\n\n        String enc = encode(prepareText(txt, changeJtoI));\n\n        System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n        System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n    }\n\n    private static String prompt(String promptText, Scanner sc, int minLen) {\n        String s;\n        do {\n            System.out.print(promptText);\n            s = sc.nextLine().trim();\n        } while (s.length() < minLen);\n        return s;\n    }\n\n    private static String prepareText(String s, boolean changeJtoI) {\n        s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n        return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n    }\n\n    private static void createTable(String key, boolean changeJtoI) {\n        charTable = new char[5][5];\n        positions = new Point[26];\n\n        String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n        int len = s.length();\n        for (int i = 0, k = 0; i < len; i++) {\n            char c = s.charAt(i);\n            if (positions[c - 'A'] == null) {\n                charTable[k / 5][k % 5] = c;\n                positions[c - 'A'] = new Point(k % 5, k / 5);\n                k++;\n            }\n        }\n    }\n\n    private static String encode(String s) {\n        StringBuilder sb = new StringBuilder(s);\n\n        for (int i = 0; i < sb.length(); i += 2) {\n\n            if (i == sb.length() - 1)\n                sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n            else if (sb.charAt(i) == sb.charAt(i + 1))\n                sb.insert(i + 1, 'X');\n        }\n        return codec(sb, 1);\n    }\n\n    private static String decode(String s) {\n        return codec(new StringBuilder(s), 4);\n    }\n\n    private static String codec(StringBuilder text, int direction) {\n        int len = text.length();\n        for (int i = 0; i < len; i += 2) {\n            char a = text.charAt(i);\n            char b = text.charAt(i + 1);\n\n            int row1 = positions[a - 'A'].y;\n            int row2 = positions[b - 'A'].y;\n            int col1 = positions[a - 'A'].x;\n            int col2 = positions[b - 'A'].x;\n\n            if (row1 == row2) {\n                col1 = (col1 + direction) % 5;\n                col2 = (col2 + direction) % 5;\n\n            } else if (col1 == col2) {\n                row1 = (row1 + direction) % 5;\n                row2 = (row2 + direction) % 5;\n\n            } else {\n                int tmp = col1;\n                col1 = col2;\n                col2 = tmp;\n            }\n\n            text.setCharAt(i, charTable[row1][col1]);\n            text.setCharAt(i + 1, charTable[row2][col2]);\n        }\n        return text.toString();\n    }\n}\n"}
{"id": 60361, "name": "Closest-pair problem", "VB": "Option Explicit\n\nPrivate Type MyPoint\n    X As Single\n    Y As Single\nEnd Type\n\nPrivate Type MyPair\n    p1 As MyPoint\n    p2 As MyPoint\nEnd Type\n\nSub Main()\nDim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long\nDim T#\nRandomize Timer\n    Nb = 10\n    Do\n        ReDim points(1 To Nb)\n        For i = 1 To Nb\n            points(i).X = Rnd * Nb\n            points(i).Y = Rnd * Nb\n        Next\n        d = 1000000000000#\nT = Timer\n        BF = BruteForce(points, d)\n        Debug.Print \"For \" & Nb & \" points, runtime : \" & Timer - T & \" sec.\"\n        Debug.Print \"point 1 : X:\" & BF.p1.X & \" Y:\" & BF.p1.Y\n        Debug.Print \"point 2 : X:\" & BF.p2.X & \" Y:\" & BF.p2.Y\n        Debug.Print \"dist : \" & d\n        Debug.Print \"--------------------------------------------------\"\n        Nb = Nb * 10\n    Loop While Nb <= 10000\nEnd Sub\n\nPrivate Function BruteForce(p() As MyPoint, mindist As Single) As MyPair\nDim i As Long, j As Long, d As Single, ClosestPair As MyPair\n    For i = 1 To UBound(p) - 1\n        For j = i + 1 To UBound(p)\n            d = Dist(p(i), p(j))\n            If d < mindist Then\n                mindist = d\n                ClosestPair.p1 = p(i)\n                ClosestPair.p2 = p(j)\n            End If\n        Next\n    Next\n    BruteForce = ClosestPair\nEnd Function\n\nPrivate Function Dist(p1 As MyPoint, p2 As MyPoint) As Single\n    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)\nEnd Function\n", "Java": "import java.util.*;\n\npublic class ClosestPair\n{\n  public static class Point\n  {\n    public final double x;\n    public final double y;\n    \n    public Point(double x, double y)\n    {\n      this.x = x;\n      this.y = y;\n    }\n    \n    public String toString()\n    {  return \"(\" + x + \", \" + y + \")\";  }\n  }\n  \n  public static class Pair\n  {\n    public Point point1 = null;\n    public Point point2 = null;\n    public double distance = 0.0;\n    \n    public Pair()\n    {  }\n    \n    public Pair(Point point1, Point point2)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      calcDistance();\n    }\n    \n    public void update(Point point1, Point point2, double distance)\n    {\n      this.point1 = point1;\n      this.point2 = point2;\n      this.distance = distance;\n    }\n    \n    public void calcDistance()\n    {  this.distance = distance(point1, point2);  }\n    \n    public String toString()\n    {  return point1 + \"-\" + point2 + \" : \" + distance;  }\n  }\n  \n  public static double distance(Point p1, Point p2)\n  {\n    double xdist = p2.x - p1.x;\n    double ydist = p2.y - p1.y;\n    return Math.hypot(xdist, ydist);\n  }\n  \n  public static Pair bruteForce(List<? extends Point> points)\n  {\n    int numPoints = points.size();\n    if (numPoints < 2)\n      return null;\n    Pair pair = new Pair(points.get(0), points.get(1));\n    if (numPoints > 2)\n    {\n      for (int i = 0; i < numPoints - 1; i++)\n      {\n        Point point1 = points.get(i);\n        for (int j = i + 1; j < numPoints; j++)\n        {\n          Point point2 = points.get(j);\n          double distance = distance(point1, point2);\n          if (distance < pair.distance)\n            pair.update(point1, point2, distance);\n        }\n      }\n    }\n    return pair;\n  }\n  \n  public static void sortByX(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.x < point2.x)\n            return -1;\n          if (point1.x > point2.x)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static void sortByY(List<? extends Point> points)\n  {\n    Collections.sort(points, new Comparator<Point>() {\n        public int compare(Point point1, Point point2)\n        {\n          if (point1.y < point2.y)\n            return -1;\n          if (point1.y > point2.y)\n            return 1;\n          return 0;\n        }\n      }\n    );\n  }\n  \n  public static Pair divideAndConquer(List<? extends Point> points)\n  {\n    List<Point> pointsSortedByX = new ArrayList<Point>(points);\n    sortByX(pointsSortedByX);\n    List<Point> pointsSortedByY = new ArrayList<Point>(points);\n    sortByY(pointsSortedByY);\n    return divideAndConquer(pointsSortedByX, pointsSortedByY);\n  }\n  \n  private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)\n  {\n    int numPoints = pointsSortedByX.size();\n    if (numPoints <= 3)\n      return bruteForce(pointsSortedByX);\n    \n    int dividingIndex = numPoints >>> 1;\n    List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n    List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n    \n    List<Point> tempList = new ArrayList<Point>(leftOfCenter);\n    sortByY(tempList);\n    Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n    \n    tempList.clear();\n    tempList.addAll(rightOfCenter);\n    sortByY(tempList);\n    Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n    \n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight;\n    \n    tempList.clear();\n    double shortestDistance =closestPair.distance;\n    double centerX = rightOfCenter.get(0).x;\n    for (Point point : pointsSortedByY)\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList.add(point);\n    \n    for (int i = 0; i < tempList.size() - 1; i++)\n    {\n      Point point1 = tempList.get(i);\n      for (int j = i + 1; j < tempList.size(); j++)\n      {\n        Point point2 = tempList.get(j);\n        if ((point2.y - point1.y) >= shortestDistance)\n          break;\n        double distance = distance(point1, point2);\n        if (distance < closestPair.distance)\n        {\n          closestPair.update(point1, point2, distance);\n          shortestDistance = distance;\n        }\n      }\n    }\n    return closestPair;\n  }\n  \n  public static void main(String[] args)\n  {\n    int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n    List<Point> points = new ArrayList<Point>();\n    Random r = new Random();\n    for (int i = 0; i < numPoints; i++)\n      points.add(new Point(r.nextDouble(), r.nextDouble()));\n    System.out.println(\"Generated \" + numPoints + \" random points\");\n    long startTime = System.currentTimeMillis();\n    Pair bruteForceClosestPair = bruteForce(points);\n    long elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n    startTime = System.currentTimeMillis();\n    Pair dqClosestPair = divideAndConquer(points);\n    elapsedTime = System.currentTimeMillis() - startTime;\n    System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      System.out.println(\"MISMATCH\");\n  }\n}\n"}
{"id": 60362, "name": "Inheritance_Single", "VB": "Class Animal\n  \nEnd Class\n\nClass Dog\n  Inherits Animal\n  \nEnd Class\n\nClass Lab\n  Inherits Dog\n  \nEnd Class\n\nClass Collie\n  Inherits Dog\n  \nEnd Class\n\nClass Cat\n  Inherits Animal\n  \nEnd Class\n", "Java": "public class Animal{\n   \n}\n"}
{"id": 60363, "name": "Associative array_Creation", "VB": "Option Explicit\nSub Test()\n    Dim h As Object\n    Set h = CreateObject(\"Scripting.Dictionary\")\n    h.Add \"A\", 1\n    h.Add \"B\", 2\n    h.Add \"C\", 3\n    Debug.Print h.Item(\"A\")\n    h.Item(\"C\") = 4\n    h.Key(\"C\") = \"D\"\n    Debug.Print h.exists(\"C\")\n    h.Remove \"B\"\n    Debug.Print h.Count\n    h.RemoveAll\n    Debug.Print h.Count\nEnd Sub\n", "Java": "Map<String, Int> map = new HashMap();\nmap[\"foo\"] = 5;      \nmap[\"bar\"] = 10;\nmap[\"baz\"] = 15;\nmap[\"foo\"] = 6;      \n"}
{"id": 60364, "name": "Color wheel", "VB": "Option explicit\n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  \n  private filename   \n  private Palette,szpal \n  \n  public property get xmin():xmin=xmini:end property  \n  public property get ymin():ymin=ymini:end property  \n  public property get xmax():xmax=xmaxi:end property  \n  public property get ymax():ymax=ymaxi:end property  \n  public property let depth(x)\n  if x<>8 and x<>32 then err.raise 9\n  Imgdepth=x\n  end property     \n  \n  public sub set0 (x0,y0) \n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1    \n  end sub\n  \n  \n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  \n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  loc=getlocale\n  \n  set0 0,0   \n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1 : diry=1   \n    Case 2: dirx=-1 : diry=1\n    Case 3: dirx=-1 : diry=-1\n    Case 4: dirx=1 : diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    \n    \n\n, not relevant\n   End if  \n  End Sub\n\n  \n  \n  \n  Private Sub Class_Terminate\n    \n    if err<>0 then wscript.echo \"Error \" & err.number\n    wscript.echo \"copying image to bmp file\"\n    savebmp\n    wscript.echo \"opening \" & filename & \" with your default bmp viewer\"\n    CreateObject(\"Shell.Application\").ShellExecute filename\n    wscript.echo timer-tt & \"  iseconds\"\n  End Sub\n  \n    function long2wstr( x)  \n      dim k1,k2,x1\n      k1=  (x and &hffff&)\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n   Public Sub SaveBMP\n    \n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  \n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") \n      .Charset = \"UTF-16LE\"    \n      .Type =  2\n      .open \n      \n      \n      \n      \n      .writetext ChrW(&h4d42)                           \n      .writetext long2wstr(hdrs+palsize+bms)            \n      .writetext long2wstr(0)                           \n      .writetext long2wstr (hdrs+palsize)               \n       \n      .writetext long2wstr(40)                          \n      .writetext long2wstr(Imgl)                        \n      .writetext long2wstr(imgh)                        \n      .writetext int2wstr(1)                            \n      .writetext int2wstr(imgdepth)                     \n      .writetext long2wstr(&H0)                         \n       \n      .writetext long2wstr(bms)                         \n      .writetext long2wstr(&Hc4e)                       \n      .writetext long2wstr(&hc43)                       \n      .writetext long2wstr(szpal)                       \n      .writetext long2wstr(&H0)                         \n     \n      \n      \n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        \n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  \n        Next\n        \n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          \n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported : \" & ImgDepth & \" bits\"\n      End Select\n\n      \n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 \n      outf.Open\n      .position=2              \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   \n      outf.close\n    end with\n  End Sub\nend class\n\n\n\nfunction hsv2rgb( Hue, Sat, Value) \n  dim Angle, Radius,Ur,Vr,Wr,Rdim\n  dim r,g,b, rgb\n  Angle = (Hue-150) *0.01745329251994329576923690768489\n  Ur = Value * 2.55\n  Radius = Ur * tan(Sat *0.01183199)\n  Vr = Radius * cos(Angle) *0.70710678  \n  Wr = Radius * sin(Angle) *0.40824829  \n  r = (Ur - Vr - Wr)  \n  g = (Ur + Vr - Wr) \n  b = (Ur + Wr + Wr) \n  \n  \n if r >255 then \n   Rdim = (Ur - 255) / (Vr + Wr)\n   r = 255\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n elseif r < 0 then\n   Rdim = Ur / (Vr + Wr)\n   r = 0\n   g = Ur + (Vr - Wr) * Rdim\n   b = Ur + 2 * Wr * Rdim \n end if \n\n if g >255 then \n   Rdim = (255 - Ur) / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 255\n   b = Ur + 2 * Wr * Rdim\n elseif g<0 then   \n   Rdim = -Ur / (Vr - Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = 0\n   b = Ur + 2 * Wr * Rdim   \n end if \n if b>255 then\n   Rdim = (255 - Ur) / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 255\n elseif b<0 then\n   Rdim = -Ur / (Wr + Wr)\n   r = Ur - (Vr + Wr) * Rdim\n   g = Ur + (Vr - Wr) * Rdim\n   b = 0\n end If\n \n hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)\nend function\n\nfunction ang(col,row)\n    \n    if col =0 then  \n      if row<0 then ang=90 else ang=270 end if\n    else  \n   if col>0 then\n      ang=atn(-row/col)*57.2957795130\n   else\n     ang=(atn(row/-col)*57.2957795130)+180\n  end if\n  end if\n   ang=(ang+360) mod 360  \nend function \n\n\nDim X,row,col,fn,tt,hr,sat,row2\nconst h=160\nconst w=160\nconst rad=159\nconst r2=25500\ntt=timer\nfn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\testwchr.bmp\"\nSet X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)\n\nx.set0 w,h\n\n\nfor row=x.xmin+1 to x.xmax\n   row2=row*row\n   hr=int(Sqr(r2-row2))\n   For col=hr To 159\n     Dim a:a=((col\\16 +row\\16) And 1)* &hffffff\n     x.imgArray(col+160,row+160)=a \n     x.imgArray(-col+160,row+160)=a \n   next    \n   for col=-hr to hr\n     sat=100-sqr(row2+col*col)/rad *50\n    \n     x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)\n    next\n    \n  next  \nSet X = Nothing\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class ColorWheel {\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(new Runnable() {\n            public void run() {\n                ColorWheelFrame frame = new ColorWheelFrame();\n                frame.setVisible(true);\n            }\n        });\n    }\n\n    private static class ColorWheelFrame extends JFrame {\n        private ColorWheelFrame() {\n            super(\"Color Wheel\");\n            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            getContentPane().add(new ColorWheelPanel());\n            pack();\n        }\n    }\n\n    private static class ColorWheelPanel extends JComponent {\n        private ColorWheelPanel() {\n            setPreferredSize(new Dimension(400, 400));\n        }\n        public void paint(Graphics g) {\n            Graphics2D g2 = (Graphics2D)g;\n            int w = getWidth();\n            int h = getHeight();\n            int margin = 10;\n            int radius = (Math.min(w, h) - 2 * margin)/2;\n            int cx = w/2;\n            int cy = h/2;\n            float[] dist = {0.F, 1.0F};\n            g2.setColor(Color.BLACK);\n            g2.fillRect(0, 0, w, h);\n            for (int angle = 0; angle < 360; ++angle) {\n                Color color = hsvToRgb(angle, 1.0, 1.0);\n                Color[] colors = {Color.WHITE, color};\n                RadialGradientPaint paint = new RadialGradientPaint(cx, cy,\n                        radius, dist, colors);\n                g2.setPaint(paint);\n                g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,\n                        angle, 1);\n            }\n        }\n    }\n\n    private static Color hsvToRgb(int h, double s, double v) {\n        double hp = h/60.0;\n        double c = s * v;\n        double x = c * (1 - Math.abs(hp % 2.0 - 1));\n        double m = v - c;\n        double r = 0, g = 0, b = 0;\n        if (hp <= 1) {\n            r = c;\n            g = x;\n        } else if (hp <= 2) {\n            r = x;\n            g = c;\n        } else if (hp <= 3) {\n            g = c;\n            b = x;\n        } else if (hp <= 4) {\n            g = x;\n            b = c;\n        } else if (hp <= 5) {\n            r = x;\n            b = c;\n        } else {\n            r = c;\n            b = x;\n        }\n        r += m;\n        g += m;\n        b += m;\n        return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));\n    }\n}\n"}
{"id": 60365, "name": "Square root by hand", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n"}
{"id": 60366, "name": "Square root by hand", "VB": "Imports System.Math, System.Console, BI = System.Numerics.BigInteger\n\nModule Module1\n\n    Sub Main(ByVal args As String())\n        Dim i, j, k, d As BI : i = 2\n        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j\n        Dim n As Integer = -1, n0 As Integer = -1,\n            st As DateTime = DateTime.Now\n        If args.Length > 0 Then Integer.TryParse(args(0), n)\n        If n > 0 Then n0 = n Else n = 1\n        Do\n            Write(d) : i = (i - k * d) * 100 : k = 20 * j\n            For d = 1 To 10\n                If (k + d) * d > i Then d -= 1 : Exit For\n            Next\n            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1\n        Loop While n > 0\n        If n0 > 0 Then WriteLine (VbLf & \"Time taken for {0} digits: {1}\", n0, DateTime.Now - st)\n    End Sub\nEnd Module\n", "Java": "import java.math.BigInteger;\n\npublic class SquareRoot {\n    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);\n    public static final BigInteger TWENTY = BigInteger.valueOf(20);\n\n    public static void main(String[] args) {\n        var i = BigInteger.TWO;\n        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));\n        var k = j;\n        var d = j;\n        int n = 500;\n        int n0 = n;\n        do {\n            System.out.print(d);\n            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);\n            k = TWENTY.multiply(j);\n            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {\n                if (k.add(d).multiply(d).compareTo(i) > 0) {\n                    d = d.subtract(BigInteger.ONE);\n                    break;\n                }\n            }\n            j = j.multiply(BigInteger.TEN).add(d);\n            k = k.add(d);\n            if (n0 > 0) {\n                n--;\n            }\n        } while (n > 0);\n        System.out.println();\n    }\n}\n"}
{"id": 60367, "name": "Reflection_List properties", "VB": "Imports System.Reflection\n\nModule Module1\n\n    Class TestClass\n        Private privateField = 7\n        Public ReadOnly Property PublicNumber = 4\n        Private ReadOnly Property PrivateNumber = 2\n    End Class\n\n    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return From p In obj.GetType().GetProperties(flags)\n               Where p.GetIndexParameters().Length = 0\n               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}\n    End Function\n\n    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable\n        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})\n    End Function\n\n    Sub Main()\n        Dim t As New TestClass()\n        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance\n        For Each prop In GetPropertyValues(t, flags)\n            Console.WriteLine(prop)\n        Next\n        For Each field In GetFieldValues(t, flags)\n            Console.WriteLine(field)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.lang.reflect.Field;\n\npublic class ListFields {\n    public int examplePublicField = 42;\n    private boolean examplePrivateField = true;\n    \n    public static void main(String[] args) throws IllegalAccessException {\n        ListFields obj = new ListFields();\n        Class clazz = obj.getClass();\n\n        System.out.println(\"All public fields (including inherited):\");\n        for (Field f : clazz.getFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n        System.out.println();\n        System.out.println(\"All declared fields (excluding inherited):\");\n        for (Field f : clazz.getDeclaredFields()) {\n            System.out.printf(\"%s\\t%s\\n\", f, f.get(obj));\n        }\n    }\n}\n"}
{"id": 60368, "name": "Align columns", "VB": "Dim MText as QMemorystream\n    MText.WriteLine \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n    MText.WriteLine \"are$delineated$by$a$single$\n    MText.WriteLine \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n    MText.WriteLine \"column$are$separated$by$at$least$one$space.\"\n    MText.WriteLine \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n    MText.WriteLine \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nDefStr TextLeft, TextRight, TextCenter\nDefStr MLine, LWord, Newline = chr$(13)+chr$(10)\nDefInt ColWidth(100), ColCount\nDefSng NrSpaces \n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))\n    next\nnext\n\n\nMText.position = 0\nfor x = 0 to MText.linecount -1\n    MLine = MText.ReadLine\n    for y = 0 to Tally(MLine, \"$\")\n        LWord = Field$(MLine, \"$\", y+1)\n        NrSpaces = ColWidth(y) - len(LWord)\n        \n        TextLeft = TextLeft + LWord + Space$(NrSpaces+1)\n        \n        TextRight = TextRight + Space$(NrSpaces+1) + LWord\n        \n        TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))\n    next\n    TextLeft = TextLeft + Newline \n    TextRight = TextRight + Newline \n    TextCenter = TextCenter + Newline \nnext\n", "Java": "import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\npublic class ColumnAligner {\n    private List<String[]> words = new ArrayList<>();\n    private int columns = 0;\n    private List<Integer> columnWidths = new ArrayList<>();\n\n    \n    public ColumnAligner(String s) {\n        String[] lines = s.split(\"\\\\n\");\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    \n    public ColumnAligner(List<String> lines) {\n        for (String line : lines) {\n            processInputLine(line);\n        }\n    }\n\n    private void processInputLine(String line) {\n        String[] lineWords = line.split(\"\\\\$\");\n        words.add(lineWords);\n        columns = Math.max(columns, lineWords.length);\n        for (int i = 0; i < lineWords.length; i++) {\n            String word = lineWords[i];\n            if (i >= columnWidths.size()) {\n                columnWidths.add(word.length());\n            } else {\n                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n            }\n        }\n    }\n\n    interface AlignFunction {\n        String align(String s, int length);\n    }\n\n    \n    public String alignLeft() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.rightPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignRight() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.leftPad(s, length);\n            }\n        });\n    }\n\n    \n    public String alignCenter() {\n        return align(new AlignFunction() {\n            @Override\n            public String align(String s, int length) {\n                return StringUtils.center(s, length);\n            }\n        });\n    }\n\n    private String align(AlignFunction a) {\n        StringBuilder result = new StringBuilder();\n        for (String[] lineWords : words) {\n            for (int i = 0; i < lineWords.length; i++) {\n                String word = lineWords[i];\n                if (i == 0) {\n                    result.append(\"|\");\n                }\n                result.append(a.align(word, columnWidths.get(i)) + \"|\");\n            }\n            result.append(\"\\n\");\n        }\n        return result.toString();\n    }\n\n    public static void main(String args[]) throws IOException {\n        if (args.length < 1) {\n            System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n            return;\n        }\n        String filePath = args[0];\n        String alignment = \"left\";\n        if (args.length >= 2) {\n            alignment = args[1];\n        }\n        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n        switch (alignment) {\n        case \"left\":\n            System.out.print(ca.alignLeft());\n            break;\n        case \"right\":\n            System.out.print(ca.alignRight());\n            break;\n        case \"center\":\n            System.out.print(ca.alignCenter());\n            break;\n        default:\n            System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n            break;\n        }\n    }\n}\n"}
{"id": 60369, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 60370, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 60371, "name": "URL parser", "VB": "Function parse_url(url)\n\tparse_url = \"URL: \" & url\n\tIf InStr(url,\"//\") Then\n\t\t\n\t\tscheme = Split(url,\"//\")\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & Mid(scheme(0),1,Len(scheme(0))-1)\n\t\t\n\t\tdomain = Split(scheme(1),\"/\")\n\t\t\n\t\tIf InStr(domain(0),\"@\") Then\n\t\t\tcred = Split(domain(0),\"@\")\n\t\t\tIf InStr(cred(0),\".\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\".\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\".\")+1,Len(cred(0))-InStr(1,cred(0),\".\"))\n\t\t\tElseIf InStr(cred(0),\":\") Then\n\t\t\t\tusername = Mid(cred(0),1,InStr(1,cred(0),\":\")-1)\n\t\t\t\tpassword = Mid(cred(0),InStr(1,cred(0),\":\")+1,Len(cred(0))-InStr(1,cred(0),\":\"))\n\t\t\tEnd If\n\t\t\tparse_url = parse_url & vbcrlf & \"Username: \" & username & vbCrLf &_\n\t\t\t\t\"Password: \" & password\n\t\t\t\n\t\t\tIf InStr(cred(1),\":\") Then\n\t\t\t\thost = Mid(cred(1),1,InStr(1,cred(1),\":\")-1)\n\t\t\t\tport = Mid(cred(1),InStr(1,cred(1),\":\")+1,Len(cred(1))-InStr(1,cred(1),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\t\tElse\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & cred(1)\n\t\t\tEnd If\n\t\tElseIf InStr(domain(0),\":\") And Instr(domain(0),\"[\") = False And Instr(domain(0),\"]\") = False Then\n\t\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\":\")-1)\n\t\t\t\tport = Mid(domain(0),InStr(1,domain(0),\":\")+1,Len(domain(0))-InStr(1,domain(0),\":\"))\n\t\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElseIf Instr(domain(0),\"[\") And Instr(domain(0),\"]:\") Then\n\t\t\thost = Mid(domain(0),1,InStr(1,domain(0),\"]\"))\n\t\t\tport = Mid(domain(0),InStr(1,domain(0),\"]\")+2,Len(domain(0))-(InStr(1,domain(0),\"]\")+1))\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & host & vbCrLf & \"Port: \" & port \n\t\tElse\n\t\t\tparse_url = parse_url & vbCrLf & \"Domain: \" & domain(0)\n\t\tEnd If\n\t\t\n\t\tIf UBound(domain) > 0 Then\n\t\t\tFor i = 1 To UBound(domain)\n\t\t\t\tIf i < UBound(domain) Then\n\t\t\t\t\tpath = path & domain(i) & \"/\"\n\t\t\t\tElseIf InStr(domain(i),\"?\") Then\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\tIf InStr(domain(i),\"#\") Then\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,InStr(1,domain(i),\"#\")-InStr(1,domain(i),\"?\")-1)\n\t\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query & vbCrLf & \"Fragment: \" & fragment\n\t\t\t\t\tElse\n\t\t\t\t\t\tquery = Mid(domain(i),InStr(1,domain(i),\"?\")+1,Len(domain(i))-InStr(1,domain(i),\"?\"))\n\t\t\t\t\t\tpath = path & vbcrlf & \"Query: \" & query\n\t\t\t\t\tEnd If\n\t\t\t\tElseIf InStr(domain(i),\"#\") Then\n\t\t\t\t\tfragment = Mid(domain(i),InStr(1,domain(i),\"#\")+1,Len(domain(i))-InStr(1,domain(i),\"#\"))\n\t\t\t\t\tpath = path & Mid(domain(i),1,InStr(1,domain(i),\"#\")-1) & vbCrLf &_\n\t\t\t\t\t\t \"Fragment: \" & fragment\n\t\t\t\tElse\n\t\t\t\t\tpath = path & domain(i)\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tparse_url = parse_url & vbCrLf & \"Path: \" & path \n\t\tEnd If\n\tElseIf InStr(url,\":\") Then\n\t\tscheme = Mid(url,1,InStr(1,url,\":\")-1)\n\t\tpath = Mid(url,InStr(1,url,\":\")+1,Len(url)-InStr(1,url,\":\"))\n\t\tparse_url = parse_url & vbcrlf & \"Scheme: \" & scheme & vbCrLf & \"Path: \" & path\n\tElse\n\t\tparse_url = parse_url & vbcrlf & \"Invalid!!!\"\n\tEnd If\n\nEnd Function\n\n\nWScript.StdOut.WriteLine parse_url(\"foo://example.com:8042/over/there?name=ferret#nose\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ftp://ftp.is.co.za/rfc/rfc1808.txt\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"http://www.ietf.org/rfc/rfc2396.txt#header1\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"mailto:John.Doe@example.com\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"news:comp.infosystems.www.servers.unix\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"tel:+1-816-555-1212\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"telnet://192.0.2.16:80/\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\")\nWScript.StdOut.WriteLine \"-------------------------------\"\nWScript.StdOut.WriteLine parse_url(\"this code is messy, long, and needs a makeover!!!\")\n", "Java": "import java.net.URI;\nimport java.net.URISyntaxException;\npublic class WebAddressParser{\n    public static void main(String[] args){\n        parseAddress(\"foo:\n        parseAddress(\"urn:example:animal:ferret:nose\");\n    }\n\n    static void parseAddress(String a){\n        System.out.println(\"Parsing \" + a);\n        try{\n\n            \n            URI u = new URI(a);\n\n            System.out.println(\"\\tscheme = \" + u.getScheme());\n            System.out.println(\"\\tdomain = \" + u.getHost());\n            System.out.println(\"\\tport = \" + (-1==u.getPort()?\"default\":u.getPort()));\n            System.out.println(\"\\tpath = \" + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));\n            System.out.println(\"\\tquery = \" + u.getQuery());\n            System.out.println(\"\\tfragment = \" + u.getFragment());\n        }\n        catch (URISyntaxException x){\n            System.err.println(\"Oops: \" + x);\n        }\n    }\n}\n"}
{"id": 60372, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 60373, "name": "Base58Check encoding", "VB": "Imports System.Numerics\nImports System.Text\n\nModule Module1\n    ReadOnly ALPHABET As String = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n    ReadOnly HEX As String = \"0123456789ABCDEF\"\n\n    Function ToBigInteger(value As String, base As Integer) As BigInteger\n        If base < 1 OrElse base > HEX.Length Then\n            Throw New ArgumentException(\"Base is out of range.\")\n        End If\n\n        Dim bi = BigInteger.Zero\n        For Each c In value\n            Dim c2 = Char.ToUpper(c)\n            Dim idx = HEX.IndexOf(c2)\n            If idx = -1 OrElse idx >= base Then\n                Throw New ArgumentException(\"Illegal character encountered.\")\n            End If\n            bi = bi * base + idx\n        Next\n\n        Return bi\n    End Function\n\n    Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String\n        Dim x As BigInteger\n        If base = 16 AndAlso hash.Substring(0, 2) = \"0x\" Then\n            x = ToBigInteger(hash.Substring(2), base)\n        Else\n            x = ToBigInteger(hash, base)\n        End If\n\n        Dim sb As New StringBuilder\n        While x > 0\n            Dim r = x Mod 58\n            sb.Append(ALPHABET(r))\n            x = x / 58\n        End While\n\n        Dim ca = sb.ToString().ToCharArray()\n        Array.Reverse(ca)\n        Return New String(ca)\n    End Function\n\n    Sub Main()\n        Dim s = \"25420294593250030202636073700053352635053786165627414518\"\n        Dim b = ConvertToBase58(s, 10)\n        Console.WriteLine(\"{0} -> {1}\", s, b)\n\n        Dim hashes = {\"0x61\", \"0x626262\", \"0x636363\", \"0x73696d706c792061206c6f6e6720737472696e67\", \"0x516b6fcd0f\", \"0xbf4f89001e670274dd\", \"0x572e4794\", \"0xecac89cad93923c02321\", \"0x10c8511e\"}\n        For Each hash In hashes\n            Dim b58 = ConvertToBase58(hash)\n            Console.WriteLine(\"{0,-56} -> {1}\", hash, b58)\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Base58CheckEncoding {\n    private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n    private static final BigInteger BIG0 = BigInteger.ZERO;\n    private static final BigInteger BIG58 = BigInteger.valueOf(58);\n\n    private static String convertToBase58(String hash) {\n        return convertToBase58(hash, 16);\n    }\n\n    private static String convertToBase58(String hash, int base) {\n        BigInteger x;\n        if (base == 16 && hash.substring(0, 2).equals(\"0x\")) {\n            x = new BigInteger(hash.substring(2), 16);\n        } else {\n            x = new BigInteger(hash, base);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (x.compareTo(BIG0) > 0) {\n            int r = x.mod(BIG58).intValue();\n            sb.append(ALPHABET.charAt(r));\n            x = x.divide(BIG58);\n        }\n\n        return sb.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        String s = \"25420294593250030202636073700053352635053786165627414518\";\n        String b = convertToBase58(s, 10);\n        System.out.printf(\"%s -> %s\\n\", s, b);\n\n        List<String> hashes = List.of(\n            \"0x61\",\n            \"0x626262\",\n            \"0x636363\",\n            \"0x73696d706c792061206c6f6e6720737472696e67\",\n            \"0x516b6fcd0f\",\n            \"0xbf4f89001e670274dd\",\n            \"0x572e4794\",\n            \"0xecac89cad93923c02321\",\n            \"0x10c8511e\"\n        );\n        for (String hash : hashes) {\n            String b58 = convertToBase58(hash);\n            System.out.printf(\"%-56s -> %s\\n\", hash, b58);\n        }\n    }\n}\n"}
{"id": 60374, "name": "Data Encryption Standard", "VB": "Imports System.IO\nImports System.Security.Cryptography\n\nModule Module1\n\n    \n    Function ByteArrayToString(ba As Byte()) As String\n        Return BitConverter.ToString(ba).Replace(\"-\", \"\")\n    End Function\n\n    \n    \n    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateEncryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(messageBytes, 0, messageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim encryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n\n        Return encryptedMessageBytes\n    End Function\n\n    \n    \n    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()\n        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}\n\n        \n        Dim provider As New DESCryptoServiceProvider\n        Dim transform = provider.CreateDecryptor(passwordBytes, iv)\n        Dim mode = CryptoStreamMode.Write\n\n        \n        Dim memStream As New MemoryStream\n        Dim cryptoStream As New CryptoStream(memStream, transform, mode)\n        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)\n        cryptoStream.FlushFinalBlock()\n\n        \n        Dim decryptedMessageBytes(memStream.Length - 1) As Byte\n        memStream.Position = 0\n        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)\n\n        Return decryptedMessageBytes\n    End Function\n\n    Sub Main()\n        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}\n        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}\n\n        Dim encStr = Encrypt(plainBytes, keyBytes)\n        Console.WriteLine(\"Encoded: {0}\", ByteArrayToString(encStr))\n\n        Dim decStr = Decrypt(encStr, keyBytes)\n        Console.WriteLine(\"Decoded: {0}\", ByteArrayToString(decStr))\n    End Sub\n\nEnd Module\n", "Java": "import javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class DataEncryptionStandard {\n    private static byte[] toHexByteArray(String self) {\n        byte[] bytes = new byte[self.length() / 2];\n        for (int i = 0; i < bytes.length; ++i) {\n            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));\n        }\n        return bytes;\n    }\n\n    private static void printHexBytes(byte[] self, String label) {\n        System.out.printf(\"%s: \", label);\n        for (byte b : self) {\n            int bb = (b >= 0) ? ((int) b) : b + 256;\n            String ts = Integer.toString(bb, 16);\n            if (ts.length() < 2) {\n                ts = \"0\" + ts;\n            }\n            System.out.print(ts);\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String strKey = \"0e329232ea6d0d73\";\n        byte[] keyBytes = toHexByteArray(strKey);\n        SecretKeySpec key = new SecretKeySpec(keyBytes, \"DES\");\n        Cipher encCipher = Cipher.getInstance(\"DES\");\n        encCipher.init(Cipher.ENCRYPT_MODE, key);\n        String strPlain = \"8787878787878787\";\n        byte[] plainBytes = toHexByteArray(strPlain);\n        byte[] encBytes = encCipher.doFinal(plainBytes);\n        printHexBytes(encBytes, \"Encoded\");\n\n        Cipher decCipher = Cipher.getInstance(\"DES\");\n        decCipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] decBytes = decCipher.doFinal(encBytes);\n        printHexBytes(decBytes, \"Decoded\");\n    }\n}\n"}
{"id": 60375, "name": "Commatizing numbers", "VB": "Public Sub commatize(s As String, Optional sep As String = \",\", Optional start As Integer = 1, Optional step As Integer = 3)\n    Dim l As Integer: l = Len(s)\n        For i = start To l\n            If Asc(Mid(s, i, 1)) >= Asc(\"1\") And Asc(Mid(s, i, 1)) <= Asc(\"9\") Then\n                For j = i + 1 To l + 1\n                    If j > l Then\n                        For k = j - 1 - step To i Step -step\n                            s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                            l = Len(s)\n                        Next k\n                        Exit For\n                    Else\n                        If (Asc(Mid(s, j, 1)) < Asc(\"0\") Or Asc(Mid(s, j, 1)) > Asc(\"9\")) Then\n                            For k = j - 1 - step To i Step -step\n                                s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)\n                                l = Len(s)\n                            Next k\n                            Exit For\n                        End If\n                    End If\n                Next j\n                Exit For\n            End If\n        Next i\n        Debug.Print s\n    End Sub\nPublic Sub main()\n    commatize \"pi=3.14159265358979323846264338327950288419716939937510582097494459231\", \" \", 6, 5\n    commatize \"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\", \".\"\n    commatize \"\"\"-in Aus$+1411.8millions\"\"\"\n    commatize \"===US$0017440 millions=== (in 2000 dollars)\"\n    commatize \"123.e8000 is pretty big.\"\n    commatize \"The land area of the earth is 57268900(29% of the surface) square miles.\"\n    commatize \"Ain\n    commatize \"James was never known as 0000000007\"\n    commatize \"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\"\n    commatize \"   $-140000±100 millions.\"\n    commatize \"6/9/1946 was a good year for some.\"\nEnd Sub\n", "Java": "import java.io.File;\nimport java.util.*;\nimport java.util.regex.*;\n\npublic class CommatizingNumbers {\n\n    public static void main(String[] args) throws Exception {\n        commatize(\"pi=3.14159265358979323846264338327950288419716939937510582\"\n                + \"097494459231\", 6, 5, \" \");\n\n        commatize(\"The author has two Z$100000000000000 Zimbabwe notes (100 \"\n                + \"trillion).\", 0, 3, \".\");\n\n        try (Scanner sc = new Scanner(new File(\"input.txt\"))) {\n            while(sc.hasNext())\n                commatize(sc.nextLine());\n        }\n    }\n\n    static void commatize(String s) {\n        commatize(s, 0, 3, \",\");\n    }\n\n    static void commatize(String s, int start, int step, String ins) {\n        if (start < 0 || start > s.length() || step < 1 || step > s.length())\n            return;\n\n        Matcher m = Pattern.compile(\"([1-9][0-9]*)\").matcher(s.substring(start));\n        StringBuffer result = new StringBuffer(s.substring(0, start));\n\n        if (m.find()) {\n            StringBuilder sb = new StringBuilder(m.group(1)).reverse();\n            for (int i = step; i < sb.length(); i += step)\n                sb.insert(i++, ins);\n            m.appendReplacement(result, sb.reverse().toString());\n        }\n\n        System.out.println(m.appendTail(result));\n    }\n}\n"}
{"id": 60376, "name": "Arithmetic coding_As a generalized change of radix", "VB": "Imports System.Numerics\nImports System.Text\nImports Freq = System.Collections.Generic.Dictionary(Of Char, Long)\nImports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))\n\nModule Module1\n\n    Function CumulativeFreq(freq As Freq) As Freq\n        Dim total As Long = 0\n        Dim cf As New Freq\n        For i = 0 To 255\n            Dim c = Chr(i)\n            If freq.ContainsKey(c) Then\n                Dim v = freq(c)\n                cf(c) = total\n                total += v\n            End If\n        Next\n        Return cf\n    End Function\n\n    Function ArithmeticCoding(str As String, radix As Long) As Triple\n        \n        Dim freq As New Freq\n        For Each c In str\n            If freq.ContainsKey(c) Then\n                freq(c) += 1\n            Else\n                freq(c) = 1\n            End If\n        Next\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim base As BigInteger = str.Length\n\n        \n        Dim lower As BigInteger = 0\n\n        \n        Dim pf As BigInteger = 1\n\n        \n        \n        For Each c In str\n            Dim x = cf(c)\n            lower = lower * base + x * pf\n            pf = pf * freq(c)\n        Next\n\n        \n        Dim upper = lower + pf\n\n        Dim powr = 0\n        Dim bigRadix As BigInteger = radix\n\n        While True\n            pf = pf / bigRadix\n            If pf = 0 Then\n                Exit While\n            End If\n            powr = powr + 1\n        End While\n\n        Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))\n        Return New Triple(diff, powr, freq)\n    End Function\n\n    Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String\n        Dim powr As BigInteger = radix\n        Dim enc = num * BigInteger.Pow(powr, pwr)\n        Dim base = freq.Values.Sum()\n\n        \n        Dim cf = CumulativeFreq(freq)\n\n        \n        Dim dict As New Dictionary(Of Long, Char)\n        For Each key In cf.Keys\n            Dim value = cf(key)\n            dict(value) = key\n        Next\n\n        \n        Dim lchar As Long = -1\n        For i As Long = 0 To base - 1\n            If dict.ContainsKey(i) Then\n                lchar = AscW(dict(i))\n            Else\n                dict(i) = ChrW(lchar)\n            End If\n        Next\n\n        \n        Dim decoded As New StringBuilder\n        Dim bigBase As BigInteger = base\n        For i As Long = base - 1 To 0 Step -1\n            Dim pow = BigInteger.Pow(bigBase, i)\n            Dim div = enc / pow\n            Dim c = dict(div)\n            Dim fv = freq(c)\n            Dim cv = cf(c)\n            Dim diff = enc - pow * cv\n            enc = diff / fv\n            decoded.Append(c)\n        Next\n\n        \n        Return decoded.ToString()\n    End Function\n\n    Sub Main()\n        Dim radix As Long = 10\n        Dim strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"}\n        For Each St In strings\n            Dim encoded = ArithmeticCoding(St, radix)\n            Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)\n            Console.WriteLine(\"{0,-25}=> {1,19} * {2}^{3}\", St, encoded.Item1, radix, encoded.Item2)\n            If St <> dec Then\n                Throw New Exception(vbTab + \"However that is incorrect!\")\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class ArithmeticCoding {\n    private static class Triple<A, B, C> {\n        A a;\n        B b;\n        C c;\n\n        Triple(A a, B b, C c) {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n        }\n    }\n\n    private static class Freq extends HashMap<Character, Long> {\n        \n    }\n\n    private static Freq cumulativeFreq(Freq freq) {\n        long total = 0;\n        Freq cf = new Freq();\n        for (int i = 0; i < 256; ++i) {\n            char c = (char) i;\n            Long v = freq.get(c);\n            if (v != null) {\n                cf.put(c, total);\n                total += v;\n            }\n        }\n        return cf;\n    }\n\n    private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {\n        \n        char[] chars = str.toCharArray();\n\n        \n        Freq freq = new Freq();\n        for (char c : chars) {\n            if (!freq.containsKey(c))\n                freq.put(c, 1L);\n            else\n                freq.put(c, freq.get(c) + 1);\n        }\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        BigInteger base = BigInteger.valueOf(chars.length);\n\n        \n        BigInteger lower = BigInteger.ZERO;\n\n        \n        BigInteger pf = BigInteger.ONE;\n\n        \n        \n        for (char c : chars) {\n            BigInteger x = BigInteger.valueOf(cf.get(c));\n            lower = lower.multiply(base).add(x.multiply(pf));\n            pf = pf.multiply(BigInteger.valueOf(freq.get(c)));\n        }\n\n        \n        BigInteger upper = lower.add(pf);\n\n        int powr = 0;\n        BigInteger bigRadix = BigInteger.valueOf(radix);\n\n        while (true) {\n            pf = pf.divide(bigRadix);\n            if (pf.equals(BigInteger.ZERO)) break;\n            powr++;\n        }\n\n        BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));\n        return new Triple<>(diff, powr, freq);\n    }\n\n    private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {\n        BigInteger powr = BigInteger.valueOf(radix);\n        BigInteger enc = num.multiply(powr.pow(pwr));\n        long base = 0;\n        for (Long v : freq.values()) base += v;\n\n        \n        Freq cf = cumulativeFreq(freq);\n\n        \n        Map<Long, Character> dict = new HashMap<>();\n        for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());\n\n        \n        long lchar = -1;\n        for (long i = 0; i < base; ++i) {\n            Character v = dict.get(i);\n            if (v != null) {\n                lchar = v;\n            } else if (lchar != -1) {\n                dict.put(i, (char) lchar);\n            }\n        }\n\n        \n        StringBuilder decoded = new StringBuilder((int) base);\n        BigInteger bigBase = BigInteger.valueOf(base);\n        for (long i = base - 1; i >= 0; --i) {\n            BigInteger pow = bigBase.pow((int) i);\n            BigInteger div = enc.divide(pow);\n            Character c = dict.get(div.longValue());\n            BigInteger fv = BigInteger.valueOf(freq.get(c));\n            BigInteger cv = BigInteger.valueOf(cf.get(c));\n            BigInteger diff = enc.subtract(pow.multiply(cv));\n            enc = diff.divide(fv);\n            decoded.append(c);\n        }\n        \n        return decoded.toString();\n    }\n\n    public static void main(String[] args) {\n        long radix = 10;\n        String[] strings = {\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"};\n        String fmt = \"%-25s=> %19s * %d^%s\\n\";\n        for (String str : strings) {\n            Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);\n            String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);\n            System.out.printf(fmt, str, encoded.a, radix, encoded.b);\n            if (!Objects.equals(str, dec)) throw new RuntimeException(\"\\tHowever that is incorrect!\");\n        }\n    }\n}\n"}
{"id": 60377, "name": "Kosaraju", "VB": "Module Module1\n\n    Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)\n        Dim size = g.Count\n        Dim vis(size - 1) As Boolean\n        Dim l(size - 1) As Integer\n        Dim x = size\n\n        Dim t As New List(Of List(Of Integer))\n        For i = 1 To size\n            t.Add(New List(Of Integer))\n        Next\n\n        Dim visit As Action(Of Integer) = Sub(u As Integer)\n                                              If Not vis(u) Then\n                                                  vis(u) = True\n                                                  For Each v In g(u)\n                                                      visit(v)\n                                                      t(v).Add(u)\n                                                  Next\n                                                  x -= 1\n                                                  l(x) = u\n                                              End If\n                                          End Sub\n\n        For i = 1 To size\n            visit(i - 1)\n        Next\n        Dim c(size - 1) As Integer\n\n        Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)\n                                                        If vis(u) Then\n                                                            vis(u) = False\n                                                            c(u) = root\n                                                            For Each v In t(u)\n                                                                assign(v, root)\n                                                            Next\n                                                        End If\n                                                    End Sub\n\n        For Each u In l\n            assign(u, u)\n        Next\n\n        Return c.ToList\n    End Function\n\n    Sub Main()\n        Dim g = New List(Of List(Of Integer)) From {\n            New List(Of Integer) From {1},\n            New List(Of Integer) From {2},\n            New List(Of Integer) From {0},\n            New List(Of Integer) From {1, 2, 4},\n            New List(Of Integer) From {3, 5},\n            New List(Of Integer) From {2, 6},\n            New List(Of Integer) From {5},\n            New List(Of Integer) From {4, 6, 7}\n        }\n\n        Dim output = Kosaraju(g)\n        Console.WriteLine(\"[{0}]\", String.Join(\", \", output))\n    End Sub\n\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.BiConsumer;\nimport java.util.function.IntConsumer;\nimport java.util.stream.Collectors;\n\npublic class Kosaraju {\n    static class Recursive<I> {\n        I func;\n    }\n\n    private static List<Integer> kosaraju(List<List<Integer>> g) {\n        \n        int size = g.size();\n        boolean[] vis = new boolean[size];\n        int[] l = new int[size];\n        AtomicInteger x = new AtomicInteger(size);\n\n        List<List<Integer>> t = new ArrayList<>();\n        for (int i = 0; i < size; ++i) {\n            t.add(new ArrayList<>());\n        }\n\n        Recursive<IntConsumer> visit = new Recursive<>();\n        visit.func = (int u) -> {\n            if (!vis[u]) {\n                vis[u] = true;\n                for (Integer v : g.get(u)) {\n                    visit.func.accept(v);\n                    t.get(v).add(u);\n                }\n                int xval = x.decrementAndGet();\n                l[xval] = u;\n            }\n        };\n\n        \n        for (int i = 0; i < size; ++i) {\n            visit.func.accept(i);\n        }\n        int[] c = new int[size];\n\n        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();\n        assign.func = (Integer u, Integer root) -> {\n            if (vis[u]) {  \n                vis[u] = false;\n                c[u] = root;\n                for (Integer v : t.get(u)) {\n                    assign.func.accept(v, root);\n                }\n            }\n        };\n\n        \n        for (int u : l) {\n            assign.func.accept(u, u);\n        }\n\n        return Arrays.stream(c).boxed().collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        List<List<Integer>> g = new ArrayList<>();\n        for (int i = 0; i < 8; ++i) {\n            g.add(new ArrayList<>());\n        }\n        g.get(0).add(1);\n        g.get(1).add(2);\n        g.get(2).add(0);\n        g.get(3).add(1);\n        g.get(3).add(2);\n        g.get(3).add(4);\n        g.get(4).add(3);\n        g.get(4).add(5);\n        g.get(5).add(2);\n        g.get(5).add(6);\n        g.get(6).add(5);\n        g.get(7).add(4);\n        g.get(7).add(6);\n        g.get(7).add(7);\n\n        List<Integer> output = kosaraju(g);\n        System.out.println(output);\n    }\n}\n"}
{"id": 60378, "name": "Pentomino tiling", "VB": "Module Module1\n\n    Dim symbols As Char() = \"XYPFTVNLUZWI█\".ToCharArray(),\n        nRows As Integer = 8, nCols As Integer = 8,\n        target As Integer = 12, blank As Integer = 12,\n        grid As Integer()() = New Integer(nRows - 1)() {},\n        placed As Boolean() = New Boolean(target - 1) {},\n        pens As List(Of List(Of Integer())), rand As Random,\n        seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}\n\n    Sub Main()\n        Unpack(seeds) : rand = New Random() : ShuffleShapes(2)\n        For r As Integer = 0 To nRows - 1\n            grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next\n        For i As Integer = 0 To 3\n            Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)\n            Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank\n        Next\n        If Solve(0, 0) Then\n            PrintResult()\n        Else\n            Console.WriteLine(\"no solution for this configuration:\") : PrintResult()\n        End If\n        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n    End Sub\n\n    Sub ShuffleShapes(count As Integer) \n        For i As Integer = 0 To count : For j = 0 To pens.Count - 1\n                Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j\n                Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp\n                Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch\n            Next : Next\n    End Sub\n\n    Sub PrintResult() \n        For Each r As Integer() In grid : For Each i As Integer In r\n                Console.Write(\"{0} \", If(i < 0, \".\", symbols(i)))\n            Next : Console.WriteLine() : Next\n    End Sub\n\n    \n    Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean\n        If numPlaced = target Then Return True\n        Dim row As Integer = pos \\ nCols, col As Integer = pos Mod nCols\n        If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)\n        For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then\n                For Each orientation As Integer() In pens(i)\n                    If Not TPO(orientation, row, col, i) Then Continue For\n                    placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True\n                    RmvO(orientation, row, col) : placed(i) = False\n                Next : End If : Next : Return False\n    End Function\n\n    \n    Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)\n        grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = -1 : Next\n    End Sub\n\n    \n    Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,\n                 ByVal sIdx As Integer) As Boolean\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)\n            If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse\n                grid(y)(x) <> -1 Then Return False\n        Next : grid(row)(col) = sIdx\n        For i As Integer = 0 To ori.Length - 1 Step 2\n            grid(row + ori(i))(col + ori(i + 1)) = sIdx\n        Next : Return True\n    End Function\n\n    \n    \n    \n    \n\n    Sub Unpack(sv As Integer()) \n        pens = New List(Of List(Of Integer())) : For Each item In sv\n            Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),\n                fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7\n                If i = 4 Then Mir(exi) Else Rot(exi)\n                fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))\n            Next : pens.Add(Gen) : Next\n    End Sub\n\n    \n    Function Expand(i As Integer) As List(Of Integer)\n        Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next\n    End Function\n\n    \n    Function ToP(p As List(Of Integer)) As Integer()\n        Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)\n            tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next\n        tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next\n        Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)\n            Dim adj = If((item And 7) > 4, 8, 0)\n            res.Add((adj + item) \\ 8) : res.Add((item And 7) - adj)\n        Next : Return res.ToArray()\n    End Function\n\n    \n    Function TheSame(a As Integer(), b As Integer()) As Boolean\n        For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False\n        Next : Return True\n    End Function\n\n    Sub Rot(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next\n    End Sub\n\n    Sub Mir(ByRef p As List(Of Integer)) \n        For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next\n    End Sub\n\nEnd Module\n", "Java": "package pentominotiling;\n\nimport java.util.*;\n\npublic class PentominoTiling {\n\n    static final char[] symbols = \"FILNPTUVWXYZ-\".toCharArray();\n    static final Random rand = new Random();\n\n    static final int nRows = 8;\n    static final int nCols = 8;\n    static final int blank = 12;\n\n    static int[][] grid = new int[nRows][nCols];\n    static boolean[] placed = new boolean[symbols.length - 1];\n\n    public static void main(String[] args) {\n        shuffleShapes();\n\n        for (int r = 0; r < nRows; r++)\n            Arrays.fill(grid[r], -1);\n\n        for (int i = 0; i < 4; i++) {\n            int randRow, randCol;\n            do {\n                randRow = rand.nextInt(nRows);\n                randCol = rand.nextInt(nCols);\n            } while (grid[randRow][randCol] == blank);\n            grid[randRow][randCol] = blank;\n        }\n\n        if (solve(0, 0)) {\n            printResult();\n        } else {\n            System.out.println(\"no solution\");\n        }\n    }\n\n    static void shuffleShapes() {\n        int n = shapes.length;\n        while (n > 1) {\n            int r = rand.nextInt(n--);\n\n            int[][] tmp = shapes[r];\n            shapes[r] = shapes[n];\n            shapes[n] = tmp;\n\n            char tmpSymbol = symbols[r];\n            symbols[r] = symbols[n];\n            symbols[n] = tmpSymbol;\n        }\n    }\n\n    static void printResult() {\n        for (int[] r : grid) {\n            for (int i : r)\n                System.out.printf(\"%c \", symbols[i]);\n            System.out.println();\n        }\n    }\n\n    static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {\n\n        for (int i = 0; i < o.length; i += 2) {\n            int x = c + o[i + 1];\n            int y = r + o[i];\n            if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)\n                return false;\n        }\n\n        grid[r][c] = shapeIndex;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = shapeIndex;\n\n        return true;\n    }\n\n    static void removeOrientation(int[] o, int r, int c) {\n        grid[r][c] = -1;\n        for (int i = 0; i < o.length; i += 2)\n            grid[r + o[i]][c + o[i + 1]] = -1;\n    }\n\n    static boolean solve(int pos, int numPlaced) {\n        if (numPlaced == shapes.length)\n            return true;\n\n        int row = pos / nCols;\n        int col = pos % nCols;\n\n        if (grid[row][col] != -1)\n            return solve(pos + 1, numPlaced);\n\n        for (int i = 0; i < shapes.length; i++) {\n            if (!placed[i]) {\n                for (int[] orientation : shapes[i]) {\n\n                    if (!tryPlaceOrientation(orientation, row, col, i))\n                        continue;\n\n                    placed[i] = true;\n\n                    if (solve(pos + 1, numPlaced + 1))\n                        return true;\n\n                    removeOrientation(orientation, row, col);\n                    placed[i] = false;\n                }\n            }\n        }\n        return false;\n    }\n\n    static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n    {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};\n\n    static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};\n\n    static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n    {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n    {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};\n\n    static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n    {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n    {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n    {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};\n\n    static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n    {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};\n\n    static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n    {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};\n\n    static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n    {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};\n\n    static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};\n\n    static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n    {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n    {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};\n\n    static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n    {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};\n\n    static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};\n}\n"}
{"id": 60379, "name": "Make a backup file", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n"}
{"id": 60380, "name": "Make a backup file", "VB": "Public Sub backup(filename As String)\n    If Len(Dir(filename)) > 0 Then\n        On Error Resume Next\n        Name filename As filename & \".bak\"\n    Else\n        If Len(Dir(filename & \".lnk\")) > 0 Then\n            On Error Resume Next\n            With CreateObject(\"Wscript.Shell\").CreateShortcut(filename & \".lnk\")\n                link = .TargetPath\n                .Close\n            End With\n            Name link As link & \".bak\"\n        End If\n    End If\nEnd Sub\nPublic Sub main()\n    backup \"D:\\test.txt\"\nEnd Sub\n", "Java": "import java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.file.*;\n \npublic class Backup {\n\tpublic static void saveWithBackup(String filename, String... data) \n        throws IOException {\n\t\t\n\t\tPath file = Paths.get(filename).toRealPath();\n\t\tFile backFile = new File(filename + \".backup\");\n\t\tif(!backFile.exists()) {\n\t\t\t\n\t\t\tbackFile.createNewFile();\n\t\t}\n\t\tPath back = Paths.get(filename + \".backup\").toRealPath();\n\t\tFiles.move(file, back, StandardCopyOption.REPLACE_EXISTING);\n\t\ttry(PrintWriter out = new PrintWriter(file.toFile())){\n\t\t\tfor(int i = 0; i < data.length; i++) {\n\t\t\t\tout.print(data[i]);\n\t\t\t\tif(i < data.length - 1) {\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n        public static void main(String[] args) {\n\t\ttry {\n\t\t\tsaveWithBackup(\"original.txt\", \"fourth\", \"fifth\", \"sixth\");\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e);\n\t\t}\n\t} \n}\n"}
{"id": 60381, "name": "Check Machin-like formulas", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n"}
{"id": 60382, "name": "Check Machin-like formulas", "VB": "Imports System.Numerics\n\nPublic Class BigRat \n    Implements IComparable\n    Public nu, de As BigInteger\n    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),\n                  One = New BigRat(BigInteger.One, BigInteger.One)\n    Sub New(bRat As BigRat)\n        nu = bRat.nu : de = bRat.de\n    End Sub\n    Sub New(n As BigInteger, d As BigInteger)\n        If d = BigInteger.Zero Then _\n            Throw (New Exception(String.Format(\"tried to set a BigRat with ({0}/{1})\", n, d)))\n        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)\n        If bi > BigInteger.One Then n /= bi : d /= bi\n        If d < BigInteger.Zero Then n = -n : d = -d\n        nu = n : de = d\n    End Sub\n    Shared Operator -(x As BigRat) As BigRat\n        Return New BigRat(-x.nu, x.de)\n    End Operator\n    Shared Operator +(x As BigRat, y As BigRat)\n        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator -(x As BigRat, y As BigRat) As BigRat\n        Return x + (-y)\n    End Operator\n    Shared Operator *(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.nu, x.de * y.de)\n    End Operator\n    Shared Operator /(x As BigRat, y As BigRat) As BigRat\n        Return New BigRat(x.nu * y.de, x.de * y.nu)\n    End Operator\n    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo\n        Dim dif As BigRat = New BigRat(nu, de) - obj\n        If dif.nu < BigInteger.Zero Then Return -1\n        If dif.nu > BigInteger.Zero Then Return 1\n        Return 0\n    End Function\n    Shared Operator =(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) = 0\n    End Operator\n    Shared Operator <>(x As BigRat, y As BigRat) As Boolean\n        Return x.CompareTo(y) <> 0\n    End Operator\n    Overrides Function ToString() As String\n        If de = BigInteger.One Then Return nu.ToString\n        Return String.Format(\"({0}/{1})\", nu, de)\n    End Function\n    Shared Function Combine(a As BigRat, b As BigRat) As BigRat\n        Return (a + b) / (BigRat.One - (a * b))\n    End Function\nEnd Class\n\nPublic Structure Term \n    Dim c As Integer, br As BigRat\n    Sub New(cc As Integer, bigr As BigRat)\n        c = cc : br = bigr\n    End Sub\nEnd Structure\n\nModule Module1\n    Function Eval(c As Integer, x As BigRat) As BigRat\n        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)\n        Dim hc As Integer = c \\ 2\n        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))\n    End Function\n\n    Function Sum(terms As List(Of Term)) As BigRat\n        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)\n        Dim htc As Integer = terms.Count / 2\n        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))\n    End Function\n\n    Function ParseLine(ByVal s As String) As List(Of Term)\n        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)\n        While t.Contains(\" \") : t = t.Replace(\" \", \"\") : End While\n        p = t.IndexOf(\"pi/4=\") : If p < 0 Then _\n            Console.WriteLine(\"warning: tan(left side of equation) <> 1\") : ParseLine.Add(x) : Exit Function\n        t = t.Substring(p + 5)\n        For Each item As String In t.Split(\")\")\n            If item.Length > 5 Then\n                If (Not item.Contains(\"tan\") OrElse item.IndexOf(\"a\") < 0 OrElse\n                    item.IndexOf(\"a\") > item.IndexOf(\"tan\")) AndAlso Not item.Contains(\"atn\") Then\n                    Console.WriteLine(\"warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]\", item)\n                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function\n                End If\n                x.c = 1 : x.br = New BigRat(BigRat.One)\n                p = item.IndexOf(\"/\") : If p > 0 Then\n                    x.br.de = UInt64.Parse(item.Substring(p + 1))\n                    item = item.Substring(0, p)\n                    p = item.IndexOf(\"(\") : If p > 0 Then\n                        x.br.nu = UInt64.Parse(item.Substring(p + 1))\n                        p = item.IndexOf(\"a\") : If p > 0 Then\n                            Integer.TryParse(item.Substring(0, p).Replace(\"*\", \"\"), x.c)\n                            If x.c = 0 Then x.c = 1\n                            If item.Contains(\"-\") AndAlso x.c > 0 Then x.c = -x.c\n                        End If\n                        ParseLine.Add(x)\n                    End If\n                End If\n            End If\n        Next\n    End Function\n\n    Sub Main(ByVal args As String())\n        Dim nl As String = vbLf\n        For Each item In (\"pi/4 = ATan(1 / 2) + ATan(1/3)\" & nl &\n              \"pi/4 = 2Atan(1/3) + ATan(1/7)\" & nl &\n              \"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)\" & nl &\n              \"pi/4 = 5arctan(1/7) + 2 * atan(3/79)\" & nl &\n              \"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)\" & nl &\n              \"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)\" & nl &\n              \"PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)\" & nl &\n              \"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)\" & nl &\n              \"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)\" & nl &\n              \"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)\" & nl &\n              \"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)\" & nl &\n              \"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)\" & nl &\n              \"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )\" & nl &\n              \"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)\" & nl &\n              \"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)\" & nl &\n              \"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)\").Split(nl)\n            Console.WriteLine(\"{0}: {1}\", If(Sum(ParseLine(item)) = BigRat.One, \"Pass\", \"Fail\"), item)\n        Next\n    End Sub\nEnd Module\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n    \n    private static String FILE_NAME = \"MachinFormula.txt\";\n    \n    public static void main(String[] args) {\n        try {\n            runPrivate();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private static void runPrivate() throws IOException {\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {        \n            String inLine = null;\n            while ( (inLine = reader.readLine()) != null ) {\n                String[] split = inLine.split(\"=\");\n                System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n            }\n        }\n    }\n    \n    private static String tanLeft(String formula) {\n        if ( formula.compareTo(\"pi/4\") == 0 ) {\n            return \"1\";\n        }\n        throw new RuntimeException(\"ERROR 104:  Unknown left side: \" + formula);\n    }\n    \n    private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n    \n    private static Fraction tanRight(String formula) {\n        Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n        List<Term> terms = new ArrayList<>();\n        while ( matcher.find() ) {\n            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n        }\n        return evaluateArctan(terms);\n    }\n    \n    private static Fraction evaluateArctan(List<Term> terms) {\n        if ( terms.size() == 1 ) {\n            Term term = terms.get(0);\n            return evaluateArctan(term.coefficient, term.fraction);\n        }\n        int size = terms.size();\n        List<Term> left = terms.subList(0, (size+1) / 2);\n        List<Term> right = terms.subList((size+1) / 2, size);\n        return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n    }\n    \n    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n        \n        if ( coefficient == 1 ) {\n            return fraction;\n        }\n        else if ( coefficient < 0 ) {\n            return evaluateArctan(-coefficient, fraction).negate();\n        }\n        if ( coefficient % 2 == 0 ) {\n            Fraction f = evaluateArctan(coefficient/2, fraction);\n            return arctanFormula(f, f);\n        }\n        Fraction a = evaluateArctan(coefficient/2, fraction);\n        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n        return arctanFormula(a, b);\n    }\n    \n    private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n    }\n    \n    private static class Fraction {\n        \n        public static final Fraction ONE = new Fraction(\"1\", \"1\");\n        \n        private BigInteger numerator;\n        private BigInteger denominator;\n        \n        public Fraction(String num, String den) {\n            numerator = new BigInteger(num);\n            denominator = new BigInteger(den);\n        }\n\n        public Fraction(BigInteger num, BigInteger den) {\n            numerator = num;\n            denominator = den;\n        }\n\n        public Fraction negate() {\n            return new Fraction(numerator.negate(), denominator);\n        }\n        \n        public Fraction add(Fraction f) {\n            BigInteger gcd = denominator.gcd(f.denominator);\n            BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n            BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n        }\n        \n        public Fraction subtract(Fraction f) {\n            return add(f.negate());\n        }\n        \n        public Fraction multiply(Fraction f) {\n            BigInteger num = numerator.multiply(f.numerator);\n            BigInteger den = denominator.multiply(f.denominator);\n            BigInteger gcd = num.gcd(den);\n            return new Fraction(num.divide(gcd), den.divide(gcd));\n        }\n\n        public Fraction divide(Fraction f) {\n            return multiply(new Fraction(f.denominator, f.numerator));\n        }\n        \n        @Override\n        public String toString() {\n            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n                return numerator.toString();\n            }\n            return numerator + \" / \" + denominator;\n        }\n    }\n    \n    private static class Term {\n        \n        private int coefficient;\n        private Fraction fraction;\n        \n        public Term(int c, Fraction f) {\n            coefficient = c;\n            fraction = f;\n        }\n    }\n    \n}\n"}
{"id": 60383, "name": "Solve triangle solitare puzzle", "VB": "Imports System, Microsoft.VisualBasic.DateAndTime\n\nPublic Module Module1\n    Const n As Integer = 5 \n    Dim Board As String \n    Dim Starting As Integer = 1 \n    Dim Target As Integer = 13 \n    Dim Moves As Integer() \n    Dim bi() As Integer \n    Dim ib() As Integer \n    Dim nl As Char = Convert.ToChar(10) \n\n    \n    Public Function Dou(s As String) As String\n        Dou = \"\" : Dim b As Boolean = True\n        For Each ch As Char In s\n            If b Then b = ch <> \" \"\n            If b Then Dou &= ch & \" \" Else Dou = \" \" & Dou\n        Next : Dou = Dou.TrimEnd()\n    End Function\n\n    \n    Public Function Fmt(s As String) As String\n        If s.Length < Board.Length Then Return s\n        Fmt = \"\" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &\n                If(i = n, s.Substring(Board.Length), \"\") & nl\n        Next\n    End Function\n\n    \n    Public Function Triangle(n As Integer) As Integer\n        Return (n * (n + 1)) / 2\n    End Function\n\n    \n    Public Function Init(s As String, pos As Integer) As String\n        Init = s : Mid(Init, pos, 1) = \"0\"\n    End Function\n\n    \n    Public Sub InitIndex()\n        ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0\n        For i As Integer = 0 To ib.Length - 1\n            If i = 0 Then\n                ib(i) = 0 : bi(j) = 0 : j += 1\n            Else\n                If Board(i - 1) = \"1\" Then ib(i) = j : bi(j) = i : j += 1\n            End If\n        Next\n    End Sub\n\n    \n    Public Function solve(brd As String, pegsLeft As Integer) As String\n        If pegsLeft = 1 Then \n            If Target = 0 Then Return \"Completed\" \n            If brd(bi(Target) - 1) = \"1\" Then Return \"Completed\" Else Return \"fail\"\n        End If\n        For i = 1 To Board.Length \n            If brd(i - 1) = \"1\" Then \n                For Each mj In Moves \n                    Dim over As Integer = i + mj \n                    Dim land As Integer = i + 2 * mj \n                    \n                    If land >= 1 AndAlso land <= brd.Length _\n                                AndAlso brd(land - 1) = \"0\" _\n                                AndAlso brd(over - 1) = \"1\" Then\n                        setPegs(brd, \"001\", i, over, land) \n                        \n                        Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)\n                        \n                        If Res.Length <> 4 Then _\n                            Return brd & info(i, over, land) & nl & Res\n                        setPegs(brd, \"110\", i, over, land) \n                    End If\n                Next\n            End If\n        Next\n        Return \"fail\"\n    End Function\n\n    \n    Function info(frm As Integer, over As Integer, dest As Integer) As String\n        Return \"  Peg from \" & ib(frm).ToString() & \" goes to \" & ib(dest).ToString() &\n            \", removing peg at \" & ib(over).ToString()\n    End Function\n\n    \n    Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)\n        Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)\n    End Sub\n\n    \n    Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)\n        x = Math.Max(Math.Min(x, hi), lo)\n    End Sub\n\n    Public Sub Main()\n        Dim t As Integer = Triangle(n) \n        LimitIt(Starting, 1, t) \n        LimitIt(Target, 0, t)\n        Dim stime As Date = Now() \n        Moves = {-n - 1, -n, -1, 1, n, n + 1} \n        Board = New String(\"1\", n * n) \n        For i As Integer = 0 To n - 2 \n            Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(\" \", n - 1 - i)\n        Next\n        InitIndex() \n        Dim B As String = Init(Board, bi(Starting)) \n        Console.WriteLine(Fmt(B & \"  Starting with peg removed from \" & Starting.ToString()))\n        Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)\n        Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & \" ms.\"\n        If res(0).Length = 4 Then\n            If Target = 0 Then\n                Console.WriteLine(\"Unable to find a solution with last peg left anywhere.\")\n            Else\n                Console.WriteLine(\"Unable to find a solution with last peg left at \" &\n                                  Target.ToString() & \".\")\n            End If\n            Console.WriteLine(\"Computation time: \" & ts)\n        Else\n            For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next\n            Console.WriteLine(\"Computation time to first found solution: \" & ts)\n        End If\n        If Diagnostics.Debugger.IsAttached Then Console.ReadLine()\n    End Sub\nEnd Module\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\n\npublic class IQPuzzle {\n\n    public static void main(String[] args) {\n        System.out.printf(\"  \");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"  %,6d\", start);\n        }\n        System.out.printf(\"%n\");\n        for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {\n            System.out.printf(\"%2d\", start);\n            Map<Integer,Integer> solutions = solve(start);    \n            for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {\n                System.out.printf(\"  %,6d\", solutions.containsKey(end) ? solutions.get(end) : 0);\n            }\n            System.out.printf(\"%n\");\n        }\n        int moveNum = 0;\n        System.out.printf(\"%nOne Solution:%n\");\n        for ( Move m : oneSolution ) {\n            moveNum++;\n            System.out.printf(\"Move %d = %s%n\", moveNum, m);\n        }\n    }\n    \n    private static List<Move> oneSolution = null;\n    \n    private static Map<Integer, Integer> solve(int emptyPeg) {\n        Puzzle puzzle = new Puzzle(emptyPeg);\n        Map<Integer,Integer> solutions = new HashMap<>();\n        Stack<Puzzle> stack = new Stack<Puzzle>();\n        stack.push(puzzle);\n        while ( ! stack.isEmpty() ) {\n            Puzzle p = stack.pop();\n            if ( p.solved() ) {\n                solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);\n                if ( oneSolution == null ) {\n                    oneSolution = p.moves;\n                }\n                continue;\n            }\n            for ( Move move : p.getValidMoves() ) {\n                Puzzle pMove = p.move(move);\n                stack.add(pMove);\n            }\n        }\n        \n        return solutions;\n    }\n    \n    private static class Puzzle {\n        \n        public static int MAX_PEGS = 16;\n        private boolean[] pegs = new boolean[MAX_PEGS];  \n        \n        private List<Move> moves;\n\n        public Puzzle(int emptyPeg) {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            pegs[emptyPeg] = false;\n            moves = new ArrayList<>();\n        }\n\n        public Puzzle() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                pegs[i] = true;\n            }\n            moves = new ArrayList<>();\n        }\n\n        private static Map<Integer,List<Move>> validMoves = new HashMap<>(); \n        static {\n            validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));\n            validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));\n            validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));\n            validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));\n            validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));\n            validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));\n            validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));\n            validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));\n            validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));\n            validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));\n            validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));\n            validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));\n            validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));\n            validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));\n            validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));\n        }\n        \n        public List<Move> getValidMoves() {\n            List<Move> moves = new ArrayList<Move>();\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    for ( Move testMove : validMoves.get(i) ) {\n                        if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {\n                            moves.add(testMove);\n                        }\n                    }\n                }\n            }\n            return moves;\n        }\n\n        public boolean solved() {\n            boolean foundFirstPeg = false;\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    if ( foundFirstPeg ) {\n                        return false;\n                    }\n                    foundFirstPeg = true;\n                }\n            }\n            return true;\n        }\n        \n        public Puzzle move(Move move) {\n            Puzzle p = new Puzzle();\n            if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {\n                throw new RuntimeException(\"Invalid move.\");\n            }\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                p.pegs[i] = pegs[i];\n            }\n            p.pegs[move.start] = false;\n            p.pegs[move.jump] = false;\n            p.pegs[move.end] = true;\n            for ( Move m : moves ) {\n                p.moves.add(new Move(m.start, m.jump, m.end));\n            }\n            p.moves.add(new Move(move.start, move.jump, move.end));\n            return p;\n        }\n        \n        public int getLastPeg() {\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                if ( pegs[i] ) {\n                    return i;\n                }\n            }\n            throw new RuntimeException(\"ERROR:  Illegal position.\");\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"[\");\n            for ( int i = 1 ; i < MAX_PEGS ; i++ ) {\n                sb.append(pegs[i] ? 1 : 0);\n                sb.append(\",\");\n            }\n            sb.setLength(sb.length()-1);            \n            sb.append(\"]\");\n            return sb.toString();\n        }\n    }\n    \n    private static class Move {\n        int start;\n        int jump;\n        int end;\n        \n        public Move(int s, int j, int e) {\n            start = s; jump = j; end = e;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder sb = new StringBuilder();\n            sb.append(\"{\");\n            sb.append(\"s=\" + start);\n            sb.append(\", j=\" + jump);\n            sb.append(\", e=\" + end);\n            sb.append(\"}\");\n            return sb.toString();\n        }\n    }\n\n}\n"}
{"id": 60384, "name": "Twelve statements", "VB": "Public s As String    \nPublic t As Integer   \n \nFunction s1()\n    s1 = Len(s) = 12\nEnd Function\nFunction s2()\n    t = 0\n    For i = 7 To 12\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s2 = t = 3\nEnd Function\nFunction s3()\n    t = 0\n    For i = 2 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s3 = t = 2\nEnd Function\nFunction s4()\n    s4 = Mid(s, 5, 1) = \"0\" Or ((Mid(s, 6, 1) = \"1\" And Mid(s, 7, 1) = \"1\"))\nEnd Function\nFunction s5()\n    s5 = Mid(s, 2, 1) = \"0\" And Mid(s, 3, 1) = \"0\" And Mid(s, 4, 1) = \"0\"\nEnd Function\nFunction s6()\n    t = 0\n    For i = 1 To 12 Step 2\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s6 = t = 4\nEnd Function\nFunction s7()\n    s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)\nEnd Function\nFunction s8()\n    s8 = Mid(s, 7, 1) = \"0\" Or (Mid(s, 5, 1) = \"1\" And Mid(s, 6, 1) = \"1\")\nEnd Function\nFunction s9()\n    t = 0\n    For i = 1 To 6\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s9 = t = 3\nEnd Function\nFunction s10()\n    s10 = Mid(s, 11, 1) = \"1\" And Mid(s, 12, 1) = \"1\"\nEnd Function\nFunction s11()\n    t = 0\n    For i = 7 To 9\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s11 = t = 1\nEnd Function\nFunction s12()\n    t = 0\n    For i = 1 To 11\n        t = t - (Mid(s, i, 1) = \"1\")\n    Next i\n    s12 = t = 4\nEnd Function\n \nPublic Sub twelve_statements()\n    For i = 0 To 2 ^ 12 - 1\n        s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \\ 128)), 5) _\n            & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)\n        For b = 1 To 12\n            Select Case b\n                Case 1: If s1 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 2: If s2 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 3: If s3 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 4: If s4 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 5: If s5 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 6: If s6 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 7: If s7 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 8: If s8 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 9: If s9 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 10: If s10 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 11: If s11 <> (Mid(s, b, 1) = \"1\") Then Exit For\n                Case 12: If s12 <> (Mid(s, b, 1) = \"1\") Then Exit For\n            End Select\n            If b = 12 Then Debug.Print s\n        Next\n    Next\nEnd Sub\n", "Java": "public class LogicPuzzle\n{\n    boolean S[] = new boolean[13];\n    int Count = 0;\n\n    public boolean check2 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 12; k++)\n            if (S[k]) count++;\n        return S[2] == (count == 3);\n    }\n\n    public boolean check3 ()\n    {\n        int count = 0;\n        for (int k = 2; k <= 12; k += 2)\n            if (S[k]) count++;\n        return S[3] == (count == 2);\n    }\n\n    public boolean check4 ()\n    {\n        return S[4] == ( !S[5] || S[6] && S[7]);\n    }\n\n    public boolean check5 ()\n    {\n        return S[5] == ( !S[2] && !S[3] && !S[4]);\n    }\n\n    public boolean check6 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k += 2)\n            if (S[k]) count++;\n        return S[6] == (count == 4);\n    }\n\n    public boolean check7 ()\n    {\n        return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));\n    }\n\n    public boolean check8 ()\n    {\n        return S[8] == ( !S[7] || S[5] && S[6]);\n    }\n\n    public boolean check9 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 6; k++)\n            if (S[k]) count++;\n        return S[9] == (count == 3);\n    }\n\n    public boolean check10 ()\n    {\n        return S[10] == (S[11] && S[12]);\n    }\n\n    public boolean check11 ()\n    {\n        int count = 0;\n        for (int k = 7; k <= 9; k++)\n            if (S[k]) count++;\n        return S[11] == (count == 1);\n    }\n\n    public boolean check12 ()\n    {\n        int count = 0;\n        for (int k = 1; k <= 11; k++)\n            if (S[k]) count++;\n        return S[12] == (count == 4);\n    }\n\n    public void check ()\n    {\n        if (check2() && check3() && check4() && check5() && check6()\n            && check7() && check8() && check9() && check10() && check11()\n            && check12())\n        {\n            for (int k = 1; k <= 12; k++)\n                if (S[k]) System.out.print(k + \" \");\n            System.out.println();\n            Count++;\n        }\n    }\n\n    public void recurseAll (int k)\n    {\n        if (k == 13)\n            check();\n        else\n        {\n            S[k] = false;\n            recurseAll(k + 1);\n            S[k] = true;\n            recurseAll(k + 1);\n        }\n    }\n\n    public static void main (String args[])\n    {\n        LogicPuzzle P = new LogicPuzzle();\n        P.S[1] = true;\n        P.recurseAll(2);\n        System.out.println();\n        System.out.println(P.Count + \" Solutions found.\");\n    }\n}\n"}
{"id": 60385, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n"}
{"id": 60386, "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", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 60387, "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", "C": "#include <unistd.h>\n#include <sys/types.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <err.h>\n\n\nint read_file_line(const char *path, int line_no)\n{\n\tstruct stat s;\n\tchar *buf;\n\toff_t start = -1, end = -1;\n\tsize_t i;\n\tint ln, fd, ret = 1;\n\n\tif (line_no == 1) start = 0;\n\telse if (line_no < 1){\n\t\twarn(\"line_no too small\");\n\t\treturn 0; \n\t}\n\n\tline_no--; \n\n\tfd = open(path, O_RDONLY);\n\tfstat(fd, &s);\n\n\t\n\tbuf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n\t\n\tmadvise(buf, s.st_size, MADV_SEQUENTIAL);\n\n\tfor (i = ln = 0; i < s.st_size && ln <= line_no; i++) {\n\t\tif (buf[i] != '\\n') continue;\n\n\t\tif (++ln == line_no) start = i + 1;\n\t\telse if (ln == line_no + 1) end = i + 1;\n\t}\n\n\tif (start >= s.st_size || start < 0) {\n\t\twarn(\"file does not have line %d\", line_no + 1);\n\t\tret = 0;\n\t} else {\n\t\t\n\t}\n\n\tmunmap(buf, s.st_size);\n\tclose(fd);\n\n\treturn ret;\n}\n"}
{"id": 60388, "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", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 60389, "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", "C": "\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <locale.h>\n#include <string.h>\n\n#ifdef _Bool\n#include <stdbool.h>\n#else\n#define bool int\n#define true  1\n#define false 0\n#endif\n\n\nint checkFileExtension(char* fileName, char* fileExtensions)\n{\n    char* fileExtension = fileExtensions;\n\n    if ( *fileName )\n    {\n        while ( *fileExtension )\n        {\n            int fileNameLength = strlen(fileName);\n            int extensionLength = strlen(fileExtension);\n            if ( fileNameLength >= extensionLength )\n            {\n                char* a = fileName + fileNameLength - extensionLength;\n                char* b = fileExtension;\n                while ( *a && toupper(*a++) == toupper(*b++) )\n                    ;\n                if ( !*a )\n                    return true;\n            }\n            fileExtension += extensionLength + 1;\n        }\n    }\n    return false;\n}\n\nvoid printExtensions(char* extensions)\n{\n    while( *extensions )\n    {\n        printf(\"%s\\n\", extensions);\n        extensions += strlen(extensions) + 1;\n    }\n}\n\nbool test(char* fileName, char* extension, bool expectedResult)\n{\n    bool result = checkFileExtension(fileName,extension);\n    bool returnValue = result == expectedResult;\n    printf(\"%20s  result: %-5s  expected: %-5s  test %s\\n\", \n        fileName,\n        result         ? \"true\"   : \"false\",\n        expectedResult ? \"true\"   : \"false\", \n        returnValue    ? \"passed\" : \"failed\" );\n    return returnValue;\n}\n\nint main(void)\n{\n    static char extensions[] = \".zip\\0.rar\\0.7z\\0.gz\\0.archive\\0.A##\\0.tar.bz2\\0\";\n\n    setlocale(LC_ALL,\"\");\n\n    printExtensions(extensions);\n    printf(\"\\n\");\n\n    if ( test(\"MyData.a##\",         extensions,true )\n    &&   test(\"MyData.tar.Gz\",      extensions,true )\n    &&   test(\"MyData.gzip\",        extensions,false)\n    &&   test(\"MyData.7z.backup\",   extensions,false)\n    &&   test(\"MyData...\",          extensions,false)\n    &&   test(\"MyData\",             extensions,false)\n    &&   test(\"MyData_v1.0.tar.bz2\",extensions,true )\n    &&   test(\"MyData_v1.0.bz2\",    extensions,false) \n    &&   test(\"filename\",           extensions,false)\n    )\n        printf(\"\\n%s\\n\", \"All tests passed.\");\n    else\n        printf(\"\\n%s\\n\", \"Last test failed.\");\n\n    printf(\"\\n%s\\n\", \"press enter\");\n    getchar();\n    return 0;\n}\n"}
{"id": 60390, "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", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 60391, "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", "C": "#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l/r:(b=1,0);\n            case 5: return l?r/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" / \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" / \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)/sizeof(int), t, 1);\n\n    return 0;\n}\n"}
{"id": 60392, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <omp.h>\n\nint main()\n{\n        int jobs = 41, tid;\n        omp_set_num_threads(5);\n\n        #pragma omp parallel shared(jobs) private(tid)\n        {\n                tid = omp_get_thread_num();\n                while (jobs > 0) {\n                        \n                        #pragma omp barrier\n                        if (!jobs) break;\n\n                        printf(\"%d: taking job %d\\n\", tid, jobs--);\n                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);\n                        printf(\"%d: done job\\n\", tid);\n                }\n\n                printf(\"[%d] leaving\\n\", tid);\n\n                \n                #pragma omp barrier\n        }\n\n        return 0;\n}\n"}
{"id": 60393, "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", "C": "#include <stdio.h>\n#include <stdint.h>\n\nvoid to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(\"seq from %llx: [ \", x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(\"%02x \", s[i]); } while ((s[i++] & 128));\n\t\tprintf(\"] back: %llx\\n\", from_seq(s));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60394, "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", "C": "#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <fcntl.h>\n\nvoid * record(size_t bytes)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_RDONLY))) return 0;\n\tvoid *a = malloc(bytes);\n\tread(fd, a, bytes);\n\tclose(fd);\n\treturn a;\n}\n\nint play(void *buf, size_t len)\n{\n\tint fd;\n\tif (-1 == (fd = open(\"/dev/dsp\", O_WRONLY))) return 0;\n\twrite(fd, buf, len);\n\tclose(fd);\n\treturn 1;\n}\n\nint main()\n{\n\tvoid *p = record(65536);\n\tplay(p, 65536);\n\treturn 0;\n}\n"}
{"id": 60395, "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", "C": "#include <glib.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nguchar* sha256_merkle_tree(FILE* in, size_t block_size) {\n    gchar* buffer = g_malloc(block_size);\n    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);\n    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);\n    size_t bytes;\n    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {\n        g_checksum_reset(checksum);\n        g_checksum_update(checksum, (guchar*)buffer, bytes);\n        gsize len = digest_length;\n        guchar* digest = g_malloc(len);\n        g_checksum_get_digest(checksum, digest, &len);\n        g_ptr_array_add(hashes, digest);\n    }\n    g_free(buffer);\n    guint hashes_length = hashes->len;\n    if (hashes_length == 0) {\n        g_ptr_array_free(hashes, TRUE);\n        g_checksum_free(checksum);\n        return NULL;\n    }\n    while (hashes_length > 1) {\n        guint j = 0;\n        for (guint i = 0; i < hashes_length; i += 2, ++j) {\n            guchar* digest1 = g_ptr_array_index(hashes, i);\n            guchar* digest_out = g_ptr_array_index(hashes, j);\n            if (i + 1 < hashes_length) {\n                guchar* digest2 = g_ptr_array_index(hashes, i + 1);\n                g_checksum_reset(checksum);\n                g_checksum_update(checksum, digest1, digest_length);\n                g_checksum_update(checksum, digest2, digest_length);\n                gsize len = digest_length;\n                g_checksum_get_digest(checksum, digest_out, &len);\n            } else {\n                memcpy(digest_out, digest1, digest_length);\n            }\n        }\n        hashes_length = j;\n    }\n    guchar* result = g_ptr_array_steal_index(hashes, 0);\n    g_ptr_array_free(hashes, TRUE);\n    g_checksum_free(checksum);\n    return result;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s filename\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    FILE* in = fopen(argv[1], \"rb\");\n    if (in) {\n        guchar* digest = sha256_merkle_tree(in, 1024);\n        fclose(in);\n        if (digest) {\n            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);\n            for (gssize i = 0; i < length; ++i)\n                printf(\"%02x\", digest[i]);\n            printf(\"\\n\");\n            g_free(digest);\n        }\n    } else {\n        perror(argv[1]);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60396, "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", "C": "\n#include <ctype.h>\n#include <stdio.h>\n\n\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n"}
{"id": 60397, "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", "C": "#include <gtk/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n"}
{"id": 60398, "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", "C": "\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct cursor_tag {\n    double x;\n    double y;\n    int angle;\n} cursor_t;\n\nvoid turn(cursor_t* cursor, int angle) {\n    cursor->angle = (cursor->angle + angle) % 360;\n}\n\nvoid draw_line(FILE* out, cursor_t* cursor, double length) {\n    double theta = (M_PI * cursor->angle)/180.0;\n    cursor->x += length * cos(theta);\n    cursor->y += length * sin(theta);\n    fprintf(out, \"L%g,%g\\n\", cursor->x, cursor->y);\n}\n\nvoid curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {\n    if (order == 0) {\n        draw_line(out, cursor, length);\n    } else {\n        curve(out, order - 1, length/2, cursor, -angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, angle);\n        turn(cursor, angle);\n        curve(out, order - 1, length/2, cursor, -angle);\n    }\n}\n\nvoid write_sierpinski_arrowhead(FILE* out, int size, int order) {\n    const double margin = 20.0;\n    const double side = size - 2.0 * margin;\n    cursor_t cursor;\n    cursor.angle = 0;\n    cursor.x = margin;\n    cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;\n    if ((order & 1) != 0)\n        turn(&cursor, -60);\n    fprintf(out, \"<svg xmlns='http:\n            size, size);\n    fprintf(out, \"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n    fprintf(out, \"<path stroke-width='1' stroke='black' fill='none' d='\");\n    fprintf(out, \"M%g,%g\\n\", cursor.x, cursor.y);\n    curve(out, order, side, &cursor, 60);\n    fprintf(out, \"'/>\\n</svg>\\n\");\n}\n\nint main(int argc, char** argv) {\n    const char* filename = \"sierpinski_arrowhead.svg\";\n    if (argc == 2)\n        filename = argv[1];\n    FILE* out = fopen(filename, \"w\");\n    if (!out) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    write_sierpinski_arrowhead(out, 600, 8);\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60399, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int badHrs, maxBadHrs;\n\nstatic double hrsTot = 0.0;\nstatic int rdgsTot = 0;\nchar bhEndDate[40];\n\nint mungeLine( char *line, int lno, FILE *fout )\n{\n    char date[40], *tkn;\n    int   dHrs, flag, hrs2, hrs;\n    double hrsSum;\n    int   hrsCnt = 0;\n    double avg;\n\n    tkn = strtok(line, \".\");\n    if (tkn) {\n        int n = sscanf(tkn, \"%s %d\", &date, &hrs2);\n        if (n<2) {\n            printf(\"badly formated line - %d %s\\n\", lno, tkn);\n            return 0;\n        }\n        hrsSum = 0.0;\n        while( tkn= strtok(NULL, \".\")) {\n            n = sscanf(tkn,\"%d %d %d\", &dHrs, &flag, &hrs);\n            if (n>=2) {\n                if (flag > 0) {\n                    hrsSum += 1.0*hrs2 + .001*dHrs;\n                    hrsCnt += 1;\n                    if (maxBadHrs < badHrs) {\n                        maxBadHrs = badHrs;\n                        strcpy(bhEndDate, date);\n                    }\n                    badHrs = 0;\n                }\n                else {\n                    badHrs += 1;\n                }\n                hrs2 = hrs;\n            }\n            else {\n                printf(\"bad file syntax line %d: %s\\n\",lno, tkn);\n            }\n        }\n        avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;\n        fprintf(fout, \"%s  Reject: %2d  Accept: %2d  Average: %7.3f\\n\",\n                date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);\n        hrsTot += hrsSum;\n        rdgsTot += hrsCnt;\n    }\n    return 1;\n}\n\nint main()\n{\n    FILE *infile, *outfile;\n    int lineNo = 0;\n    char line[512];\n    const char *ifilename = \"readings.txt\";\n    outfile = fopen(\"V0.txt\", \"w\");\n\n    infile = fopen(ifilename, \"rb\");\n    if (!infile) {\n        printf(\"Can't open %s\\n\", ifilename);\n        exit(1);\n    }\n    while (NULL != fgets(line, 512, infile)) {\n        lineNo += 1;\n        if (0 == mungeLine(line, lineNo, outfile))\n            printf(\"Bad line at %d\",lineNo);\n    }\n    fclose(infile);\n\n    fprintf(outfile, \"File:     %s\\n\", ifilename);\n    fprintf(outfile, \"Total:    %.3f\\n\", hrsTot);\n    fprintf(outfile, \"Readings: %d\\n\", rdgsTot);\n    fprintf(outfile, \"Average:  %.3f\\n\", hrsTot/rdgsTot);\n    fprintf(outfile, \"\\nMaximum number of consecutive bad readings is %d\\n\", maxBadHrs);\n    fprintf(outfile, \"Ends on date %s\\n\", bhEndDate);\n    fclose(outfile);\n    return 0;\n}\n"}
{"id": 60400, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 60401, "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", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 60402, "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", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 60403, "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", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nunsigned long long bruteForceProperDivisorSum(unsigned long long n){\n\tunsigned long long i,sum = 0;\n\t\n\tfor(i=1;i<(n+1)/2;i++)\n\t\tif(n%i==0 && n!=i)\n\t\t\tsum += i;\n\t\t\n\treturn sum;\n}\n\nvoid printSeries(unsigned long long* arr,int size,char* type){\n\tint i;\n\t\n\tprintf(\"\\nInteger : %llu, Type : %s, Series : \",arr[0],type);\n\t\n\tfor(i=0;i<size-1;i++)\n\t\tprintf(\"%llu, \",arr[i]);\n\tprintf(\"%llu\",arr[i]);\n}\n\nvoid aliquotClassifier(unsigned long long n){\n\tunsigned long long arr[16];\n\tint i,j;\n\t\n\tarr[0] = n;\n\t\n\tfor(i=1;i<16;i++){\n\t\tarr[i] = bruteForceProperDivisorSum(arr[i-1]);\n\t\t\n\t\tif(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){\n\t\t\tprintSeries(arr,i+1,(arr[i]==0)?\"Terminating\":(arr[i]==n && i==1)?\"Perfect\":(arr[i]==n && i==2)?\"Amicable\":(arr[i]==arr[i-1] && arr[i]!=n)?\"Aspiring\":\"Sociable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(j=1;j<i;j++){\n\t\t\tif(arr[j]==arr[i]){\n\t\t\t\tprintSeries(arr,i+1,\"Cyclic\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintSeries(arr,i+1,\"Non-Terminating\");\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tchar str[21];\n\t\n\twhile(fgets(str,21,fp)!=NULL)\n\t\taliquotClassifier(strtoull(str,(char**)NULL,10));\n\t\n\tfclose(fp);\n}\n\nint main(int argC,char* argV[])\n{\n    if(argC!=2)\n\t\tprintf(\"Usage : %s <positive integer>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],'.')!=NULL)\n\t\t\tprocessFile(argV[1]);\n\t\telse\n\t\t\taliquotClassifier(strtoull(argV[1],(char**)NULL,10));\n\t}\n\treturn 0;\n}\n"}
{"id": 60404, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main()\n{\n  struct tm ts;\n  time_t t;\n  const char *d = \"March 7 2009 7:30pm EST\";\n  \n  strptime(d, \"%B %d %Y %I:%M%p %Z\", &ts);\n  \n  t = mktime(&ts);\n  t += 12*60*60;\n  printf(\"%s\", ctime(&t));\n\n  return EXIT_SUCCESS;\n}\n"}
{"id": 60405, "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", "C": ">>>>>,----------[++++++++\n++[->+>+<<]>+>[-<<+>>]+++\n+++++[-<------>]>>+>,----\n------<<+[->>>>>+<<<<<]>>\n]>>>[<<<<[<<<[->>+<<[->+>\n[-]<<]]>[-<+>]>[-<<<.>>>>\n->>>>>[>>>>>]<-<<<<[<<<<<\n]+<]<<<<]>>>>>[>>>>>]<]\n"}
{"id": 60406, "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", "C": "#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\nint main() {\n    int a[10][10], i, j;\n\n    srand(time(NULL));\n    for (i = 0; i < 10; i++)\n        for (j = 0; j < 10; j++)\n            a[i][j] = rand() % 20 + 1;\n\n    for (i = 0; i < 10; i++) {\n        for (j = 0; j < 10; j++) {\n            printf(\" %d\", a[i][j]);\n            if (a[i][j] == 20)\n                goto Done;\n        }\n        printf(\"\\n\");\n    }\nDone:\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60407, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 60408, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p / 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \n        fflush(stdout);\n\n        \n        for (b = a + 1; b < max_p/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\n"}
{"id": 60409, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n"}
{"id": 60410, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\tchar *a = malloc(2), *b = 0, *x, c;\n\tint cnt, len = 1;\n\n\tfor (sprintf(a, \"1\"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {\n\t\tputs(x = a);\n\t\tfor (len = 0, cnt = 1; (c = *a); ) {\n\t\t\tif (c == *++a)\n\t\t\t\tcnt++;\n\t\t\telse if (c) {\n\t\t\t\tlen += sprintf(b + len, \"%d%c\", cnt, c);\n\t\t\t\tcnt = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60411, "name": "Stack", "Go": "var intStack []int\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc /= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\n\tstk_int_delete(stk);\n\treturn 0;\n}\n"}
{"id": 60412, "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", "C": "\n\n#include<stdio.h>\n\nint totient(int n){\n\tint 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\nint main()\n{\n\tint count = 0,n,tot;\n\t\n\tprintf(\" n    %c   prime\",237);\n        printf(\"\\n---------------\\n\");\n\t\n\tfor(n=1;n<=25;n++){\n\t\ttot = totient(n);\n\t\t\n\t\tif(n-1 == tot)\n\t\t\tcount++;\n\t\t\n\t\tprintf(\"%2d   %2d   %s\\n\", n, tot, n-1 == tot?\"True\":\"False\");\n\t}\n\t\n\tprintf(\"\\nNumber of primes up to %6d =%4d\\n\", 25,count);\n\t\n\tfor(n = 26; n <= 100000; n++){\n        tot = totient(n);\n        if(tot == n-1)\n\t\t\tcount++;\n        \n        if(n == 100 || n == 1000 || n%10000 == 0){\n            printf(\"\\nNumber of primes up to %6d = %4d\\n\", n, count);\n        }\n    }\n\t\n\treturn 0;\n}\n"}
{"id": 60413, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "C": "int a = 3;\n\n\nif (a == 2) {\n    puts (\"a is 2\"); \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}\n\n\nunless (a == 2) { \n    puts (\"a is 2\");  \n} else if (a == 3) {\n    puts (\"a is 3\");\n} else {\n    puts(\"a is 4\");\n}   \n\n\nswitch (a) {\n    case 2:\n        puts (\"a is 2\"); \n        break;\n    case 3:\n        puts (\"a is 3\");\n        break;\n    case 4:\n        puts (\"a is 4\");\n        break;\n    default: \n        puts(\"is neither\");\n}\n"}
{"id": 60414, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef struct frac_s *frac;\nstruct frac_s {\n\tint n, d;\n\tfrac next;\n};\n\nfrac parse(char *s)\n{\n\tint offset = 0;\n\tstruct frac_s h = {0}, *p = &h;\n\n\twhile (2 == sscanf(s, \"%d/%d%n\", &h.n, &h.d, &offset)) {\n\t\ts += offset;\n\t\tp = p->next = malloc(sizeof *p);\n\t\t*p = h;\n\t\tp->next = 0;\n\t}\n\n\treturn h.next;\n}\n\nint run(int v, char *s)\n{\n\tfrac n, p = parse(s);\n\tmpz_t val;\n\tmpz_init_set_ui(val, v);\n\nloop:\tn = p;\n\tif (mpz_popcount(val) == 1)\n\t\tgmp_printf(\"\\n[2^%d = %Zd]\", mpz_scan1(val, 0), val);\n\telse\n\t\tgmp_printf(\" %Zd\", val);\n\n\tfor (n = p; n; n = n->next) {\n\t\t\n\t\tif (!mpz_divisible_ui_p(val, n->d)) continue;\n\n\t\tmpz_divexact_ui(val, val, n->d);\n\t\tmpz_mul_ui(val, val, n->n);\n\t\tgoto loop;\n\t}\n\n\tgmp_printf(\"\\nhalt: %Zd has no divisors\\n\", val);\n\n\tmpz_clear(val);\n\twhile (p) {\n\t\tn = p->next;\n\t\tfree(p);\n\t\tp = n;\n\t}\n\n\treturn 0;\n}\n\nint main(void)\n{\n\trun(2,\t\"17/91 78/85 19/51 23/38 29/33 77/29 95/23 \"\n\t\t\"77/19 1/17 11/13 13/11 15/14 15/2 55/1\");\n\n\treturn 0;\n}\n"}
{"id": 60415, "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", "C": "#include <stdio.h>\n\n#define SWAP(r,s)  do{ t=r; r=s; s=t; } while(0)\n\nvoid StoogeSort(int a[], int i, int j) \n{\n   int t;\n   \n   if (a[j] < a[i]) SWAP(a[i], a[j]);\n   if (j - i > 1)\n   {\n       t = (j - i + 1) / 3;\n       StoogeSort(a, i, j - t);\n       StoogeSort(a, i + t, j);\n       StoogeSort(a, i, j - t);\n   }\n}\n  \nint main(int argc, char *argv[])\n{\n   int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};\n   int i, n;\n  \n   n = sizeof(nums)/sizeof(int);\n   StoogeSort(nums, 0, n-1);\n   \n   for(i = 0; i <= n-1; i++)\n      printf(\"%5d\", nums[i]);\n   \n   return 0;\n}\n"}
{"id": 60416, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BALLS 1024\nint n, w, h = 45, *x, *y, cnt = 0;\nchar *b;\n\n#define B(y, x) b[(y)*w + x]\n#define C(y, x) ' ' == b[(y)*w + x]\n#define V(i) B(y[i], x[i])\ninline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }\n\nvoid show_board()\n{\n\tint i, j;\n\tfor (puts(\"\\033[H\"), i = 0; i < h; i++, putchar('\\n'))\n\t\tfor (j = 0; j < w; j++, putchar(' '))\n\t\t\tprintf(B(i, j) == '*' ?\n\t\t\t\tC(i - 1, j) ? \"\\033[32m%c\\033[m\" :\n\t\t\t\t\"\\033[31m%c\\033[m\" : \"%c\", B(i, j));\n}\n\nvoid init()\n{\n\tint i, j;\n\tputs(\"\\033[H\\033[J\");\n\tb = malloc(w * h);\n\tmemset(b, ' ', w * h);\n\n\tx = malloc(sizeof(int) * BALLS * 2);\n\ty = x + BALLS;\n\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = -i; j <= i; j += 2)\n\t\t\tB(2 * i+2, j + w/2) = '*';\n\tsrand(time(0));\n}\n\nvoid move(int idx)\n{\n\tint xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;\n\n\tif (yy < 0) return;\n\tif (yy == h - 1) { y[idx] = -1; return; }\n\n\tswitch(c = B(yy + 1, xx)) {\n\tcase ' ':\tyy++; break;\n\tcase '*':\tsl = 1;\n\tdefault:\tif (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))\n\t\t\t\tif (!rnd(sl++)) o = 1;\n\t\t\tif (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))\n\t\t\t\tif (!rnd(sl++)) o = -1;\n\t\t\tif (!o) kill = 1;\n\t\t\txx += o;\n\t}\n\n\tc = V(idx); V(idx) = ' ';\n\tidx[y] = yy, idx[x] = xx;\n\tB(yy, xx) = c;\n\tif (kill) idx[y] = -1;\n}\n\nint run(void)\n{\n\tstatic int step = 0;\n\tint i;\n\tfor (i = 0; i < cnt; i++) move(i);\n\tif (2 == ++step && cnt < BALLS) {\n\t\tstep = 0;\n\t\tx[cnt] = w/2;\n\t\ty[cnt] = 0;\n\t\tif (V(cnt) != ' ') return 0;\n\t\tV(cnt) = rnd(80) + 43;\n\t\tcnt++;\n\t}\n\treturn 1;\n}\n\nint main(int c, char **v)\n{\n\tif (c < 2 || (n = atoi(v[1])) <= 3) n = 5;\n\tif (n >= 20) n = 20;\n\tw = n * 2 + 1;\n\tinit();\n\n\tdo { show_board(), usleep(60000); } while (run());\n\n\treturn 0;\n}\n"}
{"id": 60417, "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", "C": "#include <stdio.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n\tint *p, *q, t, swapped;\n\n\tif (start == end) return 0;\n\n\t\n\tfor (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n\t\tif (*p > *q)\n\t\t\tt = *p, *p = *q, *q = t, swapped = 1;\n\n\t\n\treturn swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\n\nvoid circle_sort(int *x, int n)\n{\n\tdo {\n\t\tint i;\n\t\tfor (i = 0; i < n; i++) printf(\"%d \", x[i]);\n\t\tputchar('\\n');\n\t} while (circle_sort_inner(x, x + (n - 1)));\n}\n\nint main(void)\n{\n\tint x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};\n\tcircle_sort(x, sizeof(x) / sizeof(*x));\n\n\treturn 0;\n}\n"}
{"id": 60418, "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", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n    int row, col;\n}cell;\n\nint ROW,COL,SUM=0;\n\nunsigned long raiseTo(int base,int power){\n    if(power==0)\n        return 1;\n    else\n        return base*raiseTo(base,power-1);\n}\n\ncell* kroneckerProduct(char* inputFile,int power){\n    FILE* fp = fopen(inputFile,\"r\");\n    \n    int i,j,k,l;\n    unsigned long prod;\n    int** matrix;\n    cell *coreList,*tempList,*resultList;\n    \n    fscanf(fp,\"%d%d\",&ROW,&COL);\n    \n    matrix = (int**)malloc(ROW*sizeof(int*));\n    \n    for(i=0;i<ROW;i++){\n        matrix[i] = (int*)malloc(COL*sizeof(int));\n        for(j=0;j<COL;j++){\n            fscanf(fp,\"%d\",&matrix[i][j]);\n            if(matrix[i][j]==1)\n                SUM++;\n        }\n    }\n    \n    coreList = (cell*)malloc(SUM*sizeof(cell));\n    resultList = (cell*)malloc(SUM*sizeof(cell));\n    \n    k = 0;\n    \n    for(i=0;i<ROW;i++){\n        for(j=0;j<COL;j++){\n            if(matrix[i][j]==1){\n                coreList[k].row = i+1;\n                coreList[k].col = j+1;\n                resultList[k].row = i+1;\n                resultList[k].col = j+1;\n                k++;\n            }\n        }\n    }\n    \n    prod = k;\n    \n    for(i=2;i<=power;i++){\n        tempList = (cell*)malloc(prod*k*sizeof(cell));\n        \n        l = 0;\n        \n        for(j=0;j<prod;j++){\n            for(k=0;k<SUM;k++){\n                tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;\n                tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;\n                l++;\n            }\n        }\n        \n        free(resultList);\n        \n        prod *= k;\n        \n        resultList = (cell*)malloc(prod*sizeof(cell));\n        \n        for(j=0;j<prod;j++){\n            resultList[j].row = tempList[j].row;\n            resultList[j].col = tempList[j].col;\n        }\n        free(tempList);\n    }\n    \n    return resultList;\n}\n\nint main(){\n    char fileName[100];\n    int power,i,length;\n    \n    cell* resultList;\n    \n    printf(\"Enter input file name : \");\n    scanf(\"%s\",fileName);\n    \n    printf(\"Enter power : \");\n    scanf(\"%d\",&power);\n    \n    resultList = kroneckerProduct(fileName,power);\n    \n    initwindow(raiseTo(ROW,power),raiseTo(COL,power),\"Kronecker Product Fractal\");\n    \n    length = raiseTo(SUM,power);\n\n    for(i=0;i<length;i++){\n        putpixel(resultList[i].row,resultList[i].col,15);\n    }\n    \n    getch();\n    \n    closegraph();\n    \n    return 0;\n}\n"}
{"id": 60419, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong :-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n"}
{"id": 60420, "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", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 60421, "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", "C": "#include <stdlib.h>  \n#include <string.h>  \n#include <strings.h> \n\nint mycmp(const void *s1, const void *s2)\n{\n    const char *l = *(const char **)s1, *r = *(const char **)s2;\n    size_t ll = strlen(l), lr = strlen(r);\n\n    if (ll > lr) return -1;\n    if (ll < lr) return 1;\n    return strcasecmp(l, r);\n}\n\nint main()\n{\n    const char *strings[] = {\n      \"Here\", \"are\", \"some\", \"sample\", \"strings\", \"to\", \"be\", \"sorted\" };\n\n    qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);\n    return 0;\n}\n"}
{"id": 60422, "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", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\nbool is_prime(uint32_t n) {\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    for (uint32_t p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\n\nuint32_t cycle(uint32_t n) {\n    uint32_t m = n, p = 1;\n    while (m >= 10) {\n        p *= 10;\n        m /= 10;\n    }\n    return m + 10 * (n % p);\n}\n\nbool is_circular_prime(uint32_t p) {\n    if (!is_prime(p))\n        return false;\n    uint32_t p2 = cycle(p);\n    while (p2 != p) {\n        if (p2 < p || !is_prime(p2))\n            return false;\n        p2 = cycle(p2);\n    }\n    return true;\n}\n\nvoid test_repunit(uint32_t digits) {\n    char* str = malloc(digits + 1);\n    if (str == 0) {\n        fprintf(stderr, \"Out of memory\\n\");\n        exit(1);\n    }\n    memset(str, '1', digits);\n    str[digits] = 0;\n    mpz_t bignum;\n    mpz_init_set_str(bignum, str, 10);\n    free(str);\n    if (mpz_probab_prime_p(bignum, 10))\n        printf(\"R(%u) is probably prime.\\n\", digits);\n    else\n        printf(\"R(%u) is not prime.\\n\", digits);\n    mpz_clear(bignum);\n}\n\nint main() {\n    uint32_t p = 2;\n    printf(\"First 19 circular primes:\\n\");\n    for (int count = 0; count < 19; ++p) {\n        if (is_circular_prime(p)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"%u\", p);\n            ++count;\n        }\n    }\n    printf(\"\\n\");\n    printf(\"Next 4 circular primes:\\n\");\n    uint32_t repunit = 1, digits = 1;\n    for (; repunit < p; ++digits)\n        repunit = 10 * repunit + 1;\n    mpz_t bignum;\n    mpz_init_set_ui(bignum, repunit);\n    for (int count = 0; count < 4; ) {\n        if (mpz_probab_prime_p(bignum, 15)) {\n            if (count > 0)\n                printf(\", \");\n            printf(\"R(%u)\", digits);\n            ++count;\n        }\n        ++digits;\n        mpz_mul_ui(bignum, bignum, 10);\n        mpz_add_ui(bignum, bignum, 1);\n    }\n    mpz_clear(bignum);\n    printf(\"\\n\");\n    test_repunit(5003);\n    test_repunit(9887);\n    test_repunit(15073);\n    test_repunit(25031);\n    test_repunit(35317);\n    test_repunit(49081);\n    return 0;\n}\n"}
{"id": 60423, "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", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 60424, "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", "C": "#include <stdlib.h>\n#include <string.h>\n#include <gtk/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \n  \n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n"}
{"id": 60425, "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", "C": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\n#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)\n\n#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));\n\nstatic void swap(unsigned *a, unsigned *b) {\n    unsigned tmp = *a;\n    *a = *b;\n    *b = tmp;\n}\n\n\nstatic void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)\n{\n\tif (!bit || to < from + 1) return;\n\n\tunsigned *ll = from, *rr = to - 1;\n\tfor (;;) {\n\t\t\n\t\twhile (ll < rr && !(*ll & bit)) ll++;\n\t\twhile (ll < rr &&  (*rr & bit)) rr--;\n\t\tif (ll >= rr) break;\n\t\tswap(ll, rr);\n\t}\n\n\tif (!(bit & *ll) && ll < to) ll++;\n\tbit >>= 1;\n\n\trad_sort_u(from, ll, bit);\n\trad_sort_u(ll, to, bit);\n}\n\n\nstatic void radix_sort(int *a, const size_t len)\n{\n\tsize_t i;\n\tunsigned *x = (unsigned*) a;\n\n\tfor (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n\n        rad_sort_u(x, x + len, INT_MIN);\n\n        for (i = 0; i < len; i++) \n            x[i] ^= INT_MIN;\n}\n\nint main(void)\n{\n        \n    srand(time(NULL));\n    int x[16];\n\n     for (size_t i = 0; i < ARR_LEN(x); i++) \n        x[i] = RAND_RNG(-128,127)\n\n    radix_sort(x, ARR_LEN(x));\n\n    for (size_t i = 0; i < ARR_LEN(x); i++) \n        printf(\"%d%c\", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\\n');\n}\n"}
{"id": 60426, "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", "C": "for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }\n"}
{"id": 60427, "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", "C": "#include <stdio.h>\n\nvoid selection_sort (int *a, int n) {\n    int i, j, m, t;\n    for (i = 0; i < n; i++) {\n        for (j = i, m = i; j < n; j++) {\n            if (a[j] < a[m]) {\n                m = j;\n            }\n        }\n        t = a[i];\n        a[i] = a[m];\n        a[m] = t;\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    selection_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": 60428, "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", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 60429, "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", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))\n\nint jacobi(unsigned long a, unsigned long n) {\n\tif (a >= n) a %= n;\n\tint result = 1;\n\twhile (a) {\n\t\twhile ((a & 1) == 0) {\n\t\t\ta >>= 1;\n\t\t\tif ((n & 7) == 3 || (n & 7) == 5) result = -result;\n\t\t}\n\t\tSWAP(a, n);\n\t\tif ((a & 3) == 3 && (n & 3) == 3) result = -result;\n\t\ta %= n;\n\t}\n\tif (n == 1) return result;\n\treturn 0;\n}\n\nvoid print_table(unsigned kmax, unsigned nmax) {\n\tprintf(\"n\\\\k|\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"%'3u\", k);\n\tprintf(\"\\n----\");\n\tfor (int k = 0; k <= kmax; ++k) printf(\"---\");\n\tputchar('\\n');\n\tfor (int n = 1; n <= nmax; n += 2) {\n\t\tprintf(\"%-2u |\", n);\n\t\tfor (int k = 0; k <= kmax; ++k)\n\t\t\tprintf(\"%'3d\", jacobi(k, n));\n\t\tputchar('\\n');\n\t}\n}\n\nint main() {\n\tprint_table(20, 21);\n\treturn 0;\n}\n"}
{"id": 60430, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 60431, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_DIM 3\nstruct kd_node_t{\n    double x[MAX_DIM];\n    struct kd_node_t *left, *right;\n};\n\n    inline double\ndist(struct kd_node_t *a, struct kd_node_t *b, int dim)\n{\n    double t, d = 0;\n    while (dim--) {\n        t = a->x[dim] - b->x[dim];\n        d += t * t;\n    }\n    return d;\n}\ninline void swap(struct kd_node_t *x, struct kd_node_t *y) {\n    double tmp[MAX_DIM];\n    memcpy(tmp,  x->x, sizeof(tmp));\n    memcpy(x->x, y->x, sizeof(tmp));\n    memcpy(y->x, tmp,  sizeof(tmp));\n}\n\n\n\n    struct kd_node_t*\nfind_median(struct kd_node_t *start, struct kd_node_t *end, int idx)\n{\n    if (end <= start) return NULL;\n    if (end == start + 1)\n        return start;\n\n    struct kd_node_t *p, *store, *md = start + (end - start) / 2;\n    double pivot;\n    while (1) {\n        pivot = md->x[idx];\n\n        swap(md, end - 1);\n        for (store = p = start; p < end; p++) {\n            if (p->x[idx] < pivot) {\n                if (p != store)\n                    swap(p, store);\n                store++;\n            }\n        }\n        swap(store, end - 1);\n\n        \n        if (store->x[idx] == md->x[idx])\n            return md;\n\n        if (store > md) end = store;\n        else        start = store;\n    }\n}\n\n    struct kd_node_t*\nmake_tree(struct kd_node_t *t, int len, int i, int dim)\n{\n    struct kd_node_t *n;\n\n    if (!len) return 0;\n\n    if ((n = find_median(t, t + len, i))) {\n        i = (i + 1) % dim;\n        n->left  = make_tree(t, n - t, i, dim);\n        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);\n    }\n    return n;\n}\n\n\nint visited;\n\nvoid nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,\n        struct kd_node_t **best, double *best_dist)\n{\n    double d, dx, dx2;\n\n    if (!root) return;\n    d = dist(root, nd, dim);\n    dx = root->x[i] - nd->x[i];\n    dx2 = dx * dx;\n\n    visited ++;\n\n    if (!*best || d < *best_dist) {\n        *best_dist = d;\n        *best = root;\n    }\n\n    \n    if (!*best_dist) return;\n\n    if (++i >= dim) i = 0;\n\n    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);\n    if (dx2 >= *best_dist) return;\n    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);\n}\n\n#define N 1000000\n#define rand1() (rand() / (double)RAND_MAX)\n#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }\nint main(void)\n{\n    int i;\n    struct kd_node_t wp[] = {\n        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}\n    };\n    struct kd_node_t testNode = {{9, 2}};\n    struct kd_node_t *root, *found, *million;\n    double best_dist;\n\n    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 2, &found, &best_dist);\n\n    printf(\">> WP tree\\nsearching for (%g, %g)\\n\"\n            \"found (%g, %g) dist %g\\nseen %d nodes\\n\\n\",\n            testNode.x[0], testNode.x[1],\n            found->x[0], found->x[1], sqrt(best_dist), visited);\n\n    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));\n    srand(time(0));\n    for (i = 0; i < N; i++) rand_pt(million[i]);\n\n    root = make_tree(million, N, 0, 3);\n    rand_pt(testNode);\n\n    visited = 0;\n    found = 0;\n    nearest(root, &testNode, 0, 3, &found, &best_dist);\n\n    printf(\">> Million tree\\nsearching for (%g, %g, %g)\\n\"\n            \"found (%g, %g, %g) dist %g\\nseen %d nodes\\n\",\n            testNode.x[0], testNode.x[1], testNode.x[2],\n            found->x[0], found->x[1], found->x[2],\n            sqrt(best_dist), visited);\n\n    \n    int sum = 0, test_runs = 100000;\n    for (i = 0; i < test_runs; i++) {\n        found = 0;\n        visited = 0;\n        rand_pt(testNode);\n        nearest(root, &testNode, 0, 3, &found, &best_dist);\n        sum += visited;\n    }\n    printf(\"\\n>> Million tree\\n\"\n            \"visited %d nodes for %d random findings (%f per lookup)\\n\",\n            sum, test_runs, sum/(double)test_runs);\n\n    \n\n    return 0;\n}\n"}
{"id": 60432, "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", "C": "#ifndef CALLBACK_H\n#define CALLBACK_H\n\n\nvoid map(int* array, int len, void(*callback)(int,int));\n\n#endif\n"}
{"id": 60433, "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", "C": "#ifndef SILLY_H\n#define SILLY_H\n\nextern void JumpOverTheDog( int numberOfTimes);\nextern int  PlayFetchWithDog( float weightOfStick);\n\n#endif\n"}
{"id": 60434, "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", "C": "#include <fenv.h>\t\n#include <stdio.h>\t\n \n\nvoid\nsafe_add(volatile double interval[2], volatile double a, volatile double b)\n{\n#pragma STDC FENV_ACCESS ON\n\tunsigned int orig;\n \n\torig = fegetround();\n\tfesetround(FE_DOWNWARD);\t\n\tinterval[0] = a + b;\n\tfesetround(FE_UPWARD);\t\t\n\tinterval[1] = a + b;\n\tfesetround(orig);\n}\n \nint\nmain()\n{\n\tconst double nums[][2] = {\n\t\t{1, 2},\n\t\t{0.1, 0.2},\n\t\t{1e100, 1e-100},\n\t\t{1e308, 1e308},\n\t};\n\tdouble ival[2];\n\tint i;\n \n\tfor (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {\n\t\t\n\t\tsafe_add(ival, nums[i][0], nums[i][1]);\n \n\t\t\n\t\tprintf(\"%.17g + %.17g =\\n\", nums[i][0], nums[i][1]);\n\t\tprintf(\"    [%.17g, %.17g]\\n\", ival[0], ival[1]);\n\t\tprintf(\"    size %.17g\\n\\n\", ival[1] - ival[0]);\n\t}\n\treturn 0;\n}\n"}
{"id": 60435, "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", "C": "#include <stdio.h>\n\nstatic const char *dog = \"Benjamin\";\nstatic const char *Dog = \"Samba\";\nstatic const char *DOG = \"Bernie\";\n\nint main()\n{\n    printf(\"The three dogs are named %s, %s and %s.\\n\", dog, Dog, DOG);\n    return 0;\n}\n"}
{"id": 60436, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 60437, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "C": "int i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n"}
{"id": 60438, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS  \n#include <stdio.h>\n\nint main(void)\n{\n    return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\", \n        freopen(\"sample.txt\",\"wb\",stdout));\n}\n"}
{"id": 60439, "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", "C": "int i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n"}
{"id": 60440, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 60441, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n    integer rev = 0;\n    while (n > 0) {\n        rev = rev * 10 + (n % 10);\n        n /= 10;\n    }\n    return rev;\n}\n\ntypedef struct palgen_tag {\n    integer power;\n    integer next;\n    int digit;\n    bool even;\n} palgen_t;\n\nvoid init_palgen(palgen_t* palgen, int digit) {\n    palgen->power = 10;\n    palgen->next = digit * palgen->power - 1;\n    palgen->digit = digit;\n    palgen->even = false;\n}\n\ninteger next_palindrome(palgen_t* p) {\n    ++p->next;\n    if (p->next == p->power * (p->digit + 1)) {\n        if (p->even)\n            p->power *= 10;\n        p->next = p->digit * p->power;\n        p->even = !p->even;\n    }\n    return p->next * (p->even ? 10 * p->power : p->power)\n        + reverse(p->even ? p->next : p->next/10);\n}\n\nbool gapful(integer n) {\n    integer m = n;\n    while (m >= 10)\n        m /= 10;\n    return n % (n % 10 + 10 * m) == 0;\n}\n\nvoid print(int len, integer array[][len]) {\n    for (int digit = 1; digit < 10; ++digit) {\n        printf(\"%d: \", digit);\n        for (int i = 0; i < len; ++i)\n            printf(\" %llu\", array[digit - 1][i]);\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    const int n1 = 20, n2 = 15, n3 = 10;\n    const int m1 = 100, m2 = 1000;\n\n    integer pg1[9][n1];\n    integer pg2[9][n2];\n    integer pg3[9][n3];\n\n    for (int digit = 1; digit < 10; ++digit) {\n        palgen_t pgen;\n        init_palgen(&pgen, digit);\n        for (int i = 0; i < m2; ) {\n            integer n = next_palindrome(&pgen);\n            if (!gapful(n))\n                continue;\n            if (i < n1)\n                pg1[digit - 1][i] = n;\n            else if (i < m1 && i >= m1 - n2)\n                pg2[digit - 1][i - (m1 - n2)] = n;\n            else if (i >= m2 - n3)\n                pg3[digit - 1][i - (m2 - n3)] = n;\n            ++i;\n        }\n    }\n\n    printf(\"First %d palindromic gapful numbers ending in:\\n\", n1);\n    print(n1, pg1);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n2, m1);\n    print(n2, pg2);\n\n    printf(\"\\nLast %d of first %d palindromic gapful numbers ending in:\\n\", n3, m2);\n    print(n3, pg3);\n\n    return 0;\n}\n"}
{"id": 60442, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 60443, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n \nlong long x, y, dx, dy, scale, clen, cscale;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n \nvoid sc_up()\n{\n\tscale *= 2; x *= 2; y *= 2;\n\tcscale *= 3;\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 / cscale;\n\tdouble VAL = 1;\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 \nvoid iter_string(const char * str, int d)\n{\n\tlong long len;\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\n\t\t\tif (d)\titer_string(\"XHXVX\", d - 1);\n\t\t\telse{\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx;\n\t\t\t\ty -= dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'V':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile (len--) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\ty += dy;\n\t\t\t}\n\t\t\tcontinue;\n\t\tcase 'H':\n\t\t\tlen = 1LLU << d;\n\t\t\twhile(len --) {\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx -= dx;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n \nvoid sierp(long leng, int depth)\n{\n\tlong i;\n\tlong h = leng + 20, w = leng + 20;\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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"VXH\", depth);\n \n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\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\tsierp(size, depth + 2);\n \n\treturn 0;\n}\n"}
{"id": 60444, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 60445, "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", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool is_prime(int n) {\n    int i = 5;\n\n    if (n < 2) {\n        return false;\n    }\n\n    if (n % 2 == 0) {\n        return n == 2;\n    }\n    if (n % 3 == 0) {\n        return n == 3;\n    }\n\n    while (i * i <= n) {\n        if (n % i == 0) {\n            return false;\n        }\n        i += 2;\n\n        if (n % i == 0) {\n            return false;\n        }\n        i += 4;\n    }\n\n    return true;\n}\n\nint main() {\n    const int start = 1;\n    const int stop = 1000;\n\n    int sum = 0;\n    int count = 0;\n    int sc = 0;\n    int p;\n\n    for (p = start; p < stop; p++) {\n        if (is_prime(p)) {\n            count++;\n            sum += p;\n            if (is_prime(sum)) {\n                printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n                sc++;\n            }\n        }\n    }\n    printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n    return 0;\n}\n"}
{"id": 60446, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 60447, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))\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\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n"}
{"id": 60448, "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", "C": "#include <assert.h>\n#include <stdio.h>\n\nint main(int c, char **v)\n{\n\tunsigned int n = 1 << (c - 1), i = n, j, k;\n\tassert(n);\n\n\twhile (i--) {\n\t\tif (!(i & (i + (i & -(int)i)))) \n\t\t\tcontinue;\n\n\t\tfor (j = n, k = 1; j >>= 1; k++)\n\t\t\tif (i & j) printf(\"%s \", v[k]);\n\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60449, "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", "C": "#include <stdio.h>\n\nint main(void)\n{\n\tputs(\t\"%!PS-Adobe-3.0 EPSF\\n\"\n\t\t\"%%BoundingBox: -10 -10 400 565\\n\"\n\t\t\"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\\n\"\n\t\t\"/b{a 90 rotate}def\");\n\n\tchar i;\n\tfor (i = 'c'; i <= 'z'; i++)\n\t\tprintf(\"/%c{%c %c}def\\n\", i, i-1, i-2);\n\n\tputs(\"0 setlinewidth z showpage\\n%%EOF\");\n\n\treturn 0;\n}\n"}
{"id": 60450, "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", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nbool isPrime(int64_t n) {\n    int64_t i;\n\n    if (n < 2)       return false;\n    if (n % 2 == 0)  return n == 2;\n    if (n % 3 == 0)  return n == 3;\n    if (n % 5 == 0)  return n == 5;\n    if (n % 7 == 0)  return n == 7;\n    if (n % 11 == 0) return n == 11;\n    if (n % 13 == 0) return n == 13;\n    if (n % 17 == 0) return n == 17;\n    if (n % 19 == 0) return n == 19;\n\n    for (i = 23; i * i <= n; i += 2) {\n        if (n % i == 0) return false;\n    }\n\n    return true;\n}\n\nint countTwinPrimes(int limit) {\n    int count = 0;\n\n    \n    int64_t p3 = true, p2 = true, p1 = false;\n    int64_t i;\n\n    for (i = 5; i <= limit; i++) {\n        p3 = p2;\n        p2 = p1;\n        p1 = isPrime(i);\n        if (p3 && p1) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvoid test(int limit) {\n    int count = countTwinPrimes(limit);\n    printf(\"Number of twin prime pairs less than %d is %d\\n\", limit, count);\n}\n\nint main() {\n    test(10);\n    test(100);\n    test(1000);\n    test(10000);\n    test(100000);\n    test(1000000);\n    test(10000000);\n    test(100000000);\n    return 0;\n}\n"}
{"id": 60451, "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", "C": "#include <stdio.h>\n#include <math.h>\n\nint main()\n{\n\tdouble a, c, s, PI2 = atan2(1, 1) * 8;\n\tint n, i;\n\n\tfor (n = 1; n < 10; n++) for (i = 0; i < n; i++) {\n\t\tc = s = 0;\n\t\tif (!i )\t\tc =  1;\n\t\telse if(n == 4 * i)\ts =  1;\n\t\telse if(n == 2 * i)\tc = -1;\n\t\telse if(3 * n == 4 * i)\ts = -1;\n\t\telse\n\t\t\ta = i * PI2 / n, c = cos(a), s = sin(a);\n\n\t\tif (c) printf(\"%.2g\", c);\n\t\tprintf(s == 1 ? \"i\" : s == -1 ? \"-i\" : s ? \"%+.2gi\" : \"\", s);\n\t\tprintf(i == n - 1 ?\"\\n\":\",  \");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60452, "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", "C": "#include <stdio.h>\n#include <string.h>\n\n\nvoid longmulti(const char *a, const char *b, char *c)\n{\n\tint i = 0, j = 0, k = 0, n, carry;\n\tint la, lb;\n\n\t\n\tif (!strcmp(a, \"0\") || !strcmp(b, \"0\")) {\n\t\tc[0] = '0', c[1] = '\\0';\n\t\treturn;\n\t}\n\n\t\n\tif (a[0] == '-') { i = 1; k = !k; }\n\tif (b[0] == '-') { j = 1; k = !k; }\n\n\t\n\tif (i || j) {\n\t\tif (k) c[0] = '-';\n\t\tlongmulti(a + i, b + j, c + k);\n\t\treturn;\n\t}\n\n\tla = strlen(a);\n\tlb = strlen(b);\n\tmemset(c, '0', la + lb);\n\tc[la + lb] = '\\0';\n\n#\tdefine I(a) (a - '0')\n\tfor (i = la - 1; i >= 0; i--) {\n\t\tfor (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {\n\t\t\tn = I(a[i]) * I(b[j]) + I(c[k]) + carry;\n\t\t\tcarry = n / 10;\n\t\t\tc[k] = (n % 10) + '0';\n\t\t}\n\t\tc[k] += carry;\n\t}\n#\tundef I\n\tif (c[0] == '0') memmove(c, c + 1, la + lb);\n\n\treturn;\n}\n\nint main()\n{\n\tchar c[1024];\n\tlongmulti(\"-18446744073709551616\", \"-18446744073709551616\", c);\n\tprintf(\"%s\\n\", c);\n\n\treturn 0;\n}\n"}
{"id": 60453, "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", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 60454, "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", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct Pair {\n    uint64_t v1, v2;\n};\n\nstruct Pair makePair(uint64_t a, uint64_t b) {\n    struct Pair r;\n    r.v1 = a;\n    r.v2 = b;\n    return r;\n}\n\nstruct Pair solvePell(int n) {\n    int x = (int) sqrt(n);\n\n    if (x * x == n) {\n        \n        return makePair(1, 0);\n    } else {\n        \n        int y = x;\n        int z = 1;\n        int r = 2 * x;\n        struct Pair e = makePair(1, 0);\n        struct Pair f = makePair(0, 1);\n        uint64_t a = 0;\n        uint64_t b = 0;\n\n        while (true) {\n            y = r * z - y;\n            z = (n - y * y) / z;\n            r = (x + y) / z;\n            e = makePair(e.v2, r * e.v2 + e.v1);\n            f = makePair(f.v2, r * f.v2 + f.v1);\n            a = e.v2 + x * f.v2;\n            b = f.v2;\n            if (a * a - n * b * b == 1) {\n                break;\n            }\n        }\n\n        return makePair(a, b);\n    }\n}\n\nvoid test(int n) {\n    struct Pair r = solvePell(n);\n    printf(\"x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\\n\", n, r.v1, r.v2);\n}\n\nint main() {\n    test(61);\n    test(109);\n    test(181);\n    test(277);\n\n    return 0;\n}\n"}
{"id": 60455, "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", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n"}
{"id": 60456, "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", "C": "#include <stdio.h>\n\nvoid bubble_sort (int *a, int n) {\n    int i, t, j = n, s = 1;\n    while (s) {\n        s = 0;\n        for (i = 1; i < j; i++) {\n            if (a[i] < a[i - 1]) {\n                t = a[i];\n                a[i] = a[i - 1];\n                a[i - 1] = t;\n                s = 1;\n            }\n        }\n        j--;\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    bubble_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": 60457, "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", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 60458, "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", "C": "#include <math.h>\n#include <stdio.h>\n\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\n\nunsigned int divisor_product(unsigned int n) {\n    return pow(n, divisor_count(n) / 2.0);\n}\n\nint main() {\n    const unsigned int limit = 50;\n    unsigned int n;\n\n    printf(\"Product of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%11d\", divisor_product(n));\n        if (n % 5 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 60459, "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", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n"}
{"id": 60460, "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", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a/b = %d\\n\", a/b); \n  printf(\"a%%b = %d\\n\", a%b); \n  return 0;\n}\n"}
{"id": 60461, "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", "C": "#include <stdio.h>\n\nvoid transpose(void *dest, void *src, int src_h, int src_w)\n{\n\tint i, j;\n\tdouble (*d)[src_h] = dest, (*s)[src_w] = src;\n\tfor (i = 0; i < src_h; i++)\n\t\tfor (j = 0; j < src_w; j++)\n\t\t\td[j][i] = s[i][j];\n}\n\nint main()\n{\n\tint i, j;\n\tdouble a[3][5] = {{ 0, 1, 2, 3, 4 },\n\t\t\t  { 5, 6, 7, 8, 9 },\n\t\t\t  { 1, 0, 0, 0, 42}};\n\tdouble b[5][3];\n\ttranspose(b, a, 3, 5);\n\n\tfor (i = 0; i < 5; i++)\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%g%c\", b[i][j], j == 2 ? '\\n' : ' ');\n\treturn 0;\n}\n"}
{"id": 60462, "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", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct arg\n{\n  int       (*fn)(struct arg*);\n  int        *k;\n  struct arg *x1, *x2, *x3, *x4, *x5;\n} ARG;\n\n\nint f_1 (ARG* _) { return -1; }\nint f0  (ARG* _) { return  0; }\nint f1  (ARG* _) { return  1; }\n\n\nint eval(ARG* a) { return a->fn(a); }\n#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})\n#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)\n\nint A(ARG*);\n\n\nint B(ARG* a)\n{\n  int k = *a->k -= 1;\n  return A(FUN(a, a->x1, a->x2, a->x3, a->x4));\n}\n\nint A(ARG* a)\n{\n  return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);\n}\n\nint main(int argc, char **argv)\n{\n  int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;\n  printf(\"%d\\n\", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),\n                       MAKE_ARG(f1), MAKE_ARG(f0))));\n  return 0;\n}\n"}
{"id": 60463, "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", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x ? \"true\" : \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \n  TEST(true, false, ||); \n  TEST(true, false, &&); \n  TEST(false, false, ||); \n\n  return 0;\n}\n"}
{"id": 60464, "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", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 60465, "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", "C": "#include <stdio.h>\n\nvoid recurse(unsigned int i)\n{\n  printf(\"%d\\n\", i);\n  recurse(i+1); \n}\n\nint main()\n{\n  recurse(0);\n  return 0;\n}\n"}
{"id": 60466, "name": "Carmichael 3 strong pseudoprimes", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc mod(n, m int) int {\n    return ((n % m) + m) % m\n}\n\nfunc isPrime(n int) bool {\n    if n < 2 { return false }\n    if n % 2 == 0 { return n == 2 }\n    if n % 3 == 0 { return n == 3 }\n    d := 5\n    for d * d <= n {\n        if n % d == 0 { return false }\n        d += 2\n        if n % d == 0 { return false }\n        d += 4\n    }\n    return true\n}\n\nfunc carmichael(p1 int) {\n    for h3 := 2; h3 < p1; h3++ {\n        for d := 1; d < h3 + p1; d++ {\n            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {\n                p2 := 1 + (p1 - 1) * (h3 + p1) / d\n                if !isPrime(p2) { continue }\n                p3 := 1 + p1 * p2 / h3\n                if !isPrime(p3) { continue }\n                if p2 * p3 % (p1 - 1) != 1 { continue }\n                c := p1 * p2 * p3\n                fmt.Printf(\"%2d   %4d   %5d     %d\\n\", p1, p2, p3, c)\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The following are Carmichael munbers for p1 <= 61:\\n\")\n    fmt.Println(\"p1     p2      p3     product\")\n    fmt.Println(\"==     ==      ==     =======\")\n\n    for p1 := 2; p1 <= 61; p1++ {\n        if isPrime(p1) { carmichael(p1) }\n    }\n}\n", "C": "#include <stdio.h>\n\n\n#define mod(n,m) ((((n) % (m)) + (m)) % (m))\n\nint is_prime(unsigned int n)\n{\n    if (n <= 3) {\n        return n > 1;\n    }\n    else if (!(n % 2) || !(n % 3)) {\n        return 0;\n    }\n    else {\n        unsigned int i;\n        for (i = 5; i*i <= n; i += 6)\n            if (!(n % i) || !(n % (i + 2)))\n                return 0;\n        return 1;\n    }\n}\n\nvoid carmichael3(int p1)\n{\n    if (!is_prime(p1)) return;\n\n    int h3, d, p2, p3;\n    for (h3 = 1; h3 < p1; ++h3) {\n        for (d = 1; d < h3 + p1; ++d) {\n            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {\n                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);\n                if (!is_prime(p2)) continue;\n                p3 = 1 + (p1 * p2 / h3);\n                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;\n                printf(\"%d %d %d\\n\", p1, p2, p3);\n            }\n        }\n    }\n}\n\nint main(void)\n{\n    int p1;\n    for (p1 = 2; p1 < 62; ++p1)\n        carmichael3(p1);\n    return 0;\n}\n"}
{"id": 60467, "name": "Arithmetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 60468, "name": "Arithmetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"sort\"\n)\n\nfunc main() {\n    arithmetic := []int{1}\n    primes := []int{}\n    limit := int(1e6)\n    for n := 3; len(arithmetic) < limit; n++ {\n        divs := rcu.Divisors(n)\n        if len(divs) == 2 {\n            primes = append(primes, n)\n            arithmetic = append(arithmetic, n)\n        } else {\n            mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n            if mean == math.Trunc(mean) {\n                arithmetic = append(arithmetic, n)\n            }\n        }\n    }\n    fmt.Println(\"The first 100 arithmetic numbers are:\")\n    rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n        last := arithmetic[x-1]\n        lastc := rcu.Commatize(last)\n        fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n        pcount := sort.SearchInts(primes, last) + 1\n        if !rcu.IsPrime(last) {\n            pcount--\n        }\n        comp := x - pcount - 1 \n        compc := rcu.Commatize(comp)\n        fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid divisor_count_and_sum(unsigned int n, unsigned int* pcount,\n                           unsigned int* psum) {\n    unsigned int divisor_count = 1;\n    unsigned int divisor_sum = 1;\n    unsigned int power = 2;\n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        ++divisor_count;\n        divisor_sum += power;\n    }\n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1, sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            ++count;\n            sum += power;\n        }\n        divisor_count *= count;\n        divisor_sum *= sum;\n    }\n    if (n > 1) {\n        divisor_count *= 2;\n        divisor_sum *= n + 1;\n    }\n    *pcount = divisor_count;\n    *psum = divisor_sum;\n}\n\nint main() {\n    unsigned int arithmetic_count = 0;\n    unsigned int composite_count = 0;\n\n    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {\n        unsigned int divisor_count;\n        unsigned int divisor_sum;\n        divisor_count_and_sum(n, &divisor_count, &divisor_sum);\n        if (divisor_sum % divisor_count != 0)\n            continue;\n        ++arithmetic_count;\n        if (divisor_count > 2)\n            ++composite_count;\n        if (arithmetic_count <= 100) {\n            printf(\"%3u \", n);\n            if (arithmetic_count % 10 == 0)\n                printf(\"\\n\");\n        }\n        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||\n            arithmetic_count == 100000 || arithmetic_count == 1000000) {\n            printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n            printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n,\n                   composite_count);\n        }\n    }\n    return 0;\n}\n"}
{"id": 60469, "name": "Image noise", "Go": "package main\n\nimport (\n    \"code.google.com/p/x-go-binding/ui/x11\"\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nvar randcol = genrandcol()\n\nfunc genrandcol() <-chan color.Color {\n    c := make(chan color.Color)\n\n    go func() {\n        for {\n            select {\n            case c <- image.Black:\n            case c <- image.White:\n            }\n        }\n    }()\n\n    return c\n}\n\nfunc gennoise(screen draw.Image) {\n    for y := 0; y < 240; y++ {\n        for x := 0; x < 320; x++ {\n            screen.Set(x, y, <-randcol)\n        }\n    }\n}\n\nfunc fps() chan<- bool {\n    up := make(chan bool)\n\n    go func() {\n        var frames int64\n        var lasttime time.Time\n        var totaltime time.Duration\n\n        for {\n            <-up\n            frames++\n            now := time.Now()\n            totaltime += now.Sub(lasttime)\n            if totaltime > time.Second {\n                fmt.Printf(\"FPS: %v\\n\", float64(frames)/totaltime.Seconds())\n                frames = 0\n                totaltime = 0\n            }\n            lasttime = now\n        }\n    }()\n\n    return up\n}\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    defer win.Close()\n\n    go func() {\n        upfps := fps()\n        screen := win.Screen()\n\n        for {\n            gennoise(screen)\n\n            win.FlushImage()\n\n            upfps <- true\n        }\n    }()\n\n    for _ = range win.EventChan() {\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <SDL/SDL.h>\n \nunsigned int frames = 0;\nunsigned int t_acc = 0;\n \nvoid print_fps ()\n{\n  static Uint32 last_t = 0;\n  Uint32 t = SDL_GetTicks();\n  Uint32 dt = t - last_t;\n  t_acc += dt;\n  if (t_acc > 1000)\n  {\n    unsigned int el_time = t_acc / 1000;\n    printf(\"- fps: %g\\n\",\n            (float) frames / (float) el_time);\n    t_acc = 0;\n    frames = 0;\n  }\n  last_t = t;\n}\n \nvoid blit_noise(SDL_Surface *surf)\n{\n  unsigned int i;\n  long dim = surf->w * surf->h;\n  while (1)\n  {\n    SDL_LockSurface(surf);\n    for (i=0; i < dim; ++i) {\n      ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);\n    }\n    SDL_UnlockSurface(surf);\n    SDL_Flip(surf);\n    ++frames;\n    print_fps();\n  }\n}\n \nint main(void)\n{\n  SDL_Surface *surf = NULL;\n  srand((unsigned int)time(NULL));\n  SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);\n  surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);\n  blit_noise(surf);\n}\n"}
{"id": 60470, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60471, "name": "Keyboard input_Obtain a Y or N response", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    s, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    var k gc.Key\n    for {\n        gc.FlushInput()\n        s.MovePrint(20, 0, \"Press y/n \")\n        s.Refresh()\n        switch k = s.GetChar(); k {\n        default:\n            continue\n        case 'y', 'Y', 'n', 'N':\n        }\n        break\n    }\n    s.Printf(\"\\nThanks for the %c!\\n\", k)\n    s.Refresh()\n    s.GetChar()\n}\n", "C": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/time.h>\n \nvoid set_mode(int want_key)\n{\n\tstatic struct termios old, new;\n\tif (!want_key) {\n\t\ttcsetattr(STDIN_FILENO, TCSANOW, &old);\n\t\treturn;\n\t}\n \n\ttcgetattr(STDIN_FILENO, &old);\n\tnew = old;\n\tnew.c_lflag &= ~(ICANON);\n\ttcsetattr(STDIN_FILENO, TCSANOW, &new);\n}\n \nint get_key(int no_timeout)\n{\n\tint c = 0;\n\tstruct timeval tv;\n\tfd_set fs;\n\ttv.tv_usec = tv.tv_sec = 0;\n \n\tFD_ZERO(&fs);\n\tFD_SET(STDIN_FILENO, &fs);\n\n\tselect(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);\n\tif (FD_ISSET(STDIN_FILENO, &fs)) {\n\t\tc = getchar();\n\t\tset_mode(0);\n\t}\n\treturn c;\n}\n \nint main()\n{\n\tint c;\n\twhile(1) {\n\t\tset_mode(1);\n\t\twhile (get_key(0)); \n\t\tprintf(\"Prompt again [Y/N]? \");\n\t\tfflush(stdout);\n\n\t\tc = get_key(1);\n\t\tif (c == 'Y' || c == 'y') {\n\t\t\tprintf(\"\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == 'N' || c == 'n') {\n\t\t\tprintf(\"\\nDone\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\nYes or no?\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60472, "name": "Perfect numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc computePerfect(n int64) bool {\n    var sum int64\n    for i := int64(1); i < n; i++ {\n        if n%i == 0 {\n            sum += i\n        }\n    }\n    return sum == n\n}\n\n\n\nfunc isPerfect(n int64) bool {\n    switch n {\n    case 6, 28, 496, 8128, 33550336, 8589869056,\n        137438691328, 2305843008139952128:\n        return true\n    }\n    return false\n}\n\n\nfunc main() {\n    for n := int64(1); ; n++ {\n        if isPerfect(n) != computePerfect(n) {\n            panic(\"bug\")\n        }\n        if n%1e3 == 0 {\n            fmt.Println(\"tested\", n)\n        }\n    }\n}\n", "C": "#include \"stdio.h\"\n#include \"math.h\"\n\nint perfect(int n) {\n    int max = (int)sqrt((double)n) + 1;\n    int tot = 1;\n    int i;\n\n    for (i = 2; i < max; i++)\n        if ( (n % i) == 0 ) {\n            tot += i;\n            int q = n / i;\n            if (q > i)\n                tot += q;\n        }\n\n    return tot == n;\n}\n\nint main() {\n    int n;\n    for (n = 2; n < 33550337; n++)\n        if (perfect(n))\n            printf(\"%d\\n\", n);\n\n    return 0;\n}\n"}
{"id": 60473, "name": "Conjugate transpose", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n"}
{"id": 60474, "name": "Conjugate transpose", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\n\ntype matrix struct {\n    ele  []complex128\n    cols int\n}\n\n\nfunc (m *matrix) conjTranspose() *matrix {\n    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n    rx := 0\n    for _, e := range m.ele {\n        r.ele[rx] = cmplx.Conj(e)\n        rx += r.cols\n        if rx >= len(r.ele) {\n            rx -= len(r.ele) - 1\n        }\n    }\n    return r\n}\n\n\nfunc main() {\n    show(\"h\", matrixFromRows([][]complex128{\n        {3, 2 + 1i},\n        {2 - 1i, 1}}))\n\n    show(\"n\", matrixFromRows([][]complex128{\n        {1, 1, 0},\n        {0, 1, 1},\n        {1, 0, 1}}))\n\n    show(\"u\", matrixFromRows([][]complex128{\n        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n        {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n    m.print(name)\n    ct := m.conjTranspose()\n    ct.print(name + \"_ct\")\n\n    fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n    mct := m.mult(ct)\n    ctm := ct.mult(m)\n    fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n    i := eye(m.cols)\n    fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n\nfunc matrixFromRows(rows [][]complex128) *matrix {\n    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n    for rx, row := range rows {\n        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n    }\n    return m\n}\n\nfunc eye(n int) *matrix {\n    r := &matrix{make([]complex128, n*n), n}\n    n++\n    for x := 0; x < len(r.ele); x += n {\n        r.ele[x] = 1\n    }\n    return r\n}\n\n\nfunc (m *matrix) print(heading string) {\n    fmt.Print(\"\\n\", heading, \"\\n\")\n    for e := 0; e < len(m.ele); e += m.cols {\n        fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n        fmt.Println()\n    }\n}\n\n\nfunc (a *matrix) equal(b *matrix, ε float64) bool {\n    for x, aEle := range a.ele {\n        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||\n            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n                m1x++\n            }\n            m3x++\n        }\n    }\n    return m3\n}\n", "C": "\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<complex.h>\n\ntypedef struct\n{\n  int rows, cols;\n  complex **z;\n} matrix;\n\nmatrix\ntranspose (matrix a)\n{\n  int i, j;\n  matrix b;\n\n  b.rows = a.cols;\n  b.cols = a.rows;\n\n  b.z = malloc (b.rows * sizeof (complex *));\n\n  for (i = 0; i < b.rows; i++)\n    {\n      b.z[i] = malloc (b.cols * sizeof (complex));\n      for (j = 0; j < b.cols; j++)\n        {\n          b.z[i][j] = conj (a.z[j][i]);\n        }\n    }\n\n  return b;\n}\n\nint\nisHermitian (matrix a)\n{\n  int i, j;\n  matrix b = transpose (a);\n\n  if (b.rows == a.rows && b.cols == a.cols)\n    {\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if (b.z[i][j] != a.z[i][j])\n                return 0;\n            }\n        }\n    }\n\n  else\n    return 0;\n\n  return 1;\n}\n\nmatrix\nmultiply (matrix a, matrix b)\n{\n  matrix c;\n  int i, j;\n\n  if (a.cols == b.rows)\n    {\n      c.rows = a.rows;\n      c.cols = b.cols;\n\n      c.z = malloc (c.rows * (sizeof (complex *)));\n\n      for (i = 0; i < c.rows; i++)\n        {\n          c.z[i] = malloc (c.cols * sizeof (complex));\n          c.z[i][j] = 0 + 0 * I;\n          for (j = 0; j < b.cols; j++)\n            {\n              c.z[i][j] += a.z[i][j] * b.z[j][i];\n            }\n        }\n\n    }\n\n  return c;\n}\n\nint\nisNormal (matrix a)\n{\n  int i, j;\n  matrix a_ah, ah_a;\n\n  if (a.rows != a.cols)\n    return 0;\n\n  a_ah = multiply (a, transpose (a));\n  ah_a = multiply (transpose (a), a);\n\n  for (i = 0; i < a.rows; i++)\n    {\n      for (j = 0; j < a.cols; j++)\n        {\n          if (a_ah.z[i][j] != ah_a.z[i][j])\n            return 0;\n        }\n    }\n\n  return 1;\n}\n\nint\nisUnitary (matrix a)\n{\n  matrix b;\n  int i, j;\n  if (isNormal (a) == 1)\n    {\n      b = multiply (a, transpose(a));\n\n      for (i = 0; i < b.rows; i++)\n        {\n          for (j = 0; j < b.cols; j++)\n            {\n              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))\n                return 0;\n            }\n        }\n      return 1;\n    }\n  return 0;\n}\n\n\nint\nmain ()\n{\n  complex z = 3 + 4 * I;\n  matrix a, aT;\n  int i, j;\n  printf (\"Enter rows and columns :\");\n  scanf (\"%d%d\", &a.rows, &a.cols);\n\n  a.z = malloc (a.rows * sizeof (complex *));\n  printf (\"Randomly Generated Complex Matrix A is : \");\n  for (i = 0; i < a.rows; i++)\n    {\n      printf (\"\\n\");\n      a.z[i] = malloc (a.cols * sizeof (complex));\n      for (j = 0; j < a.cols; j++)\n        {\n          a.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (a.z[i][j]), cimag (a.z[i][j]));\n        }\n    }\n\n  aT = transpose (a);\n\n  printf (\"\\n\\nTranspose of Complex Matrix A is : \");\n  for (i = 0; i < aT.rows; i++)\n    {\n      printf (\"\\n\");\n      aT.z[i] = malloc (aT.cols * sizeof (complex));\n      for (j = 0; j < aT.cols; j++)\n        {\n          aT.z[i][j] = rand () % 10 + rand () % 10 * I;\n          printf (\"\\t%f + %fi\", creal (aT.z[i][j]), cimag (aT.z[i][j]));\n        }\n    }\n\n  printf (\"\\n\\nComplex Matrix A %s hermitian\",\n          isHermitian (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s unitary\",\n          isUnitary (a) == 1 ? \"is\" : \"is not\");\n  printf (\"\\n\\nComplex Matrix A %s normal\",\n          isNormal (a) == 1 ? \"is\" : \"is not\");\n\n\n\n  return 0;\n}\n"}
{"id": 60475, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 60476, "name": "Jacobsthal numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    s := big.NewInt(1)\n    if n%2 != 0 {\n        s.Neg(s)\n    }\n    t.Sub(t, s)\n    return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n    t := big.NewInt(1)\n    t.Lsh(t, n)\n    a := big.NewInt(1)\n    if n%2 != 0 {\n        a.Neg(a)\n    }\n    return t.Add(t, a)\n}\n\nfunc main() {\n    jac := make([]*big.Int, 30)\n    fmt.Println(\"First 30 Jacobsthal numbers:\")\n    for i := uint(0); i < 30; i++ {\n        jac[i] = jacobsthal(i)\n        fmt.Printf(\"%9d \", jac[i])\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n    for i := uint(0); i < 30; i++ {\n        fmt.Printf(\"%9d \", jacobsthalLucas(i))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n    for i := uint(0); i < 20; i++ {\n        t := big.NewInt(0)\n        fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n        if (i+1)%5 == 0 {\n            fmt.Println()\n        }\n    }\n\n    fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n    for n, count := uint(0), 0; count < 20; n++ {\n        j := jacobsthal(n)\n        if j.ProbablyPrime(10) {\n            fmt.Println(j)\n            count++\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <gmp.h>\n\nvoid jacobsthal(mpz_t r, unsigned long n) {\n    mpz_t s;\n    mpz_init(s);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(s, 1);\n    if (n % 2) mpz_neg(s, s);\n    mpz_sub(r, r, s);\n    mpz_div_ui(r, r, 3);\n}\n\nvoid jacobsthal_lucas(mpz_t r, unsigned long n) {\n    mpz_t a;\n    mpz_init(a);\n    mpz_set_ui(r, 1);\n    mpz_mul_2exp(r, r, n);\n    mpz_set_ui(a, 1);\n    if (n % 2) mpz_neg(a, a);\n    mpz_add(r, r, a);\n}\n\nint main() {\n    int i, count;\n    mpz_t jac[30], j;\n    printf(\"First 30 Jacobsthal numbers:\\n\");\n    for (i = 0; i < 30; ++i) {\n        mpz_init(jac[i]);\n        jacobsthal(jac[i], i);\n        gmp_printf(\"%9Zd \", jac[i]);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 30 Jacobsthal-Lucas numbers:\\n\");\n    mpz_init(j);\n    for (i = 0; i < 30; ++i) {\n        jacobsthal_lucas(j, i);\n        gmp_printf(\"%9Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal oblong numbers:\\n\");\n    for (i = 0; i < 20; ++i) {\n        mpz_mul(j, jac[i], jac[i+1]);\n        gmp_printf(\"%11Zd \", j);\n        if (!((i+1)%5)) printf(\"\\n\");\n    }\n\n    printf(\"\\nFirst 20 Jacobsthal primes:\\n\");\n    for (i = 0, count = 0; count < 20; ++i) {\n        jacobsthal(j, i);\n        if (mpz_probab_prime_p(j, 15) > 0) {\n            gmp_printf(\"%Zd\\n\", j);\n            ++count;\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 60477, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 60478, "name": "Sorting algorithms_Bead sort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar a = []int{170, 45, 75, 90, 802, 24, 2, 66}\nvar aMax = 1000\n\nconst bead = 'o'\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    beadSort()\n    fmt.Println(\"after: \", a)\n}\n\nfunc beadSort() {\n    \n    all := make([]byte, aMax*len(a))\n    \n    \n    abacus := make([][]byte, aMax)\n    for pole, space := 0, all; pole < aMax; pole++ {\n        abacus[pole] = space[:len(a)]\n        space = space[len(a):]\n    }\n    \n    var wg sync.WaitGroup\n    \n    \n    \n    wg.Add(len(a))\n    for row, n := range a {\n        go func(row, n int) {\n            for pole := 0; pole < n; pole++ {\n                abacus[pole][row] = bead\n            }\n            wg.Done()\n        }(row, n)\n    }\n    wg.Wait()\n    \n    wg.Add(aMax)\n    for _, pole := range abacus {\n        go func(pole []byte) {\n            \n            top := 0\n            for row, space := range pole {\n                if space == bead {\n                    \n                    \n                    \n                    \n                    \n                    pole[row] = 0\n                    pole[top] = bead\n                    top++\n                }\n            }\n            wg.Done()\n        }(pole)\n    }\n    wg.Wait()\n    \n    for row := range a {\n        x := 0\n        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {\n            x++\n        }\n        a[len(a)-1-row] = x\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid bead_sort(int *a, int len)\n{\n\tint i, j, max, sum;\n\tunsigned char *beads;\n#\tdefine BEAD(i, j) beads[i * max + j]\n\n\tfor (i = 1, max = a[0]; i < len; i++)\n\t\tif (a[i] > max) max = a[i];\n\n\tbeads = calloc(1, max * len);\n\n\t\n\tfor (i = 0; i < len; i++)\n\t\tfor (j = 0; j < a[i]; j++)\n\t\t\tBEAD(i, j) = 1;\n\n\tfor (j = 0; j < max; j++) {\n\t\t\n\t\tfor (sum = i = 0; i < len; i++) {\n\t\t\tsum += BEAD(i, j);\n\t\t\tBEAD(i, j) = 0;\n\t\t}\n\t\t\n\t\tfor (i = len - sum; i < len; i++) BEAD(i, j) = 1;\n\t}\n\n\tfor (i = 0; i < len; i++) {\n\t\tfor (j = 0; j < max && BEAD(i, j); j++);\n\t\ta[i] = j;\n\t}\n\tfree(beads);\n}\n\nint main()\n{\n\tint i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};\n\tint len = sizeof(x)/sizeof(x[0]);\n\n\tbead_sort(x, len);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\\n\", x[i]);\n\n\treturn 0;\n}\n"}
{"id": 60479, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 60480, "name": "Cistercian numerals", "Go": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n    for i := 0; i < 15; i++ {\n        n[i] = make([]string, 11)\n        for j := 0; j < 11; j++ {\n            n[i][j] = \" \"\n        }\n        n[i][5] = \"x\"\n    }\n}\n\nfunc horiz(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc verti(r1, r2, c int) {\n    for r := r1; r <= r2; r++ {\n        n[r][c] = \"x\"\n    }\n}\n\nfunc diagd(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r+c-c1][c] = \"x\"\n    }\n}\n\nfunc diagu(c1, c2, r int) {\n    for c := c1; c <= c2; c++ {\n        n[r-c+c1][c] = \"x\"\n    }\n}\n\nvar draw map[int]func() \n\nfunc initDraw() {\n    draw = map[int]func(){\n        1: func() { horiz(6, 10, 0) },\n        2: func() { horiz(6, 10, 4) },\n        3: func() { diagd(6, 10, 0) },\n        4: func() { diagu(6, 10, 4) },\n        5: func() { draw[1](); draw[4]() },\n        6: func() { verti(0, 4, 10) },\n        7: func() { draw[1](); draw[6]() },\n        8: func() { draw[2](); draw[6]() },\n        9: func() { draw[1](); draw[8]() },\n\n        10: func() { horiz(0, 4, 0) },\n        20: func() { horiz(0, 4, 4) },\n        30: func() { diagu(0, 4, 4) },\n        40: func() { diagd(0, 4, 0) },\n        50: func() { draw[10](); draw[40]() },\n        60: func() { verti(0, 4, 0) },\n        70: func() { draw[10](); draw[60]() },\n        80: func() { draw[20](); draw[60]() },\n        90: func() { draw[10](); draw[80]() },\n\n        100: func() { horiz(6, 10, 14) },\n        200: func() { horiz(6, 10, 10) },\n        300: func() { diagu(6, 10, 14) },\n        400: func() { diagd(6, 10, 10) },\n        500: func() { draw[100](); draw[400]() },\n        600: func() { verti(10, 14, 10) },\n        700: func() { draw[100](); draw[600]() },\n        800: func() { draw[200](); draw[600]() },\n        900: func() { draw[100](); draw[800]() },\n\n        1000: func() { horiz(0, 4, 14) },\n        2000: func() { horiz(0, 4, 10) },\n        3000: func() { diagd(0, 4, 10) },\n        4000: func() { diagu(0, 4, 14) },\n        5000: func() { draw[1000](); draw[4000]() },\n        6000: func() { verti(10, 14, 0) },\n        7000: func() { draw[1000](); draw[6000]() },\n        8000: func() { draw[2000](); draw[6000]() },\n        9000: func() { draw[1000](); draw[8000]() },\n    }\n}\n\nfunc printNumeral() {\n    for i := 0; i < 15; i++ {\n        for j := 0; j < 11; j++ {\n            fmt.Printf(\"%s \", n[i][j])\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    initDraw()\n    numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n    for _, number := range numbers {\n        initN()\n        fmt.Printf(\"%d:\\n\", number)\n        thousands := number / 1000\n        number %= 1000\n        hundreds := number / 100\n        number %= 100\n        tens := number / 10\n        ones := number % 10\n        if thousands > 0 {\n            draw[thousands*1000]()\n        }\n        if hundreds > 0 {\n            draw[hundreds*100]()\n        }\n        if tens > 0 {\n            draw[tens*10]()\n        }\n        if ones > 0 {\n            draw[ones]()\n        }\n        printNumeral()\n    }\n}\n", "C": "#include <stdio.h>\n\n#define GRID_SIZE 15\nchar canvas[GRID_SIZE][GRID_SIZE];\n\nvoid initN() {\n    int i, j;\n    for (i = 0; i < GRID_SIZE; i++) {\n        for (j = 0; j < GRID_SIZE; j++) {\n            canvas[i][j] = ' ';\n        }\n        canvas[i][5] = 'x';\n    }\n}\n\nvoid horizontal(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid vertical(size_t r1, size_t r2, size_t c) {\n    size_t r;\n    for (r = r1; r <= r2; r++) {\n        canvas[r][c] = 'x';\n    }\n}\n\nvoid diagd(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r + c - c1][c] = 'x';\n    }\n}\n\nvoid diagu(size_t c1, size_t c2, size_t r) {\n    size_t c;\n    for (c = c1; c <= c2; c++) {\n        canvas[r - c + c1][c] = 'x';\n    }\n}\n\nvoid drawOnes(int v) {\n    switch (v) {\n    case 1:\n        horizontal(6, 10, 0);\n        break;\n    case 2:\n        horizontal(6, 10, 4);\n        break;\n    case 3:\n        diagd(6, 10, 0);\n        break;\n    case 4:\n        diagu(6, 10, 4);\n        break;\n    case 5:\n        drawOnes(1);\n        drawOnes(4);\n        break;\n    case 6:\n        vertical(0, 4, 10);\n        break;\n    case 7:\n        drawOnes(1);\n        drawOnes(6);\n        break;\n    case 8:\n        drawOnes(2);\n        drawOnes(6);\n        break;\n    case 9:\n        drawOnes(1);\n        drawOnes(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawTens(int v) {\n    switch (v) {\n    case 1:\n        horizontal(0, 4, 0);\n        break;\n    case 2:\n        horizontal(0, 4, 4);\n        break;\n    case 3:\n        diagu(0, 4, 4);\n        break;\n    case 4:\n        diagd(0, 4, 0);\n        break;\n    case 5:\n        drawTens(1);\n        drawTens(4);\n        break;\n    case 6:\n        vertical(0, 4, 0);\n        break;\n    case 7:\n        drawTens(1);\n        drawTens(6);\n        break;\n    case 8:\n        drawTens(2);\n        drawTens(6);\n        break;\n    case 9:\n        drawTens(1);\n        drawTens(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawHundreds(int hundreds) {\n    switch (hundreds) {\n    case 1:\n        horizontal(6, 10, 14);\n        break;\n    case 2:\n        horizontal(6, 10, 10);\n        break;\n    case 3:\n        diagu(6, 10, 14);\n        break;\n    case 4:\n        diagd(6, 10, 10);\n        break;\n    case 5:\n        drawHundreds(1);\n        drawHundreds(4);\n        break;\n    case 6:\n        vertical(10, 14, 10);\n        break;\n    case 7:\n        drawHundreds(1);\n        drawHundreds(6);\n        break;\n    case 8:\n        drawHundreds(2);\n        drawHundreds(6);\n        break;\n    case 9:\n        drawHundreds(1);\n        drawHundreds(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid drawThousands(int thousands) {\n    switch (thousands) {\n    case 1:\n        horizontal(0, 4, 14);\n        break;\n    case 2:\n        horizontal(0, 4, 10);\n        break;\n    case 3:\n        diagd(0, 4, 10);\n        break;\n    case 4:\n        diagu(0, 4, 14);\n        break;\n    case 5:\n        drawThousands(1);\n        drawThousands(4);\n        break;\n    case 6:\n        vertical(10, 14, 0);\n        break;\n    case 7:\n        drawThousands(1);\n        drawThousands(6);\n        break;\n    case 8:\n        drawThousands(2);\n        drawThousands(6);\n        break;\n    case 9:\n        drawThousands(1);\n        drawThousands(8);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid draw(int v) {\n    int thousands = v / 1000;\n    v %= 1000;\n\n    int hundreds = v / 100;\n    v %= 100;\n\n    int tens = v / 10;\n    int ones = v % 10;\n\n    if (thousands > 0) {\n        drawThousands(thousands);\n    }\n    if (hundreds > 0) {\n        drawHundreds(hundreds);\n    }\n    if (tens > 0) {\n        drawTens(tens);\n    }\n    if (ones > 0) {\n        drawOnes(ones);\n    }\n}\n\nvoid write(FILE *out) {\n    int i;\n    for (i = 0; i < GRID_SIZE; i++) {\n        fprintf(out, \"%-.*s\", GRID_SIZE, canvas[i]);\n        putc('\\n', out);\n    }\n}\n\nvoid test(int n) {\n    printf(\"%d:\\n\", n);\n    initN();\n    draw(n);\n    write(stdout);\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    test(0);\n    test(1);\n    test(20);\n    test(300);\n    test(4000);\n    test(5555);\n    test(6789);\n    test(9999);\n\n    return 0;\n}\n"}
{"id": 60481, "name": "Arbitrary-precision integers (included)", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tx := big.NewInt(2)\n\tx = x.Exp(big.NewInt(3), x, nil)\n\tx = x.Exp(big.NewInt(4), x, nil)\n\tx = x.Exp(big.NewInt(5), x, nil)\n\tstr := x.String()\n\tfmt.Printf(\"5^(4^(3^2)) has %d digits: %s ... %s\\n\",\n\t\tlen(str),\n\t\tstr[:20],\n\t\tstr[len(str)-20:],\n\t)\n}\n", "C": "#include <gmp.h>\n#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n\tmpz_t a;\n\tmpz_init_set_ui(a, 5);\n\tmpz_pow_ui(a, a, 1 << 18); \n\n\tint len = mpz_sizeinbase(a, 10);\n\tprintf(\"GMP says size is: %d\\n\", len);\n\n\t\n\tchar *s = mpz_get_str(0, 10, a);\n\tprintf(\"size really is %d\\n\", len = strlen(s));\n\tprintf(\"Digits: %.20s...%s\\n\", s, s + len - 20);\n\n\t\n\treturn 0;\n}\n"}
{"id": 60482, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 60483, "name": "Draw a sphere", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.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#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j / 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n"}
{"id": 60484, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 60485, "name": "Inverted index", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nvar index map[string][]int \nvar indexed []doc\n\ntype doc struct {\n    file  string\n    title string\n}\n\nfunc main() {\n    \n    index = make(map[string][]int)\n\n    \n    if err := indexDir(\"docs\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \n    ui()\n}\n\nfunc indexDir(dir string) error {\n    df, err := os.Open(dir)\n    if err != nil {\n        return err\n    }\n    fis, err := df.Readdir(-1)\n    if err != nil {\n        return err\n    }\n    if len(fis) == 0 {\n        return errors.New(fmt.Sprintf(\"no files in %s\", dir))\n    }\n    indexed := 0\n    for _, fi := range fis {\n        if !fi.IsDir() {\n            if indexFile(dir + \"/\" + fi.Name()) {\n                indexed++\n            }\n        }\n    }\n    return nil\n}\n\nfunc indexFile(fn string) bool {\n    f, err := os.Open(fn)\n    if err != nil {\n        fmt.Println(err)\n        return false \n    }\n\n    \n    x := len(indexed)\n    indexed = append(indexed, doc{fn, fn})\n    pdoc := &indexed[x]\n\n    \n    r := bufio.NewReader(f)\n    lines := 0\n    for {\n        b, isPrefix, err := r.ReadLine()\n        switch {\n        case err == io.EOF:\n            return true\n        case err != nil:\n            fmt.Println(err)\n            return true\n        case isPrefix:\n            fmt.Printf(\"%s: unexpected long line\\n\", fn)\n            return true\n        case lines < 20 && bytes.HasPrefix(b, []byte(\"Title:\")):\n            \n            \n            \n            pdoc.title = string(b[7:])\n        }\n        \n        \n        \n    wordLoop:\n        for _, bword := range bytes.Fields(b) {\n            bword := bytes.Trim(bword, \".,-~?!\\\"'`;:()<>[]{}\\\\|/=_+*&^%$#@\")\n            if len(bword) > 0 {\n                word := string(bword)\n                dl := index[word]\n                for _, d := range dl {\n                    if d == x {\n                        continue wordLoop\n                    }\n                }\n                index[word] = append(dl, x)\n            }\n        }\n    }\n    return true\n}\n\nfunc ui() {\n    fmt.Println(len(index), \"words indexed in\", len(indexed), \"files\")\n    fmt.Println(\"enter single words to search for\")\n    fmt.Println(\"enter a blank line when done\")\n    var word string\n    for {\n        fmt.Print(\"search word: \")\n        wc, _ := fmt.Scanln(&word)\n        if wc == 0 {\n            return\n        }\n        switch dl := index[word]; len(dl) {\n        case 0:\n            fmt.Println(\"no match\")\n        case 1:\n            fmt.Println(\"one match:\")\n            fmt.Println(\"   \", indexed[dl[0]].file, indexed[dl[0]].title)\n        default:\n            fmt.Println(len(dl), \"matches:\")\n            for _, d := range dl {\n                fmt.Println(\"   \", indexed[d].file, indexed[d].title)\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nchar chr_legal[] = \"abcdefghijklmnopqrstuvwxyz0123456789_-./\";\nint  chr_idx[256] = {0};\nchar idx_chr[256] = {0};\n\n#define FNAME 0\ntypedef struct trie_t *trie, trie_t;\nstruct trie_t {\n    trie next[sizeof(chr_legal)]; \n    int eow;\n};\n\ntrie trie_new() { return calloc(sizeof(trie_t), 1); }\n\n#define find_word(r, w) trie_trav(r, w, 1)\n\ntrie trie_trav(trie root, const char * str, int no_create)\n{\n    int c;\n    while (root) {\n        if ((c = str[0]) == '\\0') {\n            if (!root->eow && no_create) return 0;\n            break;\n        }\n        if (! (c = chr_idx[c]) ) {\n            str++;\n            continue;\n        }\n\n        if (!root->next[c]) {\n            if (no_create) return 0;\n            root->next[c] = trie_new();\n        }\n        root = root->next[c];\n        str++;\n    }\n    return root;\n}\n\n\nint trie_all(trie root, char path[], int depth, int (*callback)(char *))\n{\n    int i;\n    if (root->eow && !callback(path)) return 0;\n\n    for (i = 1; i < sizeof(chr_legal); i++) {\n        if (!root->next[i]) continue;\n\n        path[depth] = idx_chr[i];\n        path[depth + 1] = '\\0';\n        if (!trie_all(root->next[i], path, depth + 1, callback))\n            return 0;\n    }\n    return 1;\n}\n\nvoid add_index(trie root, const char *word, const char *fname)\n{\n    trie x = trie_trav(root, word, 0);\n    x->eow = 1;\n\n    if (!x->next[FNAME])\n        x->next[FNAME] = trie_new();\n    x = trie_trav(x->next[FNAME], fname, 0);\n    x->eow = 1;\n}\n\nint print_path(char *path)\n{\n    printf(\" %s\", path);\n    return 1;\n}\n\n\nconst char *files[] = { \"f1.txt\", \"source/f2.txt\", \"other_file\" };\nconst char *text[][5] ={{ \"it\", \"is\", \"what\", \"it\", \"is\" },\n                { \"what\", \"is\", \"it\", 0 },\n                { \"it\", \"is\", \"a\", \"banana\", 0 }};\n\ntrie init_tables()\n{\n    int i, j;\n    trie root = trie_new();\n    for (i = 0; i < sizeof(chr_legal); i++) {\n        chr_idx[(int)chr_legal[i]] = i + 1;\n        idx_chr[i + 1] = chr_legal[i];\n    }\n\n\n#define USE_ADVANCED_FILE_HANDLING 0\n#if USE_ADVANCED_FILE_HANDLING\n    void read_file(const char * fname) {\n        char cmd[1024];\n        char word[1024];\n        sprintf(cmd, \"perl -p -e 'while(/(\\\\w+)/g) {print lc($1),\\\"\\\\n\\\"}' %s\", fname);\n        FILE *in = popen(cmd, \"r\");\n        while (!feof(in)) {\n            fscanf(in, \"%1000s\", word);\n            add_index(root, word, fname);\n        }\n        pclose(in);\n    };\n\n    read_file(\"f1.txt\");\n    read_file(\"source/f2.txt\");\n    read_file(\"other_file\");\n#else\n    for (i = 0; i < 3; i++) {\n        for (j = 0; j < 5; j++) {\n            if (!text[i][j]) break;\n            add_index(root, text[i][j], files[i]);\n        }\n    }\n#endif \n\n    return root;\n}\n\nvoid search_index(trie root, const char *word)\n{\n    char path[1024];\n    printf(\"Search for \\\"%s\\\": \", word);\n    trie found = find_word(root, word);\n\n    if (!found) printf(\"not found\\n\");\n    else {\n        trie_all(found->next[FNAME], path, 0, print_path);\n        printf(\"\\n\");\n    }\n}\n\nint main()\n{\n    trie root = init_tables();\n\n    search_index(root, \"what\");\n    search_index(root, \"is\");\n    search_index(root, \"banana\");\n    search_index(root, \"boo\");\n    return 0;\n}\n"}
{"id": 60486, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 60487, "name": "Least common multiple", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n", "C": "#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m / gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n"}
{"id": 60488, "name": "Loops_Break", "Go": "package main\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n", "C": "int main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n"}
{"id": 60489, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 60490, "name": "Hello world_Line printer", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n   FILE *lp;\n   lp = fopen(\"/dev/lp0\",\"w\");\n   fprintf(lp,\"Hello world!\\n\");\n   fclose(lp);\n   return 0;\n}\n"}
{"id": 60491, "name": "Water collected between towers", "Go": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int)  []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\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\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 60492, "name": "Descending primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combinations(a []int, k int) [][]int {\n    n := len(a)\n    c := make([]int, k)\n    var combs [][]int\n    var combine func(start, end, index int)\n    combine = func(start, end, index int) {\n        if index == k {\n            t := make([]int, len(c))\n            copy(t, c)\n            combs = append(combs, t)\n            return\n        }\n        for i := start; i <= end && end-i+1 >= k-index; i++ {\n            c[index] = a[i]\n            combine(i+1, end, index+1)\n        }\n    }\n    combine(0, n-1, 0)\n    return combs\n}\n\nfunc powerset(a []int) (res [][]int) {\n    if len(a) == 0 {\n        return\n    }\n    for i := 1; i <= len(a); i++ {\n        res = append(res, combinations(a, i)...)\n    }\n    return\n}\n\nfunc main() {\n    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})\n    var descPrimes []int\n    for i := 1; i < len(ps); i++ {\n        s := \"\"\n        for _, e := range ps[i] {\n            s += string(e + '0')\n        }\n        p, _ := strconv.Atoi(s)\n        if rcu.IsPrime(p) {\n            descPrimes = append(descPrimes, p)\n        }\n    }\n    sort.Ints(descPrimes)\n    fmt.Println(\"There are\", len(descPrimes), \"descending primes, namely:\")\n    for i := 0; i < len(descPrimes); i++ {\n        fmt.Printf(\"%8d \", descPrimes[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n}\n", "C": "#include <stdio.h>\n\nint ispr(unsigned int n) {\n    if ((n & 1) == 0 || n < 2) return n == 2;\n    for (unsigned int j = 3; j * j <= n; j += 2)\n      if (n % j == 0) return 0; return 1; }\n\nint main() {\n  unsigned int c = 0, nc, pc = 9, i, a, b, l,\n    ps[128], nxt[128];\n  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;\n  while (1) {\n    nc = 0;\n    for (i = 0; i < pc; i++) {\n        if (ispr(a = ps[i]))\n          printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n        for (b = a * 10, l = a % 10 + b++; b < l; b++)\n          nxt[nc++] = b;\n      }\n      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n      else break;\n    }\n    printf(\"\\n%d descending primes found\", c);\n}\n"}
{"id": 60493, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 60494, "name": "Square-free integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n    primes := []uint64{2}\n    c := make([]bool, limit+1) \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    for i := uint64(3); i <= limit; i += 2 {\n        if !c[i] {\n            primes = append(primes, i)\n        }\n    }\n    return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n    limit := uint64(math.Sqrt(float64(to)))\n    primes := sieve(limit)\nouter:\n    for i := from; i <= to; i++ {\n        for _, p := range primes {\n            p2 := p * p\n            if p2 > i {\n                break\n            }\n            if i%p2 == 0 {\n                continue outer\n            }\n        }\n        results = append(results, i)\n    }\n    return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n    fmt.Println(\"Square-free integers from 1 to 145:\")\n    sf := squareFree(1, 145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", sf[i])\n    }\n\n    fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n    sf = squareFree(trillion, trillion+145)\n    for i := 0; i < len(sf); i++ {\n        if i > 0 && i%5 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%14d\", sf[i])\n    }\n\n    fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n    a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n    for _, n := range a {\n        fmt.Printf(\"  from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n#define TRILLION 1000000000000\n\ntypedef unsigned char bool;\ntypedef unsigned long long uint64;\n\nvoid sieve(uint64 limit, uint64 *primes, uint64 *length) {\n    uint64 i, count, p, p2;\n    bool *c = calloc(limit + 1, sizeof(bool));  \n    primes[0] = 2;\n    count  = 1;\n    \n    p = 3;\n    for (;;) {\n        p2 = p * p;\n        if (p2 > limit) break;\n        for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;\n        for (;;) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    for (i = 3; i <= limit; i += 2) {\n        if (!c[i]) primes[count++] = i;\n    }\n    *length = count;\n    free(c);\n}\n\nvoid squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {    \n    uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);\n    uint64 *primes = malloc((limit + 1) * sizeof(uint64));\n    bool add;\n    sieve(limit, primes, &np);\n    for (i = from; i <= to; ++i) {\n        add = TRUE;\n        for (j = 0; j < np; ++j) {\n            p = primes[j];\n            p2 = p * p;\n            if (p2 > i) break;\n            if (i % p2 == 0) {\n                add = FALSE;\n                break;\n            }\n        }\n        if (add) results[count++] = i;\n    }\n    *len = count;\n    free(primes);\n}\n\nint main() {\n    uint64 i, *sf, len;\n    \n    sf = malloc(1000000 * sizeof(uint64));\n    printf(\"Square-free integers from 1 to 145:\\n\");\n    squareFree(1, 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 20 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%4lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nSquare-free integers from %ld to %ld:\\n\", TRILLION, TRILLION + 145);\n    squareFree(TRILLION, TRILLION + 145, sf, &len);\n    for (i = 0; i < len; ++i) {\n        if (i > 0 && i % 5 == 0) {\n            printf(\"\\n\");\n        }\n        printf(\"%14lld\", sf[i]);\n    }\n\n    printf(\"\\n\\nNumber of square-free integers:\\n\");\n    int a[5] = {100, 1000, 10000, 100000, 1000000};\n    for (i = 0; i < 5; ++i) {\n        squareFree(1, a[i], sf, &len);\n        printf(\"  from %d to %d = %lld\\n\", 1, a[i], len);\n    }\n    free(sf);\n    return 0;   \n}\n"}
{"id": 60495, "name": "Jaro similarity", "Go": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n    if len(str1) == 0 && len(str2) == 0 {\n        return 1\n    }\n    if len(str1) == 0 || len(str2) == 0 {\n        return 0\n    }\n    match_distance := len(str1)\n    if len(str2) > match_distance {\n        match_distance = len(str2)\n    }\n    match_distance = match_distance/2 - 1\n    str1_matches := make([]bool, len(str1))\n    str2_matches := make([]bool, len(str2))\n    matches := 0.\n    transpositions := 0.\n    for i := range str1 {\n        start := i - match_distance\n        if start < 0 {\n            start = 0\n        }\n        end := i + match_distance + 1\n        if end > len(str2) {\n            end = len(str2)\n        }\n        for k := start; k < end; k++ {\n            if str2_matches[k] {\n                continue\n            }\n            if str1[i] != str2[k] {\n                continue\n            }\n            str1_matches[i] = true\n            str2_matches[k] = true\n            matches++\n            break\n        }\n    }\n    if matches == 0 {\n        return 0\n    }\n    k := 0\n    for i := range str1 {\n        if !str1_matches[i] {\n            continue\n        }\n        for !str2_matches[k] {\n            k++\n        }\n        if str1[i] != str2[k] {\n            transpositions++\n        }\n        k++\n    }\n    transpositions /= 2\n    return (matches/float64(len(str1)) +\n        matches/float64(len(str2)) +\n        (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n    fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n    fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n\n#define TRUE    1\n#define FALSE   0\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\ndouble jaro(const char *str1, const char *str2) {\n    \n    int str1_len = strlen(str1);\n    int str2_len = strlen(str2);\n\n    \n    \n    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;\n\n    \n    \n    int match_distance = (int) max(str1_len, str2_len)/2 - 1;\n\n    \n    int *str1_matches = calloc(str1_len, sizeof(int));\n    int *str2_matches = calloc(str2_len, sizeof(int));\n\n    \n    double matches = 0.0;\n    double transpositions = 0.0;\n\n    \n    for (int i = 0; i < str1_len; i++) {\n        \n        int start = max(0, i - match_distance);\n        int end = min(i + match_distance + 1, str2_len);\n\n        for (int k = start; k < end; k++) {\n            \n            if (str2_matches[k]) continue;\n            \n            if (str1[i] != str2[k]) continue;\n            \n            str1_matches[i] = TRUE;\n            str2_matches[k] = TRUE;\n            matches++;\n            break;\n        }\n    }\n\n    \n    if (matches == 0) {\n        free(str1_matches);\n        free(str2_matches);\n        return 0.0;\n    }\n\n    \n    int k = 0;\n    for (int i = 0; i < str1_len; i++) {\n        \n        if (!str1_matches[i]) continue;\n        \n        while (!str2_matches[k]) k++;\n        \n        if (str1[i] != str2[k]) transpositions++;\n        k++;\n    }\n\n    \n    \n    \n    transpositions /= 2.0;\n\n    \n    free(str1_matches);\n    free(str2_matches);\n\n    \n    return ((matches / str1_len) +\n        (matches / str2_len) +\n        ((matches - transpositions) / matches)) / 3.0;\n}\n\nint main() {\n    printf(\"%f\\n\", jaro(\"MARTHA\",    \"MARHTA\"));\n    printf(\"%f\\n\", jaro(\"DIXON\",     \"DICKSONX\"));\n    printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"));\n}\n"}
{"id": 60496, "name": "Sum and product puzzle", "Go": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t\n\t\n\t\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a<b)\")\n\tproducts := countProducts(all)\n\n\t\n\t\n\tvar sPairs []pair\npairs:\n\tfor _, p := range all {\n\t\ts := p.x + p.y\n\t\t\n\t\tfor a := 2; a < s/2+s&1; a++ {\n\t\t\tb := s - a\n\t\t\tif products[a*b] == 1 {\n\t\t\t\t\n\t\t\t\tcontinue pairs\n\t\t\t}\n\t\t}\n\t\tsPairs = append(sPairs, p)\n\t}\n\tfmt.Println(\"S starts with\", len(sPairs), \"possible pairs.\")\n\t\n\tsProducts := countProducts(sPairs)\n\n\t\n\t\n\tvar pPairs []pair\n\tfor _, p := range sPairs {\n\t\tif sProducts[p.x*p.y] == 1 {\n\t\t\tpPairs = append(pPairs, p)\n\t\t}\n\t}\n\tfmt.Println(\"P then has\", len(pPairs), \"possible pairs.\")\n\t\n\tpSums := countSums(pPairs)\n\n\t\n\tvar final []pair\n\tfor _, p := range pPairs {\n\t\tif pSums[p.x+p.y] == 1 {\n\t\t\tfinal = append(final, p)\n\t\t}\n\t}\n\n\t\n\tswitch len(final) {\n\tcase 1:\n\t\tfmt.Println(\"Answer:\", final[0].x, \"and\", final[0].y)\n\tcase 0:\n\t\tfmt.Println(\"No possible answer.\")\n\tdefault:\n\t\tfmt.Println(len(final), \"possible answers:\", final)\n\t}\n}\n\nfunc countProducts(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x*p.y]++\n\t}\n\treturn m\n}\n\nfunc countSums(list []pair) map[int]int {\n\tm := make(map[int]int)\n\tfor _, p := range list {\n\t\tm[p.x+p.y]++\n\t}\n\treturn m\n}\n\n\nfunc decomposeSum(s int) []pair {\n\tpairs := make([]pair, 0, s/2)\n\tfor a := 2; a < s/2+s&1; a++ {\n\t\tpairs = append(pairs, pair{a, s - a})\n\t}\n\treturn pairs\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct node_t {\n    int x, y;\n    struct node_t *prev, *next;\n} node;\n\nnode *new_node(int x, int y) {\n    node *n = malloc(sizeof(node));\n    n->x = x;\n    n->y = y;\n    n->next = NULL;\n    n->prev = NULL;\n    return n;\n}\n\nvoid free_node(node **n) {\n    if (n == NULL) {\n        return;\n    }\n\n    (*n)->prev = NULL;\n    (*n)->next = NULL;\n\n    free(*n);\n\n    *n = NULL;\n}\n\ntypedef struct list_t {\n    node *head;\n    node *tail;\n} list;\n\nlist make_list() {\n    list lst = { NULL, NULL };\n    return lst;\n}\n\nvoid append_node(list *const lst, int x, int y) {\n    if (lst == NULL) {\n        return;\n    }\n\n    node *n = new_node(x, y);\n\n    if (lst->head == NULL) {\n        lst->head = n;\n        lst->tail = n;\n    } else {\n        n->prev = lst->tail;\n        lst->tail->next = n;\n        lst->tail = n;\n    }\n}\n\nvoid remove_node(list *const lst, const node *const n) {\n    if (lst == NULL || n == NULL) {\n        return;\n    }\n\n    if (n->prev != NULL) {\n        n->prev->next = n->next;\n        if (n->next != NULL) {\n            n->next->prev = n->prev;\n        } else {\n            lst->tail = n->prev;\n        }\n    } else {\n        if (n->next != NULL) {\n            n->next->prev = NULL;\n            lst->head = n->next;\n        }\n    }\n\n    free_node(&n);\n}\n\nvoid free_list(list *const lst) {\n    node *ptr;\n\n    if (lst == NULL) {\n        return;\n    }\n    ptr = lst->head;\n\n    while (ptr != NULL) {\n        node *nxt = ptr->next;\n        free_node(&ptr);\n        ptr = nxt;\n    }\n\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid print_list(const list *lst) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        int prod = it->x * it->y;\n        printf(\"[%d, %d] S=%d P=%d\\n\", it->x, it->y, sum, prod);\n    }\n}\n\nvoid print_count(const list *const lst) {\n    node *it;\n    int c = 0;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        c++;\n    }\n\n    if (c == 0) {\n        printf(\"no candidates\\n\");\n    } else    if (c == 1) {\n        printf(\"one candidate\\n\");\n    } else {\n        printf(\"%d candidates\\n\", c);\n    }\n}\n\nvoid setup(list *const lst) {\n    int x, y;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    \n    for (x = 2; x <= 98; x++) {\n        \n        for (y = x + 1; y <= 98; y++) {\n            if (x + y <= 100) {\n                append_node(lst, x, y);\n            }\n        }\n    }\n}\n\nvoid remove_by_sum(list *const lst, const int sum) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int s = it->x + it->y;\n\n        if (s == sum) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid remove_by_prod(list *const lst, const int prod) {\n    node *it;\n\n    if (lst == NULL) {\n        return;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int p = it->x * it->y;\n\n        if (p == prod) {\n            remove_node(lst, it);\n            it = lst->head;\n        } else {\n            it = it->next;\n        }\n    }\n}\n\nvoid statement1(list *const lst) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = lst->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = lst->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] == 1) {\n            remove_by_sum(lst, it->x + it->y);\n            it = lst->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement2(list *const candidates) {\n    short *unique = calloc(100000, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int prod = it->x * it->y;\n        unique[prod]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int prod = it->x * it->y;\n        nxt = it->next;\n        if (unique[prod] > 1) {\n            remove_by_prod(candidates, prod);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nvoid statement3(list *const candidates) {\n    short *unique = calloc(100, sizeof(short));\n    node *it, *nxt;\n\n    for (it = candidates->head; it != NULL; it = it->next) {\n        int sum = it->x + it->y;\n        unique[sum]++;\n    }\n\n    it = candidates->head;\n    while (it != NULL) {\n        int sum = it->x + it->y;\n        nxt = it->next;\n        if (unique[sum] > 1) {\n            remove_by_sum(candidates, sum);\n            it = candidates->head;\n        } else {\n            it = nxt;\n        }\n    }\n\n    free(unique);\n}\n\nint main() {\n    list candidates = make_list();\n\n    setup(&candidates);\n    print_count(&candidates);\n\n    statement1(&candidates);\n    print_count(&candidates);\n\n    statement2(&candidates);\n    print_count(&candidates);\n\n    statement3(&candidates);\n    print_count(&candidates);\n\n    print_list(&candidates);\n\n    free_list(&candidates);\n    return 0;\n}\n"}
{"id": 60497, "name": "Fairshare between two and more", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n    res := make([]int, n)\n    for i := 0; i < n; i++ {\n        j := i\n        sum := 0\n        for j > 0 {\n            sum += j % base\n            j /= base\n        }\n        res[i] = sum % base\n    }\n    return res\n}\n\nfunc turns(n int, fss []int) string {\n    m := make(map[int]int)\n    for _, fs := range fss {\n        m[fs]++\n    }\n    m2 := make(map[int]int)\n    for _, v := range m {\n        m2[v]++\n    }\n    res := []int{}\n    sum := 0\n    for k, v := range m2 {\n        sum += v\n        res = append(res, k)\n    }\n    if sum != n {\n        return fmt.Sprintf(\"only %d have a turn\", sum)\n    }\n    sort.Ints(res)\n    res2 := make([]string, len(res))\n    for i := range res {\n        res2[i] = strconv.Itoa(res[i])\n    }\n    return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n    for _, base := range []int{2, 3, 5, 11} {\n        fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n    }\n    fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n    for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n        t := turns(base, fairshare(50000, base))\n        fmt.Printf(\"  With %d people: %s\\n\", base, t)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint turn(int base, int n) {\n    int sum = 0;\n    while (n != 0) {\n        int rem = n % base;\n        n = n / base;\n        sum += rem;\n    }\n    return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n    int i;\n\n    printf(\"Base %2d:\", base);\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        printf(\" %2d\", t);\n    }\n    printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n    int *cnt = calloc(base, sizeof(int));\n    int i, minTurn, maxTurn, portion;\n\n    if (NULL == cnt) {\n        printf(\"Failed to allocate space to determine the spread of turns.\\n\");\n        return;\n    }\n\n    for (i = 0; i < count; i++) {\n        int t = turn(base, i);\n        cnt[t]++;\n    }\n\n    minTurn = INT_MAX;\n    maxTurn = INT_MIN;\n    portion = 0;\n    for (i = 0; i < base; i++) {\n        if (cnt[i] > 0) {\n            portion++;\n        }\n        if (cnt[i] < minTurn) {\n            minTurn = cnt[i];\n        }\n        if (cnt[i] > maxTurn) {\n            maxTurn = cnt[i];\n        }\n    }\n\n    printf(\"  With %d people: \", base);\n    if (0 == minTurn) {\n        printf(\"Only %d have a turn\\n\", portion);\n    } else if (minTurn == maxTurn) {\n        printf(\"%d\\n\", minTurn);\n    } else {\n        printf(\"%d or %d\\n\", minTurn, maxTurn);\n    }\n\n    free(cnt);\n}\n\nint main() {\n    fairshare(2, 25);\n    fairshare(3, 25);\n    fairshare(5, 25);\n    fairshare(11, 25);\n\n    printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n    turnCount(191, 50000);\n    turnCount(1377, 50000);\n    turnCount(49999, 50000);\n    turnCount(50000, 50000);\n    turnCount(50001, 50000);\n\n    return 0;\n}\n"}
{"id": 60498, "name": "Two bullet roulette", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n    t := cylinder[5]\n    for i := 4; i >= 0; i-- {\n        cylinder[i+1] = cylinder[i]\n    }\n    cylinder[0] = t\n}\n\nfunc unload() {\n    for i := 0; i < 6; i++ {\n        cylinder[i] = false\n    }\n}\n\nfunc load() {\n    for cylinder[0] {\n        rshift()\n    }\n    cylinder[0] = true\n    rshift()\n}\n\nfunc spin() {\n    var lim = 1 + rand.Intn(6)\n    for i := 1; i < lim; i++ {\n        rshift()\n    }\n}\n\nfunc fire() bool {\n    shot := cylinder[0]\n    rshift()\n    return shot\n}\n\nfunc method(s string) int {\n    unload()\n    for _, c := range s {\n        switch c {\n        case 'L':\n            load()\n        case 'S':\n            spin()\n        case 'F':\n            if fire() {\n                return 1\n            }\n        }\n    }\n    return 0\n}\n\nfunc mstring(s string) string {\n    var l []string\n    for _, c := range s {\n        switch c {\n        case 'L':\n            l = append(l, \"load\")\n        case 'S':\n            l = append(l, \"spin\")\n        case 'F':\n            l = append(l, \"fire\")\n        }\n    }\n    return strings.Join(l, \", \")\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    tests := 100000\n    for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n        sum := 0\n        for t := 1; t <= tests; t++ {\n            sum += method(m)\n        }\n        pc := float64(sum) * 100 / float64(tests)\n        fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstatic int nextInt(int size) {\n    return rand() % size;\n}\n\nstatic bool cylinder[6];\n\nstatic void rshift() {\n    bool t = cylinder[5];\n    int i;\n    for (i = 4; i >= 0; i--) {\n        cylinder[i + 1] = cylinder[i];\n    }\n    cylinder[0] = t;\n}\n\nstatic void unload() {\n    int i;\n    for (i = 0; i < 6; i++) {\n        cylinder[i] = false;\n    }\n}\n\nstatic void load() {\n    while (cylinder[0]) {\n        rshift();\n    }\n    cylinder[0] = true;\n    rshift();\n}\n\nstatic void spin() {\n    int lim = nextInt(6) + 1;\n    int i;\n    for (i = 1; i < lim; i++) {\n        rshift();\n    }\n}\n\nstatic bool fire() {\n    bool shot = cylinder[0];\n    rshift();\n    return shot;\n}\n\nstatic int method(const char *s) {\n    unload();\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            load();\n            break;\n        case 'S':\n            spin();\n            break;\n        case 'F':\n            if (fire()) {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nstatic void append(char *out, const char *txt) {\n    if (*out != '\\0') {\n        strcat(out, \", \");\n    }\n    strcat(out, txt);\n}\n\nstatic void mstring(const char *s, char *out) {\n    for (; *s != '\\0'; s++) {\n        switch (*s) {\n        case 'L':\n            append(out, \"load\");\n            break;\n        case 'S':\n            append(out, \"spin\");\n            break;\n        case 'F':\n            append(out, \"fire\");\n            break;\n        }\n    }\n}\n\nstatic void test(char *src) {\n    char buffer[41] = \"\";\n    const int tests = 100000;\n    int sum = 0;\n    int t;\n    double pc;\n\n    for (t = 0; t < tests; t++) {\n        sum += method(src);\n    }\n\n    mstring(src, buffer);\n    pc = 100.0 * sum / tests;\n\n    printf(\"%-40s produces %6.3f%% deaths.\\n\", buffer, pc);\n}\n\nint main() {\n    srand(time(0));\n\n    test(\"LSLSFSF\");\n    test(\"LSLSFF\");\n    test(\"LLSFSF\");\n    test(\"LLSFF\");\n\n    return 0;\n}\n"}
{"id": 60499, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60500, "name": "Parsing_Shunting-yard algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n    prec   int\n    rAssoc bool\n}{\n    \"^\": {4, true},\n    \"*\": {3, false},\n    \"/\": {3, false},\n    \"+\": {2, false},\n    \"-\": {2, false},\n}\n\nfunc main() {\n    fmt.Println(\"infix:  \", input)\n    fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n    var stack []string \n    for _, tok := range strings.Fields(e) {\n        switch tok {\n        case \"(\":\n            stack = append(stack, tok) \n        case \")\":\n            var op string\n            for {\n                \n                op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n                if op == \"(\" {\n                    break \n                }\n                rpn += \" \" + op \n            }\n        default:\n            if o1, isOp := opa[tok]; isOp {\n                \n                for len(stack) > 0 {\n                    \n                    op := stack[len(stack)-1]\n                    if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n                        o1.prec == o2.prec && o1.rAssoc {\n                        break\n                    }\n                    \n                    stack = stack[:len(stack)-1] \n                    rpn += \" \" + op              \n                }\n                \n                stack = append(stack, tok)\n            } else { \n                if rpn > \"\" {\n                    rpn += \" \"\n                }\n                rpn += tok \n            }\n        }\n    }\n    \n    for len(stack) > 0 {\n        rpn += \" \" + stack[len(stack)-1]\n        stack = stack[:len(stack)-1]\n    }\n    return\n}\n", "C": "#include <sys/types.h>\n#include <regex.h>\n#include <stdio.h>\n\ntypedef struct {\n\tconst char *s;\n\tint len, prec, assoc;\n} str_tok_t;\n\ntypedef struct {\n\tconst char * str;\n\tint assoc, prec;\n\tregex_t re;\n} pat_t;\n\nenum assoc { A_NONE, A_L, A_R };\npat_t pat_eos = {\"\", A_NONE, 0};\n\npat_t pat_ops[] = {\n\t{\"^\\\\)\",\tA_NONE, -1},\n\t{\"^\\\\*\\\\*\",\tA_R, 3},\n\t{\"^\\\\^\",\tA_R, 3},\n\t{\"^\\\\*\",\tA_L, 2},\n\t{\"^/\",\t\tA_L, 2},\n\t{\"^\\\\+\",\tA_L, 1},\n\t{\"^-\",\t\tA_L, 1},\n\t{0}\n};\n\npat_t pat_arg[] = {\n\t{\"^[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?\"},\n\t{\"^[a-zA-Z_][a-zA-Z_0-9]*\"},\n\t{\"^\\\\(\", A_L, -1},\n\t{0}\n};\n\nstr_tok_t stack[256]; \nstr_tok_t queue[256];\nint l_queue, l_stack;\n#define qpush(x) queue[l_queue++] = x\n#define spush(x) stack[l_stack++] = x\n#define spop()   stack[--l_stack]\n\nvoid display(const char *s)\n{\n\tint i;\n\tprintf(\"\\033[1;1H\\033[JText | %s\", s);\n\tprintf(\"\\nStack| \");\n\tfor (i = 0; i < l_stack; i++)\n\t\tprintf(\"%.*s \", stack[i].len, stack[i].s); \n\tprintf(\"\\nQueue| \");\n\tfor (i = 0; i < l_queue; i++)\n\t\tprintf(\"%.*s \", queue[i].len, queue[i].s);\n\tputs(\"\\n\\n<press enter>\");\n\tgetchar();\n}\n\nint prec_booster;\n\n#define fail(s1, s2) {fprintf(stderr, \"[Error %s] %s\\n\", s1, s2); return 0;}\n\nint init(void)\n{\n\tint i;\n\tpat_t *p;\n\n\tfor (i = 0, p = pat_ops; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\tfor (i = 0, p = pat_arg; p[i].str; i++)\n\t\tif (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))\n\t\t\tfail(\"comp\", p[i].str);\n\n\treturn 1;\n}\n\npat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)\n{\n\tint i;\n\tregmatch_t m;\n\n\twhile (*s == ' ') s++;\n\t*e = s;\n\n\tif (!*s) return &pat_eos;\n\n\tfor (i = 0; p[i].str; i++) {\n\t\tif (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))\n\t\t\tcontinue;\n\t\tt->s = s;\n\t\t*e = s + (t->len = m.rm_eo - m.rm_so);\n\t\treturn p + i;\n\t}\n\treturn 0;\n}\n\nint parse(const char *s) {\n\tpat_t *p;\n\tstr_tok_t *t, tok;\n\n\tprec_booster = l_queue = l_stack = 0;\n\tdisplay(s);\n\twhile (*s) {\n\t\tp = match(s, pat_arg, &tok, &s);\n\t\tif (!p || p == &pat_eos) fail(\"parse arg\", s);\n\n\t\t\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster += 100;\n\t\t\tcontinue;\n\t\t}\n\t\tqpush(tok);\n\t\tdisplay(s);\n\nre_op:\t\tp = match(s, pat_ops, &tok, &s);\n\t\tif (!p) fail(\"parse op\", s);\n\n\t\ttok.assoc = p->assoc;\n\t\ttok.prec = p->prec;\n\n\t\tif (p->prec > 0)\n\t\t\ttok.prec = p->prec + prec_booster;\n\t\telse if (p->prec == -1) {\n\t\t\tif (prec_booster < 100)\n\t\t\t\tfail(\"unmatched )\", s);\n\t\t\ttok.prec = prec_booster;\n\t\t}\n\n\t\twhile (l_stack) {\n\t\t\tt = stack + l_stack - 1;\n\t\t\tif (!(t->prec == tok.prec && t->assoc == A_L)\n\t\t\t\t\t&& t->prec <= tok.prec)\n\t\t\t\tbreak;\n\t\t\tqpush(spop());\n\t\t\tdisplay(s);\n\t\t}\n\n\t\tif (p->prec == -1) {\n\t\t\tprec_booster -= 100;\n\t\t\tgoto re_op;\n\t\t}\n\n\t\tif (!p->prec) {\n\t\t\tdisplay(s);\n\t\t\tif (prec_booster)\n\t\t\t\tfail(\"unmatched (\", s);\n\t\t\treturn 1;\n\t\t}\n\n\t\tspush(tok);\n\t\tdisplay(s);\n\t}\n\n\tif (p->prec > 0)\n\t\tfail(\"unexpected eol\", s);\n\n\treturn 1;\n}\n\nint main()\n{\n\tint i;\n\tconst char *tests[] = { \n\t\t\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\t\n\t\t\"123\",\t\t\t\t\t\n\t\t\"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14\",\t\n\t\t\"(((((((1+2+3**(4 + 5))))))\",\t\t\n\t\t\"a^(b + c/d * .1e5)!\",\t\t\t\n\t\t\"(1**2)**3\",\t\t\t\t\n\t\t\"2 + 2 *\",\t\t\t\t\n\t\t0\n\t};\n\n\tif (!init()) return 1;\n\tfor (i = 0; tests[i]; i++) {\n\t\tprintf(\"Testing string `%s'   <enter>\\n\", tests[i]);\n\t\tgetchar();\n\n\t\tprintf(\"string `%s': %s\\n\\n\", tests[i],\n\t\t\tparse(tests[i]) ? \"Ok\" : \"Error\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60501, "name": "Prime triangle", "Go": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n    for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n        pmap[i] = true\n    }\n}\n\nfunc ptrs(res, n, done int) int {\n    ad := arrang[done-1]\n    if n-done <= 1 {\n        if canFollow[ad-1][n-1] {\n            if bFirst {\n                for _, e := range arrang {\n                    fmt.Printf(\"%2d \", e)\n                }\n                fmt.Println()\n                bFirst = false\n            }\n            res++\n        }\n    } else {\n        done++\n        for i := done - 1; i <= n-2; i += 2 {\n            ai := arrang[i]\n            if canFollow[ad-1][ai-1] {\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n                res = ptrs(res, n, done)\n                arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n            }\n        }\n    }\n    return res\n}\n\nfunc primeTriangle(n int) int {\n    canFollow = make([][]bool, n)\n    for i := 0; i < n; i++ {\n        canFollow[i] = make([]bool, n)\n        for j := 0; j < n; j++ {\n            _, ok := pmap[i+j+2]\n            canFollow[i][j] = ok\n        }\n    }\n    bFirst = true\n    arrang = make([]int, n)\n    for i := 0; i < n; i++ {\n        arrang[i] = i + 1\n    }\n    return ptrs(0, n, 1)\n}\n\nfunc main() {\n    counts := make([]int, 19)\n    for i := 2; i <= 20; i++ {\n        counts[i-2] = primeTriangle(i)\n    }\n    fmt.Println()\n    for i := 0; i < 19; i++ {\n        fmt.Printf(\"%d \", counts[i])\n    }\n    fmt.Println()\n}\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool is_prime(unsigned int n) {\n    assert(n < 64);\n    static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,\n                             0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n                             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};\n    return isprime[n];\n}\n\nvoid swap(unsigned int* a, size_t i, size_t j) {\n    unsigned int tmp = a[i];\n    a[i] = a[j];\n    a[j] = tmp;\n}\n\nbool prime_triangle_row(unsigned int* a, size_t length) {\n    if (length == 2)\n        return is_prime(a[0] + a[1]);\n    for (size_t i = 1; i + 1 < length; i += 2) {\n        if (is_prime(a[0] + a[i])) {\n            swap(a, i, 1);\n            if (prime_triangle_row(a + 1, length - 1))\n                return true;\n            swap(a, i, 1);\n        }\n    }\n    return false;\n}\n\nint prime_triangle_count(unsigned int* a, size_t length) {\n    int count = 0;\n    if (length == 2) {\n        if (is_prime(a[0] + a[1]))\n            ++count;\n    } else {\n        for (size_t i = 1; i + 1 < length; i += 2) {\n            if (is_prime(a[0] + a[i])) {\n                swap(a, i, 1);\n                count += prime_triangle_count(a + 1, length - 1);\n                swap(a, i, 1);\n            }\n        }\n    }\n    return count;\n}\n\nvoid print(unsigned int* a, size_t length) {\n    if (length == 0)\n        return;\n    printf(\"%2u\", a[0]);\n    for (size_t i = 1; i < length; ++i)\n        printf(\" %2u\", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    clock_t start = clock();\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (prime_triangle_row(a, n))\n            print(a, n);\n    }\n    printf(\"\\n\");\n    for (unsigned int n = 2; n < 21; ++n) {\n        unsigned int a[n];\n        for (unsigned int i = 0; i < n; ++i)\n            a[i] = i + 1;\n        if (n > 2)\n            printf(\" \");\n        printf(\"%d\", prime_triangle_count(a, n));\n    }\n    printf(\"\\n\");\n    clock_t end = clock();\n    double duration = (end - start + 0.0) / CLOCKS_PER_SEC;\n    printf(\"\\nElapsed time: %f seconds\\n\", duration);\n    return 0;\n}\n"}
{"id": 60502, "name": "Trabb Pardo–Knuth algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nfunc main() {\n    \n    fmt.Print(\"Enter 11 numbers: \")\n    \n    var s [11]float64\n    for i := 0; i < 11; {\n        if n, _ := fmt.Scan(&s[i]); n > 0 {\n            i++\n        }\n    }\n    \n    for i, item := range s[:5] {\n        s[i], s[10-i] = s[10-i], item\n    }\n    \n    for _, item := range s {\n        if result, overflow := f(item); overflow {\n            \n            log.Printf(\"f(%g) overflow\", item)\n        } else {\n            \n            fmt.Printf(\"f(%g) = %g\\n\", item, result)\n        }\n    }\n}\n\nfunc f(x float64) (float64, bool) {\n    result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n    return result, result > 400\n}\n", "C": "#include<math.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  double inputs[11], check = 400, result;\n  int i;\n\n  printf (\"\\nPlease enter 11 numbers :\");\n\n  for (i = 0; i < 11; i++)\n    {\n      scanf (\"%lf\", &inputs[i]);\n    }\n\n  printf (\"\\n\\n\\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :\");\n\n  for (i = 10; i >= 0; i--)\n    {\n      result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);\n\n      printf (\"\\nf(%lf) = \");\n\n      if (result > check)\n        {\n          printf (\"Overflow!\");\n        }\n\n      else\n        {\n          printf (\"%lf\", result);\n        }\n    }\n\n  return 0;\n}\n"}
{"id": 60503, "name": "Middle three digits", "Go": "package m3\n\nimport (\n    \"errors\"\n    \"strconv\"\n)\n\nvar (\n    ErrorLT3  = errors.New(\"N of at least three digits required.\")\n    ErrorEven = errors.New(\"N with odd number of digits required.\")\n)\n\nfunc Digits(i int) (string, error) {\n    if i < 0 {\n        i = -i\n    }\n    if i < 100 {\n        return \"\", ErrorLT3\n    }\n    s := strconv.Itoa(i)\n    if len(s)%2 == 0 {\n        return \"\", ErrorEven\n    }\n    m := len(s) / 2\n    return s[m-1 : m+2], nil\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nchar * mid3(int n)\n{\n\tstatic char buf[32];\n\tint l;\n\tsprintf(buf, \"%d\", n > 0 ? n : -n);\n\tl = strlen(buf);\n\tif (l < 3 || !(l & 1)) return 0;\n\tl = l / 2 - 1;\n\tbuf[l + 3] = 0;\n\treturn buf + l;\n}\n\nint main(void)\n{\n\tint x[] = {123, 12345, 1234567, 987654321, 10001, -10001,\n\t\t-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,\n\t\t1234567890};\n\n\tint i;\n\tchar *m;\n\tfor (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {\n\t\tif (!(m = mid3(x[i])))\n\t\t\tm = \"error\";\n\t\tprintf(\"%d: %s\\n\", x[i], m);\n\t}\n\treturn 0;\n}\n"}
{"id": 60504, "name": "Sequence_ nth number with exactly n divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n    bi.SetUint64(uint64(n))\n    return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n    primes := make([]int, n)\n    primes[0] = 2\n    for i, count := 3, 1; count < n; i += 2 {\n        if isPrime(i) {\n            primes[count] = i\n            count++\n        }\n    }\n    return primes\n}\n\nfunc countDivisors(n int) int {\n    count := 1\n    for n%2 == 0 {\n        n >>= 1\n        count++\n    }\n    for d := 3; d*d <= n; d += 2 {\n        q, r := n/d, n%d\n        if r == 0 {\n            dc := 0\n            for r == 0 {\n                dc += count\n                n = q\n                q, r = n/d, n%d\n            }\n            count += dc\n        }\n    }\n    if n != 1 {\n        count *= 2\n    }\n    return count\n}\n\nfunc main() {\n    const max = 33\n    primes := generateSmallPrimes(max)\n    z := new(big.Int)\n    p := new(big.Int)\n    fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n    for i := 1; i <= max; i++ {\n        if isPrime(i) {\n            z.SetUint64(uint64(primes[i-1]))\n            p.SetUint64(uint64(i - 1))\n            z.Exp(z, p, nil)\n            fmt.Printf(\"%2d : %d\\n\", i, z)\n        } else {\n            count := 0\n            for j := 1; ; j++ {\n                if i%2 == 1 {\n                    sq := int(math.Sqrt(float64(j)))\n                    if sq*sq != j {\n                        continue\n                    }\n                }\n                if countDivisors(j) == i {\n                    count++\n                    if count == i {\n                        fmt.Printf(\"%2d : %d\\n\", i, j)\n                        break\n                    }\n                }\n            }\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define LIMIT 15\nint smallPrimes[LIMIT];\n\nstatic void sieve() {\n    int i = 2, j;\n    int p = 5;\n\n    smallPrimes[0] = 2;\n    smallPrimes[1] = 3;\n\n    while (i < LIMIT) {\n        for (j = 0; j < i; j++) {\n            if (smallPrimes[j] * smallPrimes[j] <= p) {\n                if (p % smallPrimes[j] == 0) {\n                    p += 2;\n                    break;\n                }\n            } else {\n                smallPrimes[i++] = p;\n                p += 2;\n                break;\n            }\n        }\n    }\n}\n\nstatic bool is_prime(uint64_t n) {\n    uint64_t i;\n\n    for (i = 0; i < LIMIT; i++) {\n        if (n % smallPrimes[i] == 0) {\n            return n == smallPrimes[i];\n        }\n    }\n\n    i = smallPrimes[LIMIT - 1] + 2;\n    for (; i * i <= n; i += 2) {\n        if (n % i == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic uint64_t divisor_count(uint64_t n) {\n    uint64_t count = 1;\n    uint64_t d;\n\n    while (n % 2 == 0) {\n        n /= 2;\n        count++;\n    }\n\n    for (d = 3; d * d <= n; d += 2) {\n        uint64_t q = n / d;\n        uint64_t r = n % d;\n        uint64_t dc = 0;\n        while (r == 0) {\n            dc += count;\n            n = q;\n            q = n / d;\n            r = n % d;\n        }\n        count += dc;\n    }\n\n    if (n != 1) {\n        return count *= 2;\n    }\n    return count;\n}\n\nstatic uint64_t OEISA073916(size_t n) {\n    uint64_t count = 0;\n    uint64_t result = 0;\n    size_t i;\n\n    if (is_prime(n)) {\n        return (uint64_t)pow(smallPrimes[n - 1], n - 1);\n    }\n\n    for (i = 1; count < n; i++) {\n        if (n % 2 == 1) {\n            \n            uint64_t root = (uint64_t)sqrt(i);\n            if (root * root != i) {\n                continue;\n            }\n        }\n        if (divisor_count(i) == n) {\n            count++;\n            result = i;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    size_t n;\n\n    sieve();\n\n    for (n = 1; n <= LIMIT; n++) {\n        if (n == 13) {\n            printf(\"A073916(%lu) = One more bit needed to represent result.\\n\", n);\n        } else {\n            printf(\"A073916(%lu) = %llu\\n\", n, OEISA073916(n));\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 60505, "name": "Sequence_ smallest number with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    seq := make([]int, max)\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, n := 1, 0; n < max; i++ {\n        if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n            seq[k-1] = i\n            n++\n        }\n    }\n    fmt.Println(seq)\n}\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, k, n, seq[MAX];\n    for (i = 0; i < MAX; ++i) seq[i] = 0;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1, n = 0; n <  MAX; ++i) {\n        k = count_divisors(i);\n        if (k <= MAX && seq[k - 1] == 0) {\n            seq[k - 1] = i;\n            ++n;\n        }\n    }\n    for (i = 0; i < MAX; ++i) printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60506, "name": "Pancake numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60507, "name": "Pancake numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n    gap, sum, adj := 2, 2, -1\n    for sum < n {\n        adj++\n        gap = gap*2 - 1\n        sum += gap\n    }\n    return n + adj\n}\n\nfunc main() {\n    for i := 0; i < 4; i++ {\n        for j := 1; j < 6; j++ {\n            n := i*5 + j\n            fmt.Printf(\"p(%2d) = %2d  \", n, pancake(n))\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n\nint pancake(int n) {\n    int gap = 2, sum = 2, adj = -1;\n    while (sum < n) {\n        adj++;\n        gap = gap * 2 - 1;\n        sum += gap;\n    }\n    return n + adj;\n}\n\nint main() {\n    int i, j;\n    for (i = 0; i < 4; i++) {\n        for (j = 1; j < 6; j++) {\n            int n = i * 5 + j;\n            printf(\"p(%2d) = %2d  \", n, pancake(n));\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60508, "name": "Generate random chess position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n    if i >= 0 {\n        return i\n    } else {\n        return -i\n    }\n}\n\nfunc createFen() string {\n    placeKings()\n    placePieces(\"PPPPPPPP\", true)\n    placePieces(\"pppppppp\", true)\n    placePieces(\"RNBQBNR\", false)\n    placePieces(\"rnbqbnr\", false)\n    return toFen()\n}\n\nfunc placeKings() {\n    for {\n        r1 := rand.Intn(8)\n        c1 := rand.Intn(8)\n        r2 := rand.Intn(8)\n        c2 := rand.Intn(8)\n        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n            grid[r1][c1] = 'K'\n            grid[r2][c2] = 'k'\n            return\n        }\n    }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n    numToPlace := rand.Intn(len(pieces))\n    for n := 0; n < numToPlace; n++ {\n        var r, c int\n        for {\n            r = rand.Intn(8)\n            c = rand.Intn(8)\n            if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n                break\n            }\n        }\n        grid[r][c] = pieces[n]\n    }\n}\n\nfunc toFen() string {\n    var fen strings.Builder\n    countEmpty := 0\n    for r := 0; r < 8; r++ {\n        for c := 0; c < 8; c++ {\n            ch := grid[r][c]\n            if ch == '\\000' {\n                ch = '.'\n            }\n            fmt.Printf(\"%2c \", ch)\n            if ch == '.' {\n                countEmpty++\n            } else {\n                if countEmpty > 0 {\n                    fen.WriteString(strconv.Itoa(countEmpty))\n                    countEmpty = 0\n                }\n                fen.WriteByte(ch)\n            }\n        }\n        if countEmpty > 0 {\n            fen.WriteString(strconv.Itoa(countEmpty))\n            countEmpty = 0\n        }\n        fen.WriteString(\"/\")\n        fmt.Println()\n    }\n    fen.WriteString(\" w - - 0 1\")\n    return fen.String()\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(createFen())\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nchar grid[8][8];\n\nvoid placeKings() {\n    int r1, r2, c1, c2;\n    for (;;) {\n        r1 = rand() % 8;\n        c1 = rand() % 8;\n        r2 = rand() % 8;\n        c2 = rand() % 8;\n        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n            grid[r1][c1] = 'K';\n            grid[r2][c2] = 'k';\n            return;\n        }\n    }\n}\n\nvoid placePieces(const char *pieces, bool isPawn) {\n    int n, r, c;\n    int numToPlace = rand() % strlen(pieces);\n    for (n = 0; n < numToPlace; ++n) {\n        do {\n            r = rand() % 8;\n            c = rand() % 8;\n        }\n        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));\n        grid[r][c] = pieces[n];\n    }\n}\n\nvoid toFen() {\n    char fen[80], ch;\n    int r, c, countEmpty = 0, index = 0;\n    for (r = 0; r < 8; ++r) {\n        for (c = 0; c < 8; ++c) {\n            ch = grid[r][c];\n            printf(\"%2c \", ch == 0 ? '.' : ch);\n            if (ch == 0) {\n                countEmpty++;\n            }\n            else {\n                if (countEmpty > 0) {\n                    fen[index++] = countEmpty + 48;\n                    countEmpty = 0;               \n                }\n                fen[index++] = ch;\n            }\n        }\n        if (countEmpty > 0) {\n            fen[index++] = countEmpty + 48;\n            countEmpty = 0;\n        }\n        fen[index++]= '/';\n        printf(\"\\n\");\n    }\n    strcpy(fen + index, \" w - - 0 1\");\n    printf(\"%s\\n\", fen);\n}\n\nchar *createFen() {\n    placeKings();\n    placePieces(\"PPPPPPPP\", TRUE);\n    placePieces(\"pppppppp\", TRUE);\n    placePieces(\"RNBQBNR\", FALSE);\n    placePieces(\"rnbqbnr\", FALSE);\n    toFen();\n}\n\nint main() {\n    srand(time(NULL));\n    createFen();\n    return 0;\n}\n"}
{"id": 60509, "name": "Esthetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n"}
{"id": 60510, "name": "Esthetic numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n    if a > b {\n        return a - b\n    }\n    return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n    if n == 0 {\n        return false\n    }\n    i := n % b\n    n /= b\n    for n > 0 {\n        j := n % b\n        if uabs(i, j) != 1 {\n            return false\n        }\n        n /= b\n        i = j\n    }\n    return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n    if i >= n && i <= m {\n        esths = append(esths, i)\n    }\n    if i == 0 || i > m {\n        return\n    }\n    d := i % 10\n    i1 := i*10 + d - 1\n    i2 := i1 + 2\n    if d == 0 {\n        dfs(n, m, i2)\n    } else if d == 9 {\n        dfs(n, m, i1)\n    } else {\n        dfs(n, m, i1)\n        dfs(n, m, i2)\n    }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n    esths = esths[:0]\n    for i := uint64(0); i < 10; i++ {\n        dfs(n2, m2, i)\n    }\n    le := len(esths)\n    fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n        commatize(uint64(le)), commatize(n), commatize(m))\n    if all {\n        for c, esth := range esths {\n            fmt.Printf(\"%d \", esth)\n            if (c+1)%perLine == 0 {\n                fmt.Println()\n            }\n        }\n    } else {\n        for i := 0; i < perLine; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n        fmt.Println(\"\\n............\\n\")\n        for i := le - perLine; i < le; i++ {\n            fmt.Printf(\"%d \", esths[i])\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) 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    for b := uint64(2); b <= 16; b++ {\n        fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n        for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n            if isEsthetic(n, b) {\n                c++\n                if c >= 4*b {\n                    fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n                }\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n\n    \n    listEsths(1000, 1010, 9999, 9898, 16, true)\n    listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n    listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n    listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n    listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}\n", "C": "#include <stdio.h> \n#include <string.h>\n#include <locale.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\nchar as_digit(int d) { \n    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';  \n}\n\nvoid revstr(char *str) { \n    int i, len = strlen(str);\n    char t; \n    for (i = 0; i < len/2; ++i) { \n        t = str[i]; \n        str[i] = str[len - i - 1]; \n        str[len - i - 1] = t; \n    } \n}  \n\nchar* to_base(char s[], ull n, int b) { \n    int i = 0; \n    while (n) { \n        s[i++] = as_digit(n % b); \n        n /= b; \n    } \n    s[i] = '\\0'; \n    revstr(s);\n    return s;  \n} \n\null uabs(ull a, ull  b) {\n    return a > b ? a - b : b - a;\n}\n\nbool is_esthetic(ull n, int b) {\n    int i, j;\n    if (!n) return FALSE;\n    i = n % b;\n    n /= b;\n    while (n) {\n        j = n % b;\n        if (uabs(i, j) != 1) return FALSE;\n        n /= b;\n        i = j;\n    }\n    return TRUE;\n}\n\null esths[45000];\nint le = 0;\n\nvoid dfs(ull n, ull m, ull i) {\n    ull d, i1, i2;\n    if (i >= n && i <= m) esths[le++] = i;\n    if (i == 0 || i > m) return; \n    d = i % 10;\n    i1 = i * 10 + d - 1;\n    i2 = i1 + 2;\n    if (d == 0) {\n        dfs(n, m, i2);\n    } else if (d == 9) {\n        dfs(n, m, i1);\n    } else {\n        dfs(n, m, i1);\n        dfs(n, m, i2);\n    }\n}\n\nvoid list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {\n    int i;\n    le = 0;\n    for (i = 0; i < 10; ++i) {\n        dfs(n2, m2, i);\n    }\n    printf(\"Base 10: %'d esthetic numbers between %'llu and %'llu:\\n\", le, n, m);\n    if (all) {\n        for (i = 0; i < le; ++i) {\n            printf(\"%llu \", esths[i]);\n            if (!(i+1)%per_line) printf(\"\\n\");\n        }\n    } else {\n        for (i = 0; i < per_line; ++i) printf(\"%llu \", esths[i]);\n        printf(\"\\n............\\n\");\n        for (i = le - per_line; i < le; ++i) printf(\"%llu \", esths[i]);\n    }\n    printf(\"\\n\\n\");\n}\n\nint main() {\n    ull n;\n    int b, c;\n    char ch[15] = {0};\n    for (b = 2; b <= 16; ++b) {\n        printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b);\n        for (n = 1, c = 0; c < 6 * b; ++n) {\n            if (is_esthetic(n, b)) {\n                if (++c >= 4 * b) printf(\"%s \", to_base(ch, n, b));\n            }\n        }\n        printf(\"\\n\\n\");\n    }\n    char *oldLocale = setlocale(LC_NUMERIC, NULL);\n    setlocale(LC_NUMERIC, \"\"); \n\n    \n    list_esths(1000, 1010, 9999, 9898, 16, TRUE);\n    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);\n    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);\n    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);\n    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);\n    setlocale(LC_NUMERIC, oldLocale);\n    return 0;\n}\n"}
{"id": 60511, "name": "Topswops", "Go": "\n\n\npackage main\n\nimport \"fmt\"\n\nconst ( \n    maxn = 10 \n    maxl = 50 \n)\n\nfunc main() {\n    for i := 1; i <= maxn; i++ {\n        fmt.Printf(\"%d: %d\\n\", i, steps(i))\n    }\n}\n\nfunc steps(n int) int {\n    var a, b [maxl][maxn + 1]int\n    var x [maxl]int\n    a[0][0] = 1\n    var m int\n    for l := 0; ; {\n        x[l]++\n        k := int(x[l])\n        if k >= n {\n            if l <= 0 {\n                break\n            }\n            l--\n            continue\n        }\n        if a[l][k] == 0 {\n            if b[l][k+1] != 0 {\n                continue\n            }\n        } else if a[l][k] != k+1 {\n            continue\n        }\n        a[l+1] = a[l]\n        for j := 1; j <= k; j++ {\n            a[l+1][j] = a[l][k-j]\n        }\n        b[l+1] = b[l]\n        a[l+1][0] = k + 1\n        b[l+1][k+1] = 1\n        if l > m-1 {\n            m = l + 1\n        }\n        l++\n        x[l] = 0\n    }\n    return m\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\ntypedef struct { char v[16]; } deck;\ntypedef unsigned int uint;\n\nuint n, d, best[16];\n\nvoid tryswaps(deck *a, uint f, uint s) {\n#\tdefine A a->v\n#\tdefine B b.v\n\tif (d > best[n]) best[n] = d;\n\twhile (1) {\n\t\tif ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))\n\t\t\t&& (d + best[s] >= best[n] || A[s] == -1))\n\t\t\tbreak;\n\n\t\tif (d + best[s] <= best[n]) return;\n\t\tif (!--s) return;\n\t}\n\n\td++;\n\tdeck b = *a;\n\tfor (uint i = 1, k = 2; i <= s; k <<= 1, i++) {\n\t\tif (A[i] != i && (A[i] != -1 || (f & k)))\n\t\t\tcontinue;\n\n\t\tfor (uint j = B[0] = i; j--;) B[i - j] = A[j];\n\t\ttryswaps(&b, f | k, s);\n\t}\n\td--;\n}\n\nint main(void) {\n\tdeck x;\n\tmemset(&x, -1, sizeof(x));\n\tx.v[0] = 0;\n\n\tfor (n = 1; n < 13; n++) {\n\t\ttryswaps(&x, 1, n - 1);\n\t\tprintf(\"%2d: %d\\n\", n, best[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60512, "name": "Old Russian measure of length", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    units := []string{\n        \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n        \"arshin\", \"sazhen\", \"versta\", \"milia\",\n        \"centimeter\", \"meter\", \"kilometer\",\n    }\n\n    convs := []float32{\n        0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n        71.12, 213.36, 10668, 74676,\n        1, 100, 10000,\n    }\n\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        for i, u := range units {\n            fmt.Printf(\"%2d %s\\n\", i+1, u)\n        }\n        fmt.Println()\n        var unit int\n        var err error\n        for {\n            fmt.Print(\"Please choose a unit 1 to 13 : \")\n            scanner.Scan()\n            unit, err = strconv.Atoi(scanner.Text())\n            if err == nil && unit >= 1 && unit <= 13 {\n                break\n            }\n        }\n        unit--\n        var value float64\n        for {\n            fmt.Print(\"Now enter a value in that unit : \")\n            scanner.Scan()\n            value, err = strconv.ParseFloat(scanner.Text(), 32)\n            if err == nil && value >= 0 {\n                break\n            }\n        }\n        fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n        for i, u := range units {\n            if i == unit {\n                continue\n            }\n            fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n        }\n        fmt.Println()\n        yn := \"\"\n        for yn != \"y\" && yn != \"n\" {\n            fmt.Print(\"Do another one y/n : \")\n            scanner.Scan()\n            yn = strings.ToLower(scanner.Text())\n        }\n        if yn == \"n\" {\n            return\n        }\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\n#define UNITS_LENGTH 13\n\nint main(int argC,char* argV[])\n{\n\tint i,reference;\n\tchar *units[UNITS_LENGTH] = {\"kilometer\",\"meter\",\"centimeter\",\"tochka\",\"liniya\",\"diuym\",\"vershok\",\"piad\",\"fut\",\"arshin\",\"sazhen\",\"versta\",\"milia\"};\n    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};\n\t\n\tif(argC!=3)\n\t\tprintf(\"Usage : %s followed by length as <value> <unit>\");\n\telse{\n\t\tfor(i=0;argV[2][i]!=00;i++)\n\t\t\targV[2][i] = tolower(argV[2][i]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(strstr(argV[2],units[i])!=NULL){\n\t\t\t\treference = i;\n\t\t\t\tfactor = atof(argV[1])*values[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%s %s is equal in length to : \\n\",argV[1],argV[2]);\n\t\t\n\t\tfor(i=0;i<UNITS_LENGTH;i++){\n\t\t\tif(i!=reference)\n\t\t\t\tprintf(\"\\n%lf %s\",factor/values[i],units[i]);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 60513, "name": "Rate counter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\ntype rateStateS struct {\n    lastFlush time.Time\n    period    time.Duration\n    tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n    pRate.tickCount++\n    now := time.Now()\n    if now.Sub(pRate.lastFlush) >= pRate.period {\n        \n        tps := 0.\n        if pRate.tickCount > 0 {\n            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n        }\n        fmt.Println(tps, \"tics per second.\")\n\n        \n        pRate.tickCount = 0\n        pRate.lastFlush = now\n    }\n}\n\nfunc somethingWeDo() {\n    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) \n}\n\nfunc main() {\n    start := time.Now()\n\n    rateWatch := rateStateS{\n        lastFlush: start,\n        period:    5 * time.Second,\n    }\n\n    \n    latest := start\n    for latest.Sub(start) < 20*time.Second {\n        somethingWeDo()\n        ticRate(&rateWatch)\n        latest = time.Now()\n    }\n}\n", "C": "#include <stdio.h>\n#include <time.h>\n\n\n\nstruct rate_state_s\n{\n    time_t lastFlush;\n    time_t period;\n    size_t tickCount;\n};\n\nvoid tic_rate(struct rate_state_s* pRate)\n{\n    pRate->tickCount += 1;\n\n    time_t now = time(NULL);\n\n    if((now - pRate->lastFlush) >= pRate->period)\n    {\n        \n        size_t tps = 0.0;\n        if(pRate->tickCount > 0)\n            tps = pRate->tickCount / (now - pRate->lastFlush);\n\n        printf(\"%u tics per second.\\n\", tps);\n\n        \n        pRate->tickCount = 0;\n        pRate->lastFlush = now;\n    }\n}\n\n\n\nvoid something_we_do()\n{\n    \n    \n    \n    \n    \n    \n    \n    volatile size_t anchor = 0;\n    size_t x = 0;\n    for(x = 0; x < 0xffff; ++x)\n    {\n        anchor = x;\n    }\n}\n\nint main()\n{\n    time_t start = time(NULL);\n\n    struct rate_state_s rateWatch;\n    rateWatch.lastFlush = start;\n    rateWatch.tickCount = 0;\n    rateWatch.period = 5; \n\n    time_t latest = start;\n    \n    for(latest = start; (latest - start) < 20; latest = time(NULL))\n    {\n        \n        something_we_do();\n\n        \n        tic_rate(&rateWatch);\n    }\n\n    return 0;\n}\n"}
{"id": 60514, "name": "Sequence_ smallest number greater than previous term with exactly n divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    for i := 1; i*i <= n; i++ {\n        if n%i == 0 {\n            if i == n/i {\n                count++\n            } else {\n                count += 2\n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    const max = 15\n    fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n    for i, next := 1, 1; next <= max; i++ {\n        if next == countDivisors(i) {\n            fmt.Printf(\"%d \", i)\n            next++\n        }\n    }\n    fmt.Println()\n}\n", "C": "#include <stdio.h>\n\n#define MAX 15\n\nint count_divisors(int n) {\n    int i, count = 0;\n    for (i = 1; i * i <= n; ++i) {\n        if (!(n % i)) {\n            if (i == n / i)\n                count++;\n            else\n                count += 2;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int i, next = 1;\n    printf(\"The first %d terms of the sequence are:\\n\", MAX);\n    for (i = 1; next <= MAX; ++i) {\n        if (next == count_divisors(i)) {           \n            printf(\"%d \", i);\n            next++;\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60515, "name": "Padovan sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n"}
{"id": 60516, "name": "Padovan sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/big\"\n    \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n    p := make([]int, n)\n    p[0], p[1], p[2] = 1, 1, 1\n    for i := 3; i < n; i++ {\n        p[i] = p[i-2] + p[i-3]\n    }\n    return p\n}\n\nfunc padovanFloor(n int) []int {\n    var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n    p, _ = p.SetString(\"1.324717957244746025960908854\")\n    s, _ = s.SetString(\"1.0453567932525329623\")\n    f := make([]int, n)\n    pow := new(big.Rat).SetInt64(1)\n    u = u.SetFrac64(1, 2)\n    t.Quo(pow, p)\n    t.Quo(t, s)\n    t.Add(t, u)\n    v, _ := t.Float64()\n    f[0] = int(math.Floor(v))\n    for i := 1; i < n; i++ {\n        t.Quo(pow, s)\n        t.Add(t, u)\n        v, _ = t.Float64()\n        f[i] = int(math.Floor(v))\n        pow.Mul(pow, p)\n    }\n    return f\n}\n\ntype LSystem struct {\n    rules         map[string]string\n    init, current string\n}\n\nfunc step(lsys *LSystem) string {\n    var sb strings.Builder\n    if lsys.current == \"\" {\n        lsys.current = lsys.init\n    } else {\n        for _, c := range lsys.current {\n            sb.WriteString(lsys.rules[string(c)])\n        }\n        lsys.current = sb.String()\n    }\n    return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n    rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n    lsys := &LSystem{rules, \"A\", \"\"}\n    p := make([]string, n)\n    for i := 0; i < n; i++ {\n        p[i] = step(lsys)\n    }\n    return p\n}\n\n\nfunc areSame(l1, l2 []int) bool {\n    for i := 0; i < len(l1); i++ {\n        if l1[i] != l2[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"First 20 members of the Padovan sequence:\")\n    fmt.Println(padovanRecur(20))\n    recur := padovanRecur(64)\n    floor := padovanFloor(64)\n    same := areSame(recur, floor)\n    s := \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n    p := padovanLSys(32)\n    lsyst := make([]int, 32)\n    for i := 0; i < 32; i++ {\n        lsyst[i] = len(p[i])\n    }\n    fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n    fmt.Println(p[:10])\n    fmt.Println(\"\\nand their lengths:\")\n    fmt.Println(lsyst[:10])\n\n    same = areSame(recur[:32], lsyst)\n    s = \"give\"\n    if !same {\n        s = \"do not give\"\n    }\n    fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n\nint pRec(int n) {\n    static int *memo = NULL;\n    static size_t curSize = 0;\n    \n    \n    if (curSize <= (size_t) n) {\n        size_t lastSize = curSize;\n        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);\n        memo = realloc(memo, curSize * sizeof(int));\n        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));\n    }\n    \n    \n    if (memo[n] == 0) {\n        if (n<=2) memo[n] = 1;\n        else memo[n] = pRec(n-2) + pRec(n-3);\n    }\n    \n    return memo[n];\n}\n\n\nint pFloor(int n) {\n    long double p = 1.324717957244746025960908854;\n    long double s = 1.0453567932525329623;\n    return powl(p, n-1)/s + 0.5;\n}\n\n\nvoid nextLSystem(const char *prev, char *buf) {\n    while (*prev) {\n        switch (*prev++) {\n            case 'A': *buf++ = 'B'; break;\n            case 'B': *buf++ = 'C'; break;\n            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;\n        }\n    }\n    *buf = '\\0';\n}\n\nint main() {\n    \n    #define BUFSZ 8192\n    char buf1[BUFSZ], buf2[BUFSZ];\n    int i;\n    \n    \n    printf(\"P_0 .. P_19: \");\n    for (i=0; i<20; i++) printf(\"%d \", pRec(i));\n    printf(\"\\n\");\n    \n    \n    printf(\"The floor- and recurrence-based functions \");\n    for (i=0; i<64; i++) {\n        if (pRec(i) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d.\\n\",\n                i, pRec(i), pFloor(i));\n            break;\n        }\n    }\n    if (i == 64) {\n        printf(\"match from P_0 to P_63.\\n\");\n    }\n    \n    \n    printf(\"\\nThe first 10 L-system strings are:\\n\"); \n    for (strcpy(buf1, \"A\"), i=0; i<10; i++) {\n        printf(\"%s\\n\", buf1);\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    \n    \n    printf(\"\\nThe floor- and L-system-based functions \");\n    for (strcpy(buf1, \"A\"), i=0; i<32; i++) {\n        if ((int)strlen(buf1) != pFloor(i)) {\n            printf(\"do not match at %d: %d != %d\\n\",\n                i, (int)strlen(buf1), pFloor(i));\n            break;\n        }\n        strcpy(buf2, buf1);\n        nextLSystem(buf2, buf1);\n    }\n    if (i == 32) {\n        printf(\"match from P_0 to P_31.\\n\");\n    }\n    \n    return 0;\n}\n"}
{"id": 60517, "name": "Pythagoras tree", "Go": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth      = 11                    \n\tcolFactor     = uint8(255 / maxDepth) \n\tfileName      = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) \n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) \n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   \n\n\tdrawSquares(340, 550, 460, 550, img, 0) \n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid pythagorasTree(point a,point b,int times){\n\t\n\tpoint c,d,e;\n\t\n\tc.x = b.x - (a.y -  b.y);\n\tc.y = b.y - (b.x - a.x);\n\t\n\td.x = a.x - (a.y -  b.y);\n\td.y = a.y - (b.x - a.x);\n\t\n\te.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;\n\te.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;\n\t\n\tif(times>0){\n\t\tsetcolor(rand()%15 + 1);\n\t\t\n\t\tline(a.x,a.y,b.x,b.y);\n\t\tline(c.x,c.y,b.x,b.y);\n\t\tline(c.x,c.y,d.x,d.y);\n\t\tline(a.x,a.y,d.x,d.y);\n\t\t\n\t\tpythagorasTree(d,e,times-1);\n\t\tpythagorasTree(e,c,times-1);\n\t}\n}\n\nint main(){\n\t\n\tpoint a,b;\n\tdouble side;\n\tint iter;\n\t\n\ttime_t t;\n\t\n\tprintf(\"Enter initial side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\t\n\ta.x = 6*side/2 - side/2;\n\ta.y = 4*side;\n\tb.x = 6*side/2 + side/2;\n\tb.y = 4*side;\n\t\n\tinitwindow(6*side,4*side,\"Pythagoras Tree ?\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tpythagorasTree(a,b,iter);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n\n}\n"}
{"id": 60518, "name": "Odd word problem", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"unicode\"\n)\n\nfunc main() {\n    owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n    fmt.Println()\n    owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n    fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n    byte_in := func () byte {\n        bs := make([]byte, 1)\n        src.Read(bs)\n        return bs[0]\n    }\n    byte_out := func (b byte) { dst.Write([]byte{b}) }    \n    var odd func() byte\n    odd = func() byte {\n        s := byte_in()\n        if unicode.IsPunct(rune(s)) {\n            return s\n        }\n        b := odd()\n        byte_out(s)\n        return b\n    }\n    for {\n        for {\n            b := byte_in()\n            byte_out(b)\n            if b == '.' {\n                return\n            }\n            if unicode.IsPunct(rune(b)) {\n                break\n            }\n        }\n        b := odd()\n        byte_out(b)\n        if b == '.' {\n            return\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n\nstatic int \nowp(int odd)\n{\n        int ch, ret;\n        ch = getc(stdin);\n        if (!odd) {\n                putc(ch, stdout);\n                if (ch == EOF || ch == '.')\n                        return EOF;\n                if (ispunct(ch))\n                        return 0;\n                owp(odd);\n                return 0;\n        } else {\n                if (ispunct(ch))\n                        return ch; \n                ret = owp(odd);\n                putc(ch, stdout);\n                return ret;\n        }\n}\n\nint\nmain(int argc, char **argv)\n{\n        int ch = 1;\n        while ((ch = owp(!ch)) != EOF) {\n                if (ch)\n                        putc(ch, stdout);\n                if (ch == '.')\n                        break;\n        }\n        return 0;\n}\n"}
{"id": 60519, "name": "Pseudo-random numbers_Combined recursive generator MRG32k3a", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n\nfunc mod(x, y int64) int64 {\n    m := x % y\n    if m < 0 {\n        if y < 0 {\n            return m - y\n        } else {\n            return m + y\n        }\n    }\n    return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n    if seedState <= 0 || seedState >= d {\n        log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n    }\n    mrg.x1 = [3]int64{seedState, 0, 0}\n    mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} \n    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} \n    return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n    randomGen := MRG32k3aNew()\n    randomGen.seed(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n\nint64_t mod(int64_t x, int64_t y) {\n    int64_t m = x % y;\n    if (m < 0) {\n        if (y < 0) {\n            return m - y;\n        } else {\n            return m + y;\n        }\n    }\n    return m;\n}\n\n\n\nconst static int64_t a1[3] = { 0, 1403580, -810728 };\nconst static int64_t m1 = (1LL << 32) - 209;\n\nconst static int64_t a2[3] = { 527612, 0, -1370589 };\nconst static int64_t m2 = (1LL << 32) - 22853;\n\nconst static int64_t d = (1LL << 32) - 209 + 1; \n\n\nstatic int64_t x1[3];\n\nstatic int64_t x2[3];\n\nvoid seed(int64_t seed_state) {\n    x1[0] = seed_state;\n    x1[1] = 0;\n    x1[2] = 0;\n\n    x2[0] = seed_state;\n    x2[1] = 0;\n    x2[2] = 0;\n}\n\nint64_t next_int() {\n    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n    int64_t z = mod(x1i - x2i, m1);\n\n    \n    x1[2] = x1[1];\n    x1[1] = x1[0];\n    x1[0] = x1i;\n\n    \n    x2[2] = x2[1];\n    x2[1] = x2[0];\n    x2[0] = x2i;\n\n    return z + 1;\n}\n\ndouble next_float() {\n    return (double)next_int() / d;\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"%lld\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int64_t value = floor(next_float() * 5);\n        counts[value]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 60520, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 60521, "name": "Colorful numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc isColorful(n int) bool {\n    if n < 0 {\n        return false\n    }\n    if n < 10 {\n        return true\n    }\n    digits := rcu.Digits(n, 10)\n    for _, d := range digits {\n        if d == 0 || d == 1 {\n            return false\n        }\n    }\n    set := make(map[int]bool)\n    for _, d := range digits {\n        set[d] = true\n    }\n    dc := len(digits)\n    if len(set) < dc {\n        return false\n    }\n    for k := 2; k <= dc; k++ {\n        for i := 0; i <= dc-k; i++ {\n            prod := 1\n            for j := i; j <= i+k-1; j++ {\n                prod *= digits[j]\n            }\n            if ok := set[prod]; ok {\n                return false\n            }\n            set[prod] = true\n        }\n    }\n    return true\n}\n\nvar count = make([]int, 9)\nvar used = make([]bool, 11)\nvar largest = 0\n\nfunc countColorful(taken int, n string) {\n    if taken == 0 {\n        for digit := 0; digit < 10; digit++ {\n            dx := digit + 1\n            used[dx] = true\n            t := 1\n            if digit < 2 {\n                t = 9\n            }\n            countColorful(t, string(digit+48))\n            used[dx] = false\n        }\n    } else {\n        nn, _ := strconv.Atoi(n)\n        if isColorful(nn) {\n            ln := len(n)\n            count[ln]++\n            if nn > largest {\n                largest = nn\n            }\n        }\n        if taken < 9 {\n            for digit := 2; digit < 10; digit++ {\n                dx := digit + 1\n                if !used[dx] {\n                    used[dx] = true\n                    countColorful(taken+1, n+string(digit+48))\n                    used[dx] = false\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    var cn []int\n    for i := 0; i < 100; i++ {\n        if isColorful(i) {\n            cn = append(cn, i)\n        }\n    }\n    fmt.Println(\"The\", len(cn), \"colorful numbers less than 100 are:\")\n    for i := 0; i < len(cn); i++ {\n        fmt.Printf(\"%2d \", cn[i])\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n\n    countColorful(0, \"\")\n    fmt.Println(\"\\n\\nThe largest possible colorful number is:\")\n    fmt.Println(rcu.Commatize(largest))\n\n    fmt.Println(\"\\nCount of colorful numbers for each order of magnitude:\")\n    pow := 10\n    for dc := 1; dc < len(count); dc++ {\n        cdc := rcu.Commatize(count[dc])\n        pc := 100 * float64(count[dc]) / float64(pow)\n        fmt.Printf(\"  %d digit colorful number count: %6s - %7.3f%%\\n\", dc, cdc, pc)\n        if pow == 10 {\n            pow = 90\n        } else {\n            pow *= 10\n        }\n    }\n\n    sum := 0\n    for _, c := range count {\n        sum += c\n    }\n    fmt.Printf(\"\\nTotal colorful numbers: %s\\n\", rcu.Commatize(sum))\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <time.h>\n\nbool colorful(int n) {\n    \n    if (n < 0 || n > 98765432)\n        return false;\n    int digit_count[10] = {};\n    int digits[8] = {};\n    int num_digits = 0;\n    for (int m = n; m > 0; m /= 10) {\n        int d = m % 10;\n        if (n > 9 && (d == 0 || d == 1))\n            return false;\n        if (++digit_count[d] > 1)\n            return false;\n        digits[num_digits++] = d;\n    }\n    \n    int products[36] = {};\n    for (int i = 0, product_count = 0; i < num_digits; ++i) {\n        for (int j = i, p = 1; j < num_digits; ++j) {\n            p *= digits[j];\n            for (int k = 0; k < product_count; ++k) {\n                if (products[k] == p)\n                    return false;\n            }\n            products[product_count++] = p;\n        }\n    }\n    return true;\n}\n\nstatic int count[8];\nstatic bool used[10];\nstatic int largest = 0;\n\nvoid count_colorful(int taken, int n, int digits) {\n    if (taken == 0) {\n        for (int d = 0; d < 10; ++d) {\n            used[d] = true;\n            count_colorful(d < 2 ? 9 : 1, d, 1);\n            used[d] = false;\n        }\n    } else {\n        if (colorful(n)) {\n            ++count[digits - 1];\n            if (n > largest)\n                largest = n;\n        }\n        if (taken < 9) {\n            for (int d = 2; d < 10; ++d) {\n                if (!used[d]) {\n                    used[d] = true;\n                    count_colorful(taken + 1, n * 10 + d, digits + 1);\n                    used[d] = false;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    clock_t start = clock();\n\n    printf(\"Colorful numbers less than 100:\\n\");\n    for (int n = 0, count = 0; n < 100; ++n) {\n        if (colorful(n))\n            printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n\n    count_colorful(0, 0, 0);\n    printf(\"\\n\\nLargest colorful number: %'d\\n\", largest);\n\n    printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n    int total = 0;\n    for (int d = 0; d < 8; ++d) {\n        printf(\"%d   %'d\\n\", d + 1, count[d]);\n        total += count[d];\n    }\n    printf(\"\\nTotal: %'d\\n\", total);\n\n    clock_t end = clock();\n    printf(\"\\nElapsed time: %f seconds\\n\",\n           (end - start + 0.0) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 60522, "name": "Rosetta Code_Tasks without examples", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"html\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {    \n    ex := `<li><a href=\"/wiki/(.*?)\"`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    tasks := make([]string, len(matches))\n    for i, match := range matches {\n        tasks[i] = match[1]\n    }\n    const base = \"http:\n    const limit = 3 \n    ex = `(?s)using any language you may know.</div>(.*?)<div id=\"toc\"`\n    ex2 := `</?[^>]*>` \n    re = regexp.MustCompile(ex)\n    re2 := regexp.MustCompile(ex2)\n    for i, task := range tasks {\n        page = base + task\n        resp, _ = http.Get(page)\n        body, _ = ioutil.ReadAll(resp.Body)\n        match := re.FindStringSubmatch(string(body))\n        resp.Body.Close()\n        text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], \"\"))\n        fmt.Println(strings.Replace(task, \"_\", \" \", -1), \"\\n\", text)\n        if i == limit-1 {\n            break\n        }\n        time.Sleep(5 * time.Second) \n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_tasks_without_examples.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60523, "name": "Biorhythms", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n"}
{"id": 60524, "name": "Biorhythms", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"time\"\n)\n\nconst layout = \"2006-01-02\" \n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day   \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n    {\"up and rising\", \"peak\"},\n    {\"up but falling\", \"transition\"},\n    {\"down and falling\", \"valley\"},\n    {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc biorhythms(birthDate, targetDate string) {\n    bd, err := time.Parse(layout, birthDate)\n    check(err)\n    td, err := time.Parse(layout, targetDate)\n    check(err)\n    days := int(td.Sub(bd).Hours() / 24)\n    fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n    fmt.Println(\"Day\", days)\n    for i := 0; i < 3; i++ {\n        length := lengths[i]\n        cycle := cycles[i]\n        position := days % length\n        quadrant := position * 4 / length\n        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n        percent = math.Floor(percent*1000) / 10\n        descript := \"\"\n        if percent > 95 {\n            descript = \" peak\"\n        } else if percent < -95 {\n            descript = \" valley\"\n        } else if math.Abs(percent) < 5 {\n            descript = \" critical transition\"\n        } else {\n            daysToAdd := (quadrant+1)*length/4 - position\n            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n            trend := quadrants[quadrant][0]\n            next := quadrants[quadrant][1]\n            transStr := transition.Format(layout)\n            descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n        }\n        fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    datePairs := [][2]string{\n        {\"1943-03-09\", \"1972-07-11\"},\n        {\"1809-01-12\", \"1863-11-19\"},\n        {\"1809-02-12\", \"1863-11-19\"}, \n    }\n    for _, datePair := range datePairs {\n        biorhythms(datePair[0], datePair[1])\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint day(int y, int m, int d) {\n    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;\n}\n\nvoid cycle(int diff, int l, char *t) {\n    int p = round(100 * sin(2 * M_PI * diff / l));\n    printf(\"%12s cycle: %3i%%\", t, p);\n    if (abs(p) < 15)\n        printf(\" (critical day)\");\n    printf(\"\\n\");\n}\n\nint main(int argc, char *argv[]) {\n    int diff;\n\n    if (argc < 7) {\n        printf(\"Usage:\\n\");\n        printf(\"cbio y1 m1 d1 y2 m2 d2\\n\");\n        exit(1);\n    }\n    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))\n             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));\n    printf(\"Age: %u days\\n\", diff);\n    cycle(diff, 23, \"Physical\");\n    cycle(diff, 28, \"Emotional\");\n    cycle(diff, 33, \"Intellectual\");\n}\n"}
{"id": 60525, "name": "Table creation_Postal addresses", "Go": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n    \n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 60526, "name": "Sine wave", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os/exec\"\n)\n\nfunc main() {\n    synthType := \"sine\"\n    duration := \"5\"\n    frequency := \"440\"\n    cmd := exec.Command(\"play\", \"-n\", \"synth\", duration, synthType, frequency)\n    err := cmd.Run()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n\nint header[] = {46, 115, 110, 100, 0, 0, 0, 24,\n                255, 255, 255, 255, 0, 0, 0, 3,\n                0, 0, 172, 68, 0, 0, 0, 1};\n\nint main(int argc, char *argv[]){\n        float freq, dur;\n        long i, v;\n\n        if (argc < 3) {\n                printf(\"Usage:\\n\");\n                printf(\"  csine <frequency> <duration>\\n\");\n                exit(1);\n        }\n        freq = atof(argv[1]);\n        dur = atof(argv[2]);\n        for (i = 0; i < 24; i++)\n                putchar(header[i]);\n        for (i = 0; i < dur * 44100; i++) {\n                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));\n                v = v % 65536;\n                putchar(v >> 8);\n                putchar(v % 256);\n        }\n}\n"}
{"id": 60527, "name": "Compiler_code generator", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 60528, "name": "Compiler_code generator", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"encoding/binary\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype code = byte\n\nconst (\n    fetch code = iota\n    store\n    push\n    add\n    sub\n    mul\n    div\n    mod\n    lt\n    gt\n    le\n    ge\n    eq\n    ne\n    and\n    or\n    neg\n    not\n    jmp\n    jz\n    prtc\n    prts\n    prti\n    halt\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n    opcode   code\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent, 255},\n    {\"String\", ndString, 255},\n    {\"Integer\", ndInteger, 255},\n    {\"Sequence\", ndSequence, 255},\n    {\"If\", ndIf, 255},\n    {\"Prtc\", ndPrtc, 255},\n    {\"Prts\", ndPrts, 255},\n    {\"Prti\", ndPrti, 255},\n    {\"While\", ndWhile, 255},\n    {\"Assign\", ndAssign, 255},\n    {\"Negate\", ndNegate, neg},\n    {\"Not\", ndNot, not},\n    {\"Multiply\", ndMul, mul},\n    {\"Divide\", ndDiv, div},\n    {\"Mod\", ndMod, mod},\n    {\"Add\", ndAdd, add},\n    {\"Subtract\", ndSub, sub},\n    {\"Less\", ndLss, lt},\n    {\"LessEqual\", ndLeq, le},\n    {\"Greater\", ndGtr, gt},\n    {\"GreaterEqual\", ndGeq, ge},\n    {\"Equal\", ndEql, eq},\n    {\"NotEqual\", ndNeq, ne},\n    {\"And\", ndAnd, and},\n    {\"Or\", ndOr, or},\n}\n\nvar (\n    stringPool []string\n    globals    []string\n    object     []code\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n    return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\n\n\nfunc emitByte(c code) {\n    object = append(object, c)\n}\n\nfunc emitWord(n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for _, b := range bs {\n        emitByte(code(b))\n    }\n}\n\nfunc emitWordAt(at, n int) {\n    bs := make([]byte, 4)\n    binary.LittleEndian.PutUint32(bs, uint32(n))\n    for i := at; i < at+4; i++ {\n        object[i] = code(bs[i-at])\n    }\n}\n\nfunc hole() int {\n    t := len(object)\n    emitWord(0)\n    return t\n}\n\nfunc fetchVarOffset(id string) int {\n    for i := 0; i < len(globals); i++ {\n        if globals[i] == id {\n            return i\n        }\n    }\n    globals = append(globals, id)\n    return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n    for i := 0; i < len(stringPool); i++ {\n        if stringPool[i] == st {\n            return i\n        }\n    }\n    stringPool = append(stringPool, st)\n    return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n    if x == nil {\n        return\n    }\n    var n, p1, p2 int\n    switch x.nodeType {\n    case ndIdent:\n        emitByte(fetch)\n        n = fetchVarOffset(x.value)\n        emitWord(n)\n    case ndInteger:\n        emitByte(push)\n        n, err = strconv.Atoi(x.value)\n        check(err)\n        emitWord(n)\n    case ndString:\n        emitByte(push)\n        n = fetchStringOffset(x.value)\n        emitWord(n)\n    case ndAssign:\n        n = fetchVarOffset(x.left.value)\n        codeGen(x.right)\n        emitByte(store)\n        emitWord(n)\n    case ndIf:\n        codeGen(x.left)       \n        emitByte(jz)          \n        p1 = hole()           \n        codeGen(x.right.left) \n        if x.right.right != nil {\n            emitByte(jmp)\n            p2 = hole()\n        }\n        emitWordAt(p1, len(object)-p1)\n        if x.right.right != nil {\n            codeGen(x.right.right)\n            emitWordAt(p2, len(object)-p2)\n        }\n    case ndWhile:\n        p1 = len(object)\n        codeGen(x.left)                \n        emitByte(jz)                   \n        p2 = hole()                    \n        codeGen(x.right)               \n        emitByte(jmp)                  \n        emitWord(p1 - len(object))     \n        emitWordAt(p2, len(object)-p2) \n    case ndSequence:\n        codeGen(x.left)\n        codeGen(x.right)\n    case ndPrtc:\n        codeGen(x.left)\n        emitByte(prtc)\n    case ndPrti:\n        codeGen(x.left)\n        emitByte(prti)\n    case ndPrts:\n        codeGen(x.left)\n        emitByte(prts)\n    case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n        ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n        codeGen(x.left)\n        codeGen(x.right)\n        emitByte(nodeType2Op(x.nodeType))\n    case ndNegate, ndNot:\n        codeGen(x.left)\n        emitByte(nodeType2Op(x.nodeType))\n    default:\n        msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n        reportError(msg)\n    }\n}\n\nfunc codeFinish() {\n    emitByte(halt)\n}\n\nfunc listCode() {\n    fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n    for _, s := range stringPool {\n        fmt.Println(s)\n    }\n    pc := 0\n    for pc < len(object) {\n        fmt.Printf(\"%5d \", pc)\n        op := object[pc]\n        pc++\n        switch op {\n        case fetch:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"fetch [%d]\\n\", x)\n            pc += 4\n        case store:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"store [%d]\\n\", x)\n            pc += 4\n        case push:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"push  %d\\n\", x)\n            pc += 4\n        case add:\n            fmt.Println(\"add\")\n        case sub:\n            fmt.Println(\"sub\")\n        case mul:\n            fmt.Println(\"mul\")\n        case div:\n            fmt.Println(\"div\")\n        case mod:\n            fmt.Println(\"mod\")\n        case lt:\n            fmt.Println(\"lt\")\n        case gt:\n            fmt.Println(\"gt\")\n        case le:\n            fmt.Println(\"le\")\n        case ge:\n            fmt.Println(\"ge\")\n        case eq:\n            fmt.Println(\"eq\")\n        case ne:\n            fmt.Println(\"ne\")\n        case and:\n            fmt.Println(\"and\")\n        case or:\n            fmt.Println(\"or\")\n        case neg:\n            fmt.Println(\"neg\")\n        case not:\n            fmt.Println(\"not\")\n        case jmp:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jmp    (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case jz:\n            x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n            fmt.Printf(\"jz     (%d) %d\\n\", x, int32(pc)+x)\n            pc += 4\n        case prtc:\n            fmt.Println(\"prtc\")\n        case prti:\n            fmt.Println(\"prti\")\n        case prts:\n            fmt.Println(\"prts\")\n        case halt:\n            fmt.Println(\"halt\")\n        default:\n            reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n        }\n    }\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        return makeLeaf(nodeType, s)\n    }\n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    codeGen(loadAst())\n    codeFinish()\n    listCode()\n}\n", "C": "count = 1;\nwhile (count < 10) {\n    print(\"count is: \", count, \"\\n\");\n    count = count + 1;\n}\n"}
{"id": 60529, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "C": "\n#include <stdlib.h>\n\n\n#include \"myutil.h\"\n"}
{"id": 60530, "name": "Include a file", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n    fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n    hello()\n    hello2()\n}\n", "C": "\n#include <stdlib.h>\n\n\n#include \"myutil.h\"\n"}
{"id": 60531, "name": "VList", "Go": "package main\n\nimport \"fmt\" \n\ntype vList struct {\n    base   *vSeg\n    offset int\n}\n\ntype vSeg struct {\n    next *vSeg\n    ele  []vEle\n}\n\n\ntype vEle string\n    \n\nfunc (v vList) index(i int) (r vEle) {\n    if i >= 0 { \n        i += v.offset\n        for sg := v.base; sg != nil; sg = sg.next {\n            if i < len(sg.ele) {\n                return sg.ele[i]\n            }\n            i -= len(sg.ele)\n        }\n    }\n    \n    panic(\"index out of range\")\n}\n\n\nfunc (v vList) cons(a vEle) vList {\n    if v.base == nil {\n        return vList{base: &vSeg{ele: []vEle{a}}}\n    }\n    if v.offset == 0 {\n        l2 := len(v.base.ele) * 2 \n        ele := make([]vEle, l2)\n        ele[l2-1] = a\n        return vList{&vSeg{v.base, ele}, l2 - 1}\n    }\n    v.offset--\n    v.base.ele[v.offset] = a\n    return v\n}   \n\n\n\nfunc (v vList) cdr() vList {\n    if v.base == nil {\n        \n        panic(\"cdr on empty vList\")\n    }\n    v.offset++\n    if v.offset < len(v.base.ele) {\n        return v\n    }\n    return vList{v.base.next, 0}\n}\n\n\nfunc (v vList) length() int {\n    if v.base == nil {\n        return 0\n    }\n    return len(v.base.ele)*2 - v.offset - 1\n}\n\n\nfunc (v vList) String() string {\n    if v.base == nil {\n        return \"[]\"\n    }\n    r := fmt.Sprintf(\"[%v\", v.base.ele[v.offset])\n    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {\n        for _, e := range sl {\n            r = fmt.Sprintf(\"%s %v\", r, e)\n        }\n        sg = sg.next\n        if sg == nil {\n            break\n        }\n        sl = sg.ele\n    }\n    return r + \"]\"\n}\n\n\nfunc (v vList) printStructure() {\n    fmt.Println(\"offset:\", v.offset)\n    for sg := v.base; sg != nil; sg = sg.next {\n        fmt.Printf(\"  %q\\n\", sg.ele) \n    }\n    fmt.Println()\n}\n\n\nfunc main() {\n    var v vList\n    fmt.Println(\"zero value for type.  empty vList:\", v)\n    v.printStructure()\n\n    for a := '6'; a >= '1'; a-- {\n        v = v.cons(vEle(a))\n    }\n    fmt.Println(\"demonstrate cons. 6 elements added:\", v)\n    v.printStructure()\n    \n    v = v.cdr()\n    fmt.Println(\"demonstrate cdr. 1 element removed:\", v)\n    v.printStructure()\n\n    fmt.Println(\"demonstrate length. length =\", v.length())\n    fmt.Println()\n\n    fmt.Println(\"demonstrate element access. v[3] =\", v.index(3))\n    fmt.Println()\n\n    v = v.cdr().cdr()\n    fmt.Println(\"show cdr releasing segment. 2 elements removed:\", v)\n    v.printStructure()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct sublist{\n\tstruct sublist* next;\n\tint *buf;\n} sublist_t;\n\nsublist_t* sublist_new(size_t s)\n{\n\tsublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);\n\tsub->buf = (int*)(sub + 1);\n\tsub->next = 0;\n\treturn sub;\n}\n\ntypedef struct vlist_t {\n\tsublist_t* head;\n\tsize_t last_size, ofs;\n} vlist_t, *vlist;\n\nvlist v_new()\n{\n\tvlist v = malloc(sizeof(vlist_t));\n\tv->head = sublist_new(1);\n\tv->last_size = 1;\n\tv->ofs = 0;\n\treturn v;\n}\n\nvoid v_del(vlist v)\n{\n\tsublist_t *s;\n\twhile (v->head) {\n\t\ts = v->head->next;\n\t\tfree(v->head);\n\t\tv->head = s;\n\t}\n\tfree(v);\n}\n\ninline size_t v_size(vlist v)\n{\n\treturn v->last_size * 2 - v->ofs - 2;\n}\n\nint* v_addr(vlist v, size_t idx)\n{\n\tsublist_t *s = v->head;\n\tsize_t top = v->last_size, i = idx + v->ofs;\n\n\tif (i + 2 >= (top << 1)) {\n\t\tfprintf(stderr, \"!: idx %d out of range\\n\", (int)idx);\n\t\tabort();\n\t}\n\twhile (s && i >= top) {\n\t\ts = s->next, i ^= top;\n\t\ttop >>= 1;\n\t}\n\treturn s->buf + i;\n}\n\ninline int v_elem(vlist v, size_t idx)\n{\n\treturn *v_addr(v, idx);\n}\n\nint* v_unshift(vlist v, int x)\n{\n\tsublist_t* s;\n\tint *p;\n\n\tif (!v->ofs) {\n\t\tif (!(s = sublist_new(v->last_size << 1))) {\n\t\t\tfprintf(stderr, \"?: alloc failure\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tv->ofs = (v->last_size <<= 1);\n\t\ts->next = v->head;\n\t\tv->head = s;\n\t}\n\t*(p = v->head->buf + --v->ofs) = x;\n\treturn p;\n}\n\nint v_shift(vlist v)\n{\n\tsublist_t* s;\n\tint x;\n\n\tif (v->last_size == 1 && v->ofs == 1) {\n\t\tfprintf(stderr, \"!: empty list\\n\");\n\t\tabort();\n\t}\n\tx = v->head->buf[v->ofs++];\n\n\tif (v->ofs == v->last_size) {\n\t\tv->ofs = 0;\n\t\tif (v->last_size > 1) {\n\t\t\ts = v->head, v->head = s->next;\n\t\t\tv->last_size >>= 1;\n\t\t\tfree(s);\n\t\t}\n\t}\n\treturn x;\n}\n\nint main()\n{\n\tint i;\n\n\tvlist v = v_new();\n\tfor (i = 0; i < 10; i++) v_unshift(v, i);\n\n\tprintf(\"size: %d\\n\", v_size(v));\n\tfor (i = 0; i < 10; i++) printf(\"v[%d] = %d\\n\", i, v_elem(v, i));\n\tfor (i = 0; i < 10; i++) printf(\"shift: %d\\n\", v_shift(v));\n\n\t \n\n\tv_del(v);\n\treturn 0;\n}\n"}
{"id": 60532, "name": "VList", "Go": "package main\n\nimport \"fmt\" \n\ntype vList struct {\n    base   *vSeg\n    offset int\n}\n\ntype vSeg struct {\n    next *vSeg\n    ele  []vEle\n}\n\n\ntype vEle string\n    \n\nfunc (v vList) index(i int) (r vEle) {\n    if i >= 0 { \n        i += v.offset\n        for sg := v.base; sg != nil; sg = sg.next {\n            if i < len(sg.ele) {\n                return sg.ele[i]\n            }\n            i -= len(sg.ele)\n        }\n    }\n    \n    panic(\"index out of range\")\n}\n\n\nfunc (v vList) cons(a vEle) vList {\n    if v.base == nil {\n        return vList{base: &vSeg{ele: []vEle{a}}}\n    }\n    if v.offset == 0 {\n        l2 := len(v.base.ele) * 2 \n        ele := make([]vEle, l2)\n        ele[l2-1] = a\n        return vList{&vSeg{v.base, ele}, l2 - 1}\n    }\n    v.offset--\n    v.base.ele[v.offset] = a\n    return v\n}   \n\n\n\nfunc (v vList) cdr() vList {\n    if v.base == nil {\n        \n        panic(\"cdr on empty vList\")\n    }\n    v.offset++\n    if v.offset < len(v.base.ele) {\n        return v\n    }\n    return vList{v.base.next, 0}\n}\n\n\nfunc (v vList) length() int {\n    if v.base == nil {\n        return 0\n    }\n    return len(v.base.ele)*2 - v.offset - 1\n}\n\n\nfunc (v vList) String() string {\n    if v.base == nil {\n        return \"[]\"\n    }\n    r := fmt.Sprintf(\"[%v\", v.base.ele[v.offset])\n    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {\n        for _, e := range sl {\n            r = fmt.Sprintf(\"%s %v\", r, e)\n        }\n        sg = sg.next\n        if sg == nil {\n            break\n        }\n        sl = sg.ele\n    }\n    return r + \"]\"\n}\n\n\nfunc (v vList) printStructure() {\n    fmt.Println(\"offset:\", v.offset)\n    for sg := v.base; sg != nil; sg = sg.next {\n        fmt.Printf(\"  %q\\n\", sg.ele) \n    }\n    fmt.Println()\n}\n\n\nfunc main() {\n    var v vList\n    fmt.Println(\"zero value for type.  empty vList:\", v)\n    v.printStructure()\n\n    for a := '6'; a >= '1'; a-- {\n        v = v.cons(vEle(a))\n    }\n    fmt.Println(\"demonstrate cons. 6 elements added:\", v)\n    v.printStructure()\n    \n    v = v.cdr()\n    fmt.Println(\"demonstrate cdr. 1 element removed:\", v)\n    v.printStructure()\n\n    fmt.Println(\"demonstrate length. length =\", v.length())\n    fmt.Println()\n\n    fmt.Println(\"demonstrate element access. v[3] =\", v.index(3))\n    fmt.Println()\n\n    v = v.cdr().cdr()\n    fmt.Println(\"show cdr releasing segment. 2 elements removed:\", v)\n    v.printStructure()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct sublist{\n\tstruct sublist* next;\n\tint *buf;\n} sublist_t;\n\nsublist_t* sublist_new(size_t s)\n{\n\tsublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);\n\tsub->buf = (int*)(sub + 1);\n\tsub->next = 0;\n\treturn sub;\n}\n\ntypedef struct vlist_t {\n\tsublist_t* head;\n\tsize_t last_size, ofs;\n} vlist_t, *vlist;\n\nvlist v_new()\n{\n\tvlist v = malloc(sizeof(vlist_t));\n\tv->head = sublist_new(1);\n\tv->last_size = 1;\n\tv->ofs = 0;\n\treturn v;\n}\n\nvoid v_del(vlist v)\n{\n\tsublist_t *s;\n\twhile (v->head) {\n\t\ts = v->head->next;\n\t\tfree(v->head);\n\t\tv->head = s;\n\t}\n\tfree(v);\n}\n\ninline size_t v_size(vlist v)\n{\n\treturn v->last_size * 2 - v->ofs - 2;\n}\n\nint* v_addr(vlist v, size_t idx)\n{\n\tsublist_t *s = v->head;\n\tsize_t top = v->last_size, i = idx + v->ofs;\n\n\tif (i + 2 >= (top << 1)) {\n\t\tfprintf(stderr, \"!: idx %d out of range\\n\", (int)idx);\n\t\tabort();\n\t}\n\twhile (s && i >= top) {\n\t\ts = s->next, i ^= top;\n\t\ttop >>= 1;\n\t}\n\treturn s->buf + i;\n}\n\ninline int v_elem(vlist v, size_t idx)\n{\n\treturn *v_addr(v, idx);\n}\n\nint* v_unshift(vlist v, int x)\n{\n\tsublist_t* s;\n\tint *p;\n\n\tif (!v->ofs) {\n\t\tif (!(s = sublist_new(v->last_size << 1))) {\n\t\t\tfprintf(stderr, \"?: alloc failure\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tv->ofs = (v->last_size <<= 1);\n\t\ts->next = v->head;\n\t\tv->head = s;\n\t}\n\t*(p = v->head->buf + --v->ofs) = x;\n\treturn p;\n}\n\nint v_shift(vlist v)\n{\n\tsublist_t* s;\n\tint x;\n\n\tif (v->last_size == 1 && v->ofs == 1) {\n\t\tfprintf(stderr, \"!: empty list\\n\");\n\t\tabort();\n\t}\n\tx = v->head->buf[v->ofs++];\n\n\tif (v->ofs == v->last_size) {\n\t\tv->ofs = 0;\n\t\tif (v->last_size > 1) {\n\t\t\ts = v->head, v->head = s->next;\n\t\t\tv->last_size >>= 1;\n\t\t\tfree(s);\n\t\t}\n\t}\n\treturn x;\n}\n\nint main()\n{\n\tint i;\n\n\tvlist v = v_new();\n\tfor (i = 0; i < 10; i++) v_unshift(v, i);\n\n\tprintf(\"size: %d\\n\", v_size(v));\n\tfor (i = 0; i < 10; i++) printf(\"v[%d] = %d\\n\", i, v_elem(v, i));\n\tfor (i = 0; i < 10; i++) printf(\"shift: %d\\n\", v_shift(v));\n\n\t \n\n\tv_del(v);\n\treturn 0;\n}\n"}
{"id": 60533, "name": "VList", "Go": "package main\n\nimport \"fmt\" \n\ntype vList struct {\n    base   *vSeg\n    offset int\n}\n\ntype vSeg struct {\n    next *vSeg\n    ele  []vEle\n}\n\n\ntype vEle string\n    \n\nfunc (v vList) index(i int) (r vEle) {\n    if i >= 0 { \n        i += v.offset\n        for sg := v.base; sg != nil; sg = sg.next {\n            if i < len(sg.ele) {\n                return sg.ele[i]\n            }\n            i -= len(sg.ele)\n        }\n    }\n    \n    panic(\"index out of range\")\n}\n\n\nfunc (v vList) cons(a vEle) vList {\n    if v.base == nil {\n        return vList{base: &vSeg{ele: []vEle{a}}}\n    }\n    if v.offset == 0 {\n        l2 := len(v.base.ele) * 2 \n        ele := make([]vEle, l2)\n        ele[l2-1] = a\n        return vList{&vSeg{v.base, ele}, l2 - 1}\n    }\n    v.offset--\n    v.base.ele[v.offset] = a\n    return v\n}   \n\n\n\nfunc (v vList) cdr() vList {\n    if v.base == nil {\n        \n        panic(\"cdr on empty vList\")\n    }\n    v.offset++\n    if v.offset < len(v.base.ele) {\n        return v\n    }\n    return vList{v.base.next, 0}\n}\n\n\nfunc (v vList) length() int {\n    if v.base == nil {\n        return 0\n    }\n    return len(v.base.ele)*2 - v.offset - 1\n}\n\n\nfunc (v vList) String() string {\n    if v.base == nil {\n        return \"[]\"\n    }\n    r := fmt.Sprintf(\"[%v\", v.base.ele[v.offset])\n    for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {\n        for _, e := range sl {\n            r = fmt.Sprintf(\"%s %v\", r, e)\n        }\n        sg = sg.next\n        if sg == nil {\n            break\n        }\n        sl = sg.ele\n    }\n    return r + \"]\"\n}\n\n\nfunc (v vList) printStructure() {\n    fmt.Println(\"offset:\", v.offset)\n    for sg := v.base; sg != nil; sg = sg.next {\n        fmt.Printf(\"  %q\\n\", sg.ele) \n    }\n    fmt.Println()\n}\n\n\nfunc main() {\n    var v vList\n    fmt.Println(\"zero value for type.  empty vList:\", v)\n    v.printStructure()\n\n    for a := '6'; a >= '1'; a-- {\n        v = v.cons(vEle(a))\n    }\n    fmt.Println(\"demonstrate cons. 6 elements added:\", v)\n    v.printStructure()\n    \n    v = v.cdr()\n    fmt.Println(\"demonstrate cdr. 1 element removed:\", v)\n    v.printStructure()\n\n    fmt.Println(\"demonstrate length. length =\", v.length())\n    fmt.Println()\n\n    fmt.Println(\"demonstrate element access. v[3] =\", v.index(3))\n    fmt.Println()\n\n    v = v.cdr().cdr()\n    fmt.Println(\"show cdr releasing segment. 2 elements removed:\", v)\n    v.printStructure()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct sublist{\n\tstruct sublist* next;\n\tint *buf;\n} sublist_t;\n\nsublist_t* sublist_new(size_t s)\n{\n\tsublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);\n\tsub->buf = (int*)(sub + 1);\n\tsub->next = 0;\n\treturn sub;\n}\n\ntypedef struct vlist_t {\n\tsublist_t* head;\n\tsize_t last_size, ofs;\n} vlist_t, *vlist;\n\nvlist v_new()\n{\n\tvlist v = malloc(sizeof(vlist_t));\n\tv->head = sublist_new(1);\n\tv->last_size = 1;\n\tv->ofs = 0;\n\treturn v;\n}\n\nvoid v_del(vlist v)\n{\n\tsublist_t *s;\n\twhile (v->head) {\n\t\ts = v->head->next;\n\t\tfree(v->head);\n\t\tv->head = s;\n\t}\n\tfree(v);\n}\n\ninline size_t v_size(vlist v)\n{\n\treturn v->last_size * 2 - v->ofs - 2;\n}\n\nint* v_addr(vlist v, size_t idx)\n{\n\tsublist_t *s = v->head;\n\tsize_t top = v->last_size, i = idx + v->ofs;\n\n\tif (i + 2 >= (top << 1)) {\n\t\tfprintf(stderr, \"!: idx %d out of range\\n\", (int)idx);\n\t\tabort();\n\t}\n\twhile (s && i >= top) {\n\t\ts = s->next, i ^= top;\n\t\ttop >>= 1;\n\t}\n\treturn s->buf + i;\n}\n\ninline int v_elem(vlist v, size_t idx)\n{\n\treturn *v_addr(v, idx);\n}\n\nint* v_unshift(vlist v, int x)\n{\n\tsublist_t* s;\n\tint *p;\n\n\tif (!v->ofs) {\n\t\tif (!(s = sublist_new(v->last_size << 1))) {\n\t\t\tfprintf(stderr, \"?: alloc failure\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tv->ofs = (v->last_size <<= 1);\n\t\ts->next = v->head;\n\t\tv->head = s;\n\t}\n\t*(p = v->head->buf + --v->ofs) = x;\n\treturn p;\n}\n\nint v_shift(vlist v)\n{\n\tsublist_t* s;\n\tint x;\n\n\tif (v->last_size == 1 && v->ofs == 1) {\n\t\tfprintf(stderr, \"!: empty list\\n\");\n\t\tabort();\n\t}\n\tx = v->head->buf[v->ofs++];\n\n\tif (v->ofs == v->last_size) {\n\t\tv->ofs = 0;\n\t\tif (v->last_size > 1) {\n\t\t\ts = v->head, v->head = s->next;\n\t\t\tv->last_size >>= 1;\n\t\t\tfree(s);\n\t\t}\n\t}\n\treturn x;\n}\n\nint main()\n{\n\tint i;\n\n\tvlist v = v_new();\n\tfor (i = 0; i < 10; i++) v_unshift(v, i);\n\n\tprintf(\"size: %d\\n\", v_size(v));\n\tfor (i = 0; i < 10; i++) printf(\"v[%d] = %d\\n\", i, v_elem(v, i));\n\tfor (i = 0; i < 10; i++) printf(\"shift: %d\\n\", v_shift(v));\n\n\t \n\n\tv_del(v);\n\treturn 0;\n}\n"}
{"id": 60534, "name": "Stern-Brocot sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"sternbrocot\"\n)\n\nfunc main() {\n    \n    \n    g := sb.Generator()\n\n    \n    fmt.Println(\"First 15:\")\n    for i := 1; i <= 15; i++ {\n        fmt.Printf(\"%2d:  %d\\n\", i, g())\n    }\n\n    \n    \n    s := sb.New()\n    fmt.Println(\"First 15:\", s.FirstN(15))\n\n    \n    for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {\n        fmt.Printf(\"%3d at 1-based index %d\\n\", x, 1+s.Find(x))\n    }\n\n    \n    fmt.Println(\"1-based indexes: gcd\")\n    for n, f := range s.FirstN(1000)[:999] {\n        g := gcd(f, (*s)[n+1])\n        fmt.Printf(\"%d,%d: gcd(%d, %d) = %d\\n\", n+1, n+2, f, (*s)[n+1], g)\n        if g != 1 {\n            panic(\"oh no!\")\n            return\n        }\n    }\n}\n\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n", "C": "    k=2; i=1; j=2;\n    while(k<nn);\n        k++; sb[k]=sb[k-i]+sb[k-j];\n        k++; sb[k]=sb[k-j];\n        i++; j++;\n    }\n"}
{"id": 60535, "name": "Useless instructions", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\ntype any = interface{}\n\nfunc uselessFunc(uselessParam any) { \n    if true {\n        \n    } else {\n        fmt.Println(\"Never called\")\n    }\n\n    for range []any{} {\n        fmt.Println(\"Never called\")\n    }\n\n    for false {\n        fmt.Println(\"Never called\")\n    }\n\n    fmt.Print(\"\") \n\n    return \n}\n\ntype NotCompletelyUseless struct {\n    \n}\n\nfunc main() {\n    uselessFunc(0)\n    set := make(map[int]NotCompletelyUseless)\n    set[0] = NotCompletelyUseless{}\n    set[0] = NotCompletelyUseless{} \n    fmt.Println(set)\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nvoid uselessFunc(int uselessParam) { \n    auto int i; \n\n    if (true) {\n        \n    } else {\n        printf(\"Never called\\n\");\n    }\n\n    for (i = 0; i < 0; ++i) {\n        printf(\"Never called\\n\");\n    }\n\n    while (false) {\n        printf(\"Never called\\n\");\n    }\n\n    printf(\"\"); \n\n    return; \n}\n\nstruct UselessStruct {\n    \n};\n\nint main() {\n    uselessFunc(0);\n    printf(\"Working OK.\\n\");\n}\n"}
{"id": 60536, "name": "Numeric error propagation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\ntype unc struct {\n    n float64 \n    s float64 \n}\n\n\nfunc newUnc(n, s float64) *unc {\n    return &unc{n, s * s}\n}\n\n\n\nfunc (z *unc) errorTerm() float64 {\n    return math.Sqrt(z.s)\n}\n\n\n\n\n\n\n\n\n\nfunc (z *unc) addC(a *unc, c float64) *unc {\n    *z = *a\n    z.n += c\n    return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n    *z = *a\n    z.n -= c\n    return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n    z.n = a.n + b.n\n    z.s = a.s + b.s\n    return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n    z.n = a.n - b.n\n    z.s = a.s + b.s\n    return z\n}\n\n\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n    z.n = a.n * c\n    z.s = a.s * c * c\n    return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n    z.n = a.n / c\n    z.s = a.s / (c * c)\n    return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n    prod := a.n * b.n\n    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n    quot := a.n / b.n\n    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n    return z\n}\n\n\nfunc (z *unc) expC(a *unc, c float64) *unc {\n    f := math.Pow(a.n, c)\n    g := f * c / a.n\n    z.n = f\n    z.s = a.s * g * g\n    return z\n}\n\nfunc main() {\n    x1 := newUnc(100, 1.1)\n    x2 := newUnc(200, 2.2)\n    y1 := newUnc(50, 1.2)\n    y2 := newUnc(100, 2.3)\n    var d, d2 unc\n    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n    fmt.Println(\"d:    \", d.n)\n    fmt.Println(\"error:\", d.errorTerm())\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n \ntypedef struct{\n    double value;\n    double delta;\n}imprecise;\n \n#define SQR(x) ((x) * (x))\nimprecise imprecise_add(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value + b.value;\n    ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));\n    return ret;\n}\n \nimprecise imprecise_mul(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value * b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));\n    return ret;\n}\n \nimprecise imprecise_div(imprecise a, imprecise b)\n{\n    imprecise ret;\n    ret.value = a.value / b.value;\n    ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);\n    return ret;\n}\n \nimprecise imprecise_pow(imprecise a, double c)\n{\n    imprecise ret;\n    ret.value = pow(a.value, c);\n    ret.delta = fabs(ret.value * c * a.delta / a.value);\n    return ret;\n}\n\nchar* printImprecise(imprecise val)\n{\n\tchar principal[30],error[30],*string,sign[2];\n\tsign[0] = 241;    \n\tsign[1] = 00;\n\t\n\tsprintf(principal,\"%f\",val.value);\n\tsprintf(error,\"%f\",val.delta);\n\t\n\tstring = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));\n\t\n\tstrcpy(string,principal);\n\tstrcat(string,sign);\n\tstrcat(string,error);\n\t\n\treturn string;\n}\n \nint main(void) {\n    imprecise x1 = {100, 1.1};\n    imprecise y1 = {50, 1.2};\n    imprecise x2 = {-200, 2.2};\n    imprecise y2 = {-100, 2.3};\n    imprecise d;\n \n    d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);\n    printf(\"Distance, d, between the following points :\");\n    printf(\"\\n( x1, y1) = ( %s, %s)\",printImprecise(x1),printImprecise(y1));\n    printf(\"\\n( x2, y2) = ( %s, %s)\",printImprecise(x2),printImprecise(y2));\n    printf(\"\\nis d = %s\", printImprecise(d));\n    return 0;\n}\n"}
{"id": 60537, "name": "Soundex", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"unicode\"\n)\n\nvar code = []byte(\"01230127022455012623017202\")\n\nfunc soundex(s string) (string, error) {\n    var sx [4]byte\n    var sxi int\n    var cx, lastCode byte\n    for i, c := range s {\n        switch {\n        case !unicode.IsLetter(c):\n            if c < ' ' || c == 127 {\n                return \"\", errors.New(\"ASCII control characters disallowed\")\n            }\n            if i == 0 {\n                return \"\", errors.New(\"initial character must be a letter\")\n            }\n            lastCode = '0'\n            continue\n        case c >= 'A' && c <= 'Z':\n            cx = byte(c - 'A')\n        case c >= 'a' && c <= 'z':\n            cx = byte(c - 'a')\n        default:\n            return \"\", errors.New(\"non-ASCII letters unsupported\")\n        }\n        \n        if i == 0 {\n            sx[0] = cx + 'A'\n            sxi = 1\n            continue\n        }\n        switch x := code[cx]; x {\n        case '7', lastCode:\n        case '0':\n            lastCode = '0'\n        default:\n            sx[sxi] = x\n            if sxi == 3 {\n                return string(sx[:]), nil\n            }\n            sxi++\n            lastCode = x\n        }\n    }\n    if sxi == 0 {\n        return \"\", errors.New(\"no letters present\")\n    }\n    for ; sxi < 4; sxi++ {\n        sx[sxi] = '0'\n    }\n    return string(sx[:]), nil\n}\n\nfunc main() {\n    for _, s := range []string{\n        \"Robert\",   \n        \"Rupert\",   \n        \"Rubin\",    \n        \"ashcroft\", \n        \"ashcraft\", \n        \"moses\",    \n        \"O'Mally\",  \n        \"d jay\",    \n        \"R2-D2\",    \n        \"12p2\",     \n        \"naïve\",    \n        \"\",         \n        \"bump\\t\",   \n    } {\n        if x, err := soundex(s); err == nil {\n            fmt.Println(\"soundex\", s, \"=\", x)\n        } else {\n            fmt.Printf(\"\\\"%s\\\" fail. %s\\n\", s, err)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic char code[128] = { 0 };\nvoid add_code(const char *s, int c)\n{\n\twhile (*s) {\n\t\tcode[(int)*s] = code[0x20 ^ (int)*s] = c;\n\t\ts++;\n\t}\n}\n\nvoid init()\n{\n\tstatic const char *cls[] =\n\t\t{ \"AEIOU\", \"\", \"BFPV\", \"CGJKQSXZ\", \"DT\", \"L\", \"MN\", \"R\", 0};\n\tint i;\n\tfor (i = 0; cls[i]; i++)\n\t\tadd_code(cls[i], i - 1);\n}\n\n\nconst char* soundex(const char *s)\n{\n\tstatic char out[5];\n\tint c, prev, i;\n\n\tout[0] = out[4] = 0;\n\tif (!s || !*s) return out;\n\n\tout[0] = *s++;\n\n\t\n\tprev = code[(int)out[0]];\n\tfor (i = 1; *s && i < 4; s++) {\n\t\tif ((c = code[(int)*s]) == prev) continue;\n\n\t\tif (c == -1) prev = 0;\t\n\t\telse if (c > 0) {\n\t\t\tout[i++] = c + '0';\n\t\t\tprev = c;\n\t\t}\n\t}\n\twhile (i < 4) out[i++] = '0';\n\treturn out;\n}\n\nint main()\n{\n\tint i;\n\tconst char *sdx, *names[][2] = {\n\t\t{\"Soundex\",\t\"S532\"},\n\t\t{\"Example\",\t\"E251\"},\n\t\t{\"Sownteks\",\t\"S532\"},\n\t\t{\"Ekzampul\",\t\"E251\"},\n\t\t{\"Euler\",\t\"E460\"},\n\t\t{\"Gauss\",\t\"G200\"},\n\t\t{\"Hilbert\",\t\"H416\"},\n\t\t{\"Knuth\",\t\"K530\"},\n\t\t{\"Lloyd\",\t\"L300\"},\n\t\t{\"Lukasiewicz\",\t\"L222\"},\n\t\t{\"Ellery\",\t\"E460\"},\n\t\t{\"Ghosh\",\t\"G200\"},\n\t\t{\"Heilbronn\",\t\"H416\"},\n\t\t{\"Kant\",\t\"K530\"},\n\t\t{\"Ladd\",\t\"L300\"},\n\t\t{\"Lissajous\",\t\"L222\"},\n\t\t{\"Wheaton\",\t\"W350\"},\n\t\t{\"Burroughs\",\t\"B620\"},\n\t\t{\"Burrows\",\t\"B620\"},\n\t\t{\"O'Hara\",\t\"O600\"},\n\t\t{\"Washington\",\t\"W252\"},\n\t\t{\"Lee\",\t\t\"L000\"},\n\t\t{\"Gutierrez\",\t\"G362\"},\n\t\t{\"Pfister\",\t\"P236\"},\n\t\t{\"Jackson\",\t\"J250\"},\n\t\t{\"Tymczak\",\t\"T522\"},\n\t\t{\"VanDeusen\",\t\"V532\"},\n\t\t{\"Ashcraft\",\t\"A261\"},\n\t\t{0, 0}\n\t};\n\n\tinit();\n\n\tputs(\"  Test name  Code  Got\\n----------------------\");\n\tfor (i = 0; names[i][0]; i++) {\n\t\tsdx = soundex(names[i][0]);\n\t\tprintf(\"%11s  %s  %s \", names[i][0], names[i][1], sdx);\n\t\tprintf(\"%s\\n\", strcmp(sdx, names[i][1]) ? \"not ok\" : \"ok\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60538, "name": "List rooted trees", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n    list   []tree\n    offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n    list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n    for ; l > 0; t >>= 1 {\n        l--\n        var paren byte\n        if (t & 1) != 0 {\n            paren = '('\n        } else {\n            paren = ')'\n        }\n        fmt.Printf(\"%c\", paren)\n    }\n}\n\nfunc listTrees(n uint) {\n    for i := offset[n]; i < offset[n+1]; i++ {\n        show(list[i], n*2)\n        fmt.Println()\n    }\n}\n\n\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n    if rem == 0 {\n        add(t)\n        return\n    }\n\n    if sl > rem { \n        sl = rem\n        pos = offset[sl]\n    } else if pos >= offset[sl+1] {\n        \n        sl--\n        if sl == 0 {\n            return\n        }\n        pos = offset[sl]\n    }\n\n    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n    assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n    if offset[n+1] > 0 {\n        return\n    }\n    if n > 0 {\n        mktrees(n - 1)\n    }\n\n    assemble(n, 0, n-1, offset[n-1], n-1)\n    offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n    if len(os.Args) != 2 {\n        log.Fatal(\"There must be exactly 1 command line argument\")\n    }\n    n, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        log.Fatal(\"Argument is not a valid number\")\n    }\n    if n <= 0 || n > 19 { \n        n = 5\n    }\n    \n    add(0)\n\n    mktrees(uint(n))\n    fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n    listTrees(uint(n))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\ntypedef unsigned long long tree;\n#define B(x) (1ULL<<(x))\n\ntree *list = 0;\nuint cap = 0, len = 0;\nuint offset[32] = {0, 1, 0};\n\nvoid append(tree t)\n{\n\tif (len == cap) {\n\t\tcap = cap ? cap*2 : 2;\n\t\tlist = realloc(list, cap*sizeof(tree));\n\t}\n\tlist[len++] = 1 | t<<1;\n}\n\nvoid show(tree t, uint len)\n{\n\tfor (; len--; t >>= 1)\n\t\tputchar(t&1 ? '(' : ')');\n}\n\nvoid listtrees(uint n)\n{\n\tuint i;\n\tfor (i = offset[n]; i < offset[n+1]; i++) {\n\t\tshow(list[i], n*2);\n\t\tputchar('\\n');\n\t}\n}\n\n\nvoid assemble(uint n, tree t, uint sl, uint pos, uint rem)\n{\n\tif (!rem) {\n\t\tappend(t);\n\t\treturn;\n\t}\n\n\tif (sl > rem) \n\t\tpos = offset[sl = rem];\n\telse if (pos >= offset[sl + 1]) {\n\t\t\n\t\tif (!--sl) return;\n\t\tpos = offset[sl];\n\t}\n\n\tassemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);\n\tassemble(n, t, sl, pos + 1, rem);\n}\n\nvoid mktrees(uint n)\n{\n\tif (offset[n + 1]) return;\n\tif (n) mktrees(n - 1);\n\n\tassemble(n, 0, n-1, offset[n-1], n-1);\n\toffset[n+1] = len;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;\n\n\t\n\tappend(0);\n\n\tmktrees((uint)n);\n\tfprintf(stderr, \"Number of %d-trees: %u\\n\", n, offset[n+1] - offset[n]);\n\tlisttrees((uint)n);\n\n\treturn 0;\n}\n"}
{"id": 60539, "name": "Documentation", "Go": "\n\n\n\npackage example\n\n\nvar (\n    \n    X, Y, Z int \n)\n\n\nfunc XP() { \n    \n}\n\n\nfunc nonXP() {}\n\n\n\nvar MEMEME int\n", "C": "\nint add(int a, int b) {\n    return a + b;\n}\n"}
{"id": 60540, "name": "Table creation", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n"}
{"id": 60541, "name": "Table creation", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"encoding/json\"\n    \"fmt\"\n    \"github.com/boltdb/bolt\"\n    \"log\"\n)\n\ntype StockTrans struct {\n    Id       int \n    Date     string\n    Trans    string\n    Symbol   string\n    Quantity int\n    Price    float32\n    Settled  bool\n}\n\n\nfunc (st *StockTrans) save(db *bolt.DB, bucket string) error {\n    err := db.Update(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(bucket))\n        id, _ := b.NextSequence()\n        st.Id = int(id)\n        encoded, err := json.Marshal(st)\n        if err != nil {\n            return err\n        }\n        return b.Put(itob(st.Id), encoded)\n    })\n    return err\n}\n\n\nfunc itob(i int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(i))\n    return b\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    db, err := bolt.Open(\"store.db\", 0600, nil)\n    check(err)\n    defer db.Close()\n\n    \n    err = db.Update(func(tx *bolt.Tx) error {\n        _, err := tx.CreateBucketIfNotExists([]byte(\"stocks\"))\n        return err\n    })\n    check(err)\n\n    transactions := []*StockTrans{\n        {0, \"2006-01-05\", \"BUY\", \"RHAT\", 100, 35.14, true},\n        {0, \"2006-03-28\", \"BUY\", \"IBM\", 1000, 45, true},\n        {0, \"2006-04-06\", \"SELL\", \"IBM\", 500, 53, true},\n        {0, \"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72, false},\n    }\n\n    \n    for _, trans := range transactions {\n        err := trans.save(db, \"stocks\")\n        check(err)\n    }\n\n    \n    fmt.Println(\"Id     Date    Trans  Sym    Qty  Price  Settled\")\n    fmt.Println(\"------------------------------------------------\")\n    db.View(func(tx *bolt.Tx) error {\n        b := tx.Bucket([]byte(\"stocks\"))\n        b.ForEach(func(k, v []byte) error {\n            st := new(StockTrans)\n            err := json.Unmarshal(v, st)\n            check(err)\n            fmt.Printf(\"%d  %s  %-4s  %-5s  %4d  %2.2f  %t\\n\",\n                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)\n            return nil\n        })\n        return nil\n    })\n}\n", "C": "#include <sqlite3.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n\tconst char *code = \n\t\"CREATE TABLE employee (\\n\"\n\t\"    empID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\t\"\tfirstName\tTEXT NOT NULL,\\n\"\n\t\"\tlastName\tTEXT NOT NULL,\\n\"\n\t\"\tAGE\t\t\tINTEGER NOT NULL,\\n\"\n\t\"\tDOB\t\t\tDATE NOT NULL)\\n\" ; \n\t\n  if ( sqlite3_open(\"employee.db\", &db) == SQLITE_OK ) {\n    sqlite3_exec(db, code, NULL, NULL,  &errmsg);\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return 0;\n}\n"}
{"id": 60542, "name": "Problem of Apollonius", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype circle struct {\n    x, y, r float64\n}\n\nfunc main() {\n    c1 := circle{0, 0, 1}\n    c2 := circle{4, 0, 1}\n    c3 := circle{2, 4, 2}\n    fmt.Println(ap(c1, c2, c3, true))\n    fmt.Println(ap(c1, c2, c3, false))\n}\n\nfunc ap(c1, c2, c3 circle, s bool) circle {\n    x1sq := c1.x * c1.x\n    y1sq := c1.y * c1.y\n    r1sq := c1.r * c1.r\n    x2sq := c2.x * c2.x\n    y2sq := c2.y * c2.y\n    r2sq := c2.r * c2.r\n    x3sq := c3.x * c3.x\n    y3sq := c3.y * c3.y\n    r3sq := c3.r * c3.r\n    v11 := 2 * (c2.x - c1.x)\n    v12 := 2 * (c2.y - c1.y)\n    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq\n    v14 := 2 * (c2.r - c1.r)\n    v21 := 2 * (c3.x - c2.x)\n    v22 := 2 * (c3.y - c2.y)\n    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq\n    v24 := 2 * (c3.r - c2.r)\n    if s {\n        v14 = -v14\n        v24 = -v24\n    }\n    w12 := v12 / v11\n    w13 := v13 / v11\n    w14 := v14 / v11\n    w22 := v22/v21 - w12\n    w23 := v23/v21 - w13\n    w24 := v24/v21 - w14\n    p := -w23 / w22\n    q := w24 / w22\n    m := -w12*p - w13\n    n := w14 - w12*q\n    a := n*n + q*q - 1\n    b := m*n - n*c1.x + p*q - q*c1.y\n    if s {\n        b -= c1.r\n    } else {\n        b += c1.r\n    }\n    b *= 2\n    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq\n    d := b*b - 4*a*c\n    rs := (-b - math.Sqrt(d)) / (2 * a)\n    return circle{m + n*rs, p + q*rs, rs}\n}\n", "C": "#include <stdio.h>\n#include <tgmath.h>\n\n#define VERBOSE 0\n#define for3 for(int i = 0; i < 3; i++)\n\ntypedef complex double vec;\ntypedef struct { vec c; double r; } circ;\n\n#define re(x) creal(x)\n#define im(x) cimag(x)\n#define cp(x) re(x), im(x)\n#define CPLX \"(%6.3f,%6.3f)\"\n#define CPLX3 CPLX\" \"CPLX\" \"CPLX\n\ndouble cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }\ndouble abs2(vec a) { return a * conj(a); }\n \nint apollonius_in(circ aa[], int ss[], int flip, int divert)\n{\n\tvec n[3], x[3], t[3], a, b, center;\n\tint s[3], iter = 0, res = 0;\n\tdouble diff = 1, diff_old = -1, axb, d, r;\n \n\tfor3 {\n\t\ts[i] = ss[i] ? 1 : -1;\n\t\tx[i] = aa[i].c;\n\t}\n \n\twhile (diff > 1e-20) {\n\t\ta = x[0] - x[2], b = x[1] - x[2];\n\t\tdiff = 0;\n\t\taxb = -cross(a, b);\n\t\td = sqrt(abs2(a) * abs2(b) * abs2(a - b));\n\n\t\tif (VERBOSE) {\n\t\t\tconst char *z = 1 + \"-0+\";\n\t\t\tprintf(\"%c%c%c|%c%c|\",\n\t\t\t\tz[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);\n\t\t\tprintf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));\n\t\t}\n\n\t\t\n\t\tr = fabs(d / (2 * axb));\n\t\tcenter = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];\n \n \t\t\n\t\tif (!axb && flip != -1 && !divert) {\n\t\t\tif (!d) { \n\t\t\t\tprintf(\"Given conditions confused me.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (VERBOSE) puts(\"\\n[divert]\");\n\t\t\tdivert = 1;\n\t\t\tres = apollonius_in(aa, ss, -1, 1);\n\t\t}\n\n \t\t\n\t\tfor3 n[i] = axb ? aa[i].c - center : a * I * flip;\n\t\tfor3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];\n\n\t\t\n\t\tfor3 diff += abs2(t[i] - x[i]), x[i] = t[i];\n\n\t\tif (VERBOSE) printf(\" %g\\n\", diff);\n \n \t\t\n\t\tif (diff >= diff_old && diff_old >= 0)\n\t\t\tif (iter++ > 20) return res;\n\n\t\tdiff_old = diff;\n\t}\n\n\tprintf(\"found: \");\n\tif (axb) printf(\"circle \"CPLX\", r = %f\\n\", cp(center), r);\n\telse\t printf(\"line \"CPLX3\"\\n\", cp(x[0]), cp(x[1]), cp(x[2]));\n\n\treturn res + 1;\n}\n \nint apollonius(circ aa[])\n{\n\tint s[3], i, sum = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\ts[0] = i & 1, s[1] = i & 2, s[2] = i & 4;\n\n\t\t\n\t\tif (s[0] && !aa[0].r) continue;\n\t\tif (s[1] && !aa[1].r) continue;\n\t\tif (s[2] && !aa[2].r) continue;\n\t\tsum += apollonius_in(aa, s, 1, 0);\n\t}\n\treturn sum;\n}\n \nint main()\n{\n\tcirc a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};\n\tcirc b[3] = {{-3, 2}, {0, 1}, {3, 2}};\n\tcirc c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};\n\t\n \n\tputs(\"set 1\"); apollonius(a);\n\tputs(\"set 2\"); apollonius(b);\n\tputs(\"set 3\"); apollonius(c);\n}\n"}
{"id": 60543, "name": "Morpion solitaire", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nconst (\n    lineLen  = 5\n    disjoint = 0\n)\n\nvar (\n    board  [][]int\n    width  int\n    height int\n)\n\nconst (\n    blank    = 0\n    occupied = 1 << (iota - 1)\n    dirNS\n    dirEW\n    dirNESW\n    dirNWSE\n    newlyAdded\n    current\n)\n\nvar ofs = [4][3]int{\n    {0, 1, dirNS},\n    {1, 0, dirEW},\n    {1, -1, dirNESW},\n    {1, 1, dirNWSE},\n}\n\ntype move struct{ m, s, seq, x, y int }\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc allocBoard(w, h int) [][]int {\n    buf := make([][]int, h)\n    for i := 0; i < h; i++ {\n        buf[i] = make([]int, w)\n    }\n    return buf\n}\n\nfunc boardSet(v, x0, y0, x1, y1 int) {\n    for i := y0; i <= y1; i++ {\n        for j := x0; j <= x1; j++ {\n            board[i][j] = v\n        }\n    }\n}\n\nfunc initBoard() {\n    height = 3 * (lineLen - 1)\n    width = height\n    board = allocBoard(width, height)\n\n    boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)\n    boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)\n    boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)\n    boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)\n}\n\n\nfunc expandBoard(dw, dh int) {\n    dw2, dh2 := 1, 1\n    if dw == 0 {\n        dw2 = 0\n    }\n    if dh == 0 {\n        dh2 = 0\n    }\n    nw, nh := width+dw2, height+dh2\n    nbuf := allocBoard(nw, nh)\n    dw, dh = -btoi(dw < 0), -btoi(dh < 0)\n    for i := 0; i < nh; i++ {\n        if i+dh < 0 || i+dh >= height {\n            continue\n        }\n        for j := 0; j < nw; j++ {\n            if j+dw < 0 || j+dw >= width {\n                continue\n            }\n            nbuf[i][j] = board[i+dh][j+dw]\n        }\n    }\n    board = nbuf\n    width, height = nw, nh\n}\n\nfunc showBoard(scr *gc.Window) {\n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            var temp string\n            switch {\n            case (board[i][j] & current) != 0:\n                temp = \"X \"\n            case (board[i][j] & newlyAdded) != 0:\n                temp = \"0 \"\n            case (board[i][j] & occupied) != 0:\n                temp = \"+ \"\n            default:\n                temp = \"  \"\n            }\n            scr.MovePrintf(i+1, j*2, temp)\n        }\n    }\n    scr.Refresh()\n}\n\n\nfunc testPosition(y, x int, rec *move) {\n    if (board[y][x] & occupied) != 0 {\n        return\n    }\n    for m := 0; m < 4; m++ { \n        dx := ofs[m][0]\n        dy := ofs[m][1]\n        dir := ofs[m][2]\n        var k int\n        for s := 1 - lineLen; s <= 0; s++ { \n            for k = 0; k < lineLen; k++ {\n                if s+k == 0 {\n                    continue\n                }\n                xx := x + dx*(s+k)\n                yy := y + dy*(s+k)\n                if xx < 0 || xx >= width || yy < 0 || yy >= height {\n                    break\n                }\n\n                \n                if (board[yy][xx] & occupied) == 0 {\n                    break\n                }\n\n                \n                if (board[yy][xx] & dir) != 0 {\n                    break\n                }\n            }\n            if k != lineLen {\n                continue\n            }\n\n            \n            \n            rec.seq++\n            if rand.Intn(rec.seq) == 0 {\n                rec.m, rec.s, rec.x, rec.y = m, s, x, y\n            }\n        }\n    }\n}\n\nfunc addPiece(rec *move) {\n    dx := ofs[rec.m][0]\n    dy := ofs[rec.m][1]\n    dir := ofs[rec.m][2]\n    board[rec.y][rec.x] |= current | occupied\n    for k := 0; k < lineLen; k++ {\n        xx := rec.x + dx*(k+rec.s)\n        yy := rec.y + dy*(k+rec.s)\n        board[yy][xx] |= newlyAdded\n        if k >= disjoint || k < lineLen-disjoint {\n            board[yy][xx] |= dir\n        }\n    }\n}\n\nfunc nextMove() bool {\n    var rec move\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            board[i][j] &^= newlyAdded | current\n        }\n    }\n\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            testPosition(i, j, &rec)\n        }\n    }\n\n    \n    if rec.seq == 0 {\n        return false\n    }\n\n    addPiece(&rec)\n\n    if rec.x == width-1 {\n        rec.x = 1\n    } else if rec.x != 0 {\n        rec.x = 0\n    } else {\n        rec.x = -1\n    }\n\n    if rec.y == height-1 {\n        rec.y = 1\n    } else if rec.y != 0 {\n        rec.y = 0\n    } else {\n        rec.y = -1\n    }\n\n    if rec.x != 0 || rec.y != 0 {\n        expandBoard(rec.x, rec.y)\n    }\n    return true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initBoard()\n    scr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n    gc.Echo(false)\n    gc.CBreak(true)\n    ch := gc.Key(0)\n    move := 0\n    waitKey := true\n    for {\n        scr.MovePrintf(0, 0, \"Move %d\", move)\n        move++\n        showBoard(scr)\n        if !nextMove() {\n            nextMove()\n            showBoard(scr)\n            break\n        }\n        if !waitKey {\n            time.Sleep(100000 * time.Microsecond)\n        }\n        if ch = scr.GetChar(); ch == ' ' {\n            waitKey = !waitKey\n            if waitKey {\n                scr.Timeout(-1)\n            } else {\n                scr.Timeout(0)\n            }\n        }\n        if ch == 'q' {\n            break\n        }\n    }\n    scr.Timeout(-1)\n    gc.CBreak(false)\n    gc.Echo(true)\n}\n", "C": "#include <ncurses.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <time.h>\n\n\nint line_len = 5;\n\n\nint disjoint = 0;\n\nint **board = 0, width, height;\n\n#define for_i for(i = 0; i < height; i++)\n#define for_j for(j = 0; j < width; j++)\nenum {\n\ts_blank\t\t= 0,\n\ts_occupied\t= 1 << 0,\n\ts_dir_ns\t= 1 << 1,\n\ts_dir_ew\t= 1 << 2,\n\ts_dir_ne_sw\t= 1 << 3,\n\ts_dir_nw_se\t= 1 << 4,\n\ts_newly_added\t= 1 << 5,\n\ts_current\t= 1 << 6,\n};\n\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / n);\n}\n\nint** alloc_board(int w, int h)\n{\n\tint i;\n\tint **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);\n\n\tbuf[0] = (int*)(buf + h);\n\tfor (i = 1; i < h; i++)\n\t\tbuf[i] = buf[i - 1] + w;\n\treturn buf;\n}\n\n\nvoid expand_board(int dw, int dh)\n{\n\tint i, j;\n\tint nw = width + !!dw, nh = height + !!dh;\n\n\t\n\tint **nbuf = alloc_board(nw, nh);\n\n\tdw = -(dw < 0), dh = -(dh < 0);\n\n\tfor (i = 0; i < nh; i++) {\n\t\tif (i + dh < 0 || i + dh >= height) continue;\n\t\tfor (j = 0; j < nw; j++) {\n\t\t\tif (j + dw < 0 || j + dw >= width) continue;\n\t\t\tnbuf[i][j] = board[i + dh][j + dw];\n\t\t}\n\t}\n\tfree(board);\n\n\tboard = nbuf;\n\twidth = nw;\n\theight = nh;\n}\n\nvoid array_set(int **buf, int v, int x0, int y0, int x1, int y1)\n{\n\tint i, j;\n\tfor (i = y0; i <= y1; i++)\n\t\tfor (j = x0; j <= x1; j++)\n\t\t\tbuf[i][j] = v;\n}\n\nvoid show_board()\n{\n\tint i, j;\n\tfor_i for_j mvprintw(i + 1, j * 2,\n\t\t\t(board[i][j] & s_current) ? \"X \"\n\t\t\t: (board[i][j] & s_newly_added) ? \"O \"\n\t\t\t: (board[i][j] & s_occupied) ? \"+ \" : \"  \");\n\trefresh();\n}\n\nvoid init_board()\n{\n\twidth = height = 3 * (line_len - 1);\n\tboard = alloc_board(width, height);\n\n\tarray_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);\n\tarray_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);\n\n\tarray_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);\n\tarray_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);\n}\n\nint ofs[4][3] = {\n\t{0, 1, s_dir_ns},\n\t{1, 0, s_dir_ew},\n\t{1, -1, s_dir_ne_sw},\n\t{1, 1, s_dir_nw_se}\n};\n\ntypedef struct { int m, s, seq, x, y; } move_t;\n\n\nvoid test_postion(int y, int x, move_t * rec)\n{\n\tint m, k, s, dx, dy, xx, yy, dir;\n\tif (board[y][x] & s_occupied) return;\n\n\tfor (m = 0; m < 4; m++) { \n\t\tdx = ofs[m][0];\n\t\tdy = ofs[m][1];\n\t\tdir = ofs[m][2];\n\n\t\tfor (s = 1 - line_len; s <= 0; s++) { \n\t\t\tfor (k = 0; k < line_len; k++) {\n\t\t\t\tif (s + k == 0) continue;\n\n\t\t\t\txx = x + dx * (s + k);\n\t\t\t\tyy = y + dy * (s + k);\n\t\t\t\tif (xx < 0 || xx >= width || yy < 0 || yy >= height)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\n\t\t\t\tif (!(board[yy][xx] & s_occupied)) break;\n\n\t\t\t\t\n\t\t\t\tif ((board[yy][xx] & dir)) break;\n\t\t\t}\n\t\t\tif (k != line_len) continue;\n\n\t\t\t\n\t\t\tif (! irand(++rec->seq))\n\t\t\t\trec->m = m, rec->s = s, rec->x = x, rec->y = y;\n\t\t}\n\t}\n}\n\nvoid add_piece(move_t *rec) {\n\tint dx = ofs[rec->m][0];\n\tint dy = ofs[rec->m][1];\n\tint dir= ofs[rec->m][2];\n\tint xx, yy, k;\n\n\tboard[rec->y][rec->x] |= (s_current | s_occupied);\n\n\tfor (k = 0; k < line_len; k++) {\n\t\txx = rec->x + dx * (k + rec->s);\n\t\tyy = rec->y + dy * (k + rec->s);\n\t\tboard[yy][xx] |= s_newly_added;\n\t\tif (k >= disjoint || k < line_len - disjoint)\n\t\t\tboard[yy][xx] |= dir;\n\t}\n}\n\nint next_move()\n{\n\tint i, j;\n\tmove_t rec;\n\trec.seq = 0;\n\n\t\n\tfor_i for_j board[i][j] &= ~(s_newly_added | s_current);\n\n\t\n\tfor_i for_j test_postion(i, j, &rec);\n\n\t\n\tif (!rec.seq) return 0;\n\n\tadd_piece(&rec);\n\n\trec.x = (rec.x == width  - 1) ? 1 : rec.x ? 0 : -1;\n\trec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;\n\n\tif (rec.x || rec.y) expand_board(rec.x, rec.y);\n\treturn 1;\n}\n\nint main()\n{\n\tint ch = 0;\n\tint move = 0;\n\tint wait_key = 1;\n\n\tinit_board();\n\tsrand(time(0));\n\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\n\tdo  {\n\t\tmvprintw(0, 0, \"Move %d\", move++);\n\t\tshow_board();\n\t\tif (!next_move()) {\n\t\t\tnext_move();\n\t\t\tshow_board();\n\t\t\tbreak;\n\t\t}\n\t\tif (!wait_key) usleep(100000);\n\t\tif ((ch = getch()) == ' ') {\n\t\t\twait_key = !wait_key;\n\t\t\tif (wait_key) timeout(-1);\n\t\t\telse timeout(0);\n\t\t}\n\t} while (ch != 'q');\n\n\ttimeout(-1);\n\tnocbreak();\n\techo();\n\n\tendwin();\n\treturn 0;\n}\n"}
{"id": 60544, "name": "Morpion solitaire", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nconst (\n    lineLen  = 5\n    disjoint = 0\n)\n\nvar (\n    board  [][]int\n    width  int\n    height int\n)\n\nconst (\n    blank    = 0\n    occupied = 1 << (iota - 1)\n    dirNS\n    dirEW\n    dirNESW\n    dirNWSE\n    newlyAdded\n    current\n)\n\nvar ofs = [4][3]int{\n    {0, 1, dirNS},\n    {1, 0, dirEW},\n    {1, -1, dirNESW},\n    {1, 1, dirNWSE},\n}\n\ntype move struct{ m, s, seq, x, y int }\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc allocBoard(w, h int) [][]int {\n    buf := make([][]int, h)\n    for i := 0; i < h; i++ {\n        buf[i] = make([]int, w)\n    }\n    return buf\n}\n\nfunc boardSet(v, x0, y0, x1, y1 int) {\n    for i := y0; i <= y1; i++ {\n        for j := x0; j <= x1; j++ {\n            board[i][j] = v\n        }\n    }\n}\n\nfunc initBoard() {\n    height = 3 * (lineLen - 1)\n    width = height\n    board = allocBoard(width, height)\n\n    boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)\n    boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)\n    boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)\n    boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)\n}\n\n\nfunc expandBoard(dw, dh int) {\n    dw2, dh2 := 1, 1\n    if dw == 0 {\n        dw2 = 0\n    }\n    if dh == 0 {\n        dh2 = 0\n    }\n    nw, nh := width+dw2, height+dh2\n    nbuf := allocBoard(nw, nh)\n    dw, dh = -btoi(dw < 0), -btoi(dh < 0)\n    for i := 0; i < nh; i++ {\n        if i+dh < 0 || i+dh >= height {\n            continue\n        }\n        for j := 0; j < nw; j++ {\n            if j+dw < 0 || j+dw >= width {\n                continue\n            }\n            nbuf[i][j] = board[i+dh][j+dw]\n        }\n    }\n    board = nbuf\n    width, height = nw, nh\n}\n\nfunc showBoard(scr *gc.Window) {\n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            var temp string\n            switch {\n            case (board[i][j] & current) != 0:\n                temp = \"X \"\n            case (board[i][j] & newlyAdded) != 0:\n                temp = \"0 \"\n            case (board[i][j] & occupied) != 0:\n                temp = \"+ \"\n            default:\n                temp = \"  \"\n            }\n            scr.MovePrintf(i+1, j*2, temp)\n        }\n    }\n    scr.Refresh()\n}\n\n\nfunc testPosition(y, x int, rec *move) {\n    if (board[y][x] & occupied) != 0 {\n        return\n    }\n    for m := 0; m < 4; m++ { \n        dx := ofs[m][0]\n        dy := ofs[m][1]\n        dir := ofs[m][2]\n        var k int\n        for s := 1 - lineLen; s <= 0; s++ { \n            for k = 0; k < lineLen; k++ {\n                if s+k == 0 {\n                    continue\n                }\n                xx := x + dx*(s+k)\n                yy := y + dy*(s+k)\n                if xx < 0 || xx >= width || yy < 0 || yy >= height {\n                    break\n                }\n\n                \n                if (board[yy][xx] & occupied) == 0 {\n                    break\n                }\n\n                \n                if (board[yy][xx] & dir) != 0 {\n                    break\n                }\n            }\n            if k != lineLen {\n                continue\n            }\n\n            \n            \n            rec.seq++\n            if rand.Intn(rec.seq) == 0 {\n                rec.m, rec.s, rec.x, rec.y = m, s, x, y\n            }\n        }\n    }\n}\n\nfunc addPiece(rec *move) {\n    dx := ofs[rec.m][0]\n    dy := ofs[rec.m][1]\n    dir := ofs[rec.m][2]\n    board[rec.y][rec.x] |= current | occupied\n    for k := 0; k < lineLen; k++ {\n        xx := rec.x + dx*(k+rec.s)\n        yy := rec.y + dy*(k+rec.s)\n        board[yy][xx] |= newlyAdded\n        if k >= disjoint || k < lineLen-disjoint {\n            board[yy][xx] |= dir\n        }\n    }\n}\n\nfunc nextMove() bool {\n    var rec move\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            board[i][j] &^= newlyAdded | current\n        }\n    }\n\n    \n    for i := 0; i < height; i++ {\n        for j := 0; j < width; j++ {\n            testPosition(i, j, &rec)\n        }\n    }\n\n    \n    if rec.seq == 0 {\n        return false\n    }\n\n    addPiece(&rec)\n\n    if rec.x == width-1 {\n        rec.x = 1\n    } else if rec.x != 0 {\n        rec.x = 0\n    } else {\n        rec.x = -1\n    }\n\n    if rec.y == height-1 {\n        rec.y = 1\n    } else if rec.y != 0 {\n        rec.y = 0\n    } else {\n        rec.y = -1\n    }\n\n    if rec.x != 0 || rec.y != 0 {\n        expandBoard(rec.x, rec.y)\n    }\n    return true\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initBoard()\n    scr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n    gc.Echo(false)\n    gc.CBreak(true)\n    ch := gc.Key(0)\n    move := 0\n    waitKey := true\n    for {\n        scr.MovePrintf(0, 0, \"Move %d\", move)\n        move++\n        showBoard(scr)\n        if !nextMove() {\n            nextMove()\n            showBoard(scr)\n            break\n        }\n        if !waitKey {\n            time.Sleep(100000 * time.Microsecond)\n        }\n        if ch = scr.GetChar(); ch == ' ' {\n            waitKey = !waitKey\n            if waitKey {\n                scr.Timeout(-1)\n            } else {\n                scr.Timeout(0)\n            }\n        }\n        if ch == 'q' {\n            break\n        }\n    }\n    scr.Timeout(-1)\n    gc.CBreak(false)\n    gc.Echo(true)\n}\n", "C": "#include <ncurses.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <time.h>\n\n\nint line_len = 5;\n\n\nint disjoint = 0;\n\nint **board = 0, width, height;\n\n#define for_i for(i = 0; i < height; i++)\n#define for_j for(j = 0; j < width; j++)\nenum {\n\ts_blank\t\t= 0,\n\ts_occupied\t= 1 << 0,\n\ts_dir_ns\t= 1 << 1,\n\ts_dir_ew\t= 1 << 2,\n\ts_dir_ne_sw\t= 1 << 3,\n\ts_dir_nw_se\t= 1 << 4,\n\ts_newly_added\t= 1 << 5,\n\ts_current\t= 1 << 6,\n};\n\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / n);\n}\n\nint** alloc_board(int w, int h)\n{\n\tint i;\n\tint **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);\n\n\tbuf[0] = (int*)(buf + h);\n\tfor (i = 1; i < h; i++)\n\t\tbuf[i] = buf[i - 1] + w;\n\treturn buf;\n}\n\n\nvoid expand_board(int dw, int dh)\n{\n\tint i, j;\n\tint nw = width + !!dw, nh = height + !!dh;\n\n\t\n\tint **nbuf = alloc_board(nw, nh);\n\n\tdw = -(dw < 0), dh = -(dh < 0);\n\n\tfor (i = 0; i < nh; i++) {\n\t\tif (i + dh < 0 || i + dh >= height) continue;\n\t\tfor (j = 0; j < nw; j++) {\n\t\t\tif (j + dw < 0 || j + dw >= width) continue;\n\t\t\tnbuf[i][j] = board[i + dh][j + dw];\n\t\t}\n\t}\n\tfree(board);\n\n\tboard = nbuf;\n\twidth = nw;\n\theight = nh;\n}\n\nvoid array_set(int **buf, int v, int x0, int y0, int x1, int y1)\n{\n\tint i, j;\n\tfor (i = y0; i <= y1; i++)\n\t\tfor (j = x0; j <= x1; j++)\n\t\t\tbuf[i][j] = v;\n}\n\nvoid show_board()\n{\n\tint i, j;\n\tfor_i for_j mvprintw(i + 1, j * 2,\n\t\t\t(board[i][j] & s_current) ? \"X \"\n\t\t\t: (board[i][j] & s_newly_added) ? \"O \"\n\t\t\t: (board[i][j] & s_occupied) ? \"+ \" : \"  \");\n\trefresh();\n}\n\nvoid init_board()\n{\n\twidth = height = 3 * (line_len - 1);\n\tboard = alloc_board(width, height);\n\n\tarray_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);\n\tarray_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);\n\n\tarray_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);\n\tarray_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);\n}\n\nint ofs[4][3] = {\n\t{0, 1, s_dir_ns},\n\t{1, 0, s_dir_ew},\n\t{1, -1, s_dir_ne_sw},\n\t{1, 1, s_dir_nw_se}\n};\n\ntypedef struct { int m, s, seq, x, y; } move_t;\n\n\nvoid test_postion(int y, int x, move_t * rec)\n{\n\tint m, k, s, dx, dy, xx, yy, dir;\n\tif (board[y][x] & s_occupied) return;\n\n\tfor (m = 0; m < 4; m++) { \n\t\tdx = ofs[m][0];\n\t\tdy = ofs[m][1];\n\t\tdir = ofs[m][2];\n\n\t\tfor (s = 1 - line_len; s <= 0; s++) { \n\t\t\tfor (k = 0; k < line_len; k++) {\n\t\t\t\tif (s + k == 0) continue;\n\n\t\t\t\txx = x + dx * (s + k);\n\t\t\t\tyy = y + dy * (s + k);\n\t\t\t\tif (xx < 0 || xx >= width || yy < 0 || yy >= height)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\n\t\t\t\tif (!(board[yy][xx] & s_occupied)) break;\n\n\t\t\t\t\n\t\t\t\tif ((board[yy][xx] & dir)) break;\n\t\t\t}\n\t\t\tif (k != line_len) continue;\n\n\t\t\t\n\t\t\tif (! irand(++rec->seq))\n\t\t\t\trec->m = m, rec->s = s, rec->x = x, rec->y = y;\n\t\t}\n\t}\n}\n\nvoid add_piece(move_t *rec) {\n\tint dx = ofs[rec->m][0];\n\tint dy = ofs[rec->m][1];\n\tint dir= ofs[rec->m][2];\n\tint xx, yy, k;\n\n\tboard[rec->y][rec->x] |= (s_current | s_occupied);\n\n\tfor (k = 0; k < line_len; k++) {\n\t\txx = rec->x + dx * (k + rec->s);\n\t\tyy = rec->y + dy * (k + rec->s);\n\t\tboard[yy][xx] |= s_newly_added;\n\t\tif (k >= disjoint || k < line_len - disjoint)\n\t\t\tboard[yy][xx] |= dir;\n\t}\n}\n\nint next_move()\n{\n\tint i, j;\n\tmove_t rec;\n\trec.seq = 0;\n\n\t\n\tfor_i for_j board[i][j] &= ~(s_newly_added | s_current);\n\n\t\n\tfor_i for_j test_postion(i, j, &rec);\n\n\t\n\tif (!rec.seq) return 0;\n\n\tadd_piece(&rec);\n\n\trec.x = (rec.x == width  - 1) ? 1 : rec.x ? 0 : -1;\n\trec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;\n\n\tif (rec.x || rec.y) expand_board(rec.x, rec.y);\n\treturn 1;\n}\n\nint main()\n{\n\tint ch = 0;\n\tint move = 0;\n\tint wait_key = 1;\n\n\tinit_board();\n\tsrand(time(0));\n\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\n\tdo  {\n\t\tmvprintw(0, 0, \"Move %d\", move++);\n\t\tshow_board();\n\t\tif (!next_move()) {\n\t\t\tnext_move();\n\t\t\tshow_board();\n\t\t\tbreak;\n\t\t}\n\t\tif (!wait_key) usleep(100000);\n\t\tif ((ch = getch()) == ' ') {\n\t\t\twait_key = !wait_key;\n\t\t\tif (wait_key) timeout(-1);\n\t\t\telse timeout(0);\n\t\t}\n\t} while (ch != 'q');\n\n\ttimeout(-1);\n\tnocbreak();\n\techo();\n\n\tendwin();\n\treturn 0;\n}\n"}
{"id": 60545, "name": "Append numbers at same position in strings", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n"}
{"id": 60546, "name": "Append numbers at same position in strings", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}\n    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}\n    var list [9]int\n    for i := 0; i < 9; i++ {\n        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]\n    }\n    fmt.Println(list)\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint main(void) {\n    int list[3][9], i;\n    for(i=0;i<27;i++) list[i/9][i%9]=1+i;\n    for(i=0;i<9;i++) printf( \"%d%d%d  \", list[0][i], list[1][i], list[2][i] );\n    return 0;\n}\n"}
{"id": 60547, "name": "Longest common suffix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc lcs(a []string) string {\n    le := len(a)\n    if le == 0 {\n        return \"\"\n    }\n    if le == 1 {\n        return a[0]\n    }\n    le0 := len(a[0])\n    minLen := le0\n    for i := 1; i < le; i++ {\n        if len(a[i]) < minLen {\n            minLen = len(a[i])\n        }\n    }\n    if minLen == 0 {\n        return \"\"\n    }\n    res := \"\"\n    a1 := a[1:]\n    for i := 1; i <= minLen; i++ {\n        suffix := a[0][le0-i:]\n        for _, e := range a1 {\n            if !strings.HasSuffix(e, suffix) {\n                return res\n            }\n        }\n        res = suffix\n    }\n    return res\n}\n\nfunc main() {\n    tests := [][]string{\n        {\"baabababc\", \"baabc\", \"bbbabc\"},\n        {\"baabababc\", \"baabc\", \"bbbazc\"},\n        {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"},\n        {\"longest\", \"common\", \"suffix\"},\n        {\"suffix\"},\n        {\"\"},\n    }\n    for _, test := range tests {\n        fmt.Printf(\"%v -> \\\"%s\\\"\\n\", test, lcs(test))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node_t {\n    char *elem;\n    int length;\n    struct node_t *next;\n} node;\n\nnode *make_node(char *s) {\n    node *t = malloc(sizeof(node));\n    t->elem = s;\n    t->length = strlen(s);\n    t->next = NULL;\n    return t;\n}\n\nvoid append_node(node *head, node *elem) {\n    while (head->next != NULL) {\n        head = head->next;\n    }\n    head->next = elem;\n}\n\nvoid print_node(node *n) {\n    putc('[', stdout);\n    while (n != NULL) {\n        printf(\"`%s` \", n->elem);\n        n = n->next;\n    }\n    putc(']', stdout);\n}\n\nchar *lcs(node *list) {\n    int minLen = INT_MAX;\n    int i;\n\n    char *res;\n    node *ptr;\n\n    if (list == NULL) {\n        return \"\";\n    }\n    if (list->next == NULL) {\n        return list->elem;\n    }\n\n    for (ptr = list; ptr != NULL; ptr = ptr->next) {\n        minLen = min(minLen, ptr->length);\n    }\n    if (minLen == 0) {\n        return \"\";\n    }\n\n    res = \"\";\n    for (i = 1; i < minLen; i++) {\n        char *suffix = &list->elem[list->length - i];\n\n        for (ptr = list->next; ptr != NULL; ptr = ptr->next) {\n            char *e = &ptr->elem[ptr->length - i];\n            if (strcmp(suffix, e) != 0) {\n                return res;\n            }\n        }\n\n        res = suffix;\n    }\n\n    return res;\n}\n\nvoid test(node *n) {\n    print_node(n);\n    printf(\" -> `%s`\\n\", lcs(n));\n}\n\nvoid case1() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbabc\"));\n    test(n);\n}\n\nvoid case2() {\n    node *n = make_node(\"baabababc\");\n    append_node(n, make_node(\"baabc\"));\n    append_node(n, make_node(\"bbbazc\"));\n    test(n);\n}\n\nvoid case3() {\n    node *n = make_node(\"Sunday\");\n    append_node(n, make_node(\"Monday\"));\n    append_node(n, make_node(\"Tuesday\"));\n    append_node(n, make_node(\"Wednesday\"));\n    append_node(n, make_node(\"Thursday\"));\n    append_node(n, make_node(\"Friday\"));\n    append_node(n, make_node(\"Saturday\"));\n    test(n);\n}\n\nvoid case4() {\n    node *n = make_node(\"longest\");\n    append_node(n, make_node(\"common\"));\n    append_node(n, make_node(\"suffix\"));\n    test(n);\n}\n\nvoid case5() {\n    node *n = make_node(\"suffix\");\n    test(n);\n}\n\nvoid case6() {\n    node *n = make_node(\"\");\n    test(n);\n}\n\nint main() {\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    return 0;\n}\n"}
{"id": 60548, "name": "Chat server", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.SetPrefix(\"chat: \")\n\taddr := flag.String(\"addr\", \"localhost:4000\", \"listen address\")\n\tflag.Parse()\n\tlog.Fatal(ListenAndServe(*addr))\n}\n\n\ntype Server struct {\n\tadd  chan *conn  \n\trem  chan string \n\tmsg  chan string \n\tstop chan bool   \n}\n\n\n\nfunc ListenAndServe(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening for connections on\", addr)\n\tdefer ln.Close()\n\ts := &Server{\n\t\tadd:  make(chan *conn),\n\t\trem:  make(chan string),\n\t\tmsg:  make(chan string),\n\t\tstop: make(chan bool),\n\t}\n\tgo s.handleConns()\n\tfor {\n\t\t\n\t\t\n\t\trwc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\n\t\t\t\n\t\t\tclose(s.stop)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"New connection from\", rwc.RemoteAddr())\n\t\tgo newConn(s, rwc).welcome()\n\t}\n}\n\n\n\nfunc (s *Server) handleConns() {\n\t\n\t\n\t\n\t\n\t\n\tconns := make(map[string]*conn)\n\n\tvar dropConn func(string)\n\twriteAll := func(str string) {\n\t\tlog.Printf(\"Broadcast: %q\", str)\n\t\t\n\t\tfor name, c := range conns {\n\t\t\tc.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))\n\t\t\t_, err := c.Write([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing to %q: %v\", name, err)\n\t\t\t\tc.Close()\n\t\t\t\tdelete(conns, name)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tdefer dropConn(name)\n\t\t\t}\n\t\t}\n\t}\n\n\tdropConn = func(name string) {\n\t\tif c, ok := conns[name]; ok {\n\t\t\tlog.Printf(\"Closing connection with %q from %v\",\n\t\t\t\tname, c.RemoteAddr())\n\t\t\tc.Close()\n\t\t\tdelete(conns, name)\n\t\t} else {\n\t\t\tlog.Printf(\"Dropped connection with %q\", name)\n\t\t}\n\t\tstr := fmt.Sprintf(\"--- %q disconnected ---\\n\", name)\n\t\twriteAll(str)\n\t}\n\n\tdefer func() {\n\t\twriteAll(\"Server stopping!\\n\")\n\t\tfor _, c := range conns {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-s.add:\n\t\t\tif _, exists := conns[c.name]; exists {\n\t\t\t\tfmt.Fprintf(c, \"Name %q is not available\\n\", c.name)\n\t\t\t\tgo c.welcome()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"+++ %q connected +++\\n\", c.name)\n\t\t\twriteAll(str)\n\t\t\tconns[c.name] = c\n\t\t\tgo c.readloop()\n\t\tcase str := <-s.msg:\n\t\t\twriteAll(str)\n\t\tcase name := <-s.rem:\n\t\t\tdropConn(name)\n\t\tcase <-s.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\ntype conn struct {\n\t*bufio.Reader         \n\tnet.Conn              \n\tserver        *Server \n\tname          string\n}\n\nfunc newConn(s *Server, rwc net.Conn) *conn {\n\treturn &conn{\n\t\tReader: bufio.NewReader(rwc),\n\t\tConn:   rwc,\n\t\tserver: s,\n\t}\n}\n\n\n\nfunc (c *conn) welcome() {\n\tvar err error\n\tfor c.name = \"\"; c.name == \"\"; {\n\t\tfmt.Fprint(c, \"Enter your name: \")\n\t\tc.name, err = c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Reading name from %v: %v\", c.RemoteAddr(), err)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\t\tc.name = strings.TrimSpace(c.name)\n\t}\n\t\n\t\n\tc.server.add <- c\n}\n\n\n\n\n\n\nfunc (c *conn) readloop() {\n\tfor {\n\t\tmsg, err := c.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tc.server.msg <- c.name + \"> \" + msg\n\t}\n\tc.server.rem <- c.name\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n\nint tsocket;\nstruct sockaddr_in tsockinfo;\nfd_set status, current;\nvoid ClientText(int handle, char *buf, int buf_len);\n\nstruct client\n{\n    char buffer[4096];\n    int pos;\n    char name[32];\n} *connections[FD_SETSIZE];\n\nvoid AddConnection(int handle)\n{\n    connections[handle] = malloc(sizeof(struct client));\n    connections[handle]->buffer[0] = '\\0';\n    connections[handle]->pos = 0;\n    connections[handle]->name[0] = '\\0';\n}\n\nvoid CloseConnection(int handle)\n{\n    char buf[512];\n    int j;\n\n    FD_CLR(handle, &status);\n    \n    if (connections[handle]->name[0])\n    {\n        sprintf(buf, \"* Disconnected: %s\\r\\n\", connections[handle]->name);\n\n        for (j = 0; j < FD_SETSIZE; j++)\n        {\n            if (handle != j && j != tsocket && FD_ISSET(j, &status))\n            {\n                if (write(j, buf, strlen(buf)) < 0)\n                {\n                    CloseConnection(j);\n                }\n            }\n        }\n    } else\n    {\n        printf (\"-- Connection %d disconnected\\n\", handle);\n    }\n    if (connections[handle])\n    {\n        free(connections[handle]);\n    }\n    close(handle);\n}\n\nvoid strip(char *buf)\n{\n    char *x;\n    \n    x = strchr(buf, '\\n');\n    if (x) { *x='\\0'; }\n    x = strchr(buf, '\\r');\n    if (x) { *x='\\0'; }\n}\n\nint RelayText(int handle)\n{\n    char *begin, *end;\n    int ret = 0;\n    begin = connections[handle]->buffer;\n    if (connections[handle]->pos == 4000)\n    {\n        if (begin[3999] != '\\n')\n            begin[4000] = '\\0';\n        else {\n            begin[4000] = '\\n';\n            begin[4001] = '\\0';\n        }\n    } else {\n        begin[connections[handle]->pos] = '\\0';\n    }\n    \n    end = strchr(begin, '\\n');\n    while (end != NULL)\n    {\n        char output[8000];\n        output[0] = '\\0';\n        if (!connections[handle]->name[0])\n        {\n            strncpy(connections[handle]->name, begin, 31);\n            connections[handle]->name[31] = '\\0';\n            \n            strip(connections[handle]->name);\n            sprintf(output, \"* Connected: %s\\r\\n\", connections[handle]->name);\n            ret = 1;\n        } else \n        {\n            sprintf(output, \"%s: %.*s\\r\\n\", connections[handle]->name, \n                    end-begin, begin);\n            ret = 1;\n        }\n        \n        if (output[0])\n        {\n            int j;\n            for (j = 0; j < FD_SETSIZE; j++)\n            {\n                if (handle != j && j != tsocket && FD_ISSET(j, &status))\n                {\n                    if (write(j, output, strlen(output)) < 0)\n                    {\n                        CloseConnection(j);\n                    }\n                }\n            }\n        }\n        begin = end+1;\n        end = strchr(begin, '\\n');\n    }\n    \n    strcpy(connections[handle]->buffer, begin);\n    connections[handle]->pos -= begin - connections[handle]->buffer;\n    return ret;\n}\n\nvoid ClientText(int handle, char *buf, int buf_len)\n{\n    int i, j;\n    if (!connections[handle])\n        return;\n    j = connections[handle]->pos; \n    \n    for (i = 0; i < buf_len; ++i, ++j)\n    {\n        connections[handle]->buffer[j] = buf[i];\n        \n        if (j == 4000)\n        {\n            while (RelayText(handle));\n            j = connections[handle]->pos;\n        }\n    }\n    connections[handle]->pos = j;\n    \n    while (RelayText(handle));\n}\n\n\nint ChatLoop()\n{\n    int i, j;\n    FD_ZERO(&status);\n\n    FD_SET(tsocket, &status);\n    FD_SET(0, &status);\n\n    while(1)\n    {\n        current = status;\n        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)\n        {\n            perror(\"Select\");\n            return 0;\n        }\n        for (i = 0; i < FD_SETSIZE; ++i)\n        {\n            if (FD_ISSET(i, &current))\n            {\n                if (i == tsocket)\n                {\n                    struct sockaddr_in cliinfo;\n                    socklen_t addrlen = sizeof(cliinfo);\n                    int handle;\n                    handle = accept(tsocket, &cliinfo, &addrlen);\n                    if (handle == -1)\n                    {\n                        perror (\"Couldn't accept connection\");\n                    } else if (handle > FD_SETSIZE)\n                    {\n                        printf (\"Unable to accept new connection.\\n\");\n                        close(handle);\n                    }\n                    else\n                    {\n                        if (write(handle, \"Enter name: \", 12) >= 0)\n                        {\n                            printf(\"-- New connection %d from %s:%hu\\n\",\n                                handle, \n                                inet_ntoa (cliinfo.sin_addr),\n                                ntohs(cliinfo.sin_port));\n                            FD_SET(handle, &status);\n\n                            AddConnection(handle);\n                        }\n                    }\n                } \n                else\n                {\n                    char buf[512];\n                    int b;\n\n                    b = read(i, buf, 500);\n                    if (b <= 0)\n                    {\n                        CloseConnection(i);\n                    }\n                    else\n                    {\n                        ClientText(i, buf, b);\n                    }\n                }\n            }\n        }\n    } \n}\n\nint main (int argc, char*argv[])\n{\n    tsocket = socket(PF_INET, SOCK_STREAM, 0);\n\n    tsockinfo.sin_family = AF_INET;\n    tsockinfo.sin_port = htons(7070);\n    if (argc > 1)\n    {\n        tsockinfo.sin_port = htons(atoi(argv[1]));\n    }\n    tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);\n    printf (\"Socket %d on port %hu\\n\", tsocket, ntohs(tsockinfo.sin_port));\n\n    if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)\n    {\n        perror(\"Couldn't bind socket\");\n        return -1;\n    }\n\n    if (listen(tsocket, 10) == -1)\n    {\n        perror(\"Couldn't listen to port\");\n    }\n\n    ChatLoop();\n\n    return 0;\n}\n"}
{"id": 60549, "name": "Arena storage pool", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n", "C": "#include <stdlib.h>\n"}
{"id": 60550, "name": "Arena storage pool", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"sync\"\n)\n\n\n\n\n\nfunc main() {\n    \n    \n    p := sync.Pool{New: func() interface{} {\n        fmt.Println(\"pool empty\")\n        return new(int)\n    }}\n    \n    i := new(int)\n    j := new(int)\n    \n    *i = 1\n    *j = 2\n    fmt.Println(*i + *j) \n    \n    \n    \n    \n    p.Put(i)\n    p.Put(j)\n    \n    \n    i = nil\n    j = nil\n    \n    \n    \n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 4\n    *j = 5\n    fmt.Println(*i + *j) \n    \n    p.Put(i)\n    p.Put(j)\n    i = nil\n    j = nil\n    runtime.GC()\n    i = p.Get().(*int)\n    j = p.Get().(*int)\n    *i = 7\n    *j = 8\n    fmt.Println(*i + *j) \n}\n", "C": "#include <stdlib.h>\n"}
{"id": 60551, "name": "Idiomatically determine all the lowercase and uppercase letters", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  for (char c = 0x41; c < 0x5b; c ++) putchar(c);\n  putchar('\\n');\n  for (char c = 0x61; c < 0x7b; c ++) putchar(c);\n  putchar('\\n');\n  return 0;\n}\n"}
{"id": 60552, "name": "Sum of elements below main diagonal of matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc main() {\n    m := [][]int{\n        {1, 3, 7, 8, 10},\n        {2, 4, 16, 14, 4},\n        {3, 1, 9, 18, 11},\n        {12, 14, 17, 18, 20},\n        {7, 1, 3, 9, 5},\n    }\n    if len(m) != len(m[0]) {\n        log.Fatal(\"Matrix must be square.\")\n    }\n    sum := 0\n    for i := 1; i < len(m); i++ {\n        for j := 0; j < i; j++ {\n            sum = sum + m[i][j]\n        }\n    }\n    fmt.Println(\"Sum of elements below main diagonal is\", sum)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint rows,cols;\n\tint** dataSet;\n}matrix;\n\nmatrix readMatrix(char* dataFile){\n\tFILE* fp = fopen(dataFile,\"r\");\n\tmatrix rosetta;\n\tint i,j;\n\t\n\tfscanf(fp,\"%d%d\",&rosetta.rows,&rosetta.cols);\n\t\n\trosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\trosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tfscanf(fp,\"%d\",&rosetta.dataSet[i][j]);\n\t}\n\t\n\tfclose(fp);\n\treturn rosetta;\n}\n\nvoid printMatrix(matrix rosetta){\n\tint i,j;\n\t\n\tfor(i=0;i<rosetta.rows;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<rosetta.cols;j++)\n\t\t\tprintf(\"%3d\",rosetta.dataSet[i][j]);\n\t}\n}\n\nint findSum(matrix rosetta){\n\tint i,j,sum = 0;\n\t\n\tfor(i=1;i<rosetta.rows;i++){\n\t\tfor(j=0;j<i;j++){\n\t\t\tsum += rosetta.dataSet[i][j];\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\treturn printf(\"Usage : %s <filename>\",argV[0]);\n\t\n\tmatrix data = readMatrix(argV[1]);\n\t\n\tprintf(\"\\n\\nMatrix is : \\n\\n\");\n\tprintMatrix(data);\n\t\n\tprintf(\"\\n\\nSum below main diagonal : %d\",findSum(data));\n\t\n\treturn 0;\n}\n"}
{"id": 60553, "name": "Retrieve and search chat history", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc get(url string) (res string, err error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n\nfunc grep(needle string, haystack string) (res []string) {\n\tfor _, line := range strings.Split(haystack, \"\\n\") {\n\t\tif strings.Contains(line, needle) {\n\t\t\tres = append(res, line)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc genUrl(i int, loc *time.Location) string {\n\tdate := time.Now().In(loc).AddDate(0, 0, i)\n\treturn date.Format(\"http:\n}\n\nfunc main() {\n\tneedle := os.Args[1]\n\tback := -10\n\tserverLoc, err := time.LoadLocation(\"Europe/Berlin\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor i := back; i <= 0; i++ {\n\t\turl := genUrl(i, serverLoc)\n\t\tcontents, err := get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfound := grep(needle, contents)\n\t\tif len(found) > 0 {\n\t\t\tfmt.Printf(\"%v\\n------\\n\", url)\n\t\t\tfor _, line := range found {\n\t\t\t\tfmt.Printf(\"%v\\n\", line)\n\t\t\t}\n\t\t\tfmt.Printf(\"------\\n\\n\")\n\t\t}\n\t}\n}\n", "C": "#include<curl/curl.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAX_LEN 1000\n\nvoid searchChatLogs(char* searchString){\n\tchar* baseURL = \"http:\n\ttime_t t;\n\tstruct tm* currentDate;\n\tchar dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];\n\tint i,flag;\n\tFILE *fp;\n\t\n\tCURL *curl;\n\tCURLcode res;\n\t\n\ttime(&t);\n\tcurrentDate = localtime(&t);\n\t\n\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\n\tprintf(\"Today is : %s\",dateString);\n\t\n\tif((curl = curl_easy_init())!=NULL){\n\t\tfor(i=0;i<=10;i++){\n\t\t\t\n\t\tflag = 0;\n\t\tsprintf(targetURL,\"%s%s.tcl\",baseURL,dateString);\n\t\t\n\t\tstrcpy(dateStringFile,dateString);\n\t\t\n\t\tprintf(\"\\nRetrieving chat logs from %s\\n\",targetURL);\n\t\t\n\t\tif((fp = fopen(\"nul\",\"w\"))==0){\n\t\t\tprintf(\"Cant's read from %s\",targetURL);\n\t\t}\n\t\telse{\n\t\t\tcurl_easy_setopt(curl, CURLOPT_URL, targetURL);\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);\n\t\t\n\t\tres = curl_easy_perform(curl);\n\t\t\n\t\tif(res == CURLE_OK){\n\t\t\twhile(fgets(lineData,MAX_LEN,fp)!=NULL){\n\t\t\t\tif(strstr(lineData,searchString)!=NULL){\n\t\t\t\t\tflag = 1;\n\t\t\t\t\tfputs(lineData,stdout);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(flag==0)\n\t\t\t\tprintf(\"\\nNo matching lines found.\");\n\t\t}\n\t\tfflush(fp);\n\t\tfclose(fp);\n\t\t}\n\t\t\n\t\tcurrentDate->tm_mday--;\n\t\tmktime(currentDate);\n\t\tstrftime(dateString, 30, \"%Y-%m-%d\", currentDate);\t\n\t\t\t\n\t}\n\tcurl_easy_cleanup(curl);\n\t\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <followed by search string, enclosed by \\\" if it contains spaces>\",argV[0]);\n\telse\n\t\tsearchChatLogs(argV[1]);\n\treturn 0;\n}\n"}
{"id": 60554, "name": "Spoof game", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nconst (\n    esc  = \"\\033\"\n    test = true \n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc indexOf(s []int, el int) int {\n    for i, v := range s {\n        if v == el {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc getNumber(prompt string, min, max int, showMinMax bool) (int, error) {\n    for {\n        fmt.Print(prompt)\n        if showMinMax {\n            fmt.Printf(\" from %d to %d : \", min, max)\n        } else {\n            fmt.Printf(\" : \")\n        }\n        scanner.Scan()\n        if scerr := scanner.Err(); scerr != nil {\n            return 0, scerr\n        }\n        input, err := strconv.Atoi(scanner.Text())\n        if err == nil && input >= min && input <= max {\n            fmt.Println()\n            return input, nil\n        }\n    }\n}\n\nfunc check(err error, text string) {\n    if err != nil {\n        log.Fatalln(err, text)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    players, err := getNumber(\"Number of players\", 2, 9, true)\n    check(err, \"when getting players\")\n    coins, err2 := getNumber(\"Number of coins per player\", 3, 6, true)\n    check(err2, \"when getting coins\")\n    remaining := make([]int, players)\n    for i := range remaining {\n        remaining[i] = i + 1\n    }\n    first := 1 + rand.Intn(players)\n    fmt.Println(\"The number of coins in your hand will be randomly determined for\")\n    fmt.Println(\"each round and displayed to you. However, when you press ENTER\")\n    fmt.Println(\"it will be erased so that the other players, who should look\")\n    fmt.Println(\"away until it's their turn, won't see it. When asked to guess\")\n    fmt.Println(\"the total, the computer won't allow a 'bum guess'.\")\n    for round := 1; ; round++ {\n        fmt.Printf(\"\\nROUND %d:\\n\\n\", round)\n        n := first\n        hands := make([]int, players+1)\n        guesses := make([]int, players+1)\n        for i := range guesses {\n            guesses[i] = -1\n        }\n        for {\n            fmt.Printf(\"  PLAYER %d:\\n\", n)\n            fmt.Println(\"    Please come to the computer and press ENTER\")\n            hands[n] = rand.Intn(coins + 1)\n            fmt.Print(\"      <There are \", hands[n], \" coin(s) in your hand>\")\n            scanner.Scan()\n            check(scanner.Err(), \"when pressing ENTER\")\n            if !test {\n                fmt.Print(esc, \"[1A\") \n                fmt.Print(esc, \"[2K\") \n                fmt.Println(\"\\r\")     \n            } else {\n                fmt.Println()\n            }\n            for {\n                min := hands[n]\n                max := (len(remaining)-1)*coins + hands[n]\n                guess, err3 := getNumber(\"    Guess the total\", min, max, false)\n                check(err3, \"when guessing the total\")\n                if indexOf(guesses, guess) == -1 {\n                    guesses[n] = guess\n                    break\n                }\n                fmt.Println(\"    Already guessed by another player, try again\")\n            }\n            index := indexOf(remaining, n)\n            if index < len(remaining)-1 {\n                n = remaining[index+1]\n            } else {\n                n = remaining[0]\n            }\n            if n == first {\n                break\n            }\n        }\n        total := 0\n        for _, hand := range hands {\n            total += hand\n        }\n        fmt.Println(\"  Total coins held =\", total)\n        eliminated := false\n        for _, v := range remaining {\n            if guesses[v] == total {\n                fmt.Println(\"  PLAYER\", v, \"guessed correctly and is eliminated\")\n                r := indexOf(remaining, v)\n                remaining = append(remaining[:r], remaining[r+1:]...)\n                eliminated = true\n                break\n            }\n        }\n        if !eliminated {\n            fmt.Println(\"  No players guessed correctly in this round\")\n        } else if len(remaining) == 1 {\n            fmt.Println(\"\\nPLAYER\", remaining[0], \"buys the drinks!\")\n            return\n        }\n        index2 := indexOf(remaining, n)\n        if index2 < len(remaining)-1 {\n            first = remaining[index2+1]\n        } else {\n            first = remaining[0]\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n#define ESC 27\n#define TEST TRUE  \n\ntypedef int bool;\n\nint get_number(const char *prompt, int min, int max, bool show_mm) {\n    int n;\n    char *line = NULL;\n    size_t len = 0;\n    ssize_t read;\n    fflush(stdin);\n    do {\n        printf(\"%s\", prompt);\n        if (show_mm)\n            printf(\" from %d to %d : \", min, max);\n        else\n            printf(\" : \");\n        read = getline(&line, &len, stdin);\n        if (read < 2) continue;\n        n = atoi(line);\n    }\n    while (n < min || n > max);\n    printf(\"\\n\");\n    return n;\n}\n\nint compare_int(const void *a, const void* b) {\n    int i = *(int *)a;\n    int j = *(int *)b;\n    return i - j;\n}\n\nint main() {\n    int i, j, n, players, coins, first, round = 1, rem_size;\n    int min, max, guess, index, index2, total;\n    int remaining[9], hands[10], guesses[10];\n    bool found, eliminated;\n    char c;\n    players = get_number(\"Number of players\", 2, 9, TRUE);\n    coins = get_number(\"Number of coins per player\", 3, 6, TRUE);\n    for (i = 0; i < 9; ++i) remaining[i] = i + 1;\n    rem_size = players;\n    srand(time(NULL));\n    first = 1 + rand() % players;\n    printf(\"The number of coins in your hand will be randomly determined for\");\n    printf(\"\\neach round and displayed to you. However, when you press ENTER\");\n    printf(\"\\nit will be erased so that the other players, who should look\");\n    printf(\"\\naway until it's their turn, won't see it. When asked to guess\");\n    printf(\"\\nthe total, the computer won't allow a 'bum guess'.\\n\");\n    while(TRUE) {\n        printf(\"\\nROUND %d:\\n\", round);\n        n = first;\n        for (i = 0; i < 10; ++i) {\n            hands[i] = 0; guesses[i] = -1;\n        }\n        do {\n            printf(\"  PLAYER %d:\\n\", n);\n            printf(\"    Please come to the computer and press ENTER\\n\");\n            hands[n] = rand() % (coins + 1);\n            printf(\"      <There are %d coin(s) in your hand>\", hands[n]);\n            while (getchar() != '\\n');\n            if (!TEST) {\n                printf(\"%c[1A\", ESC);  \n                printf(\"%c[2K\", ESC);  \n                printf(\"\\r\\n\");        \n            }\n            else printf(\"\\n\");\n            while (TRUE) {\n                min = hands[n];\n                max = (rem_size - 1) * coins + hands[n];\n                guess = get_number(\"    Guess the total\", min, max, FALSE);\n                found = FALSE;\n                for (i = 1; i < 10; ++i) {\n                    if (guess == guesses[i]) {\n                        found = TRUE;\n                        break;\n                    }\n                }\n                if (!found) {\n                    guesses[n] = guess;\n                    break;\n                }\n                printf(\"    Already guessed by another player, try again\\n\");\n            }\n            index = -1;\n            for (i = 0; i < rem_size; ++i) {\n                if (remaining[i] == n) {\n                    index = i;\n                    break;\n                }\n            }\n            if (index < rem_size - 1)\n                n = remaining[index + 1];\n            else\n                n = remaining[0];\n        }\n        while (n != first);\n        total = 0;\n        for (i = 1; i < 10; ++i) total += hands[i];\n        printf(\"  Total coins held = %d\\n\", total);\n        eliminated = FALSE;\n        for (i = 0; i < rem_size; ++i) {\n            j = remaining[i];\n            if (guesses[j] == total) {\n                printf(\"  PLAYER %d guessed correctly and is eliminated\\n\", j);\n                remaining[i] = 10;\n                rem_size--;\n                qsort(remaining, players, sizeof(int), compare_int);\n                eliminated = TRUE;\n                break;\n            }\n        }\n        if (!eliminated)\n            printf(\"  No players guessed correctly in this round\\n\");\n        else if (rem_size == 1) {\n            printf(\"\\nPLAYER %d buys the drinks!\\n\", remaining[0]);\n            break;\n        }\n        index2 = -1;\n        for (i = 0; i < rem_size; ++i) {\n            if (remaining[i] == first) {\n                index2 = i;\n                break;\n            }\n        }\n        if (index2 < rem_size - 1)\n            first = remaining[index2 + 1];\n        else\n            first = remaining[0];\n        round++;\n    }\n    return 0;\n}\n"}
{"id": 60555, "name": "Spoof game", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"strconv\"\n    \"time\"\n)\n\nconst (\n    esc  = \"\\033\"\n    test = true \n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nfunc indexOf(s []int, el int) int {\n    for i, v := range s {\n        if v == el {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc getNumber(prompt string, min, max int, showMinMax bool) (int, error) {\n    for {\n        fmt.Print(prompt)\n        if showMinMax {\n            fmt.Printf(\" from %d to %d : \", min, max)\n        } else {\n            fmt.Printf(\" : \")\n        }\n        scanner.Scan()\n        if scerr := scanner.Err(); scerr != nil {\n            return 0, scerr\n        }\n        input, err := strconv.Atoi(scanner.Text())\n        if err == nil && input >= min && input <= max {\n            fmt.Println()\n            return input, nil\n        }\n    }\n}\n\nfunc check(err error, text string) {\n    if err != nil {\n        log.Fatalln(err, text)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    players, err := getNumber(\"Number of players\", 2, 9, true)\n    check(err, \"when getting players\")\n    coins, err2 := getNumber(\"Number of coins per player\", 3, 6, true)\n    check(err2, \"when getting coins\")\n    remaining := make([]int, players)\n    for i := range remaining {\n        remaining[i] = i + 1\n    }\n    first := 1 + rand.Intn(players)\n    fmt.Println(\"The number of coins in your hand will be randomly determined for\")\n    fmt.Println(\"each round and displayed to you. However, when you press ENTER\")\n    fmt.Println(\"it will be erased so that the other players, who should look\")\n    fmt.Println(\"away until it's their turn, won't see it. When asked to guess\")\n    fmt.Println(\"the total, the computer won't allow a 'bum guess'.\")\n    for round := 1; ; round++ {\n        fmt.Printf(\"\\nROUND %d:\\n\\n\", round)\n        n := first\n        hands := make([]int, players+1)\n        guesses := make([]int, players+1)\n        for i := range guesses {\n            guesses[i] = -1\n        }\n        for {\n            fmt.Printf(\"  PLAYER %d:\\n\", n)\n            fmt.Println(\"    Please come to the computer and press ENTER\")\n            hands[n] = rand.Intn(coins + 1)\n            fmt.Print(\"      <There are \", hands[n], \" coin(s) in your hand>\")\n            scanner.Scan()\n            check(scanner.Err(), \"when pressing ENTER\")\n            if !test {\n                fmt.Print(esc, \"[1A\") \n                fmt.Print(esc, \"[2K\") \n                fmt.Println(\"\\r\")     \n            } else {\n                fmt.Println()\n            }\n            for {\n                min := hands[n]\n                max := (len(remaining)-1)*coins + hands[n]\n                guess, err3 := getNumber(\"    Guess the total\", min, max, false)\n                check(err3, \"when guessing the total\")\n                if indexOf(guesses, guess) == -1 {\n                    guesses[n] = guess\n                    break\n                }\n                fmt.Println(\"    Already guessed by another player, try again\")\n            }\n            index := indexOf(remaining, n)\n            if index < len(remaining)-1 {\n                n = remaining[index+1]\n            } else {\n                n = remaining[0]\n            }\n            if n == first {\n                break\n            }\n        }\n        total := 0\n        for _, hand := range hands {\n            total += hand\n        }\n        fmt.Println(\"  Total coins held =\", total)\n        eliminated := false\n        for _, v := range remaining {\n            if guesses[v] == total {\n                fmt.Println(\"  PLAYER\", v, \"guessed correctly and is eliminated\")\n                r := indexOf(remaining, v)\n                remaining = append(remaining[:r], remaining[r+1:]...)\n                eliminated = true\n                break\n            }\n        }\n        if !eliminated {\n            fmt.Println(\"  No players guessed correctly in this round\")\n        } else if len(remaining) == 1 {\n            fmt.Println(\"\\nPLAYER\", remaining[0], \"buys the drinks!\")\n            return\n        }\n        index2 := indexOf(remaining, n)\n        if index2 < len(remaining)-1 {\n            first = remaining[index2+1]\n        } else {\n            first = remaining[0]\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define TRUE 1\n#define FALSE 0\n#define ESC 27\n#define TEST TRUE  \n\ntypedef int bool;\n\nint get_number(const char *prompt, int min, int max, bool show_mm) {\n    int n;\n    char *line = NULL;\n    size_t len = 0;\n    ssize_t read;\n    fflush(stdin);\n    do {\n        printf(\"%s\", prompt);\n        if (show_mm)\n            printf(\" from %d to %d : \", min, max);\n        else\n            printf(\" : \");\n        read = getline(&line, &len, stdin);\n        if (read < 2) continue;\n        n = atoi(line);\n    }\n    while (n < min || n > max);\n    printf(\"\\n\");\n    return n;\n}\n\nint compare_int(const void *a, const void* b) {\n    int i = *(int *)a;\n    int j = *(int *)b;\n    return i - j;\n}\n\nint main() {\n    int i, j, n, players, coins, first, round = 1, rem_size;\n    int min, max, guess, index, index2, total;\n    int remaining[9], hands[10], guesses[10];\n    bool found, eliminated;\n    char c;\n    players = get_number(\"Number of players\", 2, 9, TRUE);\n    coins = get_number(\"Number of coins per player\", 3, 6, TRUE);\n    for (i = 0; i < 9; ++i) remaining[i] = i + 1;\n    rem_size = players;\n    srand(time(NULL));\n    first = 1 + rand() % players;\n    printf(\"The number of coins in your hand will be randomly determined for\");\n    printf(\"\\neach round and displayed to you. However, when you press ENTER\");\n    printf(\"\\nit will be erased so that the other players, who should look\");\n    printf(\"\\naway until it's their turn, won't see it. When asked to guess\");\n    printf(\"\\nthe total, the computer won't allow a 'bum guess'.\\n\");\n    while(TRUE) {\n        printf(\"\\nROUND %d:\\n\", round);\n        n = first;\n        for (i = 0; i < 10; ++i) {\n            hands[i] = 0; guesses[i] = -1;\n        }\n        do {\n            printf(\"  PLAYER %d:\\n\", n);\n            printf(\"    Please come to the computer and press ENTER\\n\");\n            hands[n] = rand() % (coins + 1);\n            printf(\"      <There are %d coin(s) in your hand>\", hands[n]);\n            while (getchar() != '\\n');\n            if (!TEST) {\n                printf(\"%c[1A\", ESC);  \n                printf(\"%c[2K\", ESC);  \n                printf(\"\\r\\n\");        \n            }\n            else printf(\"\\n\");\n            while (TRUE) {\n                min = hands[n];\n                max = (rem_size - 1) * coins + hands[n];\n                guess = get_number(\"    Guess the total\", min, max, FALSE);\n                found = FALSE;\n                for (i = 1; i < 10; ++i) {\n                    if (guess == guesses[i]) {\n                        found = TRUE;\n                        break;\n                    }\n                }\n                if (!found) {\n                    guesses[n] = guess;\n                    break;\n                }\n                printf(\"    Already guessed by another player, try again\\n\");\n            }\n            index = -1;\n            for (i = 0; i < rem_size; ++i) {\n                if (remaining[i] == n) {\n                    index = i;\n                    break;\n                }\n            }\n            if (index < rem_size - 1)\n                n = remaining[index + 1];\n            else\n                n = remaining[0];\n        }\n        while (n != first);\n        total = 0;\n        for (i = 1; i < 10; ++i) total += hands[i];\n        printf(\"  Total coins held = %d\\n\", total);\n        eliminated = FALSE;\n        for (i = 0; i < rem_size; ++i) {\n            j = remaining[i];\n            if (guesses[j] == total) {\n                printf(\"  PLAYER %d guessed correctly and is eliminated\\n\", j);\n                remaining[i] = 10;\n                rem_size--;\n                qsort(remaining, players, sizeof(int), compare_int);\n                eliminated = TRUE;\n                break;\n            }\n        }\n        if (!eliminated)\n            printf(\"  No players guessed correctly in this round\\n\");\n        else if (rem_size == 1) {\n            printf(\"\\nPLAYER %d buys the drinks!\\n\", remaining[0]);\n            break;\n        }\n        index2 = -1;\n        for (i = 0; i < rem_size; ++i) {\n            if (remaining[i] == first) {\n                index2 = i;\n                break;\n            }\n        }\n        if (index2 < rem_size - 1)\n            first = remaining[index2 + 1];\n        else\n            first = remaining[0];\n        round++;\n    }\n    return 0;\n}\n"}
{"id": 60556, "name": "Rosetta Code_Rank languages by number of users", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60557, "name": "Rosetta Code_Rank languages by number of users", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strconv\"\n)\n\ntype Result struct {\n    lang  string\n    users int\n}\n\nfunc main() {\n    const minimum = 25\n    ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n    re := regexp.MustCompile(ex)\n    page := \"http:\n    action := \"action=query\"\n    format := \"format=json\"\n    fversion := \"formatversion=2\"\n    generator := \"generator=categorymembers\"\n    gcmTitle := \"gcmtitle=Category:Language%20users\"\n    gcmLimit := \"gcmlimit=500\"\n    prop := \"prop=categoryinfo\"\n    rawContinue := \"rawcontinue=\"\n    page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n        generator, gcmTitle, gcmLimit, prop, rawContinue)\n    resp, _ := http.Get(page)\n    body, _ := ioutil.ReadAll(resp.Body)\n    matches := re.FindAllStringSubmatch(string(body), -1)\n    resp.Body.Close()\n    var results []Result\n    for _, match := range matches {\n        if len(match) == 5 {\n            users, _ := strconv.Atoi(match[4]) \n            if users >= minimum {\n                result := Result{match[1], users}\n                results = append(results, result)\n            }\n        }\n    }\n    sort.Slice(results, func(i, j int) bool {\n        return results[j].users < results[i].users\n    })\n\n    fmt.Println(\"Rank  Users  Language\")\n    fmt.Println(\"----  -----  --------\")\n    rank := 0\n    lastUsers := 0\n    lastRank := 0\n    for i, result := range results {\n        eq := \" \"\n        rank = i + 1\n        if lastUsers == result.users {\n            eq = \"=\"\n            rank = lastRank\n        } else {\n            lastUsers = result.users\n            lastRank = rank\n        }\n        fmt.Printf(\" %-2d%s   %3d    %s\\n\", rank, eq, result.users, result.lang)\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_rank_languages_by_number_of_users.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60558, "name": "Addition-chain exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    N    = 32\n    NMAX = 40000\n)\n\nvar (\n    u     = [N]int{0: 1, 1: 2} \n    l     = [N]int{0: 1, 1: 2} \n    out   = [N]int{}\n    sum   = [N]int{}\n    tail  = [N]int{}\n    cache = [NMAX + 1]int{2: 1}\n    known = 2\n    stack = 0\n    undo  = [N * N]save{}\n)\n\ntype save struct {\n    p *int\n    v int\n}\n\nfunc replace(x *[N]int, i, n int) {\n    undo[stack].p = &x[i]\n    undo[stack].v = x[i]\n    x[i] = n\n    stack++\n}\n\nfunc restore(n int) {\n    for stack > n {\n        stack--\n        *undo[stack].p = undo[stack].v\n    }\n}\n\n\nfunc lower(n int, up *int) int {\n    if n <= 2 || (n <= NMAX && cache[n] != 0) {\n        if up != nil {\n            *up = cache[n]\n        }\n        return cache[n]\n    }\n    i, o := -1, 0\n    for ; n != 0; n, i = n>>1, i+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    if up != nil {\n        i--\n        *up = o + i\n    }\n    for {\n        i++\n        o >>= 1\n        if o == 0 {\n            break\n        }\n    }\n    if up == nil {\n        return i\n    }\n    for o = 2; o*o < n; o++ {\n        if n%o != 0 {\n            continue\n        }\n        q := cache[o] + cache[n/o]\n        if q < *up {\n            *up = q\n            if q == i {\n                break\n            }\n        }\n    }\n    if n > 2 {\n        if *up > cache[n-2]+1 {\n            *up = cache[n-1] + 1\n        }\n        if *up > cache[n-2]+1 {\n            *up = cache[n-2] + 1\n        }\n    }\n    return i\n}\n\nfunc insert(x, pos int) bool {\n    save := stack\n    if l[pos] > x || u[pos] < x {\n        return false\n    }\n    if l[pos] == x {\n        goto replU\n    }\n    replace(&l, pos, x)\n    for i := pos - 1; u[i]*2 < u[i+1]; i-- {\n        t := l[i+1] + 1\n        if t*2 > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\n    for i := pos + 1; l[i] <= l[i-1]; i++ {\n        t := l[i-1] + 1\n        if t > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\nreplU:\n    if u[pos] == x {\n        return true\n    }\n    replace(&u, pos, x)\n    for i := pos - 1; u[i] >= u[i+1]; i-- {\n        t := u[i+1] - 1\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    for i := pos + 1; u[i] > u[i-1]*2; i++ {\n        t := u[i-1] * 2\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    return true\nbail:\n    restore(save)\n    return false\n}\n\nfunc try(p, q, le int) bool {\n    pl := cache[p]\n    if pl >= le {\n        return false\n    }\n    ql := cache[q]\n    if ql >= le {\n        return false\n    }\n    var pu, qu int\n    for pl < le && u[pl] < p {\n        pl++\n    }\n    for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {\n\n    }\n    for ql < le && u[ql] < q {\n        ql++\n    }\n    for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {\n\n    }\n    if p != q && pl <= ql {\n        pl = ql + 1\n    }\n    if pl > pu || ql > qu || ql > pu {\n        return false\n    }\n    if out[le] == 0 {\n        pu = le - 1\n        pl = pu\n    }\n    ps := stack\n    for ; pu >= pl; pu-- {\n        if !insert(p, pu) {\n            continue\n        }\n        out[pu]++\n        sum[pu] += le\n        if p != q {\n            qs := stack\n            j := qu\n            if j >= pu {\n                j = pu - 1\n            }\n            for ; j >= ql; j-- {\n                if !insert(q, j) {\n                    continue\n                }\n                out[j]++\n                sum[j] += le\n                tail[le] = q\n                if seqRecur(le - 1) {\n                    return true\n                }\n                restore(qs)\n                out[j]--\n                sum[j] -= le\n            }\n        } else {\n            out[pu]++\n            sum[pu] += le\n            tail[le] = p\n            if seqRecur(le - 1) {\n                return true\n            }\n            out[pu]--\n            sum[pu] -= le\n        }\n        out[pu]--\n        sum[pu] -= le\n        restore(ps)\n    }\n    return false\n}\n\nfunc seqRecur(le int) bool {\n    n := l[le]\n    if le < 2 {\n        return true\n    }\n    limit := n - 1\n    if out[le] == 1 {\n        limit = n - tail[sum[le]]\n    }\n    if limit > u[le-1] {\n        limit = u[le-1]\n    }\n    \n    \n    p := limit\n    for q := n - p; q <= p; q, p = q+1, p-1 {\n        if try(p, q, le) {\n            return true\n        }\n    }\n    return false\n}\n\nfunc seq(n, le int, buf []int) int {\n    if le == 0 {\n        le = seqLen(n)\n    }\n    stack = 0\n    l[le], u[le] = n, n\n    for i := 0; i <= le; i++ {\n        out[i], sum[i] = 0, 0\n    }\n    for i := 2; i < le; i++ {\n        l[i] = l[i-1] + 1\n        u[i] = u[i-1] * 2\n    }\n    for i := le - 1; i > 2; i-- {\n        if l[i]*2 < l[i+1] {\n            l[i] = (1 + l[i+1]) / 2\n        }\n        if u[i] >= u[i+1] {\n            u[i] = u[i+1] - 1\n        }\n    }\n    if !seqRecur(le) {\n        return 0\n    }\n    if buf != nil {\n        for i := 0; i <= le; i++ {\n            buf[i] = u[i]\n        }\n    }\n    return le\n}\n\nfunc seqLen(n int) int {\n    if n <= known {\n        return cache[n]\n    }\n    \n    for known+1 < n {\n        seqLen(known + 1)\n    }\n    var ub int\n    lb := lower(n, &ub)\n    for lb < ub && seq(n, lb, nil) == 0 {\n        lb++\n    }\n    known = n\n    if n&1023 == 0 {\n        fmt.Printf(\"Cached %d\\n\", known)\n    }\n    cache[n] = lb\n    return lb\n}\n\nfunc binLen(n int) int {\n    r, o := -1, -1\n    for ; n != 0; n, r = n>>1, r+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    return r + o\n}\n\ntype(\n    vector = []float64\n    matrix []vector\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m matrix) pow(n int, printout bool) matrix {\n    e := make([]int, N)\n    var v [N]matrix\n    le := seq(n, 0, e)\n    if printout {\n        fmt.Println(\"Addition chain:\")\n        for i := 0; i <= le; i++ {\n            c := ' '\n            if i == le {\n                c = '\\n'\n            }\n            fmt.Printf(\"%d%c\", e[i], c)\n        }\n    }\n    v[0] = m\n    v[1] = m.mul(m)\n    for i := 2; i <= le; i++ {\n        for j := i - 1; j != 0; j-- {\n            for k := j; k >= 0; k-- {\n                if e[k]+e[j] < e[i] {\n                    break\n                }\n                if e[k]+e[j] > e[i] {\n                    continue\n                }\n                v[i] = v[j].mul(v[k])\n                j = 1\n                break\n            }\n        }\n    }\n    return v[le]\n}\n\nfunc (m matrix) print() {\n    for _, v := range m {\n        fmt.Printf(\"% f\\n\", v)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    m := 27182\n    n := 31415\n    fmt.Println(\"Precompute chain lengths:\")\n    seqLen(n)\n    rh := math.Sqrt(0.5)\n    mx := matrix{\n        {rh, 0, rh, 0, 0, 0},\n        {0, rh, 0, rh, 0, 0},\n        {0, rh, 0, -rh, 0, 0},\n        {-rh, 0, rh, 0, 0, 0},\n        {0, 0, 0, 0, 0, 1},\n        {0, 0, 0, 0, 1, 0},\n    }\n    fmt.Println(\"\\nThe first 100 terms of A003313 are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%d \", seqLen(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n    exs := [2]int{m, n}\n    mxs := [2]matrix{}\n    for i, ex := range exs {\n        fmt.Println(\"\\nExponent:\", ex)\n        mxs[i] = mx.pow(ex, true)\n        fmt.Printf(\"A ^ %d:-\\n\\n\", ex)\n        mxs[i].print()\n        fmt.Println(\"Number of A/C multiplies:\", seqLen(ex))\n        fmt.Println(\"  c.f. Binary multiplies:\", binLen(ex))\n    }\n    fmt.Printf(\"\\nExponent: %d x %d = %d\\n\", m, n, m*n)\n    fmt.Printf(\"A ^ %d = (A ^ %d) ^ %d:-\\n\\n\", m*n, m, n)   \n    mx2 := mxs[0].pow(n, false)\n    mx2.print()\n}\n", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n"}
{"id": 60559, "name": "Addition-chain exponentiation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    N    = 32\n    NMAX = 40000\n)\n\nvar (\n    u     = [N]int{0: 1, 1: 2} \n    l     = [N]int{0: 1, 1: 2} \n    out   = [N]int{}\n    sum   = [N]int{}\n    tail  = [N]int{}\n    cache = [NMAX + 1]int{2: 1}\n    known = 2\n    stack = 0\n    undo  = [N * N]save{}\n)\n\ntype save struct {\n    p *int\n    v int\n}\n\nfunc replace(x *[N]int, i, n int) {\n    undo[stack].p = &x[i]\n    undo[stack].v = x[i]\n    x[i] = n\n    stack++\n}\n\nfunc restore(n int) {\n    for stack > n {\n        stack--\n        *undo[stack].p = undo[stack].v\n    }\n}\n\n\nfunc lower(n int, up *int) int {\n    if n <= 2 || (n <= NMAX && cache[n] != 0) {\n        if up != nil {\n            *up = cache[n]\n        }\n        return cache[n]\n    }\n    i, o := -1, 0\n    for ; n != 0; n, i = n>>1, i+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    if up != nil {\n        i--\n        *up = o + i\n    }\n    for {\n        i++\n        o >>= 1\n        if o == 0 {\n            break\n        }\n    }\n    if up == nil {\n        return i\n    }\n    for o = 2; o*o < n; o++ {\n        if n%o != 0 {\n            continue\n        }\n        q := cache[o] + cache[n/o]\n        if q < *up {\n            *up = q\n            if q == i {\n                break\n            }\n        }\n    }\n    if n > 2 {\n        if *up > cache[n-2]+1 {\n            *up = cache[n-1] + 1\n        }\n        if *up > cache[n-2]+1 {\n            *up = cache[n-2] + 1\n        }\n    }\n    return i\n}\n\nfunc insert(x, pos int) bool {\n    save := stack\n    if l[pos] > x || u[pos] < x {\n        return false\n    }\n    if l[pos] == x {\n        goto replU\n    }\n    replace(&l, pos, x)\n    for i := pos - 1; u[i]*2 < u[i+1]; i-- {\n        t := l[i+1] + 1\n        if t*2 > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\n    for i := pos + 1; l[i] <= l[i-1]; i++ {\n        t := l[i-1] + 1\n        if t > u[i] {\n            goto bail\n        }\n        replace(&l, i, t)\n    }\nreplU:\n    if u[pos] == x {\n        return true\n    }\n    replace(&u, pos, x)\n    for i := pos - 1; u[i] >= u[i+1]; i-- {\n        t := u[i+1] - 1\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    for i := pos + 1; u[i] > u[i-1]*2; i++ {\n        t := u[i-1] * 2\n        if t < l[i] {\n            goto bail\n        }\n        replace(&u, i, t)\n    }\n    return true\nbail:\n    restore(save)\n    return false\n}\n\nfunc try(p, q, le int) bool {\n    pl := cache[p]\n    if pl >= le {\n        return false\n    }\n    ql := cache[q]\n    if ql >= le {\n        return false\n    }\n    var pu, qu int\n    for pl < le && u[pl] < p {\n        pl++\n    }\n    for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {\n\n    }\n    for ql < le && u[ql] < q {\n        ql++\n    }\n    for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {\n\n    }\n    if p != q && pl <= ql {\n        pl = ql + 1\n    }\n    if pl > pu || ql > qu || ql > pu {\n        return false\n    }\n    if out[le] == 0 {\n        pu = le - 1\n        pl = pu\n    }\n    ps := stack\n    for ; pu >= pl; pu-- {\n        if !insert(p, pu) {\n            continue\n        }\n        out[pu]++\n        sum[pu] += le\n        if p != q {\n            qs := stack\n            j := qu\n            if j >= pu {\n                j = pu - 1\n            }\n            for ; j >= ql; j-- {\n                if !insert(q, j) {\n                    continue\n                }\n                out[j]++\n                sum[j] += le\n                tail[le] = q\n                if seqRecur(le - 1) {\n                    return true\n                }\n                restore(qs)\n                out[j]--\n                sum[j] -= le\n            }\n        } else {\n            out[pu]++\n            sum[pu] += le\n            tail[le] = p\n            if seqRecur(le - 1) {\n                return true\n            }\n            out[pu]--\n            sum[pu] -= le\n        }\n        out[pu]--\n        sum[pu] -= le\n        restore(ps)\n    }\n    return false\n}\n\nfunc seqRecur(le int) bool {\n    n := l[le]\n    if le < 2 {\n        return true\n    }\n    limit := n - 1\n    if out[le] == 1 {\n        limit = n - tail[sum[le]]\n    }\n    if limit > u[le-1] {\n        limit = u[le-1]\n    }\n    \n    \n    p := limit\n    for q := n - p; q <= p; q, p = q+1, p-1 {\n        if try(p, q, le) {\n            return true\n        }\n    }\n    return false\n}\n\nfunc seq(n, le int, buf []int) int {\n    if le == 0 {\n        le = seqLen(n)\n    }\n    stack = 0\n    l[le], u[le] = n, n\n    for i := 0; i <= le; i++ {\n        out[i], sum[i] = 0, 0\n    }\n    for i := 2; i < le; i++ {\n        l[i] = l[i-1] + 1\n        u[i] = u[i-1] * 2\n    }\n    for i := le - 1; i > 2; i-- {\n        if l[i]*2 < l[i+1] {\n            l[i] = (1 + l[i+1]) / 2\n        }\n        if u[i] >= u[i+1] {\n            u[i] = u[i+1] - 1\n        }\n    }\n    if !seqRecur(le) {\n        return 0\n    }\n    if buf != nil {\n        for i := 0; i <= le; i++ {\n            buf[i] = u[i]\n        }\n    }\n    return le\n}\n\nfunc seqLen(n int) int {\n    if n <= known {\n        return cache[n]\n    }\n    \n    for known+1 < n {\n        seqLen(known + 1)\n    }\n    var ub int\n    lb := lower(n, &ub)\n    for lb < ub && seq(n, lb, nil) == 0 {\n        lb++\n    }\n    known = n\n    if n&1023 == 0 {\n        fmt.Printf(\"Cached %d\\n\", known)\n    }\n    cache[n] = lb\n    return lb\n}\n\nfunc binLen(n int) int {\n    r, o := -1, -1\n    for ; n != 0; n, r = n>>1, r+1 {\n        if n&1 != 0 {\n            o++\n        }\n    }\n    return r + o\n}\n\ntype(\n    vector = []float64\n    matrix []vector\n)\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    rows1, cols1 := len(m1), len(m1[0])\n    rows2, cols2 := len(m2), len(m2[0])\n    if cols1 != rows2 {\n        panic(\"Matrices cannot be multiplied.\")\n    }\n    result := make(matrix, rows1)\n    for i := 0; i < rows1; i++ {\n        result[i] = make(vector, cols2)\n        for j := 0; j < cols2; j++ {\n            for k := 0; k < rows2; k++ {\n                result[i][j] += m1[i][k] * m2[k][j]\n            }\n        }\n    }\n    return result\n}\n\nfunc (m matrix) pow(n int, printout bool) matrix {\n    e := make([]int, N)\n    var v [N]matrix\n    le := seq(n, 0, e)\n    if printout {\n        fmt.Println(\"Addition chain:\")\n        for i := 0; i <= le; i++ {\n            c := ' '\n            if i == le {\n                c = '\\n'\n            }\n            fmt.Printf(\"%d%c\", e[i], c)\n        }\n    }\n    v[0] = m\n    v[1] = m.mul(m)\n    for i := 2; i <= le; i++ {\n        for j := i - 1; j != 0; j-- {\n            for k := j; k >= 0; k-- {\n                if e[k]+e[j] < e[i] {\n                    break\n                }\n                if e[k]+e[j] > e[i] {\n                    continue\n                }\n                v[i] = v[j].mul(v[k])\n                j = 1\n                break\n            }\n        }\n    }\n    return v[le]\n}\n\nfunc (m matrix) print() {\n    for _, v := range m {\n        fmt.Printf(\"% f\\n\", v)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    m := 27182\n    n := 31415\n    fmt.Println(\"Precompute chain lengths:\")\n    seqLen(n)\n    rh := math.Sqrt(0.5)\n    mx := matrix{\n        {rh, 0, rh, 0, 0, 0},\n        {0, rh, 0, rh, 0, 0},\n        {0, rh, 0, -rh, 0, 0},\n        {-rh, 0, rh, 0, 0, 0},\n        {0, 0, 0, 0, 0, 1},\n        {0, 0, 0, 0, 1, 0},\n    }\n    fmt.Println(\"\\nThe first 100 terms of A003313 are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%d \", seqLen(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n    exs := [2]int{m, n}\n    mxs := [2]matrix{}\n    for i, ex := range exs {\n        fmt.Println(\"\\nExponent:\", ex)\n        mxs[i] = mx.pow(ex, true)\n        fmt.Printf(\"A ^ %d:-\\n\\n\", ex)\n        mxs[i].print()\n        fmt.Println(\"Number of A/C multiplies:\", seqLen(ex))\n        fmt.Println(\"  c.f. Binary multiplies:\", binLen(ex))\n    }\n    fmt.Printf(\"\\nExponent: %d x %d = %d\\n\", m, n, m*n)\n    fmt.Printf(\"A ^ %d = (A ^ %d) ^ %d:-\\n\\n\", m*n, m, n)   \n    mx2 := mxs[0].pow(n, false)\n    mx2.print()\n}\n", "C": "#include <stdio.h>\n\n#include \"achain.c\" \n\n\ntypedef struct {double u, v;} cplx;\n\ninline cplx c_mul(cplx a, cplx b)\n{\n\tcplx c;\n\tc.u = a.u * b.u - a.v * b.v;\n\tc.v = a.u * b.v + a.v * b.u;\n\treturn c;\n}\n\ncplx chain_expo(cplx x, int n)\n{\n\tint i, j, k, l, e[32];\n\tcplx v[32];\n\n\tl = seq(n, 0, e);\n\n\tputs(\"Exponents:\");\n\tfor (i = 0; i <= l; i++)\n\t\tprintf(\"%d%c\", e[i], i == l ? '\\n' : ' ');\n\n\tv[0] = x; v[1] = c_mul(x, x);\n\tfor (i = 2; i <= l; i++) {\n\t\tfor (j = i - 1; j; j--) {\n\t\t\tfor (k = j; k >= 0; k--) {\n\t\t\t\tif (e[k] + e[j] < e[i]) break;\n\t\t\t\tif (e[k] + e[j] > e[i]) continue;\n\t\t\t\tv[i] = c_mul(v[j], v[k]);\n\t\t\t\tj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"(%f + i%f)^%d = %f + i%f\\n\",\n\t\tx.u, x.v, n, v[l].u, v[l].v);\n\n\treturn x;\n}\n\nint bin_len(int n)\n{\n\tint r, o;\n\tfor (r = o = -1; n; n >>= 1, r++)\n\t\tif (n & 1) o++;\n\treturn r + o;\n}\n\nint main()\n{\n\tcplx\tr1 = {1.0000254989, 0.0000577896},\n\t\tr2 = {1.0000220632, 0.0000500026};\n\tint n1 = 27182, n2 = 31415, i;\n\n\tinit();\n\tputs(\"Precompute chain lengths\");\n\tseq_len(n2);\n\n\tchain_expo(r1, n1);\n\tchain_expo(r2, n2);\n\tputs(\"\\nchain lengths: shortest binary\");\n\tprintf(\"%14d %7d %7d\\n\", n1, seq_len(n1), bin_len(n1));\n\tprintf(\"%14d %7d %7d\\n\", n2, seq_len(n2), bin_len(n2));\n\tfor (i = 1; i < 100; i++)\n\t\tprintf(\"%14d %7d %7d\\n\", i, seq_len(i), bin_len(i));\n\treturn 0;\n}\n"}
{"id": 60560, "name": "Multiline shebang", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n", "C": "\n"}
{"id": 60561, "name": "Multiline shebang", "Go": "#!/bin/bash\nsed -n -e '12,$p' < \"$0\" > ttmmpp.go\ngo build ttmmpp.go\nrm ttmmpp.go\nbinfile=\"${0%.*}\"\nmv ttmmpp $binfile\n$binfile \"$@\"\nSTATUS=$?\nrm $binfile\nexit $STATUS\n######## Go Code start on line 12\npackage main\nimport (\n  \"fmt\"\n  \"os\"\n)\n \nfunc main() {\n  for i, x := range os.Args {\n    if i == 0 {\n      fmt.Printf(\"This program is named %s.\\n\", x)\n    } else {\n      fmt.Printf(\"the argument #%d is %s\\n\", i, x)\n    }\n  }\n}\n", "C": "\n"}
{"id": 60562, "name": "Terminal control_Unicode output", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n"}
{"id": 60563, "name": "Terminal control_Unicode output", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    lang := strings.ToUpper(os.Getenv(\"LANG\"))\n    if strings.Contains(lang, \"UTF\") {\n        fmt.Printf(\"This terminal supports unicode and U+25b3 is : %c\\n\", '\\u25b3')\n    } else {\n        fmt.Println(\"This terminal does not support unicode\")\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint\nmain ()\n{\n  int i;\n  char *str = getenv (\"LANG\");\n\n  for (i = 0; str[i + 2] != 00; i++)\n    {\n      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')\n          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))\n        {\n          printf\n            (\"Unicode is supported on this terminal and U+25B3 is : \\u25b3\");\n          i = -1;\n          break;\n        }\n    }\n\n  if (i != -1)\n    printf (\"Unicode is not supported on this terminal.\");\n\n  return 0;\n}\n"}
{"id": 60564, "name": "Sorting algorithms_Tree sort on a linked list", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n"}
{"id": 60565, "name": "Sorting algorithms_Tree sort on a linked list", "Go": "package main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\ntype BinaryTree struct {\n    node         int\n    leftSubTree  *BinaryTree\n    rightSubTree *BinaryTree\n}\n\nfunc (bt *BinaryTree) insert(item int) {\n    if bt.node == 0 {\n        bt.node = item\n        bt.leftSubTree = &BinaryTree{}\n        bt.rightSubTree = &BinaryTree{}\n    } else if item < bt.node {\n        bt.leftSubTree.insert(item)\n    } else {\n        bt.rightSubTree.insert(item)\n    }\n}\n\nfunc (bt *BinaryTree) inOrder(ll *list.List) {\n    if bt.node == 0 {\n        return\n    }\n    bt.leftSubTree.inOrder(ll)\n    ll.PushBack(bt.node)\n    bt.rightSubTree.inOrder(ll)\n}\nfunc treeSort(ll *list.List) *list.List {\n    searchTree := &BinaryTree{}\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        searchTree.insert(i)\n    }\n    ll2 := list.New()\n    searchTree.inOrder(ll2)\n    return ll2\n}\n\nfunc printLinkedList(ll *list.List, f string, sorted bool) {\n    for e := ll.Front(); e != nil; e = e.Next() {\n        i := e.Value.(int)\n        fmt.Printf(f+\" \", i)\n    }\n    if !sorted {\n        fmt.Print(\"-> \")\n    } else {\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    sl := []int{5, 3, 7, 9, 1}\n    ll := list.New()\n    for _, i := range sl {\n        ll.PushBack(i)\n    }\n    printLinkedList(ll, \"%d\", false)\n    lls := treeSort(ll)\n    printLinkedList(lls, \"%d\", true)\n\n    sl2 := []int{'d', 'c', 'e', 'b', 'a'}\n    ll2 := list.New()\n    for _, c := range sl2 {\n        ll2.PushBack(c)\n    }\n    printLinkedList(ll2, \"%c\", false)\n    lls2 := treeSort(ll2)\n    printLinkedList(lls2, \"%c\", true)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\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\ntypedef struct node_tag {\n    int item;\n    struct node_tag* prev;\n    struct node_tag* next;\n} node_t;\n\nvoid list_initialize(node_t* list) {\n    list->prev = list;\n    list->next = list;\n}\n\nvoid list_destroy(node_t* list) {\n    node_t* n = list->next;\n    while (n != list) {\n        node_t* tmp = n->next;\n        free(n);\n        n = tmp;\n    }\n}\n\nvoid list_append_node(node_t* list, node_t* node) {\n    node_t* prev = list->prev;\n    prev->next = node;\n    list->prev = node;\n    node->prev = prev;\n    node->next = list;\n}\n\nvoid list_append_item(node_t* list, int item) {\n    node_t* node = xmalloc(sizeof(node_t));\n    node->item = item;\n    list_append_node(list, node);\n}\n\nvoid list_print(node_t* list) {\n    printf(\"[\");\n    node_t* n = list->next;\n    if (n != list) {\n        printf(\"%d\", n->item);\n        n = n->next;\n    }\n    for (; n != list; n = n->next)\n        printf(\", %d\", n->item);\n    printf(\"]\\n\");\n}\n\nvoid tree_insert(node_t** p, node_t* n) {\n    while (*p != NULL) {\n        if (n->item < (*p)->item)\n            p = &(*p)->prev;\n        else\n            p = &(*p)->next;\n    }\n    *p = n;\n}\n\nvoid tree_to_list(node_t* list, node_t* node) {\n    if (node == NULL)\n        return;\n    node_t* prev = node->prev;\n    node_t* next = node->next;\n    tree_to_list(list, prev);\n    list_append_node(list, node);\n    tree_to_list(list, next);\n}\n\nvoid tree_sort(node_t* list) {\n    node_t* n = list->next;\n    if (n == list)\n        return;\n    node_t* root = NULL;\n    while (n != list) {\n        node_t* next = n->next;\n        n->next = n->prev = NULL;\n        tree_insert(&root, n);\n        n = next;\n    }\n    list_initialize(list);\n    tree_to_list(list, root);\n}\n\nint main() {\n    srand(time(0));\n    node_t list;\n    list_initialize(&list);\n    for (int i = 0; i < 16; ++i)\n        list_append_item(&list, rand() % 100);\n    printf(\"before sort: \");\n    list_print(&list);\n    tree_sort(&list);\n    printf(\" after sort: \");\n    list_print(&list);\n    list_destroy(&list);\n    return 0;\n}\n"}
{"id": 60566, "name": "Find adjacent primes which differ by a square integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n"}
{"id": 60567, "name": "Find adjacent primes which differ by a square integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := 999999\n    primes := rcu.Primes(limit)\n    fmt.Println(\"Adjacent primes under 1,000,000 whose difference is a square > 36:\")\n    for i := 1; i < len(primes); i++ {\n        diff := primes[i] - primes[i-1]\n        if diff > 36 {\n            s := int(math.Sqrt(float64(diff)))\n            if diff == s*s {\n                cp1 := rcu.Commatize(primes[i])\n                cp2 := rcu.Commatize(primes[i-1])\n                fmt.Printf(\"%7s - %7s = %3d = %2d x %2d\\n\", cp1, cp2, diff, s, s)\n            }\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint issquare( int p ) {\n    int i;\n    for(i=0;i*i<p;i++);\n    return i*i==p;\n}\n\nint main(void) {\n    int i=3, j=2;\n    for(i=3;j<=1000000;i=j) {\n        j=nextprime(i);\n        if(j-i>36&&issquare(j-i)) printf( \"%d %d %d\\n\", i, j, j-i );\n    }\n    return 0;\n}\n"}
{"id": 60568, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 60569, "name": "Truncate a file", "Go": "import (\n    \"fmt\"\n    \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n    fmt.Println(err)\n}\n", "C": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n\n\nvoid\noops(const wchar_t *message)\n{\n\twchar_t *buf;\n\tDWORD error;\n\n\tbuf = NULL;\n\terror = GetLastError();\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t    NULL, error, 0, (wchar_t *)&buf, 0, NULL);\n\n\tif (buf) {\n\t\tfwprintf(stderr, L\"%ls: %ls\", message, buf);\n\t\tLocalFree(buf);\n\t} else {\n\t\t\n\t\tfwprintf(stderr, L\"%ls: unknown error 0x%x\\n\",\n\t\t    message, error);\n\t}\n}\n\nint\ndotruncate(wchar_t *fn, LARGE_INTEGER fp)\n{\n\tHANDLE fh;\n\n\tfh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\toops(fn);\n\t\treturn 1;\n\t}\n\n\tif (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||\n\t    SetEndOfFile(fh) == 0) {\n\t\toops(fn);\n\t\tCloseHandle(fh);\n\t\treturn 1;\n\t}\n\n\tCloseHandle(fh);\n\treturn 0;\n}\n\n\nint\nmain()\n{\n\tLARGE_INTEGER fp;\n\tint argc;\n\twchar_t **argv, *fn, junk[2];\n\n\t\n\targv = CommandLineToArgvW(GetCommandLineW(), &argc);\n\tif (argv == NULL) {\n\t\toops(L\"CommandLineToArgvW\");\n\t\treturn 1;\n\t}\n\n\tif (argc != 3) {\n\t\tfwprintf(stderr, L\"usage: %ls filename length\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tfn = argv[1];\n\n\t\n\tif (swscanf(argv[2], L\"%lld%1ls\", &fp.QuadPart, &junk) != 1) {\n\t\tfwprintf(stderr, L\"%ls: not a number\\n\", argv[2]);\n\t\treturn 1;\n\t}\n\n\treturn dotruncate(fn, fp);\n}\n"}
{"id": 60570, "name": "Video display modes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60571, "name": "Video display modes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"time\"\n)\n\nfunc main() {\n    \n    out, err := exec.Command(\"xrandr\", \"-q\").Output()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(out))\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1024x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n    time.Sleep(3 * time.Second)\n\n    \n    err = exec.Command(\"xrandr\", \"-s\", \"1366x768\").Run()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_xrandr(WrenVM* vm) {\n     const char *arg = wrenGetSlotString(vm, 1);\n     char command[strlen(arg) + 8];\n     strcpy(command, \"xrandr \");\n     strcat(command, arg);\n     system(command);\n}\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"xrandr(_)\") == 0) return C_xrandr;\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0) return C_usleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"video_display_modes.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60572, "name": "Keyboard input_Flush the keyboard buffer", "Go": "package main\n\nimport (\n    \"log\"\n\n    gc \"code.google.com/p/goncurses\"\n)\n\nfunc main() {\n    _, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init:\", err)\n    }\n    defer gc.End()\n    gc.FlushInput()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char* argv[])\n{\n    \n    \n    char text[256];\n    getchar();\n\n    \n    \n    \n    \n\n    \n    \n    fseek(stdin, 0, SEEK_END);\n\n    \n    \n    \n\n    \n    \n    fgets(text, sizeof(text), stdin);\n    puts(text);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60573, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n"}
{"id": 60574, "name": "Numerical integration_Adaptive Simpson's method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype F = func(float64) float64\n\n\nfunc quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {\n    \n    m = (a + b) / 2\n    fm = f(m)\n    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)\n    return\n}\n\nfunc quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {\n    \n    \n    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)\n    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)\n    delta := left + right - whole\n    if math.Abs(delta) <= eps*15 {\n        return left + right + delta/15\n    }\n    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +\n        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)\n}\n\nfunc quadAsr(f F, a, b, eps float64) float64 {\n    \n    fa, fb := f(a), f(b)\n    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)\n    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)\n}\n\nfunc main() {\n    a, b := 0.0, 1.0\n    sinx := quadAsr(math.Sin, a, b, 1e-09)\n    fmt.Printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx)   \n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct { double m; double fm; double simp; } triple;\n\n\ntriple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {\n    \n    double m = (a + b) / 2;\n    double fm = f(m);\n    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);\n    triple t = {m, fm, simp};\n    return t;\n}\n\ndouble _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {\n    \n    \n    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);\n    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);\n    double delta = lt.simp + rt.simp - whole;\n    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;\n    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +\n           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);\n}\n\ndouble quad_asr(double (*f)(double), double a, double b, double eps) {\n    \n    double fa = f(a);\n    double fb = f(b);\n    triple t = _quad_simpsons_mem(f, a, fa, b, fb);\n    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);\n}\n\nint main(){\n    double a = 0.0, b = 1.0;\n    double sinx = quad_asr(sin, a, b, 1e-09);\n    printf(\"Simpson's integration of sine from %g to %g = %f\\n\", a, b, sinx);\n    return 0;\n}\n"}
{"id": 60575, "name": "FASTA format", "Go": "package main\n\nimport (\n        \"bufio\"\n        \"fmt\"\n        \"os\"\n)\n\nfunc main() {\n        f, err := os.Open(\"rc.fasta\")\n        if err != nil {\n                fmt.Println(err)\n                return\n        }\n        defer f.Close()\n        s := bufio.NewScanner(f)\n        headerFound := false\n        for s.Scan() {\n                line := s.Text()\n                switch {\n                case line == \"\":\n                        continue\n                case line[0] != '>':\n                        if !headerFound {\n                                fmt.Println(\"missing header\")\n                                return\n                        }\n                        fmt.Print(line)\n                case headerFound:\n                        fmt.Println()\n                        fallthrough\n                default:\n                        fmt.Printf(\"%s: \", line[1:])\n                        headerFound = true\n                }\n        }\n        if headerFound {\n                fmt.Println()\n        }\n        if err := s.Err(); err != nil {\n                fmt.Println(err)\n        }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid main()\n{\n\tFILE * fp;\n\tchar * line = NULL;\n\tsize_t len = 0;\n\tssize_t read;\n\n\tfp = fopen(\"fasta.txt\", \"r\");\n\tif (fp == NULL)\n\t\texit(EXIT_FAILURE);\n\n\tint state = 0;\n\twhile ((read = getline(&line, &len, fp)) != -1) {\n\t\t\n\t\tif (line[read - 1] == '\\n')\n\t\t\tline[read - 1] = 0;\n\t\t\n\t\tif (line[0] == '>') {\n\t\t\tif (state == 1)\n\t\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"%s: \", line+1);\n\t\t\tstate = 1;\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\", line);\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\n\tfclose(fp);\n\tif (line)\n\t\tfree(line);\n\texit(EXIT_SUCCESS);\n}\n"}
{"id": 60576, "name": "Cousin 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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\n    return 0;\n}\n"}
{"id": 60577, "name": "Cousin 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 main() {\n    count := 0\n    fmt.Println(\"Cousin prime pairs whose elements are less than 1,000:\")\n    for i := 3; i <= 995; i += 2 {\n        if isPrime(i) && isPrime(i+4) {\n            fmt.Printf(\"%3d:%3d  \", i, i+4)\n            count++\n            if count%7 == 0 {\n                fmt.Println()\n            }\n            if i != 3 {\n                i += 4\n            } else {\n                i += 2\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d pairs found\\n\", count)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 1000\n\nvoid sieve(int max, char *s) {\n    int p, k;\n    memset(s, 0, max);\n    for (p=2; p*p<=max; p++)\n        if (!s[p]) \n            for (k=p*p; k<=max; k+=p) \n                s[k]=1;\n}\n\nint main(void) {\n    char primes[LIMIT+1];\n    int p, count=0;\n    \n    sieve(LIMIT, primes);\n    for (p=2; p<=LIMIT; p++) {\n        if (!primes[p] && !primes[p+4]) {\n            count++;\n            printf(\"%4d: %4d\\n\", p, p+4);\n        }\n    }\n    \n    printf(\"There are %d cousin prime pairs below %d.\\n\", count, LIMIT);\n    return 0;\n}\n"}
{"id": 60578, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 60579, "name": "Find palindromic numbers in both binary and ternary bases", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n    x := uint64(0)\n    if (n & 1) == 0 {\n        return n == 0\n    }\n    for x < n {\n        x = (x << 1) | (n & 1)\n        n >>= 1\n    }\n    return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n    x := uint64(0)\n    for n != 0 {\n        x = x*3 + (n % 3)\n        n /= 3\n    }\n    return x\n}\n\nfunc show(n uint64) {\n    fmt.Println(\"Decimal :\", n)\n    fmt.Println(\"Binary  :\", strconv.FormatUint(n, 2))\n    fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n    fmt.Println(\"Time    :\", time.Since(start))\n    fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n    if a < b {\n        return a\n    }\n    return b\n}\n\nfunc max(a, b uint64) uint64 {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nvar start time.Time\n\nfunc main() {\n    start = time.Now()\n    fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n    show(0)\n    cnt := 1\n    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n    for {\n        i := lo\n        for ; i < hi; i++ {\n            n := (i*3+1)*pow3 + reverse3(i)\n            if !isPalindrome2(n) {\n                continue\n            }\n            show(n)\n            cnt++\n            if cnt >= 7 {\n                return\n            }\n        }\n\n        if i == pow3 {\n            pow3 *= 3\n        } else {\n            pow2 *= 4\n        }\n\n        for {\n            for pow2 <= pow3 {\n                pow2 *= 4\n            }\n\n            lo2 := (pow2/pow3 - 1) / 3\n            hi2 := (pow2*2/pow3-1)/3 + 1\n            lo3 := pow3 / 3\n            hi3 := pow3\n\n            if lo2 >= hi3 {\n                pow3 *= 3\n            } else if lo3 >= hi2 {\n                pow2 *= 4\n            } else {\n                lo = max(lo2, lo3)\n                hi = min(hi2, hi3)\n                break\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\ntypedef unsigned long long xint;\n\nint is_palin2(xint n)\n{\n\txint x = 0;\n\tif (!(n&1)) return !n;\n\twhile (x < n) x = x<<1 | (n&1), n >>= 1;\n\treturn n == x || n == x>>1;\n}\n\nxint reverse3(xint n)\n{\n\txint x = 0;\n\twhile (n) x = x*3 + (n%3), n /= 3;\n\treturn x;\n}\n\nvoid print(xint n, xint base)\n{\n\tputchar(' ');\n\t\n\tdo { putchar('0' + (n%base)), n /= base; } while(n);\n\tprintf(\"(%lld)\", base);\n}\n\nvoid show(xint n)\n{\n\tprintf(\"%llu\", n);\n\tprint(n, 2);\n\tprint(n, 3);\n\tputchar('\\n');\n}\n\nxint min(xint a, xint b) { return a < b ? a : b; }\nxint max(xint a, xint b) { return a > b ? a : b; }\n\nint main(void)\n{\n\txint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;\n\tint cnt;\n\n\tshow(0);\n\tcnt = 1;\n\n\tlo = 0;\n\thi = pow2 = pow3 = 1;\n\n\twhile (1) {\n\t\tfor (i = lo; i < hi; i++) {\n\t\t\tn = (i * 3 + 1) * pow3 + reverse3(i);\n\t\t\tif (!is_palin2(n)) continue;\n\t\t\tshow(n);\n\t\t\tif (++cnt >= 7) return 0;\n\t\t}\n\n\t\tif (i == pow3)\n\t\t\tpow3 *= 3;\n\t\telse\n\t\t\tpow2 *= 4;\n\n\t\twhile (1) {\n\t\t\twhile (pow2 <= pow3) pow2 *= 4;\n\n\t\t\tlo2 = (pow2 / pow3 - 1) / 3;\n\t\t\thi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;\n\t\t\tlo3 = pow3 / 3;\n\t\t\thi3 = pow3;\n\n\t\t\tif (lo2 >= hi3)\n\t\t\t\tpow3 *= 3;\n\t\t\telse if (lo3 >= hi2)\n\t\t\t\tpow2 *= 4;\n\t\t\telse {\n\t\t\t\tlo = max(lo2, lo3);\n\t\t\t\thi = min(hi2, hi3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 60580, "name": "Check input device is a terminal", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n"}
{"id": 60581, "name": "Check input device is a terminal", "Go": "package main\n\nimport (\n    \"golang.org/x/crypto/ssh/terminal\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if terminal.IsTerminal(int(os.Stdin.Fd())) {\n        fmt.Println(\"Hello terminal\")\n    } else {\n        fmt.Println(\"Who are you?  You're not a terminal.\")\n    }\n}\n", "C": "#include <unistd.h>\t\n#include <stdio.h>\t\n\nint main(void)\n{\n\tputs(isatty(fileno(stdin))\n\t\t? \"stdin is tty\"\n\t\t: \"stdin is not tty\");\n\treturn 0;\n}\n"}
{"id": 60582, "name": "Window creation_X11", "Go": "package main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"github.com/jezek/xgb\"\n    \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n    \n    X, err := xgb.NewConn()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    points := []xproto.Point{\n        {10, 10},\n        {10, 20},\n        {20, 10},\n        {20, 20}};\n\n    polyline := []xproto.Point{\n        {50, 10},\n        { 5, 20},     \n        {25,-20},\n        {10, 10}};\n\n    segments := []xproto.Segment{\n        {100, 10, 140, 30},\n        {110, 25, 130, 60}};\n\n    rectangles := []xproto.Rectangle{\n        { 10, 50, 40, 20},\n        { 80, 50, 10, 40}};\n\n    arcs := []xproto.Arc{\n        {10, 100, 60, 40, 0, 90 << 6},\n        {90, 100, 55, 40, 0, 270 << 6}};\n\n    setup := xproto.Setup(X)\n    \n    screen := setup.DefaultScreen(X)\n\n    \n    foreground, _ := xproto.NewGcontextId(X)\n    mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n    values := []uint32{screen.BlackPixel, 0}\n    xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n    \n    win, _ := xproto.NewWindowId(X)\n    winDrawable := xproto.Drawable(win)\n\n    \n    mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n    values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n    xproto.CreateWindow(X,                  \n            screen.RootDepth,               \n            win,                            \n            screen.Root,                    \n            0, 0,                           \n            150, 150,                       \n            10,                             \n            xproto.WindowClassInputOutput,  \n            screen.RootVisual,              \n            mask, values)                   \n\n    \n    xproto.MapWindow(X, win)\n\n    for {\n        evt, err := X.WaitForEvent()\n        switch evt.(type) {\n            case xproto.ExposeEvent:\n                \n                xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n                \n                xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n                \n                xproto.PolySegment(X, winDrawable, foreground, segments)\n\n                \n                xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n                \n                xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n            default:\n                \n        }\n\n        if err != nil {\n            log.Fatal(err)\n        }\n    }\n    return\n}\n", "C": "'--- added a flush to exit cleanly   \nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n \n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n \n'---pointer to X Display structure\nDECLARE d TYPE  Display*\n \n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n \n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n \nDECLARE msg TYPE char*\n \n'--- number of screen to place the window on\nDECLARE s TYPE int\n \n \n \n  msg = \"Hello, World!\"\n \n \n   d = DISPLAY(NULL)\n   IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n   END IF\n \n   s = SCREEN(d)\n   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n \n   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n   MAP_EVENT(d, w)\n \n   WHILE  (1) \n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t    BREAK\n\t END IF   \n   WEND\n   FLUSH(d)\n   CLOSE_DISPLAY(d)\n"}
{"id": 60583, "name": "Elementary cellular automaton_Random number generator", "Go": "package main\n\nimport \"fmt\"\n\nconst n = 64\n\nfunc pow2(x uint) uint64 {\n    return uint64(1) << x\n}\n\nfunc evolve(state uint64, rule int) {\n    for p := 0; p < 10; p++ {\n        b := uint64(0)\n        for q := 7; q >= 0; q-- {\n            st := state\n            b |= (st & 1) << uint(q)\n            state = 0\n            for i := uint(0); i < n; i++ {\n                var t1, t2, t3 uint64\n                if i > 0 {\n                    t1 = st >> (i - 1)\n                } else {\n                    t1 = st >> 63\n                }\n                if i == 0 {\n                    t2 = st << 1\n                } else if i == 1 {\n                    t2 = st << 63\n\n                } else {\n                    t2 = st << (n + 1 - i)\n                }\n                t3 = 7 & (t1 | t2)\n                if (uint64(rule) & pow2(uint(t3))) != 0 {\n                    state |= pow2(i)\n                }\n            }\n        }\n        fmt.Printf(\"%d \", b)\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    evolve(1, 30)\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\ntypedef unsigned long long ull;\n#define N (sizeof(ull) * CHAR_BIT)\n#define B(x) (1ULL << (x))\n\nvoid evolve(ull state, int rule)\n{\n\tint i, p, q, b;\n\n\tfor (p = 0; p < 10; p++) {\n\t\tfor (b = 0, q = 8; q--; ) {\n\t\t\tull st = state;\n\t\t\tb |= (st&1) << q;\n\n\t\t\tfor (state = i = 0; i < N; i++)\n\t\t\t\tif (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))\n\t\t\t\t\tstate |= B(i);\n\t\t}\n\t\tprintf(\" %d\", b);\n\t}\n\tputchar('\\n');\n\treturn;\n}\n\nint main(void)\n{\n\tevolve(1, 30);\n\treturn 0;\n}\n"}
{"id": 60584, "name": "Terminal control_Dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n\n    \"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(h, w)\n}\n", "C": "#include <sys/ioctl.h>\t\n#include <err.h>\t\n#include <fcntl.h>\t\n#include <stdio.h>\t\n#include <unistd.h>\t\n\nint\nmain()\n{\n\tstruct winsize ws;\n\tint fd;\n\n\t\n\tfd = open(\"/dev/tty\", O_RDWR);\n\tif (fd < 0)\n\t\terr(1, \"/dev/tty\");\n\n\t \n\tif (ioctl(fd, TIOCGWINSZ, &ws) < 0)\n\t\terr(1, \"/dev/tty\");\n\n\tprintf(\"%d rows by %d columns\\n\", ws.ws_row, ws.ws_col);\n\tprintf(\"(%d by %d pixels)\\n\", ws.ws_xpixel, ws.ws_ypixel);\n\n\tclose(fd);\t\n\treturn 0;\n}\n"}
{"id": 60585, "name": "Finite state machine", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strings\"\n)\n\ntype state int\n\nconst (\n    ready state = iota\n    waiting\n    exit\n    dispense\n    refunding\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc fsm() {\n    fmt.Println(\"Please enter your option when prompted\")\n    fmt.Println(\"(any characters after the first will be ignored)\")\n    state := ready\n    var trans string\n    scanner := bufio.NewScanner(os.Stdin)\n    for {\n        switch state {\n        case ready:\n            for {\n                fmt.Print(\"\\n(D)ispense or (Q)uit : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'd' {\n                    state = waiting\n                    break\n                } else if option == 'q' {\n                    state = exit\n                    break\n                }\n            }\n        case waiting:\n            fmt.Println(\"OK, put your money in the slot\")\n            for {\n                fmt.Print(\"(S)elect product or choose a (R)efund : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 's' {\n                    state = dispense\n                    break\n                } else if option == 'r' {\n                    state = refunding\n                    break\n                }\n            }\n        case dispense:\n            for {\n                fmt.Print(\"(R)emove product : \")\n                scanner.Scan()\n                trans = scanner.Text()\n                check(scanner.Err())\n                if len(trans) == 0 {\n                    continue\n                }\n                option := strings.ToLower(trans)[0]\n                if option == 'r' {\n                    state = ready\n                    break\n                }\n            }\n        case refunding:\n            \n            fmt.Println(\"OK, refunding your money\")\n            state = ready\n        case exit:\n            fmt.Println(\"OK, quitting\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    fsm()\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;\n\n  typedef struct statechange {\n    const int in;\n    const State out;\n  } statechange;\n\n#define MAXINPUTS 3\n  typedef struct FSM {\n    const State state;\n    void (*Action)(void);\n    const statechange table[MAXINPUTS]; \n  } FSM;\n\n  char str[10];\n  void Ready(void)    { fprintf(stderr, \"\\nMachine is READY. (D)eposit or (Q)uit :\"); scanf(\"%s\", str); }\n  void Waiting(void)  { fprintf(stderr, \"(S)elect product or choose to (R)efund :\"); scanf(\"%s\", str); }\n  void Refund(void)   { fprintf(stderr, \"Please collect refund.\\n\"); }\n  void Dispense(void) { fprintf(stderr, \"Dispensing product...\\n\"); }\n  void Collect(void)  { fprintf(stderr, \"Please (C)ollect product. :\"); scanf(\"%s\", str); }\n  void Quit(void)     { fprintf(stderr, \"Thank you, shutting down now.\\n\"); exit(0); }\n\n  const FSM fsm[] = {\n    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},\n    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},\n    { REFUND,   &Refund,   {{ -1, READY}                                     }},\n    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},\n    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},\n    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},\n  };\n\n  int each;\n  State state = READY;\n\n  for (;;) {\n    fsm[state].Action();\n    each = 0;\n    while (!( ((fsm[state].table[each].in == -1)\n               \n               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;\n    state = fsm[state].table[each].out;\n  }\n \n  return 0;\n}\n"}
{"id": 60586, "name": "Vibrating rectangles", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"os\"\n)\n\nvar (\n    black   = color.RGBA{0, 0, 0, 255}\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n    yellow  = color.RGBA{255, 255, 0, 255}\n    white   = color.RGBA{255, 255, 255, 255}\n)\n\nvar palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}\n\nfunc hline(img *image.Paletted, x1, y, x2 int, ci uint8) {\n    for ; x1 <= x2; x1++ {\n        img.SetColorIndex(x1, y, ci)\n    }\n}\n\nfunc vline(img *image.Paletted, x, y1, y2 int, ci uint8) {\n    for ; y1 <= y2; y1++ {\n        img.SetColorIndex(x, y1, ci)\n    }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n    hline(img, x1, y1, x2, ci)\n    hline(img, x1, y2, x2, ci)\n    vline(img, x1, y1, y2, ci)\n    vline(img, x2, y1, y2, ci)\n}\n\nfunc main() {\n    const nframes = 140\n    const delay = 10 \n    width, height := 500, 500\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, width, height)\n    for c := uint8(0); c < 7; c++ {\n        for f := 0; f < 20; f++ {\n            img := image.NewPaletted(rect, palette)\n            setBackgroundColor(img, width, height, 7) \n            for r := 0; r < 20; r++ {\n                ix := c\n                if r < f {\n                    ix = (ix + 1) % 7\n                }\n                x := width * (r + 1) / 50\n                y := height * (r + 1) / 50\n                w := width - x\n                h := height - y\n                drawRectangle(img, x, y, w, h, ix)\n            }\n            anim.Delay = append(anim.Delay, delay)\n            anim.Image = append(anim.Image, img)\n        }\n    }\n    file, err := os.Create(\"vibrating.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }   \n}\n", "C": "\n\n#include<graphics.h>\n\nvoid vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)\n{\n\tint color = 1,i,x = winWidth/2, y = winHeight/2;\n\t\n\twhile(!kbhit()){\n\t\tsetcolor(color++);\n\t\tfor(i=num;i>0;i--){\n\t\t\trectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);\n\t\t\tdelay(msec);\n\t\t}\n\n\t\tif(color>MAXCOLORS){\n\t\t\tcolor = 1;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Vibrating Rectangles...\");\n\t\n\tvibratingRectangles(1000,1000,30,15,20,500);\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 60587, "name": "Last list item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}\n    for len(a) > 1 {\n        sort.Ints(a)\n        fmt.Println(\"Sorted list:\", a)\n        sum := a[0] + a[1]\n        fmt.Printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum)\n        a = append(a, sum)\n        a = a[2:]\n    }\n    fmt.Println(\"Last item is\", a[0], \"\\b.\")\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint compare(const void *a, const void *b) {\n    int aa = *(const int *)a;\n    int bb = *(const int *)b;\n    if (aa < bb) return -1;\n    if (aa > bb) return 1;\n    return 0;\n}\n\nint main() {\n    int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};\n    int isize = sizeof(int);\n    int asize = sizeof(a) / isize;\n    int i, sum;\n    while (asize > 1) {\n        qsort(a, asize, isize, compare);\n        printf(\"Sorted list: \");\n        for (i = 0; i < asize; ++i) printf(\"%d \", a[i]);\n        printf(\"\\n\");\n        sum = a[0] + a[1];\n        printf(\"Two smallest: %d + %d = %d\\n\", a[0], a[1], sum);\n        for (i = 2; i < asize; ++i) a[i-2] = a[i];\n        a[asize - 2] = sum;\n        asize--;\n    }\n    printf(\"Last item is %d.\\n\", a[0]);\n    return 0;\n}\n"}
{"id": 60588, "name": "Audio frequency generator", "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    freq := 0\n    for freq < 40 || freq > 10000 {\n        fmt.Print(\"Enter frequency in Hz (40 to 10000) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        freq, _ = strconv.Atoi(input)\n    }\n    freqS := strconv.Itoa(freq)\n\n    vol := 0\n    for vol < 1 || vol > 50 {\n        fmt.Print(\"Enter volume in dB (1 to 50) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        vol, _ = strconv.Atoi(input)\n    }\n    volS := strconv.Itoa(vol)\n\n    dur := 0.0\n    for dur < 2 || dur > 10 {\n        fmt.Print(\"Enter duration in seconds (2 to 10) : \")\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    kind := 0\n    for kind < 1 || kind > 3 {\n        fmt.Print(\"Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        kind, _ = strconv.Atoi(input)\n    }\n    kindS := \"sine\"\n    if kind == 2 {\n        kindS = \"square\"\n    } else if kind == 3 {\n        kindS = \"sawtooth\"\n    }\n\n    args := []string{\"-n\", \"synth\", durS, kindS, freqS, \"vol\", volS, \"dB\"}\n    cmd := exec.Command(\"play\", args...)\n    err := cmd.Run()\n    check(err)\n}\n", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_frequency_generator.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60589, "name": "Audio frequency generator", "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    freq := 0\n    for freq < 40 || freq > 10000 {\n        fmt.Print(\"Enter frequency in Hz (40 to 10000) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        freq, _ = strconv.Atoi(input)\n    }\n    freqS := strconv.Itoa(freq)\n\n    vol := 0\n    for vol < 1 || vol > 50 {\n        fmt.Print(\"Enter volume in dB (1 to 50) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        vol, _ = strconv.Atoi(input)\n    }\n    volS := strconv.Itoa(vol)\n\n    dur := 0.0\n    for dur < 2 || dur > 10 {\n        fmt.Print(\"Enter duration in seconds (2 to 10) : \")\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    kind := 0\n    for kind < 1 || kind > 3 {\n        fmt.Print(\"Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        kind, _ = strconv.Atoi(input)\n    }\n    kindS := \"sine\"\n    if kind == 2 {\n        kindS = \"square\"\n    } else if kind == 3 {\n        kindS = \"sawtooth\"\n    }\n\n    args := []string{\"-n\", \"synth\", durS, kindS, freqS, \"vol\", volS, \"dB\"}\n    cmd := exec.Command(\"play\", args...)\n    err := cmd.Run()\n    check(err)\n}\n", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_frequency_generator.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60590, "name": "Piprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(79) \n    ix := 0\n    n := 1\n    count := 0\n    var pi []int\n    for {\n        if primes[ix] <= n {\n            count++\n            if count == 22 {\n                break\n            }\n            ix++\n        }\n        n++\n        pi = append(pi, count)\n    }\n    fmt.Println(\"pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:\")\n    for i, n := range pi {\n        fmt.Printf(\"%2d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nHighest n for this range = %d.\\n\", len(pi))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( int n ) {\n\tint i;\n        if (n<2) return 0;\n\tfor(i=2; i*i<=n; i++) {\n\t\tif (n % i == 0) {return 0;}\n\t}\n\treturn 1;\n}\n\nint main(void)  {\n\tint n = 0, p = 1;\n\twhile (n<22) {\n\t\tprintf( \"%d   \", n );\n\t\tp++;\n\t\tif (isprime(p)) n+=1;\n        }\n\treturn 0;\n}\n"}
{"id": 60591, "name": "Piprimes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(79) \n    ix := 0\n    n := 1\n    count := 0\n    var pi []int\n    for {\n        if primes[ix] <= n {\n            count++\n            if count == 22 {\n                break\n            }\n            ix++\n        }\n        n++\n        pi = append(pi, count)\n    }\n    fmt.Println(\"pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:\")\n    for i, n := range pi {\n        fmt.Printf(\"%2d \", n)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nHighest n for this range = %d.\\n\", len(pi))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( int n ) {\n\tint i;\n        if (n<2) return 0;\n\tfor(i=2; i*i<=n; i++) {\n\t\tif (n % i == 0) {return 0;}\n\t}\n\treturn 1;\n}\n\nint main(void)  {\n\tint n = 0, p = 1;\n\twhile (n<22) {\n\t\tprintf( \"%d   \", n );\n\t\tp++;\n\t\tif (isprime(p)) n+=1;\n        }\n\treturn 0;\n}\n"}
{"id": 60592, "name": "Minimum numbers of three lists", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 98, 53}\n    numbers := [5]int{}\n    for n := 0; n < 5; n++ {\n        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])\n    }\n    fmt.Println(numbers)\n}\n", "C": "#include <stdio.h>\n\nint min(int a, int b) {\n    if (a < b) return a;\n    return b;\n}\n\nint main() {\n    int n;\n    int numbers1[5] = {5, 45, 23, 21, 67};\n    int numbers2[5] = {43, 22, 78, 46, 38};\n    int numbers3[5] = {9, 98, 12, 98, 53};\n    int numbers[5]  = {};\n    for (n = 0; n < 5; ++n) {\n        numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);\n        printf(\"%d \", numbers[n]);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60593, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 60594, "name": "Cipolla's algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc c(n, p int) (R1, R2 int, ok bool) {\n    \n    powModP := func(a, e int) int {\n        s := 1\n        for ; e > 0; e-- {\n            s = s * a % p\n        }\n        return s\n    }\n    \n    ls := func(a int) int {\n        return powModP(a, (p-1)/2)\n    }\n    \n    if ls(n) != 1 {\n        return\n    }\n    \n    var a, ω2 int\n    for a = 0; ; a++ {\n        \n        ω2 = (a*a + p - n) % p\n        if ls(ω2) == p-1 {\n            break\n        }\n    }\n    \n    type point struct{ x, y int }\n    mul := func(a, b point) point {\n        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}\n    }\n    \n    r := point{1, 0}\n    s := point{a, 1}\n    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {\n        if n&1 == 1 {\n            r = mul(r, s)\n        }\n        s = mul(s, s)\n    }\n    \n    if r.y != 0 {\n        return\n    }\n    \n    if r.x*r.x%p != n {\n        return\n    }\n    \n    return r.x, p - r.x, true\n}\n\nfunc main() {\n    fmt.Println(c(10, 13))\n    fmt.Println(c(56, 101))\n    fmt.Println(c(8218, 10007))\n    fmt.Println(c(8219, 10007))\n    fmt.Println(c(331575, 1000003))\n}\n", "C": "#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct fp2 {\n    int64_t x, y;\n};\n\nuint64_t randULong(uint64_t min, uint64_t max) {\n    uint64_t t = (uint64_t)rand();\n    return min + t % (max - min);\n}\n\n\nuint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {\n    uint64_t x = 0, y = a % modulus;\n\n    while (b > 0) {\n        if ((b & 1) == 1) {\n            x = (x + y) % modulus;\n        }\n        y = (y << 1) % modulus;\n        b = b >> 1;\n    }\n\n    return x;\n}\n\n\nuint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {\n    uint64_t x = 1;\n\n    while (power > 0) {\n        if ((power & 1) == 1) {\n            x = mul_mod(x, b, modulus);\n        }\n        b = mul_mod(b, b, modulus);\n        power = power >> 1;\n    }\n\n    return x;\n}\n\n\nbool isPrime(uint64_t n, int64_t k) {\n    uint64_t a, x, n_one = n - 1, d = n_one;\n    uint32_t s = 0;\n    uint32_t r;\n\n    if (n < 2) {\n        return false;\n    }\n\n    \n    if (n > 9223372036854775808ull) {\n        printf(\"The number is too big, program will end.\\n\");\n        exit(1);\n    }\n\n    if ((n % 2) == 0) {\n        return n == 2;\n    }\n\n    while ((d & 1) == 0) {\n        d = d >> 1;\n        s = s + 1;\n    }\n\n    while (k > 0) {\n        k = k - 1;\n        a = randULong(2, n);\n        x = pow_mod(a, d, n);\n        if (x == 1 || x == n_one) {\n            continue;\n        }\n        for (r = 1; r < s; r++) {\n            x = pow_mod(x, 2, n);\n            if (x == 1) return false;\n            if (x == n_one) goto continue_while;\n        }\n        if (x != n_one) {\n            return false;\n        }\n\n    continue_while: {}\n    }\n\n    return true;\n}\n\nint64_t legendre_symbol(int64_t a, int64_t p) {\n    int64_t x = pow_mod(a, (p - 1) / 2, p);\n    if ((p - 1) == x) {\n        return x - p;\n    } else {\n        return x;\n    }\n}\n\nstruct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {\n    struct fp2 answer;\n    uint64_t tmp1, tmp2;\n\n    tmp1 = mul_mod(a.x, b.x, p);\n    tmp2 = mul_mod(a.y, b.y, p);\n    tmp2 = mul_mod(tmp2, w2, p);\n    answer.x = (tmp1 + tmp2) % p;\n    tmp1 = mul_mod(a.x, b.y, p);\n    tmp2 = mul_mod(a.y, b.x, p);\n    answer.y = (tmp1 + tmp2) % p;\n\n    return answer;\n}\n\nstruct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {\n    return fp2mul(a, a, p, w2);\n}\n\nstruct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {\n    struct fp2 ret;\n\n    if (n == 0) {\n        ret.x = 1;\n        ret.y = 0;\n        return ret;\n    }\n    if (n == 1) {\n        return a;\n    }\n    if ((n & 1) == 0) {\n        return fp2square(fp2pow(a, n / 2, p, w2), p, w2);\n    } else {\n        return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);\n    }\n}\n\nvoid test(int64_t n, int64_t p) {\n    int64_t a, w2;\n    int64_t x1, x2;\n    struct fp2 answer;\n\n    printf(\"Find solution for n = %lld and p = %lld\\n\", n, p);\n    if (p == 2 || !isPrime(p, 15)) {\n        printf(\"No solution, p is not an odd prime.\\n\\n\");\n        return;\n    }\n\n    \n    if (legendre_symbol(n, p) != 1) {\n        printf(\" %lld is not a square in F%lld\\n\\n\", n, p);\n        return;\n    }\n\n    while (true) {\n        do {\n            a = randULong(2, p);\n            w2 = a * a - n;\n        } while (legendre_symbol(w2, p) != -1);\n\n        answer.x = a;\n        answer.y = 1;\n        answer = fp2pow(answer, (p + 1) / 2, p, w2);\n        if (answer.y != 0) {\n            continue;\n        }\n\n        x1 = answer.x;\n        x2 = p - x1;\n        if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {\n            printf(\"Solution found: x1 = %lld, x2 = %lld\\n\\n\", x1, x2);\n            return;\n        }\n    }\n}\n\nint main() {\n    srand((size_t)time(0));\n\n    test(10, 13);\n    test(56, 101);\n    test(8218, 10007);\n    test(8219, 10007);\n    test(331575, 1000003);\n    test(665165880, 1000000007);\n    \n\n    return 0;\n}\n"}
{"id": 60595, "name": "Pseudo-random numbers_PCG32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n    pcg.state = 0\n    pcg.inc = (seedSequence << 1) | 1\n    pcg.nextInt()\n    pcg.state = pcg.state + seedState\n    pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n    old := pcg.state\n    pcg.state = old*CONST + pcg.inc\n    pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n    rot := uint32(old >> 59)\n    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n    return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := Pcg32New()\n    randomGen.seed(42, 54)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321, 1)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nconst uint64_t N = 6364136223846793005;\n\nstatic uint64_t state = 0x853c49e6748fea9b;\nstatic uint64_t inc = 0xda3e39cb94b95bdb;\n\nuint32_t pcg32_int() {\n    uint64_t old = state;\n    state = old * N + inc;\n    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n    uint32_t rot = old >> 59;\n    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n}\n\ndouble pcg32_float() {\n    return ((double)pcg32_int()) / (1LL << 32);\n}\n\nvoid pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {\n    state = 0;\n    inc = (seed_sequence << 1) | 1;\n    pcg32_int();\n    state = state + seed_state;\n    pcg32_int();\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    pcg32_seed(42, 54);\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"%u\\n\", pcg32_int());\n    printf(\"\\n\");\n\n    pcg32_seed(987654321, 1);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(pcg32_float() * 5.0);\n        counts[j]++;\n    }\n\n    printf(\"The counts for 100,000 repetitions are:\\n\");\n    for (i = 0; i < 5; i++) {\n        printf(\"  %d : %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 60596, "name": "Deconvolution_1D", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    h := []float64{-8, -9, -3, -1, -6, 7}\n    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}\n    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,\n        96, 31, 55, 36, 29, -43, -7}\n    fmt.Println(h)\n    fmt.Println(deconv(g, f))\n    fmt.Println(f)\n    fmt.Println(deconv(g, h))\n}\n\nfunc deconv(g, f []float64) []float64 {\n    h := make([]float64, len(g)-len(f)+1)\n    for n := range h {\n        h[n] = g[n]\n        var lower int\n        if n >= len(f) {\n            lower = n - len(f) + 1\n        }\n        for i := lower; i < n; i++ {\n            h[n] -= h[i] * f[n-i]\n        }\n        h[n] /= f[0]\n    }\n    return h\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n \ndouble PI;\ntypedef double complex cplx;\n \nvoid _fft(cplx buf[], cplx out[], int n, int step)\n{\n\tif (step < n) {\n\t\t_fft(out, buf, n, step * 2);\n\t\t_fft(out + step, buf + step, n, step * 2);\n \n\t\tfor (int i = 0; i < n; i += 2 * step) {\n\t\t\tcplx t = cexp(-I * PI * i / n) * out[i + step];\n\t\t\tbuf[i / 2]     = out[i] + t;\n\t\t\tbuf[(i + n)/2] = out[i] - t;\n\t\t}\n\t}\n}\n \nvoid fft(cplx buf[], int n)\n{\n\tcplx out[n];\n\tfor (int i = 0; i < n; i++) out[i] = buf[i];\n\t_fft(buf, out, n, 1);\n}\n\n\ncplx *pad_two(double g[], int len, int *ns)\n{\n\tint n = 1;\n\tif (*ns) n = *ns;\n\telse while (n < len) n *= 2;\n\n\tcplx *buf = calloc(sizeof(cplx), n);\n\tfor (int i = 0; i < len; i++) buf[i] = g[i];\n\t*ns = n;\n\treturn buf;\n}\n\nvoid deconv(double g[], int lg, double f[], int lf, double out[]) {\n\tint ns = 0;\n\tcplx *g2 = pad_two(g, lg, &ns);\n\tcplx *f2 = pad_two(f, lf, &ns);\n\n\tfft(g2, ns);\n\tfft(f2, ns);\n\n\tcplx h[ns];\n\tfor (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];\n\tfft(h, ns);\n\n\tfor (int i = 0; i >= lf - lg; i--)\n\t\tout[-i] = h[(i + ns) % ns]/32;\n\tfree(g2);\n\tfree(f2);\n}\n\nint main()\n{\n\tPI = atan2(1,1) * 4;\n\tdouble g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};\n\tdouble f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };\n\tdouble h[] = { -8,-9,-3,-1,-6,7 };\n\n\tint lg = sizeof(g)/sizeof(double);\n\tint lf = sizeof(f)/sizeof(double);\n\tint lh = sizeof(h)/sizeof(double);\n\n\tdouble h2[lh];\n\tdouble f2[lf];\n\n\tprintf(\"f[] data is : \");\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, h): \");\n\tdeconv(g, lg, h, lh, f2);\n\tfor (int i = 0; i < lf; i++) printf(\" %g\", f2[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"h[] data is : \");\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h[i]);\n\tprintf(\"\\n\");\n\n\tprintf(\"deconv(g, f): \");\n\tdeconv(g, lg, f, lf, h2);\n\tfor (int i = 0; i < lh; i++) printf(\" %g\", h2[i]);\n\tprintf(\"\\n\");\n}\n"}
{"id": 60597, "name": "Bitmap_PPM conversion through a pipe", "Go": "package main\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    b := raster.NewBitmap(400, 300)\n    \n    b.FillRgb(0xc08040)\n    for i := 0; i < 2000; i++ {\n        b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)\n    }\n    for x := 0; x < 400; x++ {\n        for y := 240; y < 245; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for y := 260; y < 265; y++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n    for y := 0; y < 300; y++ {\n        for x := 80; x < 85; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n        for x := 95; x < 100; x++ {\n            b.SetPxRgb(x, y, 0x804020)\n        }\n    }\n\n    \n    c := exec.Command(\"cjpeg\", \"-outfile\", \"pipeout.jpg\")\n    pipe, err := c.StdinPipe()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = c.Start()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = b.WritePpmTo(pipe)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = pipe.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "C": "\nvoid print_jpg(image img, int qual);\n"}
{"id": 60598, "name": "Bitcoin_public point to address", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n"}
{"id": 60599, "name": "Bitcoin_public point to address", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"encoding/hex\"\n    \"errors\"\n    \"fmt\"\n\n    \"golang.org/x/crypto/ripemd160\"\n)\n\n\ntype Point struct {\n    x, y [32]byte\n}\n\n\nfunc (p *Point) SetHex(x, y string) error {\n    if len(x) != 64 || len(y) != 64 {\n        return errors.New(\"invalid hex string length\")\n    }\n    if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {\n        return err\n    }\n    _, err := hex.Decode(p.y[:], []byte(y))\n    return err\n}\n\n\ntype A25 [25]byte\n\n\nfunc (a *A25) doubleSHA256() []byte {\n    h := sha256.New()\n    h.Write(a[:21])\n    d := h.Sum([]byte{})\n    h = sha256.New()\n    h.Write(d)\n    return h.Sum(d[:0])\n}\n\n\n\nfunc (a *A25) UpdateChecksum() {\n    copy(a[21:], a.doubleSHA256())\n}\n\n\n\nfunc (a *A25) SetPoint(p *Point) {\n    c := [65]byte{4}\n    copy(c[1:], p.x[:])\n    copy(c[33:], p.y[:])\n    h := sha256.New()\n    h.Write(c[:])\n    s := h.Sum([]byte{})\n    h = ripemd160.New()\n    h.Write(s)\n    h.Sum(a[1:1])\n    a.UpdateChecksum()\n}\n\n\nvar tmpl = []byte(\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\")\n\n\n\nfunc (a *A25) A58() []byte {\n    var out [34]byte\n    for n := 33; n >= 0; n-- {\n        c := 0\n        for i := 0; i < 25; i++ {\n            c = c*256 + int(a[i])\n            a[i] = byte(c / 58)\n            c %= 58\n        }\n        out[n] = tmpl[c]\n    }\n    i := 1\n    for i < 34 && out[i] == '1' {\n        i++\n    }\n    return out[i-1:]\n}\n\nfunc main() {\n    \n    var p Point\n    err := p.SetHex(\n        \"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n        \"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    var a A25\n    a.SetPoint(&p)\n    \n    fmt.Println(string(a.A58()))\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n#define COIN_VER 0\nconst char *coin_err;\n\ntypedef unsigned char byte;\n\nint is_hex(const char *s) {\n\tint i;\n\tfor (i = 0; i < 64; i++)\n\t\tif (!isxdigit(s[i])) return 0;\n\treturn 1;\n}\n\nvoid str_to_byte(const char *src, byte *dst, int n) {\n\twhile (n--) sscanf(src + n * 2, \"%2hhx\", dst + n);\n}\n\nchar* base58(byte *s, char *out) {\n\tstatic const char *tmpl = \"123456789\"\n\t\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\"\n\t\t\"abcdefghijkmnopqrstuvwxyz\";\n\tstatic char buf[40];\n\n\tint c, i, n;\n\tif (!out) out = buf;\n\n\tout[n = 34] = 0;\n\twhile (n--) {\n\t\tfor (c = i = 0; i < 25; i++) {\n\t\t\tc = c * 256 + s[i];\n\t\t\ts[i] = c / 58;\n\t\t\tc %= 58;\n\t\t}\n\t\tout[n] = tmpl[c];\n\t}\n\n\tfor (n = 0; out[n] == '1'; n++);\n\tmemmove(out, out + n, 34 - n);\n\n\treturn out;\n}\n\nchar *coin_encode(const char *x, const char *y, char *out) {\n\tbyte s[65];\n\tbyte rmd[5 + RIPEMD160_DIGEST_LENGTH];\n\n\tif (!is_hex(x) || !(is_hex(y))) {\n\t\tcoin_err = \"bad public point string\";\n\t\treturn 0;\n\t}\n\n\ts[0] = 4;\n\tstr_to_byte(x, s + 1, 32);\n\tstr_to_byte(y, s + 33, 32);\n\n\trmd[0] = COIN_VER;\n\tRIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);\n\n\tmemcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);\n\n\treturn base58(rmd, out);\n}\n\nint main(void) {\n\tputs(coin_encode(\n\t\t\"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\",\n\t\t\"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\",\n\t\t0));\n\treturn 0;\n}\n"}
{"id": 60600, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 60601, "name": "NYSIIS", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype pair struct{ first, second string }\n\nvar (\n    fStrs = []pair{{\"MAC\", \"MCC\"}, {\"KN\", \"N\"}, {\"K\", \"C\"}, {\"PH\", \"FF\"},\n        {\"PF\", \"FF\"}, {\"SCH\", \"SSS\"}}\n    lStrs = []pair{{\"EE\", \"Y\"}, {\"IE\", \"Y\"}, {\"DT\", \"D\"}, {\"RT\", \"D\"},\n        {\"RD\", \"D\"}, {\"NT\", \"D\"}, {\"ND\", \"D\"}}\n    mStrs = []pair{{\"EV\", \"AF\"}, {\"KN\", \"N\"}, {\"SCH\", \"SSS\"}, {\"PH\", \"FF\"}}\n    eStrs = []string{\"JR\", \"JNR\", \"SR\", \"SNR\"}\n)\n\nfunc isVowel(b byte) bool {\n    return strings.ContainsRune(\"AEIOU\", rune(b))\n}\n\nfunc isRoman(s string) bool {\n    if s == \"\" {\n        return false\n    }\n    for _, r := range s {\n        if !strings.ContainsRune(\"IVX\", r) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nysiis(word string) string {\n    if word == \"\" {\n        return \"\"\n    }\n    w := strings.ToUpper(word)\n    ww := strings.FieldsFunc(w, func(r rune) bool {\n        return r == ' ' || r == ','\n    })\n    if len(ww) > 1 {\n        last := ww[len(ww)-1]\n        if isRoman(last) {\n            w = w[:len(w)-len(last)]\n        }\n    }\n    for _, c := range \" ,'-\" {\n        w = strings.Replace(w, string(c), \"\", -1)\n    }\n    for _, eStr := range eStrs {\n        if strings.HasSuffix(w, eStr) {\n            w = w[:len(w)-len(eStr)]\n        }\n    }\n    for _, fStr := range fStrs {\n        if strings.HasPrefix(w, fStr.first) {\n            w = strings.Replace(w, fStr.first, fStr.second, 1)\n        }\n    }\n    for _, lStr := range lStrs {\n        if strings.HasSuffix(w, lStr.first) {\n            w = w[:len(w)-2] + lStr.second\n        }\n    }\n    initial := w[0]\n    var key strings.Builder\n    key.WriteByte(initial)\n    w = w[1:]\n    for _, mStr := range mStrs {\n        w = strings.Replace(w, mStr.first, mStr.second, -1)\n    }\n    sb := []byte{initial}\n    sb = append(sb, w...)\n    le := len(sb)\n    for i := 1; i < le; i++ {\n        switch sb[i] {\n        case 'E', 'I', 'O', 'U':\n            sb[i] = 'A'\n        case 'Q':\n            sb[i] = 'G'\n        case 'Z':\n            sb[i] = 'S'\n        case 'M':\n            sb[i] = 'N'\n        case 'K':\n            sb[i] = 'C'\n        case 'H':\n            if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {\n                sb[i] = sb[i-1]\n            }\n        case 'W':\n            if isVowel(sb[i-1]) {\n                sb[i] = 'A'\n            }\n        }\n    }\n    if sb[le-1] == 'S' {\n        sb = sb[:le-1]\n        le--\n    }\n    if le > 1 && string(sb[le-2:]) == \"AY\" {\n        sb = sb[:le-2]\n        sb = append(sb, 'Y')\n        le--\n    }\n    if le > 0 && sb[le-1] == 'A' {\n        sb = sb[:le-1]\n        le--\n    }\n    prev := initial\n    for j := 1; j < le; j++ {\n        c := sb[j]\n        if prev != c {\n            key.WriteByte(c)\n            prev = c\n        }\n    }\n    return key.String()\n}\n\nfunc main() {\n    names := []string{\n        \"Bishop\", \"Carlson\", \"Carr\", \"Chapman\",\n        \"Franklin\", \"Greene\", \"Harper\", \"Jacobs\", \"Larson\", \"Lawrence\",\n        \"Lawson\", \"Louis, XVI\", \"Lynch\", \"Mackenzie\", \"Matthews\", \"May jnr\",\n        \"McCormack\", \"McDaniel\", \"McDonald\", \"Mclaughlin\", \"Morrison\",\n        \"O'Banion\", \"O'Brien\", \"Richards\", \"Silva\", \"Watkins\", \"Xi\",\n        \"Wheeler\", \"Willis\", \"brown, sr\", \"browne, III\", \"browne, IV\",\n        \"knight\", \"mitchell\", \"o'daniel\", \"bevan\", \"evans\", \"D'Souza\",\n        \"Hoyle-Johnson\", \"Vaughan Williams\", \"de Sousa\", \"de la Mare II\",\n    }\n    for _, name := range names {\n        name2 := nysiis(name)\n        if len(name2) > 6 {\n            name2 = fmt.Sprintf(\"%s(%s)\", name2[:6], name2[6:])\n        }\n        fmt.Printf(\"%-16s : %s\\n\", name, name2)\n    }\n}\n", "C": "#include <iostream>   \n#include <iomanip>    \n#include <string>\n\nstd::string NYSIIS( std::string const& str )\n{\n    std::string s, out;\n    s.reserve( str.length() );\n    for( auto const c : str )\n    {\n        if( c >= 'a' && c <= 'z' )\n            s += c - ('a' - 'A');\n        else if( c >= 'A' && c <= 'Z' )\n            s += c;\n    }\n\n    auto replace = []( char const * const from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( from );\n        if( strncmp( from, dst, n ) == 0 )\n        {\n            strncpy( dst, to, n );\n            return true;\n        }\n        return false;\n    };\n\n    auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool\n    {\n        auto const n = strlen( *from );\n        for( ; *from; ++from )\n            if( strncmp( *from, dst, n ) == 0 )\n            {\n                memcpy( dst, to, n );\n                return true;\n            }\n        return false;\n    };\n\n    auto isVowel = []( char const c ) -> bool\n    {\n        return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';\n    };\n\n    size_t n = s.length();\n    replace( \"MAC\", \"MCC\", &s[0] );\n    replace( \"KN\", \"NN\", &s[0] );\n    replace( \"K\", \"C\", &s[0] );\n    char const* const prefix[] = { \"PH\", \"PF\", 0 };\n    multiReplace( prefix, \"FF\", &s[0] );\n    replace( \"SCH\", \"SSS\", &s[0] );\n\n    char const* const suffix1[] = { \"EE\", \"IE\", 0 };\n    char const* const suffix2[] = { \"DT\", \"RT\", \"RD\", \"NT\", \"ND\", 0 };\n    if( multiReplace( suffix1, \"Y\", &s[n - 2] ) || multiReplace( suffix2, \"D\", &s[n - 2] ))\n    {\n        s.pop_back();\n        --n;\n    }\n\n    out += s[0];\n\n    char* vowels[] = { \"A\", \"E\", \"I\", \"O\", \"U\", 0 };\n    for( unsigned i = 1; i < n; ++i )\n    {\n        char* const c = &s[i];\n        if( !replace( \"EV\", \"AV\", c ) )\n            multiReplace( vowels, \"A\", c );\n        replace( \"Q\", \"G\", c );\n        replace( \"Z\", \"S\", c );\n        replace( \"M\", \"N\", c );\n        if( !replace( \"KN\", \"NN\", c ))\n            replace( \"K\", \"C\", c );\n        replace( \"SCH\", \"SSS\", c );\n        replace( \"PH\", \"FF\", c );\n        if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))\n            *c = s[i - 1];\n        if( *c == 'W' && isVowel( s[i - 1] ))\n            *c = 'A';\n        if( out.back() != *c )\n            out += *c;\n    }\n\n    if( out.back() == 'S' || out.back() == 'A' )\n        out.pop_back();\n    n = out.length() - 2;\n    if( out[n] == 'A' && out[n + 1] == 'Y' )\n        out = out.substr( 0, n ) + \"Y\";\n\n    return out;\n}\n\nint main()\n{\n    static char const * const names[][2] = {\n    { \"Bishop\", \"BASAP\" },\n    { \"Carlson\", \"CARLSAN\" },\n    { \"Carr\", \"CAR\" },\n    { \"Chapman\", \"CAPNAN\" },\n    { \"Franklin\", \"FRANCLAN\" },\n    { \"Greene\", \"GRAN\" },\n    { \"Harper\", \"HARPAR\" },\n    { \"Jacobs\", \"JACAB\" },\n    { \"Larson\", \"LARSAN\" },\n    { \"Lawrence\", \"LARANC\" },\n    { \"Lawson\", \"LASAN\" },\n    { \"Louis, XVI\", \"LASXV\" },\n    { \"Lynch\", \"LYNC\" },\n    { \"Mackenzie\", \"MCANSY\" },\n    { \"Matthews\", \"MATA\" },\n    { \"McCormack\", \"MCARNAC\" },\n    { \"McDaniel\", \"MCDANAL\" },\n    { \"McDonald\", \"MCDANALD\" },\n    { \"Mclaughlin\", \"MCLAGLAN\" },\n    { \"Morrison\", \"MARASAN\" },\n    { \"O'Banion\", \"OBANAN\" },\n    { \"O'Brien\", \"OBRAN\" },\n    { \"Richards\", \"RACARD\" },\n    { \"Silva\", \"SALV\" },\n    { \"Watkins\", \"WATCAN\" },\n    { \"Wheeler\", \"WALAR\" },\n    { \"Willis\", \"WALA\" },\n    { \"brown, sr\", \"BRANSR\" },\n    { \"browne, III\", \"BRAN\" },\n    { \"browne, IV\", \"BRANAV\" },\n    { \"knight\", \"NAGT\" },\n    { \"mitchell\", \"MATCAL\" },\n    { \"o'daniel\", \"ODANAL\" } };\n\n    for( auto const& name : names )\n    {\n        auto const code = NYSIIS( name[0] );\n        std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;\n        if( code == std::string( name[1] ))\n            std::cout << \" ok\";\n        else\n            std::cout << \" ERROR: \" << name[1] << \" expected\";\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n"}
{"id": 60602, "name": "OpenGL_Utah teapot", "Go": "package main\n\n\nimport \"C\"\nimport \"unsafe\"\n\nvar rot = 0.0\nvar matCol = [4]C.float{1, 0, 0, 0}\n\n\nfunc display() {\n    C.glClear(C.GL_COLOR_BUFFER_BIT | C.GL_DEPTH_BUFFER_BIT)\n    C.glPushMatrix()\n    C.glRotatef(30, 1, 1, 0)\n    C.glRotatef(C.float(rot), 0, 1, 1)\n    C.glMaterialfv(C.GL_FRONT, C.GL_DIFFUSE, &matCol[0])\n    C.glutWireTeapot(0.5)\n    C.glPopMatrix()\n    C.glFlush()\n}\n\n\nfunc onIdle() {\n    rot += 0.01\n    C.glutPostRedisplay()\n}\n\nfunc initialize() {\n    white := [4]C.float{1, 1, 1, 0}\n    shini := [1]C.float{70}\n    C.glClearColor(0.5, 0.5, 0.5, 0)\n    C.glShadeModel(C.GL_SMOOTH)\n    C.glLightfv(C.GL_LIGHT0, C.GL_AMBIENT, &white[0])\n    C.glLightfv(C.GL_LIGHT0, C.GL_DIFFUSE, &white[0])\n    C.glMaterialfv(C.GL_FRONT, C.GL_SHININESS, &shini[0])\n    C.glEnable(C.GL_LIGHTING)\n    C.glEnable(C.GL_LIGHT0)\n    C.glEnable(C.GL_DEPTH_TEST)\n}\n\nfunc main() {\n    argc := C.int(0)\n    C.glutInit(&argc, nil)\n    C.glutInitDisplayMode(C.GLUT_SINGLE | C.GLUT_RGB | C.GLUT_DEPTH)\n    C.glutInitWindowSize(900, 700)\n    tl := \"The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.\"\n    tlc := C.CString(tl)\n    C.glutCreateWindow(tlc)\n    initialize()\n    C.glutDisplayFunc(C.displayFunc())\n    C.glutIdleFunc(C.idleFunc())\n    C.glutMainLoop()\n    C.free(unsafe.Pointer(tlc))\n}\n", "C": "#include<gl/freeglut.h>\n\ndouble rot = 0;\nfloat matCol[] = {1,0,0,0};\n\nvoid display(){\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\tglPushMatrix();\n\tglRotatef(30,1,1,0);\n\tglRotatef(rot,0,1,1);\n\tglMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);\n\tglutWireTeapot(0.5);\n\tglPopMatrix();\n\tglFlush();\n}\n\n\nvoid onIdle(){\n\trot += 0.01;\n\tglutPostRedisplay();\n}\n\nvoid init(){\n\tfloat pos[] = {1,1,1,0};\n\tfloat white[] = {1,1,1,0};\n\tfloat shini[] = {70};\n\t\n\tglClearColor(.5,.5,.5,0);\n\tglShadeModel(GL_SMOOTH);\n\tglLightfv(GL_LIGHT0,GL_AMBIENT,white);\n\tglLightfv(GL_LIGHT0,GL_DIFFUSE,white);\n\tglMaterialfv(GL_FRONT,GL_SHININESS,shini);\n\tglEnable(GL_LIGHTING);\n\tglEnable(GL_LIGHT0);\n\tglEnable(GL_DEPTH_TEST);\n}\n\nint main(int argC, char* argV[])\n{\n\tglutInit(&argC,argV);\n\tglutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);\n\tglutInitWindowSize(900,700);\n\tglutCreateWindow(\"The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.\");\n\tinit();\n\tglutDisplayFunc(display);\n\tglutIdleFunc(onIdle);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 60603, "name": "Disarium numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n"}
{"id": 60604, "name": "Disarium numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst DMAX = 20  \nconst LIMIT = 20 \n\nfunc main() {\n    \n    EXP := make([][]uint64, 1+DMAX)\n    POW := make([][]uint64, 1+DMAX)\n\n    EXP[0] = make([]uint64, 11)\n    EXP[1] = make([]uint64, 11)\n    POW[0] = make([]uint64, 11)\n    POW[1] = make([]uint64, 11)\n    for i := uint64(1); i <= 10; i++ {\n        EXP[1][i] = i\n    }\n    for i := uint64(1); i <= 9; i++ {\n        POW[1][i] = i\n    }\n    POW[1][10] = 9\n\n    for i := 2; i <= DMAX; i++ {\n        EXP[i] = make([]uint64, 11)\n        POW[i] = make([]uint64, 11)\n    }\n    for i := 1; i < DMAX; i++ {\n        for j := 0; j <= 9; j++ {\n            EXP[i+1][j] = EXP[i][j] * 10\n            POW[i+1][j] = POW[i][j] * uint64(j)\n        }\n        EXP[i+1][10] = EXP[i][10] * 10\n        POW[i+1][10] = POW[i][10] + POW[i+1][9]\n    }\n\n    \n    DIGITS := make([]int, 1+DMAX) \n    Exp := make([]uint64, 1+DMAX) \n    Pow := make([]uint64, 1+DMAX) \n\n    var exp, pow, min, max uint64\n    start := 1\n    final := DMAX\n    count := 0\n    for digit := start; digit <= final; digit++ {\n        fmt.Println(\"# of digits:\", digit)\n        level := 1\n        DIGITS[0] = 0\n        for {\n            \n            \n            for 0 < level && level < digit {\n                \n                if DIGITS[level] > 9 {\n                    DIGITS[level] = 0\n                    level--\n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n                \n                pow = Pow[level] + POW[digit-level][10]\n\n                if pow < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                max = pow % EXP[level][10]\n                pow -= max\n                if max < Exp[level] {\n                    pow -= EXP[level][10]\n                }\n                max = pow + Exp[level]\n\n                if max < EXP[digit][1] { \n                    DIGITS[level]++\n                    continue\n                }\n\n                \n                exp = Exp[level] + EXP[digit][1]\n                pow = Pow[level] + 1\n\n                if exp > max || max < pow { \n                    DIGITS[level]++\n                    continue\n                }\n\n                if pow > exp {\n                    min = pow % EXP[level][10]\n                    pow -= min\n                    if min > Exp[level] {\n                        pow += EXP[level][10]\n                    }\n                    min = pow + Exp[level]\n                } else {\n                    min = exp\n                }\n\n                \n                if max < min {\n                    DIGITS[level]++ \n                } else {\n                    level++ \n                }\n            }\n\n            \n            if level < 1 {\n                break\n            }\n\n            \n            \n            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n            \n            for DIGITS[level] < 10 {\n                \n                if Exp[level] == Pow[level] {\n                    s := \"\"\n                    for i := DMAX; i > 0; i-- {\n                        s += fmt.Sprintf(\"%d\", DIGITS[i])\n                    }\n                    n, _ := strconv.ParseUint(s, 10, 64)\n                    fmt.Println(n)\n                    count++\n                    if count == LIMIT {\n                        fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n                        return\n                    }\n                }\n\n                \n                DIGITS[level]++\n                Exp[level] += EXP[level][1]\n                Pow[level]++\n            }\n\n            \n            DIGITS[level] = 0\n            level--\n            DIGITS[level]++\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint power (int base, int exponent) {\n    int result = 1;\n    for (int i = 1; i <= exponent; i++) {\n        result *= base;\n    }\n    return result;\n}\n\nint is_disarium (int num) {\n    int n = num;\n    int sum = 0;\n    int len = n <= 9 ? 1 : floor(log10(n)) + 1;\n    while (n > 0) {\n        sum += power(n % 10, len);\n        n /= 10;\n        len--;\n    }\n\n    return num == sum;\n}\n\nint main() {\n    int count = 0;\n    int i = 0;\n    while (count < 19) {\n        if (is_disarium(i)) {\n            printf(\"%d \", i);\n            count++;\n        }\n        i++;\n    }\n    printf(\"%s\\n\", \"\\n\");\n}\n"}
{"id": 60605, "name": "Sierpinski pentagon", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"image/color\"\n    \"math\"\n)\n\nvar (\n    red     = color.RGBA{255, 0, 0, 255}\n    green   = color.RGBA{0, 255, 0, 255}\n    blue    = color.RGBA{0, 0, 255, 255}\n    magenta = color.RGBA{255, 0, 255, 255}\n    cyan    = color.RGBA{0, 255, 255, 255}\n)\n\nvar (\n    w, h        = 640, 640\n    dc          = gg.NewContext(w, h)\n    deg72       = gg.Radians(72)\n    scaleFactor = 1 / (2 + math.Cos(deg72)*2)\n    palette     = [5]color.Color{red, green, blue, magenta, cyan}\n    colorIndex  = 0\n)\n\nfunc drawPentagon(x, y, side float64, depth int) {\n    angle := 3 * deg72\n    if depth == 0 {\n        dc.MoveTo(x, y)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * side\n            y -= math.Sin(angle) * side\n            dc.LineTo(x, y)\n            angle += deg72\n        }\n        dc.SetColor(palette[colorIndex])\n        dc.Fill()\n        colorIndex = (colorIndex + 1) % 5\n    } else {\n        side *= scaleFactor\n        dist := side * (1 + math.Cos(deg72)*2)\n        for i := 0; i < 5; i++ {\n            x += math.Cos(angle) * dist\n            y -= math.Sin(angle) * dist\n            drawPentagon(x, y, side, depth-1)\n            angle += deg72\n        }\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    order := 5 \n    hw := float64(w / 2)\n    margin := 20.0\n    radius := hw - 2*margin\n    side := radius * math.Sin(math.Pi/5) * 2\n    drawPentagon(hw, 3*margin, side, order-1)\n    dc.SavePNG(\"sierpinski_pentagon.png\")\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n#include<time.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\ttime_t t;\n\tdouble side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;\n\tint i,iter,choice,numSides;\n\t\n\tprintf(\"Enter number of sides : \");\n\tscanf(\"%d\",&numSides);\n\t\n\tprintf(\"Enter polygon side length : \");\n\tscanf(\"%lf\",&side);\n\t\n\tprintf(\"Enter number of iterations : \");\n\tscanf(\"%d\",&iter);\n\n\tinitwindow(windowSide,windowSide,\"Polygon Chaos\");\n\t\n\tvertices = (double**)malloc(numSides*sizeof(double*));\n\t\n\tfor(i=0;i<numSides;i++){\n\t\tvertices[i] = (double*)malloc(2 * sizeof(double));\n\t\t\n\t\tvertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);\n\t\tvertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);\n\t\tsumX+= vertices[i][0];\n\t\tsumY+= vertices[i][1];\n\t\tputpixel(vertices[i][0],vertices[i][1],15);\n\t}\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tseedX = sumX/numSides;\n\tseedY = sumY/numSides;\n\t\n\tputpixel(seedX,seedY,15);\n\t\n\tfor(i=0;i<iter;i++){\n\t\tchoice = rand()%numSides;\n\t\t\n\t\tseedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);\n\t\tseedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);\n\t\t\n\t\tputpixel(seedX,seedY,15);\n\t}\n\t\n\tfree(vertices);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 60606, "name": "Minimum primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    numbers1 := [5]int{5, 45, 23, 21, 67}\n    numbers2 := [5]int{43, 22, 78, 46, 38}\n    numbers3 := [5]int{9, 98, 12, 54, 53}\n    primes := [5]int{}\n    for n := 0; n < 5; n++ {\n        max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])\n        if max % 2 == 0 {\n            max++\n        }\n        for !rcu.IsPrime(max) {\n            max += 2\n        }\n        primes[n] = max\n    }\n    fmt.Println(primes)\n}\n", "C": "#include <stdio.h>\n\n#define TRUE 1\n#define FALSE 0\n\nint isPrime(int n) {\n    int d;\n    if (n < 2) return FALSE;\n    if (n%2 == 0) return n == 2;\n    if (n%3 == 0) 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\nint max(int a, int b) {\n    if (a > b) return a;\n    return b;\n}\n\nint main() {\n    int n, m;\n    int numbers1[5] = { 5, 45, 23, 21, 67};\n    int numbers2[5] = {43, 22, 78, 46, 38};\n    int numbers3[5] = { 9, 98, 12, 54, 53};\n    int primes[5]   = {};\n    for (n = 0; n < 5; ++n) {\n        m = max(max(numbers1[n], numbers2[n]), numbers3[n]);\n        if (!(m % 2)) m++;\n        while (!isPrime(m)) m += 2;\n        primes[n] = m;\n        printf(\"%d \", primes[n]);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60607, "name": "Bitmap_Histogram", "Go": "package raster\n\nimport \"math\"\n\nfunc (g *Grmap) Histogram(bins int) []int {\n    if bins <= 0 {\n        bins = g.cols\n    }\n    h := make([]int, bins)\n    for _, p := range g.px {\n        h[int(p)*(bins-1)/math.MaxUint16]++\n    }\n    return h\n}\n\nfunc (g *Grmap) Threshold(t uint16) {\n    for i, p := range g.px {\n        if p < t {\n            g.px[i] = 0\n        } else {\n            g.px[i] = math.MaxUint16\n        }\n    }\n}\n", "C": "typedef unsigned int histogram_t;\ntypedef histogram_t *histogram;\n\n#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )\n\nhistogram get_histogram(grayimage im);\nluminance histogram_median(histogram h);\n"}
{"id": 60608, "name": "Padovan n-step number sequences", "Go": "package main\n\nimport \"fmt\"\n\nfunc padovanN(n, t int) []int {\n    if n < 2 || t < 3 {\n        ones := make([]int, t)\n        for i := 0; i < t; i++ {\n            ones[i] = 1\n        }\n        return ones\n    }\n    p := padovanN(n-1, t)\n    for i := n + 1; i < t; i++ {\n        p[i] = 0\n        for j := i - 2; j >= i-n-1; j-- {\n            p[i] += p[j]\n        }\n    }\n    return p\n}\n\nfunc main() {\n    t := 15\n    fmt.Println(\"First\", t, \"terms of the Padovan n-step number sequences:\")\n    for n := 2; n <= 8; n++ {\n        fmt.Printf(\"%d: %3d\\n\", n, padovanN(n, t))\n    }\n}\n", "C": "#include <stdio.h>\n\nvoid padovanN(int n, size_t t, int *p) {\n    int i, j;\n    if (n < 2 || t < 3) {\n        for (i = 0; i < t; ++i) p[i] = 1;\n        return;\n    }\n    padovanN(n-1, t, p);\n    for (i = n + 1; i < t; ++i) {\n        p[i] = 0;\n        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];\n    }\n}\n\nint main() {\n    int n, i;\n    const size_t t = 15;\n    int p[t];\n    printf(\"First %ld terms of the Padovan n-step number sequences:\\n\", t);\n    for (n = 2; n <= 8; ++n) {\n        for (i = 0; i < t; ++i) p[i] = 0;\n        padovanN(n, t, p);\n        printf(\"%d: \", n);\n        for (i = 0; i < t; ++i) printf(\"%3d \", p[i]);\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60609, "name": "Mutex", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n    m.Lock()\n    v := value\n    time.Sleep(1e8)\n    value = v+1\n    m.Unlock()\n    wg.Done()\n}\n\nfunc main() {\n    wg.Add(2)\n    go slowInc()\n    go slowInc()\n    wg.Wait()\n    fmt.Println(value)\n}\n", "C": "HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);\n"}
{"id": 60610, "name": "Metronome", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 \n\tvar bpb = 4    \n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/time.h>\n\nstruct timeval start, last;\n\ninline int64_t tv_to_u(struct timeval s)\n{\n\treturn s.tv_sec * 1000000 + s.tv_usec;\n}\n\ninline struct timeval u_to_tv(int64_t x)\n{\n\tstruct timeval s;\n\ts.tv_sec = x / 1000000;\n\ts.tv_usec = x % 1000000;\n\treturn s;\n}\n\nvoid draw(int dir, int64_t period, int64_t cur, int64_t next)\n{\n\tint len = 40 * (next - cur) / period;\n\tint s, i;\n\n\tif (len > 20) len = 40 - len;\n\ts = 20 + (dir ? len : -len);\n\n\tprintf(\"\\033[H\");\n\tfor (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');\n}\n\nvoid beat(int delay)\n{\n\tstruct timeval tv = start;\n\tint dir = 0;\n\tint64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;\n\tint64_t draw_interval = 20000;\n\tprintf(\"\\033[H\\033[J\");\n\twhile (1) {\n\t\tgettimeofday(&tv, 0);\n\t\tslp = next - tv_to_u(tv) - corr;\n\t\tusleep(slp);\n\t\tgettimeofday(&tv, 0);\n\n\t\tputchar(7); \n\t\tfflush(stdout);\n\n\t\tprintf(\"\\033[5;1Hdrift: %d compensate: %d (usec)   \",\n\t\t\t(int)d, (int)corr);\n\t\tdir = !dir;\n\n\t\tcur = tv_to_u(tv);\n\t\td = cur - next;\n\t\tcorr = (corr + d) / 2;\n\t\tnext += delay;\n\n\t\twhile (cur + d + draw_interval < next) {\n\t\t\tusleep(draw_interval);\n\t\t\tgettimeofday(&tv, 0);\n\t\t\tcur = tv_to_u(tv);\n\t\t\tdraw(dir, delay, cur, next);\n\t\t\tfflush(stdout);\n\t\t}\n\t}\n}\n\nint main(int c, char**v)\n{\n\tint bpm;\n\n\tif (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;\n\tif (bpm > 600) {\n\t\tfprintf(stderr, \"frequency %d too high\\n\", bpm);\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start, 0);\n\tlast = start;\n\tbeat(60 * 1000000 / bpm);\n\n\treturn 0;\n}\n"}
{"id": 60611, "name": "Native shebang", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n"}
{"id": 60612, "name": "Native shebang", "Go": "\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    if len(os.Args) > 1 {\n        fmt.Println(os.Args[1])\n    }\n}\n", "C": "#!/usr/local/bin/script_gcc.sh\n\n#include <errno.h>\n#include <libgen.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n\n\n\ntypedef char  *STRING;\ntypedef enum{FALSE=0, TRUE=1} BOOL;\nconst STRING ENDCAT = NULL;\n\n\n#define DIALECT \"c\" \nconst STRING\n  CC=\"gcc\",\n  COPTS=\"-lm -x \"DIALECT,\n  IEXT=\".\"DIALECT,\n  OEXT=\".out\";\nconst BOOL OPT_CACHE = TRUE;\n\n\nchar strcat_out[BUFSIZ];\n\nSTRING STRCAT(STRING argv, ... ){\n  va_list ap;\n  va_start(ap, argv);\n  STRING arg;\n  strcat_out[0]='\\0';\n  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){\n     strncat(strcat_out, arg, sizeof strcat_out);\n  }\n  va_end(ap);\n  return strndup(strcat_out, sizeof strcat_out);\n}\n\nchar itoa_out[BUFSIZ];\n\nSTRING itoa_(int i){\n  sprintf(itoa_out, \"%d\", i);\n  return itoa_out;\n}\n\ntime_t modtime(STRING filename){\n  struct stat buf;\n  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);\n  return buf.st_mtime;\n}\n\n\nBOOL compile(STRING srcpath, STRING binpath){\n  int out;\n  STRING compiler_command=STRCAT(CC, \" \", COPTS, \" -o \", binpath, \" -\", ENDCAT);\n  FILE *src=fopen(srcpath, \"r\"),\n       *compiler=popen(compiler_command, \"w\");\n  char buf[BUFSIZ];\n  BOOL shebang;\n\n  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)\n    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);\n\n  out=pclose(compiler);\n  return out;\n}\n\nvoid main(int argc, STRING *argv, STRING *envp){\n\n  STRING binpath,\n         srcpath=argv[1],\n         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),\n         *dirnamew, *dirnamex;\n  argv++; \n\n\n  STRING paths[] = {\n    dirname(strdup(srcpath)), \n    STRCAT(getenv(\"HOME\"), \"/bin\", ENDCAT),\n    \"/usr/local/bin\",\n    \".\",\n    STRCAT(getenv(\"HOME\"), \"/tmp\", ENDCAT),\n    getenv(\"HOME\"),\n    STRCAT(getenv(\"HOME\"), \"/Desktop\", ENDCAT),\n\n    ENDCAT\n  };\n\n  for(dirnamew = paths; *dirnamew; dirnamew++){\n    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;\n  }\n\n\n  if(OPT_CACHE == FALSE){\n    binpath=STRCAT(*dirnamew, \"/\", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);\n    if(compile(srcpath, binpath) == EXIT_SUCCESS){\n      if(fork()){\n        sleep(0.1); unlink(binpath);\n      } else {\n        execvp(binpath, argv);\n      }\n    }\n  } else {\n\n    time_t modtime_srcpath = modtime(srcpath);\n    for(dirnamex = paths; *dirnamex; dirnamex++){\n      binpath=STRCAT(*dirnamex, \"/\", argv0_basename, OEXT, ENDCAT);\n      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))\n        execvp(binpath, argv);\n    }\n  }\n\n  binpath=STRCAT(*dirnamew, \"/\", argv0_basename, OEXT, ENDCAT);\n  if(compile(srcpath, binpath) == EXIT_SUCCESS)\n    execvp(binpath, argv);\n\n  perror(STRCAT(binpath, \": executable not available\", ENDCAT));\n  exit(errno);\n}\n"}
{"id": 60613, "name": "EKG sequence convergence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n    for _, j := range a {\n        if j == b {\n            return true\n        }\n    }\n    return false\n}\n\nfunc gcd(a, b int) int {\n    for a != b {\n        if a > b {\n            a -= b\n        } else {\n            b -= a\n        }\n    }\n    return a\n}\n\nfunc areSame(s, t []int) bool {\n    le := len(s)\n    if le != len(t) {\n        return false\n    }\n    sort.Ints(s)\n    sort.Ints(t)\n    for i := 0; i < le; i++ {\n        if s[i] != t[i] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100\n    starts := [5]int{2, 5, 7, 9, 10}\n    var ekg [5][limit]int\n\n    for s, start := range starts {\n        ekg[s][0] = 1\n        ekg[s][1] = start\n        for n := 2; n < limit; n++ {\n            for i := 2; ; i++ {\n                \n                \n                if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n                    ekg[s][n] = i\n                    break\n                }\n            }\n        }\n        fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n    }   \n\n    \n    for i := 2; i < limit; i++ {\n        if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n            fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n            return\n        }\n    }\n    fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define TRUE 1\n#define FALSE 0\n#define LIMIT 100\n\ntypedef int bool;\n\nint compareInts(const void *a, const void *b) {\n    int aa = *(int *)a;\n    int bb = *(int *)b;\n    return aa - bb;\n}\n\nbool contains(int a[], int b, size_t len) {\n    int i;\n    for (i = 0; i < len; ++i) {\n        if (a[i] == b) return TRUE;\n    }\n    return FALSE;\n}\n\nint gcd(int a, int b) {\n    while (a != b) {\n        if (a > b)\n            a -= b;\n        else\n            b -= a;\n    }\n    return a;\n}\n\nbool areSame(int s[], int t[], size_t len) {\n    int i;\n    qsort(s, len, sizeof(int), compareInts);    \n    qsort(t, len, sizeof(int), compareInts);\n    for (i = 0; i < len; ++i) {\n        if (s[i] != t[i]) return FALSE;\n    }\n    return TRUE;\n}\n\nint main() {\n    int s, n, i;\n    int starts[5] = {2, 5, 7, 9, 10};\n    int ekg[5][LIMIT];\n    for (s = 0; s < 5; ++s) {\n        ekg[s][0] = 1;\n        ekg[s][1] = starts[s];\n        for (n = 2; n < LIMIT; ++n) {\n            for (i = 2; ; ++i) {\n                \n                \n                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {\n                    ekg[s][n] = i;\n                    break;\n                }\n            }\n        }\n        printf(\"EKG(%2d): [\", starts[s]);\n        for (i = 0; i < 30; ++i) printf(\"%d \", ekg[s][i]);\n        printf(\"\\b]\\n\");\n    }\n    \n    \n    for (i = 2; i < LIMIT; ++i) {\n        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {\n            printf(\"\\nEKG(5) and EKG(7) converge at term %d\\n\", i + 1);\n            return 0;\n        }\n    }\n    printf(\"\\nEKG5(5) and EKG(7) do not converge within %d terms\\n\", LIMIT);\n    return 0;\n}\n"}
{"id": 60614, "name": "Rep-string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rep(s string) int {\n    for x := len(s) / 2; x > 0; x-- {\n        if strings.HasPrefix(s, s[x:]) {\n            return x\n        }\n    }\n    return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n    for _, s := range strings.Fields(m) {\n        if n := rep(s); n > 0 {\n            fmt.Printf(\"%q  %d rep-string %q\\n\", s, n, s[:n])\n        } else {\n            fmt.Printf(\"%q  not a rep-string\\n\", s)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint repstr(char *str)\n{\n    if (!str) return 0;\n\n    size_t sl = strlen(str) / 2;\n    while (sl > 0) {\n        if (strstr(str, str + sl) == str)\n            return sl;\n        --sl;\n    }\n\n    return 0;\n}\n\nint main(void)\n{\n    char *strs[] = { \"1001110011\", \"1110111011\", \"0010010010\", \"1111111111\",\n        \"0100101101\", \"0100100\", \"101\", \"11\", \"00\", \"1\" };\n\n    size_t strslen = sizeof(strs) / sizeof(strs[0]);\n    size_t i;\n    for (i = 0; i < strslen; ++i) {\n        int n = repstr(strs[i]);\n        if (n)\n            printf(\"\\\"%s\\\" = rep-string \\\"%.*s\\\"\\n\", strs[i], n, strs[i]);\n        else\n            printf(\"\\\"%s\\\" = not a rep-string\\n\", strs[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 60615, "name": "Terminal control_Preserve screen", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"\\033[?1049h\\033[H\")\n    fmt.Println(\"Alternate screen buffer\\n\")\n    s := \"s\"\n    for i := 5; i > 0; i-- {\n        if i == 1 {\n            s = \"\"\n        }\n        fmt.Printf(\"\\rgoing back in %d second%s...\", i, s)\n        time.Sleep(time.Second)\n    }\n    fmt.Print(\"\\033[?1049l\")\n}\n", "C": "#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n\tint i;\n\tprintf(\"\\033[?1049h\\033[H\");\n\tprintf(\"Alternate screen buffer\\n\");\n\tfor (i = 5; i; i--) {\n\t\tprintf(\"\\rgoing back in %d...\", i);\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tprintf(\"\\033[?1049l\");\n\n\treturn 0;\n}\n"}
{"id": 60616, "name": "Literals_String", "Go": "ch := 'z'\nch = 122          \nch = '\\x7a'       \nch = '\\u007a'     \nch = '\\U0000007a' \nch = '\\172'       \n", "C": "char ch = 'z';\n"}
{"id": 60617, "name": "Changeable words", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"unicode/utf8\"\n)\n\nfunc hammingDist(s1, s2 string) int {\n    r1 := []rune(s1) \n    r2 := []rune(s2) \n    if len(r1) != len(r2) {\n        return 0\n    }\n    count := 0\n    for i := 0; i < len(r1); i++ {\n        if r1[i] != r2[i] {\n            count++\n            if count == 2 {\n                break \n            }\n        }\n    }\n    return count\n}\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) > 11 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    fmt.Println(\"Changeable words in\", wordList, \"\\b:\")\n    for _, word1 := range words {\n        for _, word2 := range words {\n            if word1 != word2 && hammingDist(word1, word2) == 1 {\n                count++\n                fmt.Printf(\"%2d: %-14s -> %s\\n\", count, word1, word2)\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 32\n\ntypedef struct string_tag {\n    size_t length;\n    char str[MAX_WORD_SIZE];\n} string_t;\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\nint hamming_distance(const string_t* str1, const string_t* str2) {\n    size_t len1 = str1->length;\n    size_t len2 = str2->length;\n    if (len1 != len2)\n        return 0;\n    int count = 0;\n    const char* s1 = str1->str;\n    const char* s2 = str2->str;\n    for (size_t i = 0; i < len1; ++i) {\n        if (s1[i] != s2[i])\n            ++count;\n        \n        if (count == 2)\n            break;\n    }\n    return count;\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    string_t* dictionary = xmalloc(sizeof(string_t) * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        if (size == capacity) {\n            capacity *= 2;\n            dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);\n        }\n        size_t len = strlen(line) - 1;\n        if (len > 11) {\n            string_t* str = &dictionary[size];\n            str->length = len;\n            memcpy(str->str, line, len);\n            str->str[len] = '\\0';\n            ++size;\n        }\n    }\n    fclose(in);\n    printf(\"Changeable words in %s:\\n\", filename);\n    int n = 1;\n    for (size_t i = 0; i < size; ++i) {\n        const string_t* str1 = &dictionary[i];\n        for (size_t j = 0; j < size; ++j) {\n            const string_t* str2 = &dictionary[j];\n            if (i != j && hamming_distance(str1, str2) == 1)\n                printf(\"%2d: %-14s -> %s\\n\", n++, str1->str, str2->str);\n        }\n    }\n    free(dictionary);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60618, "name": "Window management", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"time\"\n)\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetResizable(true)\n    window.SetTitle(\"Window management\")\n    window.SetBorderWidth(5)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n    check(err, \"Unable to create stack box:\")\n\n    bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n    check(err, \"Unable to create maximize button:\")\n    bmax.Connect(\"clicked\", func() {\n        window.Maximize()\n    })\n\n    bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n    check(err, \"Unable to create unmaximize button:\")\n    bunmax.Connect(\"clicked\", func() {\n        window.Unmaximize()\n    })\n\n    bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n    check(err, \"Unable to create iconize button:\")\n    bicon.Connect(\"clicked\", func() {\n        window.Iconify()\n    })\n\n    bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n    check(err, \"Unable to create deiconize button:\")\n    bdeicon.Connect(\"clicked\", func() {\n        window.Deiconify()\n    })\n\n    bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n    check(err, \"Unable to create hide button:\")\n    bhide.Connect(\"clicked\", func() {\n        \n        window.Hide() \n        time.Sleep(10 * time.Second)\n        window.Show()\n    })\n\n    bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n    check(err, \"Unable to create show button:\")\n    bshow.Connect(\"clicked\", func() {\n        window.Show()\n    })\n\n    bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n    check(err, \"Unable to create move button:\")\n    isShifted := false\n    bmove.Connect(\"clicked\", func() {\n        w, h := window.GetSize()\n        if isShifted {\n            window.Move(w-10, h-10)\n        } else {\n            window.Move(w+10, h+10)\n        }\n        isShifted = !isShifted\n    })\n\n    bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n    check(err, \"Unable to create quit button:\")\n    bquit.Connect(\"clicked\", func() {\n        window.Destroy()\n    })\n\n    stackbox.PackStart(bmax, true, true, 0)\n    stackbox.PackStart(bunmax, true, true, 0)\n    stackbox.PackStart(bicon, true, true, 0)\n    stackbox.PackStart(bdeicon, true, true, 0)\n    stackbox.PackStart(bhide, true, true, 0)\n    stackbox.PackStart(bshow, true, true, 0)\n    stackbox.PackStart(bmove, true, true, 0)\n    stackbox.PackStart(bquit, true, true, 0)\n\n    window.Add(stackbox)\n    window.ShowAll()\n    gtk.Main()\n}\n", "C": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch(msg)\n    {\n        case WM_CLOSE:\n            DestroyWindow(hwnd);\n        break;\n        case WM_DESTROY:\n            PostQuitMessage(0);\n        break;\n        default:\n            return DefWindowProc(hwnd, msg, wParam, lParam);\n    }\n    return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n    LPSTR lpCmdLine, int nCmdShow)\n{\n    WNDCLASSEX wc;\n    HWND hwnd[3];\n    MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n    wc.cbSize        = sizeof(WNDCLASSEX);\n    wc.style         = 0;\n    wc.lpfnWndProc   = WndProc;\n    wc.cbClsExtra    = 0;\n    wc.cbWndExtra    = 0;\n    wc.hInstance     = hInstance;\n    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);\n    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n    wc.lpszMenuName  = NULL;\n    wc.lpszClassName = g_szClassName;\n    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);\n\n    if(!RegisterClassEx(&wc))\n    {\n        MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n        return 0;\n    }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n    while(GetMessage(&Msg, NULL, 0, 0) > 0)\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n"}
{"id": 60619, "name": "Monads_List monad", "Go": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n    return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n    return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = v + 1\n    }\n    return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n    lst2 := make([]int, len(lst))\n    for i, v := range lst {\n        lst2[i] = 2 * v\n    }\n    return unit(lst2)\n}\n\nfunc main() {\n    ml1 := unit([]int{3, 4, 5})\n    ml2 := ml1.bind(increment).bind(double)\n    fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MONAD void*\n#define INTBIND(f, g, x) (f((int*)g(x)))\n#define RETURN(type,x) &((type)*)(x)\n\nMONAD boundInt(int *x) {\n    return (MONAD)(x);\n}\n\nMONAD boundInt2str(int *x) {\n    char buf[100];\n    char*str= malloc(1+sprintf(buf, \"%d\", *x));\n    sprintf(str, \"%d\", *x);\n    return (MONAD)(str);\n}\n\nvoid task(int y) {\n    char *z= INTBIND(boundInt2str, boundInt, &y);\n    printf(\"%s\\n\", z);\n    free(z);\n}\n\nint main() {\n    task(13);\n}\n"}
{"id": 60620, "name": "Find squares n where n+1 is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60621, "name": "Find squares n where n+1 is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    var squares []int\n    limit := int(math.Sqrt(1000))\n    i := 1\n    for i <= limit {\n        n := i * i\n        if rcu.IsPrime(n + 1) {\n            squares = append(squares, n)\n        }\n        if i == 1 {\n            i = 2\n        } else {\n            i += 2\n        }\n    }\n    fmt.Println(\"There are\", len(squares), \"square numbers 'n' where 'n+1' is prime, viz:\")\n    fmt.Println(squares)\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n#include <math.h>\n\n#define MAX 1000\n\nvoid sieve(int n, bool *prime) {\n    prime[0] = prime[1] = false;\n    for (int i=2; i<=n; i++) prime[i] = true;\n    for (int p=2; p*p<=n; p++) \n        if (prime[p])\n            for (int c=p*p; c<=n; c+=p) prime[c] = false;\n}\n\nbool square(int n) {\n    int sq = sqrt(n);\n    return (sq * sq == n);\n}\n\nint main() {\n    bool prime[MAX + 1];\n    sieve(MAX, prime);\n    for (int i=2; i<=MAX; i++) if (prime[i]) {\n        int sq = i-1;\n        if (square(sq)) printf(\"%d \", sq);\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60622, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n"}
{"id": 60623, "name": "Next special 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 main() {\n    c := sieve(1049)\n    fmt.Println(\"Special primes under 1,050:\")\n    fmt.Println(\"Prime1 Prime2 Gap\")\n    lastSpecial := 3\n    lastGap := 1\n    fmt.Printf(\"%6d %6d %3d\\n\", 2, 3, lastGap)\n    for i := 5; i < 1050; i += 2 {\n        if !c[i] && (i-lastSpecial) > lastGap {\n            lastGap = i - lastSpecial\n            fmt.Printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap)\n            lastSpecial = i\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool isPrime(int n) {\n    int 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\nint main() {\n    int i, lastSpecial = 3, lastGap = 1;\n    printf(\"Special primes under 1,050:\\n\");\n    printf(\"Prime1 Prime2 Gap\\n\");\n    printf(\"%6d %6d %3d\\n\", 2, 3, lastGap);\n    for (i = 5; i < 1050; i += 2) {\n        if (isPrime(i) && (i-lastSpecial) > lastGap) {\n            lastGap = i - lastSpecial;\n            printf(\"%6d %6d %3d\\n\", lastSpecial, i, lastGap);\n            lastSpecial = i;\n        }\n    }\n}\n"}
{"id": 60624, "name": "Mayan numerals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nconst (\n    ul = \"╔\"\n    uc = \"╦\"\n    ur = \"╗\"\n    ll = \"╚\"\n    lc = \"╩\"\n    lr = \"╝\"\n    hb = \"═\"\n    vb = \"║\"\n)\n\nvar mayan = [5]string{\n    \"    \",\n    \" ∙  \",\n    \" ∙∙ \",\n    \"∙∙∙ \",\n    \"∙∙∙∙\",\n}\n\nconst (\n    m0 = \" Θ  \"\n    m5 = \"────\"\n)\n\nfunc dec2vig(n uint64) []uint64 {\n    vig := strconv.FormatUint(n, 20)\n    res := make([]uint64, len(vig))\n    for i, d := range vig {\n        res[i], _ = strconv.ParseUint(string(d), 20, 64)\n    }\n    return res\n}\n\nfunc vig2quin(n uint64) [4]string {\n    if n >= 20 {\n        panic(\"Cant't convert a number >= 20\")\n    }\n    res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}\n    if n == 0 {\n        res[3] = m0\n        return res\n    }\n    fives := n / 5\n    rem := n % 5\n    res[3-fives] = mayan[rem]\n    for i := 3; i > 3-int(fives); i-- {\n        res[i] = m5\n    }\n    return res\n}\n\nfunc draw(mayans [][4]string) {\n    lm := len(mayans)\n    fmt.Print(ul)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(uc)\n        } else {\n            fmt.Println(ur)\n        }\n    }\n    for i := 1; i < 5; i++ {\n        fmt.Print(vb)\n        for j := 0; j < lm; j++ {\n            fmt.Print(mayans[j][i-1])\n            fmt.Print(vb)\n        }\n        fmt.Println()\n    }\n    fmt.Print(ll)\n    for i := 0; i < lm; i++ {\n        for j := 0; j < 4; j++ {\n            fmt.Print(hb)\n        }\n        if i < lm-1 {\n            fmt.Print(lc)\n        } else {\n            fmt.Println(lr)\n        }\n    }\n}\n\nfunc main() {\n    numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}\n    for _, n := range numbers {\n        fmt.Printf(\"Converting %d to Mayan:\\n\", n)\n        vigs := dec2vig(n)\n        lv := len(vigs)\n        mayans := make([][4]string, lv)\n        for i, vig := range vigs {\n            mayans[i] = vig2quin(vig)\n        }\n        draw(mayans)\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define MIN(x,y) ((x) < (y) ? (x) : (y)) \n\n\nsize_t base20(unsigned int n, uint8_t *out) {\n    \n    uint8_t *start = out;\n    do {*out++ = n % 20;} while (n /= 20);\n    size_t length = out - start;\n    \n    \n    while (out > start) {\n        uint8_t x = *--out;\n        *out = *start;\n        *start++ = x;\n    }\n    return length;\n}\n\n\nvoid make_digit(int n, char *place, size_t line_length) {\n    static const char *parts[] = {\"    \",\" .  \",\" .. \",\"... \",\"....\",\"----\"};\n    int i;\n\n    \n    for (i=4; i>0; i--, n -= 5)\n        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);\n        \n    \n    if (n == -20) place[4 * line_length + 1] = '@';\n}\n\n\nchar *mayan(unsigned int n) {\n    if (n == 0) return NULL; \n    \n    uint8_t digits[15]; \n    size_t n_digits = base20(n, digits);\n    \n    \n    size_t line_length = n_digits*5 + 2;\n    \n    \n    char *str = malloc(line_length * 6 + 1);\n    if (str == NULL) return NULL;\n    str[line_length * 6] = 0;\n    \n    \n    char *ptr;\n    unsigned int i;\n    \n    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) \n        memcpy(ptr, \"+----\", 5);\n    memcpy(ptr-5, \"+\\n\", 2);\n    memcpy(str+5*line_length, str, line_length);\n    \n    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)\n        memcpy(ptr, \"|    \", 5);\n    memcpy(ptr-5, \"|\\n\", 2);\n    memcpy(str+2*line_length, str+line_length, line_length);\n    memcpy(str+3*line_length, str+line_length, 2*line_length);\n\n    \n    for (i=0; i<n_digits; i++)\n        make_digit(digits[i], str+1+5*i, line_length);\n\n    return str;\n}\n        \nint main(int argc, char **argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: mayan <number>\\n\");\n        return 1;\n    }\n    int i = atoi(argv[1]);\n    if (i <= 0) {\n        fprintf(stderr, \"number must be positive\\n\");\n        return 1;\n    }\n    char *m = mayan(i);\n    printf(\"%s\",m);\n    free(m);\n    return 0;\n}\n"}
{"id": 60625, "name": "Special factorials", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc sf(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    sfact := big.NewInt(1)\n    fact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        sfact.Mul(sfact, fact)\n    }\n    return sfact\n}\n\nfunc H(n int) *big.Int {\n    if n < 2 {\n        return big.NewInt(1)\n    }\n    hfact := big.NewInt(1)\n    for i := 2; i <= n; i++ {\n        bi := big.NewInt(int64(i))\n        hfact.Mul(hfact, bi.Exp(bi, bi, nil))\n    }\n    return hfact\n}\n\nfunc af(n int) *big.Int {\n    if n < 1 {\n        return new(big.Int)\n    }\n    afact := new(big.Int)\n    fact := big.NewInt(1)\n    sign := new(big.Int)\n    if n%2 == 0 {\n        sign.SetInt64(-1)\n    } else {\n        sign.SetInt64(1)\n    }\n    t := new(big.Int)\n    for i := 1; i <= n; i++ {\n        fact.Mul(fact, big.NewInt(int64(i)))\n        afact.Add(afact, t.Mul(fact, sign))\n        sign.Neg(sign)\n    }\n    return afact\n}\n\nfunc ef(n int) *big.Int {\n    if n < 1 {\n        return big.NewInt(1)\n    }\n    t := big.NewInt(int64(n))\n    return t.Exp(t, ef(n-1), nil)\n}\n\nfunc rf(n *big.Int) int {\n    i := 0\n    fact := big.NewInt(1)\n    for {\n        if fact.Cmp(n) == 0 {\n            return i\n        }\n        if fact.Cmp(n) > 0 {\n            return -1\n        }\n        i++\n        fact.Mul(fact, big.NewInt(int64(i)))\n    }\n}\n\nfunc main() {\n    fmt.Println(\"First 10 superfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(sf(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 hyperfactorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Println(H(i))\n    }\n\n    fmt.Println(\"\\nFirst 10 alternating factorials:\")\n    for i := 0; i < 10; i++ {\n        fmt.Print(af(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nFirst 5 exponential factorials:\")\n    for i := 0; i <= 4; i++ {\n        fmt.Print(ef(i), \" \")\n    }\n\n    fmt.Println(\"\\n\\nThe number of digits in 5$ is\", len(ef(5).String()))\n\n    fmt.Println(\"\\nReverse factorials:\")\n    facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}\n    for _, fact := range facts {\n        bfact := big.NewInt(fact)\n        rfact := rf(bfact)\n        srfact := fmt.Sprintf(\"%d\", rfact)\n        if rfact == -1 {\n            srfact = \"none\"\n        }\n        fmt.Printf(\"%4s <- rf(%d)\\n\", srfact, fact)\n    }\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nuint64_t factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= i;\n    }\n\n    return result;\n}\n\n\nint inverse_factorial(uint64_t f) {\n    int p = 1;\n    int i = 1;\n\n    if (f == 1) {\n        return 0;\n    }\n\n    while (p < f) {\n        p *= i;\n        i++;\n    }\n\n    if (p == f) {\n        return i - 1;\n    }\n    return -1;\n}\n\n\nuint64_t super_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= factorial(i);\n    }\n\n    return result;\n}\n\n\nuint64_t hyper_factorial(int n) {\n    uint64_t result = 1;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result *= (uint64_t)powl(i, i);\n    }\n\n    return result;\n}\n\n\nuint64_t alternating_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        if ((n - i) % 2 == 0) {\n            result += factorial(i);\n        } else {\n            result -= factorial(i);\n        }\n    }\n\n    return result;\n}\n\n\nuint64_t exponential_factorial(int n) {\n    uint64_t result = 0;\n    int i;\n\n    for (i = 1; i <= n; i++) {\n        result = (uint64_t)powl(i, (long double)result);\n    }\n\n    return result;\n}\n\nvoid test_factorial(int count, uint64_t(*func)(int), char *name) {\n    int i;\n\n    printf(\"First %d %s:\\n\", count, name);\n    for (i = 0; i < count ; i++) {\n        printf(\"%llu \", func(i));\n    }\n    printf(\"\\n\");\n}\n\nvoid test_inverse(uint64_t f) {\n    int n = inverse_factorial(f);\n    if (n < 0) {\n        printf(\"rf(%llu) = No Solution\\n\", f);\n    } else {\n        printf(\"rf(%llu) = %d\\n\", f, n);\n    }\n}\n\nint main() {\n    int i;\n\n    \n    test_factorial(9, super_factorial, \"super factorials\");\n    printf(\"\\n\");\n\n    \n    test_factorial(8, super_factorial, \"hyper factorials\");\n    printf(\"\\n\");\n\n    test_factorial(10, alternating_factorial, \"alternating factorials\");\n    printf(\"\\n\");\n\n    test_factorial(5, exponential_factorial, \"exponential factorials\");\n    printf(\"\\n\");\n\n    test_inverse(1);\n    test_inverse(2);\n    test_inverse(6);\n    test_inverse(24);\n    test_inverse(120);\n    test_inverse(720);\n    test_inverse(5040);\n    test_inverse(40320);\n    test_inverse(362880);\n    test_inverse(3628800);\n    test_inverse(119);\n\n    return 0;\n}\n"}
{"id": 60626, "name": "Special neighbor primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n"}
{"id": 60627, "name": "Special neighbor primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nconst MAX = 1e7 - 1\n\nvar primes = rcu.Primes(MAX)\n\nfunc specialNP(limit int, showAll bool) {\n    if showAll {\n        fmt.Println(\"Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:\")\n    }\n    count := 0\n    for i := 1; i < len(primes); i++ {\n        p2 := primes[i]\n        if p2 >= limit {\n            break\n        }\n        p1 := primes[i-1]\n        p3 := p1 + p2 - 1\n        if rcu.IsPrime(p3) {\n            if showAll {\n                fmt.Printf(\"(%2d, %2d) => %3d\\n\", p1, p2, p3)\n            }\n            count++\n        }\n    }\n    ccount := rcu.Commatize(count)\n    climit := rcu.Commatize(limit)\n    fmt.Printf(\"\\nFound %s special neighbor primes under %s.\\n\", ccount, climit)\n}\n\nfunc main() {\n    specialNP(100, true)\n    var pow = 1000\n    for i := 3; i < 8; i++ {\n        specialNP(pow, false)\n        pow *= 10\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint nextprime( int p ) {\n    int i=0;\n    if(p==0) return 2;\n    if(p<3) return p+1;\n    while(!isprime(++i + p));\n    return i+p;\n}\n\nint main(void) {\n    int p1, p2;\n    for(p1=3;p1<=99;p1+=2) {\n        p2=nextprime(p1);\n        if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {\n            printf( \"%d + %d - 1 = %d\\n\", p1, p2, p1+p2-1 );\n        }\n    }\n    return 0;\n}\n"}
{"id": 60628, "name": "Ramsey's theorem", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    a   [17][17]int\n    idx [4]int\n)\n\nfunc findGroup(ctype, min, max, depth int) bool {\n    if depth == 4 {\n        cs := \"\"\n        if ctype == 0 {\n            cs = \"un\"\n        }\n        fmt.Printf(\"Totally %sconnected group:\", cs)\n        for i := 0; i < 4; i++ {\n            fmt.Printf(\" %d\", idx[i])\n        }\n        fmt.Println()\n        return true\n    }\n\n    for i := min; i < max; i++ {\n        n := 0\n        for ; n < depth; n++ {\n            if a[idx[n]][i] != ctype {\n                break\n            }\n        }\n\n        if n == depth {\n            idx[n] = i\n            if findGroup(ctype, 1, max, depth+1) {\n                return true\n            }\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const mark = \"01-\"\n\n    for i := 0; i < 17; i++ {\n        a[i][i] = 2\n    }\n\n    for k := 1; k <= 8; k <<= 1 {\n        for i := 0; i < 17; i++ {\n            j := (i + k) % 17\n            a[i][j], a[j][i] = 1, 1\n        }\n    }\n\n    for i := 0; i < 17; i++ {\n        for j := 0; j < 17; j++ {\n            fmt.Printf(\"%c \", mark[a[i][j]])\n        }\n        fmt.Println()\n    }\n\n    \n    \n\n    \n    for i := 0; i < 17; i++ {\n        idx[0] = i\n        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {\n            fmt.Println(\"No good.\")\n            return\n        }\n    }\n    fmt.Println(\"All good.\")\n}\n", "C": "#include <stdio.h>\n\nint a[17][17], idx[4];\n\nint find_group(int type, int min_n, int max_n, int depth)\n{\n\tint i, n;\n\tif (depth == 4) {\n\t\tprintf(\"totally %sconnected group:\", type ? \"\" : \"un\");\n\t\tfor (i = 0; i < 4; i++) printf(\" %d\", idx[i]);\n\t\tputchar('\\n');\n\t\treturn 1;\n\t}\n\n\tfor (i = min_n; i < max_n; i++) {\n\t\tfor (n = 0; n < depth; n++)\n\t\t\tif (a[idx[n]][i] != type) break;\n\n\t\tif (n == depth) {\n\t\t\tidx[n] = i;\n\t\t\tif (find_group(type, 1, max_n, depth + 1))\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tconst char *mark = \"01-\";\n\n\tfor (i = 0; i < 17; i++)\n\t\ta[i][i] = 2;\n\n\tfor (k = 1; k <= 8; k <<= 1) {\n\t\tfor (i = 0; i < 17; i++) {\n\t\t\tj = (i + k) % 17;\n\t\t\ta[i][j] = a[j][i] = 1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < 17; i++) {\n\t\tfor (j = 0; j < 17; j++)\n\t\t\tprintf(\"%c \", mark[a[i][j]]);\n\t\tputchar('\\n');\n\t}\n\n\t\n\t\n\n\t\n\tfor (i = 0; i < 17; i++) {\n\t\tidx[0] = i;\n\t\tif (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {\n\t\t\tputs(\"no good\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"all good\");\n\treturn 0;\n}\n"}
{"id": 60629, "name": "GUI_Maximum window dimensions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/go-vgo/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable : %d x %d\\n\", w, h)\n    }\n}\n", "C": "#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h) : %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n"}
{"id": 60630, "name": "Terminal control_Inverse video", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    tput(\"rev\")\n    fmt.Print(\"Rosetta\")\n    tput(\"sgr0\")\n    fmt.Println(\" Code\")\n}\n\nfunc tput(arg string) error {\n    cmd := exec.Command(\"tput\", arg)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tprintf(\"\\033[7mReversed\\033[m Normal\\n\");\n\n\treturn 0;\n}\n"}
{"id": 60631, "name": "Four is magic", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \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 <stdint.h>\n#include <stdio.h>\n#include <glib.h>\n\ntypedef struct named_number_tag {\n    const char* name;\n    uint64_t number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", 100 },\n    { \"thousand\", 1000 },\n    { \"million\", 1000000 },\n    { \"billion\", 1000000000 },\n    { \"trillion\", 1000000000000 },\n    { \"quadrillion\", 1000000000000000ULL },\n    { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number* get_named_number(uint64_t n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_number);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(GString* str, uint64_t n) {\n    static const char* small[] = {\n        \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n        \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n        \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n    };\n    static const char* tens[] = {\n        \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    size_t len = str->len;\n    if (n < 20) {\n        g_string_append(str, small[n]);\n    }\n    else if (n < 100) {\n        g_string_append(str, tens[n/10 - 2]);\n        if (n % 10 != 0) {\n            g_string_append_c(str, '-');\n            g_string_append(str, small[n % 10]);\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        uint64_t p = num->number;\n        append_number_name(str, n/p);\n        g_string_append_c(str, ' ');\n        g_string_append(str, num->name);\n        if (n % p != 0) {\n            g_string_append_c(str, ' ');\n            append_number_name(str, n % p);\n        }\n    }\n    return str->len - len;\n}\n\nGString* magic(uint64_t n) {\n    GString* str = g_string_new(NULL);\n    for (unsigned int i = 0; ; ++i) {\n        size_t count = append_number_name(str, n);\n        if (i == 0)\n            str->str[0] = g_ascii_toupper(str->str[0]);\n        if (n == 4) {\n            g_string_append(str, \" is magic.\");\n            break;\n        }\n        g_string_append(str, \" is \");\n        append_number_name(str, count);\n        g_string_append(str, \", \");\n        n = count;\n    }\n    return str;\n}\n\nvoid test_magic(uint64_t n) {\n    GString* str = magic(n);\n    printf(\"%s\\n\", str->str);\n    g_string_free(str, TRUE);\n}\n\nint main() {\n    test_magic(5);\n    test_magic(13);\n    test_magic(78);\n    test_magic(797);\n    test_magic(2739);\n    test_magic(4000);\n    test_magic(7893);\n    test_magic(93497412);\n    test_magic(2673497412U);\n    test_magic(10344658531277200972ULL);\n    return 0;\n}\n"}
{"id": 60632, "name": "Using a speech engine to highlight words", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    s := \"Actions speak louder than words.\"\n    prev := \"\"\n    prevLen := 0\n    bs := \"\"\n    for _, word := range strings.Fields(s) {\n        cmd := exec.Command(\"espeak\", word)\n        if err := cmd.Run(); err != nil {\n            log.Fatal(err)\n        }\n        if prevLen > 0 {\n            bs = strings.Repeat(\"\\b\", prevLen)\n        }\n        fmt.Printf(\"%s%s%s \", bs, prev, strings.ToUpper(word))\n        prev = word + \" \"\n        prevLen = len(word) + 1\n    }\n    bs = strings.Repeat(\"\\b\", prevLen)\n    time.Sleep(time.Second)\n    fmt.Printf(\"%s%s\\n\", bs, prev)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nvoid C_espeak(WrenVM* vm) {\n    const char *arg = wrenGetSlotString(vm, 1);\n    char command[strlen(arg) + 10];\n    strcpy(command, \"espeak \\\"\");\n    strcat(command, arg);\n    strcat(command, \"\\\"\");\n    system(command);\n}\n\nvoid C_flushStdout(WrenVM* vm) {\n    fflush(stdout);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0)     return C_usleep;\n            if (isStatic && strcmp(signature, \"espeak(_)\") == 0)     return C_espeak;\n            if (isStatic && strcmp(signature, \"flushStdout()\") == 0) return C_flushStdout;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"speech_engine_highlight_words.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60633, "name": "Using a speech engine to highlight words", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    s := \"Actions speak louder than words.\"\n    prev := \"\"\n    prevLen := 0\n    bs := \"\"\n    for _, word := range strings.Fields(s) {\n        cmd := exec.Command(\"espeak\", word)\n        if err := cmd.Run(); err != nil {\n            log.Fatal(err)\n        }\n        if prevLen > 0 {\n            bs = strings.Repeat(\"\\b\", prevLen)\n        }\n        fmt.Printf(\"%s%s%s \", bs, prev, strings.ToUpper(word))\n        prev = word + \" \"\n        prevLen = len(word) + 1\n    }\n    bs = strings.Repeat(\"\\b\", prevLen)\n    time.Sleep(time.Second)\n    fmt.Printf(\"%s%s\\n\", bs, prev)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\nvoid C_usleep(WrenVM* vm) {\n    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);\n    usleep(usec);\n}\n\nvoid C_espeak(WrenVM* vm) {\n    const char *arg = wrenGetSlotString(vm, 1);\n    char command[strlen(arg) + 10];\n    strcpy(command, \"espeak \\\"\");\n    strcat(command, arg);\n    strcat(command, \"\\\"\");\n    system(command);\n}\n\nvoid C_flushStdout(WrenVM* vm) {\n    fflush(stdout);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"usleep(_)\") == 0)     return C_usleep;\n            if (isStatic && strcmp(signature, \"espeak(_)\") == 0)     return C_espeak;\n            if (isStatic && strcmp(signature, \"flushStdout()\") == 0) return C_flushStdout;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"speech_engine_highlight_words.wren\";\n    char *script = readFile(fileName);\n    wrenInterpret(vm, module, script);\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60634, "name": "Getting the number of decimals", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"strings\"\n)\n\nvar error = \"Argument must be a numeric literal or a decimal numeric string.\"\n\nfunc getNumDecimals(n interface{}) int {\n    switch v := n.(type) {\n    case int:\n        return 0\n    case float64:\n        if v == math.Trunc(v) {\n            return 0\n        }\n        s := fmt.Sprintf(\"%g\", v)\n        return len(strings.Split(s, \".\")[1])\n    case string:\n        if v == \"\" {\n            log.Fatal(error)\n        }\n        if v[0] == '+' || v[0] == '-' {\n            v = v[1:]\n        }\n        for _, c := range v {\n            if strings.IndexRune(\"0123456789.\", c) == -1 {\n                log.Fatal(error)\n            }\n        }\n        s := strings.Split(v, \".\")\n        ls := len(s)\n        if ls == 1 {\n            return 0\n        } else if ls == 2 {\n            return len(s[1])\n        } else {\n            log.Fatal(\"Too many decimal points\")\n        }\n    default:\n        log.Fatal(error)\n    }\n    return 0\n}\n\nfunc main() {\n    var a = []interface{}{12, 12.345, 12.345555555555, \"12.3450\", \"12.34555555555555555555\", 12.345e53}\n    for _, n := range a {\n        d := getNumDecimals(n)\n        switch v := n.(type) {\n        case string:\n            fmt.Printf(\"%q has %d decimals\\n\", v, d)\n        case float32, float64:\n            fmt.Printf(\"%g has %d decimals\\n\", v, d)\n        default:\n            fmt.Printf(\"%d has %d decimals\\n\", v, d)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nint findNumOfDec(double x) {\n    char buffer[128];\n    int pos, num;\n\n    sprintf(buffer, \"%.14f\", x);\n\n    pos = 0;\n    num = 0;\n    while (buffer[pos] != 0 && buffer[pos] != '.') {\n        pos++;\n    }\n    if (buffer[pos] != 0) {\n        pos++; \n        while (buffer[pos] != 0) {\n            pos++; \n        }\n        pos--; \n        while (buffer[pos] == '0') {\n            pos--; \n        }\n        while (buffer[pos] != '.') {\n            num++;\n            pos--; \n        }\n    }\n    return num;\n}\n\nvoid test(double x) {\n    int num = findNumOfDec(x);\n    printf(\"%f has %d decimals\\n\", x, num);\n}\n\nint main() {\n    test(12.0);\n    test(12.345);\n    test(12.345555555555);\n    test(12.3450);\n    test(12.34555555555555555555);\n    test(1.2345e+54);\n    return 0;\n}\n"}
{"id": 60635, "name": "Enumerations", "Go": "const (\n\tapple = iota\n\tbanana\n\tcherry\n)\n", "C": "enum fruits { apple, banana, cherry };\n\nenum fruits { apple = 0, banana = 1, cherry = 2 };\n"}
{"id": 60636, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60637, "name": "Paraffins", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n    for b := br + 1; b <= branches; b++ {\n        sum += n\n        if sum > nMax {\n            return\n        }\n        if l*2 >= sum && b >= branches {\n            return\n        }\n        if b == br+1 {\n            c[br].Mul(&rooted[n], cnt)\n        } else {\n            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n            c[br].Mul(&c[br], tmp)\n            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n        }\n        if l*2 < sum {\n            unrooted[sum].Add(&unrooted[sum], &c[br])\n        }\n        if b < branches {\n            rooted[sum].Add(&rooted[sum], &c[br])\n        }\n        for m := n - 1; m > 0; m-- {\n            tree(b, m, l, sum, &c[br])\n        }\n    }\n}\n\nfunc bicenter(s int) {\n    if s&1 == 0 {\n        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n        unrooted[s].Add(&unrooted[s], tmp)\n    }\n}\n\nfunc main() {\n    rooted[0].SetInt64(1)\n    rooted[1].SetInt64(1)\n    unrooted[0].SetInt64(1)\n    unrooted[1].SetInt64(1)\n    for n := 1; n <= nMax; n++ {\n        tree(0, n, n, 1, big.NewInt(1))\n        bicenter(n)\n        fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n    }\n}\n", "C": "#include <stdio.h>\n\n#define MAX_N 33\t\n#define BRANCH 4\t\n\n\n\ntypedef unsigned long long xint;\n#define FMT \"llu\"\n\nxint rooted[MAX_N] = {1, 1, 0};\nxint unrooted[MAX_N] = {1, 1, 0};\n\n\nxint choose(xint m, xint k)\n{\n\txint i, r;\n\n\tif (k == 1) return m;\n\tfor (r = m, i = 1; i < k; i++)\n\t\tr = r * (m + i) / (i + 1);\n\treturn r;\n}\n\n\nvoid tree(xint br, xint n, xint cnt, xint sum, xint l)\n{\n\txint b, c, m, s;\n\n\tfor (b = br + 1; b <= BRANCH; b++) {\n\t\ts = sum + (b - br) * n;\n\t\tif (s >= MAX_N) return;\n\n\t\t\n\t\tc = choose(rooted[n], b - br) * cnt;\n\n\t\t\n\t\tif (l * 2 < s) unrooted[s] += c;\n\n\t\t\n\t\tif (b == BRANCH) return;\n\t\trooted[s] += c;\n\n\t\t\n\t\tfor (m = n; --m; ) tree(b, m, c, s, l);\n\t}\n}\n\nvoid bicenter(int s)\n{\n\tif (s & 1) return;\n\n\t\n\tunrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;\n}\n\nint main()\n{\n\txint n;\n\tfor (n = 1; n < MAX_N; n++) {\n\t\ttree(0, n, 1, 1, n);\n\t\tbicenter(n);\n\t\tprintf(\"%\"FMT\": %\"FMT\"\\n\", n, unrooted[n]);\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60638, "name": "Minimum number of cells after, before, above and below NxN squares", "Go": "package main\n\nimport \"fmt\"\n\nfunc printMinCells(n int) {\n    fmt.Printf(\"Minimum number of cells after, before, above and below %d x %d square:\\n\", n, n)\n    p := 1\n    if n > 20 {\n        p = 2\n    }\n    for r := 0; r < n; r++ {\n        cells := make([]int, n)\n        for c := 0; c < n; c++ {\n            nums := []int{n - r - 1, r, c, n - c - 1}\n            min := n\n            for _, num := range nums {\n                if num < min {\n                    min = num\n                }\n            }\n            cells[c] = min\n        }\n        fmt.Printf(\"%*d \\n\", p, cells)\n    }\n}\n\nfunc main() {\n    for _, n := range []int{23, 10, 9, 2, 1} {\n        printMinCells(n)\n        fmt.Println()\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\n#define min(a, b) (a<=b?a:b)\n\nvoid minab( unsigned int n ) {\n    int i, j;\n    for(i=0;i<n;i++) {\n        for(j=0;j<n;j++) {\n            printf( \"%2d  \", min( min(i, n-1-i), min(j, n-1-j) ));\n        }\n        printf( \"\\n\" );\n    }\n    return;\n}\n\nint main(void) {\n    minab(10);\n    return 0;\n}\n"}
{"id": 60639, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 60640, "name": "Pentagram", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc Pentagram(x, y, r float64) []gg.Point {\n    points := make([]gg.Point, 5)\n    for i := 0; i < 5; i++ {\n        fi := float64(i)\n        angle := 2*math.Pi*fi/5 - math.Pi/2\n        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}\n    }\n    return points\n}\n\nfunc main() {\n    points := Pentagram(320, 320, 250)\n    dc := gg.NewContext(640, 640)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for i := 0; i <= 5; i++ {\n        index := (i * 2) % 5\n        p := points[index]\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetHexColor(\"#6495ED\") \n    dc.SetFillRule(gg.FillRuleWinding)\n    dc.FillPreserve()\n    dc.SetRGB(0, 0, 0) \n    dc.SetLineWidth(5)\n    dc.Stroke()\n    dc.SavePNG(\"pentagram.png\")\n}\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tchar colourNames[][14] = { \"BLACK\", \"BLUE\", \"GREEN\", \"CYAN\", \"RED\", \"MAGENTA\", \"BROWN\", \"LIGHTGRAY\", \"DARKGRAY\",\n              \"LIGHTBLUE\", \"LIGHTGREEN\", \"LIGHTCYAN\", \"LIGHTRED\", \"LIGHTMAGENTA\", \"YELLOW\", \"WHITE\" };\n\t\t\t  \n\tint stroke=0,fill=0,back=0,i;\n\t\n\tdouble centerX = 300,centerY = 300,coreSide,armLength,pentaLength;\n\t\n\tprintf(\"Enter core pentagon side length : \");\n\tscanf(\"%lf\",&coreSide);\n\t\n\tprintf(\"Enter pentagram arm length : \");\n\tscanf(\"%lf\",&armLength);\n\t\n\tprintf(\"Available colours are :\\n\");\n\t\n\tfor(i=0;i<16;i++){\n\t\tprintf(\"%d. %s\\t\",i+1,colourNames[i]);\n\t\tif((i+1) % 3 == 0){\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\twhile(stroke==fill && fill==back){\n\t\tprintf(\"\\nEnter three diffrenet options for stroke, fill and background : \");\n\t\tscanf(\"%d%d%d\",&stroke,&fill,&back);\n\t}\n\t\n\tpentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);\n\t\n\tinitwindow(2*centerX,2*centerY,\"Pentagram\");\n\t\t\n\tsetcolor(stroke-1);\n\t\n\tsetfillstyle(SOLID_FILL,back-1);\n\t\n\tbar(0,0,2*centerX,2*centerY);\n\t\n\tfloodfill(centerX,centerY,back-1);\n\t\n\tsetfillstyle(SOLID_FILL,fill-1);\n\n\tfor(i=0;i<5;i++){\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));\n\t\tline(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\tline(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));\n\t\t\n\t\tfloodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);\n\t}\n\t\n\tfloodfill(centerX,centerY,stroke-1);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 60641, "name": "Parse an IP Address", "Go": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n", "C": "#include <string.h>\n#include <memory.h>\n\n\nstatic unsigned int _parseDecimal ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )\n    {\n        \n        nVal *= 10;\n        nVal += chNow - '0';\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\nstatic unsigned int _parseHex ( const char** pchCursor )\n{\n    unsigned int nVal = 0;\n    char chNow;\n    while ( chNow = **pchCursor & 0x5f, \n            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || \n            (chNow >= 'A' && chNow <= 'F') \n            )\n    {\n        unsigned char nybbleValue;\n        chNow -= 0x10;  \n        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );\n        \n        nVal <<= 4;\n        nVal += nybbleValue;\n\n        ++*pchCursor;\n    }\n    return nVal;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint ParseIPv4OrIPv6 ( const char** ppszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    unsigned char* abyAddrLocal;\n    unsigned char abyDummyAddr[16];\n\n    \n    const char* pchColon = strchr ( *ppszText, ':' );\n    const char* pchDot = strchr ( *ppszText, '.' );\n    const char* pchOpenBracket = strchr ( *ppszText, '[' );\n    const char* pchCloseBracket = NULL;\n\n\n    \n    \n    \n    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||\n            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );\n    \n    if ( bIsIPv6local )\n    {\n        \n        pchCloseBracket = strchr ( *ppszText, ']' );\n        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||\n                pchCloseBracket < pchOpenBracket ) )\n            return 0;\n    }\n    else    \n    {\n        \n        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )\n            return 0;\n    }\n\n    \n    if ( NULL != pbIsIPv6 )\n        *pbIsIPv6 = bIsIPv6local;\n    \n    \n    \n    \n    abyAddrLocal = abyAddr; \n    if ( NULL == abyAddrLocal ) \n        abyAddrLocal = abyDummyAddr;\n\n    \n    \n    \n    if ( ! bIsIPv6local )   \n    {\n        \n        \n        \n        unsigned char* pbyAddrCursor = abyAddrLocal;\n        unsigned int nVal;\n        const char* pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;  \n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )\n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n        ++(*ppszText);  \n\n        pszTextBefore = *ppszText;\n        nVal =_parseDecimal ( ppszText );           \n        if ( nVal > 255 || pszTextBefore == *ppszText ) \n            return 0;\n        *(pbyAddrCursor++) = (unsigned char) nVal;\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n    else    \n    {\n        unsigned char* pbyAddrCursor;\n        unsigned char* pbyZerosLoc;\n        int bIPv4Detected;\n        int nIdx;\n        \n        \n        \n        \n        \n        if ( NULL != pchOpenBracket )   \n            *ppszText = pchOpenBracket + 1;\n        pbyAddrCursor = abyAddrLocal;\n        pbyZerosLoc = NULL; \n        bIPv4Detected = 0;\n        for ( nIdx = 0; nIdx < 8; ++nIdx )  \n        {\n            const char* pszTextBefore = *ppszText;\n            unsigned nVal =_parseHex ( ppszText );      \n            if ( pszTextBefore == *ppszText )   \n            {\n                if ( NULL != pbyZerosLoc )  \n                {\n                    \n                    if ( pbyZerosLoc == pbyAddrCursor )\n                    {\n                        --nIdx;\n                        break;\n                    }\n                    return 0;   \n                }\n                if ( ':' != **ppszText )    \n                    return 0;\n                if ( 0 == nIdx )    \n                {\n                    ++(*ppszText);\n                    if ( ':' != **ppszText )\n                        return 0;\n                }\n\n                pbyZerosLoc = pbyAddrCursor;\n                ++(*ppszText);\n            }\n            else\n            {\n                if ( '.' == **ppszText )    \n                {\n                    \n                    const char* pszTextlocal = pszTextBefore;   \n                    unsigned char abyAddrlocal[16];\n                    int bIsIPv6local;\n                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );\n                    *ppszText = pszTextlocal;   \n                    if ( ! bParseResultlocal || bIsIPv6local )  \n                        return 0;\n                    \n                    *(pbyAddrCursor++) = abyAddrlocal[0];\n                    *(pbyAddrCursor++) = abyAddrlocal[1];\n                    *(pbyAddrCursor++) = abyAddrlocal[2];\n                    *(pbyAddrCursor++) = abyAddrlocal[3];\n                    ++nIdx; \n                    bIPv4Detected = 1;  \n                    break;  \n                }\n\n                if ( nVal > 65535 ) \n                    return 0;\n                *(pbyAddrCursor++) = nVal >> 8;     \n                *(pbyAddrCursor++) = nVal & 0xff;\n                if ( ':' == **ppszText )    \n                {\n                    ++(*ppszText);\n                }\n                else    \n                {\n                    break;\n                }\n            }\n        }\n        \n        \n        if ( NULL != pbyZerosLoc )\n        {\n            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    \n            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); \n            int nZeros = 16 - nTail - nHead;        \n            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    \n            memset ( pbyZerosLoc, 0, nZeros );      \n        }\n        \n        \n        if ( bIPv4Detected )\n        {\n            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };\n            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )\n                return 0;\n        }\n\n        \n        if ( NULL != pchOpenBracket )\n        {\n            if ( ']' != **ppszText )\n                return 0;\n            ++(*ppszText);\n        }\n\n        if ( ':' == **ppszText && NULL != pnPort )  \n        {\n            const char* pszTextBefore;\n            unsigned int nVal;\n            unsigned short usPortNetwork;   \n            ++(*ppszText);  \n            pszTextBefore = *ppszText;\n            pszTextBefore = *ppszText;\n            nVal =_parseDecimal ( ppszText );\n            if ( nVal > 65535 || pszTextBefore == *ppszText )\n                return 0;\n            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;\n            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );\n            *pnPort = usPortNetwork;\n            return 1;\n        }\n        else    \n        {\n            if ( NULL != pnPort )\n                *pnPort = 0;    \n            return 1;\n        }\n    }\n\n}\n\n\n\nint ParseIPv4OrIPv6_2 ( const char* pszText, \n        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )\n{\n    const char* pszTextLocal = pszText;\n    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);\n}\n"}
{"id": 60642, "name": "OpenGL pixel shader", "Go": "package main\n\n\nimport \"C\"\nimport \"log\"\nimport \"unsafe\"\n\nvar ps, vs, prog, r_mod C.GLuint\nvar angle = float32(0)\n\n\nfunc render() {\n    C.glClear(C.GL_COLOR_BUFFER_BIT)\n    C.glUniform1f_macro(C.GLint(r_mod), C.GLfloat(C.rand())/C.GLfloat(C.RAND_MAX))\n    C.glLoadIdentity()\n    C.glRotatef(C.float(angle), C.float(angle*0.1), 1, 0)\n    C.glBegin(C.GL_TRIANGLES)\n    C.glVertex3f(-1, -0.5, 0)\n    C.glVertex3f(0, 1, 0)\n    C.glVertex3f(1, 0, 0)\n    C.glEnd()\n    angle += 0.02\n    C.glutSwapBuffers()\n}\n\nfunc setShader() {\n    f := \"varying float x, y, z;\" +\n        \"uniform float r_mod;\" +\n        \"float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }\" +\n        \"void main() {\" +\n        \"    gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);\" +\n        \"}\"\n\n    v := \"varying float x, y, z;\" +\n        \"void main() {\" +\n        \"    gl_Position = ftransform();\" +\n        \"    x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;\" +\n        \"    x += y; y -= x; z += x - y;\" +\n        \"}\"\n\n    fc, vc := C.CString(f), C.CString(v)\n    defer C.free(unsafe.Pointer(fc))\n    defer C.free(unsafe.Pointer(vc))\n\n    vs = C.glCreateShader_macro(C.GL_VERTEX_SHADER)\n    ps = C.glCreateShader_macro(C.GL_FRAGMENT_SHADER)\n    C.glShaderSource_macro(ps, 1, &fc, nil)\n    C.glShaderSource_macro(vs, 1, &vc, nil)\n\n    C.glCompileShader_macro(vs)\n    C.glCompileShader_macro(ps)\n\n    prog = C.glCreateProgram_macro()\n    C.glAttachShader_macro(prog, ps)\n    C.glAttachShader_macro(prog, vs)\n\n    C.glLinkProgram_macro(prog)\n    C.glUseProgram_macro(prog)\n    rms := C.CString(\"r_mod\")\n    r_mod = C.GLuint(C.glGetUniformLocation_macro(prog, rms))\n    C.free(unsafe.Pointer(rms))\n}\n\nfunc main() {\n    argc := C.int(0)\n    C.glutInit(&argc, nil)\n    C.glutInitDisplayMode(C.GLUT_DOUBLE | C.GLUT_RGB)\n    C.glutInitWindowSize(200, 200)\n    tl := \"Pixel Shader\"\n    tlc := C.CString(tl)\n    C.glutCreateWindow(tlc)\n    defer C.free(unsafe.Pointer(tlc))\n    C.glutIdleFunc(C.idleFunc())\n\n    C.glewInit()\n    glv := C.CString(\"GL_VERSION_2_0\")\n    if C.glewIsSupported(glv) == 0 {\n        log.Fatal(\"GL 2.0 unsupported\")\n    }\n    defer C.free(unsafe.Pointer(glv))\n\n    setShader()\n    C.glutMainLoop()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <GL/glew.h>\n#include <GL/glut.h>\n\nGLuint ps, vs, prog, r_mod;\nfloat angle = 0;\nvoid render(void)\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglUniform1f(r_mod, rand() / (float)RAND_MAX);\n\n\tglLoadIdentity();\n\tglRotatef(angle, angle * .1, 1, 0);\n\tglBegin(GL_TRIANGLES);\n\t\tglVertex3f(-1, -.5, 0);\n\t\tglVertex3f(0, 1, 0);\n\t\tglVertex3f(1, 0, 0);\n\tglEnd();\n\tangle += .02;\n\tglutSwapBuffers();\n}\n\nvoid set_shader()\n{\n\tconst char *f =\n\t\t\"varying float x, y, z;\"\n\t\t\"uniform float r_mod;\"\n\t\t\"float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }\"\n\t\t\"void main() {\"\n\t\t\"\tgl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);\"\n\t\t\"}\";\n\tconst char *v =\n\t\t\"varying float x, y, z;\"\n\t\t\"void main() {\"\n\t\t\"\tgl_Position = ftransform();\"\n\t\t\"\tx = gl_Position.x; y = gl_Position.y; z = gl_Position.z;\"\n\t\t\"\tx += y; y -= x; z += x - y;\"\n\t\t\"}\";\n\n\tvs = glCreateShader(GL_VERTEX_SHADER);\n\tps = glCreateShader(GL_FRAGMENT_SHADER);\n\tglShaderSource(ps, 1, &f, 0);\n\tglShaderSource(vs, 1, &v, 0);\n\n\tglCompileShader(vs);\n\tglCompileShader(ps);\n\n\tprog = glCreateProgram();\n\tglAttachShader(prog, ps);\n\tglAttachShader(prog, vs);\n\n\tglLinkProgram(prog);\n\tglUseProgram(prog);\n\tr_mod = glGetUniformLocation(prog, \"r_mod\");\n}\n\nint main(int argc, char **argv)\n{\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\tglutInitWindowSize(200, 200);\n\tglutCreateWindow(\"Stuff\");\n\tglutIdleFunc(render);\n\n\tglewInit();\n\tif (!glewIsSupported(\"GL_VERSION_2_0\")) {\n\t\tfprintf(stderr, \"GL 2.0 unsupported\\n\");\n\t\treturn 1;\n\t}\n\n\tset_shader();\n\tglutMainLoop();\n\n\treturn 0;\n}\n"}
{"id": 60643, "name": "Matrix digital rain", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n"}
{"id": 60644, "name": "Matrix digital rain", "Go": "package main\n\nimport (\n    gc \"github.com/rthornton128/goncurses\"\n    \"log\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\nconst rowDelay = 40000\n\nfunc main() {\n    start := time.Now()\n    rand.Seed(time.Now().UnixNano())\n\n    \n    chars := []byte(\"0123456789\")\n    totalChars := len(chars)\n\n    \n    stdscr, err := gc.Init()\n    if err != nil {\n        log.Fatal(\"init\", err)\n    }\n    defer gc.End()\n\n    gc.Echo(false)\n    gc.Cursor(0)\n\n    if !gc.HasColors() {\n        log.Fatal(\"Program requires a colour capable terminal\")\n    }\n\n    if err := gc.StartColor(); err != nil {\n        log.Fatal(err)\n    }\n\n    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {\n        log.Fatal(\"InitPair failed: \", err)\n    }\n    stdscr.ColorOn(1)\n    maxY, maxX := stdscr.MaxYX()\n\n    \n\n    \n    columnsRow := make([]int, maxX)\n\n    \n    \n    columnsActive := make([]int, maxX)\n\n    \n    for i := 0; i < maxX; i++ {\n        columnsRow[i] = -1\n        columnsActive[i] = 0\n    }\n\n    for {\n        for i := 0; i < maxX; i++ {\n            if columnsRow[i] == -1 {\n                \n                \n                columnsRow[i] = rand.Intn(maxY + 1)\n                columnsActive[i] = rand.Intn(2)\n            }\n        }\n\n        \n        for i := 0; i < maxX; i++ {\n            if columnsActive[i] == 1 {\n                \n                charIndex := rand.Intn(totalChars)\n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", chars[charIndex])\n            } else {\n                \n                stdscr.MovePrintf(columnsRow[i], i, \"%c\", ' ')\n            }\n\n            columnsRow[i]++\n\n            \n            if columnsRow[i] >= maxY {\n                columnsRow[i] = -1\n            }\n\n            \n            if rand.Intn(1001) == 0 {\n                if columnsActive[i] == 0 {\n                    columnsActive[i] = 1\n                } else {\n                    columnsActive[i] = 0\n                }\n            }\n        }\n        time.Sleep(rowDelay * time.Microsecond)\n        stdscr.Refresh()\n        elapsed := time.Since(start)\n        \n        if elapsed.Minutes() >= 1 {\n            break\n        }\n    }\n}\n", "C": "\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ncurses.h>\n\n\n#define ROW_DELAY 40000\n\n\nint get_rand_in_range(int min, int max)\n{\n  return (rand() % ((max + 1) - min) + min);\n}\n\nint main(void)\n{\n  \n  srand(time(NULL));\n\n  \n  char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n\n  int total_chars = sizeof(chars);\n\n  \n  initscr();\n  noecho();\n  curs_set(FALSE);\n\n  start_color();\n  init_pair(1, COLOR_GREEN, COLOR_BLACK);\n  attron(COLOR_PAIR(1));\n\n  int max_x = 0, max_y = 0;\n\n  getmaxyx(stdscr, max_y, max_x);\n\n  \n\n  \n  int columns_row[max_x];\n\n  \n  int columns_active[max_x];\n\n  int i;\n\n  \n  for (i = 0; i < max_x; i++)\n  {\n    columns_row[i] = -1;\n    columns_active[i] = 0;\n  }\n\n  while (1)\n  {\n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_row[i] == -1)\n      {\n        \n        columns_row[i] = get_rand_in_range(0, max_y);\n        columns_active[i] = get_rand_in_range(0, 1);\n      }\n    }\n\n    \n    for (i = 0; i < max_x; i++)\n    {\n      if (columns_active[i] == 1)\n      {\n        \n        int char_index = get_rand_in_range(0, total_chars);\n        mvprintw(columns_row[i], i, \"%c\", chars[char_index]);\n      }\n      else\n      {\n        \n        mvprintw(columns_row[i], i, \" \");\n      }\n\n      columns_row[i]++;\n\n      \n      if (columns_row[i] >= max_y)\n      {\n        columns_row[i] = -1;\n      }\n\n      \n      if (get_rand_in_range(0, 1000) == 0)\n      {\n        columns_active[i] = (columns_active[i] == 0) ? 1 : 0;\n      }\n    }\n\n    usleep(ROW_DELAY);\n    refresh();\n  }\n\n  endwin();\n  return 0;\n}\n"}
{"id": 60645, "name": "Audio overlap loop", "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    fileName := \"loop.wav\"\n    scanner := bufio.NewScanner(os.Stdin)\n    reps := 0\n    for reps < 1 || reps > 6 {\n        fmt.Print(\"Enter number of repetitions (1 to 6) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        reps, _ = strconv.Atoi(input)\n    }\n\n    delay := 0\n    for delay < 50 || delay > 500 {\n        fmt.Print(\"Enter delay between repetitions in microseconds (50 to 500) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        delay, _ = strconv.Atoi(input)\n    }\n\n    decay := 0.0\n    for decay < 0.2 || decay > 0.9 {\n        fmt.Print(\"Enter decay between repetitions (0.2 to 0.9) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        decay, _ = strconv.ParseFloat(input, 64)\n    }\n\n    args := []string{fileName, \"echo\", \"0.8\", \"0.7\"}\n    decay2 := 1.0    \n    for i := 1; i <= reps; i++ {\n        delayStr := strconv.Itoa(i * delay)\n        decay2 *= decay\n        decayStr := strconv.FormatFloat(decay2, 'f', -1, 64)        \n        args = append(args, delayStr, decayStr)        \n    }\n    cmd := exec.Command(\"play\", args...)    \n    err := cmd.Run()\n    check(err)\n}\n", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_overlap_loop.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60646, "name": "Audio overlap loop", "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    fileName := \"loop.wav\"\n    scanner := bufio.NewScanner(os.Stdin)\n    reps := 0\n    for reps < 1 || reps > 6 {\n        fmt.Print(\"Enter number of repetitions (1 to 6) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        reps, _ = strconv.Atoi(input)\n    }\n\n    delay := 0\n    for delay < 50 || delay > 500 {\n        fmt.Print(\"Enter delay between repetitions in microseconds (50 to 500) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        delay, _ = strconv.Atoi(input)\n    }\n\n    decay := 0.0\n    for decay < 0.2 || decay > 0.9 {\n        fmt.Print(\"Enter decay between repetitions (0.2 to 0.9) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        decay, _ = strconv.ParseFloat(input, 64)\n    }\n\n    args := []string{fileName, \"echo\", \"0.8\", \"0.7\"}\n    decay2 := 1.0    \n    for i := 1; i <= reps; i++ {\n        delayStr := strconv.Itoa(i * delay)\n        decay2 *= decay\n        decayStr := strconv.FormatFloat(decay2, 'f', -1, 64)        \n        args = append(args, delayStr, decayStr)        \n    }\n    cmd := exec.Command(\"play\", args...)    \n    err := cmd.Run()\n    check(err)\n}\n", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_play(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 5];\n    strcpy(command, \"play \");\n    strcat(command, args);\n    system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0) return C_getInput;\n            if (isStatic && strcmp(signature, \"play(_)\") == 0) return C_play;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"audio_overlap_loop.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60647, "name": "Knapsack problem_Unbounded", "Go": "package main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) / sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight / items[i].weight;\n    m2 = volume / items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value: %.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n"}
{"id": 60648, "name": "Mind boggling card trick", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n"}
{"id": 60649, "name": "Mind boggling card trick", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n"}
{"id": 60650, "name": "Mind boggling card trick", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    \n    var pack [52]byte\n    for i := 0; i < 26; i++ {\n        pack[i] = 'R'\n        pack[26+i] = 'B'\n    }\n    rand.Seed(time.Now().UnixNano())\n    rand.Shuffle(52, func(i, j int) {\n        pack[i], pack[j] = pack[j], pack[i]\n    })\n\n    \n    var red, black, discard []byte\n    for i := 0; i < 51; i += 2 {\n        switch pack[i] {\n        case 'B':\n            black = append(black, pack[i+1])\n        case 'R':\n            red = append(red, pack[i+1])\n        }\n        discard = append(discard, pack[i])\n    }\n    lr, lb, ld := len(red), len(black), len(discard)\n    fmt.Println(\"After dealing the cards the state of the stacks is:\")\n    fmt.Printf(\"  Red    : %2d cards -> %c\\n\", lr, red)\n    fmt.Printf(\"  Black  : %2d cards -> %c\\n\", lb, black)\n    fmt.Printf(\"  Discard: %2d cards -> %c\\n\", ld, discard)\n\n    \n    min := lr\n    if lb < min {\n        min = lb\n    }\n    n := 1 + rand.Intn(min)\n    rp := rand.Perm(lr)[:n]\n    bp := rand.Perm(lb)[:n]\n    fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n    fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n    fmt.Printf(\"  Red    : %2d\\n\", rp)\n    fmt.Printf(\"  Black  : %2d\\n\", bp)\n    for i := 0; i < n; i++ {\n        red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n    }\n    fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n    fmt.Printf(\"  Red    : %c\\n\", red)\n    fmt.Printf(\"  Black  : %c\\n\", black)\n\n    \n    \n    rcount, bcount := 0, 0\n    for _, c := range red {\n        if c == 'R' {\n            rcount++\n        }\n    }\n    for _, c := range black {\n        if c == 'B' {\n            bcount++\n        }\n    }\n\n    fmt.Println(\"\\nThe number of red cards in the red stack     =\", rcount)\n    fmt.Println(\"The number of black cards in the black stack =\", bcount)\n    if rcount == bcount {\n        fmt.Println(\"So the asssertion is correct!\")\n    } else {\n        fmt.Println(\"So the asssertion is incorrect!\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define SIM_N           5  \n#define PRINT_DISCARDED 1  \n\n#define min(x,y) ((x<y)?(x):(y))\n\ntypedef uint8_t card_t;\n\n\nunsigned int rand_n(unsigned int n) {\n    unsigned int out, mask = 1;\n    \n    while (mask < n) mask = mask<<1 | 1;\n    \n    do {\n        out = rand() & mask;\n    } while (out >= n);\n    return out;\n}\n\n\ncard_t rand_card() {\n    return rand_n(52);\n}\n\n\nvoid print_card(card_t card) {\n    static char *suits = \"HCDS\"; \n    static char *cards[] = {\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"};\n    printf(\" %s%c\", cards[card>>2], suits[card&3]);\n}\n\n\nvoid shuffle(card_t *pack) {\n    int card;\n    card_t temp, randpos;\n    for (card=0; card<52; card++) {\n        randpos = rand_card();\n        temp = pack[card];\n        pack[card] = pack[randpos];\n        pack[randpos] = temp;\n    }\n}\n\n\nint trick() {\n    card_t pack[52];\n    card_t blacks[52/4], reds[52/4];\n    card_t top, x, card;\n    int blackn=0, redn=0, blacksw=0, redsw=0, result;\n   \n    \n    for (card=0; card<52; card++) pack[card] = card;\n    shuffle(pack);\n    \n    \n#if PRINT_DISCARDED\n    printf(\"Discarded:\"); \n#endif\n    for (card=0; card<52; card += 2) {\n        top = pack[card]; \n        if (top & 1) { \n            blacks[blackn++] = pack[card+1];\n        } else {\n            reds[redn++] = pack[card+1];\n        }\n#if PRINT_DISCARDED\n        print_card(top); \n#endif\n    }\n#if PRINT_DISCARDED\n    printf(\"\\n\");\n#endif\n\n    \n    x = rand_n(min(blackn, redn));\n    for (card=0; card<x; card++) {\n        \n        blacksw = rand_n(blackn);\n        redsw = rand_n(redn); \n        \n        top = blacks[blacksw];\n        blacks[blacksw] = reds[redsw];\n        reds[redsw] = top;\n    }\n    \n    \n    result = 0;\n    for (card=0; card<blackn; card++)\n        result += (blacks[card] & 1) == 1;\n    for (card=0; card<redn; card++)\n        result -= (reds[card] & 1) == 0;\n    result = !result;\n    \n    printf(\"The number of black cards in the 'black' pile\"\n           \" %s the number of red cards in the 'red' pile.\\n\",\n           result? \"equals\" : \"does not equal\");\n    return result;\n}\n\nint main() {\n    unsigned int seed, i, successes = 0;\n    FILE *r;\n    \n    \n    if ((r = fopen(\"/dev/urandom\", \"r\")) == NULL) {\n        fprintf(stderr, \"cannot open /dev/urandom\\n\");\n        return 255;\n    }\n    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {\n        fprintf(stderr, \"failed to read from /dev/urandom\\n\");\n        return 255;\n    }\n    fclose(r);\n    srand(seed);\n    \n    \n    for (i=1; i<=SIM_N; i++) {\n        printf(\"Simulation %d\\n\", i);\n        successes += trick();\n        printf(\"\\n\");\n    }\n    \n    printf(\"Result: %d successes out of %d simulations\\n\",\n        successes, SIM_N);\n    \n    return 0;\n}\n"}
{"id": 60651, "name": "Textonyms", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n\n\n\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string \n\tletterMap map[rune]byte       \n\tcount     int                 \n\ttextonyms int                 \n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t\n\t\t\n\t\t\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nchar text_char(char c) {\n    switch (c) {\n    case 'a': case 'b': case 'c':\n        return '2';\n    case 'd': case 'e': case 'f':\n        return '3';\n    case 'g': case 'h': case 'i':\n        return '4';\n    case 'j': case 'k': case 'l':\n        return '5';\n    case 'm': case 'n': case 'o':\n        return '6';\n    case 'p': case 'q': case 'r': case 's':\n        return '7';\n    case 't': case 'u': case 'v':\n        return '8';\n    case 'w': case 'x': case 'y': case 'z':\n        return '9';\n    default:\n        return 0;\n    }\n}\n\nbool text_string(const GString* word, GString* text) {\n    g_string_set_size(text, word->len);\n    for (size_t i = 0; i < word->len; ++i) {\n        char c = text_char(g_ascii_tolower(word->str[i]));\n        if (c == 0)\n            return false;\n        text->str[i] = c;\n    }\n    return true;\n}\n\ntypedef struct textonym_tag {\n    const char* text;\n    size_t length;\n    GPtrArray* words;\n} textonym_t;\n\nint compare_by_text_length(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->length > t2->length)\n        return -1;\n    if (t1->length < t2->length)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nint compare_by_word_count(const void* p1, const void* p2) {\n    const textonym_t* t1 = p1;\n    const textonym_t* t2 = p2;\n    if (t1->words->len > t2->words->len)\n        return -1;\n    if (t1->words->len < t2->words->len)\n        return 1;\n    return strcmp(t1->text, t2->text);\n}\n\nvoid print_words(GPtrArray* words) {\n    for (guint i = 0, n = words->len; i < n; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%s\", g_ptr_array_index(words, i));\n    }\n    printf(\"\\n\");\n}\n\nvoid print_top_words(GArray* textonyms, guint top) {\n    for (guint i = 0; i < top; ++i) {\n        const textonym_t* t = &g_array_index(textonyms, textonym_t, i);\n        printf(\"%s = \", t->text);\n        print_words(t->words);\n    }\n}\n\nvoid free_strings(gpointer ptr) {\n    g_ptr_array_free(ptr, TRUE);\n}\n\nbool find_textonyms(const char* filename, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(filename, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return false;\n    }\n    GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,\n                                           g_free, free_strings);\n    GString* word = g_string_sized_new(64);\n    GString* text = g_string_sized_new(64);\n    guint count = 0;\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, word, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        g_string_truncate(word, term_pos);\n        if (!text_string(word, text))\n            continue;\n        GPtrArray* words = g_hash_table_lookup(ht, text->str);\n        if (words == NULL) {\n            words = g_ptr_array_new_full(1, g_free);\n            g_hash_table_insert(ht, g_strdup(text->str), words);\n        }\n        g_ptr_array_add(words, g_strdup(word->str));\n        ++count;\n    }\n    g_io_channel_unref(channel);\n    g_string_free(word, TRUE);\n    g_string_free(text, TRUE);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_hash_table_destroy(ht);\n        return false;\n    }\n\n    GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));\n    GHashTableIter iter;\n    gpointer key, value;\n    g_hash_table_iter_init(&iter, ht);\n    while (g_hash_table_iter_next(&iter, &key, &value)) {\n        GPtrArray* v = value;\n        if (v->len > 1) {\n            textonym_t textonym;\n            textonym.text = key;\n            textonym.length = strlen(key);\n            textonym.words = v;\n            g_array_append_val(words, textonym);\n        }\n    }\n\n    printf(\"There are %u words in '%s' which can be represented by the digit key mapping.\\n\",\n           count, filename);\n    guint size = g_hash_table_size(ht);\n    printf(\"They require %u digit combinations to represent them.\\n\", size);\n    guint textonyms = words->len;\n    printf(\"%u digit combinations represent Textonyms.\\n\", textonyms);\n\n    guint top = 5;\n    if (textonyms < top)\n        top = textonyms;\n\n    printf(\"\\nTop %u by number of words:\\n\", top);\n    g_array_sort(words, compare_by_word_count);\n    print_top_words(words, top);\n    \n    printf(\"\\nTop %u by length:\\n\", top);\n    g_array_sort(words, compare_by_text_length);\n    print_top_words(words, top);\n\n    g_array_free(words, TRUE);\n    g_hash_table_destroy(ht);\n    return true;\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s word-list\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    if (!find_textonyms(argv[1], &error)) {\n        if (error != NULL) {\n            fprintf(stderr, \"%s: %s\\n\", argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60652, "name": "Bitmap_Bézier curves_Quadratic", "Go": "package raster\n\nconst b2Seg = 20\n\nfunc (b *Bitmap) Bézier2(x1, y1, x2, y2, x3, y3 int, p Pixel) {\n    var px, py [b2Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    for i := range px {\n        c := float64(i) / b2Seg\n        a := 1 - c\n        a, b, c := a*a, 2 * c * a, c*c\n        px[i] = int(a*fx1 + b*fx2 + c*fx3)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b2Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) {\n    b.Bézier2(x1, y1, x2, y2, x3, y3, c.Pixel())\n}\n", "C": "void quad_bezier(\n        image img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 60653, "name": "Waveform analysis_Top and tail", "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    const sec = \"00:00:01\"\n    scanner := bufio.NewScanner(os.Stdin)\n    name := \"\"\n    for name == \"\" {\n        fmt.Print(\"Enter name of audio file to be trimmed : \")\n        scanner.Scan()\n        name = scanner.Text()\n        check(scanner.Err())\n    }\n\n    name2 := \"\"\n    for name2 == \"\" {\n        fmt.Print(\"Enter name of output file              : \")\n        scanner.Scan()\n        name2 = scanner.Text()\n        check(scanner.Err())\n    }    \n    \n    squelch := 0.0\n    for squelch < 1 || squelch > 10 {\n        fmt.Print(\"Enter squelch level % max (1 to 10)    : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        squelch, _ = strconv.ParseFloat(input, 64)\n    }\n    squelchS := strconv.FormatFloat(squelch, 'f', -1, 64) + \"%\"\n\n    tmp1 := \"tmp1_\" + name\n    tmp2 := \"tmp2_\" + name\n\n    \n    args := []string{name, tmp1, \"silence\", \"1\", sec, squelchS}\n    cmd := exec.Command(\"sox\", args...)\n    err := cmd.Run()\n    check(err) \n\n    \n    args = []string{tmp1, tmp2, \"reverse\"}     \n    cmd = exec.Command(\"sox\", args...)\n    err = cmd.Run()\n    check(err)\n\n    \n    args = []string{tmp2, tmp1, \"silence\", \"1\", sec, squelchS}\n    cmd  = exec.Command(\"sox\", args...)\n    err = cmd.Run()\n    check(err)\n\n    \n    args = []string{tmp1, name2, \"reverse\"}    \n    cmd = exec.Command(\"sox\", args...)\n    err = cmd.Run()\n    check(err)\n\n    \n    err = os.Remove(tmp1)\n    check(err)\n    err = os.Remove(tmp2)\n    check(err)\n}\n", "C": "#include <stdio.h>\n#include <stdio_ext.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\nvoid C_getInput(WrenVM* vm) {\n    int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;\n    char input[maxSize];\n    fgets(input, maxSize, stdin);\n    __fpurge(stdin);\n    input[strcspn(input, \"\\n\")] = 0;\n    wrenSetSlotString(vm, 0, (const char*)input);\n}\n\nvoid C_sox(WrenVM* vm) {\n    const char *args = wrenGetSlotString(vm, 1);\n    char command[strlen(args) + 4];\n    strcpy(command, \"sox \");\n    strcat(command, args);\n    system(command);\n}\n\nvoid C_removeFile(WrenVM* vm) {\n    const char *name = wrenGetSlotString(vm, 1);\n    if (remove(name) != 0) perror(\"Error deleting file.\");\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"C\") == 0) {\n            if (isStatic && strcmp(signature, \"getInput(_)\") == 0)   return C_getInput;\n            if (isStatic && strcmp(signature, \"sox(_)\") == 0)        return C_sox;\n            if (isStatic && strcmp(signature, \"removeFile(_)\") == 0) return C_removeFile;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"waveform_analysis_top_and_tail.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60654, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n"}
{"id": 60655, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n"}
{"id": 60656, "name": "A_ search algorithm", "Go": "\n\npackage astar\n\nimport \"container/heap\"\n\n\ntype Node interface {\n    To() []Arc               \n    Heuristic(from Node) int \n}\n\n\ntype Arc struct {\n    To   Node\n    Cost int\n}\n\n\ntype rNode struct {\n    n    Node\n    from Node\n    l    int \n    g    int \n    f    int \n    fx   int \n}\n\ntype openHeap []*rNode \n\n\n\n\n\n\n\nfunc Route(start, end Node) (route []Node, cost int) {\n    \n    cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}\n    \n    r := map[Node]*rNode{start: cr}\n    \n    \n    \n    oh := openHeap{cr}\n    for len(oh) > 0 {\n        bestRoute := heap.Pop(&oh).(*rNode)\n        bestNode := bestRoute.n\n        if bestNode == end {\n            \n            cost = bestRoute.g\n            route = make([]Node, bestRoute.l)\n            for i := len(route) - 1; i >= 0; i-- {\n                route[i] = bestRoute.n\n                bestRoute = r[bestRoute.from]\n            }\n            return\n        }\n        l := bestRoute.l + 1\n        for _, to := range bestNode.To() {\n            \n            g := bestRoute.g + to.Cost\n            if alt, ok := r[to.To]; !ok {\n                \n                alt = &rNode{n: to.To, from: bestNode, l: l,\n                    g: g, f: g + end.Heuristic(to.To)}\n                r[to.To] = alt\n                heap.Push(&oh, alt)\n            } else {\n                if g >= alt.g {\n                    continue \n                }\n                \n                \n                alt.from = bestNode\n                alt.l = l\n                alt.g = g\n                alt.f = end.Heuristic(alt.n)\n                if alt.fx < 0 {\n                    heap.Push(&oh, alt)\n                } else {\n                    heap.Fix(&oh, alt.fx)\n                }\n            }\n        }\n    }\n    return nil, 0\n}\n\n\nfunc (h openHeap) Len() int           { return len(h) }\nfunc (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }\nfunc (h openHeap) Swap(i, j int) {\n    h[i], h[j] = h[j], h[i]\n    h[i].fx = i\n    h[j].fx = j\n}\n\nfunc (p *openHeap) Push(x interface{}) {\n    h := *p\n    fx := len(h)\n    h = append(h, x.(*rNode))\n    h[fx].fx = fx\n    *p = h\n}\n\nfunc (p *openHeap) Pop() interface{} {\n    h := *p\n    last := len(h) - 1\n    *p = h[:last]\n    h[last].fx = -1\n    return h[last]\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n\n#include <iso646.h>\n\n#include <math.h>\n\n#define map_size_rows 10\n#define map_size_cols 10\n\nchar map[map_size_rows][map_size_cols] = {\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 1, 1, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 0, 0, 0, 1, 0, 1},\n    {1, 0, 0, 1, 1, 1, 1, 1, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},\n    {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n};\n\n\nstruct stop {\n    double col, row;\n    \n    int * n;\n    int n_len;\n    double f, g, h;\n    int from;\n};\n\nint ind[map_size_rows][map_size_cols] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n};\n\n\nstruct route {\n    \n    int x; \n    int y; \n    double d;\n};\n\nint main() {\n    int i, j, k, l, b, found;\n    int p_len = 0;\n    int * path = NULL;\n    int c_len = 0;\n    int * closed = NULL;\n    int o_len = 1;\n    int * open = (int*)calloc(o_len, sizeof(int));\n    double min, tempg;\n    int s;\n    int e;\n    int current;\n    int s_len = 0;\n    struct stop * stops = NULL;\n    int r_len = 0;\n    struct route * routes = NULL;\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (!map[i][j]) {\n                ++s_len;\n                stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));\n                int t = s_len - 1;\n                stops[t].col = j;\n                stops[t].row = i;\n                stops[t].from = -1;\n                stops[t].g = DBL_MAX;\n                stops[t].n_len = 0;\n                stops[t].n = NULL;\n                ind[i][j] = t;\n            }\n        }\n    }\n\n    \n    s = 0;\n    \n    e = s_len - 1;\n\n    for (i = 0; i < s_len; i++) {\n        stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));\n    }\n\n    for (i = 1; i < map_size_rows - 1; i++) {\n        for (j = 1; j < map_size_cols - 1; j++) {\n            if (ind[i][j] >= 0) {\n                for (k = i - 1; k <= i + 1; k++) {\n                    for (l = j - 1; l <= j + 1; l++) {\n                        if ((k == i) and (l == j)) {\n                            continue;\n                        }\n                        if (ind[k][l] >= 0) {\n                            ++r_len;\n                            routes = (struct route *)realloc(routes, r_len * sizeof(struct route));\n                            int t = r_len - 1;\n                            routes[t].x = ind[i][j];\n                            routes[t].y = ind[k][l];\n                            routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));\n                            ++stops[routes[t].x].n_len;\n                            stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));\n                            stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    open[0] = s;\n    stops[s].g = 0;\n    stops[s].f = stops[s].g + stops[s].h;\n    found = 0;\n\n    while (o_len and not found) {\n        min = DBL_MAX;\n\n        for (i = 0; i < o_len; i++) {\n            if (stops[open[i]].f < min) {\n                current = open[i];\n                min = stops[open[i]].f;\n            }\n        }\n\n        if (current == e) {\n            found = 1;\n\n            ++p_len;\n            path = (int*)realloc(path, p_len * sizeof(int));\n            path[p_len - 1] = current;\n            while (stops[current].from >= 0) {\n                current = stops[current].from;\n                ++p_len;\n                path = (int*)realloc(path, p_len * sizeof(int));\n                path[p_len - 1] = current;\n            }\n        }\n\n        for (i = 0; i < o_len; i++) {\n            if (open[i] == current) {\n                if (i not_eq (o_len - 1)) {\n                    for (j = i; j < (o_len - 1); j++) {\n                        open[j] = open[j + 1];\n                    }\n                }\n                --o_len;\n                open = (int*)realloc(open, o_len * sizeof(int));\n                break;\n            }\n        }\n\n        ++c_len;\n        closed = (int*)realloc(closed, c_len * sizeof(int));\n        closed[c_len - 1] = current;\n\n        for (i = 0; i < stops[current].n_len; i++) {\n            b = 0;\n\n            for (j = 0; j < c_len; j++) {\n                if (routes[stops[current].n[i]].y == closed[j]) {\n                    b = 1;\n                }\n            }\n\n            if (b) {\n                continue;\n            }\n\n            tempg = stops[current].g + routes[stops[current].n[i]].d;\n\n            b = 1;\n\n            if (o_len > 0) {\n                for (j = 0; j < o_len; j++) {\n                    if (routes[stops[current].n[i]].y == open[j]) {\n                        b = 0;\n                    }\n                }\n            }\n\n            if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {\n                stops[routes[stops[current].n[i]].y].from = current;\n                stops[routes[stops[current].n[i]].y].g = tempg;\n                stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;\n\n                if (b) {\n                    ++o_len;\n                    open = (int*)realloc(open, o_len * sizeof(int));\n                    open[o_len - 1] = routes[stops[current].n[i]].y;\n                }\n            }\n        }\n    }\n\n    for (i = 0; i < map_size_rows; i++) {\n        for (j = 0; j < map_size_cols; j++) {\n            if (map[i][j]) {\n                putchar(0xdb);\n            } else {\n                b = 0;\n                for (k = 0; k < p_len; k++) {\n                    if (ind[i][j] == path[k]) {\n                        ++b;\n                    }\n                }\n                if (b) {\n                    putchar('x');\n                } else {\n                    putchar('.');\n                }\n            }\n        }\n        putchar('\\n');\n    }\n\n    if (not found) {\n        puts(\"IMPOSSIBLE\");\n    } else {\n        printf(\"path cost is %d:\\n\", p_len);\n        for (i = p_len - 1; i >= 0; i--) {\n            printf(\"(%1.0f, %1.0f)\\n\", stops[path[i]].col, stops[path[i]].row);\n        }\n    }\n\n    for (i = 0; i < s_len; ++i) {\n        free(stops[i].n);\n    }\n    free(stops);\n    free(routes);\n    free(path);\n    free(open);\n    free(closed);\n\n    return 0;\n}\n"}
{"id": 60657, "name": "Teacup rim text", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc readWords(fileName string) []string {\n    file, err := os.Open(fileName)\n    check(err)\n    defer file.Close()\n    var words []string\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n        if len(word) >= 3 {\n            words = append(words, word)\n        }\n    }\n    check(scanner.Err())\n    return words\n}\n\nfunc rotate(runes []rune) {\n    first := runes[0]\n    copy(runes, runes[1:])\n    runes[len(runes)-1] = first\n}\n\nfunc main() {\n    dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} \n    for _, dict := range dicts {\n        fmt.Printf(\"Using %s:\\n\\n\", dict)\n        words := readWords(dict)\n        n := len(words)\n        used := make(map[string]bool)\n    outer:\n        for _, word := range words {\n            runes := []rune(word)\n            variants := []string{word}\n            for i := 0; i < len(runes)-1; i++ {\n                rotate(runes)\n                word2 := string(runes)\n                if word == word2 || used[word2] {\n                    continue outer\n                }\n                ix := sort.SearchStrings(words, word2)\n                if ix == n || words[ix] != word2 {\n                    continue outer\n                }\n                variants = append(variants, word2)\n            }\n            for _, variant := range variants {\n                used[variant] = true\n            }\n            fmt.Println(variants)\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\n\nint string_compare(gconstpointer p1, gconstpointer p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nGPtrArray* load_dictionary(const char* file, GError** error_ptr) {\n    GError* error = NULL;\n    GIOChannel* channel = g_io_channel_new_file(file, \"r\", &error);\n    if (channel == NULL) {\n        g_propagate_error(error_ptr, error);\n        return NULL;\n    }\n    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);\n    GString* line = g_string_sized_new(64);\n    gsize term_pos;\n    while (g_io_channel_read_line_string(channel, line, &term_pos,\n                                         &error) == G_IO_STATUS_NORMAL) {\n        char* word = g_strdup(line->str);\n        word[term_pos] = '\\0';\n        g_ptr_array_add(dict, word);\n    }\n    g_string_free(line, TRUE);\n    g_io_channel_unref(channel);\n    if (error != NULL) {\n        g_propagate_error(error_ptr, error);\n        g_ptr_array_free(dict, TRUE);\n        return NULL;\n    }\n    g_ptr_array_sort(dict, string_compare);\n    return dict;\n}\n\nvoid rotate(char* str, size_t len) {\n    char c = str[0];\n    memmove(str, str + 1, len - 1);\n    str[len - 1] = c;\n}\n\nchar* dictionary_search(const GPtrArray* dictionary, const char* word) {\n    char** result = bsearch(&word, dictionary->pdata, dictionary->len,\n                            sizeof(char*), string_compare);\n    return result != NULL ? *result : NULL;\n}\n\nvoid find_teacup_words(GPtrArray* dictionary) {\n    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);\n    GPtrArray* teacup_words = g_ptr_array_new();\n    GString* temp = g_string_sized_new(8);\n    for (size_t i = 0, n = dictionary->len; i < n; ++i) {\n        char* word = g_ptr_array_index(dictionary, i);\n        size_t len = strlen(word);\n        if (len < 3 || g_hash_table_contains(found, word))\n            continue;\n        g_ptr_array_set_size(teacup_words, 0);\n        g_string_assign(temp, word);\n        bool is_teacup_word = true;\n        for (size_t i = 0; i < len - 1; ++i) {\n            rotate(temp->str, len);\n            char* w = dictionary_search(dictionary, temp->str);\n            if (w == NULL) {\n                is_teacup_word = false;\n                break;\n            }\n            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))\n                g_ptr_array_add(teacup_words, w);\n        }\n        if (is_teacup_word && teacup_words->len > 0) {\n            printf(\"%s\", word);\n            g_hash_table_add(found, word);\n            for (size_t i = 0; i < teacup_words->len; ++i) {\n                char* teacup_word = g_ptr_array_index(teacup_words, i);\n                printf(\" %s\", teacup_word);\n                g_hash_table_add(found, teacup_word);\n            }\n            printf(\"\\n\");\n        }\n    }\n    g_string_free(temp, TRUE);\n    g_ptr_array_free(teacup_words, TRUE);\n    g_hash_table_destroy(found);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        fprintf(stderr, \"usage: %s dictionary\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n    GError* error = NULL;\n    GPtrArray* dictionary = load_dictionary(argv[1], &error);\n    if (dictionary == NULL) {\n        if (error != NULL) {\n            fprintf(stderr, \"Cannot load dictionary file '%s': %s\\n\",\n                    argv[1], error->message);\n            g_error_free(error);\n        }\n        return EXIT_FAILURE;\n    }\n    find_teacup_words(dictionary);\n    g_ptr_array_free(dictionary, TRUE);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60658, "name": "Increasing gaps between consecutive Niven numbers", "Go": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n    var ms is\n    ms = func() uint64 {\n        ms = newSum()\n        return ms()\n    }\n    var msd, d uint64\n    return func() uint64 {\n        if d < 9 {\n            d++\n        } else {\n            d = 0\n            msd = ms()\n        }\n        return msd + d\n    }\n}\n\nfunc newHarshard() is {\n    i := uint64(0)\n    sum := newSum()\n    return func() uint64 {\n        for i++; i%sum() != 0; i++ {\n        }\n        return i\n    }\n}\n\nfunc commatize(n uint64) 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(\"Gap    Index of gap   Starting Niven\")\n    fmt.Println(\"===   =============   ==============\")\n    h := newHarshard()\n    pg := uint64(0) \n    pn := h()       \n    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n        g := n - pn\n        if g > pg {\n            fmt.Printf(\"%3d   %13s   %14s\\n\", g, commatize(i), commatize(pn))\n            pg = g\n        }\n        pn = n\n    }\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n    ++sum;\n    while (n > 0 && n % 10 == 0) {\n        sum -= 9;\n        n /= 10;\n    }\n    return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n    if ((d & 1) == 0 && (n & 1) == 1)\n        return false;\n    return n % d == 0;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n\n    uint64_t previous = 1, gap = 0, sum = 0;\n    int niven_index = 0, gap_index = 1;\n\n    printf(\"Gap index  Gap    Niven index    Niven number\\n\");\n    for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n        sum = digit_sum(niven, sum);\n        if (divisible(niven, sum)) {\n            if (niven > previous + gap) {\n                gap = niven - previous;\n                printf(\"%'9d %'4llu %'14d %'15llu\\n\", gap_index++,\n                       gap, niven_index, previous);\n            }\n            previous = niven;\n            ++niven_index;\n        }\n    }\n    return 0;\n}\n"}
{"id": 60659, "name": "Print debugging statement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\ntype point struct {\n    x, y float64\n}\n\nfunc add(x, y int) int {\n    result := x + y\n    debug(\"x\", x)\n    debug(\"y\", y)\n    debug(\"result\", result)\n    debug(\"result+1\", result+1)\n    return result\n}\n\nfunc debug(s string, x interface{}) {\n    _, _, lineNo, _ := runtime.Caller(1)\n    fmt.Printf(\"%q at line %d type '%T'\\nvalue: %#v\\n\\n\", s, lineNo, x, x)\n}\n\nfunc main() {\n    add(2, 7)\n    b := true\n    debug(\"b\", b)\n    s := \"Hello\"\n    debug(\"s\", s)\n    p := point{2, 3}\n    debug(\"p\", p)\n    q := &p\n    debug(\"q\", q)\n}\n", "C": "#include <stdio.h>\n\n#define DEBUG_INT(x) printf( #x \" at line %d\\nresult: %d\\n\\n\", __LINE__, x)\n\nint add(int x, int y) {\n  int result = x + y;\n  DEBUG_INT(x);\n  DEBUG_INT(y);\n  DEBUG_INT(result);\n  DEBUG_INT(result+1);\n  return result;\n}\n\nint main() {\n  add(2, 7);\n  return 0;\n}\n"}
{"id": 60660, "name": "Find prime n such that reversed n is also prime", "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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n"}
{"id": 60661, "name": "Find prime n such that reversed n is also prime", "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    for i := 4; i < limit; i += 2 {\n        c[i] = 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 reversed(n int) int {\n    rev := 0\n    for n > 0 {\n        rev = rev*10 + n%10\n        n /= 10\n    }\n    return rev\n}\n\nfunc main() {\n    c := sieve(999)\n    reversedPrimes := []int{2}\n    for i := 3; i < 500; i += 2 {\n        if !c[i] && !c[reversed(i)] {\n            reversedPrimes = append(reversedPrimes, i)\n        }\n    }\n    fmt.Println(\"Primes under 500 which are also primes when the digits are reversed:\")\n    for i, p := range reversedPrimes {\n        fmt.Printf(\"%5d\", p)\n        if (i+1) % 10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such primes found.\\n\", len(reversedPrimes))\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\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 reverse(unsigned int n) {\n    unsigned int rev = 0;\n    for (; n > 0; n /= 10)\n        rev = rev * 10 + n % 10;\n    return rev;\n}\n\nint main() {\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < 500; ++n) {\n        if (is_prime(n) && is_prime(reverse(n)))\n            printf(\"%3u%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n    }\n    printf(\"\\nCount = %u\\n\", count);\n    return 0;\n}\n"}
{"id": 60662, "name": "Superellipse", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\n\nfunc superEllipse(dc *gg.Context, n float64, a int) {\n    hw := float64(dc.Width() / 2)\n    hh := float64(dc.Height() / 2)\n\n    \n    y := make([]float64, a+1)\n    for x := 0; x <= a; x++ {\n        aa := math.Pow(float64(a), n)\n        xx := math.Pow(float64(x), n)\n        y[x] = math.Pow(aa-xx, 1.0/n)\n    }\n\n    \n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw+float64(x), hh-y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw+float64(x), hh+y[x])\n    }\n    for x := a; x >= 0; x-- {\n        dc.LineTo(hw-float64(x), hh+y[x])\n    }\n    for x := 0; x <= a; x++ {\n        dc.LineTo(hw-float64(x), hh-y[x])\n    }\n\n    dc.SetRGB(1, 1, 1) \n    dc.Fill()\n}\n\nfunc main() {\n    dc := gg.NewContext(500, 500)\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    superEllipse(dc, 2.5, 200)\n    dc.SavePNG(\"superellipse.png\")\n}\n", "C": "#include<graphics.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main(){\n\t\n\tdouble a,b,n,i,incr = 0.0001;\n\t\n\tprintf(\"Enter major and minor axes of the SuperEllipse : \");\n\tscanf(\"%lf%lf\",&a,&b);\n\t\n\tprintf(\"Enter n : \");\n\tscanf(\"%lf\",&n);\n\t\n\tinitwindow(500,500,\"Superellipse\");\n\t\n\tfor(i=0;i<2*pi;i+=incr){\n\t\tputpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);\n\t}\n\t\n\tprintf(\"Done. %lf\",i);\n\t\n\tgetch();\n\t\n\tclosegraph();\n}\n"}
{"id": 60663, "name": "Permutations_Rank of a permutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n"}
{"id": 60664, "name": "Permutations_Rank of a permutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\n\nfunc MRPerm(q, n int) []int {\n    p := ident(n)\n    var r int\n    for n > 0 {\n        q, r = q/n, q%n\n        n--\n        p[n], p[r] = p[r], p[n]\n    }\n    return p\n}\n\n\nfunc ident(n int) []int {\n    p := make([]int, n)\n    for i := range p {\n        p[i] = i\n    }\n    return p\n}\n\n\nfunc MRRank(p []int) (r int) {\n    p = append([]int{}, p...)\n    inv := inverse(p)\n    for i := len(p) - 1; i > 0; i-- {\n        s := p[i]\n        p[inv[i]] = s\n        inv[s] = inv[i]\n    }\n    for i := 1; i < len(p); i++ {\n        r = r*(i+1) + p[i]\n    }\n    return\n}\n\n\nfunc inverse(p []int) []int {\n    r := make([]int, len(p))\n    for i, x := range p {\n        r[x] = i\n    }\n    return r\n}\n\n\nfunc fact(n int) (f int) {\n    for f = n; n > 2; {\n        n--\n        f *= n\n    }\n    return\n}\n\nfunc main() {\n    n := 3\n    fmt.Println(\"permutations of\", n, \"items\")\n    f := fact(n)\n    for i := 0; i < f; i++ {\n        p := MRPerm(i, n)\n        fmt.Println(i, p, MRRank(p))\n    }\n    n = 12\n    fmt.Println(\"permutations of\", n, \"items\")\n    f = fact(n)\n    m := map[int]bool{}\n    for len(m) < 4 {\n        r := rand.Intn(f)\n        if m[r] {\n            continue\n        }\n        m[r] = true\n        fmt.Println(r, MRPerm(r, n))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)\n\nvoid _mr_unrank1(int rank, int n, int *vec) {\n    int t, q, r;\n    if (n < 1) return;\n\n    q = rank / n;\n    r = rank % n;\n    SWAP(vec[r], vec[n-1]);\n    _mr_unrank1(q, n-1, vec);\n}\n\nint _mr_rank1(int n, int *vec, int *inv) {\n    int s, t;\n    if (n < 2) return 0;\n\n    s = vec[n-1];\n    SWAP(vec[n-1], vec[inv[n-1]]);\n    SWAP(inv[s], inv[n-1]);\n    return s + n * _mr_rank1(n-1, vec, inv);\n}\n\n\nvoid get_permutation(int rank, int n, int *vec) {\n    int i;\n    for (i = 0; i < n; ++i) vec[i] = i;\n    _mr_unrank1(rank, n, vec);\n}\n\n\nint get_rank(int n, int *vec) {\n    int i, r, *v, *inv;\n\n    v = malloc(n * sizeof(int));\n    inv = malloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        v[i] = vec[i];\n        inv[vec[i]] = i;\n    }\n    r = _mr_rank1(n, v, inv);\n    free(inv);\n    free(v);\n    return r;\n}\n\nint main(int argc, char *argv[]) {\n    int i, r, tv[4];\n\n    for (r = 0; r < 24; ++r) {\n        printf(\"%3d: \", r);\n        get_permutation(r, 4, tv);\n\n        for (i = 0; i < 4; ++i) {\n            if (0 == i) printf(\"[ \");\n            else printf(\", \");\n            printf(\"%d\", tv[i]);\n        }\n        printf(\" ] = %d\\n\", get_rank(4, tv));\n    }\n}\n"}
{"id": 60665, "name": "Banker's algorithm", "Go": "package bank\n\nimport (\n    \"bytes\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n    \"sort\"\n    \"sync\"\n)\n\ntype PID string\ntype RID string\ntype RMap map[RID]int\n\n\nfunc (m RMap) String() string {\n    rs := make([]string, len(m))\n    i := 0\n    for r := range m {\n        rs[i] = string(r)\n        i++\n    }\n    sort.Strings(rs)\n    var b bytes.Buffer\n    b.WriteString(\"{\")\n    for _, r := range rs {\n        fmt.Fprintf(&b, \"%q: %d, \", r, m[RID(r)])\n    }\n    bb := b.Bytes()\n    if len(bb) > 1 {\n        bb[len(bb)-2] = '}'\n    }\n    return string(bb)\n}\n\ntype Bank struct {\n    available  RMap\n    max        map[PID]RMap\n    allocation map[PID]RMap\n    sync.Mutex\n}\n\nfunc (b *Bank) need(p PID, r RID) int {\n    return b.max[p][r] - b.allocation[p][r]\n}\n\nfunc New(available RMap) (b *Bank, err error) {\n    for r, a := range available {\n        if a < 0 {\n            return nil, fmt.Errorf(\"negative resource %s: %d\", r, a)\n        }\n    }\n    return &Bank{\n        available:  available,\n        max:        map[PID]RMap{},\n        allocation: map[PID]RMap{},\n    }, nil\n}\n\nfunc (b *Bank) NewProcess(p PID, max RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[p]; ok {\n        return fmt.Errorf(\"process %s already registered\", p)\n    }\n    for r, m := range max {\n        switch a, ok := b.available[r]; {\n        case !ok:\n            return fmt.Errorf(\"resource %s unknown\", r)\n        case m > a:\n            return fmt.Errorf(\"resource %s: process %s max %d > available %d\",\n                r, p, m, a)\n        }\n    }\n    b.max[p] = max\n    b.allocation[p] = RMap{}\n    return\n}\n\nfunc (b *Bank) Request(pid PID, change RMap) (err error) {\n    b.Lock()\n    defer b.Unlock()\n    if _, ok := b.max[pid]; !ok {\n        return fmt.Errorf(\"process %s unknown\", pid)\n    }\n    for r, c := range change {\n        if c < 0 {\n            return errors.New(\"decrease not allowed\")\n        }\n        if _, ok := b.available[r]; !ok {\n            return fmt.Errorf(\"resource %s unknown\", r)\n        }\n        if c > b.need(pid, r) {\n            return errors.New(\"increase exceeds declared max\")\n        }\n    }\n    \n    \n    for r, c := range change {\n        b.allocation[pid][r] += c \n    }\n    defer func() {\n        if err != nil { \n            for r, c := range change {\n                b.allocation[pid][r] -= c \n            }\n        }\n    }()\n    \n    \n    cash := RMap{}\n    for r, a := range b.available {\n        cash[r] = a\n    }\n    perm := make([]PID, len(b.allocation))\n    i := 1\n    for pr, a := range b.allocation {\n        if pr == pid {\n            perm[0] = pr\n        } else {\n            perm[i] = pr\n            i++\n        }\n        for r, a := range a {\n            cash[r] -= a\n        }\n    }\n    ret := RMap{}  \n    m := len(perm) \n    for {\n        \n        h := 0\n    h:\n        for ; ; h++ {\n            if h == m {\n                \n                return errors.New(\"request would make deadlock possible\")\n            }\n            for r := range b.available {\n                if b.need(perm[h], r) > cash[r]+ret[r] {\n                    \n                    continue h\n                }\n            }\n            \n            log.Println(\" \", perm[h], \"could terminate\")\n            \n            break\n        }\n        if h == 0 { \n            \n            \n            return nil\n        }\n        for r, a := range b.allocation[perm[h]] {\n            ret[r] += a\n        }\n        m--\n        perm[h] = perm[m]\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint main() {\n    int curr[5][5];\n    int max_claim[5][5];\n    int avl[5];\n    int alloc[5] = {0, 0, 0, 0, 0};\n    int max_res[5];\n    int running[5];\n\n    int i, j, exec, r, p;\n    int count = 0;\n    bool safe = false;\n\n    printf(\"\\nEnter the number of resources: \");\n    scanf(\"%d\", &r);\n\n    printf(\"\\nEnter the number of processes: \");\n    scanf(\"%d\", &p);\n    for (i = 0; i < p; i++) {\n        running[i] = 1;\n        count++;\n    }\n\n    printf(\"\\nEnter Claim Vector: \");\n    for (i = 0; i < r; i++)\n        scanf(\"%d\", &max_res[i]);\n\n    printf(\"\\nEnter Allocated Resource Table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &curr[i][j]);\n    }\n\n    printf(\"\\nEnter Maximum Claim table: \");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            scanf(\"%d\", &max_claim[i][j]);\n    }\n\n    printf(\"\\nThe Claim Vector is: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", max_res[i]);\n\n    printf(\"\\nThe Allocated Resource Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", curr[i][j]);\n        printf(\"\\n\");\n    }\n\n    printf(\"\\nThe Maximum Claim Table:\\n\");\n    for (i = 0; i < p; i++) {\n        for (j = 0; j < r; j++)\n            printf(\"\\t%d\", max_claim[i][j]);\n        printf(\"\\n\");\n    }\n\n    for (i = 0; i < p; i++)\n        for (j = 0; j < r; j++)\n            alloc[j] += curr[i][j];\n\n    printf(\"\\nAllocated resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", alloc[i]);\n    for (i = 0; i < r; i++)\n        avl[i] = max_res[i] - alloc[i];\n\n    printf(\"\\nAvailable resources: \");\n    for (i = 0; i < r; i++)\n        printf(\"%d \", avl[i]);\n    printf(\"\\n\");\n\n    while (count != 0) {\n        safe = false;\n        for (i = 0; i < p; i++) {\n            if (running[i]) {\n                exec = 1;\n                for (j = 0; j < r; j++) {\n                    if (max_claim[i][j] - curr[i][j] > avl[j]) {\n                        exec = 0;\n                        break;\n                    }\n                }\n\n                if (exec) {\n                    printf(\"\\nProcess%d is executing.\\n\", i + 1);\n                    running[i] = 0;\n                    count--;\n                    safe = true;\n                    for (j = 0; j < r; j++)\n                        avl[j] += curr[i][j];\n                    break;\n                }\n            }\n        }\n\n        if (!safe) {\n            printf(\"\\nThe processes are in unsafe state.\");\n            break;\n        }\n\n        if (safe)\n            printf(\"\\nThe process is in safe state.\");\n\n        printf(\"\\nAvailable vector: \");\n        for (i = 0; i < r; i++)\n            printf(\"%d \", avl[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 60666, "name": "Range extraction", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    rf, err := rangeFormat([]int{\n        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n        37, 38, 39,\n    })\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n    if len(a) == 0 {\n        return \"\", nil\n    }\n    var parts []string\n    for n1 := 0; ; {\n        n2 := n1 + 1\n        for n2 < len(a) && a[n2] == a[n2-1]+1 {\n            n2++\n        }\n        s := strconv.Itoa(a[n1])\n        if n2 == n1+2 {\n            s += \",\" + strconv.Itoa(a[n2-1])\n        } else if n2 > n1+2 {\n            s += \"-\" + strconv.Itoa(a[n2-1])\n        }\n        parts = append(parts, s)\n        if n2 == len(a) {\n            break\n        }\n        if a[n2] == a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence repeats value %d\", a[n2]))\n        }\n        if a[n2] < a[n2-1] {\n            return \"\", errors.New(fmt.Sprintf(\n                \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n        }\n        n1 = n2\n    }\n    return strings.Join(parts, \",\"), nil\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t rprint(char *s, int *x, int len)\n{\n#define sep (a > s ? \",\" : \"\") \n#define ol (s ? 100 : 0)       \n\tint i, j;\n\tchar *a = s;\n\tfor (i = j = 0; i < len; i = ++j) {\n\t\tfor (; j < len - 1 && x[j + 1] == x[j] + 1; j++);\n\n\t\tif (i + 1 < j)\n\t\t\ta += snprintf(s?a:s, ol, \"%s%d-%d\", sep, x[i], x[j]);\n\t\telse\n\t\t\twhile (i <= j)\n\t\t\t\ta += snprintf(s?a:s, ol, \"%s%d\", sep, x[i++]);\n\t}\n\treturn a - s;\n#undef sep\n#undef ol\n}\n\nint main()\n{\n\tint x[] = {\t0,  1,  2,  4,  6,  7,  8, 11, 12, 14,\n\t\t\t15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t\t\t25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t\t\t37, 38, 39 };\n\n\tchar *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);\n\trprint(s, x, sizeof(x) / sizeof(int));\n\tprintf(\"%s\\n\", s);\n\n\treturn 0;\n}\n"}
{"id": 60667, "name": "Machine code", "Go": "package main\n\nimport \"fmt\"\n\n\nimport \"C\"\n\nfunc main() {\n    code := []byte{\n        0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,\n        0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,\n        0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,\n        0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,\n    }\n    le := len(code)\n    buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,\n        C.MAP_PRIVATE|C.MAP_ANON, -1, 0)\n    codePtr := C.CBytes(code)\n    C.memcpy(buf, codePtr, C.size_t(le))\n    var a, b byte = 7, 12\n    fmt.Printf(\"%d + %d = \", a, b)\n    C.runMachineCode(buf, C.byte(a), C.byte(b))\n    C.munmap(buf, C.size_t(le))\n    C.free(codePtr)\n}\n", "C": "#include <stdio.h>\n#include <sys/mman.h>\n#include <string.h>\n\nint test (int a, int b)\n{\n  \n  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};\n  void *buf;\n  int c;\n  \n  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,\n             MAP_PRIVATE|MAP_ANON,-1,0);\n\n  memcpy (buf, code, sizeof(code));\n  \n  c = ((int (*) (int, int))buf)(a, b);\n  \n  munmap (buf, sizeof(code));\n  return c;\n}\n\nint main ()\n{\n  printf(\"%d\\n\", test(7,12));\n  return 0;\n}\n"}
{"id": 60668, "name": "Type detection", "Go": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc showType(a any) {\n    switch a.(type) {\n    case rune:\n        fmt.Printf(\"The type of '%c' is %T\\n\", a, a)\n    default:\n        fmt.Printf(\"The type of '%v' is %T\\n\", a, a)\n    }\n}\n\nfunc main() {\n    values := []any{5, 7.5, 2 + 3i, 'd', true, \"Rosetta\"}\n    for _, value := range values {\n        showType(value)\n    }\n}\n", "C": "#include<stdio.h>\n#include<ctype.h>\n\nvoid typeDetector(char* str){\t\n\tif(isalnum(str[0])!=0)\n\t\tprintf(\"\\n%c is alphanumeric\",str[0]);\n\tif(isalpha(str[0])!=0)\n\t\tprintf(\"\\n%c is alphabetic\",str[0]);\n\tif(iscntrl(str[0])!=0)\n\t\tprintf(\"\\n%c is a control character\",str[0]);\n\tif(isdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a digit\",str[0]);\n\tif(isprint(str[0])!=0)\n\t\tprintf(\"\\n%c is printable\",str[0]);\n\tif(ispunct(str[0])!=0)\n\t\tprintf(\"\\n%c is a punctuation character\",str[0]);\n\tif(isxdigit(str[0])!=0)\n\t\tprintf(\"\\n%c is a hexadecimal digit\",str[0]);\n}\n\nint main(int argC, char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by ASCII characters>\");\n\telse{\n\t\tfor(i=1;i<argC;i++)\n\t\t\ttypeDetector(argV[i]);\n\t}\n\treturn 0;\n}\n"}
{"id": 60669, "name": "Maximum triangle path sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nconst t = `               55\n                        94 48\n                       95 30 96\n                     77 71 26 67\n                    97 13 76 38 45\n                  07 36 79 16 37 68\n                 48 07 09 18 70 26 06\n               18 72 79 46 59 79 29 90\n              20 76 87 11 32 07 07 49 18\n            27 83 58 35 71 11 25 57 29 85\n           14 64 36 96 27 11 58 56 92 18 55\n         02 90 03 60 48 49 41 46 33 36 47 23\n        92 50 48 02 36 59 42 79 72 20 82 77 42\n      56 78 38 80 39 75 02 71 66 66 01 03 55 72\n     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n    lines := strings.Split(t, \"\\n\")\n    f := strings.Fields(lines[len(lines)-1])\n    d := make([]int, len(f))\n    var err error\n    for i, s := range f {\n        if d[i], err = strconv.Atoi(s); err != nil {\n            panic(err)\n        }\n    }\n    d1 := d[1:]\n    var l, r, u int\n    for row := len(lines) - 2; row >= 0; row-- {\n        l = d[0]\n        for i, s := range strings.Fields(lines[row]) {\n            if u, err = strconv.Atoi(s); err != nil {\n                panic(err)\n            }\n            if r = d1[i]; l > r {\n                d[i] = u + l\n            } else {\n                d[i] = u + r\n            }\n            l = r\n        }\n    }\n    fmt.Println(d[0])\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define max(x,y)  ((x) > (y) ? (x) : (y))\n\nint tri[] = {\n        55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n};\n\nint main(void)\n{\n    const int len  = sizeof(tri) / sizeof(tri[0]);\n    const int base = (sqrt(8*len + 1) - 1) / 2;\n    int step       = base - 1;\n    int stepc      = 0;\n\n    int i;\n    for (i = len - base - 1; i >= 0; --i) {\n        tri[i] += max(tri[i + step], tri[i + step + 1]);\n        if (++stepc == step) {\n            step--;\n            stepc = 0;\n        }\n    }\n\n    printf(\"%d\\n\", tri[0]);\n    return 0;\n}\n"}
{"id": 60670, "name": "Zhang-Suen thinning algorithm", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n    b := wbFromString(in, '1')\n    b.zhangSuen()\n    fmt.Println(b)\n}\n\nconst (\n    white = 0\n    black = 1\n)\n\ntype wbArray [][]byte \n\n\n\n\nfunc wbFromString(s string, blk byte) wbArray {\n    lines := strings.Split(s, \"\\n\")[1:]\n    b := make(wbArray, len(lines))\n    for i, sl := range lines {\n        bl := make([]byte, len(sl))\n        for j := 0; j < len(sl); j++ {\n            bl[j] = sl[j] & 1\n        }\n        b[i] = bl\n    }\n    return b\n}\n\n\n\nvar sym = [2]byte{\n    white: ' ',\n    black: '#',\n}\n\nfunc (b wbArray) String() string {\n    b2 := bytes.Join(b, []byte{'\\n'})\n    for i, b1 := range b2 {\n        if b1 > 1 {\n            continue\n        }\n        b2[i] = sym[b1]\n    }\n    return string(b2)\n}\n\n\nvar nb = [...][2]int{\n    2: {-1, 0}, \n    3: {-1, 1}, \n    4: {0, 1},\n    5: {1, 1},\n    6: {1, 0},\n    7: {1, -1},\n    8: {0, -1},\n    9: {-1, -1}, \n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n    var r, c int\n    var p [10]byte\n\n    readP := func() {\n        for nx := 1; nx <= 9; nx++ {\n            n := nb[nx]\n            p[nx] = b[r+n[0]][c+n[1]]\n        }\n    }\n\n    shiftRead := func() {\n        n := nb[3]\n        p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n        n = nb[4]\n        p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n        n = nb[5]\n        p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n    }\n\n    \n    \n    countA := func() (ct byte) {\n        bit := p[9]\n        for nx := 2; nx <= 9; nx++ {\n            last := bit\n            bit = p[nx]\n            if last == white {\n                ct += bit\n            }\n        }\n        return ct\n    }\n\n    \n    countB := func() (ct byte) {\n        for nx := 2; nx <= 9; nx++ {\n            ct += p[nx]\n        }\n        return ct\n    }\n\n    lastRow := len(b) - 1\n    lastCol := len(b[0]) - 1\n\n    mark := make([][]bool, lastRow)\n    for r = range mark {\n        mark[r] = make([]bool, lastCol)\n    }\n\n    for r = 1; r < lastRow; r++ {\n        c = 1\n        readP()\n        for { \n            m := false\n            \n            if !(p[1] == black) {\n                goto markDone\n            }\n            if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n                goto markDone\n            }\n            if !(countA() == 1) {\n                goto markDone\n            }\n            {\n                e1, e2 := p[en[1]], p[en[2]]\n                if !(p[en[0]]&e1&e2 == 0) {\n                    goto markDone\n                }\n                if !(e1&e2&p[en[3]] == 0) {\n                    goto markDone\n                }\n            }\n            \n            m = true\n            rs = true \n        markDone:\n            mark[r][c] = m\n            c++\n            if c == lastCol {\n                break\n            }\n            shiftRead()\n        }\n    }\n    if rs {\n        for r = 1; r < lastRow; r++ {\n            for c = 1; c < lastCol; c++ {\n                if mark[r][c] {\n                    b[r][c] = white\n                }\n            }\n        }\n    }\n    return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n    for {\n        rs1 := b.reset(step1)\n        rs2 := b.reset(step2)\n        if !rs1 && !rs2 {\n            break\n        }\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nchar** imageMatrix;\n\nchar blankPixel,imagePixel;\n\ntypedef struct{\n\tint row,col;\n}pixel;\n\nint getBlackNeighbours(int row,int col){\n\t\n\tint i,j,sum = 0;\n\t\n\tfor(i=-1;i<=1;i++){\n\t\tfor(j=-1;j<=1;j++){\n\t\t\tif(i!=0 || j!=0)\n\t\t\t\tsum+= (imageMatrix[row+i][col+j]==imagePixel);\n\t\t}\n\t}\n\t\n\treturn sum;\n}\n\nint getBWTransitions(int row,int col){\n\treturn \t((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)\n\t\t\t+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));\n}\n\nint zhangSuenTest1(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) \n\t\t&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));\n}\n\nint zhangSuenTest2(int row,int col){\n\tint neighbours = getBlackNeighbours(row,col);\n\t\n\treturn ((neighbours>=2 && neighbours<=6) \n\t\t&& (getBWTransitions(row,col)==1) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) \n\t\t&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));\n}\n\nvoid zhangSuen(char* inputFile, char* outputFile){\n\t\n\tint startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;\n\t\n\tpixel* markers;\n\t\n\tFILE* inputP = fopen(inputFile,\"r\");\n\t\n\tfscanf(inputP,\"%d%d\",&rows,&cols);\n\t\n\tfscanf(inputP,\"%d%d\",&blankPixel,&imagePixel);\n\t\n\tblankPixel<=9?blankPixel+='0':blankPixel;\n\timagePixel<=9?imagePixel+='0':imagePixel;\n\t\n\tprintf(\"\\nPrinting original image :\\n\");\n\t\n\timageMatrix = (char**)malloc(rows*sizeof(char*));\n\t\n\tfor(i=0;i<rows;i++){\n\t\timageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));\n\t\tfscanf(inputP,\"%s\\n\",imageMatrix[i]);\n\t\tprintf(\"\\n%s\",imageMatrix[i]);\n\t\t\n\t}\n\n\tfclose(inputP);\n\t\n\tendRow = rows-2;\n\tendCol = cols-2;\n\tdo{\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t\tmarkers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));\n\t\tcount = 0;\n\t\t\n\t\tfor(i=startRow;i<=endRow;i++){\n\t\t\tfor(j=startCol;j<=endCol;j++){\n\t\t\t\tif(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){\n\t\t\t\t\tmarkers[count].row = i;\n\t\t\t\t\tmarkers[count].col = j;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(processed==0)\n\t\t\tprocessed = (count>0);\n\t\t\n\t\tfor(i=0;i<count;i++){\n\t\t\timageMatrix[markers[i].row][markers[i].col] = blankPixel;\n\t\t}\n\t\t\n\t\tfree(markers);\n\t}while(processed==1);\n\t\n\tFILE* outputP = fopen(outputFile,\"w\");\n\t\n\tprintf(\"\\n\\n\\nPrinting image after applying Zhang Suen Thinning Algorithm : \\n\\n\\n\");\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<cols;j++){\n\t\t\tprintf(\"%c\",imageMatrix[i][j]);\n\t\t\tfprintf(outputP,\"%c\",imageMatrix[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfprintf(outputP,\"\\n\");\n\t}\n\t\n\tfclose(outputP);\n\t\n\tprintf(\"\\nImage also written to : %s\",outputFile);\n}\n\nint main()\n{\n\tchar inputFile[100],outputFile[100];\n\t\n\tprintf(\"Enter full path of input image file : \");\n\tscanf(\"%s\",inputFile);\n\t\n\tprintf(\"Enter full path of output image file : \");\n\tscanf(\"%s\",outputFile);\n\t\n\tzhangSuen(inputFile,outputFile);\n\t\n\treturn 0;\n}\n"}
{"id": 60671, "name": "Median filter", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"fmt\"\n    \"raster\"\n)\n\nvar g0, g1 *raster.Grmap\nvar ko [][]int\nvar kc []uint16\nvar mid int\n\nfunc init() {\n    \n    ko = [][]int{\n        {-1, -1}, {0, -1}, {1, -1},\n        {-1,  0}, {0,  0}, {1,  0},\n        {-1,  1}, {0,  1}, {1,  1}}\n    kc = make([]uint16, len(ko))\n    mid = len(ko) / 2\n}\n\nfunc main() {\n    \n    \n    \n    \n    \n    b, err := raster.ReadPpmFile(\"Lenna50.ppm\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    g0 = b.Grmap()\n    w, h := g0.Extent()\n    g1 = raster.NewGrmap(w, h)\n    for y := 0; y < h; y++ {\n        for x := 0; x < w; x++ {\n            g1.SetPx(x, y, median(x, y))\n        }\n    }\n    \n    \n    err = g1.Bitmap().WritePpmFile(\"median.ppm\")\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc median(x, y int) uint16 {\n    var n int\n    \n    \n    \n    for _, o := range ko {\n        \n        c, ok := g0.GetPx(x+o[0], y+o[1])\n        if !ok {\n            continue\n        }\n        \n        var i int\n        for ; i < n; i++ {\n            if c < kc[i] {\n                for j := n; j > i; j-- {\n                    kc[j] = kc[j-1]\n                }\n                break\n            }\n        }\n        kc[i] = c\n        n++\n    }\n    \n    switch {\n    case n == len(kc): \n        return kc[mid]\n    case n%2 == 1: \n        return kc[n/2]\n    }\n    \n    m := n / 2\n    return (kc[m-1] + kc[m]) / 2\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef struct { unsigned char r, g, b; } rgb_t;\ntypedef struct {\n\tint w, h;\n\trgb_t **pix;\n} image_t, *image;\n\ntypedef struct {\n\tint r[256], g[256], b[256];\n\tint n;\n} color_histo_t;\n\nint write_ppm(image im, char *fn)\n{\n\tFILE *fp = fopen(fn, \"w\");\n\tif (!fp) return 0;\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", im->w, im->h);\n\tfwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);\n\tfclose(fp);\n\treturn 1;\n}\n\nimage img_new(int w, int h)\n{\n\tint i;\n\timage im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)\n\t\t\t+ sizeof(rgb_t) * w * h);\n\tim->w = w; im->h = h;\n\tim->pix = (rgb_t**)(im + 1);\n\tfor (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)\n\t\tim->pix[i] = im->pix[i - 1] + w;\n\treturn im;\n}\n\nint read_num(FILE *f)\n{\n\tint n;\n\twhile (!fscanf(f, \"%d \", &n)) {\n\t\tif ((n = fgetc(f)) == '#') {\n\t\t\twhile ((n = fgetc(f)) != '\\n')\n\t\t\t\tif (n == EOF) break;\n\t\t\tif (n == '\\n') continue;\n\t\t} else return 0;\n\t}\n\treturn n;\n}\n\nimage read_ppm(char *fn)\n{\n\tFILE *fp = fopen(fn, \"r\");\n\tint w, h, maxval;\n\timage im = 0;\n\tif (!fp) return 0;\n\n\tif (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))\n\t\tgoto bail;\n\n\tw = read_num(fp);\n\th = read_num(fp);\n\tmaxval = read_num(fp);\n\tif (!w || !h || !maxval) goto bail;\n\n\tim = img_new(w, h);\n\tfread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);\nbail:\n\tif (fp) fclose(fp);\n\treturn im;\n}\n\nvoid del_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]--;\n\t\th->g[pix->g]--;\n\t\th->b[pix->b]--;\n\t\th->n--;\n\t}\n}\n\nvoid add_pixels(image im, int row, int col, int size, color_histo_t *h)\n{\n\tint i;\n\trgb_t *pix;\n\n\tif (col < 0 || col >= im->w) return;\n\tfor (i = row - size; i <= row + size && i < im->h; i++) {\n\t\tif (i < 0) continue;\n\t\tpix = im->pix[i] + col;\n\t\th->r[pix->r]++;\n\t\th->g[pix->g]++;\n\t\th->b[pix->b]++;\n\t\th->n++;\n\t}\n}\n\nvoid init_histo(image im, int row, int size, color_histo_t*h)\n{\n\tint j;\n\n\tmemset(h, 0, sizeof(color_histo_t));\n\n\tfor (j = 0; j < size && j < im->w; j++)\n\t\tadd_pixels(im, row, j, size, h);\n}\n\nint median(const int *x, int n)\n{\n\tint i;\n\tfor (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);\n\treturn i;\n}\n\nvoid median_color(rgb_t *pix, const color_histo_t *h)\n{\n\tpix->r = median(h->r, h->n);\n\tpix->g = median(h->g, h->n);\n\tpix->b = median(h->b, h->n);\n}\n\nimage median_filter(image in, int size)\n{\n\tint row, col;\n\timage out = img_new(in->w, in->h);\n\tcolor_histo_t h;\n\n\tfor (row = 0; row < in->h; row ++) {\n\t\tfor (col = 0; col < in->w; col++) {\n\t\t\tif (!col) init_histo(in, row, size, &h);\n\t\t\telse {\n\t\t\t\tdel_pixels(in, row, col - size, size, &h);\n\t\t\t\tadd_pixels(in, row, col + size, size, &h);\n\t\t\t}\n\t\t\tmedian_color(out->pix[row] + col, &h);\n\t\t}\n\t}\n\n\treturn out;\n}\n\nint main(int c, char **v)\n{\n\tint size;\n\timage in, out;\n\tif (c <= 3) {\n\t\tprintf(\"Usage: %s size ppm_in ppm_out\\n\", v[0]);\n\t\treturn 0;\n\t}\n\tsize = atoi(v[1]);\n\tprintf(\"filter size %d\\n\", size);\n\tif (size < 0) size = 1;\n\n\tin = read_ppm(v[2]);\n\tout = median_filter(in, size);\n\twrite_ppm(out, v[3]);\n\tfree(in);\n\tfree(out);\n\n\treturn 0;\n}\n"}
{"id": 60672, "name": "Run as a daemon or service", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n"}
{"id": 60673, "name": "Run as a daemon or service", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/sevlyar/go-daemon\"\n    \"log\"\n    \"os\"\n    \"time\"\n)\n\nfunc work() {\n    f, err := os.Create(\"daemon_output.txt\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    ticker := time.NewTicker(time.Second)\n    go func() {\n        for t := range ticker.C {\n            fmt.Fprintln(f, t) \n        }\n    }()\n    time.Sleep(60 * time.Second) \n    ticker.Stop()\n    log.Print(\"ticker stopped\")\n}\n\nfunc main() {\n    cntxt := &daemon.Context{\n        PidFileName: \"pid\",\n        PidFilePerm: 0644,\n        LogFileName: \"log\",\n        LogFilePerm: 0640,\n        WorkDir:     \"./\",\n        Umask:       027,\n        Args:        []string{\"[Rosetta Code daemon example]\"},\n    }\n\n    d, err := cntxt.Reborn()\n    if err != nil {\n        log.Fatal(\"Unable to run: \", err)\n    }\n    if d != nil {\n        return\n    }\n    defer cntxt.Release()\n\n    log.Print(\"- - - - - - - - - - - - - - -\")\n    log.Print(\"daemon started\")\n\n    work()\n}\n", "C": "#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n\textern char *__progname;\n\ttime_t clock;\n\tint fd;\n\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"usage: %s file\\n\", __progname);\n\t\texit(1);\n\t}\n\n\t\n\tfd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);\n\tif (fd < 0)\n\t\terr(1, argv[1]);\n\n\t\n\tif (daemon(0, 0) < 0)\n\t\terr(1, \"daemon\");\n\n\t\n\tif (dup2(fd, STDOUT_FILENO) < 0) {\n\t\tsyslog(LOG_ERR, \"dup2: %s\", strerror(errno));\n\t\texit(1);\n\t}\n\tclose(fd);\n\n\t\n\tfor (;;) {\n\t\ttime(&clock);\n\t\tfputs(ctime(&clock), stdout);\n\t\tif (fflush(stdout) == EOF) {\n\t\t\tsyslog(LOG_ERR, \"%s: %s\", argv[1], strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tsleep(1);\t\n\t}\n}\n"}
{"id": 60674, "name": "Compiler_Verifying syntax", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/parser\"\n    \"regexp\"\n    \"strings\"\n)\n\nvar (\n    re1 = regexp.MustCompile(`[^_a-zA-Z0-9\\+\\-\\*/=<\\(\\)\\s]`)\n    re2 = regexp.MustCompile(`\\b_\\w*\\b`)\n    re3 = regexp.MustCompile(`[=<+*/-]\\s*not`)\n    re4 = regexp.MustCompile(`(=|<)\\s*[^(=< ]+\\s*([=<+*/-])`)\n)\n\nvar subs = [][2]string{\n    {\"=\", \"==\"}, {\" not \", \" ! \"}, {\"(not \", \"(! \"}, {\" or \", \" || \"}, {\" and \", \" && \"},\n}\n\nfunc possiblyValid(expr string) error {\n    matches := re1.FindStringSubmatch(expr)\n    if matches != nil {\n        return fmt.Errorf(\"invalid character %q found\", []rune(matches[0])[0])\n    }\n    if re2.MatchString(expr) {\n        return fmt.Errorf(\"identifier cannot begin with an underscore\")\n    }\n    if re3.MatchString(expr) {\n        return fmt.Errorf(\"expected operand, found 'not'\")\n    }\n    matches = re4.FindStringSubmatch(expr)\n    if matches != nil {\n        return fmt.Errorf(\"operator %q is non-associative\", []rune(matches[1])[0])\n    }\n    return nil\n}\n\nfunc modify(err error) string {\n    e := err.Error()\n    for _, sub := range subs {\n        e = strings.ReplaceAll(e, strings.TrimSpace(sub[1]), strings.TrimSpace(sub[0]))\n    }\n    return strings.Split(e, \":\")[2][1:] \n}\n\nfunc main() {\n    exprs := []string{\n        \"$\",\n        \"one\",\n        \"either or both\",\n        \"a + 1\",\n        \"a + b < c\",\n        \"a = b\",\n        \"a or b = c\",\n        \"3 + not 5\",\n        \"3 + (not 5)\",\n        \"(42 + 3\",\n        \"(42 + 3)\",\n        \" not 3 < 4 or (true or 3 /  4 + 8 *  5 - 5 * 2 < 56) and 4 * 3  < 12 or not true\",\n        \" and 3 < 2\",\n        \"not 7 < 2\",\n        \"2 < 3 < 4\",\n        \"2 < (3 < 4)\",\n        \"2 < foobar - 3 < 4\",\n        \"2 < foobar and 3 < 4\",\n        \"4 * (32 - 16) + 9 = 73\",\n        \"235 76 + 1\",\n        \"true or false = not true\",\n        \"true or false = (not true)\",\n        \"not true or false = false\",\n        \"not true = false\",\n        \"a + b = not c and false\",\n        \"a + b = (not c) and false\",\n        \"a + b = (not c and false)\",\n        \"ab_c / bd2 or < e_f7\",\n        \"g not = h\",\n        \"été = false\",\n        \"i++\",\n        \"j & k\",\n        \"l or _m\",\n    } \n   \n    for _, expr := range exprs {\n        fmt.Printf(\"Statement to verify: %q\\n\", expr)\n        if err := possiblyValid(expr); err != nil {\n            fmt.Printf(\"\\\"false\\\" -> %s\\n\\n\", err.Error())\n            continue\n        }\n        expr = fmt.Sprintf(\" %s \", expr) \n        for _, sub := range subs {\n            expr = strings.ReplaceAll(expr, sub[0], sub[1])\n        }\n        _, err := parser.ParseExpr(expr)\n        if err != nil {\n            fmt.Println(`\"false\" ->`, modify(err))\n        } else {\n            fmt.Println(`\"true\"`)\n        }\n        fmt.Println()\n    }\n}\n", "C": "\n\n\n\n\n#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <setjmp.h>\n\n#define AT(CHAR) ( *pos == CHAR && ++pos )\n#define TEST(STR) ( strncmp( pos, STR, strlen(STR) ) == 0 \\\n  && ! isalnum(pos[strlen(STR)]) && pos[strlen(STR)] != '_' )\n#define IS(STR) ( TEST(STR) && (pos += strlen(STR)) )\n\nstatic char *pos;                                 \nstatic char *startpos;                            \nstatic jmp_buf jmpenv;\n\nstatic int\nerror(char *message)\n  {\n  printf(\"false  %s\\n%*s^ %s\\n\", startpos, pos - startpos + 7, \"\", message);\n  longjmp( jmpenv, 1 );\n  }\n\nstatic int\nexpr(int level)\n  {\n  while( isspace(*pos) ) ++pos;                     \n  if( AT('(') )                                     \n    {\n    if( expr(0) && ! AT(')') ) error(\"missing close paren\");\n    }\n  else if( level <= 4 && IS(\"not\") && expr(6) ) { }\n  else if( TEST(\"or\") || TEST(\"and\") || TEST(\"not\") )\n    {\n    error(\"expected a primary, found an operator\");\n    }\n  else if( isdigit(*pos) ) pos += strspn( pos, \"0123456789\" );\n  else if( isalpha(*pos) ) pos += strspn( pos, \"0123456789_\"\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" );\n  else error(\"expected a primary\");\n\n  do                    \n    {\n    while( isspace(*pos) ) ++pos;\n    }\n  while(\n    level <= 2 && IS(\"or\") ? expr(3) :\n    level <= 3 && IS(\"and\") ? expr(4) :\n    level <= 4 && (AT('=') || AT('<')) ? expr(5) :\n    level == 5 && (*pos == '=' || *pos == '<') ? error(\"non-associative\") :\n    level <= 6 && (AT('+') || AT('-')) ? expr(7) :\n    level <= 7 && (AT('*') || AT('/')) ? expr(8) :\n    0 );\n  return 1;\n  }\n\nstatic void\nparse(char *source)\n  {\n  startpos = pos = source;\n  if( setjmp(jmpenv) ) return; \n  expr(0);\n  if( *pos ) error(\"unexpected character following valid parse\");\n  printf(\" true  %s\\n\", source);\n  }\n\nstatic char *tests[] = {\n  \"3 + not 5\",\n  \"3 + (not 5)\",\n  \"(42 + 3\",\n  \"(42 + 3 some_other_syntax_error\",\n  \"not 3 < 4 or (true or 3/4+8*5-5*2 < 56) and 4*3 < 12 or not true\",\n  \"and 3 < 2\",\n  \"not 7 < 2\",\n  \"2 < 3 < 4\",\n  \"2 < foobar - 3 < 4\",\n  \"2 < foobar and 3 < 4\",\n  \"4 * (32 - 16) + 9 = 73\",\n  \"235 76 + 1\",\n  \"a + b = not c and false\",\n  \"a + b = (not c) and false\",\n  \"a + b = (not c and false)\",\n  \"ab_c / bd2 or < e_f7\",\n  \"g not = h\",\n  \"i++\",\n  \"j & k\",\n  \"l or _m\",\n  \"wombat\",\n  \"WOMBAT or monotreme\",\n  \"a + b - c * d / e < f and not ( g = h )\",\n  \"$\",\n  };\n\nint\nmain(int argc, char *argv[])\n  {\n  for( int i = 0; i < sizeof(tests)/sizeof(*tests); i++ ) parse(tests[i]);\n  }\n"}
{"id": 60675, "name": "Coprime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n"}
{"id": 60676, "name": "Coprime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n"}
{"id": 60677, "name": "Coprime triplets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc contains(a []int, v int) bool {\n    for _, e := range a {\n        if e == v {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    const limit = 50\n    cpt := []int{1, 2}\n    for {\n        m := 1\n        l := len(cpt)\n        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {\n            m++\n        }\n        if m >= limit {\n            break\n        }\n        cpt = append(cpt, m)\n    }\n    fmt.Printf(\"Coprime triplets under %d:\\n\", limit)\n    for i, t := range cpt {\n        fmt.Printf(\"%2d \", t)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\nFound %d such numbers\\n\", len(cpt))\n}\n", "C": "\n\n\n#include <stdio.h>\n\nint Gcd(int v1, int v2)\n{\n\t\n\tint a, b, r;\n\tif (v1 < v2)\n\t{\n\t\ta = v2;\n\t\tb = v1;\n\t}\n\telse\n\t{\n\t\ta = v1;\n\t\tb = v2;\n\t}\n\tdo\n\t{\n\t\tr = a % b;\n\t\tif (r == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = b;\n\t\t\tb = r;\n\t\t}\n\t} while (1 == 1);\n\treturn b;\n}\n\nint NotInList(int num, int numtrip, int *tripletslist)\n{\n\t\n\tfor (int i = 0; i < numtrip; i++)\n\t{\n\t\tif (num == tripletslist[i])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n} \t\n\nint main()\n{\n\tint coprime[50];\n\tint gcd1, gcd2;\n\tint ntrip = 2;\n\tint n = 3;\n\t\n\t\n\tcoprime[0] = 1;\n\tcoprime[1] = 2;\n\n\twhile ( n < 50)\n\t{\n\t\tgcd1 = Gcd(n, coprime[ntrip-1]);\n\t\tgcd2 = Gcd(n, coprime[ntrip-2]);\n\t\t\n\t\tif (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))\n\t\t{\n\t\t\tcoprime[ntrip++] = n;\n\t\t\t\n\t\t\tn = 3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tn++;\n\t\t}\n\t}\n\t\n\t\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < ntrip; i++)\n\t{\n\t\tprintf(\"%2d \", coprime[i]);\n\t\tif ((i+1) % 10 == 0)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tprintf(\"\\n\\nNumber of elements in coprime triplets: %d\\n\\n\", ntrip);\n\t\n\treturn 0;\n}\n"}
{"id": 60678, "name": "Variable declaration reset", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := []int{1, 2, 2, 3, 4, 4, 5}\n\n    \n    \n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        var prev int\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n\n    \n    \n    var prev int\n    for i := 0; i < len(s); i++ {\n        curr := s[i]\n        if i > 0 && curr == prev {\n            fmt.Println(i)\n        }\n        prev = curr\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n    int i, gprev = 0;\n    int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n    \n    for (i = 0; i < 7; ++i) {\n\n        int curr = s[i];\n        int prev = 0;\n\n        if (i > 0 && curr == prev) printf(\"%d\\n\", i);\n        prev = curr;\n    }\n\n    \n    for (i = 0; i < 7; ++i) {\n        int curr = s[i];\n        if (i > 0 && curr == gprev) printf(\"%d\\n\", i);\n        gprev = curr;\n    }\n\n    return 0;\n}\n"}
{"id": 60679, "name": "SOAP", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/tiaguinho/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \n    soap, err := gosoap.SoapClient(\"http:\n\n    \n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \n    fmt.Println(\"Country Code  : \", rv.CountryCode)\n    fmt.Println(\"Vat Number    : \", rv.VatNumber)\n    fmt.Println(\"Request Date  : \", rv.RequestDate)\n    fmt.Println(\"Valid         : \", rv.Valid)\n    fmt.Println(\"Name          : \", rv.Name)\n    fmt.Println(\"Address       : \", rv.Address)\n}\n", "C": "#include <curl/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage : %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n"}
{"id": 60680, "name": "Pragmatic directives", "Go": "\n", "C": "\n#include<stdio.h> \n\n\n#define Hi printf(\"Hi There.\");\n\n\n\n#define start int main(){\n#define end return 0;}\n\nstart\n\nHi\n\n\n#warning \"Don't you have anything better to do ?\"\n\n#ifdef __unix__\n#warning \"What are you doing still working on Unix ?\"\nprintf(\"\\nThis is an Unix system.\");\n#elif _WIN32\n#warning \"You couldn't afford a 64 bit ?\"\nprintf(\"\\nThis is a 32 bit Windows system.\");\n#elif _WIN64\n#warning \"You couldn't afford an Apple ?\"\nprintf(\"\\nThis is a 64 bit Windows system.\");\n#endif\n\nend\n\n\n"}
{"id": 60681, "name": "Find first and last set bit of a long integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60682, "name": "Find first and last set bit of a long integer", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nconst (\n    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota\n    mask1, bit1\n    mask2, bit2\n    mask3, bit3\n    mask4, bit4\n    mask5, bit5\n)\n\nfunc rupb(x uint64) (out int) {\n    if x == 0 {\n        return -1\n    }\n    if x&^mask5 != 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&^mask4 != 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&^mask3 != 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&^mask2 != 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&^mask1 != 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&^mask0 != 0 {\n        out |= bit0\n    }\n    return\n}\n\nfunc rlwb(x uint64) (out int) {\n    if x == 0 {\n        return 0\n    }\n    if x&mask5 == 0 {\n        x >>= bit5\n        out |= bit5\n    }\n    if x&mask4 == 0 {\n        x >>= bit4\n        out |= bit4\n    }\n    if x&mask3 == 0 {\n        x >>= bit3\n        out |= bit3\n    }\n    if x&mask2 == 0 {\n        x >>= bit2\n        out |= bit2\n    }\n    if x&mask1 == 0 {\n        x >>= bit1\n        out |= bit1\n    }\n    if x&mask0 == 0 {\n        out |= bit0\n    }\n    return\n}\n\n\n\n\n\nfunc rupbBig(x *big.Int) int {\n    return x.BitLen() - 1\n}\n\n\n\n\nfunc rlwbBig(x *big.Int) int {\n    if x.BitLen() < 2 {\n        return 0\n    }\n    bit := uint(1)\n    mask := big.NewInt(1)\n    var ms []*big.Int\n    var y, z big.Int\n    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {\n        ms = append(ms, mask)\n        mask = new(big.Int).Or(mask, &z)\n        bit <<= 1\n    }\n    out := bit\n    for i := len(ms) - 1; i >= 0; i-- {\n        bit >>= 1\n        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {\n            out |= bit\n        }\n    }\n    return int(out)\n}\n\nfunc main() {\n    show()\n    showBig()\n}\n\nfunc show() {\n    fmt.Println(\"uint64:\")\n    fmt.Println(\"power              number  rupb  rlwb\")\n    const base = 42\n    n := uint64(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %19d %5d %5d\\n\", base, i, n, rupb(n), rlwb(n))\n        n *= base\n    }\n}\n\nfunc showBig() {\n    fmt.Println(\"\\nbig numbers:\")\n    fmt.Println(\"  power                               number  rupb  rlwb\")\n    base := big.NewInt(1302)\n    n := big.NewInt(1)\n    for i := 0; i < 12; i++ {\n        fmt.Printf(\"%d^%02d %36d %5d %5d\\n\", base, i, n, rupbBig(n), rlwbBig(n))\n        n.Mul(n, base)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint32_t msb32(uint32_t n)\n{\n\tuint32_t b = 1;\n\tif (!n) return 0;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\nint msb32_idx(uint32_t n)\n{\n\tint b = 0;\n\tif (!n) return -1;\n\n#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x\n\tstep(16); step(8); step(4); step(2); step(1);\n#undef step\n\treturn b;\n}\n\n#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )\n\n\ninline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }\n\nint main()\n{\n\tint32_t n;\n\tint i;\n\n\tfor (i = 0, n = 1; ; i++, n *= 42) {\n\t\tprintf(\"42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\\n\",\n\t\t\ti, n, n,\n\t\t\tmsb32(n), msb32_idx(n),\n\t\t\tlsb32(n), lsb32_idx(n));\n\n\t\tif (n >= INT32_MAX / 42) break;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60683, "name": "Numbers with equal rises and falls", "Go": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n    if n < 10 {\n        return true\n    }\n    rises := 0\n    falls := 0\n    prev := -1\n    for n > 0 {\n        d := n % 10\n        if prev >= 0 {\n            if d < prev {\n                rises = rises + 1\n            } else if d > prev {\n                falls = falls + 1\n            }\n        }\n        prev = d\n        n /= 10   \n    }\n    return rises == falls\n}\n\nfunc main() {\n    fmt.Println(\"The first 200 numbers in the sequence are:\")\n    count := 0\n    n := 1\n    for {\n        if risesEqualsFalls(n) {\n            count++\n            if count <= 200 {\n                fmt.Printf(\"%3d \", n)\n                if count%20 == 0 {\n                    fmt.Println()\n                }\n            }\n            if count == 1e7 {\n                fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n                break\n            }\n        }\n        n++\n    }\n}\n", "C": "#include <stdio.h>\n\n\nint riseEqFall(int num) {\n    int rdigit = num % 10;\n    int netHeight = 0;\n    while (num /= 10) {\n        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);\n        rdigit = num % 10;\n    }\n    return netHeight == 0;\n}\n\n\nint nextNum() {\n    static int num = 0;\n    do {num++;} while (!riseEqFall(num));\n    return num;\n}\n\nint main(void) {\n    int total, num;\n    \n    \n    printf(\"The first 200 numbers are: \\n\");\n    for (total = 0; total < 200; total++)\n        printf(\"%d \", nextNum());\n    \n    \n    printf(\"\\n\\nThe 10,000,000th number is: \");\n    for (; total < 10000000; total++) num = nextNum();\n    printf(\"%d\\n\", num);\n    \n    return 0;\n}\n"}
{"id": 60684, "name": "Terminal control_Cursor movement", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc main() {\n    tput(\"clear\") \n    tput(\"cup\", \"6\", \"3\") \n    time.Sleep(1 * time.Second)\n    tput(\"cub1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuf1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cuu1\") \n    time.Sleep(1 * time.Second)\n    \n    tput(\"cud\", \"1\") \n    time.Sleep(1 * time.Second)\n    tput(\"cr\") \n    time.Sleep(1 * time.Second)\n    \n    var h, w int\n    cmd := exec.Command(\"stty\", \"size\")\n    cmd.Stdin = os.Stdin\n    d, _ := cmd.Output()\n    fmt.Sscan(string(d), &h, &w)\n    \n    tput(\"hpa\", strconv.Itoa(w-1))\n    time.Sleep(2 * time.Second)\n    \n    tput(\"home\")\n    time.Sleep(2 * time.Second)\n    \n    tput(\"cup\", strconv.Itoa(h-1), strconv.Itoa(w-1))\n    time.Sleep(3 * time.Second)\n}\n\nfunc tput(args ...string) error {\n    cmd := exec.Command(\"tput\", args...)\n    cmd.Stdout = os.Stdout\n    return cmd.Run()\n}\n", "C": "#include<conio.h>\n#include<dos.h>\n\nchar *strings[] = {\"The cursor will move one position to the left\", \n  \t\t   \"The cursor will move one position to the right\",\n \t\t   \"The cursor will move vetically up one line\", \n \t\t   \"The cursor will move vertically down one line\", \n \t\t   \"The cursor will move to the beginning of the line\", \n \t\t   \"The cursor will move to the end of the line\", \n \t\t   \"The cursor will move to the top left corner of the screen\", \n \t\t   \"The cursor will move to the bottom right corner of the screen\"};\n \t\t             \nint main()\n{\n\tint i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\t\n\tclrscr();\n\tcprintf(\"This is a demonstration of cursor control using gotoxy(). Press any key to continue.\");\n\tgetch();\n\t\n\tfor(i=0;i<8;i++)\n\t{\n\t\tclrscr();\n\t\tgotoxy(5,MAXROW/2);\n\t\t\n\t\tcprintf(\"%s\",strings[i]);\n\t\tgetch();\n\t\t\n\t\tswitch(i){\n\t\t\tcase 0:gotoxy(wherex()-1,wherey());\n\t\t\tbreak;\n\t\t\tcase 1:gotoxy(wherex()+1,wherey());\n\t\t\tbreak;\n\t\t\tcase 2:gotoxy(wherex(),wherey()-1);\n\t\t\tbreak;\n\t\t\tcase 3:gotoxy(wherex(),wherey()+1);\n\t\t\tbreak;\n\t\t\tcase 4:for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()-1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 5:gotoxy(wherex()-strlen(strings[i]),wherey());\n\t\t\t       for(j=0;j<strlen(strings[i]);j++){\n\t\t\t\t   gotoxy(wherex()+1,wherey());\n\t\t\t\t   delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 6:while(wherex()!=1)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()-1,wherey());\n\t\t\t\t     delay(100);\n\t\t               }\n\t\t\t       while(wherey()!=1)\n\t\t\t       {\n\t\t\t             gotoxy(wherex(),wherey()-1);\n\t\t\t             delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\tcase 7:while(wherex()!=MAXCOL)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex()+1,wherey());\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\t       while(wherey()!=MAXROW)\n\t\t\t       {\n\t\t\t\t     gotoxy(wherex(),wherey()+1);\n\t\t\t\t     delay(100);\n\t\t\t       }\n\t\t\tbreak;\n\t\t\t};\n\t\t\tgetch();\n\t}\n\t\n\tclrscr();\n\tcprintf(\"End of demonstration.\");\n\tgetch();\n\treturn 0;\n}\n"}
{"id": 60685, "name": "Simulated annealing", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nvar (\n    dists = calcDists()\n    dirs  = [8]int{1, -1, 10, -10, 9, 11, -11, -9} \n)\n\n\nfunc calcDists() []float64 {\n    dists := make([]float64, 10000)\n    for i := 0; i < 10000; i++ {\n        ab, cd := math.Floor(float64(i)/100), float64(i%100)\n        a, b := math.Floor(ab/10), float64(int(ab)%10)\n        c, d := math.Floor(cd/10), float64(int(cd)%10)\n        dists[i] = math.Hypot(a-c, b-d)\n    }\n    return dists\n}\n\n\nfunc dist(ci, cj int) float64 {\n    return dists[cj*100+ci]\n}\n\n\nfunc Es(path []int) float64 {\n    d := 0.0\n    for i := 0; i < len(path)-1; i++ {\n        d += dist(path[i], path[i+1])\n    }\n    return d\n}\n\n\nfunc T(k, kmax, kT int) float64 {\n    return (1 - float64(k)/float64(kmax)) * float64(kT)\n}\n\n\nfunc dE(s []int, u, v int) float64 {\n    su, sv := s[u], s[v]\n    \n    a, b, c, d := dist(s[u-1], su), dist(s[u+1], su), dist(s[v-1], sv), dist(s[v+1], sv)\n    \n    na, nb, nc, nd := dist(s[u-1], sv), dist(s[u+1], sv), dist(s[v-1], su), dist(s[v+1], su)\n    if v == u+1 {\n        return (na + nd) - (a + d)\n    } else if u == v+1 {\n        return (nc + nb) - (c + b)\n    } else {\n        return (na + nb + nc + nd) - (a + b + c + d)\n    }\n}\n\n\nfunc P(deltaE float64, k, kmax, kT int) float64 {\n    return math.Exp(-deltaE / T(k, kmax, kT))\n}\n\nfunc sa(kmax, kT int) {\n    rand.Seed(time.Now().UnixNano())\n    temp := make([]int, 99)\n    for i := 0; i < 99; i++ {\n        temp[i] = i + 1\n    }\n    rand.Shuffle(len(temp), func(i, j int) {\n        temp[i], temp[j] = temp[j], temp[i]\n    })\n    s := make([]int, 101) \n    copy(s[1:], temp)     \n    fmt.Println(\"kT =\", kT)\n    fmt.Printf(\"E(s0) %f\\n\\n\", Es(s)) \n    Emin := Es(s)                     \n    for k := 0; k <= kmax; k++ {\n        if k%(kmax/10) == 0 {\n            fmt.Printf(\"k:%10d   T: %8.4f   Es: %8.4f\\n\", k, T(k, kmax, kT), Es(s))\n        }\n        u := 1 + rand.Intn(99)          \n        cv := s[u] + dirs[rand.Intn(8)] \n        if cv <= 0 || cv >= 100 {       \n            continue\n        }\n        if dist(s[u], cv) > 5 { \n            continue\n        }\n        v := s[cv] \n        deltae := dE(s, u, v)\n        if deltae < 0 || \n            P(deltae, k, kmax, kT) >= rand.Float64() {\n            s[u], s[v] = s[v], s[u]\n            Emin += deltae\n        }\n    }\n    fmt.Printf(\"\\nE(s_final) %f\\n\", Emin)\n    fmt.Println(\"Path:\")\n    \n    for i := 0; i < len(s); i++ {\n        if i > 0 && i%10 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"%4d\", s[i])\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    sa(1e6, 1)\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <unistd.h>\n\n#define VECSZ 100\n#define STATESZ 64\n\ntypedef float floating_pt;\n#define EXP expf\n#define SQRT sqrtf\n\nstatic floating_pt\nrandnum (void)\n{\n  return (floating_pt)\n    ((double) (random () & 2147483647) / 2147483648.0);\n}\n\nstatic void\nshuffle (uint8_t vec[], size_t i, size_t n)\n{\n  \n  for (size_t j = 0; j != n; j += 1)\n    {\n      size_t k = i + j + (random () % (n - j));\n      uint8_t xi = vec[i];\n      uint8_t xk = vec[k];\n      vec[i] = xk;\n      vec[k] = xi;\n    }\n}\n\nstatic void\ninit_s (uint8_t vec[VECSZ])\n{\n  for (uint8_t j = 0; j != VECSZ; j += 1)\n    vec[j] = j;\n  shuffle (vec, 1, VECSZ - 1);\n}\n\nstatic inline void\nadd_neighbor (uint8_t neigh[8],\n              unsigned int *neigh_size,\n              uint8_t neighbor)\n{\n  if (neighbor != 0)\n    {\n      neigh[*neigh_size] = neighbor;\n      *neigh_size += 1;\n    }\n}\n\nstatic void\nneighborhood (uint8_t neigh[8],\n              unsigned int *neigh_size,\n              uint8_t city)\n{\n  \n\n  const uint8_t i = city / 10;\n  const uint8_t j = city % 10;\n\n  uint8_t c0 = 0;\n  uint8_t c1 = 0;\n  uint8_t c2 = 0;\n  uint8_t c3 = 0;\n  uint8_t c4 = 0;\n  uint8_t c5 = 0;\n  uint8_t c6 = 0;\n  uint8_t c7 = 0;\n\n  if (i < 9)\n    {\n      c0 = (10 * (i + 1)) + j;\n      if (j < 9)\n        c1 = (10 * (i + 1)) + (j + 1);\n      if (0 < j)\n        c2 = (10 * (i + 1)) + (j - 1);\n    }\n  if (0 < i)\n    {\n      c3 = (10 * (i - 1)) + j;\n      if (j < 9)\n        c4 = (10 * (i - 1)) + (j + 1);\n      if (0 < j)\n        c5 = (10 * (i - 1)) + (j - 1);\n    }\n  if (j < 9)\n    c6 = (10 * i) + (j + 1);\n  if (0 < j)\n    c7 = (10 * i) + (j - 1);\n\n  *neigh_size = 0;\n  add_neighbor (neigh, neigh_size, c0);\n  add_neighbor (neigh, neigh_size, c1);\n  add_neighbor (neigh, neigh_size, c2);\n  add_neighbor (neigh, neigh_size, c3);\n  add_neighbor (neigh, neigh_size, c4);\n  add_neighbor (neigh, neigh_size, c5);\n  add_neighbor (neigh, neigh_size, c6);\n  add_neighbor (neigh, neigh_size, c7);\n}\n\nstatic floating_pt\ndistance (uint8_t m, uint8_t n)\n{\n  const uint8_t im = m / 10;\n  const uint8_t jm = m % 10;\n  const uint8_t in = n / 10;\n  const uint8_t jn = n % 10;\n  const int di = (int) im - (int) in;\n  const int dj = (int) jm - (int) jn;\n  return SQRT ((di * di) + (dj * dj));\n}\n\nstatic floating_pt\npath_length (uint8_t vec[VECSZ])\n{\n  floating_pt len = distance (vec[0], vec[VECSZ - 1]);\n  for (size_t j = 0; j != VECSZ - 1; j += 1)\n    len += distance (vec[j], vec[j + 1]);\n  return len;\n}\n\nstatic void\nswap_s_elements (uint8_t vec[], uint8_t u, uint8_t v)\n{\n  size_t j = 1;\n  size_t iu = 0;\n  size_t iv = 0;\n  while (iu == 0 || iv == 0)\n    {\n      if (vec[j] == u)\n        iu = j;\n      else if (vec[j] == v)\n        iv = j;\n      j += 1;\n    }\n  vec[iu] = v;\n  vec[iv] = u;\n}\n\nstatic void\nupdate_s (uint8_t vec[])\n{\n  const uint8_t u = 1 + (random () % (VECSZ - 1));\n  uint8_t neighbors[8];\n  unsigned int num_neighbors;\n  neighborhood (neighbors, &num_neighbors, u);\n  const uint8_t v = neighbors[random () % num_neighbors];\n  swap_s_elements (vec, u, v);\n}\n\nstatic inline void\ncopy_s (uint8_t dst[VECSZ], uint8_t src[VECSZ])\n{\n  memcpy (dst, src, VECSZ * (sizeof src[0]));\n}\n\nstatic void\ntrial_s (uint8_t trial[VECSZ], uint8_t vec[VECSZ])\n{\n  copy_s (trial, vec);\n  update_s (trial);\n}\n\nstatic floating_pt\ntemperature (floating_pt kT, unsigned int kmax, unsigned int k)\n{\n  return kT * (1 - ((floating_pt) k / (floating_pt) kmax));\n}\n\nstatic floating_pt\nprobability (floating_pt delta_E, floating_pt T)\n{\n  floating_pt prob;\n  if (delta_E < 0)\n    prob = 1;\n  else if (T == 0)\n    prob = 0;\n  else\n    prob = EXP (-(delta_E / T));\n  return prob;\n}\n\nstatic void\nshow (unsigned int k, floating_pt T, floating_pt E)\n{\n  printf (\" %7u %7.1f %13.5f\\n\", k, (double) T, (double) E);\n}\n\nstatic void\nsimulate_annealing (floating_pt kT,\n                    unsigned int kmax,\n                    uint8_t s[VECSZ])\n{\n  uint8_t trial[VECSZ];\n\n  unsigned int kshow = kmax / 10;\n  floating_pt E = path_length (s);\n  for (unsigned int k = 0; k != kmax + 1; k += 1)\n    {\n      const floating_pt T = temperature (kT, kmax, k);\n      if (k % kshow == 0)\n        show (k, T, E);\n      trial_s (trial, s);\n      const floating_pt E_trial = path_length (trial);\n      const floating_pt delta_E = E_trial - E;\n      const floating_pt P = probability (delta_E, T);\n      if (P == 1 || randnum () <= P)\n        {\n          copy_s (s, trial);\n          E = E_trial;\n        }\n    }\n}\n\nstatic void\ndisplay_path (uint8_t vec[VECSZ])\n{\n  for (size_t i = 0; i != VECSZ; i += 1)\n    {\n      const uint8_t x = vec[i];\n      printf (\"%2u ->\", (unsigned int) x);\n      if ((i % 8) == 7)\n        printf (\"\\n\");\n      else\n        printf (\" \");\n    }\n  printf (\"%2u\\n\", vec[0]);\n}\n\nint\nmain (void)\n{\n  char state[STATESZ];\n  uint32_t seed[1];\n  int status = getentropy (&seed[0], sizeof seed[0]);\n  if (status < 0)\n    seed[0] = 1;\n  initstate (seed[0], state, STATESZ);\n\n  floating_pt kT = 1.0;\n  unsigned int kmax = 1000000;\n\n  uint8_t s[VECSZ];\n  init_s (s);\n\n  printf (\"\\n\");\n  printf (\"   kT: %f\\n\", (double) kT);\n  printf (\"   kmax: %u\\n\", kmax);\n  printf (\"\\n\");\n  printf (\"       k       T          E(s)\\n\");\n  printf (\" -----------------------------\\n\");\n  simulate_annealing (kT, kmax, s);\n  printf (\"\\n\");\n  display_path (s);\n  printf (\"\\n\");\n  printf (\"Final E(s): %.5f\\n\", (double) path_length (s));\n  printf (\"\\n\");\n\n  return 0;\n}\n"}
{"id": 60686, "name": "Start from a main routine", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n"}
{"id": 60687, "name": "Start from a main routine", "Go": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n    fmt.Println(\"foo called\")\n}\n\nfunc init() {\n    fmt.Println(\"first init called\")\n    foo()\n}\n\nfunc init() {\n    fmt.Println(\"second init called\")\n    main()\n}\n\nfunc main() {\n    count++\n    fmt.Println(\"main called when count is\", count)\n}\n", "C": "#include<stdio.h>\n\n#define start main()\n\nint start\n{\n\tprintf(\"Hello World !\");\n\treturn 0;\n}\n"}
{"id": 60688, "name": "Summation of primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    sum := 0\n    for _, p := range rcu.Primes(2e6 - 1) {\n        sum += p\n    }\n    fmt.Printf(\"The sum of all primes below 2 million is %s.\\n\", rcu.Commatize(sum))\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n    int p;\n    long int s = 2;\n    for(p=3;p<2000000;p+=2) {\n        if(isprime(p)) s+=p;\n    }\n    printf( \"%ld\\n\", s );\n    return 0;\n}\n"}
{"id": 60689, "name": "Koch curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n    angle := math.Pi / 3 \n    x3 := (x1*2 + x2) / 3\n    y3 := (y1*2 + y2) / 3\n    x4 := (x1 + x2*2) / 3\n    y4 := (y1 + y2*2) / 3\n    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n    if iter > 0 {\n        iter--\n        koch(x1, y1, x3, y3, iter)\n        koch(x3, y3, x5, y5, iter)\n        koch(x5, y5, x4, y4, iter)\n        koch(x4, y4, x2, y2, iter)\n    } else {\n        dc.LineTo(x1, y1)\n        dc.LineTo(x3, y3)\n        dc.LineTo(x5, y5)\n        dc.LineTo(x4, y4)\n        dc.LineTo(x2, y2)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    koch(100, 100, 400, 400, 4)\n    dc.SetRGB(0, 0, 1) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"koch.png\")\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}point;\n\nvoid kochCurve(point p1,point p2,int times){\n\tpoint p3,p4,p5;\n\tdouble theta = pi/3;\n\t\n\tif(times>0){\n\t\tp3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};\n\t\tp5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};\n\t\t\n\t\tp4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};\n\t\t\n\t\tkochCurve(p1,p3,times-1);\n\t\tkochCurve(p3,p4,times-1);\n\t\tkochCurve(p4,p5,times-1);\n\t\tkochCurve(p5,p2,times-1);\n\t}\n\t\n\telse{\n\t\tline(p1.x,p1.y,p2.x,p2.y);\n\t}\n}\n\nint main(int argC, char** argV)\n{\n\tint w,h,r;\n\tpoint p1,p2;\n\t\n\tif(argC!=4){\n\t\tprintf(\"Usage : %s <window width> <window height> <recursion level>\",argV[0]);\n\t}\n\t\n\telse{\n\t\tw = atoi(argV[1]);\n\t\th = atoi(argV[2]);\n\t\tr = atoi(argV[3]);\n\t\t\n\t\tinitwindow(w,h,\"Koch Curve\");\n\t\t\n\t\tp1 = (point){10,h-10};\n\t\tp2 = (point){w-10,h-10};\n\t\t\n\t\tkochCurve(p1,p2,r);\n\t\t\n\t\tgetch();\n\t\n\t\tclosegraph();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 60690, "name": "Draw pixel 2", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 640, 480)\n    img := image.NewRGBA(rect)\n\n    \n    blue := color.RGBA{0, 0, 255, 255}\n    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)\n\n    \n    yellow := color.RGBA{255, 255, 0, 255}\n    width := img.Bounds().Dx()\n    height := img.Bounds().Dy()\n    rand.Seed(time.Now().UnixNano())\n    x := rand.Intn(width)\n    y := rand.Intn(height)\n    img.Set(x, y, yellow)\n\n    \n    cmap := map[color.Color]string{blue: \"blue\", yellow: \"yellow\"}\n    for i := 0; i < width; i++ {\n        for j := 0; j < height; j++ {\n            c := img.At(i, j)\n            if cmap[c] == \"yellow\" {\n                fmt.Printf(\"The color of the pixel at (%d, %d) is yellow\\n\", i, j)\n            }\n        }\n    }\n}\n", "C": "#include<graphics.h>\n#include<stdlib.h>\n#include<time.h>\n\nint main()\n{\n\tsrand(time(NULL));\n\t\n\tinitwindow(640,480,\"Yellow Random Pixel\");\n\t\n\tputpixel(rand()%640,rand()%480,YELLOW);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 60691, "name": "Count how many vowels and consonants occur in a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n"}
{"id": 60692, "name": "Count how many vowels and consonants occur in a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        vowels     = \"aeiou\"\n        consonants = \"bcdfghjklmnpqrstvwxyz\"\n    )\n    strs := []string{\n        \"Forever Go programming language\",\n        \"Now is the time for all good men to come to the aid of their country.\",\n    }\n    for _, str := range strs {\n        fmt.Println(str)\n        str = strings.ToLower(str)\n        vc, cc := 0, 0\n        vmap := make(map[rune]bool)\n        cmap := make(map[rune]bool)\n        for _, c := range str {\n            if strings.ContainsRune(vowels, c) {\n                vc++\n                vmap[c] = true\n            } else if strings.ContainsRune(consonants, c) {\n                cc++\n                cmap[c] = true\n            }\n        }\n        fmt.Printf(\"contains (total) %d vowels and %d consonants.\\n\", vc, cc)\n        fmt.Printf(\"contains (distinct %d vowels and %d consonants.\\n\\n\", len(vmap), len(cmap))\n    }\n}\n", "C": "\n\n#include <stdio.h>\n\nchar vowels[] = {'a','e','i','o','u','\\n'};\n\nint len(char * str) {\n\tint i = 0;\n\twhile (str[i] != '\\n') i++;\n\treturn i;\n}\n\nint  isvowel(char c){\n\tint b = 0;\n\tint v = len(vowels);\n\tfor(int i = 0; i < v;i++) {\n\t\tif(c == vowels[i]) {\n\t\t\tb = 1;\n\t\t\tbreak; \n\t\t}\n\t}\n\treturn b;\n}\n\nint isletter(char c){\n\treturn ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));\n}\n\nint isconsonant(char c){\n\treturn isletter(c) && !isvowel(c);\n}\n\nint cVowels(char * str) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isvowel(str[i])) {\n\t\t\tcount++;;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint cConsonants(char * str ) {\n\tint i = 0;\n\tint count = 0;\n\twhile (str[i] != '\\n') {\n\t\tif (isconsonant(str[i])) {\n\t\t\tcount++;\n\t\t}\n\t\ti++;\n\t}\n\treturn count;\n}\n\nint main() {\n\n\tchar buff[] = \"This is 1 string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff), cConsonants(buff), len(buff), buff);\n\n\tchar buff2[] = \"This is a second string\\n\";\n\tprintf(\"%4d, %4d, %4d, %s\\n\", cVowels(buff2), cConsonants(buff2), len(buff2),  buff2);\n\n\n\tprintf(\"a: %d\\n\", isvowel('a'));\n\tprintf(\"b: %d\\n\", isvowel('b'));\n\tprintf(\"Z: %d\\n\", isconsonant('Z'));\n\tprintf(\"1: %d\\n\", isletter('1'));\n}\n"}
{"id": 60693, "name": "Compiler_syntax analyzer", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n"}
{"id": 60694, "name": "Compiler_syntax analyzer", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype TokenType int\n\nconst (\n    tkEOI TokenType = iota\n    tkMul\n    tkDiv\n    tkMod\n    tkAdd\n    tkSub\n    tkNegate\n    tkNot\n    tkLss\n    tkLeq\n    tkGtr\n    tkGeq\n    tkEql\n    tkNeq\n    tkAssign\n    tkAnd\n    tkOr\n    tkIf\n    tkElse\n    tkWhile\n    tkPrint\n    tkPutc\n    tkLparen\n    tkRparen\n    tkLbrace\n    tkRbrace\n    tkSemi\n    tkComma\n    tkIdent\n    tkInteger\n    tkString\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype tokS struct {\n    tok    TokenType\n    errLn  int\n    errCol int\n    text   string \n}\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    string\n}\n\n\ntype atr struct {\n    text             string\n    enumText         string\n    tok              TokenType\n    rightAssociative bool\n    isBinary         bool\n    isUnary          bool\n    precedence       int\n    nodeType         NodeType\n}\n\nvar atrs = []atr{\n    {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n    {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n    {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n    {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n    {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n    {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n    {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n    {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n    {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n    {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n    {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n    {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n    {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n    {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n    {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n    {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n    {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n    {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n    {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n    {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n    {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n    {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n    {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n    {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n    {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n    {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n    {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n    {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n    {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n    {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n    {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n    \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n    \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n    \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n    \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n    err     error\n    token   tokS\n    scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n    log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc getEum(name string) TokenType { \n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.tok\n        }\n    }\n    reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return tkEOI\n}\n\nfunc getTok() tokS {\n    tok := tokS{}\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        fields := strings.Fields(line)\n        \n        tok.errLn, err = strconv.Atoi(fields[0])\n        check(err)\n        tok.errCol, err = strconv.Atoi(fields[1])\n        check(err)\n        tok.tok = getEum(fields[2])\n        le := len(fields)\n        if le == 4 {\n            tok.text = fields[3]\n        } else if le > 4 {\n            idx := strings.Index(line, `\"`)\n            tok.text = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n    if token.tok == s {\n        token = getTok()\n        return\n    }\n    reportError(token.errLn, token.errCol,\n        fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n    var x, node *Tree\n    switch token.tok {\n    case tkLparen:\n        x = parenExpr()\n    case tkSub, tkAdd:\n        op := token.tok\n        token = getTok()\n        node = expr(atrs[tkNegate].precedence)\n        if op == tkSub {\n            x = makeNode(ndNegate, node, nil)\n        } else {\n            x = node\n        }\n    case tkNot:\n        token = getTok()\n        x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n    case tkIdent:\n        x = makeLeaf(ndIdent, token.text)\n        token = getTok()\n    case tkInteger:\n        x = makeLeaf(ndInteger, token.text)\n        token = getTok()\n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n    }\n\n    for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n        op := token.tok\n        token = getTok()\n        q := atrs[op].precedence\n        if !atrs[op].rightAssociative {\n            q++\n        }\n        node = expr(q)\n        x = makeNode(atrs[op].nodeType, x, node)\n    }\n    return x\n}\n\nfunc parenExpr() *Tree {\n    expect(\"parenExpr\", tkLparen)\n    t := expr(0)\n    expect(\"parenExpr\", tkRparen)\n    return t\n}\n\nfunc stmt() *Tree {\n    var t, v, e, s, s2 *Tree\n    switch token.tok {\n    case tkIf:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        s2 = nil\n        if token.tok == tkElse {\n            token = getTok()\n            s2 = stmt()\n        }\n        t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n    case tkPutc:\n        token = getTok()\n        e = parenExpr()\n        t = makeNode(ndPrtc, e, nil)\n        expect(\"Putc\", tkSemi)\n    case tkPrint: \n        token = getTok()\n        for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n            if token.tok == tkString {\n                e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n                token = getTok()\n            } else {\n                e = makeNode(ndPrti, expr(0), nil)\n            }\n            t = makeNode(ndSequence, t, e)\n            if token.tok != tkComma {\n                break\n            }\n        }\n        expect(\"Print\", tkRparen)\n        expect(\"Print\", tkSemi)\n    case tkSemi:\n        token = getTok()\n    case tkIdent:\n        v = makeLeaf(ndIdent, token.text)\n        token = getTok()\n        expect(\"assign\", tkAssign)\n        e = expr(0)\n        t = makeNode(ndAssign, v, e)\n        expect(\"assign\", tkSemi)\n    case tkWhile:\n        token = getTok()\n        e = parenExpr()\n        s = stmt()\n        t = makeNode(ndWhile, e, s)\n    case tkLbrace: \n        for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n            t = makeNode(ndSequence, t, stmt())\n        }\n        expect(\"Lbrace\", tkRbrace)\n    case tkEOI:\n        \n    default:\n        reportError(token.errLn, token.errCol,\n            fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n    }\n    return t\n}\n\nfunc parse() *Tree {\n    var t *Tree\n    token = getTok()\n    for {\n        t = makeNode(ndSequence, t, stmt())\n        if t == nil || token.tok == tkEOI {\n            break\n        }\n    }\n    return t\n}\n\nfunc prtAst(t *Tree) {\n    if t == nil {\n        fmt.Print(\";\\n\")\n    } else {\n        fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n        if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n            fmt.Printf(\"%s\\n\", t.value)\n        } else {\n            fmt.Println()\n            prtAst(t.left)\n            prtAst(t.right)\n        }\n    }\n}\n\nfunc main() {\n    source, err := os.Open(\"source.txt\")\n    check(err)\n    defer source.Close()\n    scanner = bufio.NewScanner(source)\n    prtAst(parse())\n}\n", "C": "count = 1;\n while (count < 10) {\n     print(\"count is: \", count, \"\\n\");\n     count = count + 1;\n }\n"}
{"id": 60695, "name": "Draw a pixel", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n", "C": "#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n"}
{"id": 60696, "name": "Numbers whose binary and ternary digit sums are prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60697, "name": "Numbers whose binary and ternary digit sums are prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var numbers []int\n    for i := 2; i < 200; i++ {\n        bds := rcu.DigitSum(i, 2)\n        if rcu.IsPrime(bds) {\n            tds := rcu.DigitSum(i, 3)\n            if rcu.IsPrime(tds) {\n                numbers = append(numbers, i)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 200 whose binary and ternary digit sums are prime:\")\n    for i, n := range numbers {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%14 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found\\n\", len(numbers))\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\n\nuint8_t prime(uint8_t n) {\n    uint8_t f;\n    if (n < 2) return 0;\n    for (f = 2; f < n; f++) {\n        if (n % f == 0) return 0;\n    }\n    return 1;\n}\n\n\nuint8_t digit_sum(uint8_t n, uint8_t base) {\n    uint8_t s = 0;\n    do {s += n % base;} while (n /= base);\n    return s;\n}\n\nint main() {\n    uint8_t n, s = 0;\n    for (n = 0; n < 200; n++) {\n        if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {\n            printf(\"%4d\",n);\n            if (++s>=10) {\n                printf(\"\\n\");\n                s=0;\n            }\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60698, "name": "Words from neighbour ones", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    wordList := \"unixdict.txt\"\n    b, err := ioutil.ReadFile(wordList)\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    bwords := bytes.Fields(b)\n    var words []string\n    for _, bword := range bwords {\n        s := string(bword)\n        if utf8.RuneCountInString(s) >= 9 {\n            words = append(words, s)\n        }\n    }\n    count := 0\n    var alreadyFound []string\n    le := len(words)\n    var sb strings.Builder\n    for i := 0; i < le-9; i++ {\n        sb.Reset()\n        for j := i; j < i+9; j++ {\n            sb.WriteByte(words[j][j-i])\n        }\n        word := sb.String()\n        ix := sort.SearchStrings(words, word)\n        if ix < le && word == words[ix] {\n            ix2 := sort.SearchStrings(alreadyFound, word)\n            if ix2 == len(alreadyFound) {\n                count++\n                fmt.Printf(\"%2d: %s\\n\", count, word)\n                alreadyFound = append(alreadyFound, word)\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX_WORD_SIZE 80\n#define MIN_LENGTH 9\n#define WORD_SIZE (MIN_LENGTH + 1)\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\nint word_compare(const void* p1, const void* p2) {\n    return memcmp(p1, p2, WORD_SIZE);\n}\n\nint main(int argc, char** argv) {\n    const char* filename = argc < 2 ? \"unixdict.txt\" : argv[1];\n    FILE* in = fopen(filename, \"r\");\n    if (!in) {\n        perror(filename);\n        return EXIT_FAILURE;\n    }\n    char line[MAX_WORD_SIZE];\n    size_t size = 0, capacity = 1024;\n    char* words = xmalloc(WORD_SIZE * capacity);\n    while (fgets(line, sizeof(line), in)) {\n        size_t len = strlen(line) - 1; \n        if (len < MIN_LENGTH)\n            continue;\n        line[len] = '\\0';\n        if (size == capacity) {\n            capacity *= 2;\n            words = xrealloc(words, WORD_SIZE * capacity);\n        }\n        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);\n        ++size;\n    }\n    fclose(in);\n    qsort(words, size, WORD_SIZE, word_compare);\n    int count = 0;\n    char prev_word[WORD_SIZE] = { 0 };\n    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {\n        char word[WORD_SIZE] = { 0 };\n        for (size_t j = 0; j < MIN_LENGTH; ++j)\n            word[j] = words[(i + j) * WORD_SIZE + j];\n        if (word_compare(word, prev_word) == 0)\n            continue;\n        if (bsearch(word, words, size, WORD_SIZE, word_compare))\n            printf(\"%2d. %s\\n\", ++count, word);\n        memcpy(prev_word, word, WORD_SIZE);\n    }\n    free(words);\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60699, "name": "Numbers divisible by their individual digits, but not by the product of their digits.", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var res []int\n    for n := 1; n < 1000; n++ {\n        digits := rcu.Digits(n, 10)\n        var all = true\n        for _, d := range digits {\n            if d == 0 || n%d != 0 {\n                all = false\n                break\n            }\n        }\n        if all {\n            prod := 1\n            for _, d := range digits {\n                prod *= d\n            }\n            if prod > 0 && n%prod != 0 {\n                res = append(res, n)\n            }\n        }\n    }\n    fmt.Println(\"Numbers < 1000 divisible by their digits, but not by the product thereof:\")\n    for i, n := range res {\n        fmt.Printf(\"%4d\", n)\n        if (i+1)%9 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\n%d such numbers found\\n\", len(res))\n}\n", "C": "#include <stdio.h>\n\nint divisible(int n) {\n    int p = 1;\n    int c, d;\n    \n    for (c=n; c; c /= 10) {\n        d = c % 10;\n        if (!d || n % d) return 0;\n        p *= d;\n    }\n    \n    return n % p;\n}\n\nint main() {\n    int n, c=0;\n    \n    for (n=1; n<1000; n++) {\n        if (divisible(n)) {\n            printf(\"%5d\", n);\n            if (!(++c % 10)) printf(\"\\n\");\n        }\n    }\n    printf(\"\\n\");\n    \n    return 0;\n}\n"}
{"id": 60700, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 60701, "name": "Four bit adder", "Go": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n    return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n    return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n    sa, ca := ha(a, c0)\n    s, cb := ha(sa, b)\n    c1 = ca | cb\n    return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n    s0, c0 := fa(a0, b0, 0)\n    s1, c1 := fa(a1, b1, c0)\n    s2, c2 := fa(a2, b2, c1)\n    s3, v = fa(a3, b3, c2)\n    return\n}\n\nfunc main() {\n    \n    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}\n", "C": "#include <stdio.h>\n\ntypedef char pin_t;\n#define IN const pin_t *\n#define OUT pin_t *\n#define PIN(X) pin_t _##X; pin_t *X = & _##X;\n#define V(X) (*(X))\n\n\n#define NOT(X) (~(X)&1)\n\n\n#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))\n\nvoid halfadder(IN a, IN b, OUT s, OUT c)\n{\n  V(s) = XOR(V(a), V(b));\n  V(c) = V(a) & V(b);\n}\n\nvoid fulladder(IN a, IN b, IN ic, OUT s, OUT oc)\n{\n  PIN(ps); PIN(pc); PIN(tc);\n\n  halfadder(a, b, ps, pc);\n  halfadder(ps, ic, s, tc);\n  V(oc) = V(tc) | V(pc);\n}\n\nvoid fourbitsadder(IN a0, IN a1, IN a2, IN a3,\n\t\t   IN b0, IN b1, IN b2, IN b3,\n\t\t   OUT o0, OUT o1, OUT o2, OUT o3,\n\t\t   OUT overflow)\n{\n  PIN(zero); V(zero) = 0;\n  PIN(tc0); PIN(tc1); PIN(tc2);\n\n  fulladder(a0, b0, zero, o0, tc0);\n  fulladder(a1, b1, tc0,  o1, tc1);\n  fulladder(a2, b2, tc1,  o2, tc2);\n  fulladder(a3, b3, tc2,  o3, overflow);\n}\n\n\nint main()\n{\n  PIN(a0); PIN(a1); PIN(a2); PIN(a3);\n  PIN(b0); PIN(b1); PIN(b2); PIN(b3);\n  PIN(s0); PIN(s1); PIN(s2); PIN(s3);\n  PIN(overflow);\n\n  V(a3) = 0; V(b3) = 1;\n  V(a2) = 0; V(b2) = 1;\n  V(a1) = 1; V(b1) = 1;\n  V(a0) = 0; V(b0) = 0;\n\n  fourbitsadder(a0, a1, a2, a3, \n\t\tb0, b1, b2, b3,\n\t\ts0, s1, s2, s3, \n\t\toverflow);\n\n  printf(\"%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\\n\",\n\t V(a3), V(a2), V(a1), V(a0),\n\t V(b3), V(b2), V(b1), V(b0),\n\t V(s3), V(s2), V(s1), V(s0),\n\t V(overflow));\n  \n  return 0;\n}\n"}
{"id": 60702, "name": "Magic squares of singly even order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n    if n < 3 || n%2 == 0 {\n        return nil, fmt.Errorf(\"base must be odd and > 2\")\n    }\n    value := 1\n    gridSize := n * n\n    c, r := n/2, 0\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for value <= gridSize {\n        result[r][c] = value\n        if r == 0 {\n            if c == n-1 {\n                r++\n            } else {\n                r = n - 1\n                c++\n            }\n        } else if c == n-1 {\n            r--\n            c = 0\n        } else if result[r-1][c+1] == 0 {\n            r--\n            c++\n        } else {\n            r++\n        }\n        value++\n    }\n    return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n    if n < 6 || (n-2)%4 != 0 {\n        return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n    }\n    size := n * n\n    halfN := n / 2\n    subSquareSize := size / 4\n    subSquare, err := magicSquareOdd(halfN)\n    if err != nil {\n        return nil, err\n    }\n    quadrantFactors := [4]int{0, 2, 3, 1}\n    result := make([][]int, n)\n\n    for i := 0; i < n; i++ {\n        result[i] = make([]int, n)\n    }\n\n    for r := 0; r < n; r++ {\n        for c := 0; c < n; c++ {\n            quadrant := r/halfN*2 + c/halfN\n            result[r][c] = subSquare[r%halfN][c%halfN]\n            result[r][c] += quadrantFactors[quadrant] * subSquareSize\n        }\n    }\n\n    nColsLeft := halfN / 2\n    nColsRight := nColsLeft - 1\n\n    for r := 0; r < halfN; r++ {\n        for c := 0; c < n; c++ {\n            if c < nColsLeft || c >= n-nColsRight ||\n                (c == nColsLeft && r == nColsLeft) {\n                if c == 0 && r == nColsLeft {\n                    continue\n                }\n                tmp := result[r][c]\n                result[r][c] = result[r+halfN][c]\n                result[r+halfN][c] = tmp\n            }\n        }\n    }\n    return result, nil\n}\n\nfunc main() {\n    const n = 6\n    msse, err := magicSquareSinglyEven(n)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, row := range msse {\n        for _, x := range row {\n            fmt.Printf(\"%2d \", x)\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}\n", "C": "   #include<stdlib.h>\n   #include<ctype.h>\n   #include<stdio.h>\n   \n   int** oddMagicSquare(int n) {\n        if (n < 3 || n % 2 == 0)\n            return NULL;\n \n        int value = 0;\n        int squareSize = n * n;\n        int c = n / 2, r = 0,i;\n \n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        while (++value <= squareSize) {\n            result[r][c] = value;\n            if (r == 0) {\n                if (c == n - 1) {\n                    r++;\n                } else {\n                    r = n - 1;\n                    c++;\n                }\n            } else if (c == n - 1) {\n                r--;\n                c = 0;\n            } else if (result[r - 1][c + 1] == 0) {\n                r--;\n                c++;\n            } else {\n                r++;\n            }\n        }\n        return result;\n    }\n \n    int** singlyEvenMagicSquare(int n) {\n        if (n < 6 || (n - 2) % 4 != 0)\n            return NULL;\n \n        int size = n * n;\n        int halfN = n / 2;\n        int subGridSize = size / 4, i;\n \n        int** subGrid = oddMagicSquare(halfN);\n        int gridFactors[] = {0, 2, 3, 1};\n        int** result = (int**)malloc(n*sizeof(int*));\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tresult[i] = (int*)malloc(n*sizeof(int));\n \n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < n; c++) {\n                int grid = (r / halfN) * 2 + (c / halfN);\n                result[r][c] = subGrid[r % halfN][c % halfN];\n                result[r][c] += gridFactors[grid] * subGridSize;\n            }\n        }\n \n        int nColsLeft = halfN / 2;\n        int nColsRight = nColsLeft - 1;\n \n        for (int r = 0; r < halfN; r++)\n            for (int c = 0; c < n; c++) {\n                if (c < nColsLeft || c >= n - nColsRight\n                        || (c == nColsLeft && r == nColsLeft)) {\n \n                    if (c == 0 && r == nColsLeft)\n                        continue;\n \n                    int tmp = result[r][c];\n                    result[r][c] = result[r + halfN][c];\n                    result[r + halfN][c] = tmp;\n                }\n            }\n \n        return result;\n    }\n\t\n\tint numDigits(int n){\n\t\tint count = 1;\n\t\t\n\t\twhile(n>=10){\n\t\t\tn /= 10;\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\t\n\tvoid printMagicSquare(int** square,int rows){\n\t\tint i,j;\n\t\t\n\t\tfor(i=0;i<rows;i++){\n\t\t\tfor(j=0;j<rows;j++){\n\t\t\t\tprintf(\"%*s%d\",rows - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tprintf(\"\\nMagic constant: %d \", (rows * rows + 1) * rows / 2);\n\t}\n\t\n\tint main(int argC,char* argV[])\n\t{\n\t\tint n;\n\t\t\n\t\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\t\telse{\n\t\t\tn = atoi(argV[1]);\n\t\t\tprintMagicSquare(singlyEvenMagicSquare(n),n);\n\t\t}\n\t\treturn 0;\n\t}\n"}
{"id": 60703, "name": "Scope_Function names and labels", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n\n    \"ex\"\n)\n\nfunc main() {\n    \n\n    \n    f := func() {\n        \n        \n        pc, _, _, _ := runtime.Caller(0)\n        fmt.Println(runtime.FuncForPC(pc).Name(), \"here!\")\n    }\n\n    ex.X(f) \n\n    \n}\n", "C": "#include <stdio.h>\n\n#define sqr(x) ((x) * (x))\n#define greet printf(\"Hello There!\\n\")\n\nint twice(int x)\n{\n\treturn 2 * x;\n}\n\nint main(void)\n{\n\tint x;\n\n\tprintf(\"This will demonstrate function and label scopes.\\n\");\n\tprintf(\"All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\\n\");\n\tprintf(\"Enter a number: \");\n\tif (scanf(\"%d\", &x) != 1)\n\t\treturn 0;\n\t\n\tswitch (x % 2) {\n\tdefault:\n\t\tprintf(\"Case labels in switch statements have scope local to the switch block.\\n\");\n\tcase 0:\n\t\tprintf(\"You entered an even number.\\n\");\n\t\tprintf(\"Its square is %d, which was computed by a macro. It has global scope within the translation unit.\\n\", sqr(x));\n\t\tbreak;\n\tcase 1:\n\t\tprintf(\"You entered an odd number.\\n\");\n\t\tgoto sayhello;\n\tjumpin:\n\t\tprintf(\"2 times %d is %d, which was computed by a function defined in this file. It has global scope within the translation unit.\\n\", x, twice(x));\n\t\tprintf(\"Since you jumped in, you will now be greeted, again!\\n\"); \n\tsayhello:\n\t\tgreet;\n\t\tif (x == -1)\n\t\t\tgoto scram;   \n\t\tbreak;\n\t}\n\n\tprintf(\"We now come to goto, it's extremely powerful but it's also prone to misuse. Its use is discouraged and it wasn't even adopted by Java and later languages.\\n\");\n\n\tif (x != -1) {\n\t\tx = -1;   \n\t \tgoto jumpin;  \n\t}\n\nscram:\n\tprintf(\"If you are trying to figure out what happened, you now understand goto.\\n\");\n\treturn 0;\n}\n"}
{"id": 60704, "name": "Generate Chess960 starting position", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'♔', '♕', '♖', '♗', '♘'}\nvar B = symbols{'♚', '♛', '♜', '♝', '♞'}\n\nvar krn = []string{\n    \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n    \"rnnkr\", \"rnknr\", \"rnkrn\",\n    \"rknnr\", \"rknrn\",\n    \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n    var pos [8]rune\n    q, r := id/4, id%4\n    pos[r*2+1] = sym.b\n    q, r = q/4, q%4\n    pos[r*2] = sym.b\n    q, r = q/6, q%6\n    for i := 0; ; i++ {\n        if pos[i] != 0 {\n            continue\n        }\n        if r == 0 {\n            pos[i] = sym.q\n            break\n        }\n        r--\n    }\n    i := 0\n    for _, f := range krn[q] {\n        for pos[i] != 0 {\n            i++\n        }\n        switch f {\n        case 'k':\n            pos[i] = sym.k\n        case 'r':\n            pos[i] = sym.r\n        case 'n':\n            pos[i] = sym.n\n        }\n    }\n    return string(pos[:])\n}\n\nfunc main() {\n    fmt.Println(\" ID  Start position\")\n    for _, id := range []int{0, 518, 959} {\n        fmt.Printf(\"%3d  %s\\n\", id, A.chess960(id))\n    }\n    fmt.Println(\"\\nRandom\")\n    for i := 0; i < 5; i++ {\n        fmt.Println(W.chess960(rand.Intn(960)))\n    }\n}\n", "C": "#include<stdlib.h>\n#include<locale.h>\n#include<wchar.h>\n#include<stdio.h>\n#include<time.h>\n\nchar rank[9];\n\nint pos[8];\n\nvoid swap(int i,int j){\n\tint temp = pos[i];\n\tpos[i] = pos[j];\n\tpos[j] = temp;\n}\n\nvoid generateFirstRank(){\n\t int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;\n\t \n\t for(i=0;i<8;i++){\n\t\t rank[i] = 'e';\n\t\t pos[i] = i;\n\t }\n\t\t \n\t do{\n\t\t kPos = rand()%8;\n\t\t rPos1 = rand()%8;\n\t\t rPos2 = rand()%8;\n\t }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));\n\n\t rank[pos[rPos1]] = 'R';\n\t rank[pos[kPos]] = 'K';\n\t rank[pos[rPos2]] = 'R';\n\t \n\t swap(rPos1,7);\n\t swap(rPos2,6);\n\t swap(kPos,5);\n\t \n\t do{\n\t\t bPos1 = rand()%5;\n\t\t bPos2 = rand()%5;\n\t }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));\n\n\t rank[pos[bPos1]] = 'B';\n\t rank[pos[bPos2]] = 'B';\n\t \n\t swap(bPos1,4);\n\t swap(bPos2,3);\n\t \n\t do{\n\t\t qPos = rand()%3;\n\t\t nPos1 = rand()%3;\n\t }while(qPos==nPos1);\n\t \n\t rank[pos[qPos]] = 'Q';\n\t rank[pos[nPos1]] = 'N';\n\t \n\t for(i=0;i<8;i++)\n\t\t if(rank[i]=='e'){\n\t\t\t rank[i] = 'N';\n\t\t\t break;\n\t\t }\t\t\n}\n\nvoid printRank(){\n\tint i;\n\t\n\t#ifdef _WIN32\n\t\tprintf(\"%s\\n\",rank);\n\t#else\n\t{\n\t\tsetlocale(LC_ALL,\"\");\n\t\tprintf(\"\\n\");\n\t\tfor(i=0;i<8;i++){\n\t\t\tif(rank[i]=='K')\n\t\t\t\tprintf(\"%lc\",(wint_t)9812);\n\t\t\telse if(rank[i]=='Q')\n\t\t\t\tprintf(\"%lc\",(wint_t)9813);\n\t\t\telse if(rank[i]=='R')\n\t\t\t\tprintf(\"%lc\",(wint_t)9814);\n\t\t\telse if(rank[i]=='B')\n\t\t\t\tprintf(\"%lc\",(wint_t)9815);\n\t\t\tif(rank[i]=='N')\n\t\t\t\tprintf(\"%lc\",(wint_t)9816);\n\t\t}\n\t}\n\t#endif\n}\n\nint main()\n{\n\tint i;\n\t\n\tsrand((unsigned)time(NULL));\n\t\n\tfor(i=0;i<9;i++){\n\t\tgenerateFirstRank();\n\t\tprintRank();\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 60705, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 60706, "name": "Execute Brain____", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n    ds := make([]byte, dLen) \n    var dp int               \n    for ip := 0; ip < len(is); ip++ {\n        switch is[ip] {\n        case '>':\n            dp++\n        case '<':\n            dp--\n        case '+':\n            ds[dp]++\n        case '-':\n            ds[dp]--\n        case '.':\n            fmt.Printf(\"%c\", ds[dp])\n        case ',':\n            fmt.Scanf(\"%c\", &ds[dp])\n        case '[':\n            if ds[dp] == 0 {\n                for nc := 1; nc > 0; {\n                    ip++\n                    if is[ip] == '[' {\n                        nc++\n                    } else if is[ip] == ']' {\n                        nc--\n                    }\n                }\n            }\n        case ']':\n            if ds[dp] != 0 {\n                for nc := 1; nc > 0; {\n                    ip--\n                    if is[ip] == ']' {\n                        nc++\n                    } else if is[ip] == '[' {\n                        nc--\n                    }\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\nint main(){\n     int ptr=0, i=0, cell[7];\n     for( i=0; i<7; ++i) cell[i]=0;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 8;\n     while(cell[ptr])\n     {\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          cell[ptr]+= 9;\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          cell[ptr]-= 1;\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 2;\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     while(cell[ptr])\n     {\n          cell[ptr]-= 1;\n     }\n     cell[ptr]+= 1;\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n               cell[ptr]+= 1;\n               ptr-= 2;\n               if(ptr<0) perror(\"Program pointer underflow\");\n               cell[ptr]+= 4;\n               ptr+= 1;\n               if(ptr>=7) perror(\"Program pointer overflow\");\n          }\n          ptr-= 2;\n          if(ptr<0) perror(\"Program pointer underflow\");\n     }\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 7;\n     putchar(cell[ptr]);\n     ptr-= 3;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     while(cell[ptr])\n     {\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr-= 1;\n          if(ptr<0) perror(\"Program pointer underflow\");\n          while(cell[ptr])\n          {\n               cell[ptr]-= 1;\n          }\n          ptr+= 1;\n          if(ptr>=7) perror(\"Program pointer overflow\");\n     }\n     ptr-= 1;\n     if(ptr<0) perror(\"Program pointer underflow\");\n     cell[ptr]+= 15;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     putchar(cell[ptr]);\n     cell[ptr]+= 3;\n     putchar(cell[ptr]);\n     cell[ptr]-= 6;\n     putchar(cell[ptr]);\n     cell[ptr]-= 8;\n     putchar(cell[ptr]);\n     ptr+= 2;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 1;\n     putchar(cell[ptr]);\n     ptr+= 1;\n     if(ptr>=7) perror(\"Program pointer overflow\");\n     cell[ptr]+= 4;\n     putchar(cell[ptr]);\n     return 0;\n}\n"}
{"id": 60707, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "C": "int meaning_of_life();\n"}
{"id": 60708, "name": "Modulinos", "Go": "\npackage main\n\nimport \"fmt\"\n\nfunc MeaningOfLife() int {\n    return 42\n}\n\nfunc libMain() {\n    fmt.Println(\"The meaning of life is\", MeaningOfLife())\n}\n", "C": "int meaning_of_life();\n"}
{"id": 60709, "name": "Perlin noise", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n    X := int(math.Floor(x)) & 255\n    Y := int(math.Floor(y)) & 255\n    Z := int(math.Floor(z)) & 255\n    x -= math.Floor(x)\n    y -= math.Floor(y)\n    z -= math.Floor(z)\n    u := fade(x)\n    v := fade(y)\n    w := fade(z)\n    A := p[X] + Y\n    AA := p[A] + Z\n    AB := p[A+1] + Z\n    B := p[X+1] + Y\n    BA := p[B] + Z\n    BB := p[B+1] + Z\n    return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n        grad(p[BA], x-1, y, z)),\n        lerp(u, grad(p[AB], x, y-1, z),\n            grad(p[BB], x-1, y-1, z))),\n        lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n            grad(p[BA+1], x-1, y, z-1)),\n            lerp(u, grad(p[AB+1], x, y-1, z-1),\n                grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64       { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n    \n    \n    \n    switch hash & 15 {\n    case 0, 12:\n        return x + y\n    case 1, 14:\n        return y - x\n    case 2:\n        return x - y\n    case 3:\n        return -x - y\n    case 4:\n        return x + z\n    case 5:\n        return z - x\n    case 6:\n        return x - z\n    case 7:\n        return -x - z\n    case 8:\n        return y + z\n    case 9, 13:\n        return z - y\n    case 10:\n        return y - z\n    }\n    \n    return -y - z\n}\n\nvar permutation = []int{\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n    140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n    247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n    57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n    74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n    60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n    65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n    200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n    52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n    207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n    119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n    129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n    218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n    81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n    184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n    222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<math.h>\n\nint p[512];\n\ndouble fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }\ndouble lerp(double t, double a, double b) { return a + t * (b - a); }\ndouble grad(int hash, double x, double y, double z) {\n      int h = hash & 15;                      \n      double u = h<8 ? x : y,                 \n             v = h<4 ? y : h==12||h==14 ? x : z;\n      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);\n   }\n   \ndouble noise(double x, double y, double z) {\n      int X = (int)floor(x) & 255,                  \n          Y = (int)floor(y) & 255,                  \n          Z = (int)floor(z) & 255;\n      x -= floor(x);                                \n      y -= floor(y);                                \n      z -= floor(z);\n      double u = fade(x),                                \n             v = fade(y),                                \n             w = fade(z);\n      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      \n          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   \n \n      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), \n                                     grad(p[BA  ], x-1, y  , z   )),\n                             lerp(u, grad(p[AB  ], x  , y-1, z   ), \n                                     grad(p[BB  ], x-1, y-1, z   ))),\n                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), \n                                     grad(p[BA+1], x-1, y  , z-1 )), \n                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),\n                                     grad(p[BB+1], x-1, y-1, z-1 ))));\n   }\n\nvoid loadPermutation(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tint permutation[256],i;\n\t\n\tfor(i=0;i<256;i++)\n\t\tfscanf(fp,\"%d\",&permutation[i]);\n\t\n\tfclose(fp);\n\t\n\tfor (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>\");\n\telse{\n\t\tloadPermutation(argV[1]);\n\t\tprintf(\"Perlin Noise for (%s,%s,%s) is %.17lf\",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 60710, "name": "File size distribution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc commatize(n int64) 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 fileSizeDistribution(root string) {\n    var sizes [12]int\n    files := 0\n    directories := 0\n    totalSize := int64(0)\n    walkFunc := func(path string, info os.FileInfo, err error) error {\n        if err != nil {\n            return err\n        }\n        files++\n        if info.IsDir() {\n            directories++\n        }\n        size := info.Size()\n        if size == 0 {\n            sizes[0]++\n            return nil\n        }\n        totalSize += size\n        logSize := math.Log10(float64(size))\n        index := int(math.Floor(logSize))\n        sizes[index+1]++\n        return nil\n    }\n    err := filepath.Walk(root, walkFunc)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n    for i := 0; i < len(sizes); i++ {\n        if i == 0 {\n            fmt.Print(\"  \")\n        } else {\n            fmt.Print(\"+ \")\n        }\n        fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n    }\n    fmt.Println(\"                                  -----\")\n    fmt.Printf(\"= Total number of files         : %5d\\n\", files)\n    fmt.Printf(\"  including directories         : %5d\\n\", directories)\n    c := commatize(totalSize)\n    fmt.Println(\"\\n  Total size of files           :\", c, \"bytes\")\n}\n\nfunc main() {\n    fileSizeDistribution(\"./\")\n}\n", "C": "#include<windows.h>\n#include<string.h>\n#include<stdio.h>\n\n#define MAXORDER 25\n\nint main(int argC, char* argV[])\n{\n\tchar str[MAXORDER],commandString[1000],*startPath;\n\tlong int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;\n\tint i,j,len;\n\tdouble scale;\n\tFILE* fp;\n\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by directory to start search from(. for current dir), followed by \\n optional parameters (T or G) to show text or graph output>\",argV[0]);\n\telse{\n\t\tif(strchr(argV[1],' ')!=NULL){\n\t\tlen = strlen(argV[1]);\n\t\tstartPath = (char*)malloc((len+2)*sizeof(char));\n\t\tstartPath[0] = '\\\"';\n\t\tstartPath[len+1]='\\\"';\n\t\tstrncpy(startPath+1,argV[1],len);\n\t\tstartPath[len+2] = argV[1][len];\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",startPath);\n\t}\n\n\telse if(strlen(argV[1])==1 && argV[1][0]=='.')\n\t\tstrcpy(commandString,\"forfiles /s /c \\\"cmd /c echo @fsize\\\" 2>&1\");\n\n\telse\n\t\tsprintf(commandString,\"forfiles /p %s /s /c \\\"cmd /c echo @fsize\\\" 2>&1\",argV[1]);\n\n\tfp = popen(commandString,\"r\");\n\n\twhile(fgets(str,100,fp)!=NULL){\n\t\t\tif(str[0]=='0')\n\t\t\t\tfileSizeLog[0]++;\n\t\t\telse\n\t\t\t\tfileSizeLog[strlen(str)]++;\n\t}\n\n\tif(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){\n\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\tprintf(\"\\nSize Order < 10^%2d bytes : %Ld\",i,fileSizeLog[i]);\n\t\t}\n\t}\n\n\telse if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);\n\t\tif(val)\n\t\t{\n\n\t\t\t\tmax = fileSizeLog[0];\n\n\t\t\t\tfor(i=1;i<MAXORDER;i++)\n\t\t\t\t\t(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;\n\n\t\t\t\t(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);\n\n\t\t\t\tfor(i=0;i<MAXORDER;i++){\n\t\t\t\t\tprintf(\"\\nSize Order < 10^%2d bytes |\",i);\n\t\t\t\t\tfor(j=0;j<(int)(scale*fileSizeLog[i]);j++)\n\t\t\t\t\t\tprintf(\"%c\",219);\n\t\t\t\t\tprintf(\"%Ld\",fileSizeLog[i]);\n\t\t\t\t}\n\t\t}\n\n\t}\n\treturn 0;\n\t}\n}\n"}
{"id": 60711, "name": "Unix_ls", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint cmpstr(const void *a, const void *b)\n{\n    return strcmp(*(const char**)a, *(const char**)b);\n}\n\nint main(void)\n{\n    DIR *basedir;\n    char path[PATH_MAX];\n    struct dirent *entry;\n    char **dirnames;\n    int diralloc = 128;\n    int dirsize  = 0;\n    \n    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {\n        perror(\"malloc error:\");\n        return 1;\n    }\n\n    if (!getcwd(path, PATH_MAX)) {\n        perror(\"getcwd error:\");\n        return 1;\n    }\n\n    if (!(basedir = opendir(path))) {\n        perror(\"opendir error:\");\n        return 1;\n    }\n\n    while ((entry = readdir(basedir))) {\n        if (dirsize >= diralloc) {\n            diralloc *= 2;\n            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {\n                perror(\"realloc error:\");\n                return 1;\n            }\n        }\n        dirnames[dirsize++] = strdup(entry->d_name);\n    }\n\n    qsort(dirnames, dirsize, sizeof(char*), cmpstr);\n\n    int i;\n    for (i = 0; i < dirsize; ++i) {\n        if (dirnames[i][0] != '.') {\n            printf(\"%s\\n\", dirnames[i]);\n        }\n    }\n\n    for (i = 0; i < dirsize; ++i)\n        free(dirnames[i]);\n    free(dirnames);\n    closedir(basedir);\n    return 0;\n}\n"}
{"id": 60712, "name": "Rendezvous", "Go": "package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n    \"sync\"\n)\n\nvar hdText = `Humpty Dumpty sat on a wall.\nHumpty Dumpty had a great fall.\nAll the king's horses and all the king's men,\nCouldn't put Humpty together again.`\n\nvar mgText = `Old Mother Goose,\nWhen she wanted to wander,\nWould ride through the air,\nOn a very fine gander.\nJack's mother came in,\nAnd caught the goose soon,\nAnd mounting its back,\nFlew up to the moon.`\n\nfunc main() {\n    reservePrinter := startMonitor(newPrinter(5), nil)\n    mainPrinter := startMonitor(newPrinter(5), reservePrinter)\n    var busy sync.WaitGroup\n    busy.Add(2)\n    go writer(mainPrinter, \"hd\", hdText, &busy)\n    go writer(mainPrinter, \"mg\", mgText, &busy)\n    busy.Wait()\n}\n\n\n\n\ntype printer func(string) error\n\n\n\n\n\nfunc newPrinter(ink int) printer {\n    return func(line string) error {\n        if ink == 0 {\n            return eOutOfInk\n        }\n        for _, c := range line {\n            fmt.Printf(\"%c\", c)\n        }\n        fmt.Println()\n        ink--\n        return nil\n    }\n}\n\nvar eOutOfInk = errors.New(\"out of ink\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype rSync struct {\n    call     chan string\n    response chan error\n}\n\n\n\n\n\n\nfunc (r *rSync) print(data string) error {\n    r.call <- data      \n    return <-r.response \n}\n\n\n\n\nfunc monitor(hardPrint printer, entry, reserve *rSync) {\n    for {\n        \n        \n        data := <-entry.call\n        \n        \n        \n\n        \n        switch err := hardPrint(data); {\n\n        \n        case err == nil:\n            entry.response <- nil \n\n        case err == eOutOfInk && reserve != nil:\n            \n            \n            \n            \n            entry.response <- reserve.print(data)\n\n        default:\n            entry.response <- err \n        }\n        \n    }\n}\n\n\n\n\n\n\nfunc startMonitor(p printer, reservePrinter *rSync) *rSync {\n    entry := &rSync{make(chan string), make(chan error)}\n    go monitor(p, entry, reservePrinter)\n    return entry\n}\n\n\n\n\n\n\nfunc writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {\n    for _, line := range strings.Split(text, \"\\n\") {\n        if err := printMonitor.print(line); err != nil {\n            fmt.Printf(\"**** writer task %q terminated: %v ****\\n\", id, err)\n            break\n        }\n    }\n    busy.Done()\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <pthread.h>\n\n\n\n\ntypedef struct rendezvous {\n    pthread_mutex_t lock;        \n    pthread_cond_t cv_entering;  \n    pthread_cond_t cv_accepting; \n    pthread_cond_t cv_done;      \n    int (*accept_func)(void*);   \n    int entering;                \n    int accepting;               \n    int done;                    \n} rendezvous_t;\n\n\n#define RENDEZVOUS_INITILIZER(accept_function) {   \\\n        .lock         = PTHREAD_MUTEX_INITIALIZER, \\\n        .cv_entering  = PTHREAD_COND_INITIALIZER,  \\\n        .cv_accepting = PTHREAD_COND_INITIALIZER,  \\\n        .cv_done      = PTHREAD_COND_INITIALIZER,  \\\n        .accept_func  = accept_function,           \\\n        .entering     = 0,                         \\\n        .accepting    = 0,                         \\\n        .done         = 0,                         \\\n    }\n\nint enter_rendezvous(rendezvous_t *rv, void* data)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n\n    rv->entering++;\n    pthread_cond_signal(&rv->cv_entering);\n\n    while (!rv->accepting) {\n        \n        pthread_cond_wait(&rv->cv_accepting, &rv->lock);\n    }\n\n    \n    int ret = rv->accept_func(data);\n\n    \n    rv->done = 1;\n    pthread_cond_signal(&rv->cv_done);\n\n    rv->entering--;\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n\n    return ret;\n}\n\nvoid accept_rendezvous(rendezvous_t *rv)\n{\n    \n    pthread_mutex_lock(&rv->lock);\n    rv->accepting = 1;\n\n    while (!rv->entering) {\n        \n        pthread_cond_wait(&rv->cv_entering, &rv->lock);\n    }\n\n    pthread_cond_signal(&rv->cv_accepting);\n\n    while (!rv->done) {\n        \n        pthread_cond_wait(&rv->cv_done, &rv->lock);\n    }\n    rv->done = 0;\n\n    rv->accepting = 0;\n    pthread_mutex_unlock(&rv->lock);\n}\n\n\n\ntypedef struct printer {\n    rendezvous_t rv;\n    struct printer *backup;\n    int id;\n    int remaining_lines;\n} printer_t;\n\ntypedef struct print_args {\n    struct printer *printer;\n    const char* line;\n} print_args_t;\n\nint print_line(printer_t *printer, const char* line) {\n    print_args_t args;\n    args.printer = printer;\n    args.line = line;\n    return enter_rendezvous(&printer->rv, &args);\n}\n\nint accept_print(void* data) {\n    \n    print_args_t *args = (print_args_t*)data;\n    printer_t *printer = args->printer;\n    const char* line = args->line;\n\n    if (printer->remaining_lines) {\n        \n        printf(\"%d: \", printer->id);\n        while (*line != '\\0') {\n            putchar(*line++);\n        }\n        putchar('\\n');\n        printer->remaining_lines--;\n        return 1;\n    }\n    else if (printer->backup) {\n        \n        return print_line(printer->backup, line);\n    }\n    else {\n        \n        return -1;\n    }\n}\n\nprinter_t backup_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = NULL,\n    .id = 2,\n    .remaining_lines = 5,\n};\n\nprinter_t main_printer = {\n    .rv = RENDEZVOUS_INITILIZER(accept_print),\n    .backup = &backup_printer,\n    .id = 1,\n    .remaining_lines = 5,\n};\n\nvoid* printer_thread(void* thread_data) {\n    printer_t *printer = (printer_t*) thread_data;\n    while (1) {\n        accept_rendezvous(&printer->rv);\n    }\n}\n\ntypedef struct poem {\n    char* name;\n    char* lines[];\n} poem_t;\n\npoem_t humpty_dumpty = {\n    .name = \"Humpty Dumpty\",\n    .lines = {\n        \"Humpty Dumpty sat on a wall.\",\n        \"Humpty Dumpty had a great fall.\",\n        \"All the king's horses and all the king's men\",\n        \"Couldn't put Humpty together again.\",\n        \"\"\n    },\n};\n\npoem_t mother_goose = {\n    .name = \"Mother Goose\",\n    .lines = {\n        \"Old Mother Goose\",\n        \"When she wanted to wander,\",\n        \"Would ride through the air\",\n        \"On a very fine gander.\",\n        \"Jack's mother came in,\",\n        \"And caught the goose soon,\",\n        \"And mounting its back,\",\n        \"Flew up to the moon.\",\n        \"\"\n    },\n};\n\nvoid* poem_thread(void* thread_data) {\n    poem_t *poem = (poem_t*)thread_data;\n\n    for (unsigned i = 0; poem->lines[i] != \"\"; i++) {\n        int ret = print_line(&main_printer, poem->lines[i]);\n        if (ret < 0) {\n            printf(\"      %s out of ink!\\n\", poem->name);\n            exit(1);\n        }\n    }\n    return NULL;\n}\n\nint main(void)\n{\n    pthread_t threads[4];\n\n    pthread_create(&threads[0], NULL, poem_thread,    &humpty_dumpty);\n    pthread_create(&threads[1], NULL, poem_thread,    &mother_goose);\n    pthread_create(&threads[2], NULL, printer_thread, &main_printer);\n    pthread_create(&threads[3], NULL, printer_thread, &backup_printer);\n\n    pthread_join(threads[0], NULL);\n    pthread_join(threads[1], NULL);\n    pthread_cancel(threads[2]);\n    pthread_cancel(threads[3]);\n\n    return 0;\n}\n"}
{"id": 60713, "name": "Primes whose first and last number is 3", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var primes []int\n    candidates := []int{3, 33}\n    for i := 303; i <= 393; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for i := 3003; i <= 3993; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for _, cand := range candidates {\n        if rcu.IsPrime(cand) {\n            primes = append(primes, cand)\n        }\n    }\n    fmt.Println(\"Primes under 4,000 which begin and end in 3:\")\n    for i, p := range primes {\n        fmt.Printf(\"%5s \", rcu.Commatize(p))\n        if (i+1)%11 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(primes), \"Such primes.\")\n    pc := len(primes)\n    for i := 30003; i <= 39993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    for i := 300003; i <= 399993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    pcc := rcu.Commatize(pc)\n    fmt.Println(\"\\nFound\", pcc, \"primes under 1,000,000 which begin and end with 3.\")\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main(void) {\n    int np = 1, d, i, n;\n    printf( \"3  \" );\n    for(d=1; d<6; d++) {\n        for(i=3; i<pow(10,d)-1; i+=10) {\n            n = i + 3*pow(10,d);\n            if(isprime(n)) {\n                ++np;\n                if(n<4009) {\n                    printf(\"%d  \",n);\n                    if(!(np%10)) printf(\"\\n\");\n                }\n            }\n        }\n    }\n    printf( \"\\n\\nThere were %d primes of the form 3x3 below one million.\\n\", np );\n    return 0;\n}\n"}
{"id": 60714, "name": "Primes whose first and last number is 3", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var primes []int\n    candidates := []int{3, 33}\n    for i := 303; i <= 393; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for i := 3003; i <= 3993; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for _, cand := range candidates {\n        if rcu.IsPrime(cand) {\n            primes = append(primes, cand)\n        }\n    }\n    fmt.Println(\"Primes under 4,000 which begin and end in 3:\")\n    for i, p := range primes {\n        fmt.Printf(\"%5s \", rcu.Commatize(p))\n        if (i+1)%11 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(primes), \"Such primes.\")\n    pc := len(primes)\n    for i := 30003; i <= 39993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    for i := 300003; i <= 399993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    pcc := rcu.Commatize(pc)\n    fmt.Println(\"\\nFound\", pcc, \"primes under 1,000,000 which begin and end with 3.\")\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main(void) {\n    int np = 1, d, i, n;\n    printf( \"3  \" );\n    for(d=1; d<6; d++) {\n        for(i=3; i<pow(10,d)-1; i+=10) {\n            n = i + 3*pow(10,d);\n            if(isprime(n)) {\n                ++np;\n                if(n<4009) {\n                    printf(\"%d  \",n);\n                    if(!(np%10)) printf(\"\\n\");\n                }\n            }\n        }\n    }\n    printf( \"\\n\\nThere were %d primes of the form 3x3 below one million.\\n\", np );\n    return 0;\n}\n"}
{"id": 60715, "name": "Primes whose first and last number is 3", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    var primes []int\n    candidates := []int{3, 33}\n    for i := 303; i <= 393; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for i := 3003; i <= 3993; i += 10 {\n        candidates = append(candidates, i)\n    }\n    for _, cand := range candidates {\n        if rcu.IsPrime(cand) {\n            primes = append(primes, cand)\n        }\n    }\n    fmt.Println(\"Primes under 4,000 which begin and end in 3:\")\n    for i, p := range primes {\n        fmt.Printf(\"%5s \", rcu.Commatize(p))\n        if (i+1)%11 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\nFound\", len(primes), \"Such primes.\")\n    pc := len(primes)\n    for i := 30003; i <= 39993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    for i := 300003; i <= 399993; i += 10 {\n        if rcu.IsPrime(i) {\n            pc++\n        }\n    }\n    pcc := rcu.Commatize(pc)\n    fmt.Println(\"\\nFound\", pcc, \"primes under 1,000,000 which begin and end with 3.\")\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main(void) {\n    int np = 1, d, i, n;\n    printf( \"3  \" );\n    for(d=1; d<6; d++) {\n        for(i=3; i<pow(10,d)-1; i+=10) {\n            n = i + 3*pow(10,d);\n            if(isprime(n)) {\n                ++np;\n                if(n<4009) {\n                    printf(\"%d  \",n);\n                    if(!(np%10)) printf(\"\\n\");\n                }\n            }\n        }\n    }\n    printf( \"\\n\\nThere were %d primes of the form 3x3 below one million.\\n\", np );\n    return 0;\n}\n"}
{"id": 60716, "name": "First class environments", "Go": "package main\n\nimport \"fmt\"\n\nconst jobs = 12\n\ntype environment struct{ seq, cnt int }\n\nvar (\n    env      [jobs]environment\n    seq, cnt *int\n)\n\nfunc hail() {\n    fmt.Printf(\"% 4d\", *seq)\n    if *seq == 1 {\n        return\n    }\n    (*cnt)++\n    if *seq&1 != 0 {\n        *seq = 3*(*seq) + 1\n    } else {\n        *seq /= 2\n    }\n}\n\nfunc switchTo(id int) {\n    seq = &env[id].seq\n    cnt = &env[id].cnt\n}\n\nfunc main() {\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        env[i].seq = i + 1\n    }\n\nagain:\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        hail()\n    }\n    fmt.Println()\n\n    for j := 0; j < jobs; j++ {\n        switchTo(j)\n        if *seq != 1 {\n            goto again\n        }\n    }\n    fmt.Println()\n\n    fmt.Println(\"COUNTS:\")\n    for i := 0; i < jobs; i++ {\n        switchTo(i)\n        fmt.Printf(\"% 4d\", *cnt)\n    }\n    fmt.Println()\n}\n", "C": "#include <stdio.h>\n\n#define JOBS 12\n#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf(\"\\n\"); switch_to(++a))\ntypedef struct { int seq, cnt; } env_t;\n\nenv_t env[JOBS] = {{0, 0}};\nint *seq, *cnt;\n\nvoid hail()\n{\n\tprintf(\"% 4d\", *seq);\n\tif (*seq == 1) return;\n\t++*cnt;\n\t*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;\n}\n\nvoid switch_to(int id)\n{\n\tseq = &env[id].seq;\n\tcnt = &env[id].cnt;\n}\n\nint main()\n{\n\tint i;\n\tjobs(i) { env[i].seq = i + 1; }\n\nagain:\tjobs(i) { hail(); }\n\tjobs(i) { if (1 != *seq) goto again; }\n\n\tprintf(\"COUNTS:\\n\");\n\tjobs(i) { printf(\"% 4d\", *cnt); }\n\n\treturn 0;\n}\n"}
{"id": 60717, "name": "UTF-8 encode and decode", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/hex\"\n    \"fmt\"\n    \"log\"\n    \"strings\"\n)\n\nvar testCases = []struct {\n    rune\n    string\n}{\n    {'A', \"41\"},\n    {'ö', \"C3 B6\"},\n    {'Ж', \"D0 96\"},\n    {'€', \"E2 82 AC\"},\n    {'𝄞', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        \n        u := fmt.Sprintf(\"U+%04X\", tc.rune)\n        b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n        if err != nil {\n            log.Fatal(\"bad test data\")\n        }\n        \n        e := encodeUTF8(tc.rune)\n        d := decodeUTF8(b)\n        \n        fmt.Printf(\"%c  %-7s  %X\\n\", d, u, e)\n        \n        if !bytes.Equal(e, b) {\n            log.Fatal(\"encodeUTF8 wrong\")\n        }\n        if d != tc.rune {\n            log.Fatal(\"decodeUTF8 wrong\")\n        }\n    }\n}\n\nconst (\n    \n    b2Lead = 0xC0 \n    b2Mask = 0x1F \n\n    \n    b3Lead = 0xE0 \n    b3Mask = 0x0F \n\n    \n    b4Lead = 0xF0 \n    b4Mask = 0x07 \n\n    \n    mbLead = 0x80 \n    mbMask = 0x3F \n)\n\nfunc encodeUTF8(r rune) []byte {\n    switch i := uint32(r); {\n    case i <= 1<<7-1: \n        return []byte{byte(r)}\n    case i <= 1<<11-1: \n        return []byte{\n            b2Lead | byte(r>>6),\n            mbLead | byte(r)&mbMask}\n    case i <= 1<<16-1: \n        return []byte{\n            b3Lead | byte(r>>12),\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    default:\n        return []byte{\n            b4Lead | byte(r>>18),\n            mbLead | byte(r>>12)&mbMask,\n            mbLead | byte(r>>6)&mbMask,\n            mbLead | byte(r)&mbMask}\n    }\n}\n\nfunc decodeUTF8(b []byte) rune {\n    switch b0 := b[0]; {\n    case b0 < 0x80:\n        return rune(b0)\n    case b0 < 0xE0:\n        return rune(b0&b2Mask)<<6 |\n            rune(b[1]&mbMask)\n    case b0 < 0xF0:\n        return rune(b0&b3Mask)<<12 |\n            rune(b[1]&mbMask)<<6 |\n            rune(b[2]&mbMask)\n    default:\n        return rune(b0&b4Mask)<<18 |\n            rune(b[1]&mbMask)<<12 |\n            rune(b[2]&mbMask)<<6 |\n            rune(b[3]&mbMask)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n\ntypedef struct {\n\tchar mask;    \n\tchar lead;    \n\tuint32_t beg; \n\tuint32_t end; \n\tint bits_stored; \n}utf_t;\n\nutf_t * utf[] = {\n\t\n\t[0] = &(utf_t){0b00111111, 0b10000000, 0,       0,        6    },\n\t[1] = &(utf_t){0b01111111, 0b00000000, 0000,    0177,     7    },\n\t[2] = &(utf_t){0b00011111, 0b11000000, 0200,    03777,    5    },\n\t[3] = &(utf_t){0b00001111, 0b11100000, 04000,   0177777,  4    },\n\t[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3    },\n\t      &(utf_t){0},\n};\n\n\nint codepoint_len(const uint32_t cp); \nint utf8_len(const char ch);          \n\nchar *to_utf8(const uint32_t cp);\nuint32_t to_cp(const char chr[4]);\n\nint codepoint_len(const uint32_t cp)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((cp >= (*u)->beg) && (cp <= (*u)->end)) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) \n\t\texit(1);\n\n\treturn len;\n}\n\nint utf8_len(const char ch)\n{\n\tint len = 0;\n\tfor(utf_t **u = utf; *u; ++u) {\n\t\tif((ch & ~(*u)->mask) == (*u)->lead) {\n\t\t\tbreak;\n\t\t}\n\t\t++len;\n\t}\n\tif(len > 4) { \n\t\texit(1);\n\t}\n\treturn len;\n}\n\nchar *to_utf8(const uint32_t cp)\n{\n\tstatic char ret[5];\n\tconst int bytes = codepoint_len(cp);\n\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;\n\tshift -= utf[0]->bits_stored;\n\tfor(int i = 1; i < bytes; ++i) {\n\t\tret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;\n\t\tshift -= utf[0]->bits_stored;\n\t}\n\tret[bytes] = '\\0';\n\treturn ret;\n}\n\nuint32_t to_cp(const char chr[4])\n{\n\tint bytes = utf8_len(*chr);\n\tint shift = utf[0]->bits_stored * (bytes - 1);\n\tuint32_t codep = (*chr++ & utf[bytes]->mask) << shift;\n\n\tfor(int i = 1; i < bytes; ++i, ++chr) {\n\t\tshift -= utf[0]->bits_stored;\n\t\tcodep |= ((char)*chr & utf[0]->mask) << shift;\n\t}\n\n\treturn codep;\n}\n\nint main(void)\n{\n\tconst uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};\n\n\tprintf(\"Character  Unicode  UTF-8 encoding (hex)\\n\");\n\tprintf(\"----------------------------------------\\n\");\n\n\tchar *utf8;\n\tuint32_t codepoint;\n\tfor(in = input; *in; ++in) {\n\t\tutf8 = to_utf8(*in);\n\t\tcodepoint = to_cp(utf8);\n\t\tprintf(\"%s          U+%-7.4x\", utf8, codepoint);\n\n\t\tfor(int i = 0; utf8[i] && i < 4; ++i) {\n\t\t\tprintf(\"%hhx \", utf8[i]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n"}
{"id": 60718, "name": "Xiaolin Wu's line algorithm", "Go": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n    return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n    return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n    return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n    return 1 - fpart(x)\n}\n\n\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n    \n    dx := x2 - x1\n    dy := y2 - y1\n    ax := dx\n    if ax < 0 {\n        ax = -ax\n    }\n    ay := dy\n    if ay < 0 {\n        ay = -ay\n    }\n    \n    var plot func(int, int, float64)\n    if ax < ay {\n        x1, y1 = y1, x1\n        x2, y2 = y2, x2\n        dx, dy = dy, dx\n        plot = func(x, y int, c float64) {\n            g.SetPx(y, x, uint16(c*math.MaxUint16))\n        }\n    } else {\n        plot = func(x, y int, c float64) {\n            g.SetPx(x, y, uint16(c*math.MaxUint16))\n        }\n    }\n    if x2 < x1 {\n        x1, x2 = x2, x1\n        y1, y2 = y2, y1\n    }\n    gradient := dy / dx\n\n    \n    xend := round(x1)\n    yend := y1 + gradient*(xend-x1)\n    xgap := rfpart(x1 + .5)\n    xpxl1 := int(xend) \n    ypxl1 := int(ipart(yend))\n    plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n    intery := yend + gradient \n\n    \n    xend = round(x2)\n    yend = y2 + gradient*(xend-x2)\n    xgap = fpart(x2 + 0.5)\n    xpxl2 := int(xend) \n    ypxl2 := int(ipart(yend))\n    plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n    \n    for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n        plot(x, int(ipart(intery)), rfpart(intery))\n        plot(x, int(ipart(intery))+1, fpart(intery))\n        intery = intery + gradient\n    }\n}\n", "C": "void draw_line_antialias(\n        image img,\n        unsigned int x0, unsigned int y0,\n        unsigned int x1, unsigned int y1,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 60719, "name": "Keyboard macros", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"unsafe\"\n\nfunc main() {\n    d := C.XOpenDisplay(nil)\n    f7, f6 := C.CString(\"F7\"), C.CString(\"F6\")\n    defer C.free(unsafe.Pointer(f7))\n    defer C.free(unsafe.Pointer(f6))\n\n    if d != nil {\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),\n            C.Mod1Mask, \n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),\n            C.Mod1Mask,\n            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)\n\n        var event C.XEvent\n        for {\n            C.XNextEvent(d, &event)\n            if C.getXEvent_type(event) == C.KeyPress {\n                xkeyEvent := C.getXEvent_xkey(event)\n                s := C.XLookupKeysym(&xkeyEvent, 0)\n                if s == C.XK_F7 {\n                    fmt.Println(\"something's happened\")\n                } else if s == C.XK_F6 {\n                    break\n                }\n            }\n        }\n\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))\n    } else {\n        fmt.Println(\"XOpenDisplay did not succeed\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/keysym.h>\n\nint main()\n{\n  Display *d;\n  XEvent event;\n  \n  d = XOpenDisplay(NULL);\n  if ( d != NULL ) {\n                \n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), \n\t     Mod1Mask,  \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), \n\t     Mod1Mask, \n\t     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);\n\n    for(;;)\n    {\n      XNextEvent(d, &event);\n      if ( event.type == KeyPress ) {\n\tKeySym s = XLookupKeysym(&event.xkey, 0);\n\tif ( s == XK_F7 ) {\n\t  printf(\"something's happened\\n\");\n\t} else if ( s == XK_F6 ) {\n\t  break;\n\t}\n      }\n    }\n\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F7\")), Mod1Mask, DefaultRootWindow(d));\n    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym(\"F6\")), Mod1Mask, DefaultRootWindow(d));\n  }\n  return EXIT_SUCCESS;\n}\n"}
{"id": 60720, "name": "McNuggets problem", "Go": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n    sv := make([]bool, limit+1) \n    for s := 0; s <= limit; s += 6 {\n        for n := s; n <= limit; n += 9 {\n            for t := n; t <= limit; t += 20 {\n                sv[t] = true\n            }\n        }\n    }\n    for i := limit; i >= 0; i-- {\n        if !sv[i] {\n            fmt.Println(\"Maximum non-McNuggets number is\", i)\n            return\n        }\n    }\n}\n\nfunc main() {\n    mcnugget(100)\n}\n", "C": "#include <stdio.h>\n\nint\nmain() {\n    int max = 0, i = 0, sixes, nines, twenties;\n\nloopstart: while (i < 100) {\n        for (sixes = 0; sixes*6 < i; sixes++) {\n            if (sixes*6 == i) {\n                i++;\n                goto loopstart;\n            }\n\n            for (nines = 0; nines*9 < i; nines++) {\n                if (sixes*6 + nines*9 == i) {\n                    i++;\n                    goto loopstart;\n                }\n\n                for (twenties = 0; twenties*20 < i; twenties++) {\n                    if (sixes*6 + nines*9 + twenties*20 == i) {\n                        i++;\n                        goto loopstart;\n                    }\n                }\n            }\n        }\n        max = i;\n        i++;\n    }\n\n    printf(\"Maximum non-McNuggets number is %d\\n\", max);\n\n    return 0;\n}\n"}
{"id": 60721, "name": "Magic squares of doubly even order", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 \n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n", "C": "#include<stdlib.h>\n#include<ctype.h>\n#include<stdio.h>\n\nint** doublyEvenMagicSquare(int n) {\n\tif (n < 4 || n % 4 != 0)\n\t\treturn NULL;\n\n\tint bits = 38505;\n\tint size = n * n;\n\tint mult = n / 4,i,r,c,bitPos;\n\n\tint** result = (int**)malloc(n*sizeof(int*));\n\t\n\tfor(i=0;i<n;i++)\n\t\tresult[i] = (int*)malloc(n*sizeof(int));\n\n\tfor (r = 0, i = 0; r < n; r++) {\n\t\tfor (c = 0; c < n; c++, i++) {\n\t\t\tbitPos = c / mult + (r / mult) * 4;\n\t\t\tresult[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;\n\t\t}\n\t}\n\treturn result;\n}\n\nint numDigits(int n){\n\tint count = 1;\n\t\n\twhile(n>=10){\n\t\tn /= 10;\n\t\tcount++;\n\t}\n\t\n\treturn count;\n}\n\nvoid printMagicSquare(int** square,int rows){\n\tint i,j,baseWidth = numDigits(rows*rows) + 3;\n\t\n\tprintf(\"Doubly Magic Square of Order : %d and Magic Constant : %d\\n\\n\",rows,(rows * rows + 1) * rows / 2);\n\t\n\tfor(i=0;i<rows;i++){\n\t\tfor(j=0;j<rows;j++){\n\t\t\tprintf(\"%*s%d\",baseWidth - numDigits(square[i][j]),\"\",square[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint n;\n\t\n\tif(argC!=2||isdigit(argV[1][0])==0)\n\t\tprintf(\"Usage : %s <integer specifying rows in magic square>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\tprintMagicSquare(doublyEvenMagicSquare(n),n);\n\t}\n\treturn 0;\n}\n"}
{"id": 60722, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n"}
{"id": 60723, "name": "Extreme floating point values", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    var zero float64                         \n    var negZero, posInf, negInf, nan float64 \n    negZero = zero * -1\n    posInf = 1 / zero\n    negInf = -1 / zero\n    nan = zero / zero\n\n    \n    fmt.Println(negZero, posInf, negInf, nan)\n\n    \n    fmt.Println(math.Float64frombits(1<<63),\n        math.Inf(1), math.Inf(-1), math.NaN())\n\n    \n    fmt.Println()\n    validateNaN(negInf+posInf, \"-Inf + Inf\")\n    validateNaN(0*posInf, \"0 * Inf\")\n    validateNaN(posInf/posInf, \"Inf / Inf\")\n    \n    \n    validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n    validateNaN(1+nan, \"1 + NaN\")\n    validateZero(1/posInf, \"1 / Inf\")\n    validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n    validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n    validateNE(nan, nan, \"NaN != NaN\")\n    validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n    if math.IsNaN(n) {\n        fmt.Println(op, \"-> NaN\")\n    } else {\n        fmt.Println(\"!!! Expected NaN from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateZero(n float64, op string) {\n    if n == 0 {\n        fmt.Println(op, \"-> 0\")\n    } else {\n        fmt.Println(\"!!! Expected 0 from\", op, \"  Found\", n)\n    }\n}\n\nfunc validateGT(a, b float64, op string) {\n    if a > b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n\nfunc validateNE(a, b float64, op string) {\n    if a == b {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    } else {\n        fmt.Println(op)\n    }\n}\n\nfunc validateEQ(a, b float64, op string) {\n    if a == b {\n        fmt.Println(op)\n    } else {\n        fmt.Println(\"!!! Expected\", op, \"  Found not true.\")\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n    double inf = 1/0.0;\n    double minus_inf = -1/0.0;\n    double minus_zero = -1/ inf ;\n    double nan = 0.0/0.0;\n\n    printf(\"positive infinity: %f\\n\",inf);\n    printf(\"negative infinity: %f\\n\",minus_inf);\n    printf(\"negative zero: %f\\n\",minus_zero);\n    printf(\"not a number: %f\\n\",nan);\n\n    \n\n    printf(\"+inf + 2.0 = %f\\n\",inf + 2.0);\n    printf(\"+inf - 10.1 = %f\\n\",inf - 10.1);\n    printf(\"+inf + -inf = %f\\n\",inf + minus_inf);\n    printf(\"0.0 * +inf = %f\\n\",0.0 * inf);\n    printf(\"1.0/-0.0 = %f\\n\",1.0/minus_zero);\n    printf(\"NaN + 1.0 = %f\\n\",nan + 1.0);\n    printf(\"NaN + NaN = %f\\n\",nan + nan);\n\n    \n\n    printf(\"NaN == NaN = %s\\n\",nan == nan ? \"true\" : \"false\");\n    printf(\"0.0 == -0.0 = %s\\n\",0.0 == minus_zero ? \"true\" : \"false\");\n\n    return 0;\n}\n"}
{"id": 60724, "name": "Pseudo-random numbers_Xorshift star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n    x := xor.state\n    x = x ^ (x >> 12)\n    x = x ^ (x << 25)\n    x = x ^ (x >> 27)\n    xor.state = x\n    return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n    return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n    randomGen := XorshiftStarNew(1234567)\n    for i := 0; i < 5; i++ {\n        fmt.Println(randomGen.nextInt())\n    }\n\n    var counts [5]int\n    randomGen.seed(987654321)\n    for i := 0; i < 1e5; i++ {\n        j := int(math.Floor(randomGen.nextFloat() * 5))\n        counts[j]++\n    }\n    fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"  %d : %d\\n\", i, counts[i])\n    }\n}\n", "C": "#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstatic uint64_t state;\nstatic const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;\n\nvoid seed(uint64_t num) {\n    state = num;\n}\n\nuint32_t next_int() {\n    uint64_t x;\n    uint32_t answer;\n\n    x = state;\n    x = x ^ (x >> 12);\n    x = x ^ (x << 25);\n    x = x ^ (x >> 27);\n    state = x;\n    answer = ((x * STATE_MAGIC) >> 32);\n\n    return answer;\n}\n\nfloat next_float() {\n    return (float)next_int() / (1LL << 32);\n}\n\nint main() {\n    int counts[5] = { 0, 0, 0, 0, 0 };\n    int i;\n\n    seed(1234567);\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"%u\\n\", next_int());\n    printf(\"\\n\");\n\n    seed(987654321);\n    for (i = 0; i < 100000; i++) {\n        int j = (int)floor(next_float() * 5.0);\n        counts[j]++;\n    }\n    for (i = 0; i < 5; i++) {\n        printf(\"%d: %d\\n\", i, counts[i]);\n    }\n\n    return 0;\n}\n"}
{"id": 60725, "name": "Four is the number of letters in the ...", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\"  Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti     int      \n\twords []string \n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n\n\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n\n\n\n\n\n", "C": "#include <ctype.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"biliionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\ntypedef struct word_tag {\n    size_t offset;\n    size_t length;\n} word_t;\n\ntypedef struct word_list_tag {\n    GArray* words;\n    GString* str;\n} word_list;\n\nvoid word_list_create(word_list* words) {\n    words->words = g_array_new(FALSE, FALSE, sizeof(word_t));\n    words->str = g_string_new(NULL);\n}\n\nvoid word_list_destroy(word_list* words) {\n    g_string_free(words->str, TRUE);\n    g_array_free(words->words, TRUE);\n}\n\nvoid word_list_clear(word_list* words) {\n    g_string_truncate(words->str, 0);\n    g_array_set_size(words->words, 0);\n}\n\nvoid word_list_append(word_list* words, const char* str) {\n    size_t offset = words->str->len;\n    size_t len = strlen(str);\n    g_string_append_len(words->str, str, len);\n    word_t word;\n    word.offset = offset;\n    word.length = len;\n    g_array_append_val(words->words, word);\n}\n\nword_t* word_list_get(word_list* words, size_t index) {\n    return &g_array_index(words->words, word_t, index);\n}\n\nvoid word_list_extend(word_list* words, const char* str) {\n    word_t* word = word_list_get(words, words->words->len - 1);\n    size_t len = strlen(str);\n    word->length += len;\n    g_string_append_len(words->str, str, len);\n}\n\nsize_t append_number_name(word_list* words, integer n, bool ordinal) {\n    size_t count = 0;\n    if (n < 20) {\n        word_list_append(words, get_small_name(&small[n], ordinal));\n        count = 1;\n    } else if (n < 100) {\n        if (n % 10 == 0) {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            word_list_append(words, get_small_name(&tens[n/10 - 2], false));\n            word_list_extend(words, \"-\");\n            word_list_extend(words, get_small_name(&small[n % 10], ordinal));\n        }\n        count = 1;\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        count += append_number_name(words, n/p, false);\n        if (n % p == 0) {\n            word_list_append(words, get_big_name(num, ordinal));\n            ++count;\n        } else {\n            word_list_append(words, get_big_name(num, false));\n            ++count;\n            count += append_number_name(words, n % p, ordinal);\n        }\n    }\n    return count;\n}\n\nsize_t count_letters(word_list* words, size_t index) {\n    const word_t* word = word_list_get(words, index);\n    size_t letters = 0;\n    const char* s = words->str->str + word->offset;\n    for (size_t i = 0, n = word->length; i < n; ++i) {\n        if (isalpha((unsigned char)s[i]))\n            ++letters;\n    }\n    return letters;\n}\n\nvoid sentence(word_list* result, size_t count) {\n    static const char* words[] = {\n        \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n        \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n    };\n    word_list_clear(result);\n    size_t n = sizeof(words)/sizeof(words[0]);\n    for (size_t i = 0; i < n; ++i)\n        word_list_append(result, words[i]);\n    for (size_t i = 1; count > n; ++i) {\n        n += append_number_name(result, count_letters(result, i), false);\n        word_list_append(result, \"in\");\n        word_list_append(result, \"the\");\n        n += 2;\n        n += append_number_name(result, i + 1, true);\n        \n        word_list_extend(result, \",\");\n    }\n}\n\nsize_t sentence_length(const word_list* words) {\n    size_t n = words->words->len;\n    if (n == 0)\n        return 0;\n    return words->str->len + n - 1;\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    size_t n = 201;\n    word_list result = { 0 };\n    word_list_create(&result);\n    sentence(&result, n);\n    printf(\"Number of letters in first %'lu words in the sequence:\\n\", n);\n    for (size_t i = 0; i < n; ++i) {\n        if (i != 0)\n            printf(\"%c\", i % 25 == 0 ? '\\n' : ' ');\n        printf(\"%'2lu\", count_letters(&result, i));\n    }\n    printf(\"\\nSentence length: %'lu\\n\", sentence_length(&result));\n    for (n = 1000; n <= 10000000; n *= 10) {\n        sentence(&result, n);\n        const word_t* word = word_list_get(&result, n - 1);\n        const char* s = result.str->str + word->offset;\n        printf(\"The %'luth word is '%.*s' and has %lu letters. \", n,\n               (int)word->length, s, count_letters(&result, n - 1));\n        printf(\"Sentence length: %'lu\\n\" , sentence_length(&result));\n    }\n    word_list_destroy(&result);\n    return 0;\n}\n"}
{"id": 60726, "name": "Calendar - for _REAL_ programmers", "Go": "PACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n", "C": "\n\n\n\n\n\nINT PUTCHAR(INT);\n\nINT WIDTH = 80, YEAR = 1969;\nINT COLS, LEAD, GAP;\n \nCONST CHAR *WDAYS[] = { \"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\" };\nSTRUCT MONTHS {\n    CONST CHAR *NAME;\n    INT DAYS, START_WDAY, AT;\n} MONTHS[12] = {\n    { \"JANUARY\",    31, 0, 0 },\n    { \"FEBRUARY\",    28, 0, 0 },\n    { \"MARCH\",    31, 0, 0 },\n    { \"APRIL\",    30, 0, 0 },\n    { \"MAY\",    31, 0, 0 },\n    { \"JUNE\",    30, 0, 0 },\n    { \"JULY\",    31, 0, 0 },\n    { \"AUGUST\",    31, 0, 0 },\n    { \"SEPTEMBER\",    30, 0, 0 },\n    { \"OCTOBER\",    31, 0, 0 },\n    { \"NOVEMBER\",    30, 0, 0 },\n    { \"DECEMBER\",    31, 0, 0 }\n};\n \nVOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }\nVOID PRINT(CONST CHAR * S){ WHILE (*S != '\\0') { PUTCHAR(*S++); } }\nINT  STRLEN(CONST CHAR * S)\n{\n   INT L = 0;\n   WHILE (*S++ != '\\0') { L ++; };\nRETURN L;\n}\nINT ATOI(CONST CHAR * S)\n{\n    INT I = 0;\n    INT SIGN = 1;\n    CHAR C;\n    WHILE ((C = *S++) != '\\0') {\n        IF (C == '-')\n            SIGN *= -1;\n        ELSE {\n            I *= 10;\n            I += (C - '0');\n        }\n    }\nRETURN I * SIGN;\n}\n\nVOID INIT_MONTHS(VOID)\n{\n    INT I;\n \n    IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))\n        MONTHS[1].DAYS = 29;\n \n    YEAR--;\n    MONTHS[0].START_WDAY\n        = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;\n \n    FOR (I = 1; I < 12; I++)\n        MONTHS[I].START_WDAY =\n            (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;\n \n    COLS = (WIDTH + 2) / 22;\n    WHILE (12 % COLS) COLS--;\n    GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;\n    IF (GAP > 4) GAP = 4;\n    LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;\n        YEAR++;\n}\n \nVOID PRINT_ROW(INT ROW)\n{\n    INT C, I, FROM = ROW * COLS, TO = FROM + COLS;\n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        I = STRLEN(MONTHS[C].NAME);\n        SPACE((20 - I)/2);\n        PRINT(MONTHS[C].NAME);\n        SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));\n    }\n    PUTCHAR('\\012');\n \n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        FOR (I = 0; I < 7; I++) {\n            PRINT(WDAYS[I]);\n            PRINT(I == 6 ? \"\" : \" \");\n        }\n        IF (C < TO - 1) SPACE(GAP);\n        ELSE PUTCHAR('\\012');\n    }\n \n    WHILE (1) {\n        FOR (C = FROM; C < TO; C++)\n            IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;\n        IF (C == TO) BREAK;\n \n        SPACE(LEAD);\n        FOR (C = FROM; C < TO; C++) {\n            FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);\n            WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {\n                INT MM = ++MONTHS[C].AT;\n                PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));\n                PUTCHAR('0' + (MM %10));\n                IF (I < 7 || C < TO - 1) PUTCHAR(' ');\n            }\n            WHILE (I++ <= 7 && C < TO - 1) SPACE(3);\n            IF (C < TO - 1) SPACE(GAP - 1);\n            MONTHS[C].START_WDAY = 0;\n        }\n        PUTCHAR('\\012');\n    }\n    PUTCHAR('\\012');\n}\n \nVOID PRINT_YEAR(VOID)\n{\n    INT Y = YEAR;\n    INT ROW;\n    CHAR BUF[32];\n    CHAR * B = &(BUF[31]);\n    *B-- = '\\0';\n    DO {\n        *B-- = '0' + (Y % 10);\n        Y /= 10;\n    } WHILE (Y > 0);\n    B++;\n    SPACE((WIDTH - STRLEN(B)) / 2);\n    PRINT(B);PUTCHAR('\\012');PUTCHAR('\\012');\n    FOR (ROW = 0; ROW * COLS < 12; ROW++)\n        PRINT_ROW(ROW);\n}\n \nINT MAIN(INT C, CHAR **V)\n{\n    INT I, YEAR_SET = 0, RESULT = 0;\n    FOR (I = 1; I < C && RESULT == 0; I++) {\n        IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\\0') {\n            IF (++I == C || (WIDTH = ATOI(V[I])) < 20)\n                RESULT = 1;\n        } ELSE IF (!YEAR_SET) {\n            YEAR = ATOI(V[I]);\n            IF (YEAR <= 0)\n                YEAR = 1969;\n            YEAR_SET = 1;\n        } ELSE\n            RESULT = 1;\n    }\n \n    IF (RESULT == 0) {\n        INIT_MONTHS();\n        PRINT_YEAR();\n    } ELSE {\n        PRINT(\"BAD ARGS\\012USAGE: \");\n        PRINT(V[0]);\n        PRINT(\" YEAR [-W WIDTH (>= 20)]\\012\");\n    }\nRETURN RESULT;\n}\n"}
{"id": 60727, "name": "ASCII art diagram converter", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"strings\"\n)\n\ntype result struct {\n    name  string\n    size  int\n    start int\n    end   int\n}\n\nfunc (r result) String() string {\n    return fmt.Sprintf(\"%-7s   %2d    %3d   %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n    var lines []string\n    for _, line := range strings.Split(diagram, \"\\n\") {\n        line = strings.Trim(line, \" \\t\")\n        if line != \"\" {\n            lines = append(lines, line)\n        }\n    }\n    if len(lines) == 0 {\n        log.Fatal(\"diagram has no non-empty lines!\")\n    }\n    width := len(lines[0])\n    cols := (width - 1) / 3\n    if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n        log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n    }\n    if len(lines)%2 == 0 {\n        log.Fatal(\"number of non-empty lines should be odd\")\n    }\n    if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n        log.Fatal(\"incorrect header line\")\n    }\n    for i, line := range lines {\n        if i == 0 {\n            continue\n        } else if i%2 == 0 {\n            if line != lines[0] {\n                log.Fatal(\"incorrect separator line\")\n            }\n        } else if len(line) != width {\n            log.Fatal(\"inconsistent line widths\")\n        } else if line[0] != '|' || line[width-1] != '|' {\n            log.Fatal(\"non-separator lines must begin and end with '|'\")\n        }\n    }\n    return lines\n}\n\nfunc decode(lines []string) []result {\n    fmt.Println(\"Name     Bits  Start  End\")\n    fmt.Println(\"=======  ====  =====  ===\")\n    start := 0\n    width := len(lines[0])\n    var results []result\n    for i, line := range lines {\n        if i%2 == 0 {\n            continue\n        }\n        line := line[1 : width-1]\n        for _, name := range strings.Split(line, \"|\") {\n            size := (len(name) + 1) / 3\n            name = strings.TrimSpace(name)\n            res := result{name, size, start, start + size - 1}\n            results = append(results, res)\n            fmt.Println(res)\n            start += size\n        }\n    }\n    return results\n}\n\nfunc unpack(results []result, hex string) {\n    fmt.Println(\"\\nTest string in hex:\")\n    fmt.Println(hex)\n    fmt.Println(\"\\nTest string in binary:\")\n    bin := hex2bin(hex)\n    fmt.Println(bin)\n    fmt.Println(\"\\nUnpacked:\\n\")\n    fmt.Println(\"Name     Size  Bit pattern\")\n    fmt.Println(\"=======  ====  ================\")\n    for _, res := range results {\n        fmt.Printf(\"%-7s   %2d   %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n    }\n}\n\nfunc hex2bin(hex string) string {\n    z := new(big.Int)\n    z.SetString(hex, 16)\n    return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n    const diagram = `\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n         |                      ID                       |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    QDCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n        |                    ANCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    NSCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n        |                    ARCOUNT                    |\n        +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n    `\n    lines := validate(diagram)\n    fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n    for _, line := range lines {\n        fmt.Println(line)\n    }\n    fmt.Println(\"\\nDecoded:\\n\")\n    results := decode(lines)\n    hex := \"78477bbf5496e12e1bf169a4\" \n    unpack(results, hex)\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\nenum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };\n\nchar *Lines[MAX_ROWS] = {\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                      ID                       |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    QDCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ANCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    NSCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\",\n   \"  |                    ARCOUNT                    |\",\n   \"  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\"\n};\ntypedef struct {\n   unsigned bit3s;\n   unsigned mask;\n   unsigned data;\n   char A[NAME_SZ+2];\n}NAME_T;\nNAME_T names[MAX_NAMES];\nunsigned idx_name;\nenum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};\nunsigned header[MAX_HDR]; \nunsigned idx_hdr;\n\nint  bit_hdr(char *pLine);\nint  bit_names(char *pLine);\nvoid dump_names(void);\nvoid make_test_hdr(void);\n\nint main(void){\n   char *p1;   int rv;\n   printf(\"Extract meta-data from bit-encoded text form\\n\");\n   make_test_hdr();\n   idx_name = 0;\n   for( int i=0; i<MAX_ROWS;i++ ){\n      p1 = Lines[i];\n      if( p1==NULL ) break;\n      if( rv = bit_hdr(Lines[i]), rv>0) continue;\n      if( rv = bit_names(Lines[i]),rv>0) continue;\n      \n   }\n   dump_names();\n}\n\nint  bit_hdr(char *pLine){ \n   char *p1 = strchr(pLine,'+');\n   if( p1==NULL ) return 0;\n   int numbits=0;\n   for( int i=0; i<strlen(p1)-1; i+=3 ){\n      if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;\n      numbits++;\n   }\n   return numbits;\n}\n\nint  bit_names(char *pLine){ \n   char *p1,*p2 = pLine, tmp[80];\n   unsigned sz=0, maskbitcount = 15;\n   while(1){\n      p1 = strchr(p2,'|');  if( p1==NULL ) break;\n      p1++;\n      p2 = strchr(p1,'|');  if( p2==NULL ) break;\n      sz = p2-p1;\n      tmp[sz] = 0;  \n      int k=0;\n      for(int j=0; j<sz;j++){  \n\t if( p1[j] > ' ') tmp[k++] = p1[j];\n      }\n      tmp[k]= 0; sz++;\n      NAME_T *pn = &names[idx_name++];\n      strcpy(&pn->A[0], &tmp[0]);\n      pn->bit3s = sz/3;\n      if( pn->bit3s < 16 ){\n\t for( int i=0; i<pn->bit3s; i++){\n\t    pn->mask |= 1 << maskbitcount--;\n\t }\n\t pn->data = header[idx_hdr] & pn->mask;\n\t unsigned m2 = pn->mask;\n\t while( (m2 & 1)==0 ){\n\t    m2>>=1; \n\t    pn->data >>= 1;\n\t }\n\t if( pn->mask == 0xf ) idx_hdr++;\n\n      }\n      else{\n\t pn->data = header[idx_hdr++];\n      }\n   }\n   return sz;\n}\n\nvoid dump_names(void){ \n   NAME_T *pn;\n   printf(\"-name-bits-mask-data-\\n\");\n   for( int i=0; i<MAX_NAMES; i++ ){\n      pn = &names[i];\n      if( pn->bit3s < 1 ) break;\n      printf(\"%10s %2d X%04x = %u\\n\",pn->A, pn->bit3s, pn->mask, pn->data);\n   }\n   puts(\"bye..\");\n}\n\nvoid make_test_hdr(void){\n   header[ID] = 1024;\n   header[QDCOUNT] = 12;\n   header[ANCOUNT] = 34;\n   header[NSCOUNT] = 56;\n   header[ARCOUNT] = 78;\n   \n   \n   \n   \n   header[BITS] = 0xB50A;\n}\n"}
{"id": 60728, "name": "Levenshtein distance_Alignment", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"github.com/biogo/biogo/align\"\n    ab \"github.com/biogo/biogo/alphabet\"\n    \"github.com/biogo/biogo/feat\"\n    \"github.com/biogo/biogo/seq/linear\"\n)\n\nfunc main() {\n    \n    \n    lc := ab.Must(ab.NewAlphabet(\"-abcdefghijklmnopqrstuvwxyz\",\n        feat.Undefined, '-', 0, true))\n    \n    \n    \n    \n    nw := make(align.NW, lc.Len())\n    for i := range nw {\n        r := make([]int, lc.Len())\n        nw[i] = r\n        for j := range r {\n            if j != i {\n                r[j] = -1\n            }\n        }\n    }\n    \n    a := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"rosettacode\"))}\n    a.Alpha = lc\n    b := &linear.Seq{Seq: ab.BytesToLetters([]byte(\"raisethysword\"))}\n    b.Alpha = lc\n    \n    aln, err := nw.Align(a, b)\n    \n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fa := align.Format(a, b, aln, '-')\n    fmt.Printf(\"%s\\n%s\\n\", fa[0], fa[1])\n    aa := fmt.Sprint(fa[0])\n    ba := fmt.Sprint(fa[1])\n    ma := make([]byte, len(aa))\n    for i := range ma {\n        if aa[i] == ba[i] {\n            ma[i] = ' '\n        } else {\n            ma[i] = '|'\n        }\n    }\n    fmt.Println(string(ma))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct edit_s edit_t, *edit;\nstruct edit_s {\n\tchar c1, c2;\n\tint n;\n\tedit next;\n};\n\nvoid leven(char *a, char *b)\n{\n\tint i, j, la = strlen(a), lb = strlen(b);\n\tedit *tbl = malloc(sizeof(edit) * (1 + la));\n\ttbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));\n\tfor (i = 1; i <= la; i++)\n\t\ttbl[i] = tbl[i-1] + (1+lb);\n\n\tfor (i = la; i >= 0; i--) {\n\t\tchar *aa = a + i;\n\t\tfor (j = lb; j >= 0; j--) {\n\t\t\tchar *bb = b + j;\n\t\t\tif (!*aa && !*bb) continue;\n\n\t\t\tedit e = &tbl[i][j];\n\t\t\tedit repl = &tbl[i+1][j+1];\n\t\t\tedit dela = &tbl[i+1][j];\n\t\t\tedit delb = &tbl[i][j+1];\n\n\t\t\te->c1 = *aa;\n\t\t\te->c2 = *bb;\n\t\t\tif (!*aa) {\n\t\t\t\te->next = delb;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!*bb) {\n\t\t\t\te->next = dela;\n\t\t\t\te->n = e->next->n + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\te->next = repl;\n\t\t\tif (*aa == *bb) {\n\t\t\t\te->n = e->next->n;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (e->next->n > delb->n) {\n\t\t\t\te->next = delb;\n\t\t\t\te->c1 = 0;\n\t\t\t}\n\t\t\tif (e->next->n > dela->n) {\n\t\t\t\te->next = dela;\n\t\t\t\te->c1 = *aa;\n\t\t\t\te->c2 = 0;\n\t\t\t}\n\t\t\te->n = e->next->n + 1;\n\t\t}\n\t}\n\n\tedit p = tbl[0];\n\tprintf(\"%s -> %s: %d edits\\n\", a, b, p->n);\n\n\twhile (p->next) {\n\t\tif (p->c1 == p->c2)\n\t\t\tprintf(\"%c\", p->c1);\n\t\telse {\n\t\t\tputchar('(');\n\t\t\tif (p->c1) putchar(p->c1);\n\t\t\tputchar(',');\n\t\t\tif (p->c2) putchar(p->c2);\n\t\t\tputchar(')');\n\t\t}\n\n\t\tp = p->next;\n\t}\n\tputchar('\\n');\n\n\tfree(tbl[0]);\n\tfree(tbl);\n}\n\nint main(void)\n{\n\tleven(\"raisethysword\", \"rosettacode\");\n\treturn 0;\n}\n"}
{"id": 60729, "name": "Compare sorting algorithms' performance", "Go": "package main\n\nimport (\n    \"log\"\n    \"math/rand\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/gonum/plot\"\n    \"github.com/gonum/plot/plotter\"\n    \"github.com/gonum/plot/plotutil\"\n    \"github.com/gonum/plot/vg\"\n)\n\n\n\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\nfunc insertionsort(a []int) {\n    for i := 1; i < len(a); i++ {\n        value := a[i]\n        j := i - 1\n        for j >= 0 && a[j] > value {\n            a[j+1] = a[j]\n            j = j - 1\n        }\n        a[j+1] = value\n    }\n}\n\nfunc quicksort(a []int) {\n    var pex func(int, int)\n    pex = func(lower, upper int) {\n        for {\n            switch upper - lower {\n            case -1, 0:\n                return\n            case 1:\n                if a[upper] < a[lower] {\n                    a[upper], a[lower] = a[lower], a[upper]\n                }\n                return\n            }\n            bx := (upper + lower) / 2\n            b := a[bx]\n            lp := lower\n            up := upper\n        outer:\n            for {\n                for lp < upper && !(b < a[lp]) {\n                    lp++\n                }\n                for {\n                    if lp > up {\n                        break outer\n                    }\n                    if a[up] < b {\n                        break\n                    }\n                    up--\n                }\n                a[lp], a[up] = a[up], a[lp]\n                lp++\n                up--\n            }\n            if bx < lp {\n                if bx < lp-1 {\n                    a[bx], a[lp-1] = a[lp-1], b\n                }\n                up = lp - 2\n            } else {\n                if bx > lp {\n                    a[bx], a[lp] = a[lp], b\n                }\n                up = lp - 1\n                lp++\n            }\n            if up-lower < upper-lp {\n                pex(lower, up)\n                lower = lp\n            } else {\n                pex(lp, upper)\n                upper = up\n            }\n        }\n    }\n    pex(0, len(a)-1)\n}\n\n\n\nfunc ones(n int) []int {\n    s := make([]int, n)\n    for i := range s {\n        s[i] = 1\n    }\n    return s\n}\n\nfunc ascending(n int) []int {\n    s := make([]int, n)\n    v := 1\n    for i := 0; i < n; {\n        if rand.Intn(3) == 0 {\n            s[i] = v\n            i++\n        }\n        v++\n    }\n    return s\n}\n\nfunc shuffled(n int) []int {\n    return rand.Perm(n)\n}\n\n\n\n\n\n\nconst (\n    nPts = 7    \n    inc  = 1000 \n)\n\nvar (\n    p        *plot.Plot\n    sortName = []string{\"Bubble sort\", \"Insertion sort\", \"Quicksort\"}\n    sortFunc = []func([]int){bubblesort, insertionsort, quicksort}\n    dataName = []string{\"Ones\", \"Ascending\", \"Shuffled\"}\n    dataFunc = []func(int) []int{ones, ascending, shuffled}\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    var err error\n    p, err = plot.New()\n    if err != nil {\n        log.Fatal(err)\n    }\n    p.X.Label.Text = \"Data size\"\n    p.Y.Label.Text = \"microseconds\"\n    p.Y.Scale = plot.LogScale{}\n    p.Y.Tick.Marker = plot.LogTicks{}\n    p.Y.Min = .5 \n\n    for dx, name := range dataName {\n        s, err := plotter.NewScatter(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        s.Shape = plotutil.DefaultGlyphShapes[dx]\n        p.Legend.Add(name, s)\n    }\n    for sx, name := range sortName {\n        l, err := plotter.NewLine(plotter.XYs{})\n        if err != nil {\n            log.Fatal(err)\n        }\n        l.Color = plotutil.DarkColors[sx]\n        p.Legend.Add(name, l)\n    }\n    for sx := range sortFunc {\n        bench(sx, 0, 1) \n        bench(sx, 1, 5) \n        bench(sx, 2, 5) \n    }\n\n    if err := p.Save(5*vg.Inch, 5*vg.Inch, \"comp.png\"); err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc bench(sx, dx, rep int) {\n    log.Println(\"bench\", sortName[sx], dataName[dx], \"x\", rep)\n    pts := make(plotter.XYs, nPts)\n    sf := sortFunc[sx]\n    for i := range pts {\n        x := (i + 1) * inc\n        \n        \n        \n        s0 := dataFunc[dx](x) \n        s := make([]int, x)   \n        var tSort int64\n        for j := 0; j < rep; j++ {\n            tSort += testing.Benchmark(func(b *testing.B) {\n                for i := 0; i < b.N; i++ {\n                    copy(s, s0)\n                    sf(s)\n                }\n            }).NsPerOp()\n        }\n        tSort /= int64(rep)\n        log.Println(x, \"items\", tSort, \"ns\") \n        pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001}\n    }\n    pl, ps, err := plotter.NewLinePoints(pts) \n    if err != nil {\n        log.Fatal(err)\n    }\n    pl.Color = plotutil.DarkColors[sx]\n    ps.Color = plotutil.DarkColors[sx]\n    ps.Shape = plotutil.DefaultGlyphShapes[dx]\n    p.Add(pl, ps)\n}\n", "C": "#ifndef _CSEQUENCE_H\n#define _CSEQUENCE_H\n#include <stdlib.h>\n\nvoid setfillconst(double c);\nvoid fillwithconst(double *v, int n);\nvoid fillwithrrange(double *v, int n);\nvoid shuffledrange(double *v, int n);\n#endif\n"}
{"id": 60730, "name": "Same fringe", "Go": "package main\n\nimport \"fmt\"\n\ntype node struct {\n    int\n    left, right *node\n}\n\n\n\nfunc leaves(t *node) chan int {\n    ch := make(chan int)\n    \n    var f func(*node)\n    f = func(n *node) {\n        if n == nil {\n            return\n        }\n        \n        if n.left == nil && n.right == nil {\n            ch <- n.int\n        } else {\n            f(n.left)\n            f(n.right)\n        }\n    }\n    \n    \n    go func() {\n        f(t)\n        close(ch)\n    }()\n    return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n    f1 := leaves(t1)\n    f2 := leaves(t2)\n    for l1 := range f1 {\n        \n        if l2, ok := <-f2; !ok || l1 != l2 {\n            return false\n        }\n    }\n    \n    _, ok := <-f2\n    return !ok\n}\n\nfunc main() {\n    \n    \n    t1 := &node{3,\n        &node{1,\n            &node{int: 1},\n            &node{int: 2}},\n        &node{8,\n            &node{int: 5},\n            &node{int: 13}}}\n    \n    \n    t2 := &node{-8,\n        &node{-3,\n            &node{-1,\n                &node{int: 1},\n                &node{int: 2}},\n            &node{int: 5}},\n        &node{int: 13}}\n    fmt.Println(sameFringe(t1, t2)) \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <ucontext.h>\n\ntypedef struct {\n\tucontext_t caller, callee;\n\tchar stack[8192];\n\tvoid *in, *out;\n} co_t;\n\nco_t * co_new(void(*f)(), void *data)\n{\n\tco_t * c = malloc(sizeof(*c));\n\tgetcontext(&c->callee);\n\tc->in = data;\n\n\tc->callee.uc_stack.ss_sp = c->stack;\n\tc->callee.uc_stack.ss_size = sizeof(c->stack);\n\tc->callee.uc_link = &c->caller;\n\tmakecontext(&c->callee, f, 1, (int)c);\n\n\treturn c;\n}\n\nvoid co_del(co_t *c)\n{\n\tfree(c);\n}\n\ninline void\nco_yield(co_t *c, void *data)\n{\n\tc->out = data;\n\tswapcontext(&c->callee, &c->caller);\n}\n\ninline void *\nco_collect(co_t *c)\n{\n\tc->out = 0;\n\tswapcontext(&c->caller, &c->callee);\n\treturn c->out;\n}\n\n\n\ntypedef struct node node;\nstruct node {\n\tint v;\n\tnode *left, *right;\n};\n\nnode *newnode(int v)\n{\n\tnode *n = malloc(sizeof(node));\n\tn->left = n->right = 0;\n\tn->v = v;\n\treturn n;\n}\n\nvoid tree_insert(node **root, node *n)\n{\n\twhile (*root) root = ((*root)->v > n->v)\n\t\t\t\t? &(*root)->left\n\t\t\t\t: &(*root)->right;\n\t*root = n;\n}\n\nvoid tree_trav(int x)\n{\n\tco_t *c = (co_t *) x;\n\n\tvoid trav(node *root) {\n\t\tif (!root) return;\n\t\ttrav(root->left);\n\t\tco_yield(c, root);\n\t\ttrav(root->right);\n\t}\n\n\ttrav(c->in);\n}\n\nint tree_eq(node *t1, node *t2)\n{\n\tco_t *c1 = co_new(tree_trav, t1);\n\tco_t *c2 = co_new(tree_trav, t2);\n\n\tnode *p = 0, *q = 0;\n\tdo {\n\t\tp = co_collect(c1);\n\t\tq = co_collect(c2);\n\t} while (p && q && (p->v == q->v));\n\n\tco_del(c1);\n\tco_del(c2);\n\treturn !p && !q;\n}\n\nint main()\n{\n\tint x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };\n\tint y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };\n\tint z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };\n\n\tnode *t1 = 0, *t2 = 0, *t3 = 0;\n\n\tvoid mktree(int *buf, node **root) {\n\t\tint i;\n\t\tfor (i = 0; buf[i] >= 0; i++)\n\t\t\ttree_insert(root, newnode(buf[i]));\n\t}\n\n\tmktree(x, &t1); \n\tmktree(y, &t2); \n\tmktree(z, &t3);\n\n\tprintf(\"t1 == t2: %s\\n\", tree_eq(t1, t2) ? \"yes\" : \"no\");\n\tprintf(\"t1 == t3: %s\\n\", tree_eq(t1, t3) ? \"yes\" : \"no\");\n\n\treturn 0;\n}\n"}
{"id": 60731, "name": "Parse command-line arguments", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n"}
{"id": 60732, "name": "Parse command-line arguments", "Go": "package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n)\n\nfunc main() {\n    b := flag.Bool(\"b\", false, \"just a boolean\")\n    s := flag.String(\"s\", \"\", \"any ol' string\")\n    n := flag.Int(\"n\", 0, \"your lucky number\")\n    flag.Parse()\n    fmt.Println(\"b:\", *b)\n    fmt.Println(\"s:\", *s)\n    fmt.Println(\"n:\", *n)\n}\n", "C": "#include <stdio.h>\nint main(int argc, char **argv){\n    int i;\n    const char *commands[]={\"-c\", \"-p\", \"-t\", \"-d\", \"-a\", NULL};\n    enum {CREATE,PRINT,TITLE,DATE,AUTH};\n    if (argc<2) {\nusage:   printf (\"Usage: %s [commands]\\n\" \n            \"-c  Create new entry.\\n\" \n            \"-p  Print the latest entry.\\n\" \n            \"-t  Sort by title.\\n\" \n            \"-d  Sort by date.\\n\" \n            \"-a  Sort by author.\\n\",argv[0]);\n        return 0;\n    }\n    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);\n    switch (i) {\n    case CREATE:\n...\n    break;\n    case PRINT:\n...\n    break;\n...\n...\n    default:\n    printf (\"Unknown command...\" ...);\n    goto usage;\n    }\n    return 0;\n}\n"}
{"id": 60733, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n"}
{"id": 60734, "name": "Show the (decimal) value of a number of 1s appended with a 3, then squared", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc a(n int) {\n    s, _ := strconv.Atoi(strings.Repeat(\"1\", n) + \"3\")\n    t := s * s\n    fmt.Printf(\"%d %d\\n\", s, t)\n}\n\nfunc main() {\n    for n := 0; n <= 7; n++ {\n        a(n)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\nuint64_t ones_plus_three(uint64_t ones) {\n    uint64_t r = 0;\n    while (ones--) r = r*10 + 1;\n    return r*10 + 3;\n}\n\nint main() {\n    uint64_t n;\n    for (n=0; n<8; n++) {\n        uint64_t x = ones_plus_three(n);\n        printf(\"%8lu^2 = %15lu\\n\", x, x*x);\n    }\n    return 0;\n}\n"}
{"id": 60735, "name": "Simulate input_Keyboard", "Go": "package main\n\nimport (\n    \"github.com/micmonay/keybd_event\"\n    \"log\"\n    \"runtime\"\n    \"time\"\n)\n\nfunc main() {\n    kb, err := keybd_event.NewKeyBonding()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    \n    if runtime.GOOS == \"linux\" {\n        time.Sleep(2 * time.Second)\n    }\n\n    \n    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)\n\n    \n    err = kb.Launching()\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n\nint main(int argc, char *argv[])\n{\n  Display *dpy;\n  Window win;\n  GC gc;\n  int scr;\n  Atom WM_DELETE_WINDOW;\n  XEvent ev;\n  XEvent ev2;\n  KeySym keysym;\n  int loop;\n\n  \n  dpy = XOpenDisplay(NULL);\n  if (dpy == NULL) {\n    fputs(\"Cannot open display\", stderr);\n    exit(1);\n  }\n  scr = XDefaultScreen(dpy);\n\n  \n  win = XCreateSimpleWindow(dpy,\n          XRootWindow(dpy, scr),\n          \n          10, 10, 300, 200, 1,\n          \n          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));\n\n  \n  XStoreName(dpy, win, argv[0]);\n\n  \n  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);\n\n  \n  XMapWindow(dpy, win);\n  XFlush(dpy);\n\n  \n  gc = XDefaultGC(dpy, scr);\n\n  \n  WM_DELETE_WINDOW = XInternAtom(dpy, \"WM_DELETE_WINDOW\", True);\n  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);\n\n  \n  loop = 1;\n  while (loop) {\n    XNextEvent(dpy, &ev);\n    switch (ev.type)\n    {\n      case Expose:\n        \n        {\n          char msg1[] = \"Clic in the window to generate\";\n          char msg2[] = \"a key press event\";\n          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);\n          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);\n        }\n        break;\n\n      case ButtonPress:\n        puts(\"ButtonPress event received\");\n        \n        ev2.type = KeyPress;\n        ev2.xkey.state = ShiftMask;\n        ev2.xkey.keycode = 24 + (rand() % 33);\n        ev2.xkey.same_screen = True;\n        XSendEvent(dpy, win, True, KeyPressMask, &ev2);\n        break;\n   \n      case ClientMessage:\n        \n        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)\n          loop = 0;\n        break;\n   \n      case KeyPress:\n        \n        puts(\"KeyPress event received\");\n        printf(\"> keycode: %d\\n\", ev.xkey.keycode);\n        \n        keysym = XLookupKeysym(&(ev.xkey), 0);\n        if (keysym == XK_q ||\n            keysym == XK_Escape) {\n          loop = 0;\n        } else {\n          char buffer[] = \"  \";\n          int nchars = XLookupString(\n                &(ev.xkey),\n                buffer,\n                2,  \n                &keysym,\n                NULL );\n          if (nchars == 1)\n            printf(\"> Key '%c' pressed\\n\", buffer[0]);\n        }\n        break;\n    }\n  }\n  XDestroyWindow(dpy, win);\n  \n  XCloseDisplay(dpy);\n  return 1;\n}\n"}
{"id": 60736, "name": "Peaceful chess queen armies", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    empty = iota\n    black\n    white\n)\n\nconst (\n    bqueen  = 'B'\n    wqueen  = 'W'\n    bbullet = '•'\n    wbullet = '◦'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n    if i < 0 {\n        return -i\n    }\n    return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n    if m == 0 {\n        return true\n    }\n    placingBlack := true\n    for i := 0; i < n; i++ {\n    inner:\n        for j := 0; j < n; j++ {\n            pos := position{i, j}\n            for _, queen := range *pBlackQueens {\n                if queen == pos || !placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            for _, queen := range *pWhiteQueens {\n                if queen == pos || placingBlack && isAttacking(queen, pos) {\n                    continue inner\n                }\n            }\n            if placingBlack {\n                *pBlackQueens = append(*pBlackQueens, pos)\n                placingBlack = false\n            } else {\n                *pWhiteQueens = append(*pWhiteQueens, pos)\n                if place(m-1, n, pBlackQueens, pWhiteQueens) {\n                    return true\n                }\n                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n                placingBlack = true\n            }\n        }\n    }\n    if !placingBlack {\n        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n    }\n    return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n    if queen.i == pos.i {\n        return true\n    }\n    if queen.j == pos.j {\n        return true\n    }\n    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n        return true\n    }\n    return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n    board := make([]int, n*n)\n    for _, queen := range blackQueens {\n        board[queen.i*n+queen.j] = black\n    }\n    for _, queen := range whiteQueens {\n        board[queen.i*n+queen.j] = white\n    }\n\n    for i, b := range board {\n        if i != 0 && i%n == 0 {\n            fmt.Println()\n        }\n        switch b {\n        case black:\n            fmt.Printf(\"%c \", bqueen)\n        case white:\n            fmt.Printf(\"%c \", wqueen)\n        case empty:\n            if i%2 == 0 {\n                fmt.Printf(\"%c \", bbullet)\n            } else {\n                fmt.Printf(\"%c \", wbullet)\n            }\n        }\n    }\n    fmt.Println(\"\\n\")\n}\n\nfunc main() {\n    nms := [][2]int{\n        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n    }\n    for _, nm := range nms {\n        n, m := nm[0], nm[1]\n        fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n        var blackQueens, whiteQueens []position\n        if place(m, n, &blackQueens, &whiteQueens) {\n            printBoard(n, blackQueens, whiteQueens)\n        } else {\n            fmt.Println(\"No solution exists.\\n\")\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nenum Piece {\n    Empty,\n    Black,\n    White,\n};\n\ntypedef struct Position_t {\n    int x, y;\n} Position;\n\n\n\nstruct Node_t {\n    Position pos;\n    struct Node_t *next;\n};\n\nvoid releaseNode(struct Node_t *head) {\n    if (head == NULL) return;\n\n    releaseNode(head->next);\n    head->next = NULL;\n\n    free(head);\n}\n\ntypedef struct List_t {\n    struct Node_t *head;\n    struct Node_t *tail;\n    size_t length;\n} List;\n\nList makeList() {\n    return (List) { NULL, NULL, 0 };\n}\n\nvoid releaseList(List *lst) {\n    if (lst == NULL) return;\n\n    releaseNode(lst->head);\n    lst->head = NULL;\n    lst->tail = NULL;\n}\n\nvoid addNode(List *lst, Position pos) {\n    struct Node_t *newNode;\n\n    if (lst == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode = malloc(sizeof(struct Node_t));\n    if (newNode == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    newNode->next = NULL;\n    newNode->pos = pos;\n\n    if (lst->head == NULL) {\n        lst->head = lst->tail = newNode;\n    } else {\n        lst->tail->next = newNode;\n        lst->tail = newNode;\n    }\n\n    lst->length++;\n}\n\nvoid removeAt(List *lst, size_t pos) {\n    if (lst == NULL) return;\n\n    if (pos == 0) {\n        struct Node_t *temp = lst->head;\n\n        if (lst->tail == lst->head) {\n            lst->tail = NULL;\n        }\n\n        lst->head = lst->head->next;\n        temp->next = NULL;\n\n        free(temp);\n        lst->length--;\n    } else {\n        struct Node_t *temp = lst->head;\n        struct Node_t *rem;\n        size_t i = pos;\n\n        while (i-- > 1) {\n            temp = temp->next;\n        }\n\n        rem = temp->next;\n        if (rem == lst->tail) {\n            lst->tail = temp;\n        }\n\n        temp->next = rem->next;\n\n        rem->next = NULL;\n        free(rem);\n\n        lst->length--;\n    }\n}\n\n\n\nbool isAttacking(Position queen, Position pos) {\n    return queen.x == pos.x\n        || queen.y == pos.y\n        || abs(queen.x - pos.x) == abs(queen.y - pos.y);\n}\n\nbool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {\n    struct Node_t *queenNode;\n    bool placingBlack = true;\n    int i, j;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    if (m == 0) return true;\n    for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n            Position pos = { i, j };\n\n            queenNode = pBlackQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            queenNode = pWhiteQueens->head;\n            while (queenNode != NULL) {\n                if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {\n                    goto inner;\n                }\n                queenNode = queenNode->next;\n            }\n\n            if (placingBlack) {\n                addNode(pBlackQueens, pos);\n                placingBlack = false;\n            } else {\n                addNode(pWhiteQueens, pos);\n                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n                    return true;\n                }\n                removeAt(pBlackQueens, pBlackQueens->length - 1);\n                removeAt(pWhiteQueens, pWhiteQueens->length - 1);\n                placingBlack = true;\n            }\n\n        inner: {}\n        }\n    }\n    if (!placingBlack) {\n        removeAt(pBlackQueens, pBlackQueens->length - 1);\n    }\n    return false;\n}\n\nvoid printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {\n    size_t length = n * n;\n    struct Node_t *queenNode;\n    char *board;\n    size_t i, j, k;\n\n    if (pBlackQueens == NULL || pWhiteQueens == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    board = calloc(length, sizeof(char));\n    if (board == NULL) {\n        exit(EXIT_FAILURE);\n    }\n\n    queenNode = pBlackQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = Black;\n        queenNode = queenNode->next;\n    }\n\n    queenNode = pWhiteQueens->head;\n    while (queenNode != NULL) {\n        board[queenNode->pos.x * n + queenNode->pos.y] = White;\n        queenNode = queenNode->next;\n    }\n\n    for (i = 0; i < length; i++) {\n        if (i != 0 && i % n == 0) {\n            printf(\"\\n\");\n        }\n        switch (board[i]) {\n        case Black:\n            printf(\"B \");\n            break;\n        case White:\n            printf(\"W \");\n            break;\n        default:\n            j = i / n;\n            k = i - j * n;\n            if (j % 2 == k % 2) {\n                printf(\"  \");\n            } else {\n                printf(\"# \");\n            }\n            break;\n        }\n    }\n\n    printf(\"\\n\\n\");\n}\n\nvoid test(int n, int q) {\n    List blackQueens = makeList();\n    List whiteQueens = makeList();\n\n    printf(\"%d black and %d white queens on a %d x %d board:\\n\", q, q, n, n);\n    if (place(q, n, &blackQueens, &whiteQueens)) {\n        printBoard(n, &blackQueens, &whiteQueens);\n    } else {\n        printf(\"No solution exists.\\n\\n\");\n    }\n\n    releaseList(&blackQueens);\n    releaseList(&whiteQueens);\n}\n\nint main() {\n    test(2, 1);\n\n    test(3, 1);\n    test(3, 2);\n\n    test(4, 1);\n    test(4, 2);\n    test(4, 3);\n\n    test(5, 1);\n    test(5, 2);\n    test(5, 3);\n    test(5, 4);\n    test(5, 5);\n\n    test(6, 1);\n    test(6, 2);\n    test(6, 3);\n    test(6, 4);\n    test(6, 5);\n    test(6, 6);\n\n    test(7, 1);\n    test(7, 2);\n    test(7, 3);\n    test(7, 4);\n    test(7, 5);\n    test(7, 6);\n    test(7, 7);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 60737, "name": "Loops_Infinite", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor {\n\t\tfmt.Printf(\"SPAM\\n\")\n\t}\n}\n", "C": "while(1) puts(\"SPAM\");\n"}
{"id": 60738, "name": "Metaprogramming", "Go": "package main\n\nimport \"fmt\"\n\ntype person struct{\n    name string\n    age int\n}\n\nfunc copy(p person) person {\n    return person{p.name, p.age}\n}\n\nfunc main() {\n    p := person{\"Dave\", 40}\n    fmt.Println(p)\n    q := copy(p)\n    fmt.Println(q)\n     \n}\n", "C": "\n#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]\n\n#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)\n#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)\n#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)\n\nCOMPILE_TIME_ASSERT(sizeof(long)==8); \nint main()\n{\n    COMPILE_TIME_ASSERT(sizeof(int)==4); \n}\n"}
{"id": 60739, "name": "Numbers with same digit set in base 10 and base 16", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc equalSets(s1, s2 map[rune]bool) bool {\n    if len(s1) != len(s2) {\n        return false\n    }\n    for k, _ := range s1 {\n        _, ok := s2[k]\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    const limit = 100_000\n    count := 0\n    fmt.Println(\"Numbers under 100,000 which use the same digits in decimal or hex:\")\n    for n := 0; n < limit; n++ {\n        h := strconv.FormatInt(int64(n), 16)\n        hs := make(map[rune]bool)\n        for _, c := range h {\n            hs[c] = true\n        }\n        ns := make(map[rune]bool)\n        for _, c := range strconv.Itoa(n) {\n            ns[c] = true\n        }\n        if equalSets(hs, ns) {\n            count++\n            fmt.Printf(\"%6s \", rcu.Commatize(n))\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n    }\n    fmt.Printf(\"\\n\\n%d such numbers found.\\n\", count)\n}\n", "C": "#include <stdio.h>\n#define LIMIT 100000\n\nint digitset(int num, int base) {\n    int set;\n    for (set = 0; num; num /= base)\n        set |= 1 << num % base;\n    return set;\n}\n\nint main() {\n    int i, c = 0;\n    for (i = 0; i < LIMIT; i++)\n        if (digitset(i,10) == digitset(i,16))\n            printf(\"%6d%c\", i, ++c%10 ? ' ' : '\\n');\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60740, "name": "Largest prime factor", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestPrimeFactor(n uint64) uint64 {\n    if n < 2 {\n        return 1\n    }\n    inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}\n    max := uint64(1)\n    for n%2 == 0 {\n        max = 2\n        n /= 2\n    }\n    for n%3 == 0 {\n        max = 3\n        n /= 3\n    }\n    for n%5 == 0 {\n        max = 5\n        n /= 5\n    }\n    k := uint64(7)\n    i := 0\n    for k*k <= n {\n        if n%k == 0 {\n            max = k\n            n /= k\n        } else {\n            k += inc[i]\n            i = (i + 1) % 8\n        }\n    }\n    if n > 1 {\n        return n\n    }\n    return max\n}\n\nfunc main() {\n    n := uint64(600851475143)\n    fmt.Println(\"The largest prime factor of\", n, \"is\", largestPrimeFactor(n), \"\\b.\")\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint isprime( long int n ) {\n    int i=3;\n    if(!(n%2)) return 0;\n    while( i*i < n ) {\n        if(!(n%i)) return 0;\n        i+=2;\n    }\n    return 1;\n}\n\nint main(void) {\n    long int n=600851475143, j=3;\n\n    while(!isprime(n)) {\n        if(!(n%j)) n/=j;\n        j+=2;\n    }\n    printf( \"%ld\\n\", n );\n    return 0;\n}\n"}
{"id": 60741, "name": "Largest proper divisor of n", "Go": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n    for i := 2; i*i <= n; i++ {\n        if n%i == 0 {\n            return n / i\n        }\n    }\n    return 1\n}\n\nfunc main() {\n    fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n    fmt.Print(\" 1  \")\n    for n := 2; n <= 100; n++ {\n        if n%2 == 0 {\n            fmt.Printf(\"%2d  \", n/2)\n        } else {\n            fmt.Printf(\"%2d  \", largestProperDivisor(n))\n        }\n        if n%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nunsigned int lpd(unsigned int n) {\n    if (n<=1) return 1;\n    int i;\n    for (i=n-1; i>0; i--)\n        if (n%i == 0) return i;   \n}\n\nint main() {\n    int i;\n    for (i=1; i<=100; i++) {\n        printf(\"%3d\", lpd(i));\n        if (i % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60742, "name": "Three word location", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc toWord(w int64) string { return fmt.Sprintf(\"W%05d\", w) }\n\nfunc fromWord(ws string) int64 {\n    var u, _ = strconv.ParseUint(ws[1:], 10, 64)\n    return int64(u)\n}\n\nfunc main() {\n    fmt.Println(\"Starting figures:\")\n    lat := 28.3852\n    lon := -81.5638\n    fmt.Printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon)\n\n    \n    ilat := int64(lat*10000 + 900000)\n    ilon := int64(lon*10000 + 1800000)\n\n    \n    latlon := (ilat << 22) + ilon\n\n    \n    w1 := (latlon >> 28) & 0x7fff\n    w2 := (latlon >> 14) & 0x3fff\n    w3 := latlon & 0x3fff\n\n    \n    w1s := toWord(w1)\n    w2s := toWord(w2)\n    w3s := toWord(w3)\n\n    \n    fmt.Println(\"\\nThree word location is:\")\n    fmt.Printf(\"  %s %s %s\\n\", w1s, w2s, w3s)\n\n    \n    w1 = fromWord(w1s)\n    w2 = fromWord(w2s)\n    w3 = fromWord(w3s)\n\n    latlon = (w1 << 28) | (w2 << 14) | w3\n    ilat = latlon >> 22\n    ilon = latlon & 0x3fffff\n    lat = float64(ilat-900000) / 10000\n    lon = float64(ilon-1800000) / 10000\n\n    \n    fmt.Println(\"\\nAfter reversing the procedure:\")\n    fmt.Printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef long long int64;\n \nvoid to_word(char *ws, int64 w) {\n    sprintf(ws, \"W%05lld\", w);\n}\n\nint64 from_word(char *ws) {\n    return atoi(++ws);\n}\n\nint main() {\n    double lat, lon;\n    int64 latlon, ilat, ilon, w1, w2, w3;\n    char w1s[7], w2s[7], w3s[7];\n    printf(\"Starting figures:\\n\");\n    lat = 28.3852;\n    lon = -81.5638;\n    printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon);\n \n    \n    ilat = (int64)(lat*10000 + 900000);\n    ilon = (int64)(lon*10000 + 1800000);\n \n    \n    latlon = (ilat << 22) + ilon;\n\n    \n    w1 = (latlon >> 28) & 0x7fff;\n    w2 = (latlon >> 14) & 0x3fff;\n    w3 = latlon & 0x3fff;\n\n    \n    to_word(w1s, w1);\n    to_word(w2s, w2);\n    to_word(w3s, w3);\n \n    \n    printf(\"\\nThree word location is:\\n\");\n    printf(\"  %s %s %s\\n\", w1s, w2s, w3s);\n\n    \n    w1 = from_word(w1s);\n    w2 = from_word(w2s);\n    w3 = from_word(w3s);\n\n    latlon = (w1 << 28) | (w2 << 14) | w3;\n    ilat = latlon >> 22;\n    ilon = latlon & 0x3fffff;\n    lat = (double)(ilat-900000) / 10000;\n    lon = (double)(ilon-1800000) / 10000;\n\n    \n    printf(\"\\nAfter reversing the procedure:\\n\");\n    printf(\"  latitude = %0.4f, longitude = %0.4f\\n\", lat, lon);\n    return 0;\n}\n"}
{"id": 60743, "name": "Move-to-front algorithm", "Go": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#define MAX_SIZE 100\n\nint move_to_front(char *str,char c)\n{\n    char *q,*p;\n    int shift=0;\n    p=(char *)malloc(strlen(str)+1);\n    strcpy(p,str);\n    q=strchr(p,c); \n    shift=q-p;      \n    strncpy(str+1,p,shift);\n    str[0]=c;\n    free(p);\n  \n    return shift;\n}\n\nvoid decode(int* pass,int size,char *sym)\n{\n    int i,index;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=table[pass[i]];\n        index=move_to_front(table,c);\n        if(pass[i]!=index) printf(\"there is an error\");\n        sym[i]=c;\n    }\n    sym[size]='\\0';\n}\n\nvoid encode(char *sym,int size,int *pass)\n{\n    int i=0;\n    char c;\n    char table[]=\"abcdefghijklmnopqrstuvwxyz\";\n    for(i=0;i<size;i++)\n    {\n        c=sym[i];\n        pass[i]=move_to_front(table,c);\n    }\n}\n\nint check(char *sym,int size,int *pass)\n{\n    int *pass2=malloc(sizeof(int)*size);\n    char *sym2=malloc(sizeof(char)*size);\n    int i,val=1;\n\n    encode(sym,size,pass2);\n    i=0;\n    while(i<size && pass[i]==pass2[i])i++;\n    if(i!=size)val=0;\n\n    decode(pass,size,sym2);\n    if(strcmp(sym,sym2)!=0)val=0;\n\n    free(sym2);\n    free(pass2);\n\n    return val;\n}\n\nint main()\n{\n    char sym[3][MAX_SIZE]={\"broood\",\"bananaaa\",\"hiphophiphop\"};\n    int pass[MAX_SIZE]={0};\n    int i,len,j;\n    for(i=0;i<3;i++)\n    {\n        len=strlen(sym[i]);\n        encode(sym[i],len,pass);\n        printf(\"%s : [\",sym[i]);\n        for(j=0;j<len;j++)\n            printf(\"%d \",pass[j]);\n        printf(\"]\\n\");\n        if(check(sym[i],len,pass))\n            printf(\"Correct :)\\n\");\n        else\n            printf(\"Incorrect :(\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60744, "name": "Active Directory_Search for a user", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:        \"dc=example,dc=com\",\n        Host:        \"ldap.example.com\",\n        Port:        389,\n        GroupFilter: \"(memberUid=%s)\",\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    groups, err := client.GetGroupsOfUser(\"username\")\n    if err != nil {\n        log.Fatalf(\"Error getting groups for user %s: %+v\", \"username\", err)\n    }\n    log.Printf(\"Groups: %+v\", groups) \n}\n", "C": "#include <ldap.h>\n\nchar *name, *password;\n...\n\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n\nLDAPMessage **result;\nldap_search_s(ld, \"dc=somewhere,dc=com\", LDAP_SCOPE_SUBTREE,\n\t\n\t\"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))\",\n\tNULL, \n\t0,  \n\tresult); \n\n\n\nldap_msgfree(*result);\t\nldap_unbind(ld);\t\n"}
{"id": 60745, "name": "Singular value decomposition", "Go": "<package main\n\nimport (\n    \"fmt\"\n    \"gonum.org/v1/gonum/mat\"\n    \"log\"\n)\n\nfunc matPrint(m mat.Matrix) {\n    fa := mat.Formatted(m, mat.Prefix(\"\"), mat.Squeeze())\n    fmt.Printf(\"%13.10f\\n\", fa)\n}\n\nfunc main() {\n    var svd mat.SVD\n    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})\n    ok := svd.Factorize(a, mat.SVDFull)\n    if !ok {\n        log.Fatal(\"Something went wrong!\")\n    }\n    u := mat.NewDense(2, 2, nil)\n    svd.UTo(u)\n    fmt.Println(\"U:\")\n    matPrint(u)\n    values := svd.Values(nil)\n    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})\n    fmt.Println(\"\\nΣ:\")\n    matPrint(sigma)\n    vt := mat.NewDense(2, 2, nil)\n    svd.VTo(vt)\n    fmt.Println(\"\\nVT:\")\n    matPrint(vt)\n}\n", "C": "#include <stdio.h>\n#include <gsl/gsl_linalg.h>\n\n\nvoid gsl_matrix_print(const gsl_matrix *M) {\n    int rows = M->size1;\n    int cols = M->size2;\n    for (int i = 0; i < rows; i++) {\n        printf(\"|\");\n        for (int j = 0; j < cols; j++) {\n            printf(\"% 12.10f \", gsl_matrix_get(M, i, j));\n        }\n        printf(\"\\b|\\n\");\n    }\n    printf(\"\\n\");\n}\n\nint main(){\n    double a[] = {3, 0, 4, 5};\n    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);\n    gsl_matrix *V = gsl_matrix_alloc(2, 2);\n    gsl_vector *S = gsl_vector_alloc(2);\n    gsl_vector *work = gsl_vector_alloc(2);\n\n    \n    gsl_linalg_SV_decomp(&A.matrix, V, S, work);\n    gsl_matrix_transpose(V);\n    double s[] = {S->data[0], 0, 0, S->data[1]};\n    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);\n\n    printf(\"U:\\n\");\n    gsl_matrix_print(&A.matrix);\n\n    printf(\"S:\\n\");\n    gsl_matrix_print(&SM.matrix);\n\n    printf(\"VT:\\n\");\n    gsl_matrix_print(V);\n    \n    gsl_matrix_free(V);\n    gsl_vector_free(S);\n    gsl_vector_free(work);\n    return 0;\n}\n"}
{"id": 60746, "name": "Sum of first n cubes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    fmt.Println(\"Cumulative sums of the first 50 cubes:\")\n    sum := 0\n    for n := 0; n < 50; n++ {\n        sum += n * n * n\n        fmt.Printf(\"%9s \", rcu.Commatize(sum))\n        if n%10 == 9 {\n            fmt.Println()\n        }\n    }\n    fmt.Println()\n", "C": "#include <stdio.h>\n\nint main() {\n    for (int i = 0, sum = 0; i < 50; ++i) {\n        sum += i * i * i;\n        printf(\"%7d%c\", sum, (i + 1) % 5 == 0 ? '\\n' : ' ');\n    }\n    return 0;\n}\n"}
{"id": 60747, "name": "IPC via named pipe", "Go": "package main\n\nimport (\n        \"fmt\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"sync/atomic\"\n        \"syscall\"\n)\n\nconst (\n        inputFifo  = \"/tmp/in.fifo\"\n        outputFifo = \"/tmp/out.fifo\"\n        readsize   = 64 << 10\n)\n\nfunc openFifo(path string, oflag int) (f *os.File, err error) {\n        err = syscall.Mkfifo(path, 0660)\n        \n        if err != nil && !os.IsExist(err) {\n                return\n        }\n        f, err = os.OpenFile(path, oflag, 0660)\n        if err != nil {\n                return\n        }\n        \n        fi, err := f.Stat()\n        if err != nil {\n                f.Close()\n                return nil, err\n        }\n        if fi.Mode()&os.ModeType != os.ModeNamedPipe {\n                f.Close()\n                return nil, os.ErrExist\n        }\n        return\n}\n\nfunc main() {\n        var byteCount int64\n        go func() {\n                var delta int\n                var err error\n                buf := make([]byte, readsize)\n                for {\n                        input, err := openFifo(inputFifo, os.O_RDONLY)\n                        if err != nil {\n                                break\n                        }\n                        for err == nil {\n                                delta, err = input.Read(buf)\n                                atomic.AddInt64(&byteCount, int64(delta))\n                        }\n                        input.Close()\n                        if err != io.EOF {\n                                break\n                        }\n                }\n                log.Fatal(err)\n        }()\n\n        for {\n                output, err := openFifo(outputFifo, os.O_WRONLY)\n                if err != nil {\n                        log.Fatal(err)\n                }\n                cnt := atomic.LoadInt64(&byteCount)\n                fmt.Fprintln(output, cnt)\n                output.Close()\n        }\n}\n", "C": "#include <stdio.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <limits.h>\n#include <pthread.h>\n\n\n\n#define WILL_BLOCK_EVERYTHING\t0\n\n#if WILL_BLOCK_EVERYTHING\n#include <poll.h>\n#endif\n\nsize_t tally = 0;\n\nvoid* write_loop(void *a)\n{\n\tint fd;\n\tchar buf[32];\n\twhile (1) {\n#if WILL_BLOCK_EVERYTHING\n\t\t\n\t\tfd = open(\"out\", O_WRONLY|O_NONBLOCK);\n\t\tif (fd < 0) { \n\t\t\tusleep(200000);\n\t\t\tcontinue;\n\t\t}\n#else\n\t\t\n\t\tfd = open(\"out\", O_WRONLY);\n#endif\n\t\twrite(fd, buf, snprintf(buf, 32, \"%d\\n\", tally));\n\t\tclose(fd);\n\n\t\t\n\t\tusleep(10000);\n\t}\n}\n\nvoid read_loop()\n{\n\tint fd;\n\tsize_t len;\n\tchar buf[PIPE_BUF];\n#if WILL_BLOCK_EVERYTHING\n\tstruct pollfd pfd;\n\tpfd.events = POLLIN;\n#endif\n\twhile (1) {\n#if WILL_BLOCK_EVERYTHING\n\t\tfd = pfd.fd = open(\"in\", O_RDONLY|O_NONBLOCK);\n\t\tfcntl(fd, F_SETFL, 0);  \n\t\tpoll(&pfd, 1, INFTIM);  \n#else\n\t\tfd = open(\"in\", O_RDONLY);\n#endif\n\t\twhile ((len = read(fd, buf, PIPE_BUF)) > 0) tally += len;\n\t\tclose(fd);\n\t}\n}\n\nint main()\n{\n\tpthread_t pid;\n\n\t\n\tmkfifo(\"in\", 0666);\n\tmkfifo(\"out\", 0666);\n\n\t\n\tpthread_create(&pid, 0, write_loop, 0);\n\tread_loop();\n\n\treturn 0;\n}\n"}
{"id": 60748, "name": "Test integerness", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n\n\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n\n\n\n\n\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t\n\t\t\n\t\t\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t\n\t\n}\n\nfunc (customIntegerType) IsInt() bool    { return true }\nfunc (customIntegerType) String() string { return \"<…>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s  %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s  %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('§'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}\n", "C": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\n\n\n#define FMTSPEC(arg) _Generic((arg), \\\n    float: \"%f\", double: \"%f\", \\\n    long double: \"%Lf\", unsigned int: \"%u\", \\\n    unsigned long: \"%lu\", unsigned long long: \"%llu\", \\\n    int: \"%d\", long: \"%ld\", long long: \"%lld\", \\\n    default: \"(invalid type (%p)\")\n\n#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \\\n            I * (long double)(y)))\n\n#define TEST_CMPL(i, j)\\\n    printf(FMTSPEC(i), i), printf(\" + \"), printf(FMTSPEC(j), j), \\\n    printf(\"i = %s\\n\", (isint(CMPPARTS(i, j)) ? \"true\" : \"false\"))\n\n#define TEST_REAL(i)\\\n    printf(FMTSPEC(i), i), printf(\" = %s\\n\", (isint(i) ? \"true\" : \"false\"))\n\n\nstatic inline int isint(long double complex n)\n{\n    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);\n}\n\nint main(void)\n{\n    TEST_REAL(0);\n    TEST_REAL(-0);\n    TEST_REAL(-2);\n    TEST_REAL(-2.00000000000001);\n    TEST_REAL(5);\n    TEST_REAL(7.3333333333333);\n    TEST_REAL(3.141592653589);\n    TEST_REAL(-9.223372036854776e18);\n    TEST_REAL(5e-324);\n    TEST_REAL(NAN);\n    TEST_CMPL(6, 0);\n    TEST_CMPL(0, 1);\n    TEST_CMPL(0, 0);\n    TEST_CMPL(3.4, 0);\n\n    \n    double complex test1 = 5 + 0*I,\n                   test2 = 3.4f,\n                   test3 = 3,\n                   test4 = 0 + 1.2*I;\n\n    printf(\"Test 1 (5+i) = %s\\n\", isint(test1) ? \"true\" : \"false\");\n    printf(\"Test 2 (3.4+0i) = %s\\n\", isint(test2) ? \"true\" : \"false\");\n    printf(\"Test 3 (3+0i) = %s\\n\", isint(test3) ? \"true\" : \"false\");\n    printf(\"Test 4 (0+1.2i) = %s\\n\", isint(test4) ? \"true\" : \"false\");\n}\n"}
{"id": 60749, "name": "Execute a system command", "Go": "package main\n\nimport (\n    \"log\"\n    \"os\"\n    \"os/exec\"\n)\n\nfunc main() {\n    cmd := exec.Command(\"ls\", \"-l\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "#include <stdlib.h>\n\nint main()\n{\n    system(\"ls\");\n    return 0;\n}\n"}
{"id": 60750, "name": "Rodrigues’ rotation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype vector [3]float64\ntype matrix [3]vector\n\nfunc norm(v vector) float64 {\n    return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])\n}\n\nfunc normalize(v vector) vector {\n    length := norm(v)\n    return vector{v[0] / length, v[1] / length, v[2] / length}\n}\n\nfunc dotProduct(v1, v2 vector) float64 {\n    return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n}\n\nfunc crossProduct(v1, v2 vector) vector {\n    return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}\n}\n\nfunc getAngle(v1, v2 vector) float64 {\n    return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))\n}\n\nfunc matrixMultiply(m matrix, v vector) vector {\n    return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}\n}\n\nfunc aRotate(p, v vector, a float64) vector {\n    ca, sa := math.Cos(a), math.Sin(a)\n    t := 1 - ca\n    x, y, z := v[0], v[1], v[2]\n    r := matrix{\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},\n    }\n    return matrixMultiply(r, p)\n}\n\nfunc main() {\n    v1 := vector{5, -6, 4}\n    v2 := vector{8, 5, -30}\n    a := getAngle(v1, v2)\n    cp := crossProduct(v1, v2)\n    ncp := normalize(cp)\n    np := aRotate(v1, ncp, a)\n    fmt.Println(np)\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef struct {\n    double x, y, z;\n} vector;\n\ntypedef struct {\n    vector i, j, k;\n} matrix;\n\ndouble norm(vector v) {\n    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);\n}\n\nvector normalize(vector v){\n    double length = norm(v);\n    vector n = {v.x / length, v.y / length, v.z / length};\n    return n;\n}\n\ndouble dotProduct(vector v1, vector v2) {\n    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;\n}\n\nvector crossProduct(vector v1, vector v2) {\n    vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x};\n    return cp;\n}\n\ndouble getAngle(vector v1, vector v2) {\n    return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2)));\n}\n\nvector matrixMultiply(matrix m ,vector v) {\n    vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)};\n    return mm;\n}\n\nvector aRotate(vector p, vector v, double a) {\n    double ca = cos(a), sa = sin(a);\n    double t = 1.0 - ca;\n    double x = v.x, y = v.y, z = v.z;\n    matrix r = {\n        {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},\n        {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},\n        {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}\n    };\n    return matrixMultiply(r, p);\n}\n\nint main() {\n    vector v1 = {5, -6, 4}, v2 = {8, 5, -30};\n    double a = getAngle(v1, v2);\n    vector cp = crossProduct(v1, v2);\n    vector ncp = normalize(cp);\n    vector np = aRotate(v1, ncp, a);\n    printf(\"[%.13f, %.13f, %.13f]\\n\", np.x, np.y, np.z);\n    return 0;\n}\n"}
{"id": 60751, "name": "XML validation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/lestrrat-go/libxml2\"\n    \"github.com/lestrrat-go/libxml2/xsd\"\n    \"io/ioutil\"\n    \"log\"\n    \"os\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    xsdfile := \"shiporder.xsd\"\n    f, err := os.Open(xsdfile)\n    check(err)\n    defer f.Close()\n\n    buf, err := ioutil.ReadAll(f)\n    check(err)\n\n    s, err := xsd.Parse(buf)\n    check(err)\n    defer s.Free()\n\n    xmlfile := \"shiporder.xml\"\n    f2, err := os.Open(xmlfile)\n    check(err)\n    defer f2.Close()\n\n    buf2, err := ioutil.ReadAll(f2)\n    check(err)\n\n    d, err := libxml2.Parse(buf2)\n    check(err)\n\n    if err := s.Validate(d); err != nil {\n        for _, e := range err.(xsd.SchemaValidationError).Errors() {\n            log.Printf(\"error: %s\", e.Error())\n        }\n        return\n    }\n\n    fmt.Println(\"Validation of\", xmlfile, \"against\", xsdfile, \"successful!\")\n}\n", "C": "#include <libxml/xmlschemastypes.h>\n\nint main(int argC, char** argV)\n{\n\tif (argC <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XSD Document Name>\\n\", argV[0]);\n\t\treturn 0;\n\t}\n\t\n\txmlDocPtr doc;\n\txmlSchemaPtr schema = NULL;\n\txmlSchemaParserCtxtPtr ctxt;\n\tchar *XMLFileName = argV[1];\n\tchar *XSDFileName = argV[2];\n\tint ret;\n\n\txmlLineNumbersDefault(1);\n\n\tctxt = xmlSchemaNewParserCtxt(XSDFileName);\n\n\txmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\tschema = xmlSchemaParse(ctxt);\n\txmlSchemaFreeParserCtxt(ctxt);\n\n\n\tdoc = xmlReadFile(XMLFileName, NULL, 0);\n\n\tif (doc == NULL){\n\t\tfprintf(stderr, \"Could not parse %s\\n\", XMLFileName);\n\t}\n\telse{\n\t\txmlSchemaValidCtxtPtr ctxt;\n\n\t\tctxt = xmlSchemaNewValidCtxt(schema);\n\t\txmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);\n\t\tret = xmlSchemaValidateDoc(ctxt, doc);\n\t\t\n\t\tif (ret == 0){\n\t\t\tprintf(\"%s validates\\n\", XMLFileName);\n\t\t}\n\t\telse if (ret > 0){\n\t\t\tprintf(\"%s fails to validate\\n\", XMLFileName);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"%s validation generated an internal error\\n\", XMLFileName);\n\t\t}\n\t\txmlSchemaFreeValidCtxt(ctxt);\n\t\txmlFreeDoc(doc);\n\t}\n\n\n\tif(schema != NULL)\n\t\txmlSchemaFree(schema);\n\n\txmlSchemaCleanupTypes();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\treturn 0;\n}\n"}
{"id": 60752, "name": "Longest increasing subsequence", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"sort\"\n)\n\ntype Node struct {\n    val int\n    back *Node\n}\n\nfunc lis (n []int) (result []int) {\n  var pileTops []*Node\n  \n  for _, x := range n {\n    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n    node := &Node{ x, nil }\n    if j != 0 { node.back = pileTops[j-1] }\n    if j != len(pileTops) {\n      pileTops[j] = node\n    } else {\n      pileTops = append(pileTops, node)\n    }\n  }\n\n  if len(pileTops) == 0 { return []int{} }\n  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n    result = append(result, node.val)\n  }\n  \n  for i := 0; i < len(result)/2; i++ {\n    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n  }\n  return\n}\n\nfunc main() {\n    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n        fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n\tint val, len;\n\tstruct node *next;\n};\n\nvoid lis(int *v, int len)\n{\n\tint i;\n\tstruct node *p, *n = calloc(len, sizeof *n);\n\tfor (i = 0; i < len; i++)\n\t\tn[i].val = v[i];\n\n\tfor (i = len; i--; ) {\n\t\t\n\t\tfor (p = n + i; p++ < n + len; ) {\n\t\t\tif (p->val > n[i].val && p->len >= n[i].len) {\n\t\t\t\tn[i].next = p;\n\t\t\t\tn[i].len = p->len + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor (i = 0, p = n; i < len; i++)\n\t\tif (n[i].len > p->len) p = n + i;\n\n\tdo printf(\" %d\", p->val); while ((p = p->next));\n\tputchar('\\n');\n\n\tfree(n);\n}\n\nint main(void)\n{\n\tint x[] = { 3, 2, 6, 4, 5, 1 };\n\tint y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n\tlis(x, sizeof(x) / sizeof(int));\n\tlis(y, sizeof(y) / sizeof(int));\n\treturn 0;\n}\n"}
{"id": 60753, "name": "Death Star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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 <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n"}
{"id": 60754, "name": "Death Star", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc (v *vector) normalize() {\n    invLen := 1 / math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\ntype sphere struct {\n    cx, cy, cz int\n    r          int\n}\n\nfunc (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {\n    x -= s.cx\n    y -= s.cy\n    if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {\n        zsqrt := math.Sqrt(float64(zsq))\n        return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true\n    }\n    return 0, 0, false\n}\n\nfunc deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {\n    w, h := pos.r*4, pos.r*3\n    bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)\n    img := image.NewGray(bounds)\n    vec := new(vector)\n    for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {\n        for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {\n            zb1, zb2, hit := pos.hit(x, y)\n            if !hit {\n                continue\n            }\n            zs1, zs2, hit := neg.hit(x, y)\n            if hit {\n                if zs1 > zb1 {\n                    hit = false\n                } else if zs2 > zb2 {\n                    continue\n                }\n            }\n            if hit {\n                vec[0] = float64(neg.cx - x)\n                vec[1] = float64(neg.cy - y)\n                vec[2] = float64(neg.cz) - zs2\n            } else {\n                vec[0] = float64(x - pos.cx)\n                vec[1] = float64(y - pos.cy)\n                vec[2] = zb1 - float64(pos.cz)\n            }\n            vec.normalize()\n            s := dot(dir, vec)\n            if s < 0 {\n                s = 0\n            }\n            lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n            if lum < 0 {\n                lum = 0\n            } else if lum > 255 {\n                lum = 255\n            }\n            img.SetGray(x, y, color.Gray{uint8(lum)})\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{20, -40, -10}\n    dir.normalize()\n    pos := &sphere{0, 0, 0, 120}\n    neg := &sphere{-90, -90, -30, 100}\n\n    img := deathStar(pos, neg, 1.5, .2, dir)\n    f, err := os.Create(\"dstar.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 <math.h>\n#include <unistd.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { -50, 0, 50 };\nvoid normalize(double * v)\n{\n\tdouble len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\tv[0] /= len; v[1] /= len; v[2] /= len;\n}\n\ndouble dot(double *x, double *y)\n{\n\tdouble d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\treturn d < 0 ? -d : 0;\n}\n\ntypedef struct { double cx, cy, cz, r; } sphere_t;\n\n\nsphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };\n\n\nint hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)\n{\n\tdouble zsq;\n\tx -= sph->cx;\n\ty -= sph->cy;\n\tzsq = sph->r * sph->r - (x * x + y * y);\n\tif (zsq < 0) return 0;\n\tzsq = sqrt(zsq);\n\t*z1 = sph->cz - zsq;\n\t*z2 = sph->cz + zsq;\n\treturn 1;\n}\n\nvoid draw_sphere(double k, double ambient)\n{\n\tint i, j, intensity, hit_result;\n\tdouble b;\n\tdouble vec[3], x, y, zb1, zb2, zs1, zs2;\n\tfor (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {\n\t\ty = i + .5;\n\t\tfor (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {\n\t\t\tx = (j - pos.cx) / 2. + .5 + pos.cx;\n\n\t\t\t\n\t\t\tif (!hit_sphere(&pos, x, y, &zb1, &zb2))\n\t\t\t\thit_result = 0;\n\n\t\t\t\n\t\t\telse if (!hit_sphere(&neg, x, y, &zs1, &zs2))\n\t\t\t\thit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs1 > zb1) hit_result = 1;\n\n\t\t\t\n\t\t\telse if (zs2 > zb2) hit_result = 0;\n\n\t\t\t\n\t\t\telse if (zs2 > zb1) hit_result = 2;\n\t\t\telse\t\t    hit_result = 1;\n\n\t\t\tswitch(hit_result) {\n\t\t\tcase 0:\n\t\t\t\tputchar('+');\n\t\t\t\tcontinue;\n\t\t\tcase 1:\n\t\t\t\tvec[0] = x - pos.cx;\n\t\t\t\tvec[1] = y - pos.cy;\n\t\t\t\tvec[2] = zb1 - pos.cz;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tvec[0] = neg.cx - x;\n\t\t\t\tvec[1] = neg.cy - y;\n\t\t\t\tvec[2] = neg.cz - zs2;\n\t\t\t}\n\n\t\t\tnormalize(vec);\n\t\t\tb = pow(dot(light, vec), k) + ambient;\n\t\t\tintensity = (1 - b) * (sizeof(shades) - 1);\n\t\t\tif (intensity < 0) intensity = 0;\n\t\t\tif (intensity >= sizeof(shades) - 1)\n\t\t\t\tintensity = sizeof(shades) - 2;\n\t\t\tputchar(shades[intensity]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\nint main()\n{\n\tdouble ang = 0;\n\n\twhile (1) {\n\t\tprintf(\"\\033[H\");\n\t\tlight[1] = cos(ang * 2);\n\t\tlight[2] = cos(ang);\n\t\tlight[0] = sin(ang);\n\t\tnormalize(light);\n\t\tang += .05;\n\n\t\tdraw_sphere(2, .3);\n\t\tusleep(100000);\n\t}\n\treturn 0;\n}\n"}
{"id": 60755, "name": "Hough transform", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\nfunc hough(im image.Image, ntx, mry int) draw.Image {\n    nimx := im.Bounds().Max.X\n    mimy := im.Bounds().Max.Y\n\n    him := image.NewGray(image.Rect(0, 0, ntx, mry))\n    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),\n        image.Point{}, draw.Src)\n\n    rmax := math.Hypot(float64(nimx), float64(mimy))\n    dr := rmax / float64(mry/2)\n    dth := math.Pi / float64(ntx)\n\n    for jx := 0; jx < nimx; jx++ {\n        for iy := 0; iy < mimy; iy++ {\n            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)\n            if col.Y == 255 {\n                continue\n            }\n            for jtx := 0; jtx < ntx; jtx++ {\n                th := dth * float64(jtx)\n                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)\n                iry := mry/2 - int(math.Floor(r/dr+.5))\n                col = him.At(jtx, iry).(color.Gray)\n                if col.Y > 0 {\n                    col.Y--\n                    him.SetGray(jtx, iry, col)\n                }\n            }\n        }\n    }\n    return him\n}\n\nfunc main() {\n    f, err := os.Open(\"Pentagon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    pent, err := png.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n    h := hough(pent, 460, 360)\n    if f, err = os.Create(\"hough.png\"); err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, h); err != nil {\n        fmt.Println(err)\n    }\n    if cErr := f.Close(); cErr != nil && err == nil {\n        fmt.Println(err)\n    }\n}\n", "C": "#include \"SL_Generated.h\"\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nint main( int argc, char** argv )\n{\n    string fileName = \"Pentagon.bmp\";\n    if(argc > 1) fileName = argv[1];\n    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);\n    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);\n    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);\n    int threads = 0; if(argc > 5) threads = atoi(argv[5]);\n    char titleBuffer[200];\n    SLTimer t;\n\n    CImg<int> image(fileName.c_str());\n    int imageDimensions[] = {image.height(), image.width(), 0};\n    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);\n    Sequence< Sequence<int> > result;\n\n    sl_init(threads);\n\n    t.start();\n    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);\n    t.stop();\n    \n    CImg<int> resultImage(result[1].size(), result.size());\n    for(int y = 0; y < result.size(); y++)\n        for(int x = 0; x < result[y+1].size(); x++)\n            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];\n    \n    sprintf(titleBuffer, \"SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\\0\", \n                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());\n    resultImage.display(titleBuffer);\n\n    sl_done();\n    return 0;\n}\n"}
{"id": 60756, "name": "Verify distribution uniformity_Chi-squared test", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n"}
{"id": 60757, "name": "Verify distribution uniformity_Chi-squared test", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n    \ntype ifctn func(float64) float64\n    \nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n    h := (b - a) / float64(n)\n    h1 := h / 3\n    sum := f(a) + f(b)\n    for j := 3*n - 1; j > 0; j-- {\n        if j%3 == 0 {\n            sum += 2 * f(a+h1*float64(j))\n        } else {\n            sum += 3 * f(a+h1*float64(j))\n        }\n    }\n    return h * sum / 8\n}\n    \nfunc gammaIncQ(a, x float64) float64 {\n    aa1 := a - 1\n    var f ifctn = func(t float64) float64 {\n        return math.Pow(t, aa1) * math.Exp(-t)\n    }\n    y := aa1\n    h := 1.5e-2\n    for f(y)*(x-y) > 2e-8 && y < x {\n        y += .4\n    }\n    if y > x {\n        y = x\n    }\n    return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n    var sum, expected float64\n    for _, d := range ds {\n        expected += float64(d)\n    }\n    expected /= float64(len(ds))\n    for _, d := range ds {\n        x := float64(d) - expected\n        sum += x * x\n    }\n    return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n    return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n    for _, dset := range [][]int{\n        {199809, 200665, 199607, 200270, 199649},\n        {522573, 244456, 139979, 71531, 21461},\n    } {\n        utest(dset)\n    }\n}\n\nfunc utest(dset []int) {\n    fmt.Println(\"Uniform distribution test\")\n    var sum int\n    for _, c := range dset {\n        sum += c\n    }\n    fmt.Println(\" dataset:\", dset)\n    fmt.Println(\" samples:                      \", sum)\n    fmt.Println(\" categories:                   \", len(dset))\n    \n    dof := len(dset) - 1\n    fmt.Println(\" degrees of freedom:           \", dof)\n\n    dist := chi2ud(dset)\n    fmt.Println(\" chi square test statistic:    \", dist)\n    \n    p := chi2p(dof, dist)\n    fmt.Println(\" p-value of test statistic:    \", p)\n\n    sig := p < sigLevel\n    fmt.Printf(\" significant at %2.0f%% level?      %t\\n\", sigLevel*100, sig)\n    fmt.Println(\" uniform?                      \", !sig, \"\\n\")\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n    int j;\n    double l1;\n    double h = (b-a)/N;\n    double h1 = h/3.0;\n    double sum = f(a) + f(b);\n\n    for (j=3*N-1; j>0; j--) {\n        l1 = (j%3)? 3.0 : 2.0;\n        sum += l1*f(a+h1*j) ;\n    }\n    return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n    int k;\n    static double cspace[A];\n    static double *coefs = NULL;\n    double accum;\n    double a = A;\n\n    if (!coefs) {\n        double k1_factrl = 1.0;\n        coefs = cspace;\n        coefs[0] = sqrt(2.0*M_PI);\n        for(k=1; k<A; k++) {\n            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n            k1_factrl *= -k;\n        }\n    }\n\n    accum = coefs[0];\n    for (k=1; k<A; k++) {\n        accum += coefs[k]/(z+k);\n    }\n    accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n    return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n    return  pow(t, aa1)*exp(-t); \n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n    double y, h = 1.5e-2;  \n\n    \n    y = aa1 = a-1;\n    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;\n    if (y>x) y=x;\n\n    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n"}
{"id": 60758, "name": "Topological sort_Extracted top item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n"}
{"id": 60759, "name": "Topological sort_Extracted top item", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nFILE    FILE DEPENDENCIES\n====    =================\ntop1    des1 ip1 ip2\ntop2    des1 ip2 ip3\nip1     extra1 ip1a ipcommon\nip2     ip2a ip2b ip2c ipcommon\ndes1    des1a des1b des1c\ndes1a   des1a1 des1a2\ndes1c   des1c1 extra1`\n\nfunc main() {\n    g, dep, err := parseLibDep(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \n    \n    \n    var tops []string\n    for n := range g {\n        if !dep[n] {\n            tops = append(tops, n)\n        }\n    }\n    fmt.Println(\"Top levels:\", tops)\n    \n    showOrder(g, \"top1\")         \n    showOrder(g, \"top2\")         \n    showOrder(g, \"top1\", \"top2\") \n\n    fmt.Println(\"Cycle examples:\")\n    \n    g, _, err = parseLibDep(data + `\ndes1a1  des1`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    showOrder(g, \"top1\")       \n    showOrder(g, \"ip1\", \"ip2\") \n}\n\nfunc showOrder(g graph, target ...string) {\n    order, cyclic := g.orderFrom(target...)\n    if cyclic == nil {\n        reverse(order) \n        fmt.Println(\"Target\", target, \"order:\", order)\n    } else {\n        fmt.Println(\"Target\", target, \"cyclic dependencies:\", cyclic)\n    }\n}\n\nfunc reverse(s []string) {\n    last := len(s) - 1\n    for i, e := range s[:len(s)/2] {\n        s[i], s[last-i] = s[last-i], e\n    }\n}\n\ntype graph map[string][]string \ntype depList map[string]bool\n\n\n\nfunc parseLibDep(data string) (g graph, d depList, err error) {\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    lines = lines[3:]\n    g = graph{}\n    d = depList{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue\n        }\n        lib := libs[0]\n        var deps []string\n        for _, dep := range libs[1:] {\n            g[dep] = g[dep]\n            if dep == lib {\n                continue\n            }\n            for i := 0; ; i++ {\n                if i == len(deps) {\n                    deps = append(deps, dep)\n                    d[dep] = true\n                    break\n                }\n                if dep == deps[i] {\n                    break\n                }\n            }\n        }\n        g[lib] = deps\n    }\n    return g, d, nil\n}\n\n\n\n\n\n\nfunc (g graph) orderFrom(start ...string) (order, cyclic []string) {\n    L := make([]string, len(g))\n    i := len(L)\n    temp := map[string]bool{}\n    perm := map[string]bool{}\n    var cycleFound bool\n    var cycleStart string\n    var visit func(string)\n    visit = func(n string) {\n        switch {\n        case temp[n]:\n            cycleFound = true\n            cycleStart = n\n            return\n        case perm[n]:\n            return\n        }\n        temp[n] = true\n        for _, m := range g[n] {\n            visit(m)\n            if cycleFound {\n                if cycleStart > \"\" {\n                    cyclic = append(cyclic, n)\n                    if n == cycleStart {\n                        cycleStart = \"\"\n                    }\n                }\n                return\n            }\n        }\n        delete(temp, n)\n        perm[n] = true\n        i--\n        L[i] = n\n    }\n    for _, n := range start {\n        if perm[n] {\n            continue\n        }\n        visit(n)\n        if cycleFound {\n            return nil, cyclic\n        }\n    }\n    return L[i:], nil\n}\n", "C": "char input[] =\t\"top1    des1 ip1 ip2\\n\"\n\t\t\"top2    des1 ip2 ip3\\n\"\n\t\t\"ip1     extra1 ip1a ipcommon\\n\"\n\t\t\"ip2     ip2a ip2b ip2c ipcommon\\n\"\n\t\t\"des1    des1a des1b des1c\\n\"\n\t\t\"des1a   des1a1 des1a2\\n\"\n\t\t\"des1c   des1c1 extra1\\n\";\n\n...\nint find_name(item base, int len, const char *name)\n{\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tif (!strcmp(base[i].name, name)) return i;\n\treturn -1;\n}\n\nint depends_on(item base, int n1, int n2)\n{\n\tint i;\n\tif (n1 == n2) return 1;\n\tfor (i = 0; i < base[n1].n_deps; i++)\n\t\tif (depends_on(base, base[n1].deps[i], n2)) return 1;\n\treturn 0;\n}\n\nvoid compile_order(item base, int n_items, int *top, int n_top)\n{\n\tint i, j, lvl;\n\tint d = 0;\n\tprintf(\"Compile order for:\");\n\tfor (i = 0; i < n_top; i++) {\n\t\tprintf(\" %s\", base[top[i]].name);\n\t\tif (base[top[i]].depth > d)\n\t\t\td = base[top[i]].depth;\n\t}\n\tprintf(\"\\n\");\n\n\tfor (lvl = 1; lvl <= d; lvl ++) {\n\t\tprintf(\"level %d:\", lvl);\n\t\tfor (i = 0; i < n_items; i++) {\n\t\t\tif (base[i].depth != lvl) continue;\n\t\t\tfor (j = 0; j < n_top; j++) {\n\t\t\t\tif (depends_on(base, top[j], i)) {\n\t\t\t\t\tprintf(\" %s\", base[i].name);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint i, n, bad = -1;\n\titem items;\n\tn = parse_input(&items);\n \n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n \n\tint top[3];\n\ttop[0] = find_name(items, n, \"top1\");\n\ttop[1] = find_name(items, n, \"top2\");\n\ttop[2] = find_name(items, n, \"ip1\");\n\n\tcompile_order(items, n, top, 1);\n\tcompile_order(items, n, top + 1, 1);\n\tcompile_order(items, n, top, 2);\n\tcompile_order(items, n, top + 2, 1);\n\n\treturn 0;\n}\n"}
{"id": 60760, "name": "Brace expansion", "Go": "package expand\n\n\ntype Expander interface {\n\tExpand() []string\n}\n\n\ntype Text string\n\nfunc (t Text) Expand() []string { return []string{string(t)} }\n\n\n\ntype Alternation []Expander\n\nfunc (alt Alternation) Expand() []string {\n\tvar out []string\n\tfor _, e := range alt {\n\t\tout = append(out, e.Expand()...)\n\t}\n\treturn out\n}\n\n\n\ntype Sequence []Expander\n\nfunc (seq Sequence) Expand() []string {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tout := seq[0].Expand()\n\tfor _, e := range seq[1:] {\n\t\tout = combine(out, e.Expand())\n\t}\n\treturn out\n}\n\nfunc combine(al, bl []string) []string {\n\tout := make([]string, 0, len(al)*len(bl))\n\tfor _, a := range al {\n\t\tfor _, b := range bl {\n\t\t\tout = append(out, a+b)\n\t\t}\n\t}\n\treturn out\n}\n\n\nconst (\n\tescape   = '\\\\'\n\taltStart = '{'\n\taltEnd   = '}'\n\taltSep   = ','\n)\n\ntype piT struct{ pos, cnt, depth int }\n\ntype Brace string\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Expand(s string) []string   { return Brace(s).Expand() }\nfunc (b Brace) Expand() []string { return b.Expander().Expand() }\nfunc (b Brace) Expander() Expander {\n\ts := string(b)\n\t\n\tvar posInfo []piT\n\tvar stack []int \n\tremovePosInfo := func(i int) {\n\t\tend := len(posInfo) - 1\n\t\tcopy(posInfo[i:end], posInfo[i+1:])\n\t\tposInfo = posInfo[:end]\n\t}\n\n\tinEscape := false\n\tfor i, r := range s {\n\t\tif inEscape {\n\t\t\tinEscape = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\tcase escape:\n\t\t\tinEscape = true\n\t\tcase altStart:\n\t\t\tstack = append(stack, len(posInfo))\n\t\t\tposInfo = append(posInfo, piT{i, 0, len(stack)})\n\t\tcase altEnd:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsi := len(stack) - 1\n\t\t\tpi := stack[si]\n\t\t\tif posInfo[pi].cnt == 0 {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t\tfor pi < len(posInfo) {\n\t\t\t\t\tif posInfo[pi].depth == len(stack) {\n\t\t\t\t\t\tremovePosInfo(pi)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpi++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tposInfo = append(posInfo, piT{i, -2, len(stack)})\n\t\t\t}\n\t\t\tstack = stack[:si]\n\t\tcase altSep:\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tposInfo = append(posInfo, piT{i, -1, len(stack)})\n\t\t\tposInfo[stack[len(stack)-1]].cnt++\n\t\t}\n\t}\n\t\n\tfor len(stack) > 0 {\n\t\tsi := len(stack) - 1\n\t\tpi := stack[si]\n\t\tdepth := posInfo[pi].depth\n\t\tremovePosInfo(pi)\n\t\tfor pi < len(posInfo) {\n\t\t\tif posInfo[pi].depth == depth {\n\t\t\t\tremovePosInfo(pi)\n\t\t\t} else {\n\t\t\t\tpi++\n\t\t\t}\n\t\t}\n\t\tstack = stack[:si]\n\t}\n\treturn buildExp(s, 0, posInfo)\n}\n\nfunc buildExp(s string, off int, info []piT) Expander {\n\tif len(info) == 0 {\n\t\treturn Text(s)\n\t}\n\t\n\tvar seq Sequence\n\ti := 0\n\tvar dj, j, depth int\n\tfor dk, piK := range info {\n\t\tk := piK.pos - off\n\t\tswitch s[k] {\n\t\tcase altStart:\n\t\t\tif depth == 0 {\n\t\t\t\tdj = dk\n\t\t\t\tj = k\n\t\t\t\tdepth = piK.depth\n\t\t\t}\n\t\tcase altEnd:\n\t\t\tif piK.depth != depth {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif j > i {\n\t\t\t\tseq = append(seq, Text(s[i:j]))\n\t\t\t}\n\t\t\talt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])\n\t\t\tseq = append(seq, alt)\n\t\t\ti = k + 1\n\t\t\tdepth = 0\n\t\t}\n\t}\n\tif j := len(s); j > i {\n\t\tseq = append(seq, Text(s[i:j]))\n\t}\n\tif len(seq) == 1 {\n\t\treturn seq[0]\n\t}\n\treturn seq\n}\n\nfunc buildAlt(s string, depth, off int, info []piT) Alternation {\n\t\n\tvar alt Alternation\n\ti := 0\n\tvar di int\n\tfor dk, piK := range info {\n\t\tif piK.depth != depth {\n\t\t\tcontinue\n\t\t}\n\t\tif k := piK.pos - off; s[k] == altSep {\n\t\t\tsub := buildExp(s[i:k], i+off, info[di:dk])\n\t\t\talt = append(alt, sub)\n\t\t\ti = k + 1\n\t\t\tdi = dk + 1\n\t\t}\n\t}\n\tsub := buildExp(s[i:], i+off, info[di:])\n\talt = append(alt, sub)\n\treturn alt\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BUFFER_SIZE 128\n\ntypedef unsigned char character;\ntypedef character *string;\n\ntypedef struct node_t node;\nstruct node_t {\n    enum tag_t {\n        NODE_LEAF,\n        NODE_TREE,\n        NODE_SEQ,\n    } tag;\n\n    union {\n        string str;\n        node *root;\n    } data;\n\n    node *next;\n};\n\nnode *allocate_node(enum tag_t tag) {\n    node *n = malloc(sizeof(node));\n    if (n == NULL) {\n        fprintf(stderr, \"Failed to allocate node for tag: %d\\n\", tag);\n        exit(1);\n    }\n    n->tag = tag;\n    n->next = NULL;\n    return n;\n}\n\nnode *make_leaf(string str) {\n    node *n = allocate_node(NODE_LEAF);\n    n->data.str = str;\n    return n;\n}\n\nnode *make_tree() {\n    node *n = allocate_node(NODE_TREE);\n    n->data.root = NULL;\n    return n;\n}\n\nnode *make_seq() {\n    node *n = allocate_node(NODE_SEQ);\n    n->data.root = NULL;\n    return n;\n}\n\nvoid deallocate_node(node *n) {\n    if (n == NULL) {\n        return;\n    }\n\n    deallocate_node(n->next);\n    n->next = NULL;\n\n    if (n->tag == NODE_LEAF) {\n        free(n->data.str);\n        n->data.str = NULL;\n    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {\n        deallocate_node(n->data.root);\n        n->data.root = NULL;\n    } else {\n        fprintf(stderr, \"Cannot deallocate node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n\n    free(n);\n}\n\nvoid append(node *root, node *elem) {\n    if (root == NULL) {\n        fprintf(stderr, \"Cannot append to uninitialized node.\");\n        exit(1);\n    }\n    if (elem == NULL) {\n        return;\n    }\n\n    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {\n        if (root->data.root == NULL) {\n            root->data.root = elem;\n        } else {\n            node *it = root->data.root;\n            while (it->next != NULL) {\n                it = it->next;\n            }\n            it->next = elem;\n        }\n    } else {\n        fprintf(stderr, \"Cannot append to node with tag: %d\\n\", root->tag);\n        exit(1);\n    }\n}\n\nsize_t count(node *n) {\n    if (n == NULL) {\n        return 0;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        return 1;\n    }\n    if (n->tag == NODE_TREE) {\n        size_t sum = 0;\n        node *it = n->data.root;\n        while (it != NULL) {\n            sum += count(it);\n            it = it->next;\n        }\n        return sum;\n    }\n    if (n->tag == NODE_SEQ) {\n        size_t prod = 1;\n        node *it = n->data.root;\n        while (it != NULL) {\n            prod *= count(it);\n            it = it->next;\n        }\n        return prod;\n    }\n\n    fprintf(stderr, \"Cannot count node with tag: %d\\n\", n->tag);\n    exit(1);\n}\n\nvoid expand(node *n, size_t pos) {\n    if (n == NULL) {\n        return;\n    }\n\n    if (n->tag == NODE_LEAF) {\n        printf(n->data.str);\n    } else if (n->tag == NODE_TREE) {\n        node *it = n->data.root;\n        while (true) {\n            size_t cnt = count(it);\n            if (pos < cnt) {\n                expand(it, pos);\n                break;\n            }\n            pos -= cnt;\n            it = it->next;\n        }\n    } else if (n->tag == NODE_SEQ) {\n        size_t prod = pos;\n        node *it = n->data.root;\n        while (it != NULL) {\n            size_t cnt = count(it);\n\n            size_t rem = prod % cnt;\n            expand(it, rem);\n\n            it = it->next;\n        }\n    } else {\n        fprintf(stderr, \"Cannot expand node with tag: %d\\n\", n->tag);\n        exit(1);\n    }\n}\n\nstring allocate_string(string src) {\n    size_t len = strlen(src);\n    string out = calloc(len + 1, sizeof(character));\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to allocate a copy of the string.\");\n        exit(1);\n    }\n    strcpy(out, src);\n    return out;\n}\n\nnode *parse_seq(string input, size_t *pos);\n\nnode *parse_tree(string input, size_t *pos) {\n    node *root = make_tree();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n    size_t depth = 0;\n    bool asSeq = false;\n    bool allow = false;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = '\\\\';\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n            asSeq = true;\n            depth++;\n        } else if (c == '}') {\n            if (depth-- > 0) {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            } else {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                }\n                break;\n            }\n        } else if (c == ',') {\n            if (depth == 0) {\n                if (asSeq) {\n                    size_t new_pos = 0;\n                    node *seq = parse_seq(buffer, &new_pos);\n                    append(root, seq);\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                    asSeq = false;\n                } else {\n                    append(root, make_leaf(allocate_string(buffer)));\n                    bufpos = 0;\n                    buffer[bufpos] = 0;\n                }\n            } else {\n                buffer[bufpos++] = c;\n                buffer[bufpos] = 0;\n            }\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    return root;\n}\n\nnode *parse_seq(string input, size_t *pos) {\n    node *root = make_seq();\n\n    character buffer[BUFFER_SIZE] = { 0 };\n    size_t bufpos = 0;\n\n    while (input[*pos] != 0) {\n        character c = input[(*pos)++];\n        if (c == '\\\\') {\n            c = input[(*pos)++];\n            if (c == 0) {\n                break;\n            }\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        } else if (c == '{') {\n            node *tree = parse_tree(input, pos);\n            if (bufpos > 0) {\n                append(root, make_leaf(allocate_string(buffer)));\n                bufpos = 0;\n                buffer[bufpos] = 0;\n            }\n            append(root, tree);\n        } else {\n            buffer[bufpos++] = c;\n            buffer[bufpos] = 0;\n        }\n    }\n\n    if (bufpos > 0) {\n        append(root, make_leaf(allocate_string(buffer)));\n        bufpos = 0;\n        buffer[bufpos] = 0;\n    }\n\n    return root;\n}\n\nvoid test(string input) {\n    size_t pos = 0;\n    node *n = parse_seq(input, &pos);\n    size_t cnt = count(n);\n    size_t i;\n\n    printf(\"Pattern: %s\\n\", input);\n\n    for (i = 0; i < cnt; i++) {\n        expand(n, i);\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n\n    deallocate_node(n);\n}\n\nint main() {\n    test(\"~/{Downloads,Pictures}/*.{jpg,gif,png}\");\n    test(\"It{{em,alic}iz,erat}e{d,}, please.\");\n    test(\"{,{,gotta have{ ,\\\\, again\\\\, }}more }cowbell!\");\n\n    \n    \n\n    return 0;\n}\n"}
{"id": 60761, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 60762, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 60763, "name": "Call a function", "Go": "import (\n\t\"image\"\n\t\"image/gif\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc f() (int, float64)  { return 0, 0 }\nfunc g(int, float64) int { return 0 }\nfunc h(string, ...int)   {}\n", "C": "\nf();\n\n\ng(1, 2, 3);\n\n\nint op_arg();\nint main()\n{\n\top_arg(1);\n\top_arg(1, 2);\n\top_arg(1, 2, 3);\n\treturn 0;\n}\nint op_arg(int a, int b)\n{\n\tprintf(\"%d %d %d\\n\", a, b, (&b)[1]);\n\treturn a;\n}  \n\n\nvoid h(int a, ...)\n{\n\tva_list ap;\n\tva_start(ap);\n\t...\n}\n\nh(1, 2, 3, 4, \"abcd\", (void*)0);\n\n\nstruct v_args {\n    int arg1;\n    int arg2;\n    char _sentinel;\n};\n\nvoid _v(struct v_args args)\n{\n    printf(\"%d, %d\\n\", args.arg1, args.arg2);\n}\n\n#define v(...) _v((struct v_args){__VA_ARGS__})\n\nv(.arg2 = 5, .arg1 = 17); \n\nv(.arg2=1); \nv();  \n\n\nprintf(\"%p\", f); \n\n\ndouble a = asin(1);\n\n\n\n\n\n\n\n"}
{"id": 60764, "name": "Superpermutation minimisation", "Go": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n    super []byte\n    pos   int\n    cnt   [max]int\n)\n\n\nfunc factSum(n int) int {\n    s := 0\n    for x, f := 0, 1; x < n; {\n        x++\n        f *= x\n        s += f\n    }\n    return s\n}\n\nfunc r(n int) bool {\n    if n == 0 {\n        return false\n    }\n    c := super[pos-n]\n    cnt[n]--\n    if cnt[n] == 0 {\n        cnt[n] = n\n        if !r(n - 1) {\n            return false\n        }\n    }\n    super[pos] = c\n    pos++\n    return true\n}\n\nfunc superperm(n int) {\n    pos = n\n    le := factSum(n)\n    super = make([]byte, le)\n    for i := 0; i <= n; i++ {\n        cnt[i] = i\n    }\n    for i := 1; i <= n; i++ {\n        super[i-1] = byte(i) + '0'\n    }\n\n    for r(n) {\n    }\n}\n\nfunc main() {\n    for n := 0; n < max; n++ {\n        fmt.Printf(\"superperm(%2d) \", n)\n        superperm(n)\n        fmt.Printf(\"len = %d\\n\", len(super))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAX 12\nchar *super = 0;\nint pos, cnt[MAX];\n\n\nint fact_sum(int n)\n{\n\tint s, x, f;\n\tfor (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);\n\treturn s;\n}\n\nint r(int n)\n{\n\tif (!n) return 0;\n\n\tchar c = super[pos - n];\n\tif (!--cnt[n]) {\n\t\tcnt[n] = n;\n\t\tif (!r(n-1)) return 0;\n\t}\n\tsuper[pos++] = c;\n\treturn 1;\n}\n\nvoid superperm(int n)\n{\n\tint i, len;\n\n\tpos = n;\n\tlen = fact_sum(n);\n\tsuper = realloc(super, len + 1);\n\tsuper[len] = '\\0';\n\n\tfor (i = 0; i <= n; i++) cnt[i] = i;\n\tfor (i = 1; i <= n; i++) super[i - 1] = i + '0';\n\n\twhile (r(n));\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 0; n < MAX; n++) {\n\t\tprintf(\"superperm(%2d) \", n);\n\t\tsuperperm(n);\n\t\tprintf(\"len = %d\", (int)strlen(super));\n\t\t\n\t\t\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60765, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n"}
{"id": 60766, "name": "GUI component interaction", "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, str string) (int64, bool) {\n    i, err := strconv.ParseInt(str, 10, 64)\n    if err != nil {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid value\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return 0, false\n    }\n    return i, 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    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create box:\")\n    box.SetBorderWidth(1)\n\n    label, err := gtk.LabelNew(\"Value:\")\n    check(err, \"Unable to create label:\")\n\n    entry, err := gtk.EntryNew()\n    check(err, \"Unable to create entry:\")\n    entry.SetText(\"0\") \n    entry.Connect(\"activate\", func() {\n        \n        str, _ := entry.GetText()\n        validateInput(window, str)\n    })\n\n    \n    ib, err := gtk.ButtonNewWithLabel(\"Increment\")\n    check(err, \"Unable to create increment button:\")\n    ib.Connect(\"clicked\", func() {\n        \n        str, _ := entry.GetText()\n        if i, ok := validateInput(window, str); ok {\n            entry.SetText(strconv.FormatInt(i+1, 10))\n        }\n    })\n\n    \n    rb, err := gtk.ButtonNewWithLabel(\"Random\")\n    check(err, \"Unable to create random button:\")\n    rb.Connect(\"clicked\", func() {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_QUESTION,\n            gtk.BUTTONS_YES_NO,\n            \"Set random value\",\n        )\n        answer := dialog.Run()\n        dialog.Destroy()\n        if answer == gtk.RESPONSE_YES {\n            entry.SetText(strconv.Itoa(rand.Intn(10000)))\n        }\n    })\n\n    box.PackStart(label, false, false, 2)\n    box.PackStart(entry, false, false, 2)\n    box.PackStart(ib, false, false, 2)\n    box.PackStart(rb, false, false, 2)\n    window.Add(box)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "C": "#include <windows.h>\n#include \"resource.h\"\n\nBOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {\n    switch( msg ) {\n\n        case WM_INITDIALOG:\n            srand( GetTickCount() );\n            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );\n            break;\n\n        case WM_COMMAND:\n            switch( LOWORD(wPar) ) {\n                case IDC_INCREMENT: {\n                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );\n                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );\n                    } break;\n                case IDC_RANDOM: {\n                    int reply = MessageBox( hwnd,\n                        \"Do you really want to\\nget a random number?\",\n                        \"Random input confirmation\", MB_ICONQUESTION|MB_YESNO );\n                    if( reply == IDYES )\n                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );\n                    } break;\n                case IDC_QUIT:\n                    SendMessage( hwnd, WM_CLOSE, 0, 0 );\n                    break;\n                default: ;\n            }\n            break;\n\n        case WM_CLOSE: {\n            int reply = MessageBox( hwnd,\n                \"Do you really want to quit?\",\n                \"Quit confirmation\", MB_ICONQUESTION|MB_YESNO );\n            if( reply == IDYES )\n                EndDialog( hwnd, 0 );\n            } break;\n\n        default: ;\n    }\n\n    return 0;\n}\n\nint WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {\n    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );\n}\n"}
{"id": 60767, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 60768, "name": "One of n lines in a file", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"io\"\n    \"math/rand\"\n    \"time\"\n)\n\n\n\n\n\n\n\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n    br := bufio.NewReader(r)\n    s, err = br.ReadString('\\n')\n    if err != nil {\n        return\n    }\n    ln = 1\n    lnLast := 1.\n    var sLast string\n    for {\n        \n        \n        sLast, err = br.ReadString('\\n')\n        if err == io.EOF {\n            return s, ln, nil \n        }\n        if err != nil {\n            break\n        }\n        lnLast++\n        if rand.Float64() < 1/lnLast {\n            s = sLast\n            ln = int(lnLast)\n        }\n    }\n    return \n}\n\n\n\n\n\nfunc oneOfN(n int, file io.Reader) int {\n    _, ln, err := choseLineRandomly(file)\n    if err != nil {\n        panic(err)\n    }\n    return ln\n}\n\n\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n    if *r <= 0 {\n        return 0, io.EOF\n    }\n    b[0] = '\\n'\n    *r--\n    return 1, nil\n}\n\nfunc main() {\n    \n    \n    n := 10\n    freq := make([]int, n)\n    rand.Seed(time.Now().UnixNano())\n    for times := 0; times < 1e6; times++ {\n        sr := simReader(n)\n        freq[oneOfN(n, &sr)-1]++\n    }\n\n    \n    fmt.Println(freq)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ninline int irand(int n)\n{\n\tint r, randmax = RAND_MAX/n * n;\n\twhile ((r = rand()) >= randmax);\n\treturn r / (randmax / n);\n}\n\ninline int one_of_n(int n)\n{\n\tint i, r = 0;\n\tfor (i = 1; i < n; i++) if (!irand(i + 1)) r = i;\n\treturn r;\n}\n\nint main(void)\n{\n\tint i, r[10] = {0};\n\n\tfor (i = 0; i < 1000000; i++, r[one_of_n(10)]++);\n\tfor (i = 0; i < 10; i++)\n\t\tprintf(\"%d%c\", r[i], i == 9 ? '\\n':' ');\n\n\treturn 0;\n}\n"}
{"id": 60769, "name": "Summarize and say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    var maxLen int\n    var seqMaxLen [][]string\n    for n := 1; n < 1e6; n++ {\n        switch s := seq(n); {\n        case len(s) == maxLen:\n            seqMaxLen = append(seqMaxLen, s)\n        case len(s) > maxLen:\n            maxLen = len(s)\n            seqMaxLen = [][]string{s}\n        }\n    }\n    fmt.Println(\"Max sequence length:\", maxLen)\n    fmt.Println(\"Sequences:\", len(seqMaxLen))\n    for _, seq := range seqMaxLen {\n        fmt.Println(\"Sequence:\")\n        for _, t := range seq {\n            fmt.Println(t)\n        }\n    }\n}\n\nfunc seq(n int) []string {\n    s := strconv.Itoa(n)\n    ss := []string{s}\n\n    for {\n        dSeq := sortD(s)\n        d := dSeq[0]\n        nd := 1\n        s = \"\"\n        for i := 1; ; i++ {\n            if i == len(dSeq) {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                break\n            }\n            if dSeq[i] == d {\n                nd++\n            } else {\n                s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n                d = dSeq[i]\n                nd = 1\n            }\n        }\n        for _, s0 := range ss {\n            if s == s0 {\n                return ss\n            }\n        }\n        ss = append(ss, s)\n    }\n    panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n    r := make([]rune, len(s))\n    for i, d := range s {\n        j := 0\n        for ; j < i; j++ {\n            if d > r[j] {\n                copy(r[j+1:], r[j:i])\n                break\n            }\n        }\n        r[j] = d\n    }\n    return r\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct rec_t rec_t;\nstruct rec_t {\n\tint depth;\n\trec_t * p[10];\n};\n\nrec_t root = {0, {0}};\n\n#define USE_POOL_ALLOC\n#ifdef USE_POOL_ALLOC \nrec_t *tail = 0, *head = 0;\n#define POOL_SIZE (1 << 20)\ninline rec_t *new_rec()\n{\n\tif (head == tail) {\n\t\thead = calloc(sizeof(rec_t), POOL_SIZE);\n\t\ttail = head + POOL_SIZE;\n\t}\n\treturn head++;\n}\n#else\n#define new_rec() calloc(sizeof(rec_t), 1)\n#endif\n\nrec_t *find_rec(char *s)\n{\n\tint i;\n\trec_t *r = &root;\n\twhile (*s) {\n\t\ti = *s++ - '0';\n\t\tif (!r->p[i]) r->p[i] = new_rec();\n\t\tr = r->p[i];\n\t}\n\treturn r;\n}\n\n\nchar number[100][4];\nvoid init()\n{\n\tint i;\n\tfor (i = 0; i < 100; i++)\n\t\tsprintf(number[i], \"%d\", i);\n}\n\nvoid count(char *buf)\n{\n\tint i, c[10] = {0};\n\tchar *s;\n\n\tfor (s = buf; *s; c[*s++ - '0']++);\n\n\tfor (i = 9; i >= 0; i--) {\n\t\tif (!c[i]) continue;\n\t\ts = number[c[i]];\n\n\t\t*buf++ = s[0];\n\t\tif ((*buf = s[1])) buf++;\n\n\t\t*buf++ = i + '0';\n\t}\n\n\t*buf = '\\0';\n}\n\nint depth(char *in, int d)\n{\n\trec_t *r = find_rec(in);\n\n\tif (r->depth > 0)\n\t\treturn r->depth;\n\n\td++;\n\tif (!r->depth)\tr->depth = -d;\n\telse\t\tr->depth += d;\n\n\tcount(in);\n\td = depth(in, d);\n\n\tif (r->depth <= 0) r->depth = d + 1;\n\treturn r->depth;\n}\n\nint main(void)\n{\n\tchar a[100];\n\tint i, d, best_len = 0, n_best = 0;\n\tint best_ints[32];\n\trec_t *r;\n\n\tinit();\n\n\tfor (i = 0; i < 1000000; i++) {\n\t\tsprintf(a, \"%d\", i);\n\t\td = depth(a, 0);\n\n\t\tif (d < best_len) continue;\n\t\tif (d > best_len) {\n\t\t\tn_best = 0;\n\t\t\tbest_len = d;\n\t\t}\n\t\tif (d == best_len)\n\t\t\tbest_ints[n_best++] = i;\n\t}\n\n\tprintf(\"longest length: %d\\n\", best_len);\n\tfor (i = 0; i < n_best; i++) {\n\t\tprintf(\"%d\\n\", best_ints[i]);\n\t\tsprintf(a, \"%d\", best_ints[i]);\n\t\tfor (d = 0; d <= best_len; d++) {\n\t\t\tr = find_rec(a);\n\t\t\tprintf(\"%3d: %s\\n\", r->depth, a);\n\t\t\tcount(a);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n\treturn 0;\n}\n"}
{"id": 60770, "name": "Spelling of ordinal numbers", "Go": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\":    \"first\",\n\t\"two\":    \"second\",\n\t\"three\":  \"third\",\n\t\"five\":   \"fifth\",\n\t\"eight\":  \"eighth\",\n\t\"nine\":   \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t\n\t\n\t\n\t\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\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 <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <glib.h>\n\ntypedef uint64_t integer;\n\ntypedef struct number_names_tag {\n    const char* cardinal;\n    const char* ordinal;\n} number_names;\n\nconst number_names small[] = {\n    { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n    { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n    { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n    { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n    { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n    { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n    { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n    { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n    { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n    { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n    { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n    { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\ntypedef struct named_number_tag {\n    const char* cardinal;\n    const char* ordinal;\n    integer number;\n} named_number;\n\nconst named_number named_numbers[] = {\n    { \"hundred\", \"hundredth\", 100 },\n    { \"thousand\", \"thousandth\", 1000 },\n    { \"million\", \"millionth\", 1000000 },\n    { \"billion\", \"billionth\", 1000000000 },\n    { \"trillion\", \"trillionth\", 1000000000000 },\n    { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n    { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_small_name(const number_names* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst char* get_big_name(const named_number* n, bool ordinal) {\n    return ordinal ? n->ordinal : n->cardinal;\n}\n\nconst named_number* get_named_number(integer n) {\n    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);\n    for (size_t i = 0; i + 1 < names_len; ++i) {\n        if (n < named_numbers[i + 1].number)\n            return &named_numbers[i];\n    }\n    return &named_numbers[names_len - 1];\n}\n\nvoid append_number_name(GString* gstr, integer n, bool ordinal) {\n    if (n < 20)\n        g_string_append(gstr, get_small_name(&small[n], ordinal));\n    else if (n < 100) {\n        if (n % 10 == 0) {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));\n        } else {\n            g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));\n            g_string_append_c(gstr, '-');\n            g_string_append(gstr, get_small_name(&small[n % 10], ordinal));\n        }\n    } else {\n        const named_number* num = get_named_number(n);\n        integer p = num->number;\n        append_number_name(gstr, n/p, false);\n        g_string_append_c(gstr, ' ');\n        if (n % p == 0) {\n            g_string_append(gstr, get_big_name(num, ordinal));\n        } else {\n            g_string_append(gstr, get_big_name(num, false));\n            g_string_append_c(gstr, ' ');\n            append_number_name(gstr, n % p, ordinal);\n        }\n    }\n}\n\nGString* number_name(integer n, bool ordinal) {\n    GString* result = g_string_sized_new(8);\n    append_number_name(result, n, ordinal);\n    return result;\n}\n\nvoid test_ordinal(integer n) {\n    GString* name = number_name(n, true);\n    printf(\"%llu: %s\\n\", n, name->str);\n    g_string_free(name, TRUE);\n}\n\nint main() {\n    test_ordinal(1);\n    test_ordinal(2);\n    test_ordinal(3);\n    test_ordinal(4);\n    test_ordinal(5);\n    test_ordinal(11);\n    test_ordinal(15);\n    test_ordinal(21);\n    test_ordinal(42);\n    test_ordinal(65);\n    test_ordinal(98);\n    test_ordinal(100);\n    test_ordinal(101);\n    test_ordinal(272);\n    test_ordinal(300);\n    test_ordinal(750);\n    test_ordinal(23456);\n    test_ordinal(7891233);\n    test_ordinal(8007006005004003LL);\n    return 0;\n}\n"}
{"id": 60771, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 60772, "name": "Self-describing numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\nfunc sdn(n int64) bool {\n    if n >= 1e10 {\n        return false\n    }\n    s := strconv.FormatInt(n, 10)\n    for d, p := range s {\n        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc main() {\n    for n := int64(0); n < 1e10; n++ {\n        if sdn(n) {\n            fmt.Println(n)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\ninline int self_desc(unsigned long long xx)\n{\n\tregister unsigned int d, x;\n\tunsigned char cnt[10] = {0}, dig[10] = {0};\n \n\tfor (d = 0; xx > ~0U; xx /= 10)\n\t\tcnt[ dig[d++] = xx % 10 ]++;\n \n\tfor (x = xx; x; x /= 10)\n\t\tcnt[ dig[d++] = x % 10 ]++;\n \n\twhile(d-- && dig[x++] == cnt[d]);\n \n\treturn d == -1;\n}\n \nint main()\n{\n\tint i;\n\tfor (i = 1; i < 100000000; i++) \n\t\tif (self_desc(i)) printf(\"%d\\n\", i);\n \n\treturn 0;\n}\n"}
{"id": 60773, "name": "Addition chains", "Go": "package main\n\nimport \"fmt\"\n\nvar example []int\n\nfunc reverse(s []int) {\n    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n        s[i], s[j] = s[j], s[i]\n    }\n}\n\nfunc checkSeq(pos, n, minLen int, seq []int) (int, int) {\n    switch {\n    case pos > minLen || seq[0] > n:\n        return minLen, 0\n    case seq[0] == n:\n        example = seq\n        return pos, 1\n    case pos < minLen:\n        return tryPerm(0, pos, n, minLen, seq)\n    default:\n        return minLen, 0\n    }\n}\n\nfunc tryPerm(i, pos, n, minLen int, seq []int) (int, int) {\n    if i > pos {\n        return minLen, 0\n    }\n    seq2 := make([]int, len(seq)+1)\n    copy(seq2[1:], seq)\n    seq2[0] = seq[0] + seq[i]\n    res11, res12 := checkSeq(pos+1, n, minLen, seq2)\n    res21, res22 := tryPerm(i+1, pos, n, res11, seq)\n    switch {\n    case res21 < res11:\n        return res21, res22\n    case res21 == res11:\n        return res21, res12 + res22\n    default:\n        fmt.Println(\"Error in tryPerm\")\n        return 0, 0\n    }\n}\n\nfunc initTryPerm(x, minLen int) (int, int) {\n    return tryPerm(0, 0, x, minLen, []int{1})\n}\n\nfunc findBrauer(num, minLen, nbLimit int) {\n    actualMin, brauer := initTryPerm(num, minLen)\n    fmt.Println(\"\\nN =\", num)\n    fmt.Printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin)\n    fmt.Println(\"Number of minimum length Brauer chains :\", brauer)\n    if brauer > 0 {\n        reverse(example)\n        fmt.Println(\"Brauer example :\", example)\n    }\n    example = nil\n    if num <= nbLimit {\n        nonBrauer := findNonBrauer(num, actualMin+1, brauer)\n        fmt.Println(\"Number of minimum length non-Brauer chains :\", nonBrauer)\n        if nonBrauer > 0 {\n            fmt.Println(\"Non-Brauer example :\", example)\n        }\n        example = nil\n    } else {\n        println(\"Non-Brauer analysis suppressed\")\n    }\n}\n\nfunc isAdditionChain(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        if a[i] > a[i-1]*2 {\n            return false\n        }\n        ok := false\n    jloop:\n        for j := i - 1; j >= 0; j-- {\n            for k := j; k >= 0; k-- {\n                if a[j]+a[k] == a[i] {\n                    ok = true\n                    break jloop\n                }\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    if example == nil && !isBrauer(a) {\n        example = make([]int, len(a))\n        copy(example, a)\n    }\n    return true\n}\n\nfunc isBrauer(a []int) bool {\n    for i := 2; i < len(a); i++ {\n        ok := false\n        for j := i - 1; j >= 0; j-- {\n            if a[i-1]+a[j] == a[i] {\n                ok = true\n                break\n            }\n        }\n        if !ok {\n            return false\n        }\n    }\n    return true\n}\n\nfunc nextChains(index, le int, seq []int, pcount *int) {\n    for {\n        if index < le-1 {\n            nextChains(index+1, le, seq, pcount)\n        }\n        if seq[index]+le-1-index >= seq[le-1] {\n            return\n        }\n        seq[index]++\n        for i := index + 1; i < le-1; i++ {\n            seq[i] = seq[i-1] + 1\n        }\n        if isAdditionChain(seq) {\n            (*pcount)++\n        }\n    }\n}\n\nfunc findNonBrauer(num, le, brauer int) int {\n    seq := make([]int, le)\n    seq[0] = 1\n    seq[le-1] = num\n    for i := 1; i < le-1; i++ {\n        seq[i] = seq[i-1] + 1\n    }\n    count := 0\n    if isAdditionChain(seq) {\n        count = 1\n    }\n    nextChains(2, le, seq, &count)\n    return count - brauer\n}\n\nfunc main() {\n    nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}\n    fmt.Println(\"Searching for Brauer chains up to a minimum length of 12:\")\n    for _, num := range nums {\n        findBrauer(num, 12, 79)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\ntypedef struct {\n    int x, y;\n} pair;\n\nint* example = NULL;\nint exampleLen = 0;\n\nvoid reverse(int s[], int len) {\n    int i, j, t;\n    for (i = 0, j = len - 1; i < j; ++i, --j) {\n        t = s[i];\n        s[i] = s[j];\n        s[j] = t;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen);\n\npair checkSeq(int pos, int seq[], int n, int len, int minLen) {\n    pair p;\n    if (pos > minLen || seq[0] > n) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    else if (seq[0] == n) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, seq, len * sizeof(int));\n        exampleLen = len;\n        p.x = pos; p.y = 1;\n        return p;\n    }\n    else if (pos < minLen) {\n        return tryPerm(0, pos, seq, n, len, minLen);\n    }\n    else {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n}\n\npair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) {\n    int *seq2;\n    pair p, res1, res2;\n    size_t size = sizeof(int);    \n    if (i > pos) {\n        p.x = minLen; p.y = 0;\n        return p;\n    }\n    seq2 = malloc((len + 1) * size);\n    memcpy(seq2 + 1, seq, len * size);\n    seq2[0] = seq[0] + seq[i];\n    res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen);\n    res2 = tryPerm(i + 1, pos, seq, n, len, res1.x);\n    free(seq2);\n    if (res2.x < res1.x)\n        return res2;\n    else if (res2.x == res1.x) {\n        p.x = res2.x; p.y = res1.y + res2.y;\n        return p;\n    }\n    else {\n        printf(\"Error in tryPerm\\n\");\n        p.x = 0; p.y = 0;\n        return p;\n    }\n}\n\npair initTryPerm(int x, int minLen) {\n    int seq[1] = {1};\n    return tryPerm(0, 0, seq, x, 1, minLen);\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}\n\nbool isBrauer(int a[], int len) {\n    int i, j;\n    bool ok;\n    for (i = 2; i < len; ++i) {\n        ok = FALSE;\n        for (j = i - 1; j >= 0; j--) {\n            if (a[i-1] + a[j] == a[i]) {\n                ok = TRUE;\n                break;\n            }\n        }\n        if (!ok) return FALSE;\n    }\n    return TRUE;\n}\n\nbool isAdditionChain(int a[], int len) {\n    int i, j, k;\n    bool ok, exit;\n    for (i = 2; i < len; ++i) {\n        if (a[i] > a[i - 1] * 2) return FALSE;\n        ok = FALSE; exit = FALSE;\n        for (j = i - 1; j >= 0; --j) {\n            for (k = j; k >= 0; --k) {\n               if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; }\n            }\n            if (exit) break;\n        }\n        if (!ok) return FALSE;\n    }\n    if (example == NULL && !isBrauer(a, len)) {\n        example = malloc(len * sizeof(int));\n        memcpy(example, a, len * sizeof(int));\n        exampleLen = len;\n    }\n    return TRUE;\n}\n\nvoid nextChains(int index, int len, int seq[], int *pcount) {\n    for (;;) {\n        int i;\n        if (index < len - 1) {\n           nextChains(index + 1, len, seq, pcount);\n        }\n        if (seq[index] + len - 1 - index >= seq[len - 1]) return;\n        seq[index]++;\n        for (i = index + 1; i < len - 1; ++i) {\n            seq[i] = seq[i-1] + 1;\n        }\n        if (isAdditionChain(seq, len)) (*pcount)++;\n    }\n}\n\nint findNonBrauer(int num, int len, int brauer) {\n    int i, count = 0;\n    int *seq = malloc(len * sizeof(int));\n    seq[0] = 1;\n    seq[len - 1] = num;\n    for (i = 1; i < len - 1; ++i) {\n        seq[i] = seq[i - 1] + 1;\n    }\n    if (isAdditionChain(seq, len)) count = 1;\n    nextChains(2, len, seq, &count);\n    free(seq);\n    return count - brauer;\n}\n\nvoid findBrauer(int num, int minLen, int nbLimit) {\n    pair p = initTryPerm(num, minLen);\n    int actualMin = p.x, brauer = p.y, nonBrauer;\n    printf(\"\\nN = %d\\n\", num);\n    printf(\"Minimum length of chains : L(%d) = %d\\n\", num, actualMin);\n    printf(\"Number of minimum length Brauer chains : %d\\n\", brauer);\n    if (brauer > 0) {\n        printf(\"Brauer example : \");\n        reverse(example, exampleLen);\n        printArray(example, exampleLen);\n    }\n    if (example != NULL) {\n        free(example);\n        example = NULL; \n        exampleLen = 0;\n    }\n    if (num <= nbLimit) {\n        nonBrauer = findNonBrauer(num, actualMin + 1, brauer);\n        printf(\"Number of minimum length non-Brauer chains : %d\\n\", nonBrauer);\n        if (nonBrauer > 0) {\n            printf(\"Non-Brauer example : \");\n            printArray(example, exampleLen);\n        }\n        if (example != NULL) {\n            free(example);\n            example = NULL; \n            exampleLen = 0;\n        }\n    }\n    else {\n        printf(\"Non-Brauer analysis suppressed\\n\");\n    }\n}\n\nint main() {\n    int i;\n    int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};\n    printf(\"Searching for Brauer chains up to a minimum length of 12:\\n\");\n    for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79);\n    return 0;\n}\n"}
{"id": 60774, "name": "Numeric separator syntax", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n"}
{"id": 60775, "name": "Numeric separator syntax", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}\n    for _, integer := range integers {\n        fmt.Printf(\"%d  \", integer)\n    }\n    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}\n    for _, float := range floats {\n        fmt.Printf(\"%g  \", float)\n    }\n    fmt.Println()\n    \n    \n}\n", "C": "#include <locale.h>\n#include <stdio.h>\n\nint main()\n{\n  unsigned long long int trillion = 1000000000000;\n\n  setlocale(LC_NUMERIC,\"\");\n\n  printf(\"Locale : %s, One Trillion : %'llu\\n\", setlocale(LC_CTYPE,NULL),trillion);\n\n  return 0;\n}\n"}
{"id": 60776, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 60777, "name": "Repeat", "Go": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n  for i := 0; i < n; i++ {\n    f()\n  }\n}\n\nfunc fn() {\n  fmt.Println(\"Example\")\n}\n\nfunc main() {\n  repeat(4, fn)\n}\n", "C": "#include <stdio.h>\n\nvoid repeat(void (*f)(void), unsigned int n) {\n while (n-->0)\n  (*f)(); \n}\n\nvoid example() {\n printf(\"Example\\n\");\n}\n\nint main(int argc, char *argv[]) {\n repeat(example, 4);\n return 0;\n}\n"}
{"id": 60778, "name": "Sparkline in unicode", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 60779, "name": "Sparkline in unicode", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"errors\"\n    \"fmt\"\n    \"math\"\n    \"os\"\n    \"regexp\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc main() {\n    fmt.Println(\"Numbers please separated by space/commas:\")\n    sc := bufio.NewScanner(os.Stdin)\n    sc.Scan()\n    s, n, min, max, err := spark(sc.Text())\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if n == 1 {\n        fmt.Println(\"1 value =\", min)\n    } else {\n        fmt.Println(n, \"values.  Min:\", min, \"Max:\", max)\n    }\n    fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n    ss := sep.Split(s0, -1)\n    n = len(ss)\n    vs := make([]float64, n)\n    var v float64\n    min = math.Inf(1)\n    max = math.Inf(-1)\n    for i, s := range ss {\n        switch v, err = strconv.ParseFloat(s, 64); {\n        case err != nil:\n        case math.IsNaN(v):\n            err = errors.New(\"NaN not supported.\")\n        case math.IsInf(v, 0):\n            err = errors.New(\"Inf not supported.\")\n        default:\n            if v < min {\n                min = v\n            }\n            if v > max {\n                max = v\n            }\n            vs[i] = v\n            continue\n        }\n        return\n    }\n    if min == max {\n        sp = strings.Repeat(\"▄\", n)\n    } else {\n        rs := make([]rune, n)\n        f := 8 / (max - min)\n        for j, v := range vs {\n            i := rune(f * (v - min))\n            if i > 7 {\n                i = 7\n            }\n            rs[j] = '▁' + i\n        }\n        sp = string(rs)\n    }\n    return\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<locale.h>\n#include<stdio.h>\n#include<wchar.h>\n#include<math.h>\n\nint main(int argC,char* argV[])\n{\n\tdouble* arr,min,max;\n\tchar* str;\n\tint i,len;\n\tif(argC == 1)\n\t\tprintf(\"Usage : %s <data points separated by spaces or commas>\",argV[0]);\n\telse{\n\t\tarr = (double*)malloc((argC-1)*sizeof(double));\n\t\tfor(i=1;i<argC;i++){\n\t\t\tlen = strlen(argV[i]);\n\t\t\t\n\t\t\tif(argV[i][len-1]==','){\n\t\t\t\tstr = (char*)malloc(len*sizeof(char));\n\t\t\t\tstrncpy(str,argV[i],len-1);\n\t\t\t\tarr[i-1] = atof(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t\telse\n\t\t\t\tarr[i-1] = atof(argV[i]);\n\t\t\tif(i==1){\n\t\t\t\tmin = arr[i-1];\n\t\t\t\tmax = arr[i-1];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmin=(min<arr[i-1]?min:arr[i-1]);\n\t\t\t\tmax=(max>arr[i-1]?max:arr[i-1]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"\\n%Max : %lf,Min : %lf,Range : %lf\\n\",max,min,max-min);\n\t\t\n\t\tsetlocale(LC_ALL, \"\");\n\t\t\n\t\tfor(i=1;i<argC;i++){\n\t\t\tprintf(\"%lc\", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 60780, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 60781, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 60782, "name": "Compiler_AST interpreter", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\ntype NodeType int\n\nconst (\n    ndIdent NodeType = iota\n    ndString\n    ndInteger\n    ndSequence\n    ndIf\n    ndPrtc\n    ndPrts\n    ndPrti\n    ndWhile\n    ndAssign\n    ndNegate\n    ndNot\n    ndMul\n    ndDiv\n    ndMod\n    ndAdd\n    ndSub\n    ndLss\n    ndLeq\n    ndGtr\n    ndGeq\n    ndEql\n    ndNeq\n    ndAnd\n    ndOr\n)\n\ntype Tree struct {\n    nodeType NodeType\n    left     *Tree\n    right    *Tree\n    value    int\n}\n\n\ntype atr struct {\n    enumText string\n    nodeType NodeType\n}\n\nvar atrs = []atr{\n    {\"Identifier\", ndIdent},\n    {\"String\", ndString},\n    {\"Integer\", ndInteger},\n    {\"Sequence\", ndSequence},\n    {\"If\", ndIf},\n    {\"Prtc\", ndPrtc},\n    {\"Prts\", ndPrts},\n    {\"Prti\", ndPrti},\n    {\"While\", ndWhile},\n    {\"Assign\", ndAssign},\n    {\"Negate\", ndNegate},\n    {\"Not\", ndNot},\n    {\"Multiply\", ndMul},\n    {\"Divide\", ndDiv},\n    {\"Mod\", ndMod},\n    {\"Add\", ndAdd},\n    {\"Subtract\", ndSub},\n    {\"Less\", ndLss},\n    {\"LessEqual\", ndLeq},\n    {\"Greater\", ndGtr},\n    {\"GreaterEqual\", ndGeq},\n    {\"Equal\", ndEql},\n    {\"NotEqual\", ndNeq},\n    {\"And\", ndAnd},\n    {\"Or\", ndOr},\n}\n\nvar (\n    stringPool   []string\n    globalNames  []string\n    globalValues = make(map[int]int)\n)\n\nvar (\n    err     error\n    scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n    log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc btoi(b bool) int {\n    if b {\n        return 1\n    }\n    return 0\n}\n\nfunc itob(i int) bool {\n    if i == 0 {\n        return false\n    }\n    return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n    return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n    return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { \n    if x == nil {\n        return 0\n    }\n    switch x.nodeType {\n    case ndInteger:\n        return x.value\n    case ndIdent:\n        return globalValues[x.value]\n    case ndString:\n        return x.value\n    case ndAssign:\n        n := interp(x.right)\n        globalValues[x.left.value] = n\n        return n\n    case ndAdd:\n        return interp(x.left) + interp(x.right)\n    case ndSub:\n        return interp(x.left) - interp(x.right)\n    case ndMul:\n        return interp(x.left) * interp(x.right)\n    case ndDiv:\n        return interp(x.left) / interp(x.right)\n    case ndMod:\n        return interp(x.left) % interp(x.right)\n    case ndLss:\n        return btoi(interp(x.left) < interp(x.right))\n    case ndGtr:\n        return btoi(interp(x.left) > interp(x.right))\n    case ndLeq:\n        return btoi(interp(x.left) <= interp(x.right))\n    case ndEql:\n        return btoi(interp(x.left) == interp(x.right))\n    case ndNeq:\n        return btoi(interp(x.left) != interp(x.right))\n    case ndAnd:\n        return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n    case ndOr:\n        return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n    case ndNegate:\n        return -interp(x.left)\n    case ndNot:\n        if interp(x.left) == 0 {\n            return 1\n        }\n        return 0\n    case ndIf:\n        if interp(x.left) != 0 {\n            interp(x.right.left)\n        } else {\n            interp(x.right.right)\n        }\n        return 0\n    case ndWhile:\n        for interp(x.left) != 0 {\n            interp(x.right)\n        }\n        return 0\n    case ndPrtc:\n        fmt.Printf(\"%c\", interp(x.left))\n        return 0\n    case ndPrti:\n        fmt.Printf(\"%d\", interp(x.left))\n        return 0\n    case ndPrts:\n        fmt.Print(stringPool[interp(x.left)])\n        return 0\n    case ndSequence:\n        interp(x.left)\n        interp(x.right)\n        return 0\n    default:\n        reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n    }\n    return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n    for _, atr := range atrs {\n        if atr.enumText == name {\n            return atr.nodeType\n        }\n    }\n    reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n    return -1\n}\n\nfunc fetchStringOffset(s string) int {\n    var d strings.Builder\n    s = s[1 : len(s)-1]\n    for i := 0; i < len(s); i++ {\n        if s[i] == '\\\\' && (i+1) < len(s) {\n            if s[i+1] == 'n' {\n                d.WriteByte('\\n')\n                i++\n            } else if s[i+1] == '\\\\' {\n                d.WriteByte('\\\\')\n                i++\n            }\n        } else {\n            d.WriteByte(s[i])\n        }\n    }\n    s = d.String()\n    for i := 0; i < len(stringPool); i++ {\n        if s == stringPool[i] {\n            return i\n        }\n    }\n    stringPool = append(stringPool, s)\n    return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n    for i := 0; i < len(globalNames); i++ {\n        if globalNames[i] == name {\n            return i\n        }\n    }\n    globalNames = append(globalNames, name)\n    return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n    var nodeType NodeType\n    var s string\n    if scanner.Scan() {\n        line := strings.TrimRight(scanner.Text(), \" \\t\")\n        tokens := strings.Fields(line)\n        first := tokens[0]\n        if first[0] == ';' {\n            return nil\n        }\n        nodeType = getEnumValue(first)\n        le := len(tokens)\n        if le == 2 {\n            s = tokens[1]\n        } else if le > 2 {\n            idx := strings.Index(line, `\"`)\n            s = line[idx:]\n        }\n    }\n    check(scanner.Err())\n    if s != \"\" {\n        var n int\n        switch nodeType {\n        case ndIdent:\n            n = fetchVarOffset(s)\n        case ndInteger:\n            n, err = strconv.Atoi(s)\n            check(err)\n        case ndString:\n            n = fetchStringOffset(s)\n        default:\n            reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n        }\n        return makeLeaf(nodeType, n)\n    }    \n    left := loadAst()\n    right := loadAst()\n    return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n    ast, err := os.Open(\"ast.txt\")\n    check(err)\n    defer ast.Close()\n    scanner = bufio.NewScanner(ast)\n    x := loadAst()\n    interp(x)\n}\n", "C": "\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n    k=3;\n    p=1;\n    n=n+2;\n    while ((k*k<=n) && (p)) {\n        p=n/k*k!=n;\n        k=k+2;\n    }\n    if (p) {\n        print(n, \" is prime\\n\");\n        count = count + 1;\n    }\n}\nprint(\"Total primes found: \", count, \"\\n\");\n"}
{"id": 60783, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 60784, "name": "Modular inverse", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}\n", "C": "#include <stdio.h>\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 main(void) {\n\tprintf(\"%d\\n\", mul_inv(42, 2017));\n\treturn 0;\n}\n"}
{"id": 60785, "name": "Simulate input_Mouse", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n"}
{"id": 60786, "name": "Simulate input_Mouse", "Go": "package main\n\nimport \"github.com/go-vgo/robotgo\"\n\nfunc main() {\n    robotgo.MouseClick(\"left\", false) \n    robotgo.MouseClick(\"right\", true) \n}\n", "C": "#define WINVER 0x500\n#include<windows.h>\n\nint main()\n{\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\tint x = maxX/2, y = maxY/2;\n\tdouble factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;\n\t\n\tINPUT ip;\n\t\n\tZeroMemory(&ip,sizeof(ip));\n\t\n\tip.type = INPUT_MOUSE;\n\t\n\twhile(x > 5 || y < maxY-5){\n\n\tip.mi.mouseData = 0;\n\tip.mi.dx = x * factorX;\n\tip.mi.dy = y * factorY;\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;\n\t\t\n\tSendInput(1,&ip,sizeof(ip));\n\tSleep(1);\n\tif(x>3)\t\n\t\tx-=1;\n\tif(y<maxY-3)\n\t\ty+=1;\n\t}\n\t\n\tip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;\n\t\n\tSendInput(1,&ip,sizeof(ip));\n\t\n\treturn 0;\n}\n"}
{"id": 60787, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 60788, "name": "Hello world_Web server", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"net/http\"\n)\n\nfunc main() {\n  http.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n    fmt.Fprintln(w, \"Goodbye, World!\")\n  })\n  log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <err.h>\n\nchar response[] = \"HTTP/1.1 200 OK\\r\\n\"\n\"Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n\"\n\"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>\"\n\"<style>body { background-color: #111 }\"\n\"h1 { font-size:4cm; text-align: center; color: black;\"\n\" text-shadow: 0 0 2mm red}</style></head>\"\n\"<body><h1>Goodbye, world!</h1></body></html>\\r\\n\";\n\nint main()\n{\n  int one = 1, client_fd;\n  struct sockaddr_in svr_addr, cli_addr;\n  socklen_t sin_len = sizeof(cli_addr);\n\n  int sock = socket(AF_INET, SOCK_STREAM, 0);\n  if (sock < 0)\n    err(1, \"can't open socket\");\n\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));\n\n  int port = 8080;\n  svr_addr.sin_family = AF_INET;\n  svr_addr.sin_addr.s_addr = INADDR_ANY;\n  svr_addr.sin_port = htons(port);\n\n  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {\n    close(sock);\n    err(1, \"Can't bind\");\n  }\n\n  listen(sock, 5);\n  while (1) {\n    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);\n    printf(\"got connection\\n\");\n\n    if (client_fd == -1) {\n      perror(\"Can't accept\");\n      continue;\n    }\n\n    write(client_fd, response, sizeof(response) - 1); \n    close(client_fd);\n  }\n}\n"}
{"id": 60789, "name": "Sunflower fractal", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    dc.SetRGB(1, 1, 1)\n    dc.Clear()\n    dc.SetRGB(0, 0, 1)\n    c := (math.Sqrt(5) + 1) / 2\n    numberOfSeeds := 3000\n    for i := 0; i <= numberOfSeeds; i++ {\n        fi := float64(i)\n        fn := float64(numberOfSeeds)\n        r := math.Pow(fi, c) / fn\n        angle := 2 * math.Pi * c * fi\n        x := r*math.Sin(angle) + 200\n        y := r*math.Cos(angle) + 200\n        fi /= fn / 5\n        dc.DrawCircle(x, y, fi)\n    }\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"sunflower_fractal.png\")\n}\n", "C": "\n\n#include<graphics.h>\n#include<math.h>\n\n#define pi M_PI\n\nvoid sunflower(int winWidth, int winHeight, double diskRatio, int iter){\n\tdouble factor = .5 + sqrt(1.25),r,theta;\n\tdouble x = winWidth/2.0, y = winHeight/2.0;\n\tdouble maxRad = pow(iter,factor)/iter;\n\t\n\tint i;\n\t\n\tsetbkcolor(LIGHTBLUE);\n\t\n\tfor(i=0;i<=iter;i++){\n\t\tr = pow(i,factor)/iter;\n\t\t\n\t\tr/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);\n\t\t\n\t\ttheta = 2*pi*factor*i;\n\t\tcircle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));\n\t}\n}\n\nint main()\n{\n\tinitwindow(1000,1000,\"Sunflower...\");\n\t\n\tsunflower(1000,1000,0.5,3000);\n\t\n\tgetch();\n\t\n\tclosegraph();\n\t\n\treturn 0;\n}\n"}
{"id": 60790, "name": "Vogel's approximation method", "Go": "#include <stdio.h>\n#include <limits.h>\n \n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 5\n#define N_COLS 5\n \ntypedef int bool;\n \nint supply[N_ROWS] = { 461, 277, 356, 488,  393 };\nint demand[N_COLS] = { 278,  60, 461, 116, 1060 };\n \nint costs[N_ROWS][N_COLS] = {\n    { 46,  74,  9, 28, 99 },\n    { 12,  75,  6, 36, 48 },\n    { 35, 199,  4,  5, 71 },\n    { 61,  81, 44, 88,  9 },\n    { 85,  60, 14, 25, 79 }\n};\n\n\n \nint main() {\n    \n\n    printf(\"     A    B    C    D    E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'V' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %3d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n#define TRUE 1\n#define FALSE 0\n#define N_ROWS 4\n#define N_COLS 5\n\ntypedef int bool;\n\nint supply[N_ROWS] = { 50, 60, 50, 50 };\nint demand[N_COLS] = { 30, 20, 70, 30, 60 };\n\nint costs[N_ROWS][N_COLS] = {\n    { 16, 16, 13, 22, 17 },\n    { 14, 14, 13, 19, 15 },\n    { 19, 19, 20, 23, 50 },\n    { 50, 12, 50, 15, 11 }\n};\n\nbool row_done[N_ROWS] = { FALSE };\nbool col_done[N_COLS] = { FALSE };\n\nvoid diff(int j, int len, bool is_row, int res[3]) {\n    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;\n    for (i = 0; i < len; ++i) {\n        if((is_row) ? col_done[i] : row_done[i]) continue;\n        c = (is_row) ? costs[j][i] : costs[i][j];\n        if (c < min1) {\n            min2 = min1;\n            min1 = c;\n            min_p = i;\n        }\n        else if (c < min2) min2 = c;\n    }\n    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;\n}\n\nvoid max_penalty(int len1, int len2, bool is_row, int res[4]) {\n    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;\n    int res2[3];\n\n    for (i = 0; i < len1; ++i) {\n        if((is_row) ? row_done[i] : col_done[i]) continue;\n        diff(i, len2, is_row, res2);\n        if (res2[0] > md) {\n            md = res2[0];  \n            pm = i;        \n            mc = res2[1];  \n            pc = res2[2];  \n        }\n    }\n\n    if (is_row) {\n        res[0] = pm; res[1] = pc;\n    }\n    else {\n        res[0] = pc; res[1] = pm;\n    }\n    res[2] = mc; res[3] = md;\n}\n\nvoid next_cell(int res[4]) {\n    int i, res1[4], res2[4];\n    max_penalty(N_ROWS, N_COLS, TRUE, res1);\n    max_penalty(N_COLS, N_ROWS, FALSE, res2);\n\n    if (res1[3] == res2[3]) {\n        if (res1[2] < res2[2])\n            for (i = 0; i < 4; ++i) res[i] = res1[i];\n        else\n            for (i = 0; i < 4; ++i) res[i] = res2[i];\n        return;\n    }\n    if (res1[3] > res2[3])\n        for (i = 0; i < 4; ++i) res[i] = res2[i];\n    else\n        for (i = 0; i < 4; ++i) res[i] = res1[i];\n}\n\nint main() {\n    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];\n    int results[N_ROWS][N_COLS] = { 0 };\n\n    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];\n    while (supply_left > 0) {\n        next_cell(cell);\n        r = cell[0];\n        c = cell[1];\n        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];\n        demand[c] -= q;\n        if (!demand[c]) col_done[c] = TRUE;\n        supply[r] -= q;\n        if (!supply[r]) row_done[r] = TRUE;\n        results[r][c] = q;\n        supply_left -= q;\n        total_cost += q * costs[r][c];\n    }\n\n    printf(\"    A   B   C   D   E\\n\");\n    for (i = 0; i < N_ROWS; ++i) {\n        printf(\"%c\", 'W' + i);\n        for (j = 0; j < N_COLS; ++j) printf(\"  %2d\", results[i][j]);\n        printf(\"\\n\");\n    }\n    printf(\"\\nTotal cost = %d\\n\", total_cost);\n    return 0;\n}\n"}
{"id": 60791, "name": "Air mass", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst (\n    RE  = 6371000 \n    DD  = 0.001   \n    FIN = 1e7     \n)\n\n\nfunc rho(a float64) float64 { return math.Exp(-a / 8500) }\n\n\nfunc radians(degrees float64) float64 { return degrees * math.Pi / 180 }\n\n\n\n\nfunc height(a, z, d float64) float64 {\n    aa := RE + a\n    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))\n    return hh - RE\n}\n\n\nfunc columnDensity(a, z float64) float64 {\n    sum := 0.0\n    d := 0.0\n    for d < FIN {\n        delta := math.Max(DD, DD*d) \n        sum += rho(height(a, z, d+0.5*delta)) * delta\n        d += delta\n    }\n    return sum\n}\n\nfunc airmass(a, z float64) float64 {\n    return columnDensity(a, z) / columnDensity(a, 0)\n}\n\nfunc main() {\n    fmt.Println(\"Angle     0 m              13700 m\")\n    fmt.Println(\"------------------------------------\")\n    for z := 0; z <= 90; z += 5 {\n        fz := float64(z)\n        fmt.Printf(\"%2d      %11.8f      %11.8f\\n\", z, airmass(0, fz), airmass(13700, fz))\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\n#define DEG 0.017453292519943295769236907684886127134  \n#define RE 6371000.0 \n#define DD 0.001 \n#define FIN 10000000.0 \n\nstatic double rho(double a) {\n    \n    return exp(-a / 8500.0);\n}\n\nstatic double height(double a, double z, double d) {\n    \n    \n    \n    double aa = RE + a;\n    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));\n    return hh - RE;\n}\n\nstatic double column_density(double a, double z) {\n    \n    double sum = 0.0, d = 0.0;\n    while (d < FIN) {\n        \n        double delta = DD * d;\n        if (delta < DD)\n            delta = DD;\n        sum += rho(height(a, z, d + 0.5 * delta)) * delta;\n        d += delta;\n    }\n    return sum;\n}\n\nstatic double airmass(double a, double z) {\n    return column_density(a, z) / column_density(a, 0.0);\n}\n\nint main() {\n    puts(\"Angle     0 m              13700 m\");\n    puts(\"------------------------------------\");\n    for (double z = 0; z <= 90; z+= 5) {\n        printf(\"%2.0f      %11.8f      %11.8f\\n\",\n               z, airmass(0.0, z), airmass(13700.0, z));\n    }\n}\n"}
{"id": 60792, "name": "Formal power series", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype fps interface {\n    extract(int) float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc one() fps {\n    return &oneFps{}\n}\n\nfunc add(s1, s2 fps) fps {\n    return &sum{s1: s1, s2: s2}\n}\n\nfunc sub(s1, s2 fps) fps {\n    return &diff{s1: s1, s2: s2}\n}\n\nfunc mul(s1, s2 fps) fps {\n    return &prod{s1: s1, s2: s2}\n}\n\nfunc div(s1, s2 fps) fps {\n    return &quo{s1: s1, s2: s2}\n}\n\nfunc differentiate(s1 fps) fps {\n    return &deriv{s1: s1}\n}\n\nfunc integrate(s1 fps) fps {\n    return &integ{s1: s1}\n}\n\n\n\n\n\n\n\nfunc sinCos() (fps, fps) {\n    sin := &integ{}\n    cos := sub(one(), integrate(sin))\n    sin.s1 = cos\n    return sin, cos\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype oneFps struct{}\n\n\n\nfunc (*oneFps) extract(n int) float64 {\n    if n == 0 {\n        return 1\n    }\n    return 0\n}\n\n\n\ntype sum struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *sum) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\n\n\n\n\ntype diff struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *diff) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))\n    }\n    return s.s[n]\n}\n\ntype prod struct {\n    s      []float64\n    s1, s2 fps\n}\n\nfunc (s *prod) extract(n int) float64 {\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 0; k <= i; k++ {\n            c += s.s1.extract(k) * s.s1.extract(n-k)\n        }\n        s.s = append(s.s, c)\n    }\n    return s.s[n]\n}\n\n\n\ntype quo struct {\n    s1, s2 fps\n    inv    float64   \n    c      []float64 \n    s      []float64\n}\n\n\n\n\nfunc (s *quo) extract(n int) float64 {\n    switch {\n    case len(s.s) > 0:\n    case !math.IsInf(s.inv, 1):\n        a0 := s.s2.extract(0)\n        s.inv = 1 / a0\n        if a0 != 0 {\n            break\n        }\n        fallthrough\n    default:\n        return math.NaN()\n    }\n    for i := len(s.s); i <= n; i++ {\n        c := 0.\n        for k := 1; k <= i; k++ {\n            c += s.s2.extract(k) * s.c[n-k]\n        }\n        c = s.s1.extract(i) - c*s.inv\n        s.c = append(s.c, c)\n        s.s = append(s.s, c*s.inv)\n    }\n    return s.s[n]\n}\n\n\n\n\ntype deriv struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *deriv) extract(n int) float64 {\n    for i := len(s.s); i <= n; {\n        i++\n        s.s = append(s.s, float64(i)*s.s1.extract(i))\n    }\n    return s.s[n]\n}\n\ntype integ struct {\n    s   []float64\n    s1  fps\n}\n\nfunc (s *integ) extract(n int) float64 {\n    if n == 0 {\n        return 0 \n    }\n    \n    for i := len(s.s) + 1; i <= n; i++ {\n        s.s = append(s.s, s.s1.extract(i-1)/float64(i))\n    }\n    return s.s[n-1]\n}\n\n\nfunc main() {\n    \n    partialSeries := func(f fps) (s string) {\n        for i := 0; i < 6; i++ {\n            s = fmt.Sprintf(\"%s %8.5f \", s, f.extract(i))\n        }\n        return\n    }\n    sin, cos := sinCos()\n    fmt.Println(\"sin:\", partialSeries(sin))\n    fmt.Println(\"cos:\", partialSeries(cos))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h> \n\nenum fps_type {\n        FPS_CONST = 0,\n        FPS_ADD,\n        FPS_SUB,\n        FPS_MUL,\n        FPS_DIV,\n        FPS_DERIV,\n        FPS_INT,\n};\n\ntypedef struct fps_t *fps;\ntypedef struct fps_t {\n        int type;\n        fps s1, s2;\n        double a0;\n} fps_t;\n\nfps fps_new()\n{\n        fps x = malloc(sizeof(fps_t));\n        x->a0 = 0;\n        x->s1 = x->s2 = 0;\n        x->type = 0;\n        return x;\n}\n\n\nvoid fps_redefine(fps x, int op, fps y, fps z)\n{\n        x->type = op;\n        x->s1 = y;\n        x->s2 = z;\n}\n\nfps _binary(fps x, fps y, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->s2 = y;\n        s->type = op;\n        return s;\n}\n\nfps _unary(fps x, int op)\n{\n        fps s = fps_new();\n        s->s1 = x;\n        s->type = op;\n        return s;\n}\n\n\ndouble term(fps x, int n)\n{\n        double ret = 0;\n        int i;\n\n        switch (x->type) {\n        case FPS_CONST: return n > 0 ? 0 : x->a0;\n        case FPS_ADD:\n                ret = term(x->s1, n) + term(x->s2, n); break;\n\n        case FPS_SUB:\n                ret = term(x->s1, n) - term(x->s2, n); break;\n\n        case FPS_MUL:\n                for (i = 0; i <= n; i++)\n                        ret += term(x->s1, i) * term(x->s2, n - i);\n                break;\n\n        case FPS_DIV:\n                if (! term(x->s2, 0)) return NAN;\n\n                ret = term(x->s1, n);\n                for (i = 1; i <= n; i++)\n                        ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0);\n                break;\n\n        case FPS_DERIV:\n                ret = n * term(x->s1, n + 1);\n                break;\n\n        case FPS_INT:\n                if (!n) return x->a0;\n                ret = term(x->s1, n - 1) / n;\n                break;\n\n        default:\n                fprintf(stderr, \"Unknown operator %d\\n\", x->type);\n                exit(1);\n        }\n\n        return ret;\n}\n\n#define _add(x, y) _binary(x, y, FPS_ADD)\n#define _sub(x, y) _binary(x, y, FPS_SUB)\n#define _mul(x, y) _binary(x, y, FPS_MUL)\n#define _div(x, y) _binary(x, y, FPS_DIV)\n#define _integ(x)  _unary(x, FPS_INT)\n#define _deriv(x)  _unary(x, FPS_DERIV)\n\nfps fps_const(double a0)\n{\n        fps x = fps_new();\n        x->type = FPS_CONST;\n        x->a0 = a0;\n        return x;\n}\n\nint main()\n{\n        int i;\n        fps one = fps_const(1);\n        fps fcos = fps_new();           \n        fps fsin = _integ(fcos);        \n        fps ftan = _div(fsin, fcos);    \n\n        \n        fps_redefine(fcos, FPS_SUB, one, _integ(fsin));\n\n        fps fexp = fps_const(1);        \n        \n        fps_redefine(fexp, FPS_INT, fexp, 0);\n\n        printf(\"Sin:\");   for (i = 0; i < 10; i++) printf(\" %g\", term(fsin, i));\n        printf(\"\\nCos:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fcos, i));\n        printf(\"\\nTan:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(ftan, i));\n        printf(\"\\nExp:\"); for (i = 0; i < 10; i++) printf(\" %g\", term(fexp, i));\n\n        return 0;\n}\n"}
{"id": 60793, "name": "Own digits power sum", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n    fmt.Println(\"Own digits power sums for N = 3 to 9 inclusive:\")\n    for n := 3; n < 10; n++ {\n        for d := 2; d < 10; d++ {\n            powers[d] *= d\n        }\n        i := int(math.Pow(10, float64(n-1)))\n        max := i * 10\n        lastDigit := 0\n        sum := 0\n        var digits []int\n        for i < max {\n            if lastDigit == 0 {\n                digits = rcu.Digits(i, 10)\n                sum = 0\n                for _, d := range digits {\n                    sum += powers[d]\n                }\n            } else if lastDigit == 1 {\n                sum++\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1]\n            }\n            if sum == i {\n                fmt.Println(i)\n                if lastDigit == 0 {\n                    fmt.Println(i + 1)\n                }\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if sum > i {\n                i += 10 - lastDigit\n                lastDigit = 0\n            } else if lastDigit < 9 {\n                i++\n                lastDigit++\n            } else {\n                i++\n                lastDigit = 0\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define MAX_DIGITS 9\n\nint digits[MAX_DIGITS];\n\nvoid getDigits(int i) {\n    int ix = 0;\n    while (i > 0) {\n        digits[ix++] = i % 10;\n        i /= 10;\n    }\n}\n\nint main() {\n    int n, d, i, max, lastDigit, sum, dp;\n    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};\n    printf(\"Own digits power sums for N = 3 to 9 inclusive:\\n\");\n    for (n = 3; n < 10; ++n) {\n        for (d = 2; d < 10; ++d) powers[d] *= d;\n        i = (int)pow(10, n-1);\n        max = i * 10;\n        lastDigit = 0;\n        while (i < max) {\n            if (!lastDigit) {\n                getDigits(i);\n                sum = 0;\n                for (d = 0; d < n; ++d) {\n                    dp = digits[d];\n                    sum += powers[dp];\n                }\n            } else if (lastDigit == 1) {\n                sum++;\n            } else {\n                sum += powers[lastDigit] - powers[lastDigit-1];\n            }\n            if (sum == i) {\n                printf(\"%d\\n\", i);\n                if (lastDigit == 0) printf(\"%d\\n\", i + 1);\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (sum > i) {\n                i += 10 - lastDigit;\n                lastDigit = 0;\n            } else if (lastDigit < 9) {\n                i++;\n                lastDigit++;\n            } else {\n                i++;\n                lastDigit = 0;\n            }\n        }\n    }\n    return 0;\n}\n"}
{"id": 60794, "name": "Bitmap_Bézier curves_Cubic", "Go": "package raster\n\nconst b3Seg = 30\n\nfunc (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {\n    var px, py [b3Seg + 1]int\n    fx1, fy1 := float64(x1), float64(y1)\n    fx2, fy2 := float64(x2), float64(y2)\n    fx3, fy3 := float64(x3), float64(y3)\n    fx4, fy4 := float64(x4), float64(y4)\n    for i := range px {\n        d := float64(i) / b3Seg\n        a := 1 - d\n        b, c := a * a, d * d\n        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d\n        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)\n        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)\n    }\n    x0, y0 := px[0], py[0]\n    for i := 1; i <= b3Seg; i++ {\n        x1, y1 := px[i], py[i]\n        b.Line(x0, y0, x1, y1, p)\n        x0, y0 = x1, y1\n    }\n}\n\nfunc (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {\n    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())\n}\n", "C": "void cubic_bezier(\n       \timage img,\n        unsigned int x1, unsigned int y1,\n        unsigned int x2, unsigned int y2,\n        unsigned int x3, unsigned int y3,\n        unsigned int x4, unsigned int y4,\n        color_component r,\n        color_component g,\n        color_component b );\n"}
{"id": 60795, "name": "Sorting algorithms_Pancake sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    list.sort()\n    fmt.Println(\"sorted!  \", list)\n}\n\ntype pancake []int\n\nfunc (a pancake) sort() {\n    for uns := len(a) - 1; uns > 0; uns-- {\n        \n        lx, lg := 0, a[0]\n        for i := 1; i <= uns; i++ {\n            if a[i] > lg {\n                lx, lg = i, a[i]\n            }\n        }\n        \n        a.flip(lx)\n        a.flip(uns)\n    }\n}\n\nfunc (a pancake) flip(r int) {\n    for l := 0; l < r; l, r = l+1, r-1 {\n        a[l], a[r] = a[r], a[l]\n    }\n}\n", "C": "int pancake_sort(int *list, unsigned int length)\n{\n    \n    if(length<2)\n        return 0;\n\n    int i,a,max_num_pos,moves;\n    moves=0;\n\n    for(i=length;i>1;i--)\n    {\n        \n        max_num_pos=0;\n        for(a=0;a<i;a++)\n        {\n            if(list[a]>list[max_num_pos])\n                max_num_pos=a;\n        }\n\n        if(max_num_pos==i-1)\n            \n            continue;\n\n\n        \n        if(max_num_pos)\n        {\n            moves++;\n            do_flip(list, length, max_num_pos+1);\n        }\n\n\n        \n        moves++;\n        do_flip(list, length, i);\n\n        \n\n    }\n\n    return moves;\n}\n"}
{"id": 60796, "name": "Largest five adjacent number", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"rcu\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var sb strings.Builder\n    for i := 0; i < 1000; i++ {\n        sb.WriteByte(byte(rand.Intn(10) + 48))\n    }\n    number := sb.String()\n    for i := 99999; i >= 0; i-- {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The largest  number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            break\n        }\n    }\n    for i := 0; i <= 99999; i++ {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The smallest number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            return\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\n#define DIGITS 1000\n#define NUMSIZE 5\n\nuint8_t randomDigit() {\n    uint8_t d;\n    do {d = rand() & 0xF;} while (d >= 10);\n    return d;\n}\n\nint numberAt(uint8_t *d, int size) {\n    int acc = 0;\n    while (size--) acc = 10*acc + *d++;\n    return acc;\n}\n\nint main() {\n    uint8_t digits[DIGITS];\n    int i, largest = 0;\n    \n    srand(time(NULL));\n    \n    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();\n    for (i=0; i<DIGITS-NUMSIZE; i++) {\n        int here = numberAt(&digits[i], NUMSIZE);\n        if (here > largest) largest = here;\n    }\n\n    printf(\"%d\\n\", largest);\n    return 0;\n}\n"}
{"id": 60797, "name": "Largest five adjacent number", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"rcu\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var sb strings.Builder\n    for i := 0; i < 1000; i++ {\n        sb.WriteByte(byte(rand.Intn(10) + 48))\n    }\n    number := sb.String()\n    for i := 99999; i >= 0; i-- {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The largest  number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            break\n        }\n    }\n    for i := 0; i <= 99999; i++ {\n        quintet := fmt.Sprintf(\"%05d\", i)\n        if strings.Contains(number, quintet) {\n            ci := rcu.Commatize(i)\n            fmt.Printf(\"The smallest number formed from 5 adjacent digits (%s) is: %6s\\n\", quintet, ci)\n            return\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\n#define DIGITS 1000\n#define NUMSIZE 5\n\nuint8_t randomDigit() {\n    uint8_t d;\n    do {d = rand() & 0xF;} while (d >= 10);\n    return d;\n}\n\nint numberAt(uint8_t *d, int size) {\n    int acc = 0;\n    while (size--) acc = 10*acc + *d++;\n    return acc;\n}\n\nint main() {\n    uint8_t digits[DIGITS];\n    int i, largest = 0;\n    \n    srand(time(NULL));\n    \n    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();\n    for (i=0; i<DIGITS-NUMSIZE; i++) {\n        int here = numberAt(&digits[i], NUMSIZE);\n        if (here > largest) largest = here;\n    }\n\n    printf(\"%d\\n\", largest);\n    return 0;\n}\n"}
{"id": 60798, "name": "Sum of square and cube digits of an integer are primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    for i := 1; i < 100; i++ {\n        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {\n            continue\n        }\n        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {\n            fmt.Printf(\"%d \", i)\n        }\n    }\n    fmt.Println()\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint digit_sum(int n) {\n    int sum;\n    for (sum = 0; n; n /= 10) sum += n % 10;\n    return sum;\n}\n\n\nbool prime(int n) {\n    if (n<4) return n>=2;\n    for (int d=2; d*d <= n; d++)\n        if (n%d == 0) return false;\n    return true;\n}\n\nint main() {\n    for (int i=1; i<100; i++)\n        if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i)))\n            printf(\"%d \", i);\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60799, "name": "The sieve of Sundaram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n    \"time\"\n)\n\nfunc sos(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        p := 2*i + 3\n        s := (p*p - 3) / 2\n        for j := s; j < k; j += p {\n            marked[j] = true\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\n\nfunc soe(n int) []int {\n    if n < 3 {\n        return []int{}\n    }\n    var primes []int\n    k := (n-3)/2 + 1\n    marked := make([]bool, k) \n    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1\n    for i := 0; i < limit; i++ {\n        if !marked[i] {\n            p := 2*i + 3\n            s := (p*p - 3) / 2\n            for j := s; j < k; j += p {\n                marked[j] = true\n            }\n        }\n    }\n    for i := 0; i < k; i++ {\n        if !marked[i] {\n            primes = append(primes, 2*i+3)\n        }\n    }\n    return primes\n}\n\nfunc main() {\n    const limit = int(16e6) \n    start := time.Now()\n    primes := sos(limit)\n    elapsed := int(time.Since(start).Milliseconds())\n    climit := rcu.Commatize(limit)\n    celapsed := rcu.Commatize(elapsed)\n    million := rcu.Commatize(1e6)\n    millionth := rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"Using the Sieve of Sundaram generated primes up to %s in %s ms.\\n\\n\", climit, celapsed)\n    fmt.Println(\"First 100 odd primes generated by the Sieve of Sundaram:\")\n    for i, p := range primes[0:100] {\n        fmt.Printf(\"%3d \", p)\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Printf(\"\\nThe %s Sundaram prime is %s\\n\", million, millionth)\n\n    start = time.Now()\n    primes = soe(limit)\n    elapsed = int(time.Since(start).Milliseconds())\n    celapsed = rcu.Commatize(elapsed)\n    millionth = rcu.Commatize(primes[1e6-1])\n    fmt.Printf(\"\\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\\n\", celapsed)\n    fmt.Printf(\"\\nAs a check, the %s Sundaram prime would again have been %s\\n\", million, millionth)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\nint main(void) {\n    int nprimes =  1000000;\n    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  \n      \n      \n    int i, j, m, k; int *a;\n    k = (nmax-2)/2; \n    a = (int *)calloc(k + 1, sizeof(int));\n    for(i = 0; i <= k; i++)a[i] = 2*i+1; \n    for (i = 1; (i+1)*i*2 <= k; i++)\n        for (j = i; j <= (k-i)/(2*i+1); j++) {\n            m = i + j + 2*i*j;\n            if(a[m]) a[m] = 0;\n            }            \n        \n    for (i = 1, j = 0; i <= k; i++) \n       if (a[i]) {\n           if(j%10 == 0 && j <= 100)printf(\"\\n\");\n           j++; \n           if(j <= 100)printf(\"%3d \", a[i]);\n           else if(j == nprimes){\n               printf(\"\\n%d th prime is %d\\n\",j,a[i]);\n               break;\n               }\n           }\n}\n"}
{"id": 60800, "name": "Active Directory_Connect", "Go": "package main\n\nimport (\n    \"log\"\n    \"github.com/jtblin/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect : %+v\", err)\n    }\n    \n}\n", "C": "#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n"}
{"id": 60801, "name": "Exactly three adjacent 3 in lists", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    lists := [][]int{\n        {9, 3, 3, 3, 2, 1, 7, 8, 5},\n        {5, 2, 9, 3, 3, 7, 8, 4, 1},\n        {1, 4, 3, 6, 7, 3, 8, 3, 2},\n        {1, 2, 3, 4, 5, 6, 7, 8, 9},\n        {4, 6, 8, 7, 2, 3, 3, 3, 1},\n        {3, 3, 3, 1, 2, 4, 5, 1, 3},\n        {0, 3, 3, 3, 3, 7, 2, 2, 6},\n        {3, 3, 3, 3, 3, 4, 4, 4, 4},\n    }\n    for d := 1; d <= 4; d++ {\n        fmt.Printf(\"Exactly %d adjacent %d's:\\n\", d, d)\n        for _, list := range lists {\n            var indices []int\n            for i, e := range list {\n                if e == d {\n                    indices = append(indices, i)\n                }\n            }\n            adjacent := false\n            if len(indices) == d {\n                adjacent = true\n                for i := 1; i < len(indices); i++ {\n                    if indices[i]-indices[i-1] != 1 {\n                        adjacent = false\n                        break\n                    }\n                }\n            }\n            fmt.Printf(\"%v -> %t\\n\", list, adjacent)\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nbool three_3s(const int *items, size_t len) {\n    int threes = 0;    \n    while (len--) \n        if (*items++ == 3)\n            if (threes<3) threes++;\n            else return false;\n        else if (threes != 0 && threes != 3) \n            return false;\n    return true;\n}\n\nvoid print_list(const int *items, size_t len) {\n    while (len--) printf(\"%d \", *items++);\n}\n\nint main() {\n    int lists[][9] = {\n        {9,3,3,3,2,1,7,8,5},\n        {5,2,9,3,3,6,8,4,1},\n        {1,4,3,6,7,3,8,3,2},\n        {1,2,3,4,5,6,7,8,9},\n        {4,6,8,7,2,3,3,3,1}\n    };\n    \n    size_t list_length = sizeof(lists[0]) / sizeof(int);\n    size_t n_lists = sizeof(lists) / sizeof(lists[0]);\n    \n    for (size_t i=0; i<n_lists; i++) {\n        print_list(lists[i], list_length);\n        printf(\"-> %s\\n\", three_3s(lists[i], list_length) ? \"true\" : \"false\");\n    }\n    \n    return 0;\n}\n"}
{"id": 60802, "name": "Permutations by swapping", "Go": "package permute\n\n\n\n\nfunc Iter(p []int) func() int {\n    f := pf(len(p))\n    return func() int {\n        return f(p)\n    }\n}\n\n\n\nfunc pf(n int) func([]int) int {\n    sign := 1\n    switch n {\n    case 0, 1:\n        return func([]int) (s int) {\n            s = sign\n            sign = 0\n            return\n        }\n    default:\n        p0 := pf(n - 1)\n        i := n\n        var d int\n        return func(p []int) int {\n            switch {\n            case sign == 0:\n            case i == n:\n                i--\n                sign = p0(p[:i])\n                d = -1\n            case i == 0:\n                i++\n                sign *= p0(p[1:])\n                d = 1\n                if sign == 0 {\n                    p[0], p[1] = p[1], p[0]\n                }\n            default:\n                p[i], p[i-1] = p[i-1], p[i]\n                sign = -sign\n                i += d\n            }\n            return sign\n        }\n    }\n}\n", "C": "#include<stdlib.h>\n#include<string.h>\n#include<stdio.h>\n\nint flag = 1;\n\nvoid heapPermute(int n, int arr[],int arrLen){\n\tint temp;\n\tint i;\n\t\n\tif(n==1){\n\t\tprintf(\"\\n[\");\n\t\t\n\t\tfor(i=0;i<arrLen;i++)\n\t\t\tprintf(\"%d,\",arr[i]);\n\t\tprintf(\"\\b] Sign : %d\",flag);\n\t\t\n\t\tflag*=-1;\n\t}\n\telse{\n\t\tfor(i=0;i<n-1;i++){\n\t\t\theapPermute(n-1,arr,arrLen);\n\t\t\t\n\t\t\tif(n%2==0){\n\t\t\t\ttemp = arr[i];\n\t\t\t\tarr[i] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttemp = arr[0];\n\t\t\t\tarr[0] = arr[n-1];\n\t\t\t\tarr[n-1] = temp;\n\t\t\t}\n\t\t}\n\t\theapPermute(n-1,arr,arrLen);\n\t}\n}\n\nint main(int argC,char* argV[0])\n{\n\tint *arr, i=0, count = 1;\n\tchar* token;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <comma separated list of integers>\",argV[0]);\n\telse{\n\t\twhile(argV[1][i]!=00){\n\t\t\tif(argV[1][i++]==',')\n\t\t\t\tcount++;\n\t\t}\n\t\t\n\t\tarr = (int*)malloc(count*sizeof(int));\n\t\t\n\t\ti = 0;\n\t\t\n\t\ttoken = strtok(argV[1],\",\");\n\t\t\n\t\twhile(token!=NULL){\n\t\t\tarr[i++] = atoi(token);\n\t\t\ttoken = strtok(NULL,\",\");\n\t\t}\n\t\t\n\t\theapPermute(i,arr,count);\n\t}\n\t\t\n\treturn 0;\n}\n"}
{"id": 60803, "name": "Minimum multiple of m where digital sum equals m", "Go": "package main\n\nimport \"rcu\"\n\nfunc main() {\n    var res []int\n    for n := 1; n <= 70; n++ {\n        m := 1\n        for rcu.DigitSum(m*n, 10) != n {\n            m++\n        }\n        res = append(res, m)\n    }\n    rcu.PrintTable(res, 7, 10, true)\n}\n", "C": "#include <stdio.h>\n\nunsigned digit_sum(unsigned n) {\n    unsigned sum = 0;\n    do { sum += n % 10; }\n    while(n /= 10);\n    return sum;\n}\n\nunsigned a131382(unsigned n) {\n    unsigned m;\n    for (m = 1; n != digit_sum(m*n); m++);\n    return m;\n}\n\nint main() {\n    unsigned n;\n    for (n = 1; n <= 70; n++) {\n        printf(\"%9u\", a131382(n));\n        if (n % 10 == 0) printf(\"\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60804, "name": "Pythagorean quadruples", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n    N = 2200\n    N2 = N * N * 2\n)\n\nfunc main() {\n    s  := 3 \n    var s1, s2 int    \n    var r  [N + 1]bool\n    var ab [N2 + 1]bool\n\n    for a := 1; a <= N; a++ {\n        a2 := a * a\n        for b := a; b <= N; b++ {\n            ab[a2 + b * b] = true\n        }\n    }\n\n    for c := 1; c <= N; c++ {\n        s1 = s\n        s += 2\n        s2 = s\n        for d := c + 1; d <= N; d++ {\n            if ab[s1] {\n                r[d] = true\n            }\n            s1 += s2\n            s2 += 2\n        }\n    }\n\n    for d := 1; d <= N; d++ {\n        if !r[d] {\n            fmt.Printf(\"%d \", d)\n        }       \n    }\n    fmt.Println()\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n#define N 2200\n\nint main(int argc, char **argv){\n   int a,b,c,d;\n   int r[N+1];\n   memset(r,0,sizeof(r));\t\n   for(a=1; a<=N; a++){\n      for(b=a; b<=N; b++){\n\t int aabb;\n\t if(a&1 && b&1) continue;  \n\t aabb=a*a + b*b;\n\t for(c=b; c<=N; c++){\n\t    int aabbcc=aabb + c*c;\n\t    d=(int)sqrt((float)aabbcc);\n\t    if(aabbcc == d*d && d<=N) r[d]=1;\t\n\t }\n      }\n   }\n   for(a=1; a<=N; a++)\n      if(!r[a]) printf(\"%d \",a);\t\n   printf(\"\\n\");\n}\n"}
{"id": 60805, "name": "Verhoeff algorithm", "Go": "package main\n\nimport \"fmt\"\n\nvar d = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},\n    {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},\n    {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},\n    {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},\n    {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n}\n\nvar inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}\n\nvar p = [][]int{\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n    {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},\n    {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},\n    {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},\n    {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n}\n\nfunc verhoeff(s string, validate, table bool) interface{} {\n    if table {\n        t := \"Check digit\"\n        if validate {\n            t = \"Validation\"\n        }\n        fmt.Printf(\"%s calculations for '%s':\\n\\n\", t, s)\n        fmt.Println(\" i  nᵢ  p[i,nᵢ]  c\")\n        fmt.Println(\"------------------\")\n    }\n    if !validate {\n        s = s + \"0\"\n    }\n    c := 0\n    le := len(s) - 1\n    for i := le; i >= 0; i-- {\n        ni := int(s[i] - 48)\n        pi := p[(le-i)%8][ni]\n        c = d[c][pi]\n        if table {\n            fmt.Printf(\"%2d  %d      %d     %d\\n\", le-i, ni, pi, c)\n        }\n    }\n    if table && !validate {\n        fmt.Printf(\"\\ninv[%d] = %d\\n\", c, inv[c])\n    }\n    if !validate {\n        return inv[c]\n    }\n    return c == 0\n}\n\nfunc main() {\n    ss := []string{\"236\", \"12345\", \"123456789012\"}\n    ts := []bool{true, true, false, true}\n    for i, s := range ss {\n        c := verhoeff(s, false, ts[i]).(int)\n        fmt.Printf(\"\\nThe check digit for '%s' is '%d'\\n\\n\", s, c)\n        for _, sc := range []string{s + string(c+48), s + \"9\"} {\n            v := verhoeff(sc, true, ts[i]).(bool)\n            ans := \"correct\"\n            if !v {\n                ans = \"incorrect\"\n            }\n            fmt.Printf(\"\\nThe validation for '%s' is %s\\n\\n\", sc, ans)\n        }\n    }\n}\n", "C": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic const int d[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n    {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n    {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n    {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n    {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n};\n\nstatic const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};\n\nstatic const int p[][10] = {\n    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n    {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n    {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n    {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n};\n\nint verhoeff(const char* s, bool validate, bool verbose) {\n    if (verbose) {\n        const char* t = validate ? \"Validation\" : \"Check digit\";\n        printf(\"%s calculations for '%s':\\n\\n\", t, s);\n        puts(u8\" i  n\\xE1\\xB5\\xA2  p[i,n\\xE1\\xB5\\xA2]  c\");\n        puts(\"------------------\");\n    }\n    int len = strlen(s);\n    if (validate)\n        --len;\n    int c = 0;\n    for (int i = len; i >= 0; --i) {\n        int ni = (i == len && !validate) ? 0 : s[i] - '0';\n        assert(ni >= 0 && ni < 10);\n        int pi = p[(len - i) % 8][ni];\n        c = d[c][pi];\n        if (verbose)\n            printf(\"%2d  %d      %d     %d\\n\", len - i, ni, pi, c);\n    }\n    if (verbose && !validate)\n        printf(\"\\ninv[%d] = %d\\n\", c, inv[c]);\n    return validate ? c == 0 : inv[c];\n}\n\nint main() {\n    const char* ss[3] = {\"236\", \"12345\", \"123456789012\"};\n    for (int i = 0; i < 3; ++i) {\n        const char* s = ss[i];\n        bool verbose = i < 2;\n        int c = verhoeff(s, false, verbose);\n        printf(\"\\nThe check digit for '%s' is '%d'.\\n\", s, c);\n        int len = strlen(s);\n        char sc[len + 2];\n        strncpy(sc, s, len + 2);\n        for (int j = 0; j < 2; ++j) {\n            sc[len] = (j == 0) ? c + '0' : '9';\n            int v = verhoeff(sc, true, verbose);\n            printf(\"\\nThe validation for '%s' is %s.\\n\", sc,\n                   v ? \"correct\" : \"incorrect\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 60806, "name": "Steady squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc contains(list []int, s int) bool {\n    for _, e := range list {\n        if e == s {\n            return true\n        }\n    }\n    return false\n}\n\nfunc main() {\n    fmt.Println(\"Steady squares under 10,000:\")\n    finalDigits := []int{1, 5, 6}\n    for i := 1; i < 10000; i++ {\n        if !contains(finalDigits, i%10) {\n            continue\n        }\n        sq := i * i\n        sqs := strconv.Itoa(sq)\n        is := strconv.Itoa(i)\n        if strings.HasSuffix(sqs, is) {\n            fmt.Printf(\"%5s -> %10s\\n\", rcu.Commatize(i), rcu.Commatize(sq))\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n \nbool steady(int n)\n{\n    int mask = 1;\n    for (int d = n; d != 0; d /= 10) \n        mask *= 10;\n    return (n * n) % mask == n;\n}\n \nint main()\n{\n    for (int i = 1; i < 10000; i++)\n        if (steady(i))\n            printf(\"%4d^2 = %8d\\n\", i, i * i);\n    return 0;\n}\n"}
{"id": 60807, "name": "Numbers in base 10 that are palindromic in bases 2, 4, and 16", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n    \"strconv\"\n)\n\nfunc reverse(s string) string {\n    chars := []rune(s)\n    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n        chars[i], chars[j] = chars[j], chars[i]\n    }\n    return string(chars)\n}\n\nfunc main() {\n    fmt.Println(\"Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:\")\n    var numbers []int\n    for i := int64(0); i < 25000; i++ {\n        b2 := strconv.FormatInt(i, 2)\n        if b2 == reverse(b2) {\n            b4 := strconv.FormatInt(i, 4)\n            if b4 == reverse(b4) {\n                b16 := strconv.FormatInt(i, 16)\n                if b16 == reverse(b16) {\n                    numbers = append(numbers, int(i))\n                }\n            }\n        }\n    }\n    for i, n := range numbers {\n        fmt.Printf(\"%6s \", rcu.Commatize(n))\n        if (i+1)%10 == 0 {\n            fmt.Println()\n        }\n    }\n    fmt.Println(\"\\n\\nFound\", len(numbers), \"such numbers.\")\n}\n", "C": "#include <stdio.h>\n#define MAXIMUM 25000\n\nint reverse(int n, int base) {\n    int r;\n    for (r = 0; n; n /= base)\n        r = r*base + n%base;\n    return r;\n}\n\nint palindrome(int n, int base) {\n    return n == reverse(n, base);\n}\n\nint main() {\n    int i, c = 0;\n    \n    for (i = 0; i < MAXIMUM; i++) {\n        if (palindrome(i, 2) &&\n            palindrome(i, 4) &&\n            palindrome(i, 16)) {\n            printf(\"%5d%c\", i, ++c % 12 ? ' ' : '\\n');\n        }\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"}
{"id": 60808, "name": "Long stairs", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    totalSecs := 0\n    totalSteps := 0\n    fmt.Println(\"Seconds    steps behind    steps ahead\")\n    fmt.Println(\"-------    ------------    -----------\")\n    for trial := 1; trial < 10000; trial++ {\n        sbeh := 0\n        slen := 100\n        secs := 0\n        for sbeh < slen {\n            sbeh++\n            for wiz := 1; wiz < 6; wiz++ {\n                if rand.Intn(slen) < sbeh {\n                    sbeh++\n                }\n                slen++\n            }\n            secs++\n            if trial == 1 && secs > 599 && secs < 610 {\n                fmt.Printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh)\n            }\n        }\n        totalSecs += secs\n        totalSteps += slen\n    }\n    fmt.Println(\"\\nAverage secs taken:\", float64(totalSecs)/10000)\n    fmt.Println(\"Average final length of staircase:\", float64(totalSteps)/10000)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n    int trial, secs_tot=0, steps_tot=0;     \n    int sbeh, slen, wiz, secs;              \n    time_t t;\n    srand((unsigned) time(&t));             \n    printf( \"Seconds    steps behind    steps ahead\\n\" );\n    for( trial=1;trial<=10000;trial++ ) {   \n        sbeh = 0; slen = 100; secs = 0;     \n        while(sbeh<slen) {                  \n            sbeh+=1;                        \n            for(wiz=1;wiz<=5;wiz++) {       \n                if(rand()%slen < sbeh)\n                    sbeh+=1;                \n                slen+=1;                    \n            }\n            secs+=1;                        \n            if(trial==1&&599<secs&&secs<610)\n                printf(\"%d        %d            %d\\n\", secs, sbeh, slen-sbeh );\n            \n        }\n        secs_tot+=secs;\n        steps_tot+=slen;\n    }\n    printf( \"Average secs taken: %f\\n\", secs_tot/10000.0 );\n    printf( \"Average final length of staircase: %f\\n\", steps_tot/10000.0 ); \n    return 0;\n}\n"}
{"id": 60809, "name": "Terminal control_Positional read", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i < 80*25; i++ {\n        fmt.Print(\"A\")  \n    }\n    fmt.Println()\n    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)\n    info := C.CONSOLE_SCREEN_BUFFER_INFO{}\n    pos := C.COORD{}\n    C.GetConsoleScreenBufferInfo(conOut, &info)\n    pos.X = info.srWindow.Left + 3 \n    pos.Y = info.srWindow.Top + 6  \n    var c C.wchar_t\n    var le C.ulong\n    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)\n    if ret == 0 || le <= 0 {\n        fmt.Println(\"Something went wrong!\")\n        return\n    }\n    fmt.Printf(\"The character at column 3, row 6 is '%c'\\n\", c) \n}\n", "C": "#include <windows.h>\n#include <wchar.h>\n\nint\nmain()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n\tCOORD pos;\n\tHANDLE conout;\n\tlong len;\n\twchar_t c;\n\n\t\n\tconout = CreateFileW(L\"CONOUT$\", GENERIC_READ | GENERIC_WRITE,\n\t    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t    0, NULL);\n\tif (conout == INVALID_HANDLE_VALUE)\n\t\treturn 1;\n\n\t\n\tif (GetConsoleScreenBufferInfo(conout, &info) == 0)\n\t\treturn 1;\n\n\t\n\tpos.X = info.srWindow.Left + 3;  \n\tpos.Y = info.srWindow.Top  + 6;  \n\tif (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||\n\t    len <= 0)\n\t\treturn 1;\n\n\twprintf(L\"Character at (3, 6) had been '%lc'\\n\", c);\n\treturn 0;\n}\n"}
{"id": 60810, "name": "Terminal control_Positional read", "Go": "package main\n\n\nimport \"C\"\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i < 80*25; i++ {\n        fmt.Print(\"A\")  \n    }\n    fmt.Println()\n    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)\n    info := C.CONSOLE_SCREEN_BUFFER_INFO{}\n    pos := C.COORD{}\n    C.GetConsoleScreenBufferInfo(conOut, &info)\n    pos.X = info.srWindow.Left + 3 \n    pos.Y = info.srWindow.Top + 6  \n    var c C.wchar_t\n    var le C.ulong\n    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)\n    if ret == 0 || le <= 0 {\n        fmt.Println(\"Something went wrong!\")\n        return\n    }\n    fmt.Printf(\"The character at column 3, row 6 is '%c'\\n\", c) \n}\n", "C": "#include <windows.h>\n#include <wchar.h>\n\nint\nmain()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n\tCOORD pos;\n\tHANDLE conout;\n\tlong len;\n\twchar_t c;\n\n\t\n\tconout = CreateFileW(L\"CONOUT$\", GENERIC_READ | GENERIC_WRITE,\n\t    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t    0, NULL);\n\tif (conout == INVALID_HANDLE_VALUE)\n\t\treturn 1;\n\n\t\n\tif (GetConsoleScreenBufferInfo(conout, &info) == 0)\n\t\treturn 1;\n\n\t\n\tpos.X = info.srWindow.Left + 3;  \n\tpos.Y = info.srWindow.Top  + 6;  \n\tif (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||\n\t    len <= 0)\n\t\treturn 1;\n\n\twprintf(L\"Character at (3, 6) had been '%lc'\\n\", c);\n\treturn 0;\n}\n"}
{"id": 60811, "name": "Pseudo-random numbers_Middle-square method", "Go": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n    return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n    seed := 675248\n    for i := 1; i <= 5; i++ {\n        seed = random(seed)\n        fmt.Println(seed)\n    }\n}\n", "C": "#include<stdio.h>\nlong long seed;\nlong long random(){\n        seed = seed * seed / 1000 % 1000000;\n        return seed;\n}\nint main(){\n        seed = 675248;\n        for(int i=1;i<=5;i++)\n                printf(\"%lld\\n\",random());\n        return 0;\n}\n"}
{"id": 60812, "name": "Update a configuration file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\ntype line struct {\n\tkind     lineKind\n\toption   string\n\tvalue    string\n\tdisabled bool\n}\n\n\ntype lineKind int\n\nconst (\n\t_ lineKind = iota\n\tignore\n\tparseError\n\tcomment\n\tblank\n\tvalue\n)\n\nfunc (l line) String() string {\n\tswitch l.kind {\n\tcase ignore, parseError, comment, blank:\n\t\treturn l.value\n\tcase value:\n\t\ts := l.option\n\t\tif l.disabled {\n\t\t\ts = \"; \" + s\n\t\t}\n\t\tif l.value != \"\" {\n\t\t\ts += \" \" + l.value\n\t\t}\n\t\treturn s\n\t}\n\tpanic(\"unexpected line kind\")\n}\n\nfunc removeDross(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 32 || r > 0x7f || unicode.IsControl(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parseLine(s string) line {\n\tif s == \"\" {\n\t\treturn line{kind: blank}\n\t}\n\tif s[0] == '#' {\n\t\treturn line{kind: comment, value: s}\n\t}\n\ts = removeDross(s)\n\tfields := strings.Fields(s)\n\tif len(fields) == 0 {\n\t\treturn line{kind: blank}\n\t}\n\t\n\tsemi := false\n\tfor len(fields[0]) > 0 && fields[0][0] == ';' {\n\t\tsemi = true\n\t\tfields[0] = fields[0][1:]\n\t}\n\t\n\tif fields[0] == \"\" {\n\t\tfields = fields[1:]\n\t}\n\tswitch len(fields) {\n\tcase 0:\n\t\t\n\t\t\n\t\treturn line{kind: ignore}\n\tcase 1:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tdisabled: semi,\n\t\t}\n\tcase 2:\n\t\treturn line{\n\t\t\tkind:     value,\n\t\t\toption:   strings.ToUpper(fields[0]),\n\t\t\tvalue:    fields[1],\n\t\t\tdisabled: semi,\n\t\t}\n\t}\n\treturn line{kind: parseError, value: s}\n}\n\n\ntype Config struct {\n\toptions map[string]int\t\t\n\tlines   []line\n}\n\n\n\nfunc (c *Config) index(option string) int {\n\tif i, ok := c.options[option]; ok {\n\t\treturn i\n\t}\n\treturn -1\n}\n\n\n\nfunc (c *Config) addLine(l line) {\n\tswitch l.kind {\n\tcase ignore:\n\t\treturn\n\tcase value:\n\t\tif c.index(l.option) >= 0 {\n\t\t\treturn\n\t\t}\n\t\tc.options[l.option] = len(c.lines)\n\t\tc.lines = append(c.lines, l)\n\tdefault:\n\t\tc.lines = append(c.lines, l)\n\t}\n}\n\n\nfunc ReadConfig(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tc := &Config{options: make(map[string]int)}\n\tfor {\n\t\ts, err := r.ReadString('\\n')\n\t\tif s != \"\" {\n\t\t\tif err == nil {\n\t\t\t\t\n\t\t\t\ts = s[:len(s)-1]\n\t\t\t}\n\t\t\tc.addLine(parseLine(s))\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}\n\n\n\nfunc (c *Config) Set(option string, val string) {\n\tif i := c.index(option); i >= 0 {\n\t\tline := &c.lines[i]\n\t\tline.disabled = false\n\t\tline.value = val\n\t\treturn\n\t}\n\tc.addLine(line{\n\t\tkind:   value,\n\t\toption: option,\n\t\tvalue:  val,\n\t})\n}\n\n\n\nfunc (c *Config) Enable(option string, enabled bool) {\n\tif i := c.index(option); i >= 0 {\n\t\tc.lines[i].disabled = !enabled\n\t}\n}\n\n\nfunc (c *Config) Write(w io.Writer) {\n\tfor _, line := range c.lines {\n\t\tfmt.Println(line)\n\t}\n}\n\nfunc main() {\n\tc, err := ReadConfig(\"/tmp/cfg\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tc.Enable(\"NEEDSPEELING\", false)\n\tc.Set(\"SEEDSREMOVED\", \"\")\n\tc.Set(\"NUMBEROFBANANAS\", \"1024\")\n\tc.Set(\"NUMBEROFSTRAWBERRIES\", \"62000\")\n\tc.Write(os.Stdout)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define strcomp(X, Y) strcasecmp(X, Y)\n\nstruct option\n{ const char *name, *value; \n  int flag; };\n\n\nstruct option updlist[] =\n{ { \"NEEDSPEELING\", NULL },\n  { \"SEEDSREMOVED\", \"\" },\n  { \"NUMBEROFBANANAS\", \"1024\" },\n  { \"NUMBEROFSTRAWBERRIES\", \"62000\" },\n  { NULL, NULL } };\n\nint output_opt(FILE *to, struct option *opt)\n{ if (opt->value == NULL)\n    return fprintf(to, \"; %s\\n\", opt->name);\n  else if (opt->value[0] == 0)\n    return fprintf(to, \"%s\\n\", opt->name);\n  else \n    return fprintf(to, \"%s %s\\n\", opt->name, opt->value); }\n\nint update(FILE *from, FILE *to, struct option *updlist) \n{ char line_buf[256], opt_name[128];\n  int i;\n  for (;;)\n  { size_t len, space_span, span_to_hash;\n    if (fgets(line_buf, sizeof line_buf, from) == NULL)\n      break;\n    len = strlen(line_buf);\n    space_span = strspn(line_buf, \"\\t \");\n    span_to_hash = strcspn(line_buf, \"#\");\n    if (space_span == span_to_hash)\n      goto line_out;\n    if (space_span == len)\n      goto line_out;\n    if ((sscanf(line_buf, \"; %127s\", opt_name) == 1) ||\n        (sscanf(line_buf, \"%127s\", opt_name) == 1))\n    { int flag = 0;\n      for (i = 0; updlist[i].name; i++)\n      { if (strcomp(updlist[i].name, opt_name) == 0)\n        { if (output_opt(to, &updlist[i]) < 0)\n            return -1;\n          updlist[i].flag = 1;\n          flag = 1; } }\n      if (flag == 0)\n        goto line_out; }\n    else\n  line_out: \n      if (fprintf(to, \"%s\", line_buf) < 0)\n        return -1;\n    continue; }\n  { for (i = 0; updlist[i].name; i++)\n    { if (!updlist[i].flag)\n        if (output_opt(to, &updlist[i]) < 0)\n          return -1; } }\n  return feof(from) ? 0 : -1; }\n\nint main(void)\n{ if (update(stdin, stdout, updlist) < 0)\n  { fprintf(stderr, \"failed\\n\");\n    return (EXIT_FAILURE); }\n  return 0; }\n"}
{"id": 60813, "name": "Image convolution", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/jpeg\"\n    \"math\"\n    \"os\"\n)\n\n\n\nfunc kf3(k *[9]float64, src, dst *image.Gray) {\n    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {\n        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {\n            var sum float64\n            var i int\n            for yo := y - 1; yo <= y+1; yo++ {\n                for xo := x - 1; xo <= x+1; xo++ {\n                    if (image.Point{xo, yo}).In(src.Rect) {\n                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)\n                    } else {\n                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)\n                    }\n                    i++\n                }\n            }\n            dst.SetGray(x, y,\n                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})\n        }\n    }\n}\n\nvar blur = [9]float64{\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9,\n    1. / 9, 1. / 9, 1. / 9}\n\n\n\nfunc blurY(src *image.YCbCr) *image.YCbCr {\n    dst := *src\n\n    \n    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {\n        return &dst\n    }\n\n    \n    srcGray := image.Gray{src.Y, src.YStride, src.Rect}\n    dstGray := srcGray\n    dstGray.Pix = make([]uint8, len(src.Y))\n    kf3(&blur, &srcGray, &dstGray) \n\n    \n    dst.Y = dstGray.Pix                   \n    dst.Cb = append([]uint8{}, src.Cb...) \n    dst.Cr = append([]uint8{}, src.Cr...)\n    return &dst\n}\n\nfunc main() {\n    \n    \n    f, err := os.Open(\"Lenna100.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    img, err := jpeg.Decode(f)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f.Close()\n    y, ok := img.(*image.YCbCr)\n    if !ok {\n        fmt.Println(\"expected color jpeg\")\n        return\n    }\n    f, err = os.Create(\"blur.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n", "C": "image filter(image img, double *K, int Ks, double, double);\n"}
{"id": 60814, "name": "Dice game probabilities", "Go": "package main\n\nimport(\n    \"math\"\n    \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n    if x < y {\n        return x\n    }\n    return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n    if nDice == 0 {\n        counts[s]++\n        return\n    }\n    for i := uint(1); i <= nSides; i++ {\n        throwDie(nSides, nDice - 1, s + i, counts)\n    }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n    len1 := (nSides1 + 1) * nDice1\n    c1 := make([]uint, len1)  \n    throwDie(nSides1, nDice1, 0, c1)\n\n    len2 := (nSides2 + 1) * nDice2\n    c2 := make([]uint, len2)\n    throwDie(nSides2, nDice2, 0, c2)\n    p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n           math.Pow(float64(nSides2), float64(nDice2))\n\n    tot := 0.0\n    for i := uint(0); i < len1; i++ {\n        for j := uint(0); j < minOf(i, len2); j++ {\n            tot += float64(c1[i] * c2[j]) / p12\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(beatingProbability(4, 9, 6, 6))\n    fmt.Println(beatingProbability(10, 5, 7, 6))\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\ntypedef uint64_t ulong;\n\nulong ipow(const uint x, const uint y) {\n    ulong result = 1;\n    for (uint i = 1; i <= y; i++)\n        result *= x;\n    return result;\n}\n\nuint min(const uint x, const uint y) {\n    return (x < y) ? x : y;\n}\n\nvoid throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {\n    if (n_dice == 0) {\n        counts[s]++;\n        return;\n    }\n\n    for (uint i = 1; i < n_sides + 1; i++)\n        throw_die(n_sides, n_dice - 1, s + i, counts);\n}\n\ndouble beating_probability(const uint n_sides1, const uint n_dice1,\n                           const uint n_sides2, const uint n_dice2) {\n    const uint len1 = (n_sides1 + 1) * n_dice1;\n    uint C1[len1];\n    for (uint i = 0; i < len1; i++)\n        C1[i] = 0;\n    throw_die(n_sides1, n_dice1, 0, C1);\n\n    const uint len2 = (n_sides2 + 1) * n_dice2;\n    uint C2[len2];\n    for (uint j = 0; j < len2; j++)\n        C2[j] = 0;\n    throw_die(n_sides2, n_dice2, 0, C2);\n\n    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));\n\n    double tot = 0;\n    for (uint i = 0; i < len1; i++)\n        for (uint j = 0; j < min(i, len2); j++)\n            tot += (double)C1[i] * C2[j] / p12;\n    return tot;\n}\n\nint main() {\n    printf(\"%1.16f\\n\", beating_probability(4, 9, 6, 6));\n    printf(\"%1.16f\\n\", beating_probability(10, 5, 7, 6));\n    return 0;\n}\n"}
{"id": 60815, "name": "Rosetta Code_Find unimplemented tasks", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n    \"net/url\"\n)\n\nconst language = \"Go\"\n\nvar baseQuery = \"http:\n    \"&format=xml&list=categorymembers&cmlimit=100\"\n\nfunc req(u string, foundCm func(string)) string {\n    resp, err := http.Get(u)\n    if err != nil {\n        fmt.Println(err) \n        return \"\"\n    }\n    defer resp.Body.Close()\n    for p := xml.NewDecoder(resp.Body); ; {\n        t, err := p.RawToken()\n        switch s, ok := t.(xml.StartElement); {\n        case err == io.EOF:\n            return \"\"\n        case err != nil:\n            fmt.Println(err)\n            return \"\"\n        case !ok:\n            continue\n        case s.Name.Local == \"cm\":\n            for _, a := range s.Attr {\n                if a.Name.Local == \"title\" {\n                    foundCm(a.Value)\n                }\n            }\n        case s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n            s.Attr[0].Name.Local == \"cmcontinue\":\n            return url.QueryEscape(s.Attr[0].Value)\n        }\n    }\n    return \"\"\n}\n\nfunc main() {\n    \n    langMap := make(map[string]bool)\n    storeLang := func(cm string) { langMap[cm] = true }\n    languageQuery := baseQuery + \"&cmtitle=Category:\" + language\n    continueAt := req(languageQuery, storeLang)\n    for continueAt > \"\" {\n        continueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n    }\n\n    \n    if len(langMap) == 0 {\n        fmt.Println(\"no tasks implemented for\", language)\n        return\n    }\n\n    \n    printUnImp := func(cm string) {\n        if !langMap[cm] {\n            fmt.Println(cm)\n        }\n    }\n    taskQuery := baseQuery + \"&cmtitle=Category:Programming_Tasks\"\n    continueAt = req(taskQuery, printUnImp)\n    for continueAt > \"\" {\n        continueAt = req(taskQuery+\"&cmcontinue=\"+continueAt, printUnImp)\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_find_unimplemented_tasks.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60816, "name": "Halt and catch fire", "Go": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}\n", "C": "int main(){int a=0, b=0, c=a/b;}\n"}
{"id": 60817, "name": "Plasma effect", "Go": "package main\n\nimport (\n    \"image\"\n    \"image/color\"\n    \"image/gif\"\n    \"log\"\n    \"math\"\n    \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n    for x := 0; x < w; x++ {\n        for y := 0; y < h; y++ {\n            img.SetColorIndex(x, y, ci)\n        }\n    }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n    u := int(bri*255 + 0.5)\n    if sat == 0 {\n        r, g, b = u, u, u\n    } else {\n        h := (hue - math.Floor(hue)) * 6\n        f := h - math.Floor(h)\n        p := int(bri*(1-sat)*255 + 0.5)\n        q := int(bri*(1-sat*f)*255 + 0.5)\n        t := int(bri*(1-sat*(1-f))*255 + 0.5)\n        switch int(h) {\n        case 0:\n            r, g, b = u, t, p\n        case 1:\n            r, g, b = q, u, p\n        case 2:\n            r, g, b = p, u, t\n        case 3:\n            r, g, b = p, q, u\n        case 4:\n            r, g, b = t, p, u\n        case 5:\n            r, g, b = u, p, q\n        }\n    }\n    return\n}\n\nfunc main() {\n    const degToRad = math.Pi / 180\n    const nframes = 100\n    const delay = 4 \n    w, h := 640, 640\n    anim := gif.GIF{LoopCount: nframes}\n    rect := image.Rect(0, 0, w, h)\n    palette := make([]color.Color, nframes+1)\n    palette[0] = color.White\n    for i := 1; i <= nframes; i++ {\n        r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n        palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n    }\n    for f := 1; f <= nframes; f++ {\n        img := image.NewPaletted(rect, palette)\n        setBackgroundColor(img, w, h, 0) \n        for y := 0; y < h; y++ {\n            for x := 0; x < w; x++ {\n                fx, fy := float64(x), float64(y)\n                value := math.Sin(fx / 16)\n                value += math.Sin(fy / 8)\n                value += math.Sin((fx + fy) / 16)\n                value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n                value += 4 \n                value /= 8 \n                _, rem := math.Modf(value + float64(f)/float64(nframes))\n                ci := uint8(nframes*rem) + 1\n                img.SetColorIndex(x, y, ci)\n            }\n        }\n        anim.Delay = append(anim.Delay, delay)\n        anim.Image = append(anim.Image, img)\n    }\n    file, err := os.Create(\"plasma.gif\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer file.Close() \n    if err2 := gif.EncodeAll(file, &anim); err != nil {\n        log.Fatal(err2)\n    }    \n}\n", "C": "#include<windows.h>\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n#include<math.h>\n\n#define pi M_PI\n\nint main()\n{\n\tCONSOLE_SCREEN_BUFFER_INFO info;\n    int cols, rows;\n\ttime_t t;\n\tint i,j;\n\n    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);\n    cols = info.srWindow.Right - info.srWindow.Left + 1;\n    rows = info.srWindow.Bottom - info.srWindow.Top + 1;\n\t\n\tHANDLE console;\n\t\n\tconsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\n\tsystem(\"@clear||cls\");\n\t\n\tsrand((unsigned)time(&t));\n\t\n\tfor(i=0;i<rows;i++)\n\t\tfor(j=0;j<cols;j++){\n\t\t\tSetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);\n\t\t\tprintf(\"%c\",219);\n\t\t}\n\t\t\n\tgetchar();\n\t\n\treturn 0;\n}\n"}
{"id": 60818, "name": "Wordle comparison", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"log\"\n)\n\nfunc wordle(answer, guess string) []int {\n    n := len(guess)\n    if n != len(answer) {\n        log.Fatal(\"The words must be of the same length.\")\n    }\n    answerBytes := []byte(answer)\n    result := make([]int, n) \n    for i := 0; i < n; i++ {\n        if guess[i] == answerBytes[i] {\n            answerBytes[i] = '\\000'\n            result[i] = 2\n        }\n    }\n    for i := 0; i < n; i++ {\n        ix := bytes.IndexByte(answerBytes, guess[i])\n        if ix >= 0 {\n            answerBytes[ix] = '\\000'\n            result[i] = 1\n        }\n    }\n    return result\n}\n\nfunc main() {\n    colors := []string{\"grey\", \"yellow\", \"green\"}\n    pairs := [][]string{\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"},\n    }\n    for _, pair := range pairs {\n        res := wordle(pair[0], pair[1])\n        res2 := make([]string, len(res))\n        for i := 0; i < len(res); i++ {\n            res2[i] = colors[res[i]]\n        }\n        fmt.Printf(\"%s v %s => %v => %v\\n\", pair[0], pair[1], res, res2)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid wordle(const char *answer, const char *guess, int *result) {\n    int i, ix, n = strlen(guess);\n    char *ptr;\n    if (n != strlen(answer)) {\n        printf(\"The words must be of the same length.\\n\");\n        exit(1);\n    }\n    char answer2[n+1];\n    strcpy(answer2, answer);\n    for (i = 0; i < n; ++i) {\n        if (guess[i] == answer2[i]) {\n            answer2[i] = '\\v';\n            result[i] = 2;\n        }\n    }\n    for (i = 0; i < n; ++i) {\n        if ((ptr = strchr(answer2, guess[i])) != NULL) {\n            ix = ptr - answer2;\n            answer2[ix] = '\\v';\n            result[i] = 1;\n        }\n    }\n}\n\nint main() {\n    int i, j;\n    const char *answer, *guess;\n    int res[5];\n    const char *res2[5];\n    const char *colors[3] = {\"grey\", \"yellow\", \"green\"};\n    const char *pairs[5][2] = {\n        {\"ALLOW\", \"LOLLY\"},\n        {\"BULLY\", \"LOLLY\"},\n        {\"ROBIN\", \"ALERT\"},\n        {\"ROBIN\", \"SONIC\"},\n        {\"ROBIN\", \"ROBIN\"}\n    };\n    for (i = 0; i < 5; ++i) {\n        answer = pairs[i][0];\n        guess  = pairs[i][1];\n        for (j = 0; j < 5; ++j) res[j] = 0;\n        wordle(answer, guess, res);\n        for (j = 0; j < 5; ++j) res2[j] = colors[res[j]];\n        printf(\"%s v %s => { \", answer, guess);\n        for (j = 0; j < 5; ++j) printf(\"%d \", res[j]);\n        printf(\"} => { \");\n        for (j = 0; j < 5; ++j) printf(\"%s \", res2[j]);\n        printf(\"}\\n\");\n    }\n    return 0;\n}\n"}
{"id": 60819, "name": "Color quantization", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"image\"\n    \"image/color\"\n    \"image/png\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    f, err := os.Open(\"Quantum_frog.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    img, err := png.Decode(f)\n    if ec := f.Close(); err != nil {\n        log.Fatal(err)\n    } else if ec != nil {\n        log.Fatal(ec)\n    }\n    fq, err := os.Create(\"frog16.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = png.Encode(fq, quant(img, 16)); err != nil {\n        log.Fatal(err)\n    }\n}\n\n\nfunc quant(img image.Image, nq int) image.Image {\n    qz := newQuantizer(img, nq) \n    qz.cluster()                \n    return qz.Paletted()        \n}\n\n\ntype quantizer struct {\n    img image.Image \n    cs  []cluster   \n    px  []point     \n    ch  chValues    \n    eq  []point     \n}\n\ntype cluster struct {\n    px       []point \n    widestCh int     \n    chRange  uint32  \n}\n\ntype point struct{ x, y int }\ntype chValues []uint32\ntype queue []*cluster\n\nconst (\n    rx = iota\n    gx\n    bx\n)\n\nfunc newQuantizer(img image.Image, nq int) *quantizer {\n    b := img.Bounds()\n    npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)\n    \n    qz := &quantizer{\n        img: img,\n        ch:  make(chValues, npx),\n        cs:  make([]cluster, nq),\n    }\n    \n    c := &qz.cs[0]\n    px := make([]point, npx)\n    c.px = px\n    i := 0\n    for y := b.Min.Y; y < b.Max.Y; y++ {\n        for x := b.Min.X; x < b.Max.X; x++ {\n            px[i].x = x\n            px[i].y = y\n            i++\n        }\n    }\n    return qz\n}\n\nfunc (qz *quantizer) cluster() {\n    \n    \n    \n    \n    \n    pq := new(queue)\n    \n    c := &qz.cs[0]\n    for i := 1; ; {\n        qz.setColorRange(c)\n        \n        \n        if c.chRange > 0 {\n            heap.Push(pq, c) \n        }\n        \n        \n        if len(*pq) == 0 {\n            qz.cs = qz.cs[:i]\n            break\n        }\n        s := heap.Pop(pq).(*cluster) \n        c = &qz.cs[i]                \n        i++\n        m := qz.Median(s)\n        qz.Split(s, c, m) \n        \n        if i == len(qz.cs) {\n            break\n        }\n        qz.setColorRange(s)\n        if s.chRange > 0 {\n            heap.Push(pq, s) \n        }\n    }\n}\n    \nfunc (q *quantizer) setColorRange(c *cluster) {\n    \n    var maxR, maxG, maxB uint32\n    minR := uint32(math.MaxUint32)\n    minG := uint32(math.MaxUint32)\n    minB := uint32(math.MaxUint32) \n    for _, p := range c.px {\n        r, g, b, _ := q.img.At(p.x, p.y).RGBA()\n        if r < minR { \n            minR = r\n        }\n        if r > maxR {\n            maxR = r\n        }\n        if g < minG {\n            minG = g \n        }\n        if g > maxG {\n            maxG = g\n        }\n        if b < minB {\n            minB = b\n        }\n        if b > maxB {\n            maxB = b\n        }\n    }\n    \n    s := gx\n    min := minG\n    max := maxG\n    if maxR-minR > max-min {\n        s = rx\n        min = minR\n        max = maxR\n    }\n    if maxB-minB > max-min {\n        s = bx\n        min = minB\n        max = maxB\n    }\n    c.widestCh = s\n    c.chRange = max - min \n}\n\nfunc (q *quantizer) Median(c *cluster) uint32 {\n    px := c.px\n    ch := q.ch[:len(px)]\n    \n    switch c.widestCh {\n    case rx:\n        for i, p := range c.px {\n            ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case gx:\n        for i, p := range c.px {\n            _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA()\n        }\n    case bx:\n        for i, p := range c.px {\n            _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA()\n        }\n    }\n    \n    sort.Sort(ch)\n    half := len(ch) / 2\n    m := ch[half]\n    if len(ch)%2 == 0 {\n        m = (m + ch[half-1]) / 2\n    }\n    return m\n}\n\nfunc (q *quantizer) Split(s, c *cluster, m uint32) {\n    px := s.px\n    var v uint32\n    i := 0\n    lt := 0\n    gt := len(px) - 1\n    eq := q.eq[:0] \n    for i <= gt {\n        \n        r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA()\n        switch s.widestCh {\n        case rx:\n            v = r\n        case gx:\n            v = g\n        case bx:\n            v = b\n        } \n        \n        switch {\n        case v < m:\n            px[lt] = px[i]\n            lt++\n            i++\n        case v > m:\n            px[gt], px[i] = px[i], px[gt]\n            gt--\n        default:\n            eq = append(eq, px[i])\n            i++\n        }\n    }\n    \n    if len(eq) > 0 {\n        copy(px[lt:], eq) \n        \n        \n        \n        if len(px)-i < lt {\n            i = lt\n        }\n        q.eq = eq \n    }\n    \n    s.px = px[:i]\n    c.px = px[i:]\n}   \n    \nfunc (qz *quantizer) Paletted() *image.Paletted {\n    cp := make(color.Palette, len(qz.cs))\n    pi := image.NewPaletted(qz.img.Bounds(), cp)\n    for i := range qz.cs {\n        px := qz.cs[i].px\n        \n        var rsum, gsum, bsum int64\n        for _, p := range px {\n            r, g, b, _ := qz.img.At(p.x, p.y).RGBA()\n            rsum += int64(r)\n            gsum += int64(g)\n            bsum += int64(b)\n        } \n        n64 := int64(len(px))\n        cp[i] = color.NRGBA64{\n            uint16(rsum / n64),\n            uint16(gsum / n64),\n            uint16(bsum / n64),\n            0xffff,\n        }\n        \n        for _, p := range px {\n            pi.SetColorIndex(p.x, p.y, uint8(i))\n        }\n    }\n    return pi\n}\n\n\nfunc (c chValues) Len() int           { return len(c) }\nfunc (c chValues) Less(i, j int) bool { return c[i] < c[j] }\nfunc (c chValues) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\n\n\nfunc (q queue) Len() int { return len(q) }\n\n\nfunc (q queue) Less(i, j int) bool {\n    return len(q[j].px) < len(q[i].px)\n}\n\nfunc (q queue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n}\nfunc (pq *queue) Push(x interface{}) {\n    c := x.(*cluster)\n    *pq = append(*pq, c)\n}\nfunc (pq *queue) Pop() interface{} {\n    q := *pq\n    n := len(q) - 1\n    c := q[n]\n    *pq = q[:n]\n    return c\n}\n", "C": "typedef struct oct_node_t oct_node_t, *oct_node;\nstruct oct_node_t{\n\t\n\tuint64_t r, g, b;\n\tint count, heap_idx;\n\toct_node kids[8], parent;\n\tunsigned char n_kids, kid_idx, flags, depth;\n};\n\n\ninline int cmp_node(oct_node a, oct_node b)\n{\n\tif (a->n_kids < b->n_kids) return -1;\n\tif (a->n_kids > b->n_kids) return 1;\n\n\tint ac = a->count * (1 + a->kid_idx) >> a->depth;\n\tint bc = b->count * (1 + b->kid_idx) >> b->depth;\n\treturn ac < bc ? -1 : ac > bc;\n}\n\n\noct_node node_insert(oct_node root, unsigned char *pix)\n{\n#\tdefine OCT_DEPTH 8\n\t\n\n\tunsigned char i, bit, depth = 0;\n\tfor (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i])\n\t\t\troot->kids[i] = node_new(i, depth, root);\n\n\t\troot = root->kids[i];\n\t}\n\n\troot->r += pix[0];\n\troot->g += pix[1];\n\troot->b += pix[2];\n\troot->count++;\n\treturn root;\n}\n\n\noct_node node_fold(oct_node p)\n{\n\tif (p->n_kids) abort();\n\toct_node q = p->parent;\n\tq->count += p->count;\n\n\tq->r += p->r;\n\tq->g += p->g;\n\tq->b += p->b;\n\tq->n_kids --;\n\tq->kids[p->kid_idx] = 0;\n\treturn q;\n}\n\n\nvoid color_replace(oct_node root, unsigned char *pix)\n{\n\tunsigned char i, bit;\n\n\tfor (bit = 1 << 7; bit; bit >>= 1) {\n\t\ti = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);\n\t\tif (!root->kids[i]) break;\n\t\troot = root->kids[i];\n\t}\n\n\tpix[0] = root->r;\n\tpix[1] = root->g;\n\tpix[2] = root->b;\n}\n\n\nvoid color_quant(image im, int n_colors)\n{\n\tint i;\n\tunsigned char *pix = im->pix;\n\tnode_heap heap = { 0, 0, 0 };\n\n\toct_node root = node_new(0, 0, 0), got;\n\tfor (i = 0; i < im->w * im->h; i++, pix += 3)\n\t\theap_add(&heap, node_insert(root, pix));\n\n\twhile (heap.n > n_colors + 1)\n\t\theap_add(&heap, node_fold(pop_heap(&heap)));\n\n\tdouble c;\n\tfor (i = 1; i < heap.n; i++) {\n\t\tgot = heap.buf[i];\n\t\tc = got->count;\n\t\tgot->r = got->r / c + .5;\n\t\tgot->g = got->g / c + .5;\n\t\tgot->b = got->b / c + .5;\n\t\tprintf(\"%2d | %3llu %3llu %3llu (%d pixels)\\n\",\n\t\t\ti, got->r, got->g, got->b, got->count);\n\t}\n\n\tfor (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)\n\t\tcolor_replace(root, pix);\n\n\tnode_free();\n\tfree(heap.buf);\n}\n"}
{"id": 60820, "name": "Function frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"go/token\"\n    \"io/ioutil\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    if len(os.Args) != 2 {\n        fmt.Println(\"usage ff <go source filename>\")\n        return\n    }\n    src, err := ioutil.ReadFile(os.Args[1])\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fs := token.NewFileSet()\n    a, err := parser.ParseFile(fs, os.Args[1], src, 0)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f := fs.File(a.Pos())\n    m := make(map[string]int)\n    ast.Inspect(a, func(n ast.Node) bool {\n        if ce, ok := n.(*ast.CallExpr); ok {\n            start := f.Offset(ce.Pos())\n            end := f.Offset(ce.Lparen)\n            m[string(src[start:end])]++\n        }\n        return true\n    })\n    cs := make(calls, 0, len(m))\n    for k, v := range m {\n        cs = append(cs, &call{k, v})\n    }\n    sort.Sort(cs)\n    for i, c := range cs {\n        fmt.Printf(\"%-20s %4d\\n\", c.expr, c.count)\n        if i == 9 {\n            break\n        }\n    }\n}\n\ntype call struct {\n    expr  string\n    count int\n}\ntype calls []*call\n\nfunc (c calls) Len() int           { return len(c) }\nfunc (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c calls) Less(i, j int) bool { return c[i].count > c[j].count }\n", "C": "#define _POSIX_SOURCE\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <stddef.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\nstruct functionInfo {\n    char* name;\n    int timesCalled;\n    char marked;\n};\nvoid addToList(struct functionInfo** list, struct functionInfo toAdd, \\\n               size_t* numElements, size_t* allocatedSize)\n{\n    static const char* keywords[32] = {\"auto\", \"break\", \"case\", \"char\", \"const\", \\\n                                       \"continue\", \"default\", \"do\", \"double\", \\\n                                       \"else\", \"enum\", \"extern\", \"float\", \"for\", \\\n                                       \"goto\", \"if\", \"int\", \"long\", \"register\", \\\n                                       \"return\", \"short\", \"signed\", \"sizeof\", \\\n                                       \"static\", \"struct\", \"switch\", \"typedef\", \\\n                                       \"union\", \"unsigned\", \"void\", \"volatile\", \\\n                                       \"while\"\n                                      };\n    int i;\n    \n    for (i = 0; i < 32; i++) {\n        if (!strcmp(toAdd.name, keywords[i])) {\n            return;\n        }\n    }\n    if (!*list) {\n        *allocatedSize = 10;\n        *list = calloc(*allocatedSize, sizeof(struct functionInfo));\n        if (!*list) {\n            printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                   *allocatedSize, sizeof(struct functionInfo));\n            abort();\n        }\n        (*list)[0].name = malloc(strlen(toAdd.name)+1);\n        if (!(*list)[0].name) {\n            printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n            abort();\n        }\n        strcpy((*list)[0].name, toAdd.name);\n        (*list)[0].timesCalled = 1;\n        (*list)[0].marked = 0;\n        *numElements = 1;\n    } else {\n        char found = 0;\n        unsigned int i;\n        for (i = 0; i < *numElements; i++) {\n            if (!strcmp((*list)[i].name, toAdd.name)) {\n                found = 1;\n                (*list)[i].timesCalled++;\n                break;\n            }\n        }\n        if (!found) {\n            struct functionInfo* newList = calloc((*allocatedSize)+10, \\\n                                                  sizeof(struct functionInfo));\n            if (!newList) {\n                printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                       (*allocatedSize)+10, sizeof(struct functionInfo));\n                abort();\n            }\n            memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo));\n            free(*list);\n            *allocatedSize += 10;\n            *list = newList;\n            (*list)[*numElements].name = malloc(strlen(toAdd.name)+1);\n            if (!(*list)[*numElements].name) {\n                printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n                abort();\n            }\n            strcpy((*list)[*numElements].name, toAdd.name);\n            (*list)[*numElements].timesCalled = 1;\n            (*list)[*numElements].marked = 0;\n            (*numElements)++;\n        }\n    }\n}\nvoid printList(struct functionInfo** list, size_t numElements)\n{\n    char maxSet = 0;\n    unsigned int i;\n    size_t maxIndex = 0;\n    for (i = 0; i<10; i++) {\n        maxSet = 0;\n        size_t j;\n        for (j = 0; j<numElements; j++) {\n            if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) {\n                if (!(*list)[j].marked) {\n                    maxSet = 1;\n                    maxIndex = j;\n                }\n            }\n        }\n        (*list)[maxIndex].marked = 1;\n        printf(\"%s() called %d times.\\n\", (*list)[maxIndex].name, \\\n               (*list)[maxIndex].timesCalled);\n    }\n}\nvoid freeList(struct functionInfo** list, size_t numElements)\n{\n    size_t i;\n    for (i = 0; i<numElements; i++) {\n        free((*list)[i].name);\n    }\n    free(*list);\n}\nchar* extractFunctionName(char* readHead)\n{\n    char* identifier = readHead;\n    if (isalpha(*identifier) || *identifier == '_') {\n        while (isalnum(*identifier) || *identifier == '_') {\n            identifier++;\n        }\n    }\n    \n    char* toParen = identifier;\n    if (toParen == readHead) return NULL;\n    while (isspace(*toParen)) {\n        toParen++;\n    }\n    if (*toParen != '(') return NULL;\n    \n    ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \\\n                     - ((ptrdiff_t)readHead)+1;\n    char* const name = malloc(size);\n    if (!name) {\n        printf(\"Failed to allocate %lu bytes.\\n\", size);\n        abort();\n    }\n    name[size-1] = '\\0';\n    memcpy(name, readHead, size-1);\n    \n    if (strcmp(name, \"\")) {\n        return name;\n    }\n    free(name);\n    return NULL;\n}\nint main(int argc, char** argv)\n{\n    int i;\n    for (i = 1; i<argc; i++) {\n        errno = 0;\n        FILE* file = fopen(argv[i], \"r\");\n        if (errno || !file) {\n            printf(\"fopen() failed with error code \\\"%s\\\"\\n\", \\\n                   strerror(errno));\n            abort();\n        }\n        char comment = 0;\n#define DOUBLEQUOTE 1\n#define SINGLEQUOTE 2\n        int string = 0;\n        struct functionInfo* functions = NULL;\n        struct functionInfo toAdd;\n        size_t numElements = 0;\n        size_t allocatedSize = 0;\n        struct stat metaData;\n        errno = 0;\n        if (fstat(fileno(file), &metaData) < 0) {\n            printf(\"fstat() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \\\n                                          MAP_PRIVATE, fileno(file), 0);\n        if (errno) {\n            printf(\"mmap() failed with error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        if (!mmappedSource) {\n            printf(\"mmap() returned NULL.\\n\");\n            abort();\n        }\n        char* readHead = mmappedSource;\n        while (readHead < mmappedSource + metaData.st_size) {\n            while (*readHead) {\n                \n                if (!string) {\n                    if (*readHead == '/' && !strncmp(readHead, \"\", 2)) {\n                        comment = 0;\n                    }\n                }\n                \n                if (!comment) {\n                    if (*readHead == '\"') {\n                        if (!string) {\n                            string = DOUBLEQUOTE;\n                        } else if (string == DOUBLEQUOTE) {\n                            \n                            if (strncmp((readHead-1), \"\\\\\\\"\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                    if (*readHead == '\\'') {\n                        if (!string) {\n                            string = SINGLEQUOTE;\n                        } else if (string == SINGLEQUOTE) {\n                            if (strncmp((readHead-1), \"\\\\\\'\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                }\n                \n                if (!comment && !string) {\n                    char* name = extractFunctionName(readHead);\n                    \n                    if (name) {\n                        toAdd.name = name;\n                        addToList(&functions, toAdd, &numElements, &allocatedSize);\n                        readHead += strlen(name);\n                    }\n                    free(name);\n                }\n                readHead++;\n            }\n        }\n        errno = 0;\n        munmap(mmappedSource, metaData.st_size);\n        if (errno) {\n            printf(\"munmap() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        errno = 0;\n        fclose(file);\n        if (errno) {\n            printf(\"fclose() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        printList(&functions, numElements);\n        freeList(&functions, numElements);\n    }\n    return 0;\n}\n"}
{"id": 60821, "name": "Function frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"go/ast\"\n    \"go/parser\"\n    \"go/token\"\n    \"io/ioutil\"\n    \"os\"\n    \"sort\"\n)\n\nfunc main() {\n    if len(os.Args) != 2 {\n        fmt.Println(\"usage ff <go source filename>\")\n        return\n    }\n    src, err := ioutil.ReadFile(os.Args[1])\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fs := token.NewFileSet()\n    a, err := parser.ParseFile(fs, os.Args[1], src, 0)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    f := fs.File(a.Pos())\n    m := make(map[string]int)\n    ast.Inspect(a, func(n ast.Node) bool {\n        if ce, ok := n.(*ast.CallExpr); ok {\n            start := f.Offset(ce.Pos())\n            end := f.Offset(ce.Lparen)\n            m[string(src[start:end])]++\n        }\n        return true\n    })\n    cs := make(calls, 0, len(m))\n    for k, v := range m {\n        cs = append(cs, &call{k, v})\n    }\n    sort.Sort(cs)\n    for i, c := range cs {\n        fmt.Printf(\"%-20s %4d\\n\", c.expr, c.count)\n        if i == 9 {\n            break\n        }\n    }\n}\n\ntype call struct {\n    expr  string\n    count int\n}\ntype calls []*call\n\nfunc (c calls) Len() int           { return len(c) }\nfunc (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c calls) Less(i, j int) bool { return c[i].count > c[j].count }\n", "C": "#define _POSIX_SOURCE\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <stddef.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\nstruct functionInfo {\n    char* name;\n    int timesCalled;\n    char marked;\n};\nvoid addToList(struct functionInfo** list, struct functionInfo toAdd, \\\n               size_t* numElements, size_t* allocatedSize)\n{\n    static const char* keywords[32] = {\"auto\", \"break\", \"case\", \"char\", \"const\", \\\n                                       \"continue\", \"default\", \"do\", \"double\", \\\n                                       \"else\", \"enum\", \"extern\", \"float\", \"for\", \\\n                                       \"goto\", \"if\", \"int\", \"long\", \"register\", \\\n                                       \"return\", \"short\", \"signed\", \"sizeof\", \\\n                                       \"static\", \"struct\", \"switch\", \"typedef\", \\\n                                       \"union\", \"unsigned\", \"void\", \"volatile\", \\\n                                       \"while\"\n                                      };\n    int i;\n    \n    for (i = 0; i < 32; i++) {\n        if (!strcmp(toAdd.name, keywords[i])) {\n            return;\n        }\n    }\n    if (!*list) {\n        *allocatedSize = 10;\n        *list = calloc(*allocatedSize, sizeof(struct functionInfo));\n        if (!*list) {\n            printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                   *allocatedSize, sizeof(struct functionInfo));\n            abort();\n        }\n        (*list)[0].name = malloc(strlen(toAdd.name)+1);\n        if (!(*list)[0].name) {\n            printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n            abort();\n        }\n        strcpy((*list)[0].name, toAdd.name);\n        (*list)[0].timesCalled = 1;\n        (*list)[0].marked = 0;\n        *numElements = 1;\n    } else {\n        char found = 0;\n        unsigned int i;\n        for (i = 0; i < *numElements; i++) {\n            if (!strcmp((*list)[i].name, toAdd.name)) {\n                found = 1;\n                (*list)[i].timesCalled++;\n                break;\n            }\n        }\n        if (!found) {\n            struct functionInfo* newList = calloc((*allocatedSize)+10, \\\n                                                  sizeof(struct functionInfo));\n            if (!newList) {\n                printf(\"Failed to allocate %lu elements of %lu bytes each.\\n\", \\\n                       (*allocatedSize)+10, sizeof(struct functionInfo));\n                abort();\n            }\n            memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo));\n            free(*list);\n            *allocatedSize += 10;\n            *list = newList;\n            (*list)[*numElements].name = malloc(strlen(toAdd.name)+1);\n            if (!(*list)[*numElements].name) {\n                printf(\"Failed to allocate %lu bytes.\\n\", strlen(toAdd.name)+1);\n                abort();\n            }\n            strcpy((*list)[*numElements].name, toAdd.name);\n            (*list)[*numElements].timesCalled = 1;\n            (*list)[*numElements].marked = 0;\n            (*numElements)++;\n        }\n    }\n}\nvoid printList(struct functionInfo** list, size_t numElements)\n{\n    char maxSet = 0;\n    unsigned int i;\n    size_t maxIndex = 0;\n    for (i = 0; i<10; i++) {\n        maxSet = 0;\n        size_t j;\n        for (j = 0; j<numElements; j++) {\n            if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) {\n                if (!(*list)[j].marked) {\n                    maxSet = 1;\n                    maxIndex = j;\n                }\n            }\n        }\n        (*list)[maxIndex].marked = 1;\n        printf(\"%s() called %d times.\\n\", (*list)[maxIndex].name, \\\n               (*list)[maxIndex].timesCalled);\n    }\n}\nvoid freeList(struct functionInfo** list, size_t numElements)\n{\n    size_t i;\n    for (i = 0; i<numElements; i++) {\n        free((*list)[i].name);\n    }\n    free(*list);\n}\nchar* extractFunctionName(char* readHead)\n{\n    char* identifier = readHead;\n    if (isalpha(*identifier) || *identifier == '_') {\n        while (isalnum(*identifier) || *identifier == '_') {\n            identifier++;\n        }\n    }\n    \n    char* toParen = identifier;\n    if (toParen == readHead) return NULL;\n    while (isspace(*toParen)) {\n        toParen++;\n    }\n    if (*toParen != '(') return NULL;\n    \n    ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \\\n                     - ((ptrdiff_t)readHead)+1;\n    char* const name = malloc(size);\n    if (!name) {\n        printf(\"Failed to allocate %lu bytes.\\n\", size);\n        abort();\n    }\n    name[size-1] = '\\0';\n    memcpy(name, readHead, size-1);\n    \n    if (strcmp(name, \"\")) {\n        return name;\n    }\n    free(name);\n    return NULL;\n}\nint main(int argc, char** argv)\n{\n    int i;\n    for (i = 1; i<argc; i++) {\n        errno = 0;\n        FILE* file = fopen(argv[i], \"r\");\n        if (errno || !file) {\n            printf(\"fopen() failed with error code \\\"%s\\\"\\n\", \\\n                   strerror(errno));\n            abort();\n        }\n        char comment = 0;\n#define DOUBLEQUOTE 1\n#define SINGLEQUOTE 2\n        int string = 0;\n        struct functionInfo* functions = NULL;\n        struct functionInfo toAdd;\n        size_t numElements = 0;\n        size_t allocatedSize = 0;\n        struct stat metaData;\n        errno = 0;\n        if (fstat(fileno(file), &metaData) < 0) {\n            printf(\"fstat() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \\\n                                          MAP_PRIVATE, fileno(file), 0);\n        if (errno) {\n            printf(\"mmap() failed with error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        if (!mmappedSource) {\n            printf(\"mmap() returned NULL.\\n\");\n            abort();\n        }\n        char* readHead = mmappedSource;\n        while (readHead < mmappedSource + metaData.st_size) {\n            while (*readHead) {\n                \n                if (!string) {\n                    if (*readHead == '/' && !strncmp(readHead, \"\", 2)) {\n                        comment = 0;\n                    }\n                }\n                \n                if (!comment) {\n                    if (*readHead == '\"') {\n                        if (!string) {\n                            string = DOUBLEQUOTE;\n                        } else if (string == DOUBLEQUOTE) {\n                            \n                            if (strncmp((readHead-1), \"\\\\\\\"\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                    if (*readHead == '\\'') {\n                        if (!string) {\n                            string = SINGLEQUOTE;\n                        } else if (string == SINGLEQUOTE) {\n                            if (strncmp((readHead-1), \"\\\\\\'\", 2)) {\n                                string = 0;\n                            }\n                        }\n                    }\n                }\n                \n                if (!comment && !string) {\n                    char* name = extractFunctionName(readHead);\n                    \n                    if (name) {\n                        toAdd.name = name;\n                        addToList(&functions, toAdd, &numElements, &allocatedSize);\n                        readHead += strlen(name);\n                    }\n                    free(name);\n                }\n                readHead++;\n            }\n        }\n        errno = 0;\n        munmap(mmappedSource, metaData.st_size);\n        if (errno) {\n            printf(\"munmap() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        errno = 0;\n        fclose(file);\n        if (errno) {\n            printf(\"fclose() returned error \\\"%s\\\"\\n\", strerror(errno));\n            abort();\n        }\n        printList(&functions, numElements);\n        freeList(&functions, numElements);\n    }\n    return 0;\n}\n"}
{"id": 60822, "name": "Unicode strings", "Go": "    var i int\n    var u rune\n    for i, u = range \"voilà\" {\n        fmt.Println(i, u)\n    }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n"}
{"id": 60823, "name": "Unicode strings", "Go": "    var i int\n    var u rune\n    for i, u = range \"voilà\" {\n        fmt.Println(i, u)\n    }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\n\nwchar_t poker[] = L\"♥♦♣♠\";\nwchar_t four_two[] = L\"\\x56db\\x5341\\x4e8c\";\n\nint main() {\n    \n    if (!setlocale(LC_CTYPE, \"\")) {\n        fprintf(stderr, \"Locale failure, check your env vars\\n\");\n        return 1;\n    }\n\n#ifdef __STDC_ISO_10646__\n    \n    printf(\"%lc\\n\", 0x2708);    \n    printf(\"%ls\\n\", poker);     \n    printf(\"%ls\\n\", four_two);  \n#else\n    \n    printf(\"airplane\\n\");\n    printf(\"club diamond club spade\\n\");\n    printf(\"for ty two\\n\");\n#endif\n    return 0;\n}\n"}
{"id": 60824, "name": "Bitmap_Read an image through a pipe", "Go": "package main\n\n\n\n\n\n\nimport (\n    \"log\"\n    \"os/exec\"\n    \"raster\"\n)\n\nfunc main() {\n    c := exec.Command(\"convert\", \"Unfilledcirc.png\", \"-depth\", \"1\", \"ppm:-\")\n    pipe, err := c.StdoutPipe()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = c.Start(); err != nil {\n        log.Fatal(err)\n    }\n    b, err := raster.ReadPpmFrom(pipe)\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = b.WritePpmFile(\"Unfilledcirc.ppm\"); err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "image read_image(const char *name);\n"}
{"id": 60825, "name": "Starting a web browser", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"html/template\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strings\"\n    \"time\"\n)\n\ntype row struct {\n    Address, Street, House, Color string\n}\n\nfunc isDigit(b byte) bool {\n    return '0' <= b && b <= '9'\n}\n\nfunc separateHouseNumber(address string) (street string, house string) {\n    length := len(address)\n    fields := strings.Fields(address)\n    size := len(fields)\n    last := fields[size-1]\n    penult := fields[size-2]\n    if isDigit(last[0]) {\n        isdig := isDigit(penult[0])\n        if size > 2 && isdig && !strings.HasPrefix(penult, \"194\") {\n            house = fmt.Sprintf(\"%s %s\", penult, last)\n        } else {\n            house = last\n        }\n    } else if size > 2 {\n        house = fmt.Sprintf(\"%s %s\", penult, last)\n    }\n    street = strings.TrimRight(address[:length-len(house)], \" \")\n    return\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nvar tmpl = `\n<head>\n  <title>Rosetta Code - Start a Web Browser</title>\n  <meta charset=\"UTF-8\">\n</head>\n<body bgcolor=\"#d8dcd6\">\n  <table border=\"2\">\n    <p align=\"center\">\n      <font face=\"Arial, sans-serif\" size=\"5\">Split the house number from the street name</font>    \n      <tr bgcolor=\"#02ccfe\"><th>Address</th><th>Street</th><th>House Number</th></tr>\n      {{range $row := .}}\n      <tr bgcolor={{$row.Color}}>         \n        <td>{{$row.Address}}</td>\n        <td>{{$row.Street}}</td>\n        <td>{{$row.House}}</td>\n      </tr>\n      {{end}}\n    </p>\n  </table>\n</body>\n`\nfunc main() {\n    addresses := []string{\n        \"Plataanstraat 5\",\n        \"Straat 12\",\n        \"Straat 12 II\",\n        \"Dr. J. Straat   12\",\n        \"Dr. J. Straat 12 a\",\n        \"Dr. J. Straat 12-14\",\n        \"Laan 1940 - 1945 37\",\n        \"Plein 1940 2\",\n        \"1213-laan 11\",\n        \"16 april 1944 Pad 1\",\n        \"1e Kruisweg 36\",\n        \"Laan 1940-'45 66\",\n        \"Laan '40-'45\",\n        \"Langeloërduinen 3 46\",\n        \"Marienwaerdt 2e Dreef 2\",\n        \"Provincialeweg N205 1\",\n        \"Rivium 2e Straat 59.\",\n        \"Nieuwe gracht 20rd\",\n        \"Nieuwe gracht 20rd 2\",\n        \"Nieuwe gracht 20zw /2\",\n        \"Nieuwe gracht 20zw/3\",\n        \"Nieuwe gracht 20 zw/4\",\n        \"Bahnhofstr. 4\",\n        \"Wertstr. 10\",\n        \"Lindenhof 1\",\n        \"Nordesch 20\",\n        \"Weilstr. 6\",\n        \"Harthauer Weg 2\",\n        \"Mainaustr. 49\",\n        \"August-Horch-Str. 3\",\n        \"Marktplatz 31\",\n        \"Schmidener Weg 3\",\n        \"Karl-Weysser-Str. 6\",\n    }\n    browser := \"firefox\" \n    colors := [2]string{\"#d7fffe\", \"#9dbcd4\"}\n    fileName := \"addresses_table.html\"\n    ct := template.Must(template.New(\"\").Parse(tmpl))\n    file, err := os.Create(fileName)\n    check(err)\n    rows := make([]row, len(addresses))\n    for i, address := range addresses {\n        street, house := separateHouseNumber(address)\n        if house == \"\" {\n            house = \"(none)\"\n        }\n        color := colors[i%2]\n        rows[i] = row{address, street, house, color}\n    }   \n    err = ct.Execute(file, rows)\n    check(err)\n    cmd := exec.Command(browser, fileName)\n    err = cmd.Run()\n    check(err)\n    file.Close()\n    time.Sleep(5 * time.Second) \n    err = os.Remove(fileName)\n    check(err)\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include \"wren.h\"\n\n\n\nvoid C_fileAllocate(WrenVM* vm) {\n    FILE** pfp = (FILE**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(FILE*));\n    const char *filename = wrenGetSlotString(vm, 1);\n    const char *mode = wrenGetSlotString(vm, 2);\n    *pfp = fopen(filename, mode);\n}\n\nvoid C_write(WrenVM* vm) {\n    FILE* fp = *(FILE**)wrenGetSlotForeign(vm, 0);\n    const char *s = wrenGetSlotString(vm, 1);\n    fputs(s, fp);\n}\n\nvoid C_close(WrenVM* vm) {\n    FILE* fp = *(FILE**)wrenGetSlotForeign(vm, 0);\n    fclose(fp);\n}\n\nvoid C_remove(WrenVM* vm) {\n    const char *filename = wrenGetSlotString(vm, 1);\n    remove(filename);\n}\n\nvoid C_flushAll(WrenVM* vm) {\n    fflush(NULL);\n}\n\nvoid C_system(WrenVM* vm) {\n    const char *s = wrenGetSlotString(vm, 1);\n    system(s);\n}\n\nvoid C_sleep(WrenVM* vm) {\n    int seconds = (int)wrenGetSlotDouble(vm, 1);\n    sleep(seconds);\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"File\") == 0) {\n            methods.allocate = C_fileAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"File\") == 0) {\n            if (!isStatic && strcmp(signature, \"write(_)\") == 0)   return C_write;\n            if (!isStatic && strcmp(signature, \"close()\") == 0)    return C_close;\n            if ( isStatic && strcmp(signature, \"remove(_)\") == 0)  return C_remove;\n            if ( isStatic && strcmp(signature, \"flushAll()\") == 0) return C_flushAll;\n        } else if (strcmp(className, \"C\") == 0) {\n            if ( isStatic && strcmp(signature, \"system(_)\") == 0)  return C_system;\n            if ( isStatic && strcmp(signature, \"sleep(_)\") == 0)   return C_sleep;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"starting_web_browser.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60826, "name": "Memory layout of a data structure", "Go": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9  rs232p9 = 1 << iota \n\tRD9                      \n\tTD9                      \n\tDTR9                     \n\tSG9                      \n\tDSR9                     \n\tRTS9                     \n\tCTS9                     \n\tRI9                      \n)\n\nfunc main() {\n\t\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}\n", "C": "struct RS232_data\n{\n  unsigned carrier_detect        : 1;\n  unsigned received_data         : 1;\n  unsigned transmitted_data      : 1;\n  unsigned data_terminal_ready   : 1;\n  unsigned signal_ground         : 1;\n  unsigned data_set_ready        : 1;\n  unsigned request_to_send       : 1;\n  unsigned clear_to_send         : 1;\n  unsigned ring_indicator        : 1;\n};\n"}
{"id": 60827, "name": "Sum of primes in odd positions is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum := 0\n    fmt.Println(\" i   p[i]  Σp[i]\")\n    fmt.Println(\"----------------\")\n    for i := 0; i < len(primes); i += 2 {\n        sum += primes[i]\n        if rcu.IsPrime(sum) {\n            fmt.Printf(\"%3d  %3d  %6s\\n\", i+1, primes[i], rcu.Commatize(sum))\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n   int s=0, p, i=1;\n   for(p=2;p<=999;p++) {\n       if(isprime(p)) {\n           if(i%2) {\n               s+=p;\n               if(isprime(s)) printf( \"%d       %d       %d\\n\", i, p, s );\n           }\n           i+=1;\n       }\n   }\n   return 0;\n}\n"}
{"id": 60828, "name": "Sum of primes in odd positions is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum := 0\n    fmt.Println(\" i   p[i]  Σp[i]\")\n    fmt.Println(\"----------------\")\n    for i := 0; i < len(primes); i += 2 {\n        sum += primes[i]\n        if rcu.IsPrime(sum) {\n            fmt.Printf(\"%3d  %3d  %6s\\n\", i+1, primes[i], rcu.Commatize(sum))\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n   int s=0, p, i=1;\n   for(p=2;p<=999;p++) {\n       if(isprime(p)) {\n           if(i%2) {\n               s+=p;\n               if(isprime(s)) printf( \"%d       %d       %d\\n\", i, p, s );\n           }\n           i+=1;\n       }\n   }\n   return 0;\n}\n"}
{"id": 60829, "name": "Sum of primes in odd positions is prime", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum := 0\n    fmt.Println(\" i   p[i]  Σp[i]\")\n    fmt.Println(\"----------------\")\n    for i := 0; i < len(primes); i += 2 {\n        sum += primes[i]\n        if rcu.IsPrime(sum) {\n            fmt.Printf(\"%3d  %3d  %6s\\n\", i+1, primes[i], rcu.Commatize(sum))\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<stdlib.h>\n\nint isprime( int p ) {\n    int i;\n    if(p==2) return 1;\n    if(!(p%2)) return 0;\n    for(i=3; i*i<=p; i+=2) {\n       if(!(p%i)) return 0;\n    }\n    return 1;\n}\n\nint main( void ) {\n   int s=0, p, i=1;\n   for(p=2;p<=999;p++) {\n       if(isprime(p)) {\n           if(i%2) {\n               s+=p;\n               if(isprime(s)) printf( \"%d       %d       %d\\n\", i, p, s );\n           }\n           i+=1;\n       }\n   }\n   return 0;\n}\n"}
{"id": 60830, "name": "Sum of two adjacent numbers are primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc main() {\n    limit := int(math.Log(1e7) * 1e7 * 1.2) \n    primes := rcu.Primes(limit)\n    fmt.Println(\"The first 20 pairs of natural numbers whose sum is prime are:\")\n    for i := 1; i <= 20; i++ {\n        p := primes[i]\n        hp := p / 2\n        fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n    }\n    fmt.Println(\"\\nThe 10 millionth such pair is:\")\n    p := primes[1e7]\n    hp := p / 2\n    fmt.Printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef int bool;\n\nvoid primeSieve(int *c, int limit, bool processEven, bool primesOnly) {\n    int i, ix, p, p2;\n    limit++;\n    c[0] = TRUE;\n    c[1] = TRUE;\n    if (processEven) {\n        for (i = 4; i < limit; i +=2) c[i] = TRUE;\n    }\n    p = 3;\n    while (TRUE) {\n        p2 = p * p;\n        if (p2 >= limit) break;\n        for (i = p2; i < limit; i += 2*p) c[i] = TRUE;\n        while (TRUE) {\n            p += 2;\n            if (!c[p]) break;\n        }\n    }\n    if (primesOnly) {\n        \n        c[0] = 2;\n        for (i = 3, ix = 1; i < limit; i += 2) {\n            if (!c[i]) c[ix++] = i;\n        }\n    }\n}\n\nint main() {\n    int i, p, hp, n = 10000000;\n    int limit = (int)(log(n) * (double)n * 1.2);  \n    int *primes = (int *)calloc(limit, sizeof(int));\n    primeSieve(primes, limit-1, FALSE, TRUE);\n    printf(\"The first 20 pairs of natural numbers whose sum is prime are:\\n\");\n    for (i = 1; i <= 20; ++i) {\n        p = primes[i];\n        hp = p / 2;\n        printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    }\n    printf(\"\\nThe 10 millionth such pair is:\\n\");\n    p = primes[n];\n    hp = p / 2;\n    printf(\"%2d + %2d = %2d\\n\", hp, hp+1, p);\n    free(primes);\n    return 0;\n}\n"}
{"id": 60831, "name": "Square form factorization", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc isqrt(x uint64) uint64 {\n    x0 := x >> 1\n    x1 := (x0 + x/x0) >> 1\n    for x1 < x0 {\n        x0 = x1\n        x1 = (x0 + x/x0) >> 1\n    }\n    return x0\n}\n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nvar multiplier = []uint64{\n    1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11,\n}\n\nfunc squfof(N uint64) uint64 {\n    s := uint64(math.Sqrt(float64(N)) + 0.5)\n    if s*s == N {\n        return s\n    }\n    for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ {\n        D := multiplier[k] * N\n        P := isqrt(D)\n        Pprev := P\n        Po := Pprev\n        Qprev := uint64(1)\n        Q := D - Po*Po\n        L := uint32(isqrt(8 * s))\n        B := 3 * L\n        i := uint32(2)\n        var b, q, r uint64\n        for ; i < B; i++ {\n            b = uint64((Po + P) / Q)\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            r = uint64(math.Sqrt(float64(Q)) + 0.5)\n            if (i&1) == 0 && r*r == Q {\n                break\n            }\n            Qprev = q\n            Pprev = P\n        }\n        if i >= B {\n            continue\n        }\n        b = uint64((Po - P) / r)\n        P = b*r + P\n        Pprev = P\n        Qprev = r\n        Q = (D - Pprev*Pprev) / Qprev\n        i = 0\n        for {\n            b = uint64((Po + P) / Q)\n            Pprev = P\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            Qprev = q\n            i++\n            if P == Pprev {\n                break\n            }\n        }\n        r = gcd(N, Qprev)\n        if r != 1 && r != N {\n            return r\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    examples := []uint64{\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877,\n    }\n    fmt.Println(\"Integer              Factor     Quotient\")\n    fmt.Println(\"------------------------------------------\")\n    for _, N := range examples {\n        fact := squfof(N)\n        quot := \"fail\"\n        if fact > 0 {\n            quot = fmt.Sprintf(\"%d\", N/fact)\n        }\n        fmt.Printf(\"%-20d %-10d %s\\n\", N, fact, quot)\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\n#define nelems(x) (sizeof(x) / sizeof((x)[0]))\n\nconst unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11};\n\nunsigned long long gcd(unsigned long long a, unsigned long long b)\n{\n    while (b != 0)\n    {\n        a %= b;\n        a ^= b;\n        b ^= a;\n        a ^= b;\n    }\n\n    return a;\n}\n\nunsigned long long SQUFOF( unsigned long long N )\n{\n    unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s;\n    unsigned long L, B, i;\n    s = (unsigned long long)(sqrtl(N)+0.5);\n    if (s*s == N) return s;\n    for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) {\n        D = multiplier[k]*N;\n        Po = Pprev = P = sqrtl(D);\n        Qprev = 1;\n        Q = D - Po*Po;\n        L = 2 * sqrtl( 2*s );\n        B = 3 * L;\n        for (i = 2 ; i < B ; i++) {\n            b = (unsigned long long)((Po + P)/Q);\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            r = (unsigned long long)(sqrtl(Q)+0.5);\n            if (!(i & 1) && r*r == Q) break;\n            Qprev = q;\n            Pprev = P;\n        };\n        if (i >= B) continue;\n        b = (unsigned long long)((Po - P)/r);\n        Pprev = P = b*r + P;\n        Qprev = r;\n        Q = (D - Pprev*Pprev)/Qprev;\n        i = 0;\n        do {\n            b = (unsigned long long)((Po + P)/Q);\n            Pprev = P;\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            Qprev = q;\n            i++;\n        } while (P != Pprev);\n        r = gcd(N, Qprev);\n        if (r != 1 && r != N) return r;\n    }\n    return 0;\n}\n\nint main(int argc, char *argv[]) {\n    int i;\n    const unsigned long long data[] = {\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877};\n\n    for(int i = 0; i < nelems(data); i++) {\n        unsigned long long example, factor, quotient;\n        example = data[i];\n        factor = SQUFOF(example);\n        if(factor == 0) {\n            printf(\"%llu was not factored.\\n\", example);\n        }\n        else {\n            quotient = example / factor;\n            printf(\"Integer %llu has factors %llu and %llu\\n\",\n               example, factor, quotient); \n        }\n    }\n}\n"}
{"id": 60832, "name": "Square form factorization", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc isqrt(x uint64) uint64 {\n    x0 := x >> 1\n    x1 := (x0 + x/x0) >> 1\n    for x1 < x0 {\n        x0 = x1\n        x1 = (x0 + x/x0) >> 1\n    }\n    return x0\n}\n\nfunc gcd(x, y uint64) uint64 {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nvar multiplier = []uint64{\n    1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11,\n}\n\nfunc squfof(N uint64) uint64 {\n    s := uint64(math.Sqrt(float64(N)) + 0.5)\n    if s*s == N {\n        return s\n    }\n    for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ {\n        D := multiplier[k] * N\n        P := isqrt(D)\n        Pprev := P\n        Po := Pprev\n        Qprev := uint64(1)\n        Q := D - Po*Po\n        L := uint32(isqrt(8 * s))\n        B := 3 * L\n        i := uint32(2)\n        var b, q, r uint64\n        for ; i < B; i++ {\n            b = uint64((Po + P) / Q)\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            r = uint64(math.Sqrt(float64(Q)) + 0.5)\n            if (i&1) == 0 && r*r == Q {\n                break\n            }\n            Qprev = q\n            Pprev = P\n        }\n        if i >= B {\n            continue\n        }\n        b = uint64((Po - P) / r)\n        P = b*r + P\n        Pprev = P\n        Qprev = r\n        Q = (D - Pprev*Pprev) / Qprev\n        i = 0\n        for {\n            b = uint64((Po + P) / Q)\n            Pprev = P\n            P = b*Q - P\n            q = Q\n            Q = Qprev + b*(Pprev-P)\n            Qprev = q\n            i++\n            if P == Pprev {\n                break\n            }\n        }\n        r = gcd(N, Qprev)\n        if r != 1 && r != N {\n            return r\n        }\n    }\n    return 0\n}\n\nfunc main() {\n    examples := []uint64{\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877,\n    }\n    fmt.Println(\"Integer              Factor     Quotient\")\n    fmt.Println(\"------------------------------------------\")\n    for _, N := range examples {\n        fact := squfof(N)\n        quot := \"fail\"\n        if fact > 0 {\n            quot = fmt.Sprintf(\"%d\", N/fact)\n        }\n        fmt.Printf(\"%-20d %-10d %s\\n\", N, fact, quot)\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\n#define nelems(x) (sizeof(x) / sizeof((x)[0]))\n\nconst unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11};\n\nunsigned long long gcd(unsigned long long a, unsigned long long b)\n{\n    while (b != 0)\n    {\n        a %= b;\n        a ^= b;\n        b ^= a;\n        a ^= b;\n    }\n\n    return a;\n}\n\nunsigned long long SQUFOF( unsigned long long N )\n{\n    unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s;\n    unsigned long L, B, i;\n    s = (unsigned long long)(sqrtl(N)+0.5);\n    if (s*s == N) return s;\n    for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) {\n        D = multiplier[k]*N;\n        Po = Pprev = P = sqrtl(D);\n        Qprev = 1;\n        Q = D - Po*Po;\n        L = 2 * sqrtl( 2*s );\n        B = 3 * L;\n        for (i = 2 ; i < B ; i++) {\n            b = (unsigned long long)((Po + P)/Q);\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            r = (unsigned long long)(sqrtl(Q)+0.5);\n            if (!(i & 1) && r*r == Q) break;\n            Qprev = q;\n            Pprev = P;\n        };\n        if (i >= B) continue;\n        b = (unsigned long long)((Po - P)/r);\n        Pprev = P = b*r + P;\n        Qprev = r;\n        Q = (D - Pprev*Pprev)/Qprev;\n        i = 0;\n        do {\n            b = (unsigned long long)((Po + P)/Q);\n            Pprev = P;\n            P = b*Q - P;\n            q = Q;\n            Q = Qprev + b*(Pprev - P);\n            Qprev = q;\n            i++;\n        } while (P != Pprev);\n        r = gcd(N, Qprev);\n        if (r != 1 && r != N) return r;\n    }\n    return 0;\n}\n\nint main(int argc, char *argv[]) {\n    int i;\n    const unsigned long long data[] = {\n        2501,\n        12851,\n        13289,\n        75301,\n        120787,\n        967009,\n        997417,\n        7091569,\n        13290059,\n        42854447,\n        223553581,\n        2027651281,\n        11111111111,\n        100895598169,\n        1002742628021,\n        60012462237239,\n        287129523414791,\n        9007199254740931,\n        11111111111111111,\n        314159265358979323,\n        384307168202281507,\n        419244183493398773,\n        658812288346769681,\n        922337203685477563,\n        1000000000000000127,\n        1152921505680588799,\n        1537228672809128917,\n        4611686018427387877};\n\n    for(int i = 0; i < nelems(data); i++) {\n        unsigned long long example, factor, quotient;\n        example = data[i];\n        factor = SQUFOF(example);\n        if(factor == 0) {\n            printf(\"%llu was not factored.\\n\", example);\n        }\n        else {\n            quotient = example / factor;\n            printf(\"Integer %llu has factors %llu and %llu\\n\",\n               example, factor, quotient); \n        }\n    }\n}\n"}
{"id": 60833, "name": "Pinstripe_Printer", "Go": "package main\n \nimport (\n    \"github.com/fogleman/gg\"\n    \"log\"\n    \"os/exec\"\n    \"runtime\"\n)\n\nvar palette = [2]string{\n    \"FFFFFF\", \n    \"000000\", \n}\n \nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 7\n    for b := 1; b <= 11; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%2])\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(842, 595)\n    pinstripe(dc)\n    fileName := \"w_pinstripe.png\"\n    dc.SavePNG(fileName)\n    var cmd *exec.Cmd\n    if runtime.GOOS == \"windows\" {\n        cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n    } else {\n        cmd = exec.Command(\"lp\", fileName)\n    }\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "\n\n#include <stdlib.h>\n#include <string.h>\n#include \"dome.h\"\n\nstatic DOME_API_v0* core;\nstatic WREN_API_v0* wren;\n\nstatic const char* source =  \"\"\n\"class Printer {\\n\" \n  \"foreign static printFile(name) \\n\"\n\"} \\n\";\n\nvoid C_printFile(WrenVM* vm) {\n    const char *arg = wren->getSlotString(vm, 1);\n    char command[strlen(arg) + 4];\n    strcpy(command, \"lp \");\n    strcat(command, arg);\n    int res = system(command);\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) {\n    core = DOME_getAPI(API_DOME, DOME_API_VERSION);\n    wren = DOME_getAPI(API_WREN, WREN_API_VERSION);\n    core->registerModule(ctx, \"printer\", source);\n    core->registerClass(ctx, \"printer\", \"Printer\", NULL, NULL);\n    core->registerFn(ctx, \"printer\", \"static Printer.printFile(_)\", C_printFile);\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n"}
{"id": 60834, "name": "Pinstripe_Printer", "Go": "package main\n \nimport (\n    \"github.com/fogleman/gg\"\n    \"log\"\n    \"os/exec\"\n    \"runtime\"\n)\n\nvar palette = [2]string{\n    \"FFFFFF\", \n    \"000000\", \n}\n \nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 7\n    for b := 1; b <= 11; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%2])\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(842, 595)\n    pinstripe(dc)\n    fileName := \"w_pinstripe.png\"\n    dc.SavePNG(fileName)\n    var cmd *exec.Cmd\n    if runtime.GOOS == \"windows\" {\n        cmd = exec.Command(\"mspaint\", \"/pt\", fileName)\n    } else {\n        cmd = exec.Command(\"lp\", fileName)\n    }\n    if err := cmd.Run(); err != nil {\n        log.Fatal(err)\n    }\n}\n", "C": "\n\n#include <stdlib.h>\n#include <string.h>\n#include \"dome.h\"\n\nstatic DOME_API_v0* core;\nstatic WREN_API_v0* wren;\n\nstatic const char* source =  \"\"\n\"class Printer {\\n\" \n  \"foreign static printFile(name) \\n\"\n\"} \\n\";\n\nvoid C_printFile(WrenVM* vm) {\n    const char *arg = wren->getSlotString(vm, 1);\n    char command[strlen(arg) + 4];\n    strcpy(command, \"lp \");\n    strcat(command, arg);\n    int res = system(command);\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) {\n    core = DOME_getAPI(API_DOME, DOME_API_VERSION);\n    wren = DOME_getAPI(API_WREN, WREN_API_VERSION);\n    core->registerModule(ctx, \"printer\", source);\n    core->registerClass(ctx, \"printer\", \"Printer\", NULL, NULL);\n    core->registerFn(ctx, \"printer\", \"static Printer.printFile(_)\", C_printFile);\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n\nDOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) {\n    return DOME_RESULT_SUCCESS;\n}\n"}
{"id": 60835, "name": "Catmull–Clark subdivision surface", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype (\n    Point [3]float64\n    Face  []int\n\n    Edge struct {\n        pn1 int   \n        pn2 int   \n        fn1 int   \n        fn2 int   \n        cp  Point \n    }\n\n    PointEx struct {\n        p Point\n        n int\n    }\n)\n\nfunc sumPoint(p1, p2 Point) Point {\n    sp := Point{}\n    for i := 0; i < 3; i++ {\n        sp[i] = p1[i] + p2[i]\n    }\n    return sp\n}\n\nfunc mulPoint(p Point, m float64) Point {\n    mp := Point{}\n    for i := 0; i < 3; i++ {\n        mp[i] = p[i] * m\n    }\n    return mp\n}\n\nfunc divPoint(p Point, d float64) Point {\n    return mulPoint(p, 1.0/d)\n}\n\nfunc centerPoint(p1, p2 Point) Point {\n    return divPoint(sumPoint(p1, p2), 2)\n}\n\nfunc getFacePoints(inputPoints []Point, inputFaces []Face) []Point {\n    facePoints := make([]Point, len(inputFaces))\n    for i, currFace := range inputFaces {\n        facePoint := Point{}\n        for _, cpi := range currFace {\n            currPoint := inputPoints[cpi]\n            facePoint = sumPoint(facePoint, currPoint)\n        }\n        facePoint = divPoint(facePoint, float64(len(currFace)))\n        facePoints[i] = facePoint\n    }\n    return facePoints\n}\n\nfunc getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge {\n    var edges [][3]int\n    for faceNum, face := range inputFaces {\n        numPoints := len(face)\n        for pointIndex := 0; pointIndex < numPoints; pointIndex++ {\n            pointNum1 := face[pointIndex]\n            var pointNum2 int\n            if pointIndex < numPoints-1 {\n                pointNum2 = face[pointIndex+1]\n            } else {\n                pointNum2 = face[0]\n            }\n            if pointNum1 > pointNum2 {\n                pointNum1, pointNum2 = pointNum2, pointNum1\n            }\n            edges = append(edges, [3]int{pointNum1, pointNum2, faceNum})\n        }\n    }\n    sort.Slice(edges, func(i, j int) bool {\n        if edges[i][0] == edges[j][0] {\n            if edges[i][1] == edges[j][1] {\n                return edges[i][2] < edges[j][2]\n            }\n            return edges[i][1] < edges[j][1]\n        }\n        return edges[i][0] < edges[j][0]\n    })\n    numEdges := len(edges)\n    eIndex := 0\n    var mergedEdges [][4]int\n    for eIndex < numEdges {\n        e1 := edges[eIndex]\n        if eIndex < numEdges-1 {\n            e2 := edges[eIndex+1]\n            if e1[0] == e2[0] && e1[1] == e2[1] {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]})\n                eIndex += 2\n            } else {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n                eIndex++\n            }\n        } else {\n            mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n            eIndex++\n        }\n    }\n    var edgesCenters []Edge\n    for _, me := range mergedEdges {\n        p1 := inputPoints[me[0]]\n        p2 := inputPoints[me[1]]\n        cp := centerPoint(p1, p2)\n        edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp})\n    }\n    return edgesCenters\n}\n\nfunc getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point {\n    edgePoints := make([]Point, len(edgesFaces))\n    for i, edge := range edgesFaces {\n        cp := edge.cp\n        fp1 := facePoints[edge.fn1]\n        var fp2 Point\n        if edge.fn2 == -1 {\n            fp2 = fp1\n        } else {\n            fp2 = facePoints[edge.fn2]\n        }\n        cfp := centerPoint(fp1, fp2)\n        edgePoints[i] = centerPoint(cp, cfp)\n    }\n    return edgePoints\n}\n\nfunc getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for faceNum := range inputFaces {\n        fp := facePoints[faceNum]\n        for _, pointNum := range inputFaces[faceNum] {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, fp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgFacePoints := make([]Point, numPoints)\n    for i, tp := range tempPoints {\n        avgFacePoints[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgFacePoints\n}\n\nfunc getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for _, edge := range edgesFaces {\n        cp := edge.cp\n        for _, pointNum := range []int{edge.pn1, edge.pn2} {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, cp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgMidEdges := make([]Point, len(tempPoints))\n    for i, tp := range tempPoints {\n        avgMidEdges[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgMidEdges\n}\n\nfunc getPointsFaces(inputPoints []Point, inputFaces []Face) []int {\n    numPoints := len(inputPoints)\n    pointsFaces := make([]int, numPoints)\n    for faceNum := range inputFaces {\n        for _, pointNum := range inputFaces[faceNum] {\n            pointsFaces[pointNum]++\n        }\n    }\n    return pointsFaces\n}\n\nfunc getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point {\n    newPoints := make([]Point, len(inputPoints))\n    for pointNum := range inputPoints {\n        n := float64(pointsFaces[pointNum])\n        m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n\n        oldCoords := inputPoints[pointNum]\n        p1 := mulPoint(oldCoords, m1)\n        afp := avgFacePoints[pointNum]\n        p2 := mulPoint(afp, m2)\n        ame := avgMidEdges[pointNum]\n        p3 := mulPoint(ame, m3)\n        p4 := sumPoint(p1, p2)\n        newPoints[pointNum] = sumPoint(p4, p3)\n    }\n    return newPoints\n}\n\nfunc switchNums(pointNums [2]int) [2]int {\n    if pointNums[0] < pointNums[1] {\n        return pointNums\n    }\n    return [2]int{pointNums[1], pointNums[0]}\n}\n\nfunc cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) {\n    facePoints := getFacePoints(inputPoints, inputFaces)\n    edgesFaces := getEdgesFaces(inputPoints, inputFaces)\n    edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints)\n    avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints)\n    avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces)\n    pointsFaces := getPointsFaces(inputPoints, inputFaces)\n    newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n    var facePointNums []int\n    nextPointNum := len(newPoints)\n    for _, facePoint := range facePoints {\n        newPoints = append(newPoints, facePoint)\n        facePointNums = append(facePointNums, nextPointNum)\n        nextPointNum++\n    }\n    edgePointNums := make(map[[2]int]int)\n    for edgeNum := range edgesFaces {\n        pointNum1 := edgesFaces[edgeNum].pn1\n        pointNum2 := edgesFaces[edgeNum].pn2\n        edgePoint := edgePoints[edgeNum]\n        newPoints = append(newPoints, edgePoint)\n        edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum\n        nextPointNum++\n    }\n    var newFaces []Face\n    for oldFaceNum, oldFace := range inputFaces {\n        if len(oldFace) == 4 {\n            a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3]\n            facePointAbcd := facePointNums[oldFaceNum]\n            edgePointAb := edgePointNums[switchNums([2]int{a, b})]\n            edgePointDa := edgePointNums[switchNums([2]int{d, a})]\n            edgePointBc := edgePointNums[switchNums([2]int{b, c})]\n            edgePointCd := edgePointNums[switchNums([2]int{c, d})]\n            newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa})\n            newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb})\n            newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc})\n            newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd})\n        }\n    }\n    return newPoints, newFaces\n}\n\nfunc main() {\n    inputPoints := []Point{\n        {-1.0, 1.0, 1.0},\n        {-1.0, -1.0, 1.0},\n        {1.0, -1.0, 1.0},\n        {1.0, 1.0, 1.0},\n        {1.0, -1.0, -1.0},\n        {1.0, 1.0, -1.0},\n        {-1.0, -1.0, -1.0},\n        {-1.0, 1.0, -1.0},\n    }\n\n    inputFaces := []Face{\n        {0, 1, 2, 3},\n        {3, 2, 4, 5},\n        {5, 4, 6, 7},\n        {7, 0, 3, 5},\n        {7, 6, 1, 0},\n        {6, 1, 2, 4},\n    }\n\n    outputPoints := make([]Point, len(inputPoints))\n    outputFaces := make([]Face, len(inputFaces))\n    copy(outputPoints, inputPoints)\n    copy(outputFaces, inputFaces)\n    iterations := 1\n    for i := 0; i < iterations; i++ {\n        outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces)\n    }\n    for _, p := range outputPoints {\n        fmt.Printf(\"% .4f\\n\", p)\n    }\n    fmt.Println()\n    for _, f := range outputFaces {\n        fmt.Printf(\"%2d\\n\", f)\n    }\n}\n", "C": "vertex face_point(face f)\n{\n\tint i;\n\tvertex v;\n\n\tif (!f->avg) {\n\t\tf->avg = vertex_new();\n\t\tforeach(i, v, f->v)\n\t\t\tif (!i) f->avg->pos = v->pos;\n\t\t\telse    vadd(f->avg->pos, v->pos);\n\n\t\tvdiv(f->avg->pos, len(f->v));\n\t}\n\treturn f->avg;\n}\n\n#define hole_edge(e) (len(e->f)==1)\nvertex edge_point(edge e)\n{\n\tint i;\n\tface f;\n\n\tif (!e->e_pt) {\n\t\te->e_pt = vertex_new();\n\t\te->avg = e->v[0]->pos;\n\t\tvadd(e->avg, e->v[1]->pos);\n\t\te->e_pt->pos = e->avg;\n\n\t\tif (!hole_edge(e)) {\n\t\t\tforeach (i, f, e->f)\n\t\t\t\tvadd(e->e_pt->pos, face_point(f)->pos);\n\t\t\tvdiv(e->e_pt->pos, 4);\n\t\t} else\n\t\t\tvdiv(e->e_pt->pos, 2);\n\n\t\tvdiv(e->avg, 2);\n\t}\n\n\treturn e->e_pt;\n}\n\n#define hole_vertex(v) (len((v)->f) != len((v)->e))\nvertex updated_point(vertex v)\n{\n\tint i, n = 0;\n\tedge e;\n\tface f;\n\tcoord_t sum = {0, 0, 0};\n\n\tif (v->v_new) return v->v_new;\n\n\tv->v_new = vertex_new();\n\tif (hole_vertex(v)) {\n\t\tv->v_new->pos = v->pos;\n\t\tforeach(i, e, v->e) {\n\t\t\tif (!hole_edge(e)) continue;\n\t\t\tvadd(v->v_new->pos, edge_point(e)->pos);\n\t\t\tn++;\n\t\t}\n\t\tvdiv(v->v_new->pos, n + 1);\n\t} else {\n\t\tn = len(v->f);\n\t\tforeach(i, f, v->f)\n\t\t\tvadd(sum, face_point(f)->pos);\n\t\tforeach(i, e, v->e)\n\t\t\tvmadd(sum, edge_point(e)->pos, 2, sum);\n\t\tvdiv(sum, n);\n\t\tvmadd(sum, v->pos, n - 3, sum);\n\t\tvdiv(sum, n);\n\t\tv->v_new->pos = sum;\n\t}\n\n\treturn v->v_new;\n}\n\nmodel catmull(model m)\n{\n\tint i, j, a, b, c, d;\n\tface f;\n\tvertex v, x;\n\n\tmodel nm = model_new();\n\tforeach (i, f, m->f) {\n\t\tforeach(j, v, f->v) {\n\t\t\t_get_idx(a, updated_point(v));\n\t\t\t_get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e))));\n\t\t\t_get_idx(c, face_point(f));\n\t\t\t_get_idx(d, edge_point(elem(f->e, j)));\n\t\t\tmodel_add_face(nm, 4, a, b, c, d);\n\t\t}\n\t}\n\treturn nm;\n}\n"}
{"id": 60836, "name": "Catmull–Clark subdivision surface", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype (\n    Point [3]float64\n    Face  []int\n\n    Edge struct {\n        pn1 int   \n        pn2 int   \n        fn1 int   \n        fn2 int   \n        cp  Point \n    }\n\n    PointEx struct {\n        p Point\n        n int\n    }\n)\n\nfunc sumPoint(p1, p2 Point) Point {\n    sp := Point{}\n    for i := 0; i < 3; i++ {\n        sp[i] = p1[i] + p2[i]\n    }\n    return sp\n}\n\nfunc mulPoint(p Point, m float64) Point {\n    mp := Point{}\n    for i := 0; i < 3; i++ {\n        mp[i] = p[i] * m\n    }\n    return mp\n}\n\nfunc divPoint(p Point, d float64) Point {\n    return mulPoint(p, 1.0/d)\n}\n\nfunc centerPoint(p1, p2 Point) Point {\n    return divPoint(sumPoint(p1, p2), 2)\n}\n\nfunc getFacePoints(inputPoints []Point, inputFaces []Face) []Point {\n    facePoints := make([]Point, len(inputFaces))\n    for i, currFace := range inputFaces {\n        facePoint := Point{}\n        for _, cpi := range currFace {\n            currPoint := inputPoints[cpi]\n            facePoint = sumPoint(facePoint, currPoint)\n        }\n        facePoint = divPoint(facePoint, float64(len(currFace)))\n        facePoints[i] = facePoint\n    }\n    return facePoints\n}\n\nfunc getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge {\n    var edges [][3]int\n    for faceNum, face := range inputFaces {\n        numPoints := len(face)\n        for pointIndex := 0; pointIndex < numPoints; pointIndex++ {\n            pointNum1 := face[pointIndex]\n            var pointNum2 int\n            if pointIndex < numPoints-1 {\n                pointNum2 = face[pointIndex+1]\n            } else {\n                pointNum2 = face[0]\n            }\n            if pointNum1 > pointNum2 {\n                pointNum1, pointNum2 = pointNum2, pointNum1\n            }\n            edges = append(edges, [3]int{pointNum1, pointNum2, faceNum})\n        }\n    }\n    sort.Slice(edges, func(i, j int) bool {\n        if edges[i][0] == edges[j][0] {\n            if edges[i][1] == edges[j][1] {\n                return edges[i][2] < edges[j][2]\n            }\n            return edges[i][1] < edges[j][1]\n        }\n        return edges[i][0] < edges[j][0]\n    })\n    numEdges := len(edges)\n    eIndex := 0\n    var mergedEdges [][4]int\n    for eIndex < numEdges {\n        e1 := edges[eIndex]\n        if eIndex < numEdges-1 {\n            e2 := edges[eIndex+1]\n            if e1[0] == e2[0] && e1[1] == e2[1] {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]})\n                eIndex += 2\n            } else {\n                mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n                eIndex++\n            }\n        } else {\n            mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1})\n            eIndex++\n        }\n    }\n    var edgesCenters []Edge\n    for _, me := range mergedEdges {\n        p1 := inputPoints[me[0]]\n        p2 := inputPoints[me[1]]\n        cp := centerPoint(p1, p2)\n        edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp})\n    }\n    return edgesCenters\n}\n\nfunc getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point {\n    edgePoints := make([]Point, len(edgesFaces))\n    for i, edge := range edgesFaces {\n        cp := edge.cp\n        fp1 := facePoints[edge.fn1]\n        var fp2 Point\n        if edge.fn2 == -1 {\n            fp2 = fp1\n        } else {\n            fp2 = facePoints[edge.fn2]\n        }\n        cfp := centerPoint(fp1, fp2)\n        edgePoints[i] = centerPoint(cp, cfp)\n    }\n    return edgePoints\n}\n\nfunc getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for faceNum := range inputFaces {\n        fp := facePoints[faceNum]\n        for _, pointNum := range inputFaces[faceNum] {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, fp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgFacePoints := make([]Point, numPoints)\n    for i, tp := range tempPoints {\n        avgFacePoints[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgFacePoints\n}\n\nfunc getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point {\n    numPoints := len(inputPoints)\n    tempPoints := make([]PointEx, numPoints)\n    for _, edge := range edgesFaces {\n        cp := edge.cp\n        for _, pointNum := range []int{edge.pn1, edge.pn2} {\n            tp := tempPoints[pointNum].p\n            tempPoints[pointNum].p = sumPoint(tp, cp)\n            tempPoints[pointNum].n++\n        }\n    }\n    avgMidEdges := make([]Point, len(tempPoints))\n    for i, tp := range tempPoints {\n        avgMidEdges[i] = divPoint(tp.p, float64(tp.n))\n    }\n    return avgMidEdges\n}\n\nfunc getPointsFaces(inputPoints []Point, inputFaces []Face) []int {\n    numPoints := len(inputPoints)\n    pointsFaces := make([]int, numPoints)\n    for faceNum := range inputFaces {\n        for _, pointNum := range inputFaces[faceNum] {\n            pointsFaces[pointNum]++\n        }\n    }\n    return pointsFaces\n}\n\nfunc getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point {\n    newPoints := make([]Point, len(inputPoints))\n    for pointNum := range inputPoints {\n        n := float64(pointsFaces[pointNum])\n        m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n\n        oldCoords := inputPoints[pointNum]\n        p1 := mulPoint(oldCoords, m1)\n        afp := avgFacePoints[pointNum]\n        p2 := mulPoint(afp, m2)\n        ame := avgMidEdges[pointNum]\n        p3 := mulPoint(ame, m3)\n        p4 := sumPoint(p1, p2)\n        newPoints[pointNum] = sumPoint(p4, p3)\n    }\n    return newPoints\n}\n\nfunc switchNums(pointNums [2]int) [2]int {\n    if pointNums[0] < pointNums[1] {\n        return pointNums\n    }\n    return [2]int{pointNums[1], pointNums[0]}\n}\n\nfunc cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) {\n    facePoints := getFacePoints(inputPoints, inputFaces)\n    edgesFaces := getEdgesFaces(inputPoints, inputFaces)\n    edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints)\n    avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints)\n    avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces)\n    pointsFaces := getPointsFaces(inputPoints, inputFaces)\n    newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)\n    var facePointNums []int\n    nextPointNum := len(newPoints)\n    for _, facePoint := range facePoints {\n        newPoints = append(newPoints, facePoint)\n        facePointNums = append(facePointNums, nextPointNum)\n        nextPointNum++\n    }\n    edgePointNums := make(map[[2]int]int)\n    for edgeNum := range edgesFaces {\n        pointNum1 := edgesFaces[edgeNum].pn1\n        pointNum2 := edgesFaces[edgeNum].pn2\n        edgePoint := edgePoints[edgeNum]\n        newPoints = append(newPoints, edgePoint)\n        edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum\n        nextPointNum++\n    }\n    var newFaces []Face\n    for oldFaceNum, oldFace := range inputFaces {\n        if len(oldFace) == 4 {\n            a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3]\n            facePointAbcd := facePointNums[oldFaceNum]\n            edgePointAb := edgePointNums[switchNums([2]int{a, b})]\n            edgePointDa := edgePointNums[switchNums([2]int{d, a})]\n            edgePointBc := edgePointNums[switchNums([2]int{b, c})]\n            edgePointCd := edgePointNums[switchNums([2]int{c, d})]\n            newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa})\n            newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb})\n            newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc})\n            newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd})\n        }\n    }\n    return newPoints, newFaces\n}\n\nfunc main() {\n    inputPoints := []Point{\n        {-1.0, 1.0, 1.0},\n        {-1.0, -1.0, 1.0},\n        {1.0, -1.0, 1.0},\n        {1.0, 1.0, 1.0},\n        {1.0, -1.0, -1.0},\n        {1.0, 1.0, -1.0},\n        {-1.0, -1.0, -1.0},\n        {-1.0, 1.0, -1.0},\n    }\n\n    inputFaces := []Face{\n        {0, 1, 2, 3},\n        {3, 2, 4, 5},\n        {5, 4, 6, 7},\n        {7, 0, 3, 5},\n        {7, 6, 1, 0},\n        {6, 1, 2, 4},\n    }\n\n    outputPoints := make([]Point, len(inputPoints))\n    outputFaces := make([]Face, len(inputFaces))\n    copy(outputPoints, inputPoints)\n    copy(outputFaces, inputFaces)\n    iterations := 1\n    for i := 0; i < iterations; i++ {\n        outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces)\n    }\n    for _, p := range outputPoints {\n        fmt.Printf(\"% .4f\\n\", p)\n    }\n    fmt.Println()\n    for _, f := range outputFaces {\n        fmt.Printf(\"%2d\\n\", f)\n    }\n}\n", "C": "vertex face_point(face f)\n{\n\tint i;\n\tvertex v;\n\n\tif (!f->avg) {\n\t\tf->avg = vertex_new();\n\t\tforeach(i, v, f->v)\n\t\t\tif (!i) f->avg->pos = v->pos;\n\t\t\telse    vadd(f->avg->pos, v->pos);\n\n\t\tvdiv(f->avg->pos, len(f->v));\n\t}\n\treturn f->avg;\n}\n\n#define hole_edge(e) (len(e->f)==1)\nvertex edge_point(edge e)\n{\n\tint i;\n\tface f;\n\n\tif (!e->e_pt) {\n\t\te->e_pt = vertex_new();\n\t\te->avg = e->v[0]->pos;\n\t\tvadd(e->avg, e->v[1]->pos);\n\t\te->e_pt->pos = e->avg;\n\n\t\tif (!hole_edge(e)) {\n\t\t\tforeach (i, f, e->f)\n\t\t\t\tvadd(e->e_pt->pos, face_point(f)->pos);\n\t\t\tvdiv(e->e_pt->pos, 4);\n\t\t} else\n\t\t\tvdiv(e->e_pt->pos, 2);\n\n\t\tvdiv(e->avg, 2);\n\t}\n\n\treturn e->e_pt;\n}\n\n#define hole_vertex(v) (len((v)->f) != len((v)->e))\nvertex updated_point(vertex v)\n{\n\tint i, n = 0;\n\tedge e;\n\tface f;\n\tcoord_t sum = {0, 0, 0};\n\n\tif (v->v_new) return v->v_new;\n\n\tv->v_new = vertex_new();\n\tif (hole_vertex(v)) {\n\t\tv->v_new->pos = v->pos;\n\t\tforeach(i, e, v->e) {\n\t\t\tif (!hole_edge(e)) continue;\n\t\t\tvadd(v->v_new->pos, edge_point(e)->pos);\n\t\t\tn++;\n\t\t}\n\t\tvdiv(v->v_new->pos, n + 1);\n\t} else {\n\t\tn = len(v->f);\n\t\tforeach(i, f, v->f)\n\t\t\tvadd(sum, face_point(f)->pos);\n\t\tforeach(i, e, v->e)\n\t\t\tvmadd(sum, edge_point(e)->pos, 2, sum);\n\t\tvdiv(sum, n);\n\t\tvmadd(sum, v->pos, n - 3, sum);\n\t\tvdiv(sum, n);\n\t\tv->v_new->pos = sum;\n\t}\n\n\treturn v->v_new;\n}\n\nmodel catmull(model m)\n{\n\tint i, j, a, b, c, d;\n\tface f;\n\tvertex v, x;\n\n\tmodel nm = model_new();\n\tforeach (i, f, m->f) {\n\t\tforeach(j, v, f->v) {\n\t\t\t_get_idx(a, updated_point(v));\n\t\t\t_get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e))));\n\t\t\t_get_idx(c, face_point(f));\n\t\t\t_get_idx(d, edge_point(elem(f->e, j)));\n\t\t\tmodel_add_face(nm, 4, a, b, c, d);\n\t\t}\n\t}\n\treturn nm;\n}\n"}
{"id": 60837, "name": "Rosetta Code_List authors of task descriptions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strings\"\n)\n\ntype authorNumber struct {\n    author string\n    number int\n}\n\nfunc main() {\n    ex1 := `<li><a href=\"/wiki/(.*?)\"`\n    ex2 := `a href=\"/(wiki/User:|mw/index\\.php\\?title=User:|wiki/Special:Contributions/)([^\"&]+)`\n    re1 := regexp.MustCompile(ex1)\n    re2 := regexp.MustCompile(ex2)\n    url1 := \"http:\n    url2 := \"http:\n    urls := []string{url1, url2}\n    var tasks []string\n    for _, url := range urls {\n        resp, _ := http.Get(url)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re1.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        for _, match := range matches {\n            \n            if !strings.HasPrefix(match[1], \"Category:\") {\n                tasks = append(tasks, match[1])\n            }\n        }\n    }\n    authors := make(map[string]int)\n    for _, task := range tasks {\n        \n        page := fmt.Sprintf(\"http:\n        resp, _ := http.Get(page)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re2.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        \n        author := matches[len(matches)-1][2]\n        author = strings.ReplaceAll(author, \"_\", \" \")\n        \n        authors[author]++\n    }\n    \n    authorNumbers := make([]authorNumber, 0, len(authors))\n    for k, v := range authors {\n        authorNumbers = append(authorNumbers, authorNumber{k, v})\n    }\n    sort.Slice(authorNumbers, func(i, j int) bool {\n        return authorNumbers[i].number > authorNumbers[j].number\n    })\n    \n    fmt.Println(\"Total tasks   :\", len(tasks))\n    fmt.Println(\"Total authors :\", len(authors))\n    fmt.Println(\"\\nThe top 20 authors by number of tasks created are:\\n\")\n    fmt.Println(\"Pos  Tasks  Author\")\n    fmt.Println(\"===  =====  ======\")\n    lastNumber, lastIndex := 0, -1\n    for i, authorNumber := range authorNumbers[0:20] {\n        j := i\n        if authorNumber.number == lastNumber {\n            j = lastIndex\n        } else {\n            lastIndex = i\n            lastNumber = authorNumber.number\n        }\n        fmt.Printf(\"%2d:   %3d   %s\\n\", j+1, authorNumber.number, authorNumber.author)\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_list_authors_of_task_descriptions.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
{"id": 60838, "name": "Rosetta Code_List authors of task descriptions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"net/http\"\n    \"regexp\"\n    \"sort\"\n    \"strings\"\n)\n\ntype authorNumber struct {\n    author string\n    number int\n}\n\nfunc main() {\n    ex1 := `<li><a href=\"/wiki/(.*?)\"`\n    ex2 := `a href=\"/(wiki/User:|mw/index\\.php\\?title=User:|wiki/Special:Contributions/)([^\"&]+)`\n    re1 := regexp.MustCompile(ex1)\n    re2 := regexp.MustCompile(ex2)\n    url1 := \"http:\n    url2 := \"http:\n    urls := []string{url1, url2}\n    var tasks []string\n    for _, url := range urls {\n        resp, _ := http.Get(url)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re1.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        for _, match := range matches {\n            \n            if !strings.HasPrefix(match[1], \"Category:\") {\n                tasks = append(tasks, match[1])\n            }\n        }\n    }\n    authors := make(map[string]int)\n    for _, task := range tasks {\n        \n        page := fmt.Sprintf(\"http:\n        resp, _ := http.Get(page)\n        body, _ := ioutil.ReadAll(resp.Body)\n        \n        matches := re2.FindAllStringSubmatch(string(body), -1)\n        resp.Body.Close()\n        \n        author := matches[len(matches)-1][2]\n        author = strings.ReplaceAll(author, \"_\", \" \")\n        \n        authors[author]++\n    }\n    \n    authorNumbers := make([]authorNumber, 0, len(authors))\n    for k, v := range authors {\n        authorNumbers = append(authorNumbers, authorNumber{k, v})\n    }\n    sort.Slice(authorNumbers, func(i, j int) bool {\n        return authorNumbers[i].number > authorNumbers[j].number\n    })\n    \n    fmt.Println(\"Total tasks   :\", len(tasks))\n    fmt.Println(\"Total authors :\", len(authors))\n    fmt.Println(\"\\nThe top 20 authors by number of tasks created are:\\n\")\n    fmt.Println(\"Pos  Tasks  Author\")\n    fmt.Println(\"===  =====  ======\")\n    lastNumber, lastIndex := 0, -1\n    for i, authorNumber := range authorNumbers[0:20] {\n        j := i\n        if authorNumber.number == lastNumber {\n            j = lastIndex\n        } else {\n            lastIndex = i\n            lastNumber = authorNumber.number\n        }\n        fmt.Printf(\"%2d:   %3d   %s\\n\", j+1, authorNumber.number, authorNumber.author)\n    }\n}\n", "C": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n    char *memory;\n    size_t size;\n};\n\n\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n    size_t realsize = size * nmemb;\n    struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n \n    char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n    if(!ptr) {\n        \n        printf(\"not enough memory (realloc returned NULL)\\n\");\n        return 0;\n    }\n\n    mem->memory = ptr;\n    memcpy(&(mem->memory[mem->size]), contents, realsize);\n    mem->size += realsize;\n    mem->memory[mem->size] = 0;\n    return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n    ms->memory = malloc(1);\n    ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)data;\n    free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n    *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n    struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n    wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n    if (opt < 10000) {\n        long lparam = (long)wrenGetSlotDouble(vm, 2);\n        curl_easy_setopt(curl, opt, lparam);\n    } else if (opt < 20000) {\n        if (opt == CURLOPT_WRITEDATA) {\n            struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n            curl_easy_setopt(curl, opt, (void *)ms);\n        } else if (opt == CURLOPT_URL) {\n            const char *url = wrenGetSlotString(vm, 2);\n            curl_easy_setopt(curl, opt, url);\n        }\n    } else if (opt < 30000) {\n        if (opt == CURLOPT_WRITEFUNCTION) {\n            curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n        }\n    }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n    WrenForeignClassMethods methods;\n    methods.allocate = NULL;\n    methods.finalize = NULL;\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            methods.allocate = C_bufferAllocate;\n            methods.finalize = C_bufferFinalize;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            methods.allocate = C_curlAllocate;\n        }\n    }\n    return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n    WrenVM* vm,\n    const char* module,\n    const char* className,\n    bool isStatic,\n    const char* signature) {\n    if (strcmp(module, \"main\") == 0) {\n        if (strcmp(className, \"Buffer\") == 0) {\n            if (!isStatic && strcmp(signature, \"value\") == 0)           return C_value;\n        } else if (strcmp(className, \"Curl\") == 0) {\n            if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n            if (!isStatic && strcmp(signature, \"easyPerform()\") == 0)   return C_easyPerform;\n            if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0)   return C_easyCleanup;\n        }\n    }\n    return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n    printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n    switch (errorType) {\n        case WREN_ERROR_COMPILE:\n            printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_STACK_TRACE:\n            printf(\"[%s line %d] in %s\\n\", module, line, msg);\n            break;\n        case WREN_ERROR_RUNTIME:\n            printf(\"[Runtime Error] %s\\n\", msg);\n            break;\n    }\n}\n\nchar *readFile(const char *fileName) {\n    FILE *f = fopen(fileName, \"r\");\n    fseek(f, 0, SEEK_END);\n    long fsize = ftell(f);\n    rewind(f);\n    char *script = malloc(fsize + 1);\n    fread(script, 1, fsize, f);\n    fclose(f);\n    script[fsize] = 0;\n    return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n    if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n    WrenLoadModuleResult result = {0};\n    if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n        result.onComplete = loadModuleComplete;\n        char fullName[strlen(name) + 6];\n        strcpy(fullName, name);\n        strcat(fullName, \".wren\");\n        result.source = readFile(fullName);\n    }\n    return result;\n}\n\nint main(int argc, char **argv) {\n    WrenConfiguration config;\n    wrenInitConfiguration(&config);\n    config.writeFn = &writeFn;\n    config.errorFn = &errorFn;\n    config.bindForeignClassFn = &bindForeignClass;\n    config.bindForeignMethodFn = &bindForeignMethod;\n    config.loadModuleFn = &loadModule;\n    WrenVM* vm = wrenNewVM(&config);\n    const char* module = \"main\";\n    const char* fileName = \"rc_list_authors_of_task_descriptions.wren\";\n    char *script = readFile(fileName);\n    WrenInterpretResult result = wrenInterpret(vm, module, script);\n    switch (result) {\n        case WREN_RESULT_COMPILE_ERROR:\n            printf(\"Compile Error!\\n\");\n            break;\n        case WREN_RESULT_RUNTIME_ERROR:\n            printf(\"Runtime Error!\\n\");\n            break;\n        case WREN_RESULT_SUCCESS:\n            break;\n    }\n    wrenFreeVM(vm);\n    free(script);\n    return 0;\n}\n"}
